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><thead><tfoot><span><div><tr><td><th><ol><ul><dl><li><dt><dd><h1><h2><h3><h4><h5><h6><hr><img><a><strong><emphasis><em><sup><sub><address><cite><blockquote><pre><strike><param><acronym><nolink><lang><tex><algebra><math><mi><mn><mo><mtext><mspace><ms><mrow><mfrac><msqrt><mroot><mstyle><merror><mpadded><mphantom><mfenced><msub><msup><msubsup><munder><mover><munderover><mmultiscripts><mtable><mtr><mtd><maligngroup><malignmark><maction><cn><ci><apply><reln><fn><interval><inverse><sep><condition><declare><lambda><compose><ident><quotient><exp><factorial><divide><max><min><minus><plus><power><rem><times><root><gcd><and><or><xor><not><implies><forall><exists><abs><conjugate><eq><neq><gt><lt><geq><leq><ln><log><int><diff><partialdiff><lowlimit><uplimit><bvar><degree><set><list><union><intersect><in><notin><subset><prsubset><notsubset><notprsubset><setdiff><sum><product><limit><tendsto><mean><sdev><variance><median><mode><moment><vector><matrix><matrixrow><determinant><transpose><selector><annotation><semantics><annotation-xml><tt><code>';
99 * Allowed protocols - array of protocols that are safe to use in links and so on
100 * @global string $ALLOWED_PROTOCOLS
102 $ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms',
103 'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style', 'font-family',
104 'border', 'margin', 'padding', 'background', 'background-color', 'text-decoration'); // CSS as well to get through kses
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' or $var === false or $var === 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);
343 * Add an array of params to the params for this page.
345 * The added params override existing ones if they have the same name.
347 * @param array $params Defaults to null. If null then return value of param 'name'.
348 * @return array Array of Params for url.
350 function params($params = null) {
351 if (!is_null($params)) {
352 return $this->params
= $params +
$this->params
;
354 return $this->params
;
359 * Remove all params if no arguments passed. Or else remove param $arg1, $arg2, etc.
361 * @param string $arg1
362 * @param string $arg2
363 * @param string $arg3
365 function remove_params(){
366 if ($thisargs = func_get_args()){
367 foreach ($thisargs as $arg){
368 if (isset($this->params
[$arg])){
369 unset($this->params
[$arg]);
373 $this->params
= array();
378 * Add a param to the params for this page. The added param overrides existing one if they
379 * have the same name.
381 * @param string $paramname name
382 * @param string $param value
384 function param($paramname, $param){
385 $this->params
= array($paramname => $param) +
$this->params
;
389 function get_query_string($overrideparams = array()){
391 $params = $overrideparams +
$this->params
;
392 foreach ($params as $key => $val){
393 $arr[] = urlencode($key)."=".urlencode($val);
395 return implode($arr, "&");
398 * Outputs params as hidden form elements.
400 * @param array $exclude params to ignore
401 * @param integer $indent indentation
402 * @param array $overrideparams params to add to the output params, these
403 * override existing ones with the same name.
404 * @return string html for form elements.
406 function hidden_params_out($exclude = array(), $indent = 0, $overrideparams=array()){
407 $tabindent = str_repeat("\t", $indent);
409 $params = $overrideparams +
$this->params
;
410 foreach ($params as $key => $val){
411 if (FALSE === array_search($key, $exclude)) {
413 $str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
421 * @param boolean $noquerystring whether to output page params as a query string in the url.
422 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
425 function out($noquerystring = false, $overrideparams = array()) {
426 $uri = $this->scheme ?
$this->scheme
.':'.((strtolower($this->scheme
) == 'mailto') ?
'':'//'): '';
427 $uri .= $this->user ?
$this->user
.($this->pass?
':'.$this->pass
:'').'@':'';
428 $uri .= $this->host ?
$this->host
: '';
429 $uri .= $this->port ?
':'.$this->port
: '';
430 $uri .= $this->path ?
$this->path
: '';
431 if (!$noquerystring){
432 $uri .= (count($this->params
)||
count($overrideparams)) ?
'?'.$this->get_query_string($overrideparams) : '';
434 $uri .= $this->fragment ?
'#'.$this->fragment
: '';
438 * Output action url with sesskey
440 * @param boolean $noquerystring whether to output page params as a query string in the url.
443 function out_action($overrideparams = array()) {
444 $overrideparams = array('sesskey'=> sesskey()) +
$overrideparams;
445 return $this->out(false, $overrideparams);
450 * Determine if there is data waiting to be processed from a form
452 * Used on most forms in Moodle to check for data
453 * Returns the data as an object, if it's found.
454 * This object can be used in foreach loops without
455 * casting because it's cast to (array) automatically
457 * Checks that submitted POST data exists and returns it as object.
459 * @param string $url not used anymore
460 * @return mixed false or object
462 function data_submitted($url='') {
467 return (object)$_POST;
472 * Moodle replacement for php stripslashes() function,
473 * works also for objects and arrays.
475 * The standard php stripslashes() removes ALL backslashes
476 * even from strings - so C:\temp becomes C:temp - this isn't good.
477 * This function should work as a fairly safe replacement
478 * to be called on quoted AND unquoted strings (to be sure)
480 * @param mixed something to remove unsafe slashes from
483 function stripslashes_safe($mixed) {
484 // there is no need to remove slashes from int, float and bool types
487 } else if (is_string($mixed)) {
488 if (ini_get_bool('magic_quotes_sybase')) { //only unescape single quotes
489 $mixed = str_replace("''", "'", $mixed);
490 } else { //the rest, simple and double quotes and backslashes
491 $mixed = str_replace("\\'", "'", $mixed);
492 $mixed = str_replace('\\"', '"', $mixed);
493 $mixed = str_replace('\\\\', '\\', $mixed);
495 } else if (is_array($mixed)) {
496 foreach ($mixed as $key => $value) {
497 $mixed[$key] = stripslashes_safe($value);
499 } else if (is_object($mixed)) {
500 $vars = get_object_vars($mixed);
501 foreach ($vars as $key => $value) {
502 $mixed->$key = stripslashes_safe($value);
510 * Recursive implementation of stripslashes()
512 * This function will allow you to strip the slashes from a variable.
513 * If the variable is an array or object, slashes will be stripped
514 * from the items (or properties) it contains, even if they are arrays
515 * or objects themselves.
517 * @param mixed the variable to remove slashes from
520 function stripslashes_recursive($var) {
521 if (is_object($var)) {
522 $new_var = new object();
523 $properties = get_object_vars($var);
524 foreach($properties as $property => $value) {
525 $new_var->$property = stripslashes_recursive($value);
528 } else if(is_array($var)) {
530 foreach($var as $property => $value) {
531 $new_var[$property] = stripslashes_recursive($value);
534 } else if(is_string($var)) {
535 $new_var = stripslashes($var);
545 * Recursive implementation of addslashes()
547 * This function will allow you to add the slashes from a variable.
548 * If the variable is an array or object, slashes will be added
549 * to the items (or properties) it contains, even if they are arrays
550 * or objects themselves.
552 * @param mixed the variable to add slashes from
555 function addslashes_recursive($var) {
556 if (is_object($var)) {
557 $new_var = new object();
558 $properties = get_object_vars($var);
559 foreach($properties as $property => $value) {
560 $new_var->$property = addslashes_recursive($value);
563 } else if (is_array($var)) {
565 foreach($var as $property => $value) {
566 $new_var[$property] = addslashes_recursive($value);
569 } else if (is_string($var)) {
570 $new_var = addslashes($var);
572 } else { // nulls, integers, etc.
580 * Given some normal text this function will break up any
581 * long words to a given size by inserting the given character
583 * It's multibyte savvy and doesn't change anything inside html tags.
585 * @param string $string the string to be modified
586 * @param int $maxsize maximum length of the string to be returned
587 * @param string $cutchar the string used to represent word breaks
590 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
592 /// Loading the textlib singleton instance. We are going to need it.
593 $textlib = textlib_get_instance();
595 /// First of all, save all the tags inside the text to skip them
597 filter_save_tags($string,$tags);
599 /// Process the string adding the cut when necessary
601 $length = $textlib->strlen($string);
604 for ($i=0; $i<$length; $i++
) {
605 $char = $textlib->substr($string, $i, 1);
606 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
610 if ($wordlength > $maxsize) {
618 /// Finally load the tags back again
620 $output = str_replace(array_keys($tags), $tags, $output);
627 * This does a search and replace, ignoring case
628 * This function is only used for versions of PHP older than version 5
629 * which do not have a native version of this function.
630 * Taken from the PHP manual, by bradhuizenga @ softhome.net
632 * @param string $find the string to search for
633 * @param string $replace the string to replace $find with
634 * @param string $string the string to search through
637 if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
638 function str_ireplace($find, $replace, $string) {
640 if (!is_array($find)) {
641 $find = array($find);
644 if(!is_array($replace)) {
645 if (!is_array($find)) {
646 $replace = array($replace);
648 // this will duplicate the string into an array the size of $find
652 for ($i = 0; $i < $c; $i++
) {
653 $replace[$i] = $rString;
658 foreach ($find as $fKey => $fItem) {
659 $between = explode(strtolower($fItem),strtolower($string));
661 foreach($between as $bKey => $bItem) {
662 $between[$bKey] = substr($string,$pos,strlen($bItem));
663 $pos +
= strlen($bItem) +
strlen($fItem);
665 $string = implode($replace[$fKey],$between);
672 * Locate the position of a string in another string
674 * This function is only used for versions of PHP older than version 5
675 * which do not have a native version of this function.
676 * Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
678 * @param string $haystack The string to be searched
679 * @param string $needle The string to search for
680 * @param int $offset The position in $haystack where the search should begin.
682 if (!function_exists('stripos')) { /// Only exists in PHP 5
683 function stripos($haystack, $needle, $offset=0) {
685 return strpos(strtoupper($haystack), strtoupper($needle), $offset);
690 * This function will print a button/link/etc. form element
691 * that will work on both Javascript and non-javascript browsers.
692 * Relies on the Javascript function openpopup in javascript.php
694 * All parameters default to null, only $type and $url are mandatory.
696 * $url must be relative to home page eg /mod/survey/stuff.php
697 * @param string $url Web link relative to home page
698 * @param string $name Name to be assigned to the popup window (this is used by
699 * client-side scripts to "talk" to the popup window)
700 * @param string $linkname Text to be displayed as web link
701 * @param int $height Height to assign to popup window
702 * @param int $width Height to assign to popup window
703 * @param string $title Text to be displayed as popup page title
704 * @param string $options List of additional options for popup window
705 * @param string $return If true, return as a string, otherwise print
706 * @param string $id id added to the element
707 * @param string $class class added to the element
711 function element_to_popup_window ($type=null, $url=null, $name=null, $linkname=null,
712 $height=400, $width=500, $title=null,
713 $options=null, $return=false, $id=null, $class=null) {
716 debugging('You must give the url to display in the popup. URL is missing - can\'t create popup window.', DEBUG_DEVELOPER
);
721 if ($options == 'none') { // 'none' is legacy, should be removed in v2.0
725 // add some sane default options for popup windows
727 $options = 'menubar=0,location=0,scrollbars,resizable';
730 $options .= ',width='. $width;
733 $options .= ',height='. $height;
736 $id = ' id="'.$id.'" ';
739 $class = ' class="'.$class.'" ';
743 if (($name = preg_replace("/\s/", '_', $name)) != $_name) {
744 debugging('The $name of a popup window shouldn\'t contain spaces - string modified. '. $_name .' changed to '. $name, DEBUG_DEVELOPER
);
750 // get some default string, using the localized version of legacy defaults
751 if (is_null($linkname) ||
$linkname === '') {
752 $linkname = get_string('clickhere');
755 $title = get_string('popupwindowname');
758 $fullscreen = 0; // must be passed to openpopup
763 $element = '<input type="button" name="'. $name .'" title="'. $title .'" value="'. $linkname .'" '. $id . $class .
764 "onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
767 // some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
768 if (!(strpos($url,$CFG->wwwroot
) === false)) {
769 $url = substr($url, strlen($CFG->wwwroot
));
771 $element = '<a title="'. s(strip_tags($title)) .'" href="'. $CFG->wwwroot
. $url .'" '.
772 "$CFG->frametarget onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
775 error('Undefined element - can\'t create popup window.');
787 * Creates and displays (or returns) a link to a popup window, using element_to_popup_window function.
789 * @return string html code to display a link to a popup window.
790 * @see element_to_popup_window()
792 function link_to_popup_window ($url, $name=null, $linkname=null,
793 $height=400, $width=500, $title=null,
794 $options=null, $return=false) {
796 return element_to_popup_window('link', $url, $name, $linkname, $height, $width, $title, $options, $return, null, null);
800 * Creates and displays (or returns) a buttons to a popup window, using element_to_popup_window function.
802 * @return string html code to display a button to a popup window.
803 * @see element_to_popup_window()
805 function button_to_popup_window ($url, $name=null, $linkname=null,
806 $height=400, $width=500, $title=null, $options=null, $return=false,
807 $id=null, $class=null) {
809 return element_to_popup_window('button', $url, $name, $linkname, $height, $width, $title, $options, $return, $id, $class);
814 * Prints a simple button to close a window
815 * @param string $name name of the window to close
816 * @param boolean $return whether this function should return a string or output it
817 * @return string if $return is true, nothing otherwise
819 function close_window_button($name='closewindow', $return=false) {
824 $output .= '<div class="closewindow">' . "\n";
825 $output .= '<form action="#"><div>';
826 $output .= '<input type="button" onclick="self.close();" value="'.get_string($name).'" />';
827 $output .= '</div></form>';
828 $output .= '</div>' . "\n";
838 * Try and close the current window immediately using Javascript
839 * @param int $delay the delay in seconds before closing the window
841 function close_window($delay=0) {
843 <script type
="text/javascript">
845 function close_this_window() {
848 setTimeout("close_this_window()", <?php
echo $delay * 1000 ?
>);
852 <?php
print_string('pleaseclose') ?
>
859 * Given an array of values, output the HTML for a select element with those options.
860 * Normally, you only need to use the first few parameters.
862 * @param array $options The options to offer. An array of the form
863 * $options[{value}] = {text displayed for that option};
864 * @param string $name the name of this form control, as in <select name="..." ...
865 * @param string $selected the option to select initially, default none.
866 * @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
867 * Set this to '' if you don't want a 'nothing is selected' option.
868 * @param string $script in not '', then this is added to the <select> element as an onchange handler.
869 * @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
870 * @param boolean $return if false (the default) the the output is printed directly, If true, the
871 * generated HTML is returned as a string.
872 * @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
873 * @param int $tabindex if give, sets the tabindex attribute on the <select> element. Default none.
874 * @param string $id value to use for the id attribute of the <select> element. If none is given,
875 * then a suitable one is constructed.
876 * @param mixed $listbox if false, display as a dropdown menu. If true, display as a list box.
877 * By default, the list box will have a number of rows equal to min(10, count($options)), but if
878 * $listbox is an integer, that number is used for size instead.
879 * @param boolean $multiple if true, enable multiple selections, else only 1 item can be selected. Used
880 * when $listbox display is enabled
881 * @param string $class value to use for the class attribute of the <select> element. If none is given,
882 * then a suitable one is constructed.
884 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
885 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0,
886 $id='', $listbox=false, $multiple=false, $class='') {
888 if ($nothing == 'choose') {
889 $nothing = get_string('choose') .'...';
892 $attributes = ($script) ?
'onchange="'. $script .'"' : '';
894 $attributes .= ' disabled="disabled"';
898 $attributes .= ' tabindex="'.$tabindex.'"';
903 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
904 $id = str_replace('[', '', $id);
905 $id = str_replace(']', '', $id);
909 $class = 'menu'.$name;
910 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
911 $class = str_replace('[', '', $class);
912 $class = str_replace(']', '', $class);
914 $class = 'select ' . $class; /// Add 'select' selector always
917 if (is_integer($listbox)) {
920 $numchoices = count($options);
924 $size = min(10, $numchoices);
926 $attributes .= ' size="' . $size . '"';
928 $attributes .= ' multiple="multiple"';
932 $output = '<select id="'. $id .'" class="'. $class .'" name="'. $name .'" '. $attributes .'>' . "\n";
934 $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
935 if ($nothingvalue === $selected) {
936 $output .= ' selected="selected"';
938 $output .= '>'. $nothing .'</option>' . "\n";
941 if (!empty($options)) {
942 foreach ($options as $value => $label) {
943 $output .= ' <option value="'. s($value) .'"';
944 if ((string)$value == (string)$selected ||
945 (is_array($selected) && in_array($value, $selected))) {
946 $output .= ' selected="selected"';
949 $output .= '>'. $value .'</option>' . "\n";
951 $output .= '>'. $label .'</option>' . "\n";
955 $output .= '</select>' . "\n";
965 * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
966 * Other options like choose_from_menu.
967 * @param string $name
968 * @param string $selected
969 * @param string $string (defaults to '')
970 * @param boolean $return whether this function should return a string or output it (defaults to false)
971 * @param boolean $disabled (defaults to false)
972 * @param int $tabindex
974 function choose_from_menu_yesno($name, $selected, $script = '',
975 $return = false, $disabled = false, $tabindex = 0) {
976 return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
977 $selected, '', $script, '0', $return, $disabled, $tabindex);
981 * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
982 * including option headings with the first level.
984 function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
985 $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
987 if ($nothing == 'choose') {
988 $nothing = get_string('choose') .'...';
991 $attributes = ($script) ?
'onchange="'. $script .'"' : '';
993 $attributes .= ' disabled="disabled"';
997 $attributes .= ' tabindex="'.$tabindex.'"';
1000 $output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
1002 $output .= ' <option value="'. $nothingvalue .'"'. "\n";
1003 if ($nothingvalue === $selected) {
1004 $output .= ' selected="selected"';
1006 $output .= '>'. $nothing .'</option>' . "\n";
1008 if (!empty($options)) {
1009 foreach ($options as $section => $values) {
1010 $output .= ' <optgroup label="'. s(strip_tags(format_string($section))) .'">'."\n";
1011 foreach ($values as $value => $label) {
1012 $output .= ' <option value="'. format_string($value) .'"';
1013 if ((string)$value == (string)$selected) {
1014 $output .= ' selected="selected"';
1016 if ($label === '') {
1017 $output .= '>'. $value .'</option>' . "\n";
1019 $output .= '>'. $label .'</option>' . "\n";
1022 $output .= ' </optgroup>'."\n";
1025 $output .= '</select>' . "\n";
1036 * Given an array of values, creates a group of radio buttons to be part of a form
1038 * @param array $options An array of value-label pairs for the radio group (values as keys)
1039 * @param string $name Name of the radiogroup (unique in the form)
1040 * @param string $checked The value that is already checked
1042 function choose_from_radio ($options, $name, $checked='', $return=false) {
1044 static $idcounter = 0;
1050 $output = '<span class="radiogroup '.$name."\">\n";
1052 if (!empty($options)) {
1054 foreach ($options as $value => $label) {
1055 $htmlid = 'auto-rb'.sprintf('%04d', ++
$idcounter);
1056 $output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
1057 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
1058 if ($value == $checked) {
1059 $output .= ' checked="checked"';
1061 if ($label === '') {
1062 $output .= ' /> <label for="'.$htmlid.'">'. $value .'</label></span>' . "\n";
1064 $output .= ' /> <label for="'.$htmlid.'">'. $label .'</label></span>' . "\n";
1066 $currentradio = ($currentradio +
1) %
2;
1070 $output .= '</span>' . "\n";
1079 /** Display an standard html checkbox with an optional label
1081 * @param string $name The name of the checkbox
1082 * @param string $value The valus that the checkbox will pass when checked
1083 * @param boolean $checked The flag to tell the checkbox initial state
1084 * @param string $label The label to be showed near the checkbox
1085 * @param string $alt The info to be inserted in the alt tag
1087 function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
1089 static $idcounter = 0;
1096 $alt = strip_tags($alt);
1102 $strchecked = ' checked="checked"';
1107 $htmlid = 'auto-cb'.sprintf('%04d', ++
$idcounter);
1108 $output = '<span class="checkbox '.$name."\">";
1109 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ?
' onclick="'.$script.'" ' : '').' />';
1110 if(!empty($label)) {
1111 $output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
1113 $output .= '</span>'."\n";
1115 if (empty($return)) {
1123 /** Display an standard html text field with an optional label
1125 * @param string $name The name of the text field
1126 * @param string $value The value of the text field
1127 * @param string $label The label to be showed near the text field
1128 * @param string $alt The info to be inserted in the alt tag
1130 function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
1132 static $idcounter = 0;
1142 if (!empty($maxlength)) {
1143 $maxlength = ' maxlength="'.$maxlength.'" ';
1146 $htmlid = 'auto-tf'.sprintf('%04d', ++
$idcounter);
1147 $output = '<span class="textfield '.$name."\">";
1148 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
1150 $output .= '</span>'."\n";
1152 if (empty($return)) {
1162 * Implements a complete little popup form
1165 * @param string $common The URL up to the point of the variable that changes
1166 * @param array $options Alist of value-label pairs for the popup list
1167 * @param string $formid Id must be unique on the page (originaly $formname)
1168 * @param string $selected The option that is already selected
1169 * @param string $nothing The label for the "no choice" option
1170 * @param string $help The name of a help page if help is required
1171 * @param string $helptext The name of the label for the help button
1172 * @param boolean $return Indicates whether the function should return the text
1173 * as a string or echo it directly to the page being rendered
1174 * @param string $targetwindow The name of the target page to open the linked page in.
1175 * @param string $selectlabel Text to place in a [label] element - preferred for accessibility.
1176 * @param array $optionsextra TODO, an array?
1177 * @param mixed $gobutton If set, this turns off the JavaScript and uses a 'go'
1178 * button instead (as is always included for JS-disabled users). Set to true
1179 * for a literal 'Go' button, or to a string to change the name of the button.
1180 * @return string If $return is true then the entire form is returned as a string.
1181 * @todo Finish documenting this function<br>
1183 function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
1184 $targetwindow='self', $selectlabel='', $optionsextra=NULL, $gobutton=NULL) {
1187 static $go, $choose; /// Locally cached, in case there's lots on a page
1189 if (empty($options)) {
1194 $go = get_string('go');
1197 if ($nothing == 'choose') {
1198 if (!isset($choose)) {
1199 $choose = get_string('choose');
1201 $nothing = $choose.'...';
1204 // changed reference to document.getElementById('id_abc') instead of document.abc
1206 $output = '<form action="'.$CFG->wwwroot
.'/course/jumpto.php"'.
1209 ' id="'.$formid.'"'.
1210 ' class="popupform">';
1212 $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
1218 $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
1222 // Using the no-JavaScript version
1224 } else if (check_browser_version('MSIE') ||
(check_browser_version('Opera') && !check_browser_operating_system("Linux"))) {
1225 //IE and Opera fire the onchange when ever you move into a dropdown list with the keyboard.
1226 //onfocus will call a function inside dropdown.js. It fixes this IE/Opera behavior.
1227 //Note: There is a bug on Opera+Linux with the javascript code (first mouse selection is inactive),
1228 //so we do not fix the Opera behavior on Linux
1229 $javascript = ' onfocus="initSelect(\''.$formid.'\','.$targetwindow.')"';
1232 $javascript = ' onchange="'.$targetwindow.
1233 '.location=document.getElementById(\''.$formid.
1234 '\').jump.options[document.getElementById(\''.
1235 $formid.'\').jump.selectedIndex].value;"';
1238 $output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" name="jump"'.$javascript.'>'."\n";
1240 if ($nothing != '') {
1241 $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
1244 $inoptgroup = false;
1246 foreach ($options as $value => $label) {
1248 if ($label == '--') { /// we are ending previous optgroup
1249 /// Check to see if we already have a valid open optgroup
1250 /// XHTML demands that there be at least 1 option within an optgroup
1251 if ($inoptgroup and (count($optgr) > 1) ) {
1252 $output .= implode('', $optgr);
1253 $output .= ' </optgroup>';
1256 $inoptgroup = false;
1258 } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
1260 /// Check to see if we already have a valid open optgroup
1261 /// XHTML demands that there be at least 1 option within an optgroup
1262 if ($inoptgroup and (count($optgr) > 1) ) {
1263 $output .= implode('', $optgr);
1264 $output .= ' </optgroup>';
1270 $optgr[] = ' <optgroup label="'. s(format_string(substr($label,2))) .'">'; // Plain labels
1272 $inoptgroup = true; /// everything following will be in an optgroup
1276 if (!empty($CFG->usesid
) && !isset($_COOKIE[session_name()]))
1278 $url=sid_process_url( $common . $value );
1281 $url=$common . $value;
1283 $optstr = ' <option value="' . $url . '"';
1285 if ($value == $selected) {
1286 $optstr .= ' selected="selected"';
1289 if (!empty($optionsextra[$value])) {
1290 $optstr .= ' '.$optionsextra[$value];
1294 $optstr .= '>'. $label .'</option>' . "\n";
1296 $optstr .= '>'. $value .'</option>' . "\n";
1308 /// catch the final group if not closed
1309 if ($inoptgroup and count($optgr) > 1) {
1310 $output .= implode('', $optgr);
1311 $output .= ' </optgroup>';
1314 $output .= '</select>';
1315 $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1317 $output .= '<input type="submit" value="'.
1318 ($gobutton===true ?
$go : $gobutton).'" />';
1320 $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
1321 $output .= '<input type="submit" value="'.$go.'" /></div>';
1322 $output .= '<script type="text/javascript">'.
1324 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
1325 "\n//]]>\n".'</script>';
1327 $output .= '</div></form>';
1338 * Prints some red text
1340 * @param string $error The text to be displayed in red
1342 function formerr($error) {
1344 if (!empty($error)) {
1345 echo '<span class="error">'. $error .'</span>';
1350 * Validates an email to make sure it makes sense.
1352 * @param string $address The email address to validate.
1355 function validate_email($address) {
1357 return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1358 '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1360 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1361 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
1366 * Extracts file argument either from file parameter or PATH_INFO
1368 * @param string $scriptname name of the calling script
1369 * @return string file path (only safe characters)
1371 function get_file_argument($scriptname) {
1374 $relativepath = FALSE;
1376 // first try normal parameter (compatible method == no relative links!)
1377 $relativepath = optional_param('file', FALSE, PARAM_PATH
);
1378 if ($relativepath === '/testslasharguments') {
1379 echo 'test -1 : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
1383 // then try extract file from PATH_INFO (slasharguments method)
1384 if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
1385 $path_info = $_SERVER['PATH_INFO'];
1386 // check that PATH_INFO works == must not contain the script name
1387 if (!strpos($path_info, $scriptname)) {
1388 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH
);
1389 if ($relativepath === '/testslasharguments') {
1390 echo 'test 1 : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
1396 // now if both fail try the old way
1397 // (for compatibility with misconfigured or older buggy php implementations)
1398 if (!$relativepath) {
1399 $arr = explode($scriptname, me());
1400 if (!empty($arr[1])) {
1401 $path_info = strip_querystring($arr[1]);
1402 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH
);
1403 if ($relativepath === '/testslasharguments') {
1404 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
1410 return $relativepath;
1414 * Searches the current environment variables for some slash arguments
1416 * @param string $file ?
1417 * @todo Finish documenting this function
1419 function get_slash_arguments($file='file.php') {
1421 if (!$string = me()) {
1425 $pathinfo = explode($file, $string);
1427 if (!empty($pathinfo[1])) {
1428 return addslashes($pathinfo[1]);
1435 * Extracts arguments from "/foo/bar/something"
1436 * eg http://mysite.com/script.php/foo/bar/something
1438 * @param string $string ?
1440 * @return array|string
1441 * @todo Finish documenting this function
1443 function parse_slash_arguments($string, $i=0) {
1445 if (detect_munged_arguments($string)) {
1448 $args = explode('/', $string);
1450 if ($i) { // return just the required argument
1453 } else { // return the whole array
1454 array_shift($args); // get rid of the empty first one
1460 * Just returns an array of text formats suitable for a popup menu
1462 * @uses FORMAT_MOODLE
1464 * @uses FORMAT_PLAIN
1465 * @uses FORMAT_MARKDOWN
1468 function format_text_menu() {
1470 return array (FORMAT_MOODLE
=> get_string('formattext'),
1471 FORMAT_HTML
=> get_string('formathtml'),
1472 FORMAT_PLAIN
=> get_string('formatplain'),
1473 FORMAT_MARKDOWN
=> get_string('formatmarkdown'));
1477 * Given text in a variety of format codings, this function returns
1478 * the text as safe HTML.
1480 * This function should mainly be used for long strings like posts,
1481 * answers, glossary items etc. For short strings @see format_string().
1484 * @uses FORMAT_MOODLE
1486 * @uses FORMAT_PLAIN
1488 * @uses FORMAT_MARKDOWN
1489 * @param string $text The text to be formatted. This is raw text originally from user input.
1490 * @param int $format Identifier of the text format to be used
1491 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1492 * @param array $options ?
1493 * @param int $courseid ?
1495 * @todo Finish documenting this function
1497 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
1499 global $CFG, $COURSE;
1501 static $croncache = array();
1504 return ''; // no need to do any filters and cleaning
1507 if (!isset($options->trusttext
)) {
1508 $options->trusttext
= false;
1511 if (!isset($options->noclean
)) {
1512 $options->noclean
=false;
1514 if (!isset($options->nocache
)) {
1515 $options->nocache
=false;
1517 if (!isset($options->smiley
)) {
1518 $options->smiley
=true;
1520 if (!isset($options->filter
)) {
1521 $options->filter
=true;
1523 if (!isset($options->para
)) {
1524 $options->para
=true;
1526 if (!isset($options->newlines
)) {
1527 $options->newlines
=true;
1530 if (empty($courseid)) {
1531 $courseid = $COURSE->id
;
1534 if (!empty($CFG->cachetext
) and empty($options->nocache
)) {
1535 $time = time() - $CFG->cachetext
;
1536 $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
);
1538 if (defined('FULLME') and FULLME
== 'cron') {
1539 if (isset($croncache[$md5key])) {
1540 return $croncache[$md5key];
1544 if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix
.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
1545 if ($oldcacheitem->timemodified
>= $time) {
1546 if (defined('FULLME') and FULLME
== 'cron') {
1547 if (count($croncache) > 150) {
1549 $key = key($croncache);
1550 unset($croncache[$key]);
1552 $croncache[$md5key] = $oldcacheitem->formattedtext
;
1554 return $oldcacheitem->formattedtext
;
1559 // trusttext overrides the noclean option!
1560 if ($options->trusttext
) {
1561 if (trusttext_present($text)) {
1562 $text = trusttext_strip($text);
1563 if (!empty($CFG->enabletrusttext
)) {
1564 $options->noclean
= true;
1566 $options->noclean
= false;
1569 $options->noclean
= false;
1571 } else if (!debugging('', DEBUG_DEVELOPER
)) {
1572 // strip any forgotten trusttext in non-developer mode
1573 // do not forget to disable text cache when debugging trusttext!!
1574 $text = trusttext_strip($text);
1577 $CFG->currenttextiscacheable
= true; // Default status - can be changed by any filter
1581 if ($options->smiley
) {
1582 replace_smilies($text);
1584 if (!$options->noclean
) {
1585 $text = clean_text($text, FORMAT_HTML
);
1587 if ($options->filter
) {
1588 $text = filter_text($text, $courseid);
1593 $text = s($text); // cleans dangerous JS
1594 $text = rebuildnolinktag($text);
1595 $text = str_replace(' ', ' ', $text);
1596 $text = nl2br($text);
1600 // this format is deprecated
1601 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1602 this message as all texts should have been converted to Markdown format instead.
1603 Please post a bug report to http://moodle.org/bugs with information about where you
1604 saw this message.</p>'.s($text);
1607 case FORMAT_MARKDOWN
:
1608 $text = markdown_to_html($text);
1609 if ($options->smiley
) {
1610 replace_smilies($text);
1612 if (!$options->noclean
) {
1613 $text = clean_text($text, FORMAT_HTML
);
1616 if ($options->filter
) {
1617 $text = filter_text($text, $courseid);
1621 default: // FORMAT_MOODLE or anything else
1622 $text = text_to_html($text, $options->smiley
, $options->para
, $options->newlines
);
1623 if (!$options->noclean
) {
1624 $text = clean_text($text, FORMAT_HTML
);
1627 if ($options->filter
) {
1628 $text = filter_text($text, $courseid);
1633 if (empty($options->nocache
) and !empty($CFG->cachetext
) and $CFG->currenttextiscacheable
) {
1634 if (defined('FULLME') and FULLME
== 'cron') {
1635 // special static cron cache - no need to store it in db if its not already there
1636 if (count($croncache) > 150) {
1638 $key = key($croncache);
1639 unset($croncache[$key]);
1641 $croncache[$md5key] = $text;
1645 $newcacheitem = new object();
1646 $newcacheitem->md5key
= $md5key;
1647 $newcacheitem->formattedtext
= addslashes($text);
1648 $newcacheitem->timemodified
= time();
1649 if ($oldcacheitem) { // See bug 4677 for discussion
1650 $newcacheitem->id
= $oldcacheitem->id
;
1651 @update_record
('cache_text', $newcacheitem); // Update existing record in the cache table
1652 // It's unlikely that the cron cache cleaner could have
1653 // deleted this entry in the meantime, as it allows
1654 // some extra time to cover these cases.
1656 @insert_record
('cache_text', $newcacheitem); // Insert a new record in the cache table
1657 // Again, it's possible that another user has caused this
1658 // record to be created already in the time that it took
1659 // to traverse this function. That's OK too, as the
1660 // call above handles duplicate entries, and eventually
1661 // the cron cleaner will delete them.
1668 /** Converts the text format from the value to the 'internal'
1669 * name or vice versa. $key can either be the value or the name
1670 * and you get the other back.
1672 * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1673 * @return mixed as above but the other way around!
1675 function text_format_name( $key ) {
1677 $lookup[FORMAT_MOODLE
] = 'moodle';
1678 $lookup[FORMAT_HTML
] = 'html';
1679 $lookup[FORMAT_PLAIN
] = 'plain';
1680 $lookup[FORMAT_MARKDOWN
] = 'markdown';
1682 if (!is_numeric($key)) {
1683 $key = strtolower( $key );
1684 $value = array_search( $key, $lookup );
1687 if (isset( $lookup[$key] )) {
1688 $value = $lookup[ $key ];
1695 * Resets all data related to filters, called during upgrade or when filter settings change.
1698 function reset_text_filters_cache() {
1701 delete_records('cache_text');
1702 $purifdir = $CFG->dataroot
.'/cache/htmlpurifier';
1703 remove_dir($purifdir, true);
1706 /** Given a simple string, this function returns the string
1707 * processed by enabled string filters if $CFG->filterall is enabled
1709 * This function should be used to print short strings (non html) that
1710 * need filter processing e.g. activity titles, post subjects,
1711 * glossary concepts.
1713 * @param string $string The string to be filtered.
1714 * @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
1715 * @param int $courseid Current course as filters can, potentially, use it
1718 function format_string ($string, $striplinks=true, $courseid=NULL ) {
1720 global $CFG, $COURSE;
1722 //We'll use a in-memory cache here to speed up repeated strings
1723 static $strcache = false;
1725 if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
1726 $strcache = array();
1730 if (empty($courseid)) {
1731 $courseid = $COURSE->id
;
1735 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
1737 //Fetch from cache if possible
1738 if (isset($strcache[$md5])) {
1739 return $strcache[$md5];
1742 // First replace all ampersands not followed by html entity code
1743 $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $string);
1745 if (!empty($CFG->filterall
)) {
1746 $string = filter_string($string, $courseid);
1749 // If the site requires it, strip ALL tags from this string
1750 if (!empty($CFG->formatstringstriptags
)) {
1751 $string = strip_tags($string);
1754 // Otherwise strip just links if that is required (default)
1755 if ($striplinks) { //strip links in string
1756 $string = preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1758 $string = clean_text($string);
1762 $strcache[$md5] = $string;
1768 * Given text in a variety of format codings, this function returns
1769 * the text as plain text suitable for plain email.
1771 * @uses FORMAT_MOODLE
1773 * @uses FORMAT_PLAIN
1775 * @uses FORMAT_MARKDOWN
1776 * @param string $text The text to be formatted. This is raw text originally from user input.
1777 * @param int $format Identifier of the text format to be used
1778 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1781 function format_text_email($text, $format) {
1790 // there should not be any of these any more!
1791 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1792 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
1793 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1794 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES
)));
1798 return html_to_text($text);
1802 case FORMAT_MARKDOWN
:
1804 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1805 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES
)));
1811 * Given some text in HTML format, this function will pass it
1812 * through any filters that have been defined in $CFG->textfilterx
1813 * The variable defines a filepath to a file containing the
1814 * filter function. The file must contain a variable called
1815 * $textfilter_function which contains the name of the function
1816 * with $courseid and $text parameters
1818 * @param string $text The text to be passed through format filters
1819 * @param int $courseid ?
1821 * @todo Finish documenting this function
1823 function filter_text($text, $courseid=NULL) {
1824 global $CFG, $COURSE;
1826 if (empty($courseid)) {
1827 $courseid = $COURSE->id
; // (copied from format_text)
1830 if (!empty($CFG->textfilters
)) {
1831 require_once($CFG->libdir
.'/filterlib.php');
1832 $textfilters = explode(',', $CFG->textfilters
);
1833 foreach ($textfilters as $textfilter) {
1834 if (is_readable($CFG->dirroot
.'/'. $textfilter .'/filter.php')) {
1835 include_once($CFG->dirroot
.'/'. $textfilter .'/filter.php');
1836 $functionname = basename($textfilter).'_filter';
1837 if (function_exists($functionname)) {
1838 $text = $functionname($courseid, $text);
1844 /// <nolink> tags removed for XHTML compatibility
1845 $text = str_replace('<nolink>', '', $text);
1846 $text = str_replace('</nolink>', '', $text);
1853 * Given a string (short text) in HTML format, this function will pass it
1854 * through any filters that have been defined in $CFG->stringfilters
1855 * The variable defines a filepath to a file containing the
1856 * filter function. The file must contain a variable called
1857 * $textfilter_function which contains the name of the function
1858 * with $courseid and $text parameters
1860 * @param string $string The text to be passed through format filters
1861 * @param int $courseid The id of a course
1864 function filter_string($string, $courseid=NULL) {
1865 global $CFG, $COURSE;
1867 if (empty($CFG->textfilters
)) { // All filters are disabled anyway so quit
1871 if (empty($courseid)) {
1872 $courseid = $COURSE->id
;
1875 require_once($CFG->libdir
.'/filterlib.php');
1877 if (isset($CFG->stringfilters
)) { // We have a predefined list to use, great!
1878 if (empty($CFG->stringfilters
)) { // but it's blank, so finish now
1881 $stringfilters = explode(',', $CFG->stringfilters
); // ..use the list we have
1883 } else { // Otherwise try to derive a list from textfilters
1884 if (strpos($CFG->textfilters
, 'filter/multilang') !== false) { // Multilang is here
1885 $stringfilters = array('filter/multilang'); // Let's use just that
1886 $CFG->stringfilters
= 'filter/multilang'; // Save it for next time through
1888 $CFG->stringfilters
= ''; // Save the result and return
1894 foreach ($stringfilters as $stringfilter) {
1895 if (is_readable($CFG->dirroot
.'/'. $stringfilter .'/filter.php')) {
1896 include_once($CFG->dirroot
.'/'. $stringfilter .'/filter.php');
1897 $functionname = basename($stringfilter).'_filter';
1898 if (function_exists($functionname)) {
1899 $string = $functionname($courseid, $string);
1904 /// <nolink> tags removed for XHTML compatibility
1905 $string = str_replace('<nolink>', '', $string);
1906 $string = str_replace('</nolink>', '', $string);
1912 * Is the text marked as trusted?
1914 * @param string $text text to be searched for TRUSTTEXT marker
1917 function trusttext_present($text) {
1918 if (strpos($text, TRUSTTEXT
) !== FALSE) {
1926 * This funtion MUST be called before the cleaning or any other
1927 * function that modifies the data! We do not know the origin of trusttext
1928 * in database, if it gets there in tweaked form we must not convert it
1929 * to supported form!!!
1931 * Please be carefull not to use stripslashes on data from database
1932 * or twice stripslashes when processing data recieved from user.
1934 * @param string $text text that may contain TRUSTTEXT marker
1935 * @return text without any TRUSTTEXT marker
1937 function trusttext_strip($text) {
1940 while (true) { //removing nested TRUSTTEXT
1942 $text = str_replace(TRUSTTEXT
, '', $text);
1943 if (strcmp($orig, $text) === 0) {
1950 * Mark text as trusted, such text may contain any HTML tags because the
1951 * normal text cleaning will be bypassed.
1952 * Please make sure that the text comes from trusted user before storing
1955 function trusttext_mark($text) {
1957 if (!empty($CFG->enabletrusttext
) and (strpos($text, TRUSTTEXT
) === FALSE)) {
1958 return TRUSTTEXT
.$text;
1963 function trusttext_after_edit(&$text, $context) {
1964 if (has_capability('moodle/site:trustcontent', $context)) {
1965 $text = trusttext_strip($text);
1966 $text = trusttext_mark($text);
1968 $text = trusttext_strip($text);
1972 function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
1975 $options = new object();
1976 $options->smiley
= false;
1977 $options->filter
= false;
1978 if (!empty($CFG->enabletrusttext
)
1979 and has_capability('moodle/site:trustcontent', $context)
1980 and trusttext_present($text)) {
1981 $options->noclean
= true;
1983 $options->noclean
= false;
1985 $text = trusttext_strip($text);
1986 if ($usehtmleditor) {
1987 $text = format_text($text, $format, $options);
1988 $format = FORMAT_HTML
;
1989 } else if (!$options->noclean
){
1990 $text = clean_text($text, $format);
1995 * Given raw text (eg typed in by a user), this function cleans it up
1996 * and removes any nasty tags that could mess up Moodle pages.
1998 * @uses FORMAT_MOODLE
1999 * @uses FORMAT_PLAIN
2000 * @uses ALLOWED_TAGS
2001 * @param string $text The text to be cleaned
2002 * @param int $format Identifier of the text format to be used
2003 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
2004 * @return string The cleaned up text
2006 function clean_text($text, $format=FORMAT_MOODLE
) {
2008 global $ALLOWED_TAGS, $CFG;
2010 if (empty($text) or is_numeric($text)) {
2011 return (string)$text;
2016 case FORMAT_MARKDOWN
:
2021 if (!empty($CFG->enablehtmlpurifier
)) {
2022 //this is PHP5 only, the lib/setup.php contains a disabler for PHP4
2023 $text = purify_html($text);
2025 /// Fix non standard entity notations
2026 $text = preg_replace('/�*([0-9]+);?/', "&#\\1;", $text);
2027 $text = preg_replace('/�*([0-9a-fA-F]+);?/', "&#x\\1;", $text);
2029 /// Remove tags that are not allowed
2030 $text = strip_tags($text, $ALLOWED_TAGS);
2032 /// Clean up embedded scripts and , using kses
2033 $text = cleanAttributes($text);
2035 /// Again remove tags that are not allowed
2036 $text = strip_tags($text, $ALLOWED_TAGS);
2040 /// Remove potential script events - some extra protection for undiscovered bugs in our code
2041 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
2042 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
2049 * KSES replacement cleaning function - uses HTML Purifier.
2052 * @param string $text The (X)HTML string to purify
2054 function purify_html($text) {
2057 // this can not be done only once because we sometimes need to reset the cache
2058 $cachedir = $CFG->dataroot
.'/cache/htmlpurifier';
2059 $status = check_dir_exists($cachedir, true, true);
2061 static $purifier = false;
2063 if ($purifier === false) {
2064 require_once $CFG->libdir
.'/htmlpurifier/HTMLPurifier.safe-includes.php';
2065 $config = HTMLPurifier_Config
::createDefault();
2066 $config->set('Output.Newline', "\n");
2067 $config->set('Core.ConvertDocumentToFragment', true);
2068 $config->set('Core.Encoding', 'UTF-8');
2069 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
2070 $config->set('Cache.SerializerPath', $cachedir);
2071 $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));
2072 $config->set('Attr.AllowedFrameTargets', array('_blank'));
2073 $purifier = new HTMLPurifier($config);
2075 return $purifier->purify($text);
2079 * This function takes a string and examines it for HTML tags.
2080 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
2081 * which checks for attributes and filters them for malicious content
2082 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2084 * @param string $str The string to be examined for html tags
2087 function cleanAttributes($str){
2088 $result = preg_replace_callback(
2089 '%(<[^>]*(>|$)|>)%m', #search for html tags
2097 * This function takes a string with an html tag and strips out any unallowed
2098 * protocols e.g. javascript:
2099 * It calls ancillary functions in kses which are prefixed by kses
2100 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2102 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
2103 * element the html to be cleared
2106 function cleanAttributes2($htmlArray){
2108 global $CFG, $ALLOWED_PROTOCOLS;
2109 require_once($CFG->libdir
.'/kses.php');
2111 $htmlTag = $htmlArray[1];
2112 if (substr($htmlTag, 0, 1) != '<') {
2113 return '>'; //a single character ">" detected
2115 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
2116 return ''; // It's seriously malformed
2118 $slash = trim($matches[1]); //trailing xhtml slash
2119 $elem = $matches[2]; //the element name
2120 $attrlist = $matches[3]; // the list of attributes as a string
2122 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
2125 foreach ($attrArray as $arreach) {
2126 $arreach['name'] = strtolower($arreach['name']);
2127 if ($arreach['name'] == 'style') {
2128 $value = $arreach['value'];
2130 $prevvalue = $value;
2131 $value = kses_no_null($value);
2132 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
2133 $value = kses_decode_entities($value);
2134 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
2135 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
2136 if ($value === $prevvalue) {
2137 $arreach['value'] = $value;
2141 $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']);
2142 $arreach['value'] = preg_replace("/v\s*b\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xvbscript", $arreach['value']);
2143 $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']);
2144 $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
2145 } else if ($arreach['name'] == 'href') {
2146 //Adobe Acrobat Reader XSS protection
2147 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd)[^#]*)#.*$/i', '$1', $arreach['value']);
2149 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
2153 if (preg_match('%/\s*$%', $attrlist)) {
2154 $xhtml_slash = ' /';
2156 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
2160 * Replaces all known smileys in the text with image equivalents
2163 * @param string $text Passed by reference. The string to search for smily strings.
2166 function replace_smilies(&$text) {
2170 if (empty($CFG->emoticons
)) { /// No emoticons defined, nothing to process here
2174 $lang = current_language();
2175 $emoticonstring = $CFG->emoticons
;
2176 static $e = array();
2177 static $img = array();
2178 static $emoticons = null;
2180 if (is_null($emoticons)) {
2181 $emoticons = array();
2182 if ($emoticonstring) {
2183 $items = explode('{;}', $CFG->emoticons
);
2184 foreach ($items as $item) {
2185 $item = explode('{:}', $item);
2186 $emoticons[$item[0]] = $item[1];
2192 if (empty($img[$lang])) { /// After the first time this is not run again
2193 $e[$lang] = array();
2194 $img[$lang] = array();
2195 foreach ($emoticons as $emoticon => $image){
2196 $alttext = get_string($image, 'pix');
2197 $alttext = preg_replace('/^\[\[(.*)\]\]$/', '$1', $alttext); /// Clean alttext in case there isn't lang string for it.
2198 $e[$lang][] = $emoticon;
2199 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath
.'/s/'. $image .'.gif" />';
2203 // Exclude from transformations all the code inside <script> tags
2204 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
2205 // Based on code from glossary fiter by Williams Castillo.
2208 // Detect all the <script> zones to take out
2209 $excludes = array();
2210 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
2212 // Take out all the <script> zones from text
2213 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
2214 $excludes['<+'.$key.'+>'] = $value;
2217 $text = str_replace($excludes,array_keys($excludes),$text);
2220 /// this is the meat of the code - this is run every time
2221 $text = str_replace($e[$lang], $img[$lang], $text);
2223 // Recover all the <script> zones to text
2225 $text = str_replace(array_keys($excludes),$excludes,$text);
2230 * Given plain text, makes it into HTML as nicely as possible.
2231 * May contain HTML tags already
2234 * @param string $text The string to convert.
2235 * @param boolean $smiley Convert any smiley characters to smiley images?
2236 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
2237 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2241 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
2246 /// Remove any whitespace that may be between HTML tags
2247 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
2249 /// Remove any returns that precede or follow HTML tags
2250 $text = eregi_replace("([\n\r])<", " <", $text);
2251 $text = eregi_replace(">([\n\r])", "> ", $text);
2253 convert_urls_into_links($text);
2255 /// Make returns into HTML newlines.
2257 $text = nl2br($text);
2260 /// Turn smileys into images.
2262 replace_smilies($text);
2265 /// Wrap the whole thing in a paragraph tag if required
2267 return '<p>'.$text.'</p>';
2274 * Given Markdown formatted text, make it into XHTML using external function
2277 * @param string $text The markdown formatted text to be converted.
2278 * @return string Converted text
2280 function markdown_to_html($text) {
2283 require_once($CFG->libdir
.'/markdown.php');
2285 return Markdown($text);
2289 * Given HTML text, make it into plain text using external function
2291 * @param string $html The text to be converted.
2292 * @param integer $width Width to wrap the text at. (optional, default 75 which
2293 * is a good value for email. 0 means do not limit line length.)
2294 * @return string plain text equivalent of the HTML.
2296 function html_to_text($html, $width = 75) {
2300 require_once($CFG->libdir
.'/html2text.php');
2302 $h2t = new html2text($html, false, true, $width);
2303 $result = $h2t->get_text();
2309 * Given some text this function converts any URLs it finds into HTML links
2311 * @param string $text Passed in by reference. The string to be searched for urls.
2313 function convert_urls_into_links(&$text) {
2314 //I've added img tags to this list of tags to ignore.
2315 //See MDL-21168 for more info. A better way to ignore tags whether or not
2316 //they are escaped partially or completely would be desirable. For example:
2318 //<a href="blah">
2319 //<a href="blah">
2320 $filterignoretagsopen = array('<a\s[^>]+?>');
2321 $filterignoretagsclose = array('</a>');
2322 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
2324 // Check if we support unicode modifiers in regular expressions. Cache it.
2325 // TODO: this check should be a environment requirement in Moodle 2.0, as far as unicode
2326 // chars are going to arrive to URLs officially really soon (2010?)
2327 // Original RFC regex from: http://www.bytemycode.com/snippets/snippet/796/
2328 // Various ideas from: http://alanstorm.com/url_regex_explained
2329 // Unicode check, negative assertion and other bits from Moodle.
2330 static $unicoderegexp;
2331 if (!isset($unicoderegexp)) {
2332 $unicoderegexp = @preg_match
('/\pL/u', 'a'); // This will fail silenty, returning false,
2335 $unicoderegexp = false;//force non use of unicode modifiers. MDL-21296
2336 if ($unicoderegexp) { //We can use unicode modifiers
2337 $text = preg_replace('#(?<!=["\'])(((http(s?))://)(((([\pLl0-9]([\pLl0-9]|-)*[\pLl0-9]|[\pLl0-9])\.)+([\pLl]([\pLl0-9]|-)*[\pLl0-9]|[\pLl]))|(([0-9]{1,3}\.){3}[0-9]{1,3}))(:[\pL0-9]*)?(/([\pLl0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-fA-F0-9]{2})*)*(\?([\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,\.;])#iu',
2338 '<a href="\\1" target="_blank">\\1</a>', $text);
2339 $text = preg_replace('#(?<!=["\']|//)((www\.([\pLl0-9]([\pLl0-9]|-)*[\pLl0-9]|[\pLl0-9])\.)+([\pLl]([\pLl0-9]|-)*[\pLl0-9]|[\pLl])(:[\pL0-9]*)?(/([\pLl0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-fA-F0-9]{2})*)*(\?([\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,\.;])#iu',
2340 '<a href="http://\\1" target="_blank">\\1</a>', $text);
2341 } else { //We cannot use unicode modifiers
2342 $text = preg_replace('#(?<!=["\'])(((http(s?))://)(((([a-z0-9]([a-z0-9]|-)*[a-z0-9]|[a-z0-9])\.)+([a-z]([a-z0-9]|-)*[a-z0-9]|[a-z]))|(([0-9]{1,3}\.){3}[0-9]{1,3}))(:[a-zA-Z0-9]*)?(/([a-z0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-f0-9]{2})*)*(\?([a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,\.;])#i',
2343 '<a href="\\1" target="_blank">\\1</a>', $text);
2344 $text = preg_replace('#(?<!=["\']|//)((www\.([a-z0-9]([a-z0-9]|-)*[a-z0-9]|[a-z0-9])\.)+([a-z]([a-z0-9]|-)*[a-z0-9]|[a-z])(:[a-zA-Z0-9]*)?(/([a-z0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-f0-9]{2})*)*(\?([a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,\.;])#i',
2345 '<a href="http://\\1" target="_blank">\\1</a>', $text);
2348 if (!empty($ignoretags)) {
2349 $ignoretags = array_reverse($ignoretags); /// Reversed so "progressive" str_replace() will solve some nesting problems.
2350 $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
2355 * This function will highlight search words in a given string
2356 * It cares about HTML and will not ruin links. It's best to use
2357 * this function after performing any conversions to HTML.
2359 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
2360 * @param string $haystack The string (HTML) within which to highlight the search terms.
2361 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
2362 * @param string $prefix the string to put before each search term found.
2363 * @param string $suffix the string to put after each search term found.
2364 * @return string The highlighted HTML.
2366 function highlight($needle, $haystack, $matchcase = false,
2367 $prefix = '<span class="highlight">', $suffix = '</span>') {
2369 /// Quick bail-out in trivial cases.
2370 if (empty($needle) or empty($haystack)) {
2374 /// Break up the search term into words, discard any -words and build a regexp.
2375 $words = preg_split('/ +/', trim($needle));
2376 foreach ($words as $index => $word) {
2377 if (strpos($word, '-') === 0) {
2378 unset($words[$index]);
2379 } else if (strpos($word, '+') === 0) {
2380 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
2382 $words[$index] = preg_quote($word, '/');
2385 $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
2390 /// Another chance to bail-out if $search was only -words
2391 if (empty($words)) {
2395 /// Find all the HTML tags in the input, and store them in a placeholders array.
2396 $placeholders = array();
2398 preg_match_all('/<[^>]*>/', $haystack, $matches);
2399 foreach (array_unique($matches[0]) as $key => $htmltag) {
2400 $placeholders['<|' . $key . '|>'] = $htmltag;
2403 /// In $hastack, replace each HTML tag with the corresponding placeholder.
2404 $haystack = str_replace($placeholders, array_keys($placeholders), $haystack);
2406 /// In the resulting string, Do the highlighting.
2407 $haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack);
2409 /// Turn the placeholders back into HTML tags.
2410 $haystack = str_replace(array_keys($placeholders), $placeholders, $haystack);
2416 * This function will highlight instances of $needle in $haystack
2417 * It's faster that the above function and doesn't care about
2420 * @param string $needle The string to search for
2421 * @param string $haystack The string to search for $needle in
2424 function highlightfast($needle, $haystack) {
2426 if (empty($needle) or empty($haystack)) {
2430 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
2432 if (count($parts) === 1) {
2438 foreach ($parts as $key => $part) {
2439 $parts[$key] = substr($haystack, $pos, strlen($part));
2440 $pos +
= strlen($part);
2442 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2443 $pos +
= strlen($needle);
2446 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2450 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2451 * Internationalisation, for print_header and backup/restorelib.
2452 * @param $dir Default false.
2453 * @return string Attributes.
2455 function get_html_lang($dir = false) {
2458 if (get_string('thisdirection') == 'rtl') {
2459 $direction = ' dir="rtl"';
2461 $direction = ' dir="ltr"';
2464 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2465 $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
2466 @header
('Content-Language: '.$language);
2467 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2471 * Return the markup for the destination of the 'Skip to main content' links.
2472 * Accessibility improvement for keyboard-only users.
2473 * Used in course formats, /index.php and /course/index.php
2474 * @return string HTML element.
2476 function skip_main_destination() {
2477 return '<span id="maincontent"></span>';
2481 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
2484 * Print a standard header
2489 * @param string $title Appears at the top of the window
2490 * @param string $heading Appears at the top of the page
2491 * @param array $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
2492 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2493 * @param string $meta Meta tags to be added to the header
2494 * @param boolean $cache Should this page be cacheable?
2495 * @param string $button HTML code for a button (usually for module editing)
2496 * @param string $menu HTML code for a popup menu
2497 * @param boolean $usexml use XML for this page
2498 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2499 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2501 function print_header ($title='', $heading='', $navigation='', $focus='',
2502 $meta='', $cache=true, $button=' ', $menu='',
2503 $usexml=false, $bodytags='', $return=false) {
2505 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
2507 if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
2508 debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
2509 . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.", DEBUG_DEVELOPER
);
2512 $heading = format_string($heading); // Fix for MDL-8582
2514 /// This makes sure that the header is never repeated twice on a page
2515 if (defined('HEADER_PRINTED')) {
2516 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().');
2519 define('HEADER_PRINTED', 'true');
2521 /// Perform a browser environment check for the flash version. Should only run once per login session.
2522 if (isloggedin() && !empty($CFG->excludeoldflashclients
) && empty($SESSION->flashversion
)) {
2523 // Unfortunately we can't use require_js here and keep it all clean in 1.9 ...
2524 // require_js(array('yui_yahoo', 'yui_event', 'yui_connection', $CFG->httpswwwroot."/lib/swfobject/swfobject.js"));
2525 $meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot
.'/lib/yui/yahoo/yahoo-min.js"></script>';
2526 $meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot
.'/lib/yui/event/event-min.js"></script>';
2527 $meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot
.'/lib/yui/connection/connection-min.js"></script>';
2528 $meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot
.'/lib/swfobject/swfobject.js"></script>';
2530 "<script type=\"text/javascript\">\n".
2532 " var flashversion = swfobject.getFlashPlayerVersion();\n".
2533 " YAHOO.util.Connect.asyncRequest('GET','".$CFG->httpswwwroot
."/login/environment.php?sesskey=".sesskey()."&flashversion='+flashversion.major+'.'+flashversion.minor+'.'+flashversion.release);\n".
2539 /// Add the required stylesheets
2540 $stylesheetshtml = '';
2541 foreach ($CFG->stylesheets
as $stylesheet) {
2542 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2544 $meta = $stylesheetshtml.$meta;
2547 /// Add the meta page from the themes if any were requested
2551 if (!isset($THEME->standardmetainclude
) ||
$THEME->standardmetainclude
) {
2553 include_once($CFG->dirroot
.'/theme/standard/meta.php');
2554 $metapage .= ob_get_contents();
2558 if ($THEME->parent
&& (!isset($THEME->parentmetainclude
) ||
$THEME->parentmetainclude
)) {
2559 if (file_exists($CFG->dirroot
.'/theme/'.$THEME->parent
.'/meta.php')) {
2561 include_once($CFG->dirroot
.'/theme/'.$THEME->parent
.'/meta.php');
2562 $metapage .= ob_get_contents();
2567 if (!isset($THEME->metainclude
) ||
$THEME->metainclude
) {
2568 if (file_exists($CFG->dirroot
.'/theme/'.current_theme().'/meta.php')) {
2570 include_once($CFG->dirroot
.'/theme/'.current_theme().'/meta.php');
2571 $metapage .= ob_get_contents();
2576 $meta = $meta."\n".$metapage;
2578 $meta .= "\n".require_js('',1);
2580 /// Set up some navigation variables
2582 if (is_newnav($navigation)){
2585 if ($navigation == 'home') {
2593 /// This is another ugly hack to make navigation elements available to print_footer later
2594 $THEME->title
= $title;
2595 $THEME->heading
= $heading;
2596 $THEME->navigation
= $navigation;
2597 $THEME->button
= $button;
2598 $THEME->menu
= $menu;
2599 $navmenulist = isset($THEME->navmenulist
) ?
$THEME->navmenulist
: '';
2601 if ($button == '') {
2605 if (file_exists($CFG->dataroot
.'/'.SITEID
.'/maintenance.html')) {
2606 $button = '<a href="'.$CFG->wwwroot
.'/'.$CFG->admin
.'/maintenance.php">'.get_string('maintenancemode', 'admin').'</a> '.$button;
2607 if(!empty($title)) {
2610 $title .= get_string('maintenancemode', 'admin');
2613 if (!$menu and $navigation) {
2614 if (empty($CFG->loginhttps
)) {
2615 $wwwroot = $CFG->wwwroot
;
2618 $wwwroot = str_replace('http:','https:',$CFG->wwwroot
);
2620 $menu = user_login_string($COURSE);
2623 if (isset($SESSION->justloggedin
)) {
2624 unset($SESSION->justloggedin
);
2625 if (!empty($CFG->displayloginfailures
)) {
2626 if (!empty($USER->username
) and $USER->username
!= 'guest') {
2627 if ($count = count_login_failures($CFG->displayloginfailures
, $USER->username
, $USER->lastlogin
)) {
2628 $menu .= ' <font size="1">';
2629 if (empty($count->accounts
)) {
2630 $menu .= get_string('failedloginattempts', '', $count);
2632 $menu .= get_string('failedloginattemptsall', '', $count);
2634 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM
))) {
2635 $menu .= ' (<a href="'.$CFG->wwwroot
.'/course/report/log/index.php'.
2636 '?chooselog=1&id=1&modid=site_errors">'.get_string('logs').'</a>)';
2645 $meta = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' .
2646 "\n" . $meta . "\n";
2648 @header
('Content-Type: text/html; charset=utf-8');
2650 @header
('Content-Script-Type: text/javascript');
2651 @header
('Content-Style-Type: text/css');
2653 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2654 $direction = get_html_lang($dir=true);
2656 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2657 @header
('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2658 @header
('Pragma: no-cache');
2659 @header
('Expires: ');
2660 } else { // Do everything we can to always prevent clients and proxies caching
2661 @header
('Cache-Control: no-store, no-cache, must-revalidate');
2662 @header
('Cache-Control: post-check=0, pre-check=0', false);
2663 @header
('Pragma: no-cache');
2664 @header
('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2665 @header
('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2667 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2668 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
2670 @header
('Accept-Ranges: none');
2672 $currentlanguage = current_language();
2674 if (empty($usexml)) {
2675 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2677 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2679 header('Content-Type: application/xhtml+xml');
2681 echo '<?xml version="1.0" ?>'."\n";
2682 if (!empty($CFG->xml_stylesheets
)) {
2683 $stylesheets = explode(';', $CFG->xml_stylesheets
);
2684 foreach ($stylesheets as $stylesheet) {
2685 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot
.'/'. $stylesheet .'" ?>' . "\n";
2688 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
2689 if (!empty($CFG->xml_doctype_extra
)) {
2690 echo ' plus '. $CFG->xml_doctype_extra
;
2692 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd
.'">'."\n";
2693 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2694 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
2695 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2698 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
2699 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2700 $meta .= '</object>'."\n";
2701 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2705 // Clean up the title
2707 $title = format_string($title); // fix for MDL-8582
2708 $title = str_replace('"', '"', $title);
2710 // Create class and id for this page
2712 page_id_and_class($pageid, $pageclass);
2714 $pageclass .= ' course-'.$COURSE->id
;
2716 if (!isloggedin()) {
2717 $pageclass .= ' notloggedin';
2720 if (!empty($USER->editing
)) {
2721 $pageclass .= ' editing';
2724 if (!empty($CFG->blocksdrag
)) {
2725 $pageclass .= ' drag';
2728 $pageclass .= ' dir-'.get_string('thisdirection');
2730 $pageclass .= ' lang-'.$currentlanguage;
2732 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
2735 include($CFG->header
);
2736 $output = ob_get_contents();
2739 // container debugging info
2740 $THEME->open_header_containers
= open_containers();
2742 // Skip to main content, see skip_main_destination().
2743 if ($pageid=='course-view' or $pageid=='site-index' or $pageid=='course-index') {
2744 $skiplink = '<a class="skip" href="#maincontent">'.get_string('tocontent', 'access').'</a>';
2745 if (! preg_match('/(.*<div[^>]+id="page"[^>]*>)(.*)/s', $output, $matches)) {
2746 preg_match('/(.*<body.*?>)(.*)/s', $output, $matches);
2748 $output = $matches[1]."\n". $skiplink .$matches[2];
2751 $output = force_strict_header($output);
2753 if (!empty($CFG->messaging
)) {
2754 $output .= message_popup_window();
2757 // Add in any extra JavaScript libraries that occurred during the header
2758 $output .= require_js('', 2);
2768 * Used to include JavaScript libraries.
2770 * When the $lib parameter is given, the function will ensure that the
2771 * named library is loaded onto the page - either in the HTML <head>,
2772 * just after the header, or at an arbitrary later point in the page,
2773 * depending on where this function is called.
2775 * Libraries will not be included more than once, so this works like
2776 * require_once in PHP.
2778 * There are two special-case calls to this function which are both used only
2779 * by weblib print_header:
2780 * $extracthtml = 1: this is used before printing the header.
2781 * It returns the script tag code that should go inside the <head>.
2782 * $extracthtml = 2: this is used after printing the header and handles any
2783 * require_js calls that occurred within the header itself.
2785 * @param mixed $lib - string or array of strings
2786 * string(s) should be the shortname for the library or the
2787 * full path to the library file.
2788 * @param int $extracthtml Do not set this parameter usually (leave 0), only
2789 * weblib should set this to 1 or 2 in print_header function.
2790 * @return mixed No return value, except when using $extracthtml it returns the html code.
2792 function require_js($lib,$extracthtml=0) {
2794 static $loadlibs = array();
2796 static $state = REQUIREJS_BEFOREHEADER
;
2797 static $latecode = '';
2800 // Add the lib to the list of libs to be loaded, if it isn't already
2802 if (is_array($lib)) {
2803 foreach($lib as $singlelib) {
2804 require_js($singlelib);
2807 $libpath = ajax_get_lib($lib);
2808 if (array_search($libpath, $loadlibs) === false) {
2809 $loadlibs[] = $libpath;
2811 // For state other than 0 we need to take action as well as just
2812 // adding it to loadlibs
2813 if($state != REQUIREJS_BEFOREHEADER
) {
2814 // Get the script statement for this library
2815 $scriptstatement=get_require_js_code(array($libpath));
2817 if($state == REQUIREJS_AFTERHEADER
) {
2818 // After the header, print it immediately
2819 print $scriptstatement;
2821 // Haven't finished the header yet. Add it after the
2823 $latecode .= $scriptstatement;
2828 } else if($extracthtml==1) {
2829 if($state !== REQUIREJS_BEFOREHEADER
) {
2830 debugging('Incorrect state in require_js (expected BEFOREHEADER): be careful not to call with empty $lib (except in print_header)');
2832 $state = REQUIREJS_INHEADER
;
2835 return get_require_js_code($loadlibs);
2836 } else if($extracthtml==2) {
2837 if($state !== REQUIREJS_INHEADER
) {
2838 debugging('Incorrect state in require_js (expected INHEADER): be careful not to call with empty $lib (except in print_header)');
2841 $state = REQUIREJS_AFTERHEADER
;
2845 debugging('Unexpected value for $extracthtml');
2850 * Should not be called directly - use require_js. This function obtains the code
2851 * (script tags) needed to include JavaScript libraries.
2852 * @param array $loadlibs Array of library files to include
2853 * @return string HTML code to include them
2855 function get_require_js_code($loadlibs) {
2857 // Return the html needed to load the JavaScript files defined in
2858 // our list of libs to be loaded.
2860 foreach ($loadlibs as $loadlib) {
2861 $output .= '<script type="text/javascript" ';
2862 $output .= " src=\"$loadlib\"></script>\n";
2863 if ($loadlib == $CFG->wwwroot
.'/lib/yui/logger/logger-min.js') {
2864 // Special case, we need the CSS too.
2865 $output .= '<link type="text/css" rel="stylesheet" ';
2866 $output .= " href=\"{$CFG->wwwroot}/lib/yui/logger/assets/logger.css\" />\n";
2874 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2875 * and substitute the XHTML strict document type.
2876 * Note, requires the 'xmlns' fix in function print_header above.
2877 * See: http://tracker.moodle.org/browse/MDL-7883
2880 function force_strict_header($output) {
2882 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2883 $xsl = '/lib/xhtml.xsl';
2885 if (!headers_sent() && !empty($CFG->xmlstrictheaders
)) { // With xml strict headers, the browser will barf
2886 $ctype = 'Content-Type: ';
2887 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2889 if (isset($_SERVER['HTTP_ACCEPT'])
2890 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2891 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2893 $ctype .= 'application/xhtml+xml';
2894 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2896 } else if (file_exists($CFG->dirroot
.$xsl)
2897 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2898 // XSL hack for IE 5+ on Windows.
2899 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2900 $www_xsl = $CFG->wwwroot
.$xsl;
2901 $ctype .= 'application/xml';
2902 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2903 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2906 //ELSE: Mac/IE, old/non-XML browsers.
2907 $ctype .= 'text/html';
2910 @header
($ctype.'; charset=utf-8');
2911 $output = $prolog . $output;
2913 // Test parser error-handling.
2914 if (isset($_GET['error'])) {
2915 $output .= "__ TEST: XML well-formed error < __\n";
2919 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
2927 * This version of print_header is simpler because the course name does not have to be
2928 * provided explicitly in the strings. It can be used on the site page as in courses
2929 * Eventually all print_header could be replaced by print_header_simple
2931 * @param string $title Appears at the top of the window
2932 * @param string $heading Appears at the top of the page
2933 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2934 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2935 * @param string $meta Meta tags to be added to the header
2936 * @param boolean $cache Should this page be cacheable?
2937 * @param string $button HTML code for a button (usually for module editing)
2938 * @param string $menu HTML code for a popup menu
2939 * @param boolean $usexml use XML for this page
2940 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2941 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2943 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
2944 $cache=true, $button=' ', $menu='', $usexml=false, $bodytags='', $return=false) {
2946 global $COURSE, $CFG;
2948 // if we have no navigation specified, build it
2949 if( empty($navigation) ){
2950 $navigation = build_navigation('');
2953 // If old style nav prepend course short name otherwise leave $navigation object alone
2954 if (!is_newnav($navigation)) {
2955 if ($COURSE->id
!= SITEID
) {
2956 $shortname = '<a href="'.$CFG->wwwroot
.'/course/view.php?id='. $COURSE->id
.'">'. $COURSE->shortname
.'</a> ->';
2957 $navigation = $shortname.' '.$navigation;
2961 $output = print_header($COURSE->shortname
.': '. $title, $COURSE->fullname
.' '. $heading, $navigation, $focus, $meta,
2962 $cache, $button, $menu, $usexml, $bodytags, true);
2973 * Can provide a course object to make the footer contain a link to
2974 * to the course home page, otherwise the link will go to the site home
2976 * @param mixed $course course object, used for course link button or
2977 * 'none' means no user link, only docs link
2978 * 'empty' means nothing printed in footer
2979 * 'home' special frontpage footer
2980 * @param object $usercourse course used in user link
2981 * @param boolean $return output as string
2982 * @return mixed string or void
2984 function print_footer($course=NULL, $usercourse=NULL, $return=false) {
2985 global $USER, $CFG, $THEME, $COURSE;
2987 if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
2988 admin_externalpage_print_footer();
2992 /// Course links or special footer
2994 if ($course === 'empty') {
2995 // special hack - sometimes we do not want even the docs link in footer
2997 if (!empty($THEME->open_header_containers
)) {
2998 for ($i=0; $i<$THEME->open_header_containers
; $i++
) {
2999 $output .= print_container_end_all(); // containers opened from header
3002 //1.8 theme compatibility
3003 $output .= "\n</div>"; // content div
3005 $output .= "\n</div>\n</body>\n</html>"; // close page div started in header
3013 } else if ($course === 'none') { // Don't print any links etc
3018 } else if ($course === 'home') { // special case for site home page - please do not remove
3019 $course = get_site();
3020 $homelink = '<div class="sitelink">'.
3021 '<a title="Moodle" href="http://moodle.org/">'.
3022 '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
3026 $homelink = '<div class="homelink"><a '.$CFG->frametarget
.' href="'.$CFG->wwwroot
.
3027 '/course/view.php?id='.$course->id
.'">'.format_string($course->shortname
).'</a></div>';
3032 $course = get_site(); // Set course as site course by default
3033 $homelink = '<div class="homelink"><a '.$CFG->frametarget
.' href="'.$CFG->wwwroot
.'/">'.get_string('home').'</a></div>';
3037 /// Set up some other navigation links (passed from print_header by ugly hack)
3038 $menu = isset($THEME->menu
) ?
str_replace('navmenu', 'navmenufooter', $THEME->menu
) : '';
3039 $title = isset($THEME->title
) ?
$THEME->title
: '';
3040 $button = isset($THEME->button
) ?
$THEME->button
: '';
3041 $heading = isset($THEME->heading
) ?
$THEME->heading
: '';
3042 $navigation = isset($THEME->navigation
) ?
$THEME->navigation
: '';
3043 $navmenulist = isset($THEME->navmenulist
) ?
$THEME->navmenulist
: '';
3046 /// Set the user link if necessary
3047 if (!$usercourse and is_object($course)) {
3048 $usercourse = $course;
3051 if (!isset($loggedinas)) {
3052 $loggedinas = user_login_string($usercourse, $USER);
3055 if ($loggedinas == $menu) {
3059 /// there should be exactly the same number of open containers as after the header
3060 if ($THEME->open_header_containers
!= open_containers()) {
3061 debugging('Unexpected number of open containers: '.open_containers().', expecting '.$THEME->open_header_containers
, DEBUG_DEVELOPER
);
3064 /// Provide some performance info if required
3065 $performanceinfo = '';
3066 if (defined('MDL_PERF') ||
(!empty($CFG->perfdebug
) and $CFG->perfdebug
> 7)) {
3067 $perf = get_performance_info();
3068 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
3069 error_log("PERF: " . $perf['txt']);
3071 if (defined('MDL_PERFTOFOOT') ||
debugging() ||
$CFG->perfdebug
> 7) {
3072 $performanceinfo = $perf['html'];
3076 /// Include the actual footer file
3079 include($CFG->footer
);
3080 $output = ob_get_contents();
3091 * Returns the name of the current theme
3100 function current_theme() {
3101 global $CFG, $USER, $SESSION, $COURSE, $FULLME;
3103 if (empty($CFG->themeorder
)) {
3104 $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
3106 $themeorder = $CFG->themeorder
;
3109 if (isloggedin() and isset($CFG->mnet_localhost_id
) and $USER->mnethostid
!= $CFG->mnet_localhost_id
) {
3110 require_once($CFG->dirroot
.'/mnet/peer.php');
3111 $mnet_peer = new mnet_peer();
3112 $mnet_peer->set_id($USER->mnethostid
);
3116 foreach ($themeorder as $themetype) {
3118 if (!empty($theme)) continue;
3120 switch ($themetype) {
3121 case 'page': // Page theme is for special page-only themes set by code
3122 if (!empty($CFG->pagetheme
)) {
3123 $theme = $CFG->pagetheme
;
3127 if (!empty($CFG->allowcoursethemes
) and !empty($COURSE->theme
)) {
3128 $theme = $COURSE->theme
;
3132 if (!empty($CFG->allowcategorythemes
)) {
3133 /// Nasty hack to check if we're in a category page
3134 if (stripos($FULLME, 'course/category.php') !== false) {
3137 $theme = current_category_theme($id);
3139 /// Otherwise check if we're in a course that has a category theme set
3140 } else if (!empty($COURSE->category
)) {
3141 $theme = current_category_theme($COURSE->category
);
3146 if (!empty($SESSION->theme
)) {
3147 $theme = $SESSION->theme
;
3151 if (!empty($CFG->allowuserthemes
) and !empty($USER->theme
)) {
3152 if (isloggedin() and $USER->mnethostid
!= $CFG->mnet_localhost_id
&& $mnet_peer->force_theme
== 1 && $mnet_peer->theme
!= '') {
3153 $theme = $mnet_peer->theme
;
3155 $theme = $USER->theme
;
3160 if (isloggedin() and isset($CFG->mnet_localhost_id
) and $USER->mnethostid
!= $CFG->mnet_localhost_id
&& $mnet_peer->force_theme
== 1 && $mnet_peer->theme
!= '') {
3161 $theme = $mnet_peer->theme
;
3163 $theme = $CFG->theme
;
3171 /// A final check in case 'site' was not included in $CFG->themeorder
3172 if (empty($theme)) {
3173 $theme = $CFG->theme
;
3180 * Retrieves the category theme if one exists, otherwise checks the parent categories.
3181 * Recursive function.
3184 * @param integer $categoryid id of the category to check
3185 * @return string theme name
3187 function current_category_theme($categoryid=0) {
3190 /// Use the COURSE global if the categoryid not set
3191 if (empty($categoryid)) {
3192 if (!empty($COURSE->category
)) {
3193 $categoryid = $COURSE->category
;
3199 /// Retrieve the current category
3200 if ($category = get_record('course_categories', 'id', $categoryid)) {
3202 /// Return the category theme if it exists
3203 if (!empty($category->theme
)) {
3204 return $category->theme
;
3206 /// Otherwise try the parent category if one exists
3207 } else if (!empty($category->parent
)) {
3208 return current_category_theme($category->parent
);
3211 /// Return false if we can't find the category record
3218 * This function is called by stylesheets to set up the header
3219 * approriately as well as the current path
3222 * @param int $lastmodified ?
3223 * @param int $lifetime ?
3224 * @param string $thename ?
3226 function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
3228 global $CFG, $THEME;
3230 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
3231 $lastmodified = time();
3233 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
3234 header('Expires: ' . gmdate("D, d M Y H:i:s", time() +
$lifetime) . ' GMT');
3235 header('Cache-Control: max-age='. $lifetime);
3237 header('Content-type: text/css'); // Correct MIME type
3239 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
3241 if (empty($themename)) {
3242 $themename = current_theme(); // So we have something. Normally not needed.
3244 $themename = clean_param($themename, PARAM_SAFEDIR
);
3247 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
3249 include($CFG->themedir
.'/'.$forceconfig.'/'.'config.php');
3252 /// If this is the standard theme calling us, then find out what sheets we need
3254 if ($themename == 'standard') {
3255 if (!isset($THEME->standardsheets
) or $THEME->standardsheets
=== true) { // Use all the sheets we have
3256 $THEME->sheets
= $DEFAULT_SHEET_LIST;
3257 } else if (empty($THEME->standardsheets
)) { // We can stop right now!
3258 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3260 } else { // Use the provided subset only
3261 $THEME->sheets
= $THEME->standardsheets
;
3264 /// If we are a parent theme, then check for parent definitions
3266 } else if (!empty($THEME->parent
) && $themename == $THEME->parent
) {
3267 if (!isset($THEME->parentsheets
) or $THEME->parentsheets
=== true) { // Use all the sheets we have
3268 $THEME->sheets
= $DEFAULT_SHEET_LIST;
3269 } else if (empty($THEME->parentsheets
)) { // We can stop right now!
3270 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3272 } else { // Use the provided subset only
3273 $THEME->sheets
= $THEME->parentsheets
;
3277 /// Work out the last modified date for this theme
3279 foreach ($THEME->sheets
as $sheet) {
3280 if (file_exists($CFG->themedir
.'/'.$themename.'/'.$sheet.'.css')) {
3281 $sheetmodified = filemtime($CFG->themedir
.'/'.$themename.'/'.$sheet.'.css');
3282 if ($sheetmodified > $lastmodified) {
3283 $lastmodified = $sheetmodified;
3289 /// Get a list of all the files we want to include
3292 foreach ($THEME->sheets
as $sheet) {
3293 $files[] = array($CFG->themedir
, $themename.'/'.$sheet.'.css');
3296 if ($themename == 'standard') { // Add any standard styles included in any modules
3297 if (!empty($THEME->modsheets
)) { // Search for styles.php within activity modules
3298 if ($mods = get_list_of_plugins('mod')) {
3299 foreach ($mods as $mod) {
3300 if (file_exists($CFG->dirroot
.'/mod/'.$mod.'/styles.php')) {
3301 $files[] = array($CFG->dirroot
, '/mod/'.$mod.'/styles.php');
3307 if (!empty($THEME->blocksheets
)) { // Search for styles.php within block modules
3308 if ($mods = get_list_of_plugins('blocks')) {
3309 foreach ($mods as $mod) {
3310 if (file_exists($CFG->dirroot
.'/blocks/'.$mod.'/styles.php')) {
3311 $files[] = array($CFG->dirroot
, '/blocks/'.$mod.'/styles.php');
3317 if (!isset($THEME->courseformatsheets
) ||
$THEME->courseformatsheets
) { // Search for styles.php in course formats
3318 if ($mods = get_list_of_plugins('format','',$CFG->dirroot
.'/course')) {
3319 foreach ($mods as $mod) {
3320 if (file_exists($CFG->dirroot
.'/course/format/'.$mod.'/styles.php')) {
3321 $files[] = array($CFG->dirroot
, '/course/format/'.$mod.'/styles.php');
3327 if (!isset($THEME->gradereportsheets
) ||
$THEME->gradereportsheets
) { // Search for styles.php in grade reports
3328 if ($reports = get_list_of_plugins('grade/report')) {
3329 foreach ($reports as $report) {
3330 if (file_exists($CFG->dirroot
.'/grade/report/'.$report.'/styles.php')) {
3331 $files[] = array($CFG->dirroot
, '/grade/report/'.$report.'/styles.php');
3337 if (!empty($THEME->langsheets
)) { // Search for styles.php within the current language
3338 if (file_exists($CFG->dirroot
.'/lang/'.$lang.'/styles.php')) {
3339 $files[] = array($CFG->dirroot
, '/lang/'.$lang.'/styles.php');
3345 /// Produce a list of all the files first
3346 echo '/**************************************'."\n";
3347 echo ' * THEME NAME: '.$themename."\n *\n";
3348 echo ' * Files included in this sheet:'."\n *\n";
3349 foreach ($files as $file) {
3350 echo ' * '.$file[1]."\n";
3352 echo ' **************************************/'."\n\n";
3355 /// check if csscobstants is set
3356 if (!empty($THEME->cssconstants
)) {
3357 require_once("$CFG->libdir/cssconstants.php");
3358 /// Actually collect all the files in order.
3360 foreach ($files as $file) {
3361 $css .= '/***** '.$file[1].' start *****/'."\n\n";
3362 $css .= file_get_contents($file[0].'/'.$file[1]);
3363 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
3365 /// replace css_constants with their values
3366 echo replace_cssconstants($css);
3368 /// Actually output all the files in order.
3369 if (empty($CFG->CSSEdit
) && empty($THEME->CSSEdit
)) {
3370 foreach ($files as $file) {
3371 echo '/***** '.$file[1].' start *****/'."\n\n";
3372 @include_once
($file[0].'/'.$file[1]);
3373 echo '/***** '.$file[1].' end *****/'."\n\n";
3376 foreach ($files as $file) {
3377 echo '/* @group '.$file[1].' */'."\n\n";
3378 if (strstr($file[1], '.css') !== FALSE) {
3379 echo '@import url("'.$CFG->themewww
.'/'.$file[1].'");'."\n\n";
3381 @include_once
($file[0].'/'.$file[1]);
3383 echo '/* @end */'."\n\n";
3389 return $CFG->themewww
.'/'.$themename; // Only to help old themes (1.4 and earlier)
3393 function theme_setup($theme = '', $params=NULL) {
3394 /// Sets up global variables related to themes
3396 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
3398 /// Do not mess with THEME if header already printed - this would break all the extra stuff in global $THEME from print_header()!!
3399 if (defined('HEADER_PRINTED')) {
3403 if (empty($theme)) {
3404 $theme = current_theme();
3407 /// If the theme doesn't exist for some reason then revert to standardwhite
3408 if (!file_exists($CFG->themedir
.'/'. $theme .'/config.php')) {
3409 $CFG->theme
= $theme = 'standardwhite';
3412 /// Load up the theme config
3413 $THEME = NULL; // Just to be sure
3414 include($CFG->themedir
.'/'. $theme .'/config.php'); // Main config for current theme
3416 /// Put together the parameters
3421 if ($theme != $CFG->theme
) {
3422 $params[] = 'forceconfig='.$theme;
3425 /// Force language too if required
3426 if (!empty($THEME->langsheets
)) {
3427 $params[] = 'lang='.current_language();
3431 /// Convert params to string
3433 $paramstring = '?'.implode('&', $params);
3438 /// Set up image paths
3439 if(isset($CFG->smartpix
) && $CFG->smartpix
==1) {
3440 if($CFG->slasharguments
) { // Use this method if possible for better caching
3446 $CFG->pixpath
= $CFG->wwwroot
. '/pix/smartpix.php'.$extra.'/'.$theme;
3447 $CFG->modpixpath
= $CFG->wwwroot
.'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
3448 } else if (empty($THEME->custompix
)) { // Could be set in the above file
3449 $CFG->pixpath
= $CFG->wwwroot
.'/pix';
3450 $CFG->modpixpath
= $CFG->wwwroot
.'/mod';
3452 $CFG->pixpath
= $CFG->themewww
.'/'. $theme .'/pix';
3453 $CFG->modpixpath
= $CFG->themewww
.'/'. $theme .'/pix/mod';
3456 /// Header and footer paths
3457 $CFG->header
= $CFG->themedir
.'/'. $theme .'/header.html';
3458 $CFG->footer
= $CFG->themedir
.'/'. $theme .'/footer.html';
3460 /// Define stylesheet loading order
3461 $CFG->stylesheets
= array();
3462 if ($theme != 'standard') { /// The standard sheet is always loaded first
3463 $CFG->stylesheets
[] = $CFG->themewww
.'/standard/styles.php'.$paramstring;
3465 if (!empty($THEME->parent
)) { /// Parent stylesheets are loaded next
3466 $CFG->stylesheets
[] = $CFG->themewww
.'/'.$THEME->parent
.'/styles.php'.$paramstring;
3468 $CFG->stylesheets
[] = $CFG->themewww
.'/'.$theme.'/styles.php'.$paramstring;
3470 /// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
3471 if (!empty($HTTPSPAGEREQUIRED)) {
3472 $CFG->themewww
= str_replace('http:', 'https:', $CFG->themewww
);
3473 $CFG->pixpath
= str_replace('http:', 'https:', $CFG->pixpath
);
3474 $CFG->modpixpath
= str_replace('http:', 'https:', $CFG->modpixpath
);
3475 foreach ($CFG->stylesheets
as $key => $stylesheet) {
3476 $CFG->stylesheets
[$key] = str_replace('http:', 'https:', $stylesheet);
3480 // RTL support - only for RTL languages, add RTL CSS
3481 if (get_string('thisdirection') == 'rtl') {
3482 $CFG->stylesheets
[] = $CFG->themewww
.'/standard/rtl.css'.$paramstring;
3483 $CFG->stylesheets
[] = $CFG->themewww
.'/'.$theme.'/rtl.css'.$paramstring;
3489 * Returns text to be displayed to the user which reflects their login status
3493 * @param course $course {@link $COURSE} object containing course information
3494 * @param user $user {@link $USER} object containing user information
3497 function user_login_string($course=NULL, $user=NULL) {
3498 global $USER, $CFG, $SITE;
3500 if (empty($user) and !empty($USER->id
)) {
3504 if (empty($course)) {
3508 if (!empty($user->realuser
)) {
3509 if ($realuser = get_record('user', 'id', $user->realuser
)) {
3510 $fullname = fullname($realuser, true);
3511 $realuserinfo = " [<a $CFG->frametarget
3512 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&return=1&sesskey=".sesskey()."\">$fullname</a>] ";
3518 if (empty($CFG->loginhttps
)) {
3519 $wwwroot = $CFG->wwwroot
;
3521 $wwwroot = str_replace('http:','https:',$CFG->wwwroot
);
3524 if (empty($course->id
)) {
3525 // $course->id is not defined during installation
3527 } else if (!empty($user->id
)) {
3528 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
3530 $fullname = fullname($user, true);
3531 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a>";
3532 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid
)) {
3533 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
3535 if (isset($user->username
) && $user->username
== 'guest') {
3536 $loggedinas = $realuserinfo.get_string('loggedinasguest').
3537 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3538 } else if (!empty($user->access
['rsw'][$context->path
])) {
3540 if ($role = get_record('role', 'id', $user->access
['rsw'][$context->path
])) {
3541 $rolename = join("", role_fix_names(array($role->id
=>$role->name
), $context));
3542 $rolename = ': '.format_string($rolename);
3544 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
3545 " (<a $CFG->frametarget
3546 href=\"$CFG->wwwroot/course/view.php?id=$course->id&switchrole=0&sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
3548 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
3549 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
3552 $loggedinas = get_string('loggedinnot', 'moodle').
3553 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3555 return '<div class="logininfo">'.$loggedinas.'</div>';
3559 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
3560 * If not it applies sensible defaults.
3562 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
3563 * search forum block, etc. Important: these are 'silent' in a screen-reader
3564 * (unlike > »), and must be accompanied by text.
3567 function check_theme_arrows() {
3570 if (!isset($THEME->rarrow
) and !isset($THEME->larrow
)) {
3571 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
3572 // Also OK in Win 9x/2K/IE 5.x
3573 $THEME->rarrow
= '►';
3574 $THEME->larrow
= '◄';
3575 if (empty($_SERVER['HTTP_USER_AGENT'])) {
3578 $uagent = $_SERVER['HTTP_USER_AGENT'];
3580 if (false !== strpos($uagent, 'Opera')
3581 ||
false !== strpos($uagent, 'Mac')) {
3582 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
3583 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
3584 $THEME->rarrow
= '▶';
3585 $THEME->larrow
= '◀';
3587 elseif (false !== strpos($uagent, 'Konqueror')) {
3588 $THEME->rarrow
= '→';
3589 $THEME->larrow
= '←';
3591 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
3592 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
3593 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
3594 // To be safe, non-Unicode browsers!
3595 $THEME->rarrow
= '>';
3596 $THEME->larrow
= '<';
3599 /// RTL support - in RTL languages, swap r and l arrows
3600 if (right_to_left()) {
3601 $t = $THEME->rarrow
;
3602 $THEME->rarrow
= $THEME->larrow
;
3603 $THEME->larrow
= $t;
3610 * Return the right arrow with text ('next'), and optionally embedded in a link.
3611 * See function above, check_theme_arrows.
3612 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3613 * @param string $url An optional link to use in a surrounding HTML anchor.
3614 * @param bool $accesshide True if text should be hidden (for screen readers only).
3615 * @param string $addclass Additional class names for the link, or the arrow character.
3616 * @return string HTML string.
3618 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
3620 check_theme_arrows();
3621 $arrowclass = 'arrow ';
3623 $arrowclass .= $addclass;
3625 $arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow
.'</span>';
3628 $htmltext = $text.' ';
3630 $htmltext = get_accesshide($htmltext);
3636 $class =" class=\"$addclass\"";
3638 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
3640 return $htmltext.$arrow;
3644 * Return the left arrow with text ('previous'), and optionally embedded in a link.
3645 * See function above, check_theme_arrows.
3646 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3647 * @param string $url An optional link to use in a surrounding HTML anchor.
3648 * @param bool $accesshide True if text should be hidden (for screen readers only).
3649 * @param string $addclass Additional class names for the link, or the arrow character.
3650 * @return string HTML string.
3652 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
3654 check_theme_arrows();
3655 $arrowclass = 'arrow ';
3657 $arrowclass .= $addclass;
3659 $arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow
.'</span>';
3662 $htmltext = ' '.$text;
3664 $htmltext = get_accesshide($htmltext);
3670 $class =" class=\"$addclass\"";
3672 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
3674 return $arrow.$htmltext;
3678 * Return a HTML element with the class "accesshide", for accessibility.
3679 * Please use cautiously - where possible, text should be visible!
3680 * @param string $text Plain text.
3681 * @param string $elem Lowercase element name, default "span".
3682 * @param string $class Additional classes for the element.
3683 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
3684 * @return string HTML string.
3686 function get_accesshide($text, $elem='span', $class='', $attrs='') {
3687 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
3691 * Return the breadcrumb trail navigation separator.
3692 * @return string HTML string.
3694 function get_separator() {
3695 //Accessibility: the 'hidden' slash is preferred for screen readers.
3696 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
3700 * Prints breadcrumb trail of links, called in theme/-/header.html
3703 * @param mixed $navigation The breadcrumb navigation string to be printed
3704 * @param string $separator OBSOLETE, mostly not used any more. See build_navigation instead.
3705 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
3706 * @return string or null, depending on $return.
3708 function print_navigation ($navigation, $separator=0, $return=false) {
3709 global $CFG, $THEME;
3712 if (0 === $separator) {
3713 $separator = get_separator();
3716 $separator = '<span class="sep">'. $separator .'</span>';
3721 if (is_newnav($navigation)) {
3723 return($navigation['navlinks']);
3725 echo $navigation['navlinks'];
3729 debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER
);
3732 if (!is_array($navigation)) {
3733 $ar = explode('->', $navigation);
3734 $navigation = array();
3736 foreach ($ar as $a) {
3737 if (strpos($a, '</a>') === false) {
3738 $navigation[] = array('title' => $a, 'url' => '');
3740 if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
3741 $navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
3747 if (! $site = get_site()) {
3748 $site = new object();
3749 $site->shortname
= get_string('home');
3752 //Accessibility: breadcrumb links now in a list, » replaced with a 'silent' character.
3753 $output .= get_accesshide(get_string('youarehere','access'), 'h2')."<ul>\n";
3755 $output .= '<li class="first">'."\n".'<a '.$CFG->frametarget
.' onclick="this.target=\''.$CFG->framename
.'\'" href="'
3756 .$CFG->wwwroot
.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))
3757 && !empty($USER->id
) && !empty($CFG->mymoodleredirect
) && !isguest())
3758 ?
'/my' : '') .'/">'. format_string($site->shortname
) ."</a>\n</li>\n";
3761 foreach ($navigation as $navitem) {
3762 $title = trim(strip_tags(format_string($navitem['title'], false)));
3763 $url = $navitem['url'];
3766 $output .= '<li>'."$separator $title</li>\n";
3768 $output .= '<li>'."$separator\n<a ".$CFG->frametarget
.' onclick="this.target=\''.$CFG->framename
.'\'" href="'
3769 .$url.'">'."$title</a>\n</li>\n";
3773 $output .= "</ul>\n";
3784 * This function will build the navigation string to be used by print_header
3787 * It automatically generates the site and course level (if appropriate) links.
3789 * If you pass in a $cm object, the method will also generate the activity (e.g. 'Forums')
3790 * and activityinstances (e.g. 'General Developer Forum') navigation levels.
3792 * If you want to add any further navigation links after the ones this function generates,
3793 * the pass an array of extra link arrays like this:
3795 * array('name' => $linktext1, 'link' => $url1, 'type' => $linktype1),
3796 * array('name' => $linktext2, 'link' => $url2, 'type' => $linktype2)
3798 * The normal case is to just add one further link, for example 'Editing forum' after
3799 * 'General Developer Forum', with no link.
3800 * To do that, you need to pass
3801 * array(array('name' => $linktext, 'link' => '', 'type' => 'title'))
3802 * However, becuase this is a very common case, you can use a shortcut syntax, and just
3803 * pass the string 'Editing forum', instead of an array as $extranavlinks.
3805 * At the moment, the link types only have limited significance. Type 'activity' is
3806 * recognised in order to implement the $CFG->hideactivitytypenavlink feature. Types
3807 * that are known to appear are 'home', 'course', 'activity', 'activityinstance' and 'title'.
3808 * This really needs to be documented better. In the mean time, try to be consistent, it will
3809 * enable people to customise the navigation more in future.
3811 * When passing a $cm object, the fields used are $cm->modname, $cm->name and $cm->course.
3812 * If you get the $cm object using the function get_coursemodule_from_instance or
3813 * get_coursemodule_from_id (as recommended) then this will be done for you automatically.
3814 * If you don't have $cm->modname or $cm->name, this fuction will attempt to find them using
3815 * the $cm->module and $cm->instance fields, but this takes extra database queries, so a
3816 * warning is printed in developer debug mode.
3821 * @param mixed $extranavlinks - Normally an array of arrays, keys: name, link, type. If you
3822 * only want one extra item with no link, you can pass a string instead. If you don't want
3823 * any extra links, pass an empty string.
3824 * @param mixed $cm - optionally the $cm object, if you want this function to generate the
3825 * activity and activityinstance levels of navigation too.
3827 * @return $navigation as an object so it can be differentiated from old style
3828 * navigation strings.
3830 function build_navigation($extranavlinks, $cm = null) {
3831 global $CFG, $COURSE;
3833 if (is_string($extranavlinks)) {
3834 if ($extranavlinks == '') {
3835 $extranavlinks = array();
3837 $extranavlinks = array(array('name' => $extranavlinks, 'link' => '', 'type' => 'title'));
3841 $navlinks = array();
3844 if ($site = get_site()) {
3845 $navlinks[] = array(
3846 'name' => format_string($site->shortname
),
3847 'link' => "$CFG->wwwroot/",
3851 // Course name, if appropriate.
3852 if (isset($COURSE) && $COURSE->id
!= SITEID
) {
3853 $navlinks[] = array(
3854 'name' => format_string($COURSE->shortname
),
3855 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",
3856 'type' => 'course');
3859 // Activity type and instance, if appropriate.
3860 if (is_object($cm)) {
3861 if (!isset($cm->modname
)) {
3862 debugging('The field $cm->modname should be set if you call build_navigation with '.
3863 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3864 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER
);
3865 if (!$cm->modname
= get_field('modules', 'name', 'id', $cm->module
)) {
3866 error('Cannot get the module type in build navigation.');
3869 if (!isset($cm->name
)) {
3870 debugging('The field $cm->name should be set if you call build_navigation with '.
3871 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3872 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER
);
3873 if (!$cm->name
= get_field($cm->modname
, 'name', 'id', $cm->instance
)) {
3874 error('Cannot get the module name in build navigation.');
3877 $navlinks[] = array(
3878 'name' => get_string('modulenameplural', $cm->modname
),
3879 'link' => $CFG->wwwroot
. '/mod/' . $cm->modname
. '/index.php?id=' . $cm->course
,
3880 'type' => 'activity');
3881 $navlinks[] = array(
3882 'name' => format_string($cm->name
),
3883 'link' => $CFG->wwwroot
. '/mod/' . $cm->modname
. '/view.php?id=' . $cm->id
,
3884 'type' => 'activityinstance');
3887 //Merge in extra navigation links
3888 $navlinks = array_merge($navlinks, $extranavlinks);
3890 // Work out whether we should be showing the activity (e.g. Forums) link.
3891 // Note: build_navigation() is called from many places --
3892 // install & upgrade for example -- where we cannot count on the
3893 // roles infrastructure to be defined. Hence the $CFG->rolesactive check.
3894 if (!isset($CFG->hideactivitytypenavlink
)) {
3895 $CFG->hideactivitytypenavlink
= 0;
3897 if ($CFG->hideactivitytypenavlink
== 2) {
3898 $hideactivitylink = true;
3899 } else if ($CFG->hideactivitytypenavlink
== 1 && $CFG->rolesactive
&&
3900 !empty($COURSE->id
) && $COURSE->id
!= SITEID
) {
3901 if (!isset($COURSE->context
)) {
3902 $COURSE->context
= get_context_instance(CONTEXT_COURSE
, $COURSE->id
);
3904 $hideactivitylink = !has_capability('moodle/course:manageactivities', $COURSE->context
);
3906 $hideactivitylink = false;
3909 //Construct an unordered list from $navlinks
3910 //Accessibility: heading hidden from visual browsers by default.
3911 $navigation = get_accesshide(get_string('youarehere','access'), 'h2')." <ul>\n";
3912 $lastindex = count($navlinks) - 1;
3913 $i = -1; // Used to count the times, so we know when we get to the last item.
3915 foreach ($navlinks as $navlink) {
3917 $last = ($i == $lastindex);
3918 if (!is_array($navlink)) {
3921 if (!empty($navlink['type']) && $navlink['type'] == 'activity' && !$last && $hideactivitylink) {
3925 $navigation .= '<li class="first">';
3927 $navigation .= '<li>';
3930 $navigation .= get_separator();
3932 if ((!empty($navlink['link'])) && !$last) {
3933 $navigation .= "<a $CFG->frametarget onclick=\"this.target='$CFG->framename'\" href=\"{$navlink['link']}\">";
3935 $navigation .= "{$navlink['name']}";
3936 if ((!empty($navlink['link'])) && !$last) {
3937 $navigation .= "</a>";
3940 $navigation .= "</li>";
3943 $navigation .= "</ul>";
3945 return(array('newnav' => true, 'navlinks' => $navigation));
3950 * Prints a string in a specified size (retained for backward compatibility)
3952 * @param string $text The text to be displayed
3953 * @param int $size The size to set the font for text display.
3955 function print_headline($text, $size=2, $return=false) {
3956 $output = print_heading($text, '', $size, true);
3965 * Prints text in a format for use in headings.
3967 * @param string $text The text to be displayed
3968 * @param string $align The alignment of the printed paragraph of text
3969 * @param int $size The size to set the font for text display.
3971 function print_heading($text, $align='', $size=2, $class='main', $return=false) {
3973 $align = ' style="text-align:'.$align.';"';
3976 $class = ' class="'.$class.'"';
3978 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
3988 * Centered heading with attached help button (same title text)
3989 * and optional icon attached
3991 * @param string $text The text to be displayed
3992 * @param string $helppage The help page to link to
3993 * @param string $module The module whose help should be linked to
3994 * @param string $icon Image to display if needed
3996 function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
3998 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
3999 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
4010 function print_heading_block($heading, $class='', $return=false) {
4011 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
4012 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
4023 * Print a link to continue on to another page.
4026 * @param string $link The url to create a link to.
4028 function print_continue($link, $return=false) {
4032 // in case we are logging upgrade in admin/index.php stop it
4033 if (function_exists('upgrade_log_finish')) {
4034 upgrade_log_finish();
4040 if (!empty($_SERVER['HTTP_REFERER'])) {
4041 $link = $_SERVER['HTTP_REFERER'];
4042 $link = str_replace('&', '&', $link); // make it valid XHTML
4044 $link = $CFG->wwwroot
.'/';
4049 $linkparts = parse_url(str_replace('&', '&', $link));
4050 if (isset($linkparts['query'])) {
4051 parse_str($linkparts['query'], $options);
4054 $output .= '<div class="continuebutton">';
4056 $output .= print_single_button($link, $options, get_string('continue'), 'get', $CFG->framename
, true);
4057 $output .= '</div>'."\n";
4068 * Print a message in a standard themed box.
4069 * Replaces print_simple_box (see deprecatedlib.php)
4071 * @param string $message, the content of the box
4072 * @param string $classes, space-separated class names.
4073 * @param string $idbase
4074 * @param boolean $return, return as string or just print it
4075 * @return mixed string or void
4077 function print_box($message, $classes='generalbox', $ids='', $return=false) {
4079 $output = print_box_start($classes, $ids, true);
4080 $output .= stripslashes_safe($message);
4081 $output .= print_box_end(true);
4091 * Starts a box using divs
4092 * Replaces print_simple_box_start (see deprecatedlib.php)
4094 * @param string $classes, space-separated class names.
4095 * @param string $idbase
4096 * @param boolean $return, return as string or just print it
4097 * @return mixed string or void
4099 function print_box_start($classes='generalbox', $ids='', $return=false) {
4102 if (strpos($classes, 'clearfix') !== false) {
4104 $classes = trim(str_replace('clearfix', '', $classes));
4109 if (!empty($THEME->customcorners
)) {
4110 $classes .= ' ccbox box';
4115 return print_container_start($clearfix, $classes, $ids, $return);
4119 * Simple function to end a box (see above)
4120 * Replaces print_simple_box_end (see deprecatedlib.php)
4122 * @param boolean $return, return as string or just print it
4124 function print_box_end($return=false) {
4125 return print_container_end($return);
4129 * Print a message in a standard themed container.
4131 * @param string $message, the content of the container
4132 * @param boolean $clearfix clear both sides
4133 * @param string $classes, space-separated class names.
4134 * @param string $idbase
4135 * @param boolean $return, return as string or just print it
4136 * @return string or void
4138 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
4140 $output = print_container_start($clearfix, $classes, $idbase, true);
4141 $output .= stripslashes_safe($message);
4142 $output .= print_container_end(true);
4152 * Starts a container using divs
4154 * @param boolean $clearfix clear both sides
4155 * @param string $classes, space-separated class names.
4156 * @param string $idbase
4157 * @param boolean $return, return as string or just print it
4158 * @return mixed string or void
4160 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
4163 if (!isset($THEME->open_containers
)) {
4164 $THEME->open_containers
= array();
4166 $THEME->open_containers
[] = $idbase;
4169 if (!empty($THEME->customcorners
)) {
4170 $output = _print_custom_corners_start($clearfix, $classes, $idbase);
4173 $id = ' id="'.$idbase.'"';
4178 $clearfix = ' clearfix';
4182 if ($classes or $clearfix) {
4183 $class = ' class="'.$classes.$clearfix.'"';
4187 $output = '<div'.$id.$class.'>';
4198 * Simple function to end a container (see above)
4199 * @param boolean $return, return as string or just print it
4200 * @return mixed string or void
4202 function print_container_end($return=false) {
4205 if (empty($THEME->open_containers
)) {
4206 debugging('Incorrect request to end container - no more open containers.', DEBUG_DEVELOPER
);
4209 $idbase = array_pop($THEME->open_containers
);
4212 if (!empty($THEME->customcorners
)) {
4213 $output = _print_custom_corners_end($idbase);
4226 * Returns number of currently open containers
4227 * @return int number of open containers
4229 function open_containers() {
4232 if (!isset($THEME->open_containers
)) {
4233 $THEME->open_containers
= array();
4236 return count($THEME->open_containers
);
4240 * Force closing of open containers
4241 * @param boolean $return, return as string or just print it
4242 * @param int $keep number of containers to be kept open - usually theme or page containers
4243 * @return mixed string or void
4245 function print_container_end_all($return=false, $keep=0) {
4247 while (open_containers() > $keep) {
4248 $output .= print_container_end($return);
4259 * Internal function - do not use directly!
4260 * Starting part of the surrounding divs for custom corners
4262 * @param boolean $clearfix, add CLASS "clearfix" to the inner div against collapsing
4263 * @param string $classes
4264 * @param mixed $idbase, optionally, define one idbase to be added to all the elements in the corners
4267 function _print_custom_corners_start($clearfix=false, $classes='', $idbase='') {
4268 /// Analise if we want ids for the custom corner elements
4276 $id = 'id="'.$idbase.'" ';
4277 $idbt = 'id="'.$idbase.'-bt" ';
4278 $idi1 = 'id="'.$idbase.'-i1" ';
4279 $idi2 = 'id="'.$idbase.'-i2" ';
4280 $idi3 = 'id="'.$idbase.'-i3" ';
4283 /// Calculate current level
4284 $level = open_containers();
4287 $output = '<div '.$id.'class="wrap wraplevel'.$level.' '.$classes.'">'."\n";
4288 $output .= '<div '.$idbt.'class="bt"><div> </div></div>';
4290 $output .= '<div '.$idi1.'class="i1"><div '.$idi2.'class="i2">';
4291 $output .= (!empty($clearfix)) ?
'<div '.$idi3.'class="i3 clearfix">' : '<div '.$idi3.'class="i3">';
4298 * Internal function - do not use directly!
4299 * Ending part of the surrounding divs for custom corners
4300 * @param string $idbase
4303 function _print_custom_corners_end($idbase) {
4304 /// Analise if we want ids for the custom corner elements
4308 $idbb = 'id="' . $idbase . '-bb" ';
4312 $output = '</div></div></div>';
4314 $output .= '<div '.$idbb.'class="bb"><div> </div></div>'."\n";
4315 $output .= '</div>';
4322 * Print a self contained form with a single submit button.
4324 * @param string $link used as the action attribute on the form, so the URL that will be hit if the button is clicked.
4325 * @param array $options these become hidden form fields, so these options get passed to the script at $link.
4326 * @param string $label the caption that appears on the button.
4327 * @param string $method HTTP method used on the request of the button is clicked. 'get' or 'post'.
4328 * @param string $target no longer used.
4329 * @param boolean $return if false, output the form directly, otherwise return the HTML as a string.
4330 * @param string $tooltip a tooltip to add to the button as a title attribute.
4331 * @param boolean $disabled if true, the button will be disabled.
4332 * @param string $jsconfirmmessage if not empty then display a confirm dialogue with this string as the question.
4333 * @return string / nothing depending on the $return paramter.
4335 function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='', $disabled = false, $jsconfirmmessage='') {
4337 $link = str_replace('"', '"', $link); //basic XSS protection
4338 $output .= '<div class="singlebutton">';
4339 // taking target out, will need to add later target="'.$target.'"
4340 $output .= '<form action="'. $link .'" method="'. $method .'">';
4343 foreach ($options as $name => $value) {
4344 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
4348 $tooltip = 'title="' . s($tooltip) . '"';
4353 $disabled = 'disabled="disabled"';
4357 if ($jsconfirmmessage){
4358 $jsconfirmmessage = addslashes_js($jsconfirmmessage);
4359 $jsconfirmmessage = 'onclick="return confirm(\''. $jsconfirmmessage .'\');" ';
4361 $output .= '<input type="submit" value="'. s($label) ."\" $tooltip $disabled $jsconfirmmessage/></div></form></div>";
4372 * Print a spacer image with the option of including a line break.
4374 * @param int $height ?
4375 * @param int $width ?
4376 * @param boolean $br ?
4377 * @todo Finish documenting this function
4379 function print_spacer($height=1, $width=1, $br=true, $return=false) {
4383 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot
.'/pix/spacer.gif" alt="" />';
4385 $output .= '<br />'."\n";
4396 * Given the path to a picture file in a course, or a URL,
4397 * this function includes the picture in the page.
4399 * @param string $path ?
4400 * @param int $courseid ?
4401 * @param int $height ?
4402 * @param int $width ?
4403 * @param string $link ?
4404 * @todo Finish documenting this function
4406 function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
4411 $height = 'height="'. $height .'"';
4414 $width = 'width="'. $width .'"';
4417 $output .= '<a href="'. $link .'">';
4419 if (substr(strtolower($path), 0, 7) == 'http://') {
4420 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
4422 } else if ($courseid) {
4423 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
4424 require_once($CFG->libdir
.'/filelib.php');
4425 $output .= get_file_url("$courseid/$path");
4428 $output .= 'Error: must pass URL or course';
4442 * Print the specified user's avatar.
4444 * @param mixed $user Should be a $user object with at least fields id, picture, imagealt, firstname, lastname
4445 * If any of these are missing, or if a userid is passed, the the database is queried. Avoid this
4446 * if at all possible, particularly for reports. It is very bad for performance.
4447 * @param int $courseid The course id. Used when constructing the link to the user's profile.
4448 * @param boolean $picture The picture to print. By default (or if NULL is passed) $user->picture is used.
4449 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
4450 * @param boolean $return If false print picture to current page, otherwise return the output as string
4451 * @param boolean $link enclose printed image in a link the user's profile (default true).
4452 * @param string $target link target attribute. Makes the profile open in a popup window.
4453 * @param boolean $alttext add non-blank alt-text to the image. (Default true, set to false for purely
4454 * decorative images, or where the username will be printed anyway.)
4455 * @return string or nothing, depending on $return.
4457 function print_user_picture($user, $courseid, $picture=NULL, $size=0, $return=false, $link=true, $target='', $alttext=true) {
4461 // only touch the DB if we are missing data...
4462 if (is_object($user)) {
4463 // Note - both picture and imagealt _can_ be empty
4464 // what we are trying to see here is if they have been fetched
4465 // from the DB. We should use isset() _except_ that some installs
4466 // have those fields as nullable, and isset() will return false
4467 // on null. The only safe thing is to ask array_key_exists()
4468 // which works on objects. property_exists() isn't quite
4469 // what we want here...
4470 if (! (array_key_exists('picture', $user)
4471 && ($alttext && array_key_exists('imagealt', $user)
4472 ||
(isset($user->firstname
) && isset($user->lastname
)))) ) {
4478 // we need firstname, lastname, imagealt, can't escape...
4481 $userobj = new StdClass
; // fake it to save DB traffic
4482 $userobj->id
= $user;
4483 $userobj->picture
= $picture;
4484 $user = clone($userobj);
4489 $user = get_record('user','id',$user, '', '', '', '', 'id,firstname,lastname,imagealt');
4493 $url = '/user/view.php?id='. $user->id
.'&course='. $courseid ;
4495 $target='onclick="return openpopup(\''.$url.'\');"';
4497 $output = '<a '.$target.' href="'. $CFG->wwwroot
. $url .'">';
4504 } else if ($size === true or $size == 1) {
4507 } else if ($size >= 50) {
4512 $class = "userpicture";
4514 if (is_null($picture) and !empty($user->picture
)) {
4515 $picture = $user->picture
;
4518 if ($picture) { // Print custom user picture
4519 require_once($CFG->libdir
.'/filelib.php');
4520 $src = get_file_url($user->id
.'/'.$file.'.jpg', null, 'user');
4521 } else { // Print default user pictures (use theme version if available)
4522 $class .= " defaultuserpic";
4523 $src = "$CFG->pixpath/u/$file.png";
4527 if (!empty($user->imagealt
)) {
4528 $imagealt = $user->imagealt
;
4530 $imagealt = get_string('pictureof','',fullname($user));
4534 $output .= "<img class=\"$class\" src=\"$src\" height=\"$size\" width=\"$size\" alt=\"".s($imagealt).'" />';
4547 * Prints a summary of a user in a nice little box.
4551 * @param user $user A {@link $USER} object representing a user
4552 * @param course $course A {@link $COURSE} object representing a course
4554 function print_user($user, $course, $messageselect=false, $return=false) {
4564 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
4565 if (isset($user->context
->id
)) {
4566 $usercontext = $user->context
;
4568 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
);
4571 if (empty($string)) { // Cache all the strings for the rest of the page
4573 $string->email
= get_string('email');
4574 $string->city
= get_string('city');
4575 $string->lastaccess
= get_string('lastaccess');
4576 $string->activity
= get_string('activity');
4577 $string->unenrol
= get_string('unenrol');
4578 $string->loginas
= get_string('loginas');
4579 $string->fullprofile
= get_string('fullprofile');
4580 $string->role
= get_string('role');
4581 $string->name
= get_string('name');
4582 $string->never
= get_string('never');
4584 $datestring->day
= get_string('day');
4585 $datestring->days
= get_string('days');
4586 $datestring->hour
= get_string('hour');
4587 $datestring->hours
= get_string('hours');
4588 $datestring->min
= get_string('min');
4589 $datestring->mins
= get_string('mins');
4590 $datestring->sec
= get_string('sec');
4591 $datestring->secs
= get_string('secs');
4592 $datestring->year
= get_string('year');
4593 $datestring->years
= get_string('years');
4595 $countries = get_list_of_countries();
4598 /// Get the hidden field list
4599 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
4600 $hiddenfields = array();
4602 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
4605 $output .= '<table class="userinfobox">';
4607 $output .= '<td class="left side">';
4608 $output .= print_user_picture($user, $course->id
, $user->picture
, true, true);
4610 $output .= '<td class="content">';
4611 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
4612 $output .= '<div class="info">';
4613 if (!empty($user->role
) and ($user->role
<> $course->teacher
)) {
4614 $output .= $string->role
.': '. $user->role
.'<br />';
4616 if ($user->maildisplay
== 1 or ($user->maildisplay
== 2 and ($course->id
!= SITEID
) and !isguest()) or
4617 has_capability('moodle/course:viewhiddenuserfields', $context)) {
4618 $output .= $string->email
.': <a href="mailto:'. $user->email
.'">'. $user->email
.'</a><br />';
4620 if (($user->city
or $user->country
) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
4621 $output .= $string->city
.': ';
4622 if ($user->city
&& !isset($hiddenfields['city'])) {
4623 $output .= $user->city
;
4625 if (!empty($countries[$user->country
]) && !isset($hiddenfields['country'])) {
4626 if ($user->city
&& !isset($hiddenfields['city'])) {
4629 $output .= $countries[$user->country
];
4631 $output .= '<br />';
4634 if (!isset($hiddenfields['lastaccess'])) {
4635 if ($user->lastaccess
) {
4636 $output .= $string->lastaccess
.': '. userdate($user->lastaccess
);
4637 $output .= ' ('. format_time(time() - $user->lastaccess
, $datestring) .')';
4639 $output .= $string->lastaccess
.': '. $string->never
;
4642 $output .= '</div></td><td class="links">';
4644 if ($CFG->bloglevel
> 0) {
4645 $output .= '<a href="'.$CFG->wwwroot
.'/blog/index.php?userid='.$user->id
.'">'.get_string('blogs','blog').'</a><br />';
4648 if (!empty($CFG->enablenotes
) and (has_capability('moodle/notes:manage', $context) ||
has_capability('moodle/notes:view', $context))) {
4649 $output .= '<a href="'.$CFG->wwwroot
.'/notes/index.php?course=' . $course->id
. '&user='.$user->id
.'">'.get_string('notes','notes').'</a><br />';
4652 if (has_capability('moodle/site:viewreports', $context) or has_capability('moodle/user:viewuseractivitiesreport', $usercontext)) {
4653 $output .= '<a href="'. $CFG->wwwroot
.'/course/user.php?id='. $course->id
.'&user='. $user->id
.'">'. $string->activity
.'</a><br />';
4655 if (has_capability('moodle/role:assign', $context) and get_user_roles($context, $user->id
, false)) { // I can unassing and user has some role
4656 $output .= '<a href="'. $CFG->wwwroot
.'/course/unenrol.php?id='. $course->id
.'&user='. $user->id
.'">'. $string->unenrol
.'</a><br />';
4658 if ($USER->id
!= $user->id
&& empty($USER->realuser
) && has_capability('moodle/user:loginas', $context) &&
4659 ! has_capability('moodle/site:doanything', $context, $user->id
, false)) {
4660 $output .= '<a href="'. $CFG->wwwroot
.'/course/loginas.php?id='. $course->id
.'&user='. $user->id
.'&sesskey='. sesskey() .'">'. $string->loginas
.'</a><br />';
4662 $output .= '<a href="'. $CFG->wwwroot
.'/user/view.php?id='. $user->id
.'&course='. $course->id
.'">'. $string->fullprofile
.'...</a>';
4664 if (!empty($messageselect)) {
4665 $output .= '<br /><input type="checkbox" name="user'.$user->id
.'" /> ';
4668 $output .= '</td></tr></table>';
4678 * Print a specified group's avatar.
4680 * @param group $group A single {@link group} object OR array of groups.
4681 * @param int $courseid The course ID.
4682 * @param boolean $large Default small picture, or large.
4683 * @param boolean $return If false print picture, otherwise return the output as string
4684 * @param boolean $link Enclose image in a link to view specified course?
4686 * @todo Finish documenting this function
4688 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
4691 if (is_array($group)) {
4693 foreach($group as $g) {
4694 $output .= print_group_picture($g, $courseid, $large, true, $link);
4704 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
4706 // If there is no picture, do nothing
4707 if (!$group->picture
) {
4711 // If picture is hidden, only show to those with course:managegroups
4712 if ($group->hidepicture
and !has_capability('moodle/course:managegroups', $context)) {
4716 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4717 $output = '<a href="'. $CFG->wwwroot
.'/user/index.php?id='. $courseid .'&group='. $group->id
.'">';
4727 // Print custom group picture
4728 require_once($CFG->libdir
.'/filelib.php');
4729 $grouppictureurl = get_file_url($group->id
.'/'.$file.'.jpg', null, 'usergroup');
4730 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
4731 ' alt="'.s(get_string('group').' '.$group->name
).'" title="'.s($group->name
).'"/>';
4733 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4745 * Print a png image.
4747 * @param string $url ?
4748 * @param int $sizex ?
4749 * @param int $sizey ?
4750 * @param boolean $return ?
4751 * @param string $parameters ?
4752 * @todo Finish documenting this function
4754 function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
4758 if (!isset($recentIE)) {
4759 $recentIE = check_browser_version('MSIE', '5.0');
4762 if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
4763 $output .= '<img src="'. $CFG->pixpath
.'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
4764 ' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
4765 ' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
4766 "'$url', sizingMethod='scale') ".
4767 ' '. $parameters .' />';
4769 $output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
4780 * Print a nicely formatted table.
4782 * @param array $table is an object with several properties.
4784 * <li>$table->head - An array of heading names.
4785 * <li>$table->align - An array of column alignments
4786 * <li>$table->size - An array of column sizes
4787 * <li>$table->wrap - An array of "nowrap"s or nothing
4788 * <li>$table->data[] - An array of arrays containing the data.
4789 * <li>$table->width - A percentage of the page
4790 * <li>$table->tablealign - Align the whole table
4791 * <li>$table->cellpadding - Padding on each cell
4792 * <li>$table->cellspacing - Spacing between cells
4793 * <li>$table->class - class attribute to put on the table
4794 * <li>$table->id - id attribute to put on the table.
4795 * <li>$table->rowclass[] - classes to add to particular rows.
4796 * <li>$table->summary - Description of the contents for screen readers.
4798 * @param bool $return whether to return an output string or echo now
4799 * @return boolean or $string
4800 * @todo Finish documenting this function
4802 function print_table($table, $return=false) {
4805 if (isset($table->align
)) {
4806 foreach ($table->align
as $key => $aa) {
4808 $align[$key] = ' text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
4814 if (isset($table->size
)) {
4815 foreach ($table->size
as $key => $ss) {
4817 $size[$key] = ' width:'. $ss .';';
4823 if (isset($table->wrap
)) {
4824 foreach ($table->wrap
as $key => $ww) {
4826 $wrap[$key] = ' white-space:nowrap;';
4833 if (empty($table->width
)) {
4834 $table->width
= '80%';
4837 if (empty($table->tablealign
)) {
4838 $table->tablealign
= 'center';
4841 if (!isset($table->cellpadding
)) {
4842 $table->cellpadding
= '5';
4845 if (!isset($table->cellspacing
)) {
4846 $table->cellspacing
= '1';
4849 if (empty($table->class)) {
4850 $table->class = 'generaltable';
4853 $tableid = empty($table->id
) ?
'' : 'id="'.$table->id
.'"';
4855 $output .= '<table width="'.$table->width
.'" ';
4856 if (!empty($table->summary
)) {
4857 $output .= " summary=\"$table->summary\"";
4859 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
4863 if (!empty($table->head
)) {
4864 $countcols = count($table->head
);
4866 $keys=array_keys($table->head
);
4867 $lastkey = end($keys);
4868 foreach ($table->head
as $key => $heading) {
4870 if (!isset($size[$key])) {
4873 if (!isset($align[$key])) {
4876 if ($key == $lastkey) {
4877 $extraclass = ' lastcol';
4882 $output .= '<th style="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.$extraclass.'" scope="col">'. $heading .'</th>';
4884 $output .= '</tr>'."\n";
4887 if (!empty($table->data
)) {
4889 $keys=array_keys($table->data
);
4890 $lastrowkey = end($keys);
4891 foreach ($table->data
as $key => $row) {
4892 $oddeven = $oddeven ?
0 : 1;
4893 if (!isset($table->rowclass
[$key])) {
4894 $table->rowclass
[$key] = '';
4896 if ($key == $lastrowkey) {
4897 $table->rowclass
[$key] .= ' lastrow';
4899 $output .= '<tr class="r'.$oddeven.' '.$table->rowclass
[$key].'">'."\n";
4900 if ($row == 'hr' and $countcols) {
4901 $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
4902 } else { /// it's a normal row of data
4903 $keys2=array_keys($row);
4904 $lastkey = end($keys2);
4905 foreach ($row as $key => $item) {
4906 if (!isset($size[$key])) {
4909 if (!isset($align[$key])) {
4912 if (!isset($wrap[$key])) {
4915 if ($key == $lastkey) {
4916 $extraclass = ' lastcol';
4920 $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.$extraclass.'">'. $item .'</td>';
4923 $output .= '</tr>'."\n";
4926 $output .= '</table>'."\n";
4936 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
4937 static $strftimerecent = null;
4940 if (is_null($viewfullnames)) {
4941 $context = get_context_instance(CONTEXT_SYSTEM
);
4942 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
4945 if (is_null($strftimerecent)) {
4946 $strftimerecent = get_string('strftimerecent');
4949 $output .= '<div class="head">';
4950 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
4951 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
4952 $output .= '</div>';
4953 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
4964 * Prints a basic textarea field.
4967 * @param boolean $usehtmleditor ?
4968 * @param int $rows ?
4969 * @param int $cols ?
4970 * @param null $width <b>Legacy field no longer used!</b> Set to zero to get control over mincols
4971 * @param null $height <b>Legacy field no longer used!</b> Set to zero to get control over minrows
4972 * @param string $name ?
4973 * @param string $value ?
4974 * @param int $courseid ?
4975 * @todo Finish documenting this function
4977 function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $courseid=0, $return=false, $id='') {
4978 /// $width and height are legacy fields and no longer used as pixels like they used to be.
4979 /// However, you can set them to zero to override the mincols and minrows values below.
4981 global $CFG, $COURSE, $HTTPSPAGEREQUIRED;
4982 static $scriptcount = 0; // For loading the htmlarea script only once.
4989 $id = 'edit-'.$name;
4992 if ( empty($CFG->editorsrc
) ) { // for backward compatibility.
4993 if (empty($courseid)) {
4994 $courseid = $COURSE->id
;
4997 if ($usehtmleditor) {
4998 if (!empty($courseid) and has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE
, $courseid))) {
4999 $httpsrequired = empty($HTTPSPAGEREQUIRED) ?
'' : '&httpsrequired=1';
5000 // needed for course file area browsing in image insert plugin
5001 $str .= ($scriptcount < 1) ?
'<script type="text/javascript" src="'.
5002 $CFG->httpswwwroot
.'/lib/editor/htmlarea/htmlarea.php?id='.$courseid.$httpsrequired.'"></script>'."\n" : '';
5004 $httpsrequired = empty($HTTPSPAGEREQUIRED) ?
'' : '?httpsrequired=1';
5005 $str .= ($scriptcount < 1) ?
'<script type="text/javascript" src="'.
5006 $CFG->httpswwwroot
.'/lib/editor/htmlarea/htmlarea.php'.$httpsrequired.'"></script>'."\n" : '';
5009 $str .= ($scriptcount < 1) ?
'<script type="text/javascript" src="'.
5010 $CFG->httpswwwroot
.'/lib/editor/htmlarea/lang/en.php?id='.$courseid.'"></script>'."\n" : '';
5013 if ($height) { // Usually with legacy calls
5014 if ($rows < $minrows) {
5018 if ($width) { // Usually with legacy calls
5019 if ($cols < $mincols) {
5025 $str .= '<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">';
5026 if ($usehtmleditor) {
5027 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
5031 $str .= '</textarea>'."\n";
5033 if ($usehtmleditor) {
5034 // Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
5035 $str .= '<script type="text/javascript">
5037 document.write(\''.addslashes_js(editorshortcutshelpbutton()).'\');
5049 * Sets up the HTML editor on textareas in the current page.
5050 * If a field name is provided, then it will only be
5051 * applied to that field - otherwise it will be used
5052 * on every textarea in the page.
5054 * In most cases no arguments need to be supplied
5056 * @param string $name Form element to replace with HTMl editor by name
5058 function use_html_editor($name='', $editorhidebuttons='', $id='') {
5061 $editor = 'editor_'.md5($name); //name might contain illegal characters
5063 $id = 'edit-'.$name;
5065 echo "\n".'<script type="text/javascript" defer="defer">'."\n";
5066 echo '//<![CDATA['."\n\n"; // Extra \n is to fix odd wiki problem, MDL-8185
5067 echo "$editor = new HTMLArea('$id');\n";
5068 echo "var config = $editor.config;\n";
5070 echo print_editor_config($editorhidebuttons);
5072 if (empty($THEME->htmleditorpostprocess
)) {
5074 echo "\nHTMLArea.replaceAll($editor.config);\n";
5076 echo "\n$editor.generate();\n";
5080 echo "\nvar HTML_name = '';";
5082 echo "\nvar HTML_name = \"$name;\"";
5084 echo "\nvar HTML_editor = $editor;";
5087 echo '</script>'."\n";
5090 function print_editor_config($editorhidebuttons='', $return=false) {
5093 $str = "config.pageStyle = \"body {";
5095 if (!(empty($CFG->editorbackgroundcolor
))) {
5096 $str .= " background-color: $CFG->editorbackgroundcolor;";
5099 if (!(empty($CFG->editorfontfamily
))) {
5100 $str .= " font-family: $CFG->editorfontfamily;";
5103 if (!(empty($CFG->editorfontsize
))) {
5104 $str .= " font-size: $CFG->editorfontsize;";
5108 $str .= "config.killWordOnPaste = ";
5109 $str .= (empty($CFG->editorkillword
)) ?
"false":"true";
5111 $str .= 'config.fontname = {'."\n";
5113 $fontlist = isset($CFG->editorfontlist
) ?
explode(';', $CFG->editorfontlist
) : array();
5114 $i = 1; // Counter is used to get rid of the last comma.
5116 foreach ($fontlist as $fontline) {
5117 if (!empty($fontline)) {
5121 list($fontkey, $fontvalue) = split(':', $fontline);
5122 $str .= '"'. $fontkey ."\":\t'". $fontvalue ."'";
5129 if (!empty($editorhidebuttons)) {
5130 $str .= "\nconfig.hideSomeButtons(\" ". $editorhidebuttons ." \");\n";
5131 } else if (!empty($CFG->editorhidebuttons
)) {
5132 $str .= "\nconfig.hideSomeButtons(\" ". $CFG->editorhidebuttons
." \");\n";
5135 if (!empty($CFG->editorspelling
) && !empty($CFG->aspellpath
)) {
5136 $str .= print_speller_code($CFG->htmleditor
, true);
5146 * Returns a turn edit on/off button for course in a self contained form.
5147 * Used to be an icon, but it's now a simple form button
5149 * Note that the caller is responsible for capchecks.
5153 * @param int $courseid The course to update by id as found in 'course' table
5156 function update_course_icon($courseid) {
5159 if (!empty($USER->editing
)) {
5160 $string = get_string('turneditingoff');
5163 $string = get_string('turneditingon');
5167 return '<form '.$CFG->frametarget
.' method="get" action="'.$CFG->wwwroot
.'/course/view.php">'.
5169 '<input type="hidden" name="id" value="'.$courseid.'" />'.
5170 '<input type="hidden" name="edit" value="'.$edit.'" />'.
5171 '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
5172 '<input type="submit" value="'.$string.'" />'.
5177 * Returns a little popup menu for switching roles
5181 * @param int $courseid The course to update by id as found in 'course' table
5184 function switchroles_form($courseid) {
5189 if (!$context = get_context_instance(CONTEXT_COURSE
, $courseid)) {
5193 if (!empty($USER->access
['rsw'][$context->path
])){ // Just a button to return to normal
5195 $options['id'] = $courseid;
5196 $options['sesskey'] = sesskey();
5197 $options['switchrole'] = 0;
5199 return print_single_button($CFG->wwwroot
.'/course/view.php', $options,
5200 get_string('switchrolereturn'), 'post', '_self', true);
5203 if (has_capability('moodle/role:switchroles', $context)) {
5204 if (!$roles = get_assignable_roles_for_switchrole($context)) {
5205 return ''; // Nothing to show!
5207 // unset default user role - it would not work
5208 unset($roles[$CFG->guestroleid
]);
5209 return popup_form($CFG->wwwroot
.'/course/view.php?id='.$courseid.'&sesskey='.sesskey().'&switchrole=',
5210 $roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
5218 * Returns a turn edit on/off button for course in a self contained form.
5219 * Used to be an icon, but it's now a simple form button
5223 * @param int $courseid The course to update by id as found in 'course' table
5226 function update_mymoodle_icon() {
5230 if (!empty($USER->editing
)) {
5231 $string = get_string('updatemymoodleoff');
5234 $string = get_string('updatemymoodleon');
5238 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
5240 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5241 "<input type=\"submit\" value=\"$string\" /></div></form>";
5245 * Returns a turn edit on/off button for tag in a self contained form.
5251 function update_tag_button($tagid) {
5255 if (!empty($USER->editing
)) {
5256 $string = get_string('turneditingoff');
5259 $string = get_string('turneditingon');
5263 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/tag/index.php\">".
5265 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5266 "<input type=\"hidden\" name=\"id\" value=\"$tagid\" />".
5267 "<input type=\"submit\" value=\"$string\" /></div></form>";
5271 * Prints the editing button on a module "view" page
5274 * @param type description
5275 * @todo Finish documenting this function
5277 function update_module_button($moduleid, $courseid, $string) {
5280 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE
, $moduleid))) {
5281 $string = get_string('updatethis', '', $string);
5283 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
5285 "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
5286 "<input type=\"hidden\" name=\"return\" value=\"true\" />".
5287 "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
5288 "<input type=\"submit\" value=\"$string\" /></div></form>";
5295 * Prints the editing button on search results listing
5296 * For bulk move courses to another category
5299 function update_categories_search_button($search,$page,$perpage) {
5302 // not sure if this capability is the best here
5303 if (has_capability('moodle/category:manage', get_context_instance(CONTEXT_SYSTEM
))) {
5304 if (!empty($USER->categoryediting
)) {
5305 $string = get_string("turneditingoff");
5309 $string = get_string("turneditingon");
5313 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
5315 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5316 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5317 "<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
5318 "<input type=\"hidden\" name=\"page\" value=\"$page\" />".
5319 "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
5320 "<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
5325 * Given a course and a (current) coursemodule
5326 * This function returns a small popup menu with all the
5327 * course activity modules in it, as a navigation menu
5328 * The data is taken from the serialised array stored in
5331 * @param course $course A {@link $COURSE} object.
5332 * @param course $cm A {@link $COURSE} object.
5333 * @param string $targetwindow ?
5335 * @todo Finish documenting this function
5337 function navmenu($course, $cm=NULL, $targetwindow='self') {
5339 global $CFG, $THEME, $USER;
5341 if (empty($THEME->navmenuwidth
)) {
5344 $width = $THEME->navmenuwidth
;
5351 if ($course->format
== 'weeks') {
5352 $strsection = get_string('week');
5354 $strsection = get_string('topic');
5356 $strjumpto = get_string('jumpto');
5358 $modinfo = get_fast_modinfo($course);
5359 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
5364 $previousmod = NULL;
5371 $menustyle = array();
5373 $sections = get_records('course_sections','course',$course->id
,'section','section,visible,summary');
5375 if (!empty($THEME->makenavmenulist
)) { /// A hack to produce an XHTML navmenu list for use in themes
5376 $THEME->navmenulist
= navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
5379 foreach ($modinfo->cms
as $mod) {
5380 if ($mod->modname
== 'label') {
5384 if ($mod->sectionnum
> $course->numsections
) { /// Don't show excess hidden sections
5388 if (!$mod->uservisible
) { // do not icnlude empty sections at all
5392 if ($mod->sectionnum
> 0 and $section != $mod->sectionnum
) {
5393 $thissection = $sections[$mod->sectionnum
];
5395 if ($thissection->visible
or !$course->hiddensections
or
5396 has_capability('moodle/course:viewhiddensections', $context)) {
5397 $thissection->summary
= strip_tags(format_string($thissection->summary
,true));
5398 if ($course->format
== 'weeks' or empty($thissection->summary
)) {
5399 $menu[] = '--'.$strsection ." ". $mod->sectionnum
;
5401 if (strlen($thissection->summary
) < ($width-3)) {
5402 $menu[] = '--'.$thissection->summary
;
5404 $menu[] = '--'.substr($thissection->summary
, 0, $width).'...';
5407 $section = $mod->sectionnum
;
5409 // no activities from this hidden section shown
5414 $url = $mod->modname
.'/view.php?id='. $mod->id
;
5415 if ($flag) { // the current mod is the "next" mod
5419 $localname = $mod->name
;
5420 if ($cm == $mod->id
) {
5423 $backmod = $previousmod;
5424 $flag = true; // set flag so we know to use next mod for "next"
5425 $localname = $strjumpto;
5428 $localname = strip_tags(format_string($localname,true));
5429 $tl=textlib_get_instance();
5430 if ($tl->strlen($localname) > ($width+
5)) {
5431 $localname = $tl->substr($localname, 0, $width).'...';
5433 if (!$mod->visible
) {
5434 $localname = '('.$localname.')';
5437 $menu[$url] = $localname;
5438 if (empty($THEME->navmenuiconshide
)) {
5439 $menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath
.'/'.$mod->modname
.'/icon.gif);"'; // Unfortunately necessary to do this here
5441 $previousmod = $mod;
5443 //Accessibility: added Alt text, replaced > < with 'silent' character and 'accesshide' text.
5445 if ($selectmod and has_capability('coursereport/log:view', $context)) {
5446 $logstext = get_string('alllogs');
5447 $logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
5448 $CFG->frametarget
.' onclick="this.target=\''.$CFG->framename
.'\';"'.' href="'.
5449 $CFG->wwwroot
.'/course/report/log/index.php?chooselog=1&user=0&date=0&id='.
5450 $course->id
.'&modid='.$selectmod->id
.'">'.
5451 '<img class="icon log" src="'.$CFG->pixpath
.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
5455 $backtext= get_string('activityprev', 'access');
5456 $backmod = '<li><form action="'.$CFG->wwwroot
.'/mod/'.$backmod->modname
.'/view.php" '.$CFG->frametarget
.' '.
5457 'onclick="this.target=\''.$CFG->framename
.'\';"'.'><fieldset class="invisiblefieldset">'.
5458 '<input type="hidden" name="id" value="'.$backmod->id
.'" />'.
5459 '<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
5460 '</button></fieldset></form></li>';
5463 $nexttext= get_string('activitynext', 'access');
5464 $nextmod = '<li><form action="'.$CFG->wwwroot
.'/mod/'.$nextmod->modname
.'/view.php" '.$CFG->frametarget
.' '.
5465 'onclick="this.target=\''.$CFG->framename
.'\';"'.'><fieldset class="invisiblefieldset">'.
5466 '<input type="hidden" name="id" value="'.$nextmod->id
.'" />'.
5467 '<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
5468 '</button></fieldset></form></li>';
5471 return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
5472 '<li>'.popup_form($CFG->wwwroot
.'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
5473 '', '', true, $targetwindow, '', $menustyle).'</li>'.
5474 $nextmod . '</ul>'."\n".'</div>';
5479 * This function returns a small popup menu with all the
5480 * course activity modules in it, as a navigation menu
5481 * outputs a simple list structure in XHTML
5482 * The data is taken from the serialised array stored in
5485 * @param course $course A {@link $COURSE} object.
5487 * @todo Finish documenting this function
5489 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
5496 $doneheading = false;
5498 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
5500 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
5501 foreach ($modinfo->cms
as $mod) {
5502 if ($mod->modname
== 'label') {
5506 if ($mod->sectionnum
> $course->numsections
) { /// Don't show excess hidden sections
5510 if (!$mod->uservisible
) { // do not icnlude empty sections at all
5514 if ($mod->sectionnum
>= 0 and $section != $mod->sectionnum
) {
5515 $thissection = $sections[$mod->sectionnum
];
5517 if ($thissection->visible
or !$course->hiddensections
or
5518 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
5519 $thissection->summary
= strip_tags(format_string($thissection->summary
,true));
5520 if (!$doneheading) {
5521 $menu[] = '</ul></li>';
5523 if ($course->format
== 'weeks' or empty($thissection->summary
)) {
5524 $item = $strsection ." ". $mod->sectionnum
;
5526 if (strlen($thissection->summary
) < ($width-3)) {
5527 $item = $thissection->summary
;
5529 $item = substr($thissection->summary
, 0, $width).'...';
5532 $menu[] = '<li class="section"><span>'.$item.'</span>';
5534 $doneheading = true;
5536 $section = $mod->sectionnum
;
5538 // no activities from this hidden section shown
5543 $url = $mod->modname
.'/view.php?id='. $mod->id
;
5544 $mod->name
= strip_tags(format_string(urldecode($mod->name
),true));
5545 if (strlen($mod->name
) > ($width+
5)) {
5546 $mod->name
= substr($mod->name
, 0, $width).'...';
5548 if (!$mod->visible
) {
5549 $mod->name
= '('.$mod->name
.')';
5551 $class = 'activity '.$mod->modname
;
5552 $class .= ($cmid == $mod->id
) ?
' selected' : '';
5553 $menu[] = '<li class="'.$class.'">'.
5554 '<img src="'.$CFG->modpixpath
.'/'.$mod->modname
.'/icon.gif" alt="" />'.
5555 '<a href="'.$CFG->wwwroot
.'/mod/'.$url.'">'.$mod->name
.'</a></li>';
5559 $menu[] = '</ul></li>';
5561 $menu[] = '</ul></li></ul>';
5563 return implode("\n", $menu);
5567 * Prints form items with the names $day, $month and $year
5569 * @param string $day fieldname
5570 * @param string $month fieldname
5571 * @param string $year fieldname
5572 * @param int $currenttime A default timestamp in GMT
5573 * @param boolean $return
5575 function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
5577 if (!$currenttime) {
5578 $currenttime = time();
5580 $currentdate = usergetdate($currenttime);
5582 for ($i=1; $i<=31; $i++
) {
5585 for ($i=1; $i<=12; $i++
) {
5586 $months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
5588 for ($i=1970; $i<=2020; $i++
) {
5592 // Build or print result
5594 // Note: There should probably be a fieldset around these fields as they are
5595 // clearly grouped. However this causes problems with display. See Mozilla
5597 $result.='<label class="accesshide" for="menu'.$day.'">'.get_string('day','form').'</label>';
5598 $result.=choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', true);
5599 $result.='<label class="accesshide" for="menu'.$month.'">'.get_string('month','form').'</label>';
5600 $result.=choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', true);
5601 $result.='<label class="accesshide" for="menu'.$year.'">'.get_string('year','form').'</label>';
5602 $result.=choose_from_menu($years, $year, $currentdate['year'], '', '', '0', true);
5612 *Prints form items with the names $hour and $minute
5614 * @param string $hour fieldname
5615 * @param string ? $minute fieldname
5616 * @param $currenttime A default timestamp in GMT
5617 * @param int $step minute spacing
5618 * @param boolean $return
5620 function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
5622 if (!$currenttime) {
5623 $currenttime = time();
5625 $currentdate = usergetdate($currenttime);
5627 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
5629 for ($i=0; $i<=23; $i++
) {
5630 $hours[$i] = sprintf("%02d",$i);
5632 for ($i=0; $i<=59; $i+
=$step) {
5633 $minutes[$i] = sprintf("%02d",$i);
5636 // Build or print result
5638 // Note: There should probably be a fieldset around these fields as they are
5639 // clearly grouped. However this causes problems with display. See Mozilla
5641 $result.='<label class="accesshide" for="menu'.$hour.'">'.get_string('hour','form').'</label>';
5642 $result.=choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',true);
5643 $result.='<label class="accesshide" for="menu'.$minute.'">'.get_string('minute','form').'</label>';
5644 $result.=choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',true);
5654 * Prints time limit value selector
5657 * @param int $timelimit default
5658 * @param string $unit
5659 * @param string $name
5660 * @param boolean $return
5662 function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
5670 // Max timelimit is sessiontimeout - 10 minutes.
5671 $maxvalue = ($CFG->sessiontimeout
/ 60) - 10;
5673 for ($i=1; $i<=$maxvalue; $i++
) {
5674 $minutes[$i] = $i.$unit;
5676 return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
5680 * Prints a grade menu (as part of an existing form) with help
5681 * Showing all possible numerical grades and scales
5684 * @param int $courseid ?
5685 * @param string $name ?
5686 * @param string $current ?
5687 * @param boolean $includenograde ?
5688 * @todo Finish documenting this function
5690 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
5695 $strscale = get_string('scale');
5696 $strscales = get_string('scales');
5698 $scales = get_scales_menu($courseid);
5699 foreach ($scales as $i => $scalename) {
5700 $grades[-$i] = $strscale .': '. $scalename;
5702 if ($includenograde) {
5703 $grades[0] = get_string('nograde');
5705 for ($i=100; $i>=1; $i--) {
5708 $output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
5710 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath
.'/help.gif" /></span>';
5711 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&list=true', 'ratingscales',
5712 $linkobject, 400, 500, $strscales, 'none', true);
5722 * Prints a scale menu (as part of an existing form) including help button
5723 * Just like {@link print_grade_menu()} but without the numeric grades
5725 * @param int $courseid ?
5726 * @param string $name ?
5727 * @param string $current ?
5728 * @todo Finish documenting this function
5730 function print_scale_menu($courseid, $name, $current, $return=false) {
5735 $strscales = get_string('scales');
5736 $output .= choose_from_menu(get_scales_menu($courseid), $name, $current, '', '', 0, true);
5738 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath
.'/help.gif" /></span>';
5739 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&list=true', 'ratingscales',
5740 $linkobject, 400, 500, $strscales, 'none', true);
5749 * Prints a help button about a scale
5752 * @param id $courseid ?
5753 * @param object $scale ?
5754 * @todo Finish documenting this function
5756 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
5761 $strscales = get_string('scales');
5763 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name
.'" src="'.$CFG->pixpath
.'/help.gif" /></span>';
5764 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&list=true&scaleid='. $scale->id
, 'ratingscale',
5765 $linkobject, 400, 500, $scale->name
, 'none', true);
5774 * Print an error page displaying an error message. New method - use this for new code.
5778 * @param string $errorcode The name of the string from error.php (or other specified file) to print
5779 * @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.
5780 * @param object $a Extra words and phrases that might be required in the error string
5781 * @param array $extralocations An array of strings with other locations to look for string files
5782 * @return does not return, terminates script
5784 function print_error($errorcode, $module='error', $link='', $a=NULL, $extralocations=NULL) {
5785 global $CFG, $SESSION, $THEME;
5787 if (empty($module) ||
$module === 'moodle' ||
$module === 'core') {
5791 $message = get_string($errorcode, $module, $a, $extralocations);
5792 if ($module === 'error' and strpos($message, '[[') === 0) {
5793 //search in moodle file if error specified - needed for backwards compatibility
5794 $message = get_string($errorcode, 'moodle', $a, $extralocations);
5797 if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
5798 if ( !empty($SESSION->fromurl
) ) {
5799 $link = $SESSION->fromurl
;
5800 unset($SESSION->fromurl
);
5802 $link = $CFG->wwwroot
.'/';
5806 if (!empty($CFG->errordocroot
)) {
5807 $errordocroot = $CFG->errordocroot
;
5808 } else if (!empty($CFG->docroot
)) {
5809 $errordocroot = $CFG->docroot
;
5811 $errordocroot = 'http://docs.moodle.org';
5814 if (defined('FULLME') && FULLME
== 'cron') {
5815 // Errors in cron should be mtrace'd.
5820 if ($module === 'error') {
5821 $modulelink = 'moodle';
5823 $modulelink = $module;
5826 $message = clean_text('<p class="errormessage">'.$message.'</p>'.
5827 '<p class="errorcode">'.
5828 '<a href="'.$errordocroot.'/en/error/'.$modulelink.'/'.$errorcode.'">'.
5829 get_string('moreinformation').'</a></p>');
5831 if (! defined('HEADER_PRINTED')) {
5832 //header not yet printed
5833 @header
('HTTP/1.0 404 Not Found');
5834 print_header(get_string('error'));
5836 print_container_end_all(false, $THEME->open_header_containers
);
5841 print_simple_box($message, '', '', '', '', 'errorbox');
5843 debugging('Stack trace:', DEBUG_DEVELOPER
);
5845 // in case we are logging upgrade in admin/index.php stop it
5846 if (function_exists('upgrade_log_finish')) {
5847 upgrade_log_finish();
5850 if (!empty($link)) {
5851 print_continue($link);
5856 for ($i=0;$i<512;$i++
) { // Padding to help IE work with 404
5863 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
5864 * Default errorcode is 1.
5866 * Very useful for perl-like error-handling:
5868 * do_somethting() or mdie("Something went wrong");
5870 * @param string $msg Error message
5871 * @param integer $errorcode Error code to emit
5873 function mdie($msg='', $errorcode=1) {
5874 trigger_error($msg);
5879 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
5880 * Should be used only with htmleditor or textarea.
5881 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
5885 function editorhelpbutton(){
5886 global $CFG, $SESSION;
5887 $items = func_get_args();
5889 $urlparams = array();
5891 foreach ($items as $item){
5892 if (is_array($item)){
5893 $urlparams[] = "keyword$i=".urlencode($item[0]);
5894 $urlparams[] = "title$i=".urlencode($item[1]);
5895 if (isset($item[2])){
5896 $urlparams[] = "module$i=".urlencode($item[2]);
5898 $titles[] = trim($item[1], ". \t");
5899 }elseif (is_string($item)){
5900 $urlparams[] = "button$i=".urlencode($item);
5903 $titles[] = get_string("helpreading");
5906 $titles[] = get_string("helpwriting");
5909 $titles[] = get_string("helpquestions");
5912 $titles[] = get_string("helpemoticons");
5915 $titles[] = get_string('helprichtext');
5918 $titles[] = get_string('helptext');
5921 error('Unknown help topic '.$item);
5926 if (count($titles)>1){
5927 //join last two items with an 'and'
5929 $a->one
= $titles[count($titles) - 2];
5930 $a->two
= $titles[count($titles) - 1];
5931 $titles[count($titles) - 2] = get_string('and', '', $a);
5932 unset($titles[count($titles) - 1]);
5934 $alttag = join (', ', $titles);
5936 $paramstring = join('&', $urlparams);
5937 $linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath
.'/help.gif" />';
5938 return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), 'popup', $linkobject, 400, 500, $alttag, 'none', true);
5942 * Print a help button.
5945 * @param string $page The keyword that defines a help page
5946 * @param string $title The title of links, rollover tips, alt tags etc
5947 * 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
5948 * @param string $module Which module is the page defined in
5949 * @param mixed $image Use a help image for the link? (true/false/"both")
5950 * @param boolean $linktext If true, display the title next to the help icon.
5951 * @param string $text If defined then this text is used in the page, and
5952 * the $page variable is ignored.
5953 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
5954 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
5956 * @todo Finish documenting this function
5958 function helpbutton ($page, $title, $module='moodle', $image=true, $linktext=false, $text='', $return=false,
5960 global $CFG, $COURSE;
5962 //warning if ever $text parameter is used
5963 //$text option won't work properly because the text needs to be always cleaned and,
5964 // when cleaned... html tags always break, so it's unusable.
5965 if ( isset($text) && $text!='') {
5966 debugging('Warning: it\'s not recommended to use $text parameter in helpbutton ($page=' . $page . ', $module=' . $module . ') function', DEBUG_DEVELOPER
);
5970 if (!empty($COURSE->lang
)) {
5971 $forcelang = $COURSE->lang
;
5976 if ($module == '') {
5980 if ($title == '' && $linktext == '') {
5981 debugging('Error in call to helpbutton function: at least one of $title and $linktext is required');
5984 // Warn users about new window for Accessibility
5985 $tooltip = get_string('helpprefix2', '', trim($title, ". \t")) .' ('.get_string('newwindow').')';
5991 // MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
5992 $linkobject .= $title.' ';
5993 $tooltip = get_string('helpwiththis');
5996 $linkobject .= $imagetext;
5998 $linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
5999 $CFG->pixpath
.'/help.gif" />';
6002 $linkobject .= $tooltip;
6007 $url = '/help.php?module='. $module .'&text='. s(urlencode($text).'&forcelang='.$forcelang);
6009 $url = '/help.php?module='. $module .'&file='. $page .'.html&forcelang='.$forcelang;
6012 $link = '<span class="helplink">'.
6013 link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
6024 * Print a help button.
6026 * Prints a special help button that is a link to the "live" emoticon popup
6029 * @param string $form ?
6030 * @param string $field ?
6031 * @todo Finish documenting this function
6033 function emoticonhelpbutton($form, $field, $return = false) {
6035 global $CFG, $SESSION;
6037 $SESSION->inserttextform
= $form;
6038 $SESSION->inserttextfield
= $field;
6039 $imagetext = '<img src="' . $CFG->pixpath
. '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
6040 $help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
6049 * Print a help button.
6051 * Prints a special help button for html editors (htmlarea in this case)
6054 function editorshortcutshelpbutton() {
6057 $imagetext = '<img src="' . $CFG->httpswwwroot
. '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
6058 get_string('editorshortcutkeys').'" class="iconkbhelp" />';
6060 return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
6064 * Print a message and exit.
6067 * @param string $message ?
6068 * @param string $link ?
6069 * @todo Finish documenting this function
6071 function notice ($message, $link='', $course=NULL) {
6072 global $CFG, $SITE, $THEME, $COURSE;
6074 $message = clean_text($message); // In case nasties are in here
6076 if (defined('FULLME') && FULLME
== 'cron') {
6077 // notices in cron should be mtrace'd.
6082 if (! defined('HEADER_PRINTED')) {
6083 //header not yet printed
6084 print_header(get_string('notice'));
6086 print_container_end_all(false, $THEME->open_header_containers
);
6089 print_box($message, 'generalbox', 'notice');
6090 print_continue($link);
6092 if (empty($course)) {
6093 print_footer($COURSE);
6095 print_footer($course);
6101 * Print a message along with "Yes" and "No" links for the user to continue.
6103 * @param string $message The text to display
6104 * @param string $linkyes The link to take the user to if they choose "Yes"
6105 * @param string $linkno The link to take the user to if they choose "No"
6106 * TODO Document remaining arguments
6108 function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
6112 $message = clean_text($message);
6113 $linkyes = clean_text($linkyes);
6114 $linkno = clean_text($linkno);
6116 print_box_start('generalbox', 'notice');
6117 echo '<p>'. $message .'</p>';
6118 echo '<div class="buttons">';
6119 print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename
);
6120 print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename
);
6126 * Provide an definition of error_get_last for PHP before 5.2.0. This simply
6127 * returns NULL, since there is not way to get the right answer.
6129 if (!function_exists('error_get_last')) {
6130 // the eval is needed to prevent PHP 5.2+ from getting a parse error!
6132 function error_get_last() {
6139 * Redirects the user to another page, after printing a notice
6141 * @param string $url The url to take the user to
6142 * @param string $message The text message to display to the user about the redirect, if any
6143 * @param string $delay How long before refreshing to the new page at $url?
6144 * @todo '&' needs to be encoded into '&' for XHTML compliance,
6145 * however, this is not true for javascript. Therefore we
6146 * first decode all entities in $url (since we cannot rely on)
6147 * the correct input) and then encode for where it's needed
6148 * echo "<script type='text/javascript'>alert('Redirect $url');</script>";
6150 function redirect($url, $message='', $delay=-1) {
6152 global $CFG, $THEME;
6154 if (!empty($CFG->usesid
) && !isset($_COOKIE[session_name()])) {
6155 $url = sid_process_url($url);
6158 $message = clean_text($message);
6160 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $url);
6161 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
6162 $url = str_replace('&', '&', $encodedurl);
6164 /// At developer debug level. Don't redirect if errors have been printed on screen.
6165 /// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
6166 $lasterror = error_get_last();
6167 $error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER
));
6168 $errorprinted = debugging('', DEBUG_ALL
) && $CFG->debugdisplay
&& $error;
6169 if ($errorprinted) {
6170 $message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
6173 $performanceinfo = '';
6174 if (defined('MDL_PERF') ||
(!empty($CFG->perfdebug
) and $CFG->perfdebug
> 7)) {
6175 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
6176 $perf = get_performance_info();
6177 error_log("PERF: " . $perf['txt']);
6181 /// when no message and header printed yet, try to redirect
6182 if (empty($message) and !defined('HEADER_PRINTED')) {
6184 // Technically, HTTP/1.1 requires Location: header to contain
6185 // the absolute path. (In practice browsers accept relative
6186 // paths - but still, might as well do it properly.)
6187 // This code turns relative into absolute.
6188 if (!preg_match('|^[a-z]+:|', $url)) {
6189 // Get host name http://www.wherever.com
6190 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot
);
6191 if (preg_match('|^/|', $url)) {
6192 // URLs beginning with / are relative to web server root so we just add them in
6193 $url = $hostpart.$url;
6195 // URLs not beginning with / are relative to path of current script, so add that on.
6196 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
6200 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
6201 if ($newurl == $url) {
6209 //try header redirection first
6210 @header
($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
6211 @header
('Location: '.$url);
6212 //another way for older browsers and already sent headers (eg trailing whitespace in config.php)
6213 echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
6214 echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
6219 $delay = 3; // if no delay specified wait 3 seconds
6221 if (! defined('HEADER_PRINTED')) {
6222 // this type of redirect might not be working in some browsers - such as lynx :-(
6223 print_header('', '', '', '', $errorprinted ?
'' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
6224 $delay +
= 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
6226 print_container_end_all(false, $THEME->open_header_containers
);
6228 echo '<div id="redirect">';
6229 echo '<div id="message">' . $message . '</div>';
6230 echo '<div id="continue">( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
6233 if (!$errorprinted) {
6235 <script type
="text/javascript">
6238 function redirect() {
6239 document
.location
.replace('<?php echo addslashes_js($url) ?>');
6241 setTimeout("redirect()", <?php
echo ($delay * 1000) ?
>);
6247 $CFG->docroot
= false; // to prevent the link to moodle docs from being displayed on redirect page.
6248 print_footer('none');
6253 * Print a bold message in an optional color.
6255 * @param string $message The message to print out
6256 * @param string $style Optional style to display message text in
6257 * @param string $align Alignment option
6258 * @param bool $return whether to return an output string or echo now
6260 function notify($message, $style='notifyproblem', $align='center', $return=false) {
6261 if ($style == 'green') {
6262 $style = 'notifysuccess'; // backward compatible with old color system
6265 $message = clean_text($message);
6267 $output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."\n";
6277 * Given an email address, this function will return an obfuscated version of it
6279 * @param string $email The email address to obfuscate
6282 function obfuscate_email($email) {
6285 $length = strlen($email);
6287 while ($i < $length) {
6288 if (rand(0,2) && $email{$i}!='@') { //MDL-20619 some browsers have problems unobfuscating @
6289 $obfuscated.='%'.dechex(ord($email{$i}));
6291 $obfuscated.=$email{$i};
6299 * This function takes some text and replaces about half of the characters
6300 * with HTML entity equivalents. Return string is obviously longer.
6302 * @param string $plaintext The text to be obfuscated
6305 function obfuscate_text($plaintext) {
6308 $length = strlen($plaintext);
6310 $prev_obfuscated = false;
6311 while ($i < $length) {
6312 $c = ord($plaintext{$i});
6313 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
6314 if ($prev_obfuscated and $numerical ) {
6315 $obfuscated.='&#'.ord($plaintext{$i}).';';
6316 } else if (rand(0,2)) {
6317 $obfuscated.='&#'.ord($plaintext{$i}).';';
6318 $prev_obfuscated = true;
6320 $obfuscated.=$plaintext{$i};
6321 $prev_obfuscated = false;
6329 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
6330 * to generate a fully obfuscated email link, ready to use.
6332 * @param string $email The email address to display
6333 * @param string $label The text to dispalyed as hyperlink to $email
6334 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
6337 function obfuscate_mailto($email, $label='', $dimmed=false) {
6339 if (empty($label)) {
6343 $title = get_string('emaildisable');
6344 $dimmed = ' class="dimmed"';
6349 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
6350 obfuscate_text('mailto'), obfuscate_email($email),
6351 obfuscate_text($label));
6355 * Prints a single paging bar to provide access to other pages (usually in a search)
6357 * @param int $totalcount Thetotal number of entries available to be paged through
6358 * @param int $page The page you are currently viewing
6359 * @param int $perpage The number of entries that should be shown per page
6360 * @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.
6361 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
6362 * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
6363 * @param bool $nocurr do not display the current page as a link
6364 * @param bool $return whether to return an output string or echo now
6365 * @return bool or string
6367 function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
6371 if ($totalcount > $perpage) {
6372 $output .= '<div class="paging">';
6373 $output .= get_string('page') .':';
6375 $pagenum = $page - 1;
6376 if (!is_a($baseurl, 'moodle_url')){
6377 $output .= ' (<a class="previous" href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>) ';
6379 $output .= ' (<a class="previous" href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>) ';
6383 $lastpage = ceil($totalcount / $perpage);
6388 $startpage = $page - 10;
6389 if (!is_a($baseurl, 'moodle_url')){
6390 $output .= ' <a href="'. $baseurl . $pagevar .'=0">1</a> ...';
6392 $output .= ' <a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a> ...';
6397 $currpage = $startpage;
6398 $displaycount = $displaypage = 0;
6399 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
6400 $displaypage = $currpage+
1;
6401 if ($page == $currpage && empty($nocurr)) {
6402 $output .= ' '. $displaypage;
6404 if (!is_a($baseurl, 'moodle_url')){
6405 $output .= ' <a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
6407 $output .= ' <a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
6414 if ($currpage < $lastpage) {
6415 $lastpageactual = $lastpage - 1;
6416 if (!is_a($baseurl, 'moodle_url')){
6417 $output .= ' ...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a> ';
6419 $output .= ' ...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a> ';
6422 $pagenum = $page +
1;
6423 if ($pagenum != $displaypage) {
6424 if (!is_a($baseurl, 'moodle_url')){
6425 $output .= ' (<a class="next" href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
6427 $output .= ' (<a class="next" href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
6430 $output .= '</div>';
6442 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
6443 * will transform it to html entities
6445 * @param string $text Text to search for nolink tag in
6448 function rebuildnolinktag($text) {
6450 $text = preg_replace('/<(\/*nolink)>/i','<$1>',$text);
6456 * Prints a nice side block with an optional header. The content can either
6457 * be a block of HTML or a list of text with optional icons.
6459 * @param string $heading Block $title embedded in HTML tags, for example <h2>.
6460 * @param string $content ?
6461 * @param array $list ?
6462 * @param array $icons ?
6463 * @param string $footer ?
6464 * @param array $attributes ?
6465 * @param string $title Plain text title, as embedded in the $heading.
6466 * @todo Finish documenting this function. Show example of various attributes, etc.
6468 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
6470 //Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
6471 static $block_id = 0;
6473 $skip_text = get_string('skipa', 'access', strip_tags($title));
6474 $skip_link = '<a href="#sb-'.$block_id.'" class="skip-block">'.$skip_text.'</a>';
6475 $skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
6477 $strip_title = strip_tags($title);
6478 if (! empty($strip_title)) {
6481 //ELSE: a single link on a page "Skip block 4" is too confusing - ignore.
6483 print_side_block_start($heading, $attributes);
6488 echo '<div class="footer">'. $footer .'</div>';
6493 //Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
6494 echo "\n<ul class='list'>\n";
6495 foreach ($list as $key => $string) {
6496 echo '<li class="r'. $row .'">';
6498 echo '<div class="icon column c0">'. $icons[$key] .'</div>';
6500 echo '<div class="column c1">' . $string . '</div>';
6507 echo '<div class="footer">'. $footer .'</div>';
6512 print_side_block_end($attributes, $title);
6517 * Starts a nice side block with an optional header.
6519 * @param string $heading ?
6520 * @param array $attributes ?
6521 * @todo Finish documenting this function
6523 function print_side_block_start($heading='', $attributes = array()) {
6525 global $CFG, $THEME;
6527 // If there are no special attributes, give a default CSS class
6528 if (empty($attributes) ||
!is_array($attributes)) {
6529 $attributes = array('class' => 'sideblock');
6531 } else if(!isset($attributes['class'])) {
6532 $attributes['class'] = 'sideblock';
6534 } else if(!strpos($attributes['class'], 'sideblock')) {
6535 $attributes['class'] .= ' sideblock';
6538 // OK, the class is surely there and in addition to anything
6539 // else, it's tagged as a sideblock
6543 // IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
6545 // If there is a cookie to hide this thing, start it hidden
6546 if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
6547 $attributes['class'] = 'hidden '.$attributes['class'];
6552 foreach ($attributes as $attr => $val) {
6553 $attrtext .= ' '.$attr.'="'.$val.'"';
6556 echo '<div '.$attrtext.'>';
6558 if (!empty($THEME->customcorners
)) {
6559 echo '<div class="wrap">'."\n";
6562 //Accessibility: H2 more appropriate in moodleblock.class.php: _title_html.
6563 echo '<div class="header">';
6564 if (!empty($THEME->customcorners
)) {
6565 echo '<div class="bt"><div> </div></div>';
6566 echo '<div class="i1"><div class="i2">';
6567 echo '<div class="i3">';
6570 if (!empty($THEME->customcorners
)) {
6571 echo '</div></div></div>';
6575 if (!empty($THEME->customcorners
)) {
6576 echo '<div class="bt"><div> </div></div>';
6580 if (!empty($THEME->customcorners
)) {
6581 echo '<div class="i1"><div class="i2">';
6582 echo '<div class="i3">';
6584 echo '<div class="content">';
6590 * Print table ending tags for a side block box.
6592 function print_side_block_end($attributes = array(), $title='') {
6593 global $CFG, $THEME;
6597 if (!empty($THEME->customcorners
)) {
6598 echo '</div></div></div><div class="bb"><div> </div></div></div>';
6603 $strshow = addslashes_js(get_string('showblocka', 'access', strip_tags($title)));
6604 $strhide = addslashes_js(get_string('hideblocka', 'access', strip_tags($title)));
6606 // IE workaround: if I do it THIS way, it works! WTF?
6607 if (!empty($CFG->allowuserblockhiding
) && isset($attributes['id'])) {
6608 echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].
6609 '","'.$strshow.'","'.$strhide."\");\n//]]>\n".'</script>';
6616 * Prints out code needed for spellchecking.
6617 * Original idea by Ludo (Marc Alier).
6619 * Opening CDATA and <script> are output by weblib::use_html_editor()
6621 * @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
6622 * @param boolean $return If false, echos the code instead of returning it
6623 * @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
6625 function print_speller_code ($usehtmleditor=false, $return=false) {
6629 if(!$usehtmleditor) {
6630 $str .= 'function openSpellChecker() {'."\n";
6631 $str .= "\tvar speller = new spellChecker();\n";
6632 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot
."/lib/speller/spellchecker.html\";\n";
6633 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot
."/lib/speller/server-scripts/spellchecker.php\";\n";
6634 $str .= "\tspeller.spellCheckAll();\n";
6637 $str .= "function spellClickHandler(editor, buttonId) {\n";
6638 $str .= "\teditor._textArea.value = editor.getHTML();\n";
6639 $str .= "\tvar speller = new spellChecker( editor._textArea );\n";
6640 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot
."/lib/speller/spellchecker.html\";\n";
6641 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot
."/lib/speller/server-scripts/spellchecker.php\";\n";
6642 $str .= "\tspeller._moogle_edit=1;\n";
6643 $str .= "\tspeller._editor=editor;\n";
6644 $str .= "\tspeller.openChecker();\n";
6655 * Print button for spellchecking when editor is disabled
6657 function print_speller_button () {
6658 echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
6662 function page_id_and_class(&$getid, &$getclass) {
6663 // Create class and id for this page
6666 static $class = NULL;
6669 if (empty($CFG->pagepath
)) {
6670 $CFG->pagepath
= $ME;
6673 if (empty($class) ||
empty($id)) {
6674 $path = str_replace($CFG->httpswwwroot
.'/', '', $CFG->pagepath
); //Because the page could be HTTPSPAGEREQUIRED
6675 $path = str_replace('.php', '', $path);
6676 if (substr($path, -1) == '/') {
6679 if (empty($path) ||
$path == 'index') {
6682 } else if (substr($path, 0, 5) == 'admin') {
6683 $id = str_replace('/', '-', $path);
6686 $id = str_replace('/', '-', $path);
6687 $class = explode('-', $id);
6689 $class = implode('-', $class);
6698 * Prints a maintenance message from /maintenance.html
6700 function print_maintenance_message () {
6703 $CFG->pagepath
= "index.php";
6704 print_header(strip_tags($SITE->fullname
), $SITE->fullname
, 'home');
6706 print_heading(get_string('sitemaintenance', 'admin'));
6707 @include
($CFG->dataroot
.'/'.SITEID
.'/maintenance.html');
6713 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
6715 function adjust_allowed_tags() {
6717 global $CFG, $ALLOWED_TAGS;
6719 if (!empty($CFG->allowobjectembed
)) {
6720 $ALLOWED_TAGS .= '<embed><object>';
6724 /// Some code to print tabs
6726 /// A class for tabs
6731 var $linkedwhenselected;
6733 /// A constructor just because I like constructors
6734 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
6736 $this->link
= $link;
6737 $this->text
= $text;
6738 $this->title
= $title ?
$title : $text;
6739 $this->linkedwhenselected
= $linkedwhenselected;
6746 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
6748 * @param array $tabrows An array of rows where each row is an array of tab objects
6749 * @param string $selected The id of the selected tab (whatever row it's on)
6750 * @param array $inactive An array of ids of inactive tabs that are not selectable.
6751 * @param array $activated An array of ids of other tabs that are currently activated
6753 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
6756 /// $inactive must be an array
6757 if (!is_array($inactive)) {
6758 $inactive = array();
6761 /// $activated must be an array
6762 if (!is_array($activated)) {
6763 $activated = array();
6766 /// Convert the tab rows into a tree that's easier to process
6767 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
6771 /// Print out the current tree of tabs (this function is recursive)
6773 $output = convert_tree_to_html($tree);
6775 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
6786 function convert_tree_to_html($tree, $row=0) {
6788 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
6791 $count = count($tree);
6793 foreach ($tree as $tab) {
6794 $count--; // countdown to zero
6798 if ($first && ($count == 0)) { // Just one in the row
6799 $liclass = 'first last';
6801 } else if ($first) {
6804 } else if ($count == 0) {
6808 if ((empty($tab->subtree
)) && (!empty($tab->selected
))) {
6809 $liclass .= (empty($liclass)) ?
'onerow' : ' onerow';
6812 if ($tab->inactive ||
$tab->active ||
$tab->selected
) {
6813 if ($tab->selected
) {
6814 $liclass .= (empty($liclass)) ?
'here selected' : ' here selected';
6815 } else if ($tab->active
) {
6816 $liclass .= (empty($liclass)) ?
'here active' : ' here active';
6820 $str .= (!empty($liclass)) ?
'<li class="'.$liclass.'">' : '<li>';
6822 if ($tab->inactive ||
$tab->active ||
($tab->selected
&& !$tab->linkedwhenselected
)) {
6823 // The a tag is used for styling
6824 $str .= '<a class="nolink"><span>'.$tab->text
.'</span></a>';
6826 $str .= '<a href="'.$tab->link
.'" title="'.$tab->title
.'"><span>'.$tab->text
.'</span></a>';
6829 if (!empty($tab->subtree
)) {
6830 $str .= convert_tree_to_html($tab->subtree
, $row+
1);
6831 } else if ($tab->selected
) {
6832 $str .= '<div class="tabrow'.($row+
1).' empty"> </div>'."\n";
6835 $str .= ' </li>'."\n";
6837 $str .= '</ul>'."\n";
6843 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
6845 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
6847 $tabrows = array_reverse($tabrows);
6851 foreach ($tabrows as $row) {
6854 foreach ($row as $tab) {
6855 $tab->inactive
= in_array((string)$tab->id
, $inactive);
6856 $tab->active
= in_array((string)$tab->id
, $activated);
6857 $tab->selected
= (string)$tab->id
== $selected;
6859 if ($tab->active ||
$tab->selected
) {
6861 $tab->subtree
= $subtree;
6874 * Returns a string containing a link to the user documentation for the current
6875 * page. Also contains an icon by default. Shown to teachers and admin only.
6877 * @param string $text The text to be displayed for the link
6878 * @param string $iconpath The path to the icon to be displayed
6880 function page_doc_link($text='', $iconpath='') {
6881 global $ME, $COURSE, $CFG;
6883 if (empty($CFG->docroot
) or empty($CFG->rolesactive
)) {
6887 if (empty($COURSE->id
)) {
6888 $context = get_context_instance(CONTEXT_SYSTEM
);
6890 $context = get_context_instance(CONTEXT_COURSE
, $COURSE->id
);
6893 if (!has_capability('moodle/site:doclinks', $context)) {
6897 if (empty($CFG->pagepath
)) {
6898 $CFG->pagepath
= $ME;
6901 $path = str_replace($CFG->httpswwwroot
.'/','', $CFG->pagepath
); // Because the page could be HTTPSPAGEREQUIRED
6902 $path = str_replace('.php', '', $path);
6904 if (empty($path)) { // Not for home page
6907 return doc_link($path, $text, $iconpath);
6911 * Returns a string containing a link to the user documentation.
6912 * Also contains an icon by default. Shown to teachers and admin only.
6914 * @param string $path The page link after doc root and language, no
6916 * @param string $text The text to be displayed for the link
6917 * @param string $iconpath The path to the icon to be displayed
6919 function doc_link($path='', $text='', $iconpath='') {
6922 if (empty($CFG->docroot
)) {
6927 if (!empty($CFG->doctonewwindow
)) {
6928 $target = ' target="_blank"';
6931 $lang = str_replace('_utf8', '', current_language());
6933 $str = '<a href="' .$CFG->docroot
. '/' .$lang. '/' .$path. '"' .$target. '>';
6935 if (empty($iconpath)) {
6936 $iconpath = $CFG->httpswwwroot
. '/pix/docs.gif';
6939 // alt left blank intentionally to prevent repetition in screenreaders
6940 $str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
6947 * Returns true if the current site debugging settings are equal or above specified level.
6948 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
6949 * routing of notices is controlled by $CFG->debugdisplay
6952 * 1) debugging('a normal debug notice');
6953 * 2) debugging('something really picky', DEBUG_ALL);
6954 * 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
6955 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
6957 * In code blocks controlled by debugging() (such as example 4)
6958 * any output should be routed via debugging() itself, or the lower-level
6959 * trigger_error() or error_log(). Using echo or print will break XHTML
6960 * JS and HTTP headers.
6963 * @param string $message a message to print
6964 * @param int $level the level at which this debugging statement should show
6967 function debugging($message='', $level=DEBUG_NORMAL
) {
6971 if (empty($CFG->debug
)) {
6975 if ($CFG->debug
>= $level) {
6977 $callers = debug_backtrace();
6978 $from = '<ul style="text-align: left">';
6979 foreach ($callers as $caller) {
6980 if (!isset($caller['line'])) {
6981 $caller['line'] = '?'; // probably call_user_func()
6983 if (!isset($caller['file'])) {
6984 $caller['file'] = $CFG->dirroot
.'/unknownfile'; // probably call_user_func()
6986 $from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot
) +
1);
6987 if (isset($caller['function'])) {
6988 $from .= ': call to ';
6989 if (isset($caller['class'])) {
6990 $from .= $caller['class'] . $caller['type'];
6992 $from .= $caller['function'] . '()';
6997 if (!isset($CFG->debugdisplay
)) {
6998 $CFG->debugdisplay
= ini_get_bool('display_errors');
7000 if ($CFG->debugdisplay
) {
7001 if (!defined('DEBUGGING_PRINTED')) {
7002 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
7004 notify($message . $from, 'notifytiny');
7006 trigger_error($message . $from, E_USER_NOTICE
);
7015 * Disable debug messages from debugging(), while keeping PHP error reporting level as is.
7017 function disable_debugging() {
7019 $CFG->debug
= $CFG->debug |
0x80000000; // switch the sign bit in integer number ;-)
7024 * Returns string to add a frame attribute, if required
7026 function frametarget() {
7029 if (empty($CFG->framename
) or ($CFG->framename
== '_top')) {
7032 return ' target="'.$CFG->framename
.'" ';
7037 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
7038 * pages that use bits from many different files in very confusing ways (e.g. blocks).
7039 * @usage print_location_comment(__FILE__, __LINE__);
7040 * @param string $file
7041 * @param integer $line
7042 * @param boolean $return Whether to return or print the comment
7043 * @return mixed Void unless true given as third parameter
7045 function print_location_comment($file, $line, $return = false)
7048 return "<!-- $file at line $line -->\n";
7050 echo "<!-- $file at line $line -->\n";
7056 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
7057 * provide this function with the language strings for sortasc and sortdesc.
7058 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
7059 * @param string $direction 'up' or 'down'
7060 * @param string $strsort The language string used for the alt attribute of this image
7061 * @param bool $return Whether to print directly or return the html string
7062 * @return string HTML for the image
7064 * TODO See if this isn't already defined somewhere. If not, move this to weblib
7066 function print_arrow($direction='up', $strsort=null, $return=false) {
7069 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
7075 switch ($direction) {
7090 // Prepare language string
7092 if (empty($strsort) && !empty($sortdir)) {
7093 $strsort = get_string('sort' . $sortdir, 'grades');
7096 $return = ' <img src="'.$CFG->pixpath
.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
7106 * Returns boolean true if the current language is right-to-left (Hebrew, Arabic etc)
7109 function right_to_left() {
7112 if (isset($result)) {
7115 return $result = (get_string('thisdirection') == 'rtl');
7120 * Returns swapped left<=>right if in RTL environment.
7121 * part of RTL support
7123 * @param string $align align to check
7126 function fix_align_rtl($align) {
7127 if (!right_to_left()) {
7130 if ($align=='left') { return 'right'; }
7131 if ($align=='right') { return 'left'; }
7137 * Returns true if the page is displayed in a popup window.
7138 * Gets the information from the URL parameter inpopup.
7142 * TODO Use a central function to create the popup calls allover Moodle and
7143 * TODO In the moment only works with resources and probably questions.
7145 function is_in_popup() {
7146 $inpopup = optional_param('inpopup', '', PARAM_BOOL
);
7152 * Return the authentication plugin title
7153 * @param string $authtype plugin type
7156 function auth_get_plugin_title ($authtype) {
7157 $authtitle = get_string("auth_{$authtype}title", "auth");
7158 if ($authtitle == "[[auth_{$authtype}title]]") {
7159 $authtitle = get_string("auth_{$authtype}title", "auth_{$authtype}");
7165 * Returns a localized sentence in the current language summarizing the current password policy
7170 function print_password_policy() {
7174 if (!empty($CFG->passwordpolicy
)) {
7175 $messages = array();
7176 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength
);
7177 if (!empty($CFG->minpassworddigits
)) {
7178 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits
);
7180 if (!empty($CFG->minpasswordlower
)) {
7181 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower
);
7183 if (!empty($CFG->minpasswordupper
)) {
7184 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper
);
7186 if (!empty($CFG->minpasswordnonalphanum
)) {
7187 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum
);
7190 $messages = join(', ', $messages); // this is ugly but we do not have anything better yet...
7191 $message = get_string('informpasswordpolicy', 'auth', $messages);
7196 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: