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') { // for integer 0, boolean false, string '0'
127 return preg_replace("/&(#\d+);/i", "&$1;", htmlspecialchars(stripslashes_safe($var)));
129 return preg_replace("/&(#\d+);/i", "&$1;", htmlspecialchars($var));
134 * Add quotes to HTML characters
136 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
137 * This function is very similar to {@link s()}
139 * @param string $var the string potentially containing HTML characters
140 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
141 * true should be used to print data from forms and false for data from DB.
144 function p($var, $strip=false) {
145 echo s($var, $strip);
149 * Does proper javascript quoting.
150 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
152 * @since 1.8 - 22/02/2007
154 * @return mixed quoted result
156 function addslashes_js($var) {
157 if (is_string($var)) {
158 $var = str_replace('\\', '\\\\', $var);
159 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
160 $var = str_replace('</', '<\/', $var); // XHTML compliance
161 } else if (is_array($var)) {
162 $var = array_map('addslashes_js', $var);
163 } else if (is_object($var)) {
164 $a = get_object_vars($var);
165 foreach ($a as $key=>$value) {
166 $a[$key] = addslashes_js($value);
174 * Remove query string from url
176 * Takes in a URL and returns it without the querystring portion
178 * @param string $url the url which may have a query string attached
181 function strip_querystring($url) {
183 if ($commapos = strpos($url, '?')) {
184 return substr($url, 0, $commapos);
191 * Returns the URL of the HTTP_REFERER, less the querystring portion if required
192 * @param boolean $stripquery if true, also removes the query part of the url.
195 function get_referer($stripquery=true) {
196 if (isset($_SERVER['HTTP_REFERER'])) {
198 return strip_querystring($_SERVER['HTTP_REFERER']);
200 return $_SERVER['HTTP_REFERER'];
209 * Returns the name of the current script, WITH the querystring portion.
210 * this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
211 * return different things depending on a lot of things like your OS, Web
212 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
213 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
219 if (!empty($_SERVER['REQUEST_URI'])) {
220 return $_SERVER['REQUEST_URI'];
222 } else if (!empty($_SERVER['PHP_SELF'])) {
223 if (!empty($_SERVER['QUERY_STRING'])) {
224 return $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
226 return $_SERVER['PHP_SELF'];
228 } else if (!empty($_SERVER['SCRIPT_NAME'])) {
229 if (!empty($_SERVER['QUERY_STRING'])) {
230 return $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
232 return $_SERVER['SCRIPT_NAME'];
234 } else if (!empty($_SERVER['URL'])) { // May help IIS (not well tested)
235 if (!empty($_SERVER['QUERY_STRING'])) {
236 return $_SERVER['URL'] .'?'. $_SERVER['QUERY_STRING'];
238 return $_SERVER['URL'];
241 notify('Warning: Could not find any of these web server variables: $REQUEST_URI, $PHP_SELF, $SCRIPT_NAME or $URL');
247 * Like {@link me()} but returns a full URL
251 function qualified_me() {
255 if (!empty($CFG->wwwroot
)) {
256 $url = parse_url($CFG->wwwroot
);
259 if (!empty($url['host'])) {
260 $hostname = $url['host'];
261 } else if (!empty($_SERVER['SERVER_NAME'])) {
262 $hostname = $_SERVER['SERVER_NAME'];
263 } else if (!empty($_ENV['SERVER_NAME'])) {
264 $hostname = $_ENV['SERVER_NAME'];
265 } else if (!empty($_SERVER['HTTP_HOST'])) {
266 $hostname = $_SERVER['HTTP_HOST'];
267 } else if (!empty($_ENV['HTTP_HOST'])) {
268 $hostname = $_ENV['HTTP_HOST'];
270 notify('Warning: could not find the name of this server!');
274 if (!empty($url['port'])) {
275 $hostname .= ':'.$url['port'];
276 } else if (!empty($_SERVER['SERVER_PORT'])) {
277 if ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
278 $hostname .= ':'.$_SERVER['SERVER_PORT'];
282 // TODO, this does not work in the situation described in MDL-11061, but
283 // I don't know how to fix it. Possibly believe $CFG->wwwroot ahead of what
284 // the server reports.
285 if (isset($_SERVER['HTTPS'])) {
286 $protocol = ($_SERVER['HTTPS'] == 'on') ?
'https://' : 'http://';
287 } else if (isset($_SERVER['SERVER_PORT'])) { # Apache2 does not export $_SERVER['HTTPS']
288 $protocol = ($_SERVER['SERVER_PORT'] == '443') ?
'https://' : 'http://';
290 $protocol = 'http://';
293 $url_prefix = $protocol.$hostname;
294 return $url_prefix . me();
299 * Class for creating and manipulating urls.
301 * See short write up here http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url
304 var $scheme = '';// e.g. http
311 var $params = array(); //associative array of query string params
314 * Pass no arguments to create a url that refers to this page. Use empty string to create empty url.
316 * @param string $url url default null means use this page url with no query string
317 * empty string means empty url.
318 * if you pass any other type of url it will be parsed into it's bits, including query string
319 * @param array $params these params override anything in the query string where params have the same name.
321 function moodle_url($url = null, $params = array()){
325 $url = strip_querystring($FULLME);
327 $parts = parse_url($url);
328 if ($parts === FALSE){
331 if (isset($parts['query'])){
332 parse_str(str_replace('&', '&', $parts['query']), $this->params
);
334 unset($parts['query']);
335 foreach ($parts as $key => $value){
336 $this->$key = $value;
338 $this->params($params);
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 $text = wiki_to_html($text);
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 $text = purify_html($text);
2024 /// Fix non standard entity notations
2025 $text = preg_replace('/�*([0-9]+);?/', "&#\\1;", $text);
2026 $text = preg_replace('/�*([0-9a-fA-F]+);?/', "&#x\\1;", $text);
2028 /// Remove tags that are not allowed
2029 $text = strip_tags($text, $ALLOWED_TAGS);
2031 /// Clean up embedded scripts and , using kses
2032 $text = cleanAttributes($text);
2034 /// Again remove tags that are not allowed
2035 $text = strip_tags($text, $ALLOWED_TAGS);
2039 /// Remove potential script events - some extra protection for undiscovered bugs in our code
2040 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
2041 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
2048 * KSES replacement cleaning function - uses HTML Purifier.
2050 function purify_html($text) {
2053 // this can not be done only once because we sometimes need to reset the cache
2054 $cachedir = $CFG->dataroot
.'/cache/htmlpurifier/';
2055 $status = check_dir_exists($cachedir, true, true);
2057 static $purifier = false;
2058 if ($purifier === false) {
2059 require_once $CFG->libdir
.'/htmlpurifier/HTMLPurifier.auto.php';
2060 $config = HTMLPurifier_Config
::createDefault();
2061 $config->set('Core', 'AcceptFullDocuments', false);
2062 $config->set('Core', 'Encoding', 'UTF-8');
2063 $config->set('HTML', 'Doctype', 'XHTML 1.0 Transitional');
2064 $config->set('Cache', 'SerializerPath', $cachedir);
2065 $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));
2066 $config->set('Attr', 'AllowedFrameTargets', array('_blank'));
2067 $purifier = new HTMLPurifier($config);
2069 return $purifier->purify($text);
2073 * This function takes a string and examines it for HTML tags.
2074 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
2075 * which checks for attributes and filters them for malicious content
2076 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2078 * @param string $str The string to be examined for html tags
2081 function cleanAttributes($str){
2082 $result = preg_replace_callback(
2083 '%(<[^>]*(>|$)|>)%m', #search for html tags
2091 * This function takes a string with an html tag and strips out any unallowed
2092 * protocols e.g. javascript:
2093 * It calls ancillary functions in kses which are prefixed by kses
2094 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2096 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
2097 * element the html to be cleared
2100 function cleanAttributes2($htmlArray){
2102 global $CFG, $ALLOWED_PROTOCOLS;
2103 require_once($CFG->libdir
.'/kses.php');
2105 $htmlTag = $htmlArray[1];
2106 if (substr($htmlTag, 0, 1) != '<') {
2107 return '>'; //a single character ">" detected
2109 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
2110 return ''; // It's seriously malformed
2112 $slash = trim($matches[1]); //trailing xhtml slash
2113 $elem = $matches[2]; //the element name
2114 $attrlist = $matches[3]; // the list of attributes as a string
2116 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
2119 foreach ($attrArray as $arreach) {
2120 $arreach['name'] = strtolower($arreach['name']);
2121 if ($arreach['name'] == 'style') {
2122 $value = $arreach['value'];
2124 $prevvalue = $value;
2125 $value = kses_no_null($value);
2126 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
2127 $value = kses_decode_entities($value);
2128 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
2129 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
2130 if ($value === $prevvalue) {
2131 $arreach['value'] = $value;
2135 $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']);
2136 $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']);
2137 $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
2138 } else if ($arreach['name'] == 'href') {
2139 //Adobe Acrobat Reader XSS protection
2140 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd)[^#]*)#.*$/i', '$1', $arreach['value']);
2142 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
2146 if (preg_match('%/\s*$%', $attrlist)) {
2147 $xhtml_slash = ' /';
2149 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
2153 * Replaces all known smileys in the text with image equivalents
2156 * @param string $text Passed by reference. The string to search for smily strings.
2159 function replace_smilies(&$text) {
2163 if (empty($CFG->emoticons
)) { /// No emoticons defined, nothing to process here
2167 $lang = current_language();
2168 $emoticonstring = $CFG->emoticons
;
2169 static $e = array();
2170 static $img = array();
2171 static $emoticons = null;
2173 if (is_null($emoticons)) {
2174 $emoticons = array();
2175 if ($emoticonstring) {
2176 $items = explode('{;}', $CFG->emoticons
);
2177 foreach ($items as $item) {
2178 $item = explode('{:}', $item);
2179 $emoticons[$item[0]] = $item[1];
2185 if (empty($img[$lang])) { /// After the first time this is not run again
2186 $e[$lang] = array();
2187 $img[$lang] = array();
2188 foreach ($emoticons as $emoticon => $image){
2189 $alttext = get_string($image, 'pix');
2190 $alttext = preg_replace('/^\[\[(.*)\]\]$/', '$1', $alttext); /// Clean alttext in case there isn't lang string for it.
2191 $e[$lang][] = $emoticon;
2192 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath
.'/s/'. $image .'.gif" />';
2196 // Exclude from transformations all the code inside <script> tags
2197 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
2198 // Based on code from glossary fiter by Williams Castillo.
2201 // Detect all the <script> zones to take out
2202 $excludes = array();
2203 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
2205 // Take out all the <script> zones from text
2206 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
2207 $excludes['<+'.$key.'+>'] = $value;
2210 $text = str_replace($excludes,array_keys($excludes),$text);
2213 /// this is the meat of the code - this is run every time
2214 $text = str_replace($e[$lang], $img[$lang], $text);
2216 // Recover all the <script> zones to text
2218 $text = str_replace(array_keys($excludes),$excludes,$text);
2223 * Given plain text, makes it into HTML as nicely as possible.
2224 * May contain HTML tags already
2227 * @param string $text The string to convert.
2228 * @param boolean $smiley Convert any smiley characters to smiley images?
2229 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
2230 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2234 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
2239 /// Remove any whitespace that may be between HTML tags
2240 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
2242 /// Remove any returns that precede or follow HTML tags
2243 $text = eregi_replace("([\n\r])<", " <", $text);
2244 $text = eregi_replace(">([\n\r])", "> ", $text);
2246 convert_urls_into_links($text);
2248 /// Make returns into HTML newlines.
2250 $text = nl2br($text);
2253 /// Turn smileys into images.
2255 replace_smilies($text);
2258 /// Wrap the whole thing in a paragraph tag if required
2260 return '<p>'.$text.'</p>';
2267 * Given Markdown formatted text, make it into XHTML using external function
2270 * @param string $text The markdown formatted text to be converted.
2271 * @return string Converted text
2273 function markdown_to_html($text) {
2276 require_once($CFG->libdir
.'/markdown.php');
2278 return Markdown($text);
2282 * Given HTML text, make it into plain text using external function
2285 * @param string $html The text to be converted.
2288 function html_to_text($html) {
2292 require_once($CFG->libdir
.'/html2text.php');
2294 $h2t = new html2text($html);
2295 $result = $h2t->get_text();
2301 * Given some text this function converts any URLs it finds into HTML links
2303 * @param string $text Passed in by reference. The string to be searched for urls.
2305 function convert_urls_into_links(&$text) {
2306 //I've added img tags to this list of tags to ignore.
2307 //See MDL-21168 for more info. A better way to ignore tags whether or not
2308 //they are escaped partially or completely would be desirable. For example:
2310 //<a href="blah">
2311 //<a href="blah">
2312 $filterignoretagsopen = array('<a\s[^>]+?>', '<img\s[^>]+?>');
2313 $filterignoretagsclose = array('</a>','');
2314 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
2316 // Check if we support unicode modifiers in regular expressions. Cache it.
2317 // TODO: this check should be a environment requirement in Moodle 2.0, as far as unicode
2318 // chars are going to arrive to URLs officially really soon (2010?)
2319 // Original RFC regex from: http://www.bytemycode.com/snippets/snippet/796/
2320 // Various ideas from: http://alanstorm.com/url_regex_explained
2321 // Unicode check, negative assertion and other bits from Moodle.
2322 static $unicoderegexp;
2323 if (!isset($unicoderegexp)) {
2324 $unicoderegexp = @preg_match
('/\pL/u', 'a'); // This will fail silenty, returning false,
2327 if ($unicoderegexp) { //We can use unicode modifiers
2328 $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\.!$&\'\(\)*+,;=_~:@/?-]*)?(\#[\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?(?<![,.;]))#i',
2329 '<a href="\\1" target="_blank">\\1</a>', $text);
2330 $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\.!$&\'\(\)*+,;=_~:@/?-]*)?(\#[\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?(?<![,.;]))#i',
2331 '<a href="http://\\1" target="_blank">\\1</a>', $text);
2332 } else { //We cannot use unicode modifiers
2333 $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-z0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?(?<![,.;]))#i',
2334 '<a href="\\1" target="_blank">\\1</a>', $text);
2335 $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-z0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?(?<![,.;]))#i',
2336 '<a href="http://\\1" target="_blank">\\1</a>', $text);
2339 if (!empty($ignoretags)) {
2340 $ignoretags = array_reverse($ignoretags); /// Reversed so "progressive" str_replace() will solve some nesting problems.
2341 $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
2346 * This function will highlight search words in a given string
2347 * It cares about HTML and will not ruin links. It's best to use
2348 * this function after performing any conversions to HTML.
2350 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
2351 * @param string $haystack The string (HTML) within which to highlight the search terms.
2352 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
2353 * @param string $prefix the string to put before each search term found.
2354 * @param string $suffix the string to put after each search term found.
2355 * @return string The highlighted HTML.
2357 function highlight($needle, $haystack, $matchcase = false,
2358 $prefix = '<span class="highlight">', $suffix = '</span>') {
2360 /// Quick bail-out in trivial cases.
2361 if (empty($needle) or empty($haystack)) {
2365 /// Break up the search term into words, discard any -words and build a regexp.
2366 $words = preg_split('/ +/', trim($needle));
2367 foreach ($words as $index => $word) {
2368 if (strpos($word, '-') === 0) {
2369 unset($words[$index]);
2370 } else if (strpos($word, '+') === 0) {
2371 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
2373 $words[$index] = preg_quote($word, '/');
2376 $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
2381 /// Another chance to bail-out if $search was only -words
2382 if (empty($words)) {
2386 /// Find all the HTML tags in the input, and store them in a placeholders array.
2387 $placeholders = array();
2389 preg_match_all('/<[^>]*>/', $haystack, $matches);
2390 foreach (array_unique($matches[0]) as $key => $htmltag) {
2391 $placeholders['<|' . $key . '|>'] = $htmltag;
2394 /// In $hastack, replace each HTML tag with the corresponding placeholder.
2395 $haystack = str_replace($placeholders, array_keys($placeholders), $haystack);
2397 /// In the resulting string, Do the highlighting.
2398 $haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack);
2400 /// Turn the placeholders back into HTML tags.
2401 $haystack = str_replace(array_keys($placeholders), $placeholders, $haystack);
2407 * This function will highlight instances of $needle in $haystack
2408 * It's faster that the above function and doesn't care about
2411 * @param string $needle The string to search for
2412 * @param string $haystack The string to search for $needle in
2415 function highlightfast($needle, $haystack) {
2417 if (empty($needle) or empty($haystack)) {
2421 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
2423 if (count($parts) === 1) {
2429 foreach ($parts as $key => $part) {
2430 $parts[$key] = substr($haystack, $pos, strlen($part));
2431 $pos +
= strlen($part);
2433 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2434 $pos +
= strlen($needle);
2437 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2441 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2442 * Internationalisation, for print_header and backup/restorelib.
2443 * @param $dir Default false.
2444 * @return string Attributes.
2446 function get_html_lang($dir = false) {
2449 if (get_string('thisdirection') == 'rtl') {
2450 $direction = ' dir="rtl"';
2452 $direction = ' dir="ltr"';
2455 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2456 $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
2457 @header
('Content-Language: '.$language);
2458 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2462 * Return the markup for the destination of the 'Skip to main content' links.
2463 * Accessibility improvement for keyboard-only users.
2464 * Used in course formats, /index.php and /course/index.php
2465 * @return string HTML element.
2467 function skip_main_destination() {
2468 return '<span id="maincontent"></span>';
2472 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
2475 * Print a standard header
2480 * @param string $title Appears at the top of the window
2481 * @param string $heading Appears at the top of the page
2482 * @param array $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
2483 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2484 * @param string $meta Meta tags to be added to the header
2485 * @param boolean $cache Should this page be cacheable?
2486 * @param string $button HTML code for a button (usually for module editing)
2487 * @param string $menu HTML code for a popup menu
2488 * @param boolean $usexml use XML for this page
2489 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2490 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2492 function print_header ($title='', $heading='', $navigation='', $focus='',
2493 $meta='', $cache=true, $button=' ', $menu='',
2494 $usexml=false, $bodytags='', $return=false) {
2496 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
2498 if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
2499 debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
2500 . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.", DEBUG_DEVELOPER
);
2503 $heading = format_string($heading); // Fix for MDL-8582
2505 /// This makes sure that the header is never repeated twice on a page
2506 if (defined('HEADER_PRINTED')) {
2507 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().');
2510 define('HEADER_PRINTED', 'true');
2512 /// Perform a browser environment check for the flash version. Should only run once per login session.
2513 if (isloggedin() && !empty($CFG->excludeoldflashclients
) && empty($SESSION->flashversion
)) {
2514 // Unfortunately we can't use require_js here and keep it all clean in 1.9 ...
2515 // require_js(array('yui_yahoo', 'yui_event', 'yui_connection', $CFG->httpswwwroot."/lib/swfobject/swfobject.js"));
2516 $meta .= '<script type="text/javascript" src="'.$CFG->wwwroot
.'/lib/yui/yahoo/yahoo-min.js"></script>';
2517 $meta .= '<script type="text/javascript" src="'.$CFG->wwwroot
.'/lib/yui/event/event-min.js"></script>';
2518 $meta .= '<script type="text/javascript" src="'.$CFG->wwwroot
.'/lib/yui/connection/connection-min.js"></script>';
2519 $meta .= '<script type="text/javascript" src="'.$CFG->wwwroot
.'/lib/swfobject/swfobject.js"></script>';
2521 "<script type=\"text/javascript\">\n".
2522 " var flashversion = swfobject.getFlashPlayerVersion();\n".
2523 " YAHOO.util.Connect.asyncRequest('GET','".$CFG->wwwroot
."/login/environment.php?sesskey=".sesskey()."&flashversion='+flashversion.major+'.'+flashversion.minor+'.'+flashversion.release);\n".
2528 /// Add the required stylesheets
2529 $stylesheetshtml = '';
2530 foreach ($CFG->stylesheets
as $stylesheet) {
2531 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2533 $meta = $stylesheetshtml.$meta;
2536 /// Add the meta page from the themes if any were requested
2540 if (!isset($THEME->standardmetainclude
) ||
$THEME->standardmetainclude
) {
2542 include_once($CFG->dirroot
.'/theme/standard/meta.php');
2543 $metapage .= ob_get_contents();
2547 if ($THEME->parent
&& (!isset($THEME->parentmetainclude
) ||
$THEME->parentmetainclude
)) {
2548 if (file_exists($CFG->dirroot
.'/theme/'.$THEME->parent
.'/meta.php')) {
2550 include_once($CFG->dirroot
.'/theme/'.$THEME->parent
.'/meta.php');
2551 $metapage .= ob_get_contents();
2556 if (!isset($THEME->metainclude
) ||
$THEME->metainclude
) {
2557 if (file_exists($CFG->dirroot
.'/theme/'.current_theme().'/meta.php')) {
2559 include_once($CFG->dirroot
.'/theme/'.current_theme().'/meta.php');
2560 $metapage .= ob_get_contents();
2565 $meta = $meta."\n".$metapage;
2567 $meta .= "\n".require_js('',1);
2569 /// Set up some navigation variables
2571 if (is_newnav($navigation)){
2574 if ($navigation == 'home') {
2582 /// This is another ugly hack to make navigation elements available to print_footer later
2583 $THEME->title
= $title;
2584 $THEME->heading
= $heading;
2585 $THEME->navigation
= $navigation;
2586 $THEME->button
= $button;
2587 $THEME->menu
= $menu;
2588 $navmenulist = isset($THEME->navmenulist
) ?
$THEME->navmenulist
: '';
2590 if ($button == '') {
2594 if (file_exists($CFG->dataroot
.'/'.SITEID
.'/maintenance.html')) {
2595 $button = '<a href="'.$CFG->wwwroot
.'/'.$CFG->admin
.'/maintenance.php">'.get_string('maintenancemode', 'admin').'</a> '.$button;
2596 if(!empty($title)) {
2599 $title .= get_string('maintenancemode', 'admin');
2602 if (!$menu and $navigation) {
2603 if (empty($CFG->loginhttps
)) {
2604 $wwwroot = $CFG->wwwroot
;
2607 $wwwroot = str_replace('http:','https:',$CFG->wwwroot
);
2609 $menu = user_login_string($COURSE);
2612 if (isset($SESSION->justloggedin
)) {
2613 unset($SESSION->justloggedin
);
2614 if (!empty($CFG->displayloginfailures
)) {
2615 if (!empty($USER->username
) and $USER->username
!= 'guest') {
2616 if ($count = count_login_failures($CFG->displayloginfailures
, $USER->username
, $USER->lastlogin
)) {
2617 $menu .= ' <font size="1">';
2618 if (empty($count->accounts
)) {
2619 $menu .= get_string('failedloginattempts', '', $count);
2621 $menu .= get_string('failedloginattemptsall', '', $count);
2623 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM
))) {
2624 $menu .= ' (<a href="'.$CFG->wwwroot
.'/course/report/log/index.php'.
2625 '?chooselog=1&id=1&modid=site_errors">'.get_string('logs').'</a>)';
2634 $meta = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' .
2635 "\n" . $meta . "\n";
2637 @header
('Content-Type: text/html; charset=utf-8');
2639 @header
('Content-Script-Type: text/javascript');
2640 @header
('Content-Style-Type: text/css');
2642 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2643 $direction = get_html_lang($dir=true);
2645 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2646 @header
('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2647 @header
('Pragma: no-cache');
2648 @header
('Expires: ');
2649 } else { // Do everything we can to always prevent clients and proxies caching
2650 @header
('Cache-Control: no-store, no-cache, must-revalidate');
2651 @header
('Cache-Control: post-check=0, pre-check=0', false);
2652 @header
('Pragma: no-cache');
2653 @header
('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2654 @header
('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2656 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2657 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
2659 @header
('Accept-Ranges: none');
2661 $currentlanguage = current_language();
2663 if (empty($usexml)) {
2664 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2666 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2668 header('Content-Type: application/xhtml+xml');
2670 echo '<?xml version="1.0" ?>'."\n";
2671 if (!empty($CFG->xml_stylesheets
)) {
2672 $stylesheets = explode(';', $CFG->xml_stylesheets
);
2673 foreach ($stylesheets as $stylesheet) {
2674 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot
.'/'. $stylesheet .'" ?>' . "\n";
2677 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
2678 if (!empty($CFG->xml_doctype_extra
)) {
2679 echo ' plus '. $CFG->xml_doctype_extra
;
2681 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd
.'">'."\n";
2682 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2683 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
2684 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2687 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
2688 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2689 $meta .= '</object>'."\n";
2690 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2694 // Clean up the title
2696 $title = format_string($title); // fix for MDL-8582
2697 $title = str_replace('"', '"', $title);
2699 // Create class and id for this page
2701 page_id_and_class($pageid, $pageclass);
2703 $pageclass .= ' course-'.$COURSE->id
;
2705 if (!isloggedin()) {
2706 $pageclass .= ' notloggedin';
2709 if (!empty($USER->editing
)) {
2710 $pageclass .= ' editing';
2713 if (!empty($CFG->blocksdrag
)) {
2714 $pageclass .= ' drag';
2717 $pageclass .= ' dir-'.get_string('thisdirection');
2719 $pageclass .= ' lang-'.$currentlanguage;
2721 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
2724 include($CFG->header
);
2725 $output = ob_get_contents();
2728 // container debugging info
2729 $THEME->open_header_containers
= open_containers();
2731 // Skip to main content, see skip_main_destination().
2732 if ($pageid=='course-view' or $pageid=='site-index' or $pageid=='course-index') {
2733 $skiplink = '<a class="skip" href="#maincontent">'.get_string('tocontent', 'access').'</a>';
2734 if (! preg_match('/(.*<div[^>]+id="page"[^>]*>)(.*)/s', $output, $matches)) {
2735 preg_match('/(.*<body.*?>)(.*)/s', $output, $matches);
2737 $output = $matches[1]."\n". $skiplink .$matches[2];
2740 $output = force_strict_header($output);
2742 if (!empty($CFG->messaging
)) {
2743 $output .= message_popup_window();
2746 // Add in any extra JavaScript libraries that occurred during the header
2747 $output .= require_js('', 2);
2757 * Used to include JavaScript libraries.
2759 * When the $lib parameter is given, the function will ensure that the
2760 * named library is loaded onto the page - either in the HTML <head>,
2761 * just after the header, or at an arbitrary later point in the page,
2762 * depending on where this function is called.
2764 * Libraries will not be included more than once, so this works like
2765 * require_once in PHP.
2767 * There are two special-case calls to this function which are both used only
2768 * by weblib print_header:
2769 * $extracthtml = 1: this is used before printing the header.
2770 * It returns the script tag code that should go inside the <head>.
2771 * $extracthtml = 2: this is used after printing the header and handles any
2772 * require_js calls that occurred within the header itself.
2774 * @param mixed $lib - string or array of strings
2775 * string(s) should be the shortname for the library or the
2776 * full path to the library file.
2777 * @param int $extracthtml Do not set this parameter usually (leave 0), only
2778 * weblib should set this to 1 or 2 in print_header function.
2779 * @return mixed No return value, except when using $extracthtml it returns the html code.
2781 function require_js($lib,$extracthtml=0) {
2783 static $loadlibs = array();
2785 static $state = REQUIREJS_BEFOREHEADER
;
2786 static $latecode = '';
2789 // Add the lib to the list of libs to be loaded, if it isn't already
2791 if (is_array($lib)) {
2792 foreach($lib as $singlelib) {
2793 require_js($singlelib);
2796 $libpath = ajax_get_lib($lib);
2797 if (array_search($libpath, $loadlibs) === false) {
2798 $loadlibs[] = $libpath;
2800 // For state other than 0 we need to take action as well as just
2801 // adding it to loadlibs
2802 if($state != REQUIREJS_BEFOREHEADER
) {
2803 // Get the script statement for this library
2804 $scriptstatement=get_require_js_code(array($libpath));
2806 if($state == REQUIREJS_AFTERHEADER
) {
2807 // After the header, print it immediately
2808 print $scriptstatement;
2810 // Haven't finished the header yet. Add it after the
2812 $latecode .= $scriptstatement;
2817 } else if($extracthtml==1) {
2818 if($state !== REQUIREJS_BEFOREHEADER
) {
2819 debugging('Incorrect state in require_js (expected BEFOREHEADER): be careful not to call with empty $lib (except in print_header)');
2821 $state = REQUIREJS_INHEADER
;
2824 return get_require_js_code($loadlibs);
2825 } else if($extracthtml==2) {
2826 if($state !== REQUIREJS_INHEADER
) {
2827 debugging('Incorrect state in require_js (expected INHEADER): be careful not to call with empty $lib (except in print_header)');
2830 $state = REQUIREJS_AFTERHEADER
;
2834 debugging('Unexpected value for $extracthtml');
2839 * Should not be called directly - use require_js. This function obtains the code
2840 * (script tags) needed to include JavaScript libraries.
2841 * @param array $loadlibs Array of library files to include
2842 * @return string HTML code to include them
2844 function get_require_js_code($loadlibs) {
2846 // Return the html needed to load the JavaScript files defined in
2847 // our list of libs to be loaded.
2849 foreach ($loadlibs as $loadlib) {
2850 $output .= '<script type="text/javascript" ';
2851 $output .= " src=\"$loadlib\"></script>\n";
2852 if ($loadlib == $CFG->wwwroot
.'/lib/yui/logger/logger-min.js') {
2853 // Special case, we need the CSS too.
2854 $output .= '<link type="text/css" rel="stylesheet" ';
2855 $output .= " href=\"{$CFG->wwwroot}/lib/yui/logger/assets/logger.css\" />\n";
2863 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2864 * and substitute the XHTML strict document type.
2865 * Note, requires the 'xmlns' fix in function print_header above.
2866 * See: http://tracker.moodle.org/browse/MDL-7883
2869 function force_strict_header($output) {
2871 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2872 $xsl = '/lib/xhtml.xsl';
2874 if (!headers_sent() && !empty($CFG->xmlstrictheaders
)) { // With xml strict headers, the browser will barf
2875 $ctype = 'Content-Type: ';
2876 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2878 if (isset($_SERVER['HTTP_ACCEPT'])
2879 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2880 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2882 $ctype .= 'application/xhtml+xml';
2883 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2885 } else if (file_exists($CFG->dirroot
.$xsl)
2886 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2887 // XSL hack for IE 5+ on Windows.
2888 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2889 $www_xsl = $CFG->wwwroot
.$xsl;
2890 $ctype .= 'application/xml';
2891 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2892 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2895 //ELSE: Mac/IE, old/non-XML browsers.
2896 $ctype .= 'text/html';
2899 @header
($ctype.'; charset=utf-8');
2900 $output = $prolog . $output;
2902 // Test parser error-handling.
2903 if (isset($_GET['error'])) {
2904 $output .= "__ TEST: XML well-formed error < __\n";
2908 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
2916 * This version of print_header is simpler because the course name does not have to be
2917 * provided explicitly in the strings. It can be used on the site page as in courses
2918 * Eventually all print_header could be replaced by print_header_simple
2920 * @param string $title Appears at the top of the window
2921 * @param string $heading Appears at the top of the page
2922 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2923 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2924 * @param string $meta Meta tags to be added to the header
2925 * @param boolean $cache Should this page be cacheable?
2926 * @param string $button HTML code for a button (usually for module editing)
2927 * @param string $menu HTML code for a popup menu
2928 * @param boolean $usexml use XML for this page
2929 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2930 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2932 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
2933 $cache=true, $button=' ', $menu='', $usexml=false, $bodytags='', $return=false) {
2935 global $COURSE, $CFG;
2937 // if we have no navigation specified, build it
2938 if( empty($navigation) ){
2939 $navigation = build_navigation('');
2942 // If old style nav prepend course short name otherwise leave $navigation object alone
2943 if (!is_newnav($navigation)) {
2944 if ($COURSE->id
!= SITEID
) {
2945 $shortname = '<a href="'.$CFG->wwwroot
.'/course/view.php?id='. $COURSE->id
.'">'. $COURSE->shortname
.'</a> ->';
2946 $navigation = $shortname.' '.$navigation;
2950 $output = print_header($COURSE->shortname
.': '. $title, $COURSE->fullname
.' '. $heading, $navigation, $focus, $meta,
2951 $cache, $button, $menu, $usexml, $bodytags, true);
2962 * Can provide a course object to make the footer contain a link to
2963 * to the course home page, otherwise the link will go to the site home
2965 * @param mixed $course course object, used for course link button or
2966 * 'none' means no user link, only docs link
2967 * 'empty' means nothing printed in footer
2968 * 'home' special frontpage footer
2969 * @param object $usercourse course used in user link
2970 * @param boolean $return output as string
2971 * @return mixed string or void
2973 function print_footer($course=NULL, $usercourse=NULL, $return=false) {
2974 global $USER, $CFG, $THEME, $COURSE;
2976 if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
2977 admin_externalpage_print_footer();
2981 /// Course links or special footer
2983 if ($course === 'empty') {
2984 // special hack - sometimes we do not want even the docs link in footer
2986 if (!empty($THEME->open_header_containers
)) {
2987 for ($i=0; $i<$THEME->open_header_containers
; $i++
) {
2988 $output .= print_container_end_all(); // containers opened from header
2991 //1.8 theme compatibility
2992 $output .= "\n</div>"; // content div
2994 $output .= "\n</div>\n</body>\n</html>"; // close page div started in header
3002 } else if ($course === 'none') { // Don't print any links etc
3007 } else if ($course === 'home') { // special case for site home page - please do not remove
3008 $course = get_site();
3009 $homelink = '<div class="sitelink">'.
3010 '<a title="Moodle" href="http://moodle.org/">'.
3011 '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
3015 $homelink = '<div class="homelink"><a '.$CFG->frametarget
.' href="'.$CFG->wwwroot
.
3016 '/course/view.php?id='.$course->id
.'">'.format_string($course->shortname
).'</a></div>';
3021 $course = get_site(); // Set course as site course by default
3022 $homelink = '<div class="homelink"><a '.$CFG->frametarget
.' href="'.$CFG->wwwroot
.'/">'.get_string('home').'</a></div>';
3026 /// Set up some other navigation links (passed from print_header by ugly hack)
3027 $menu = isset($THEME->menu
) ?
str_replace('navmenu', 'navmenufooter', $THEME->menu
) : '';
3028 $title = isset($THEME->title
) ?
$THEME->title
: '';
3029 $button = isset($THEME->button
) ?
$THEME->button
: '';
3030 $heading = isset($THEME->heading
) ?
$THEME->heading
: '';
3031 $navigation = isset($THEME->navigation
) ?
$THEME->navigation
: '';
3032 $navmenulist = isset($THEME->navmenulist
) ?
$THEME->navmenulist
: '';
3035 /// Set the user link if necessary
3036 if (!$usercourse and is_object($course)) {
3037 $usercourse = $course;
3040 if (!isset($loggedinas)) {
3041 $loggedinas = user_login_string($usercourse, $USER);
3044 if ($loggedinas == $menu) {
3048 /// there should be exactly the same number of open containers as after the header
3049 if ($THEME->open_header_containers
!= open_containers()) {
3050 debugging('Unexpected number of open containers: '.open_containers().', expecting '.$THEME->open_header_containers
, DEBUG_DEVELOPER
);
3053 /// Provide some performance info if required
3054 $performanceinfo = '';
3055 if (defined('MDL_PERF') ||
(!empty($CFG->perfdebug
) and $CFG->perfdebug
> 7)) {
3056 $perf = get_performance_info();
3057 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
3058 error_log("PERF: " . $perf['txt']);
3060 if (defined('MDL_PERFTOFOOT') ||
debugging() ||
$CFG->perfdebug
> 7) {
3061 $performanceinfo = $perf['html'];
3065 /// Include the actual footer file
3068 include($CFG->footer
);
3069 $output = ob_get_contents();
3080 * Returns the name of the current theme
3089 function current_theme() {
3090 global $CFG, $USER, $SESSION, $COURSE, $FULLME;
3092 if (empty($CFG->themeorder
)) {
3093 $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
3095 $themeorder = $CFG->themeorder
;
3098 if (isloggedin() and isset($CFG->mnet_localhost_id
) and $USER->mnethostid
!= $CFG->mnet_localhost_id
) {
3099 require_once($CFG->dirroot
.'/mnet/peer.php');
3100 $mnet_peer = new mnet_peer();
3101 $mnet_peer->set_id($USER->mnethostid
);
3105 foreach ($themeorder as $themetype) {
3107 if (!empty($theme)) continue;
3109 switch ($themetype) {
3110 case 'page': // Page theme is for special page-only themes set by code
3111 if (!empty($CFG->pagetheme
)) {
3112 $theme = $CFG->pagetheme
;
3116 if (!empty($CFG->allowcoursethemes
) and !empty($COURSE->theme
)) {
3117 $theme = $COURSE->theme
;
3121 if (!empty($CFG->allowcategorythemes
)) {
3122 /// Nasty hack to check if we're in a category page
3123 if (stripos($FULLME, 'course/category.php') !== false) {
3126 $theme = current_category_theme($id);
3128 /// Otherwise check if we're in a course that has a category theme set
3129 } else if (!empty($COURSE->category
)) {
3130 $theme = current_category_theme($COURSE->category
);
3135 if (!empty($SESSION->theme
)) {
3136 $theme = $SESSION->theme
;
3140 if (!empty($CFG->allowuserthemes
) and !empty($USER->theme
)) {
3141 if (isloggedin() and $USER->mnethostid
!= $CFG->mnet_localhost_id
&& $mnet_peer->force_theme
== 1 && $mnet_peer->theme
!= '') {
3142 $theme = $mnet_peer->theme
;
3144 $theme = $USER->theme
;
3149 if (isloggedin() and isset($CFG->mnet_localhost_id
) and $USER->mnethostid
!= $CFG->mnet_localhost_id
&& $mnet_peer->force_theme
== 1 && $mnet_peer->theme
!= '') {
3150 $theme = $mnet_peer->theme
;
3152 $theme = $CFG->theme
;
3160 /// A final check in case 'site' was not included in $CFG->themeorder
3161 if (empty($theme)) {
3162 $theme = $CFG->theme
;
3169 * Retrieves the category theme if one exists, otherwise checks the parent categories.
3170 * Recursive function.
3173 * @param integer $categoryid id of the category to check
3174 * @return string theme name
3176 function current_category_theme($categoryid=0) {
3179 /// Use the COURSE global if the categoryid not set
3180 if (empty($categoryid)) {
3181 if (!empty($COURSE->category
)) {
3182 $categoryid = $COURSE->category
;
3188 /// Retrieve the current category
3189 if ($category = get_record('course_categories', 'id', $categoryid)) {
3191 /// Return the category theme if it exists
3192 if (!empty($category->theme
)) {
3193 return $category->theme
;
3195 /// Otherwise try the parent category if one exists
3196 } else if (!empty($category->parent
)) {
3197 return current_category_theme($category->parent
);
3200 /// Return false if we can't find the category record
3207 * This function is called by stylesheets to set up the header
3208 * approriately as well as the current path
3211 * @param int $lastmodified ?
3212 * @param int $lifetime ?
3213 * @param string $thename ?
3215 function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
3217 global $CFG, $THEME;
3219 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
3220 $lastmodified = time();
3222 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
3223 header('Expires: ' . gmdate("D, d M Y H:i:s", time() +
$lifetime) . ' GMT');
3224 header('Cache-Control: max-age='. $lifetime);
3226 header('Content-type: text/css'); // Correct MIME type
3228 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
3230 if (empty($themename)) {
3231 $themename = current_theme(); // So we have something. Normally not needed.
3233 $themename = clean_param($themename, PARAM_SAFEDIR
);
3236 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
3238 include($CFG->themedir
.'/'.$forceconfig.'/'.'config.php');
3241 /// If this is the standard theme calling us, then find out what sheets we need
3243 if ($themename == 'standard') {
3244 if (!isset($THEME->standardsheets
) or $THEME->standardsheets
=== true) { // Use all the sheets we have
3245 $THEME->sheets
= $DEFAULT_SHEET_LIST;
3246 } else if (empty($THEME->standardsheets
)) { // We can stop right now!
3247 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3249 } else { // Use the provided subset only
3250 $THEME->sheets
= $THEME->standardsheets
;
3253 /// If we are a parent theme, then check for parent definitions
3255 } else if (!empty($THEME->parent
) && $themename == $THEME->parent
) {
3256 if (!isset($THEME->parentsheets
) or $THEME->parentsheets
=== true) { // Use all the sheets we have
3257 $THEME->sheets
= $DEFAULT_SHEET_LIST;
3258 } else if (empty($THEME->parentsheets
)) { // We can stop right now!
3259 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3261 } else { // Use the provided subset only
3262 $THEME->sheets
= $THEME->parentsheets
;
3266 /// Work out the last modified date for this theme
3268 foreach ($THEME->sheets
as $sheet) {
3269 if (file_exists($CFG->themedir
.'/'.$themename.'/'.$sheet.'.css')) {
3270 $sheetmodified = filemtime($CFG->themedir
.'/'.$themename.'/'.$sheet.'.css');
3271 if ($sheetmodified > $lastmodified) {
3272 $lastmodified = $sheetmodified;
3278 /// Get a list of all the files we want to include
3281 foreach ($THEME->sheets
as $sheet) {
3282 $files[] = array($CFG->themedir
, $themename.'/'.$sheet.'.css');
3285 if ($themename == 'standard') { // Add any standard styles included in any modules
3286 if (!empty($THEME->modsheets
)) { // Search for styles.php within activity modules
3287 if ($mods = get_list_of_plugins('mod')) {
3288 foreach ($mods as $mod) {
3289 if (file_exists($CFG->dirroot
.'/mod/'.$mod.'/styles.php')) {
3290 $files[] = array($CFG->dirroot
, '/mod/'.$mod.'/styles.php');
3296 if (!empty($THEME->blocksheets
)) { // Search for styles.php within block modules
3297 if ($mods = get_list_of_plugins('blocks')) {
3298 foreach ($mods as $mod) {
3299 if (file_exists($CFG->dirroot
.'/blocks/'.$mod.'/styles.php')) {
3300 $files[] = array($CFG->dirroot
, '/blocks/'.$mod.'/styles.php');
3306 if (!isset($THEME->courseformatsheets
) ||
$THEME->courseformatsheets
) { // Search for styles.php in course formats
3307 if ($mods = get_list_of_plugins('format','',$CFG->dirroot
.'/course')) {
3308 foreach ($mods as $mod) {
3309 if (file_exists($CFG->dirroot
.'/course/format/'.$mod.'/styles.php')) {
3310 $files[] = array($CFG->dirroot
, '/course/format/'.$mod.'/styles.php');
3316 if (!isset($THEME->gradereportsheets
) ||
$THEME->gradereportsheets
) { // Search for styles.php in grade reports
3317 if ($reports = get_list_of_plugins('grade/report')) {
3318 foreach ($reports as $report) {
3319 if (file_exists($CFG->dirroot
.'/grade/report/'.$report.'/styles.php')) {
3320 $files[] = array($CFG->dirroot
, '/grade/report/'.$report.'/styles.php');
3326 if (!empty($THEME->langsheets
)) { // Search for styles.php within the current language
3327 if (file_exists($CFG->dirroot
.'/lang/'.$lang.'/styles.php')) {
3328 $files[] = array($CFG->dirroot
, '/lang/'.$lang.'/styles.php');
3334 /// Produce a list of all the files first
3335 echo '/**************************************'."\n";
3336 echo ' * THEME NAME: '.$themename."\n *\n";
3337 echo ' * Files included in this sheet:'."\n *\n";
3338 foreach ($files as $file) {
3339 echo ' * '.$file[1]."\n";
3341 echo ' **************************************/'."\n\n";
3344 /// check if csscobstants is set
3345 if (!empty($THEME->cssconstants
)) {
3346 require_once("$CFG->libdir/cssconstants.php");
3347 /// Actually collect all the files in order.
3349 foreach ($files as $file) {
3350 $css .= '/***** '.$file[1].' start *****/'."\n\n";
3351 $css .= file_get_contents($file[0].'/'.$file[1]);
3352 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
3354 /// replace css_constants with their values
3355 echo replace_cssconstants($css);
3357 /// Actually output all the files in order.
3358 if (empty($CFG->CSSEdit
) && empty($THEME->CSSEdit
)) {
3359 foreach ($files as $file) {
3360 echo '/***** '.$file[1].' start *****/'."\n\n";
3361 @include_once
($file[0].'/'.$file[1]);
3362 echo '/***** '.$file[1].' end *****/'."\n\n";
3365 foreach ($files as $file) {
3366 echo '/* @group '.$file[1].' */'."\n\n";
3367 if (strstr($file[1], '.css') !== FALSE) {
3368 echo '@import url("'.$CFG->themewww
.'/'.$file[1].'");'."\n\n";
3370 @include_once
($file[0].'/'.$file[1]);
3372 echo '/* @end */'."\n\n";
3378 return $CFG->themewww
.'/'.$themename; // Only to help old themes (1.4 and earlier)
3382 function theme_setup($theme = '', $params=NULL) {
3383 /// Sets up global variables related to themes
3385 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
3387 /// Do not mess with THEME if header already printed - this would break all the extra stuff in global $THEME from print_header()!!
3388 if (defined('HEADER_PRINTED')) {
3392 if (empty($theme)) {
3393 $theme = current_theme();
3396 /// If the theme doesn't exist for some reason then revert to standardwhite
3397 if (!file_exists($CFG->themedir
.'/'. $theme .'/config.php')) {
3398 $CFG->theme
= $theme = 'standardwhite';
3401 /// Load up the theme config
3402 $THEME = NULL; // Just to be sure
3403 include($CFG->themedir
.'/'. $theme .'/config.php'); // Main config for current theme
3405 /// Put together the parameters
3410 if ($theme != $CFG->theme
) {
3411 $params[] = 'forceconfig='.$theme;
3414 /// Force language too if required
3415 if (!empty($THEME->langsheets
)) {
3416 $params[] = 'lang='.current_language();
3420 /// Convert params to string
3422 $paramstring = '?'.implode('&', $params);
3427 /// Set up image paths
3428 if(isset($CFG->smartpix
) && $CFG->smartpix
==1) {
3429 if($CFG->slasharguments
) { // Use this method if possible for better caching
3435 $CFG->pixpath
= $CFG->wwwroot
. '/pix/smartpix.php'.$extra.'/'.$theme;
3436 $CFG->modpixpath
= $CFG->wwwroot
.'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
3437 } else if (empty($THEME->custompix
)) { // Could be set in the above file
3438 $CFG->pixpath
= $CFG->wwwroot
.'/pix';
3439 $CFG->modpixpath
= $CFG->wwwroot
.'/mod';
3441 $CFG->pixpath
= $CFG->themewww
.'/'. $theme .'/pix';
3442 $CFG->modpixpath
= $CFG->themewww
.'/'. $theme .'/pix/mod';
3445 /// Header and footer paths
3446 $CFG->header
= $CFG->themedir
.'/'. $theme .'/header.html';
3447 $CFG->footer
= $CFG->themedir
.'/'. $theme .'/footer.html';
3449 /// Define stylesheet loading order
3450 $CFG->stylesheets
= array();
3451 if ($theme != 'standard') { /// The standard sheet is always loaded first
3452 $CFG->stylesheets
[] = $CFG->themewww
.'/standard/styles.php'.$paramstring;
3454 if (!empty($THEME->parent
)) { /// Parent stylesheets are loaded next
3455 $CFG->stylesheets
[] = $CFG->themewww
.'/'.$THEME->parent
.'/styles.php'.$paramstring;
3457 $CFG->stylesheets
[] = $CFG->themewww
.'/'.$theme.'/styles.php'.$paramstring;
3459 /// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
3460 if (!empty($HTTPSPAGEREQUIRED)) {
3461 $CFG->themewww
= str_replace('http:', 'https:', $CFG->themewww
);
3462 $CFG->pixpath
= str_replace('http:', 'https:', $CFG->pixpath
);
3463 $CFG->modpixpath
= str_replace('http:', 'https:', $CFG->modpixpath
);
3464 foreach ($CFG->stylesheets
as $key => $stylesheet) {
3465 $CFG->stylesheets
[$key] = str_replace('http:', 'https:', $stylesheet);
3469 // RTL support - only for RTL languages, add RTL CSS
3470 if (get_string('thisdirection') == 'rtl') {
3471 $CFG->stylesheets
[] = $CFG->themewww
.'/standard/rtl.css'.$paramstring;
3472 $CFG->stylesheets
[] = $CFG->themewww
.'/'.$theme.'/rtl.css'.$paramstring;
3478 * Returns text to be displayed to the user which reflects their login status
3482 * @param course $course {@link $COURSE} object containing course information
3483 * @param user $user {@link $USER} object containing user information
3486 function user_login_string($course=NULL, $user=NULL) {
3487 global $USER, $CFG, $SITE;
3489 if (empty($user) and !empty($USER->id
)) {
3493 if (empty($course)) {
3497 if (!empty($user->realuser
)) {
3498 if ($realuser = get_record('user', 'id', $user->realuser
)) {
3499 $fullname = fullname($realuser, true);
3500 $realuserinfo = " [<a $CFG->frametarget
3501 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&return=1&sesskey=".sesskey()."\">$fullname</a>] ";
3507 if (empty($CFG->loginhttps
)) {
3508 $wwwroot = $CFG->wwwroot
;
3510 $wwwroot = str_replace('http:','https:',$CFG->wwwroot
);
3513 if (empty($course->id
)) {
3514 // $course->id is not defined during installation
3516 } else if (!empty($user->id
)) {
3517 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
3519 $fullname = fullname($user, true);
3520 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a>";
3521 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid
)) {
3522 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
3524 if (isset($user->username
) && $user->username
== 'guest') {
3525 $loggedinas = $realuserinfo.get_string('loggedinasguest').
3526 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3527 } else if (!empty($user->access
['rsw'][$context->path
])) {
3529 if ($role = get_record('role', 'id', $user->access
['rsw'][$context->path
])) {
3530 $rolename = join("", role_fix_names(array($role->id
=>$role->name
), $context));
3531 $rolename = ': '.format_string($rolename);
3533 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
3534 " (<a $CFG->frametarget
3535 href=\"$CFG->wwwroot/course/view.php?id=$course->id&switchrole=0&sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
3537 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
3538 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
3541 $loggedinas = get_string('loggedinnot', 'moodle').
3542 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3544 return '<div class="logininfo">'.$loggedinas.'</div>';
3548 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
3549 * If not it applies sensible defaults.
3551 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
3552 * search forum block, etc. Important: these are 'silent' in a screen-reader
3553 * (unlike > »), and must be accompanied by text.
3556 function check_theme_arrows() {
3559 if (!isset($THEME->rarrow
) and !isset($THEME->larrow
)) {
3560 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
3561 // Also OK in Win 9x/2K/IE 5.x
3562 $THEME->rarrow
= '►';
3563 $THEME->larrow
= '◄';
3564 if (empty($_SERVER['HTTP_USER_AGENT'])) {
3567 $uagent = $_SERVER['HTTP_USER_AGENT'];
3569 if (false !== strpos($uagent, 'Opera')
3570 ||
false !== strpos($uagent, 'Mac')) {
3571 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
3572 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
3573 $THEME->rarrow
= '▶';
3574 $THEME->larrow
= '◀';
3576 elseif (false !== strpos($uagent, 'Konqueror')) {
3577 $THEME->rarrow
= '→';
3578 $THEME->larrow
= '←';
3580 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
3581 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
3582 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
3583 // To be safe, non-Unicode browsers!
3584 $THEME->rarrow
= '>';
3585 $THEME->larrow
= '<';
3588 /// RTL support - in RTL languages, swap r and l arrows
3589 if (right_to_left()) {
3590 $t = $THEME->rarrow
;
3591 $THEME->rarrow
= $THEME->larrow
;
3592 $THEME->larrow
= $t;
3599 * Return the right arrow with text ('next'), and optionally embedded in a link.
3600 * See function above, check_theme_arrows.
3601 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3602 * @param string $url An optional link to use in a surrounding HTML anchor.
3603 * @param bool $accesshide True if text should be hidden (for screen readers only).
3604 * @param string $addclass Additional class names for the link, or the arrow character.
3605 * @return string HTML string.
3607 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
3609 check_theme_arrows();
3610 $arrowclass = 'arrow ';
3612 $arrowclass .= $addclass;
3614 $arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow
.'</span>';
3617 $htmltext = $text.' ';
3619 $htmltext = get_accesshide($htmltext);
3625 $class =" class=\"$addclass\"";
3627 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
3629 return $htmltext.$arrow;
3633 * Return the left arrow with text ('previous'), and optionally embedded in a link.
3634 * See function above, check_theme_arrows.
3635 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3636 * @param string $url An optional link to use in a surrounding HTML anchor.
3637 * @param bool $accesshide True if text should be hidden (for screen readers only).
3638 * @param string $addclass Additional class names for the link, or the arrow character.
3639 * @return string HTML string.
3641 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
3643 check_theme_arrows();
3644 $arrowclass = 'arrow ';
3646 $arrowclass .= $addclass;
3648 $arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow
.'</span>';
3651 $htmltext = ' '.$text;
3653 $htmltext = get_accesshide($htmltext);
3659 $class =" class=\"$addclass\"";
3661 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
3663 return $arrow.$htmltext;
3667 * Return a HTML element with the class "accesshide", for accessibility.
3668 * Please use cautiously - where possible, text should be visible!
3669 * @param string $text Plain text.
3670 * @param string $elem Lowercase element name, default "span".
3671 * @param string $class Additional classes for the element.
3672 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
3673 * @return string HTML string.
3675 function get_accesshide($text, $elem='span', $class='', $attrs='') {
3676 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
3680 * Return the breadcrumb trail navigation separator.
3681 * @return string HTML string.
3683 function get_separator() {
3684 //Accessibility: the 'hidden' slash is preferred for screen readers.
3685 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
3689 * Prints breadcrumb trail of links, called in theme/-/header.html
3692 * @param mixed $navigation The breadcrumb navigation string to be printed
3693 * @param string $separator OBSOLETE, mostly not used any more. See build_navigation instead.
3694 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
3695 * @return string or null, depending on $return.
3697 function print_navigation ($navigation, $separator=0, $return=false) {
3698 global $CFG, $THEME;
3701 if (0 === $separator) {
3702 $separator = get_separator();
3705 $separator = '<span class="sep">'. $separator .'</span>';
3710 if (is_newnav($navigation)) {
3712 return($navigation['navlinks']);
3714 echo $navigation['navlinks'];
3718 debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER
);
3721 if (!is_array($navigation)) {
3722 $ar = explode('->', $navigation);
3723 $navigation = array();
3725 foreach ($ar as $a) {
3726 if (strpos($a, '</a>') === false) {
3727 $navigation[] = array('title' => $a, 'url' => '');
3729 if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
3730 $navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
3736 if (! $site = get_site()) {
3737 $site = new object();
3738 $site->shortname
= get_string('home');
3741 //Accessibility: breadcrumb links now in a list, » replaced with a 'silent' character.
3742 $output .= get_accesshide(get_string('youarehere','access'), 'h2')."<ul>\n";
3744 $output .= '<li class="first">'."\n".'<a '.$CFG->frametarget
.' onclick="this.target=\''.$CFG->framename
.'\'" href="'
3745 .$CFG->wwwroot
.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))
3746 && !empty($USER->id
) && !empty($CFG->mymoodleredirect
) && !isguest())
3747 ?
'/my' : '') .'/">'. format_string($site->shortname
) ."</a>\n</li>\n";
3750 foreach ($navigation as $navitem) {
3751 $title = trim(strip_tags(format_string($navitem['title'], false)));
3752 $url = $navitem['url'];
3755 $output .= '<li>'."$separator $title</li>\n";
3757 $output .= '<li>'."$separator\n<a ".$CFG->frametarget
.' onclick="this.target=\''.$CFG->framename
.'\'" href="'
3758 .$url.'">'."$title</a>\n</li>\n";
3762 $output .= "</ul>\n";
3773 * This function will build the navigation string to be used by print_header
3776 * It automatically generates the site and course level (if appropriate) links.
3778 * If you pass in a $cm object, the method will also generate the activity (e.g. 'Forums')
3779 * and activityinstances (e.g. 'General Developer Forum') navigation levels.
3781 * If you want to add any further navigation links after the ones this function generates,
3782 * the pass an array of extra link arrays like this:
3784 * array('name' => $linktext1, 'link' => $url1, 'type' => $linktype1),
3785 * array('name' => $linktext2, 'link' => $url2, 'type' => $linktype2)
3787 * The normal case is to just add one further link, for example 'Editing forum' after
3788 * 'General Developer Forum', with no link.
3789 * To do that, you need to pass
3790 * array(array('name' => $linktext, 'link' => '', 'type' => 'title'))
3791 * However, becuase this is a very common case, you can use a shortcut syntax, and just
3792 * pass the string 'Editing forum', instead of an array as $extranavlinks.
3794 * At the moment, the link types only have limited significance. Type 'activity' is
3795 * recognised in order to implement the $CFG->hideactivitytypenavlink feature. Types
3796 * that are known to appear are 'home', 'course', 'activity', 'activityinstance' and 'title'.
3797 * This really needs to be documented better. In the mean time, try to be consistent, it will
3798 * enable people to customise the navigation more in future.
3800 * When passing a $cm object, the fields used are $cm->modname, $cm->name and $cm->course.
3801 * If you get the $cm object using the function get_coursemodule_from_instance or
3802 * get_coursemodule_from_id (as recommended) then this will be done for you automatically.
3803 * If you don't have $cm->modname or $cm->name, this fuction will attempt to find them using
3804 * the $cm->module and $cm->instance fields, but this takes extra database queries, so a
3805 * warning is printed in developer debug mode.
3810 * @param mixed $extranavlinks - Normally an array of arrays, keys: name, link, type. If you
3811 * only want one extra item with no link, you can pass a string instead. If you don't want
3812 * any extra links, pass an empty string.
3813 * @param mixed $cm - optionally the $cm object, if you want this function to generate the
3814 * activity and activityinstance levels of navigation too.
3816 * @return $navigation as an object so it can be differentiated from old style
3817 * navigation strings.
3819 function build_navigation($extranavlinks, $cm = null) {
3820 global $CFG, $COURSE;
3822 if (is_string($extranavlinks)) {
3823 if ($extranavlinks == '') {
3824 $extranavlinks = array();
3826 $extranavlinks = array(array('name' => $extranavlinks, 'link' => '', 'type' => 'title'));
3830 $navlinks = array();
3833 if ($site = get_site()) {
3834 $navlinks[] = array(
3835 'name' => format_string($site->shortname
),
3836 'link' => "$CFG->wwwroot/",
3840 // Course name, if appropriate.
3841 if (isset($COURSE) && $COURSE->id
!= SITEID
) {
3842 $navlinks[] = array(
3843 'name' => format_string($COURSE->shortname
),
3844 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",
3845 'type' => 'course');
3848 // Activity type and instance, if appropriate.
3849 if (is_object($cm)) {
3850 if (!isset($cm->modname
)) {
3851 debugging('The field $cm->modname should be set if you call build_navigation with '.
3852 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3853 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER
);
3854 if (!$cm->modname
= get_field('modules', 'name', 'id', $cm->module
)) {
3855 error('Cannot get the module type in build navigation.');
3858 if (!isset($cm->name
)) {
3859 debugging('The field $cm->name should be set if you call build_navigation with '.
3860 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3861 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER
);
3862 if (!$cm->name
= get_field($cm->modname
, 'name', 'id', $cm->instance
)) {
3863 error('Cannot get the module name in build navigation.');
3866 $navlinks[] = array(
3867 'name' => get_string('modulenameplural', $cm->modname
),
3868 'link' => $CFG->wwwroot
. '/mod/' . $cm->modname
. '/index.php?id=' . $cm->course
,
3869 'type' => 'activity');
3870 $navlinks[] = array(
3871 'name' => format_string($cm->name
),
3872 'link' => $CFG->wwwroot
. '/mod/' . $cm->modname
. '/view.php?id=' . $cm->id
,
3873 'type' => 'activityinstance');
3876 //Merge in extra navigation links
3877 $navlinks = array_merge($navlinks, $extranavlinks);
3879 // Work out whether we should be showing the activity (e.g. Forums) link.
3880 // Note: build_navigation() is called from many places --
3881 // install & upgrade for example -- where we cannot count on the
3882 // roles infrastructure to be defined. Hence the $CFG->rolesactive check.
3883 if (!isset($CFG->hideactivitytypenavlink
)) {
3884 $CFG->hideactivitytypenavlink
= 0;
3886 if ($CFG->hideactivitytypenavlink
== 2) {
3887 $hideactivitylink = true;
3888 } else if ($CFG->hideactivitytypenavlink
== 1 && $CFG->rolesactive
&&
3889 !empty($COURSE->id
) && $COURSE->id
!= SITEID
) {
3890 if (!isset($COURSE->context
)) {
3891 $COURSE->context
= get_context_instance(CONTEXT_COURSE
, $COURSE->id
);
3893 $hideactivitylink = !has_capability('moodle/course:manageactivities', $COURSE->context
);
3895 $hideactivitylink = false;
3898 //Construct an unordered list from $navlinks
3899 //Accessibility: heading hidden from visual browsers by default.
3900 $navigation = get_accesshide(get_string('youarehere','access'), 'h2')." <ul>\n";
3901 $lastindex = count($navlinks) - 1;
3902 $i = -1; // Used to count the times, so we know when we get to the last item.
3904 foreach ($navlinks as $navlink) {
3906 $last = ($i == $lastindex);
3907 if (!is_array($navlink)) {
3910 if (!empty($navlink['type']) && $navlink['type'] == 'activity' && !$last && $hideactivitylink) {
3914 $navigation .= '<li class="first">';
3916 $navigation .= '<li>';
3919 $navigation .= get_separator();
3921 if ((!empty($navlink['link'])) && !$last) {
3922 $navigation .= "<a $CFG->frametarget onclick=\"this.target='$CFG->framename'\" href=\"{$navlink['link']}\">";
3924 $navigation .= "{$navlink['name']}";
3925 if ((!empty($navlink['link'])) && !$last) {
3926 $navigation .= "</a>";
3929 $navigation .= "</li>";
3932 $navigation .= "</ul>";
3934 return(array('newnav' => true, 'navlinks' => $navigation));
3939 * Prints a string in a specified size (retained for backward compatibility)
3941 * @param string $text The text to be displayed
3942 * @param int $size The size to set the font for text display.
3944 function print_headline($text, $size=2, $return=false) {
3945 $output = print_heading($text, '', $size, true);
3954 * Prints text in a format for use in headings.
3956 * @param string $text The text to be displayed
3957 * @param string $align The alignment of the printed paragraph of text
3958 * @param int $size The size to set the font for text display.
3960 function print_heading($text, $align='', $size=2, $class='main', $return=false) {
3962 $align = ' style="text-align:'.$align.';"';
3965 $class = ' class="'.$class.'"';
3967 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
3977 * Centered heading with attached help button (same title text)
3978 * and optional icon attached
3980 * @param string $text The text to be displayed
3981 * @param string $helppage The help page to link to
3982 * @param string $module The module whose help should be linked to
3983 * @param string $icon Image to display if needed
3985 function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
3987 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
3988 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
3999 function print_heading_block($heading, $class='', $return=false) {
4000 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
4001 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
4012 * Print a link to continue on to another page.
4015 * @param string $link The url to create a link to.
4017 function print_continue($link, $return=false) {
4021 // in case we are logging upgrade in admin/index.php stop it
4022 if (function_exists('upgrade_log_finish')) {
4023 upgrade_log_finish();
4029 if (!empty($_SERVER['HTTP_REFERER'])) {
4030 $link = $_SERVER['HTTP_REFERER'];
4031 $link = str_replace('&', '&', $link); // make it valid XHTML
4033 $link = $CFG->wwwroot
.'/';
4038 $linkparts = parse_url(str_replace('&', '&', $link));
4039 if (isset($linkparts['query'])) {
4040 parse_str($linkparts['query'], $options);
4043 $output .= '<div class="continuebutton">';
4045 $output .= print_single_button($link, $options, get_string('continue'), 'get', $CFG->framename
, true);
4046 $output .= '</div>'."\n";
4057 * Print a message in a standard themed box.
4058 * Replaces print_simple_box (see deprecatedlib.php)
4060 * @param string $message, the content of the box
4061 * @param string $classes, space-separated class names.
4062 * @param string $idbase
4063 * @param boolean $return, return as string or just print it
4064 * @return mixed string or void
4066 function print_box($message, $classes='generalbox', $ids='', $return=false) {
4068 $output = print_box_start($classes, $ids, true);
4069 $output .= stripslashes_safe($message);
4070 $output .= print_box_end(true);
4080 * Starts a box using divs
4081 * Replaces print_simple_box_start (see deprecatedlib.php)
4083 * @param string $classes, space-separated class names.
4084 * @param string $idbase
4085 * @param boolean $return, return as string or just print it
4086 * @return mixed string or void
4088 function print_box_start($classes='generalbox', $ids='', $return=false) {
4091 if (strpos($classes, 'clearfix') !== false) {
4093 $classes = trim(str_replace('clearfix', '', $classes));
4098 if (!empty($THEME->customcorners
)) {
4099 $classes .= ' ccbox box';
4104 return print_container_start($clearfix, $classes, $ids, $return);
4108 * Simple function to end a box (see above)
4109 * Replaces print_simple_box_end (see deprecatedlib.php)
4111 * @param boolean $return, return as string or just print it
4113 function print_box_end($return=false) {
4114 return print_container_end($return);
4118 * Print a message in a standard themed container.
4120 * @param string $message, the content of the container
4121 * @param boolean $clearfix clear both sides
4122 * @param string $classes, space-separated class names.
4123 * @param string $idbase
4124 * @param boolean $return, return as string or just print it
4125 * @return string or void
4127 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
4129 $output = print_container_start($clearfix, $classes, $idbase, true);
4130 $output .= stripslashes_safe($message);
4131 $output .= print_container_end(true);
4141 * Starts a container using divs
4143 * @param boolean $clearfix clear both sides
4144 * @param string $classes, space-separated class names.
4145 * @param string $idbase
4146 * @param boolean $return, return as string or just print it
4147 * @return mixed string or void
4149 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
4152 if (!isset($THEME->open_containers
)) {
4153 $THEME->open_containers
= array();
4155 $THEME->open_containers
[] = $idbase;
4158 if (!empty($THEME->customcorners
)) {
4159 $output = _print_custom_corners_start($clearfix, $classes, $idbase);
4162 $id = ' id="'.$idbase.'"';
4167 $clearfix = ' clearfix';
4171 if ($classes or $clearfix) {
4172 $class = ' class="'.$classes.$clearfix.'"';
4176 $output = '<div'.$id.$class.'>';
4187 * Simple function to end a container (see above)
4188 * @param boolean $return, return as string or just print it
4189 * @return mixed string or void
4191 function print_container_end($return=false) {
4194 if (empty($THEME->open_containers
)) {
4195 debugging('Incorrect request to end container - no more open containers.', DEBUG_DEVELOPER
);
4198 $idbase = array_pop($THEME->open_containers
);
4201 if (!empty($THEME->customcorners
)) {
4202 $output = _print_custom_corners_end($idbase);
4215 * Returns number of currently open containers
4216 * @return int number of open containers
4218 function open_containers() {
4221 if (!isset($THEME->open_containers
)) {
4222 $THEME->open_containers
= array();
4225 return count($THEME->open_containers
);
4229 * Force closing of open containers
4230 * @param boolean $return, return as string or just print it
4231 * @param int $keep number of containers to be kept open - usually theme or page containers
4232 * @return mixed string or void
4234 function print_container_end_all($return=false, $keep=0) {
4236 while (open_containers() > $keep) {
4237 $output .= print_container_end($return);
4248 * Internal function - do not use directly!
4249 * Starting part of the surrounding divs for custom corners
4251 * @param boolean $clearfix, add CLASS "clearfix" to the inner div against collapsing
4252 * @param string $classes
4253 * @param mixed $idbase, optionally, define one idbase to be added to all the elements in the corners
4256 function _print_custom_corners_start($clearfix=false, $classes='', $idbase='') {
4257 /// Analise if we want ids for the custom corner elements
4265 $id = 'id="'.$idbase.'" ';
4266 $idbt = 'id="'.$idbase.'-bt" ';
4267 $idi1 = 'id="'.$idbase.'-i1" ';
4268 $idi2 = 'id="'.$idbase.'-i2" ';
4269 $idi3 = 'id="'.$idbase.'-i3" ';
4272 /// Calculate current level
4273 $level = open_containers();
4276 $output = '<div '.$id.'class="wrap wraplevel'.$level.' '.$classes.'">'."\n";
4277 $output .= '<div '.$idbt.'class="bt"><div> </div></div>';
4279 $output .= '<div '.$idi1.'class="i1"><div '.$idi2.'class="i2">';
4280 $output .= (!empty($clearfix)) ?
'<div '.$idi3.'class="i3 clearfix">' : '<div '.$idi3.'class="i3">';
4287 * Internal function - do not use directly!
4288 * Ending part of the surrounding divs for custom corners
4289 * @param string $idbase
4292 function _print_custom_corners_end($idbase) {
4293 /// Analise if we want ids for the custom corner elements
4297 $idbb = 'id="' . $idbase . '-bb" ';
4301 $output = '</div></div></div>';
4303 $output .= '<div '.$idbb.'class="bb"><div> </div></div>'."\n";
4304 $output .= '</div>';
4311 * Print a self contained form with a single submit button.
4313 * @param string $link used as the action attribute on the form, so the URL that will be hit if the button is clicked.
4314 * @param array $options these become hidden form fields, so these options get passed to the script at $link.
4315 * @param string $label the caption that appears on the button.
4316 * @param string $method HTTP method used on the request of the button is clicked. 'get' or 'post'.
4317 * @param string $target no longer used.
4318 * @param boolean $return if false, output the form directly, otherwise return the HTML as a string.
4319 * @param string $tooltip a tooltip to add to the button as a title attribute.
4320 * @param boolean $disabled if true, the button will be disabled.
4321 * @param string $jsconfirmmessage if not empty then display a confirm dialogue with this string as the question.
4322 * @return string / nothing depending on the $return paramter.
4324 function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='', $disabled = false, $jsconfirmmessage='') {
4326 $link = str_replace('"', '"', $link); //basic XSS protection
4327 $output .= '<div class="singlebutton">';
4328 // taking target out, will need to add later target="'.$target.'"
4329 $output .= '<form action="'. $link .'" method="'. $method .'">';
4332 foreach ($options as $name => $value) {
4333 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
4337 $tooltip = 'title="' . s($tooltip) . '"';
4342 $disabled = 'disabled="disabled"';
4346 if ($jsconfirmmessage){
4347 $jsconfirmmessage = addslashes_js($jsconfirmmessage);
4348 $jsconfirmmessage = 'onclick="return confirm(\''. $jsconfirmmessage .'\');" ';
4350 $output .= '<input type="submit" value="'. s($label) ."\" $tooltip $disabled $jsconfirmmessage/></div></form></div>";
4361 * Print a spacer image with the option of including a line break.
4363 * @param int $height ?
4364 * @param int $width ?
4365 * @param boolean $br ?
4366 * @todo Finish documenting this function
4368 function print_spacer($height=1, $width=1, $br=true, $return=false) {
4372 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot
.'/pix/spacer.gif" alt="" />';
4374 $output .= '<br />'."\n";
4385 * Given the path to a picture file in a course, or a URL,
4386 * this function includes the picture in the page.
4388 * @param string $path ?
4389 * @param int $courseid ?
4390 * @param int $height ?
4391 * @param int $width ?
4392 * @param string $link ?
4393 * @todo Finish documenting this function
4395 function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
4400 $height = 'height="'. $height .'"';
4403 $width = 'width="'. $width .'"';
4406 $output .= '<a href="'. $link .'">';
4408 if (substr(strtolower($path), 0, 7) == 'http://') {
4409 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
4411 } else if ($courseid) {
4412 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
4413 require_once($CFG->libdir
.'/filelib.php');
4414 $output .= get_file_url("$courseid/$path");
4417 $output .= 'Error: must pass URL or course';
4431 * Print the specified user's avatar.
4433 * @param mixed $user Should be a $user object with at least fields id, picture, imagealt, firstname, lastname
4434 * If any of these are missing, or if a userid is passed, the the database is queried. Avoid this
4435 * if at all possible, particularly for reports. It is very bad for performance.
4436 * @param int $courseid The course id. Used when constructing the link to the user's profile.
4437 * @param boolean $picture The picture to print. By default (or if NULL is passed) $user->picture is used.
4438 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
4439 * @param boolean $return If false print picture to current page, otherwise return the output as string
4440 * @param boolean $link enclose printed image in a link the user's profile (default true).
4441 * @param string $target link target attribute. Makes the profile open in a popup window.
4442 * @param boolean $alttext add non-blank alt-text to the image. (Default true, set to false for purely
4443 * decorative images, or where the username will be printed anyway.)
4444 * @return string or nothing, depending on $return.
4446 function print_user_picture($user, $courseid, $picture=NULL, $size=0, $return=false, $link=true, $target='', $alttext=true) {
4450 // only touch the DB if we are missing data...
4451 if (is_object($user)) {
4452 // Note - both picture and imagealt _can_ be empty
4453 // what we are trying to see here is if they have been fetched
4454 // from the DB. We should use isset() _except_ that some installs
4455 // have those fields as nullable, and isset() will return false
4456 // on null. The only safe thing is to ask array_key_exists()
4457 // which works on objects. property_exists() isn't quite
4458 // what we want here...
4459 if (! (array_key_exists('picture', $user)
4460 && ($alttext && array_key_exists('imagealt', $user)
4461 ||
(isset($user->firstname
) && isset($user->lastname
)))) ) {
4467 // we need firstname, lastname, imagealt, can't escape...
4470 $userobj = new StdClass
; // fake it to save DB traffic
4471 $userobj->id
= $user;
4472 $userobj->picture
= $picture;
4473 $user = clone($userobj);
4478 $user = get_record('user','id',$user, '', '', '', '', 'id,firstname,lastname,imagealt');
4482 $url = '/user/view.php?id='. $user->id
.'&course='. $courseid ;
4484 $target='onclick="return openpopup(\''.$url.'\');"';
4486 $output = '<a '.$target.' href="'. $CFG->wwwroot
. $url .'">';
4493 } else if ($size === true or $size == 1) {
4496 } else if ($size >= 50) {
4501 $class = "userpicture";
4503 if (is_null($picture) and !empty($user->picture
)) {
4504 $picture = $user->picture
;
4507 if ($picture) { // Print custom user picture
4508 require_once($CFG->libdir
.'/filelib.php');
4509 $src = get_file_url($user->id
.'/'.$file.'.jpg', null, 'user');
4510 } else { // Print default user pictures (use theme version if available)
4511 $class .= " defaultuserpic";
4512 $src = "$CFG->pixpath/u/$file.png";
4516 if (!empty($user->imagealt
)) {
4517 $imagealt = $user->imagealt
;
4519 $imagealt = get_string('pictureof','',fullname($user));
4523 $output .= "<img class=\"$class\" src=\"$src\" height=\"$size\" width=\"$size\" alt=\"".s($imagealt).'" />';
4536 * Prints a summary of a user in a nice little box.
4540 * @param user $user A {@link $USER} object representing a user
4541 * @param course $course A {@link $COURSE} object representing a course
4543 function print_user($user, $course, $messageselect=false, $return=false) {
4553 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
4554 if (isset($user->context
->id
)) {
4555 $usercontext = $user->context
;
4557 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
);
4560 if (empty($string)) { // Cache all the strings for the rest of the page
4562 $string->email
= get_string('email');
4563 $string->city
= get_string('city');
4564 $string->lastaccess
= get_string('lastaccess');
4565 $string->activity
= get_string('activity');
4566 $string->unenrol
= get_string('unenrol');
4567 $string->loginas
= get_string('loginas');
4568 $string->fullprofile
= get_string('fullprofile');
4569 $string->role
= get_string('role');
4570 $string->name
= get_string('name');
4571 $string->never
= get_string('never');
4573 $datestring->day
= get_string('day');
4574 $datestring->days
= get_string('days');
4575 $datestring->hour
= get_string('hour');
4576 $datestring->hours
= get_string('hours');
4577 $datestring->min
= get_string('min');
4578 $datestring->mins
= get_string('mins');
4579 $datestring->sec
= get_string('sec');
4580 $datestring->secs
= get_string('secs');
4581 $datestring->year
= get_string('year');
4582 $datestring->years
= get_string('years');
4584 $countries = get_list_of_countries();
4587 /// Get the hidden field list
4588 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
4589 $hiddenfields = array();
4591 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
4594 $output .= '<table class="userinfobox">';
4596 $output .= '<td class="left side">';
4597 $output .= print_user_picture($user, $course->id
, $user->picture
, true, true);
4599 $output .= '<td class="content">';
4600 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
4601 $output .= '<div class="info">';
4602 if (!empty($user->role
) and ($user->role
<> $course->teacher
)) {
4603 $output .= $string->role
.': '. $user->role
.'<br />';
4605 if ($user->maildisplay
== 1 or ($user->maildisplay
== 2 and ($course->id
!= SITEID
) and !isguest()) or
4606 has_capability('moodle/course:viewhiddenuserfields', $context)) {
4607 $output .= $string->email
.': <a href="mailto:'. $user->email
.'">'. $user->email
.'</a><br />';
4609 if (($user->city
or $user->country
) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
4610 $output .= $string->city
.': ';
4611 if ($user->city
&& !isset($hiddenfields['city'])) {
4612 $output .= $user->city
;
4614 if (!empty($countries[$user->country
]) && !isset($hiddenfields['country'])) {
4615 if ($user->city
&& !isset($hiddenfields['city'])) {
4618 $output .= $countries[$user->country
];
4620 $output .= '<br />';
4623 if (!isset($hiddenfields['lastaccess'])) {
4624 if ($user->lastaccess
) {
4625 $output .= $string->lastaccess
.': '. userdate($user->lastaccess
);
4626 $output .= ' ('. format_time(time() - $user->lastaccess
, $datestring) .')';
4628 $output .= $string->lastaccess
.': '. $string->never
;
4631 $output .= '</div></td><td class="links">';
4633 if ($CFG->bloglevel
> 0) {
4634 $output .= '<a href="'.$CFG->wwwroot
.'/blog/index.php?userid='.$user->id
.'">'.get_string('blogs','blog').'</a><br />';
4637 if (!empty($CFG->enablenotes
) and (has_capability('moodle/notes:manage', $context) ||
has_capability('moodle/notes:view', $context))) {
4638 $output .= '<a href="'.$CFG->wwwroot
.'/notes/index.php?course=' . $course->id
. '&user='.$user->id
.'">'.get_string('notes','notes').'</a><br />';
4641 if (has_capability('moodle/site:viewreports', $context) or has_capability('moodle/user:viewuseractivitiesreport', $usercontext)) {
4642 $output .= '<a href="'. $CFG->wwwroot
.'/course/user.php?id='. $course->id
.'&user='. $user->id
.'">'. $string->activity
.'</a><br />';
4644 if (has_capability('moodle/role:assign', $context) and get_user_roles($context, $user->id
, false)) { // I can unassing and user has some role
4645 $output .= '<a href="'. $CFG->wwwroot
.'/course/unenrol.php?id='. $course->id
.'&user='. $user->id
.'">'. $string->unenrol
.'</a><br />';
4647 if ($USER->id
!= $user->id
&& empty($USER->realuser
) && has_capability('moodle/user:loginas', $context) &&
4648 ! has_capability('moodle/site:doanything', $context, $user->id
, false)) {
4649 $output .= '<a href="'. $CFG->wwwroot
.'/course/loginas.php?id='. $course->id
.'&user='. $user->id
.'&sesskey='. sesskey() .'">'. $string->loginas
.'</a><br />';
4651 $output .= '<a href="'. $CFG->wwwroot
.'/user/view.php?id='. $user->id
.'&course='. $course->id
.'">'. $string->fullprofile
.'...</a>';
4653 if (!empty($messageselect)) {
4654 $output .= '<br /><input type="checkbox" name="user'.$user->id
.'" /> ';
4657 $output .= '</td></tr></table>';
4667 * Print a specified group's avatar.
4669 * @param group $group A single {@link group} object OR array of groups.
4670 * @param int $courseid The course ID.
4671 * @param boolean $large Default small picture, or large.
4672 * @param boolean $return If false print picture, otherwise return the output as string
4673 * @param boolean $link Enclose image in a link to view specified course?
4675 * @todo Finish documenting this function
4677 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
4680 if (is_array($group)) {
4682 foreach($group as $g) {
4683 $output .= print_group_picture($g, $courseid, $large, true, $link);
4693 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
4695 if ($group->hidepicture
and !has_capability('moodle/course:managegroups', $context)) {
4699 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4700 $output = '<a href="'. $CFG->wwwroot
.'/user/index.php?id='. $courseid .'&group='. $group->id
.'">';
4709 if ($group->picture
) { // Print custom group picture
4710 require_once($CFG->libdir
.'/filelib.php');
4711 $grouppictureurl = get_file_url($group->id
.'/'.$file.'.jpg', null, 'usergroup');
4712 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
4713 ' alt="'.s(get_string('group').' '.$group->name
).'" title="'.s($group->name
).'"/>';
4715 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4727 * Print a png image.
4729 * @param string $url ?
4730 * @param int $sizex ?
4731 * @param int $sizey ?
4732 * @param boolean $return ?
4733 * @param string $parameters ?
4734 * @todo Finish documenting this function
4736 function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
4740 if (!isset($recentIE)) {
4741 $recentIE = check_browser_version('MSIE', '5.0');
4744 if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
4745 $output .= '<img src="'. $CFG->pixpath
.'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
4746 ' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
4747 ' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
4748 "'$url', sizingMethod='scale') ".
4749 ' '. $parameters .' />';
4751 $output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
4762 * Print a nicely formatted table.
4764 * @param array $table is an object with several properties.
4766 * <li>$table->head - An array of heading names.
4767 * <li>$table->align - An array of column alignments
4768 * <li>$table->size - An array of column sizes
4769 * <li>$table->wrap - An array of "nowrap"s or nothing
4770 * <li>$table->data[] - An array of arrays containing the data.
4771 * <li>$table->width - A percentage of the page
4772 * <li>$table->tablealign - Align the whole table
4773 * <li>$table->cellpadding - Padding on each cell
4774 * <li>$table->cellspacing - Spacing between cells
4775 * <li>$table->class - class attribute to put on the table
4776 * <li>$table->id - id attribute to put on the table.
4777 * <li>$table->rowclass[] - classes to add to particular rows.
4778 * <li>$table->summary - Description of the contents for screen readers.
4780 * @param bool $return whether to return an output string or echo now
4781 * @return boolean or $string
4782 * @todo Finish documenting this function
4784 function print_table($table, $return=false) {
4787 if (isset($table->align
)) {
4788 foreach ($table->align
as $key => $aa) {
4790 $align[$key] = ' text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
4796 if (isset($table->size
)) {
4797 foreach ($table->size
as $key => $ss) {
4799 $size[$key] = ' width:'. $ss .';';
4805 if (isset($table->wrap
)) {
4806 foreach ($table->wrap
as $key => $ww) {
4808 $wrap[$key] = ' white-space:nowrap;';
4815 if (empty($table->width
)) {
4816 $table->width
= '80%';
4819 if (empty($table->tablealign
)) {
4820 $table->tablealign
= 'center';
4823 if (!isset($table->cellpadding
)) {
4824 $table->cellpadding
= '5';
4827 if (!isset($table->cellspacing
)) {
4828 $table->cellspacing
= '1';
4831 if (empty($table->class)) {
4832 $table->class = 'generaltable';
4835 $tableid = empty($table->id
) ?
'' : 'id="'.$table->id
.'"';
4837 $output .= '<table width="'.$table->width
.'" ';
4838 if (!empty($table->summary
)) {
4839 $output .= " summary=\"$table->summary\"";
4841 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
4845 if (!empty($table->head
)) {
4846 $countcols = count($table->head
);
4848 $keys=array_keys($table->head
);
4849 $lastkey = end($keys);
4850 foreach ($table->head
as $key => $heading) {
4852 if (!isset($size[$key])) {
4855 if (!isset($align[$key])) {
4858 if ($key == $lastkey) {
4859 $extraclass = ' lastcol';
4864 $output .= '<th style="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.$extraclass.'" scope="col">'. $heading .'</th>';
4866 $output .= '</tr>'."\n";
4869 if (!empty($table->data
)) {
4871 $keys=array_keys($table->data
);
4872 $lastrowkey = end($keys);
4873 foreach ($table->data
as $key => $row) {
4874 $oddeven = $oddeven ?
0 : 1;
4875 if (!isset($table->rowclass
[$key])) {
4876 $table->rowclass
[$key] = '';
4878 if ($key == $lastrowkey) {
4879 $table->rowclass
[$key] .= ' lastrow';
4881 $output .= '<tr class="r'.$oddeven.' '.$table->rowclass
[$key].'">'."\n";
4882 if ($row == 'hr' and $countcols) {
4883 $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
4884 } else { /// it's a normal row of data
4885 $keys2=array_keys($row);
4886 $lastkey = end($keys2);
4887 foreach ($row as $key => $item) {
4888 if (!isset($size[$key])) {
4891 if (!isset($align[$key])) {
4894 if (!isset($wrap[$key])) {
4897 if ($key == $lastkey) {
4898 $extraclass = ' lastcol';
4902 $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.$extraclass.'">'. $item .'</td>';
4905 $output .= '</tr>'."\n";
4908 $output .= '</table>'."\n";
4918 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
4919 static $strftimerecent = null;
4922 if (is_null($viewfullnames)) {
4923 $context = get_context_instance(CONTEXT_SYSTEM
);
4924 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
4927 if (is_null($strftimerecent)) {
4928 $strftimerecent = get_string('strftimerecent');
4931 $output .= '<div class="head">';
4932 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
4933 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
4934 $output .= '</div>';
4935 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
4946 * Prints a basic textarea field.
4949 * @param boolean $usehtmleditor ?
4950 * @param int $rows ?
4951 * @param int $cols ?
4952 * @param null $width <b>Legacy field no longer used!</b> Set to zero to get control over mincols
4953 * @param null $height <b>Legacy field no longer used!</b> Set to zero to get control over minrows
4954 * @param string $name ?
4955 * @param string $value ?
4956 * @param int $courseid ?
4957 * @todo Finish documenting this function
4959 function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $courseid=0, $return=false, $id='') {
4960 /// $width and height are legacy fields and no longer used as pixels like they used to be.
4961 /// However, you can set them to zero to override the mincols and minrows values below.
4963 global $CFG, $COURSE, $HTTPSPAGEREQUIRED;
4964 static $scriptcount = 0; // For loading the htmlarea script only once.
4971 $id = 'edit-'.$name;
4974 if ( empty($CFG->editorsrc
) ) { // for backward compatibility.
4975 if (empty($courseid)) {
4976 $courseid = $COURSE->id
;
4979 if ($usehtmleditor) {
4980 if (!empty($courseid) and has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE
, $courseid))) {
4981 $httpsrequired = empty($HTTPSPAGEREQUIRED) ?
'' : '&httpsrequired=1';
4982 // needed for course file area browsing in image insert plugin
4983 $str .= ($scriptcount < 1) ?
'<script type="text/javascript" src="'.
4984 $CFG->httpswwwroot
.'/lib/editor/htmlarea/htmlarea.php?id='.$courseid.$httpsrequired.'"></script>'."\n" : '';
4986 $httpsrequired = empty($HTTPSPAGEREQUIRED) ?
'' : '?httpsrequired=1';
4987 $str .= ($scriptcount < 1) ?
'<script type="text/javascript" src="'.
4988 $CFG->httpswwwroot
.'/lib/editor/htmlarea/htmlarea.php'.$httpsrequired.'"></script>'."\n" : '';
4991 $str .= ($scriptcount < 1) ?
'<script type="text/javascript" src="'.
4992 $CFG->httpswwwroot
.'/lib/editor/htmlarea/lang/en.php?id='.$courseid.'"></script>'."\n" : '';
4995 if ($height) { // Usually with legacy calls
4996 if ($rows < $minrows) {
5000 if ($width) { // Usually with legacy calls
5001 if ($cols < $mincols) {
5007 $str .= '<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">';
5008 if ($usehtmleditor) {
5009 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
5013 $str .= '</textarea>'."\n";
5015 if ($usehtmleditor) {
5016 // Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
5017 $str .= '<script type="text/javascript">
5019 document.write(\''.addslashes_js(editorshortcutshelpbutton()).'\');
5031 * Sets up the HTML editor on textareas in the current page.
5032 * If a field name is provided, then it will only be
5033 * applied to that field - otherwise it will be used
5034 * on every textarea in the page.
5036 * In most cases no arguments need to be supplied
5038 * @param string $name Form element to replace with HTMl editor by name
5040 function use_html_editor($name='', $editorhidebuttons='', $id='') {
5043 $editor = 'editor_'.md5($name); //name might contain illegal characters
5045 $id = 'edit-'.$name;
5047 echo "\n".'<script type="text/javascript" defer="defer">'."\n";
5048 echo '//<![CDATA['."\n\n"; // Extra \n is to fix odd wiki problem, MDL-8185
5049 echo "$editor = new HTMLArea('$id');\n";
5050 echo "var config = $editor.config;\n";
5052 echo print_editor_config($editorhidebuttons);
5054 if (empty($THEME->htmleditorpostprocess
)) {
5056 echo "\nHTMLArea.replaceAll($editor.config);\n";
5058 echo "\n$editor.generate();\n";
5062 echo "\nvar HTML_name = '';";
5064 echo "\nvar HTML_name = \"$name;\"";
5066 echo "\nvar HTML_editor = $editor;";
5069 echo '</script>'."\n";
5072 function print_editor_config($editorhidebuttons='', $return=false) {
5075 $str = "config.pageStyle = \"body {";
5077 if (!(empty($CFG->editorbackgroundcolor
))) {
5078 $str .= " background-color: $CFG->editorbackgroundcolor;";
5081 if (!(empty($CFG->editorfontfamily
))) {
5082 $str .= " font-family: $CFG->editorfontfamily;";
5085 if (!(empty($CFG->editorfontsize
))) {
5086 $str .= " font-size: $CFG->editorfontsize;";
5090 $str .= "config.killWordOnPaste = ";
5091 $str .= (empty($CFG->editorkillword
)) ?
"false":"true";
5093 $str .= 'config.fontname = {'."\n";
5095 $fontlist = isset($CFG->editorfontlist
) ?
explode(';', $CFG->editorfontlist
) : array();
5096 $i = 1; // Counter is used to get rid of the last comma.
5098 foreach ($fontlist as $fontline) {
5099 if (!empty($fontline)) {
5103 list($fontkey, $fontvalue) = split(':', $fontline);
5104 $str .= '"'. $fontkey ."\":\t'". $fontvalue ."'";
5111 if (!empty($editorhidebuttons)) {
5112 $str .= "\nconfig.hideSomeButtons(\" ". $editorhidebuttons ." \");\n";
5113 } else if (!empty($CFG->editorhidebuttons
)) {
5114 $str .= "\nconfig.hideSomeButtons(\" ". $CFG->editorhidebuttons
." \");\n";
5117 if (!empty($CFG->editorspelling
) && !empty($CFG->aspellpath
)) {
5118 $str .= print_speller_code($CFG->htmleditor
, true);
5128 * Returns a turn edit on/off button for course in a self contained form.
5129 * Used to be an icon, but it's now a simple form button
5131 * Note that the caller is responsible for capchecks.
5135 * @param int $courseid The course to update by id as found in 'course' table
5138 function update_course_icon($courseid) {
5141 if (!empty($USER->editing
)) {
5142 $string = get_string('turneditingoff');
5145 $string = get_string('turneditingon');
5149 return '<form '.$CFG->frametarget
.' method="get" action="'.$CFG->wwwroot
.'/course/view.php">'.
5151 '<input type="hidden" name="id" value="'.$courseid.'" />'.
5152 '<input type="hidden" name="edit" value="'.$edit.'" />'.
5153 '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
5154 '<input type="submit" value="'.$string.'" />'.
5159 * Returns a little popup menu for switching roles
5163 * @param int $courseid The course to update by id as found in 'course' table
5166 function switchroles_form($courseid) {
5171 if (!$context = get_context_instance(CONTEXT_COURSE
, $courseid)) {
5175 if (!empty($USER->access
['rsw'][$context->path
])){ // Just a button to return to normal
5177 $options['id'] = $courseid;
5178 $options['sesskey'] = sesskey();
5179 $options['switchrole'] = 0;
5181 return print_single_button($CFG->wwwroot
.'/course/view.php', $options,
5182 get_string('switchrolereturn'), 'post', '_self', true);
5185 if (has_capability('moodle/role:switchroles', $context)) {
5186 if (!$roles = get_assignable_roles_for_switchrole($context)) {
5187 return ''; // Nothing to show!
5189 // unset default user role - it would not work
5190 unset($roles[$CFG->guestroleid
]);
5191 return popup_form($CFG->wwwroot
.'/course/view.php?id='.$courseid.'&sesskey='.sesskey().'&switchrole=',
5192 $roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
5200 * Returns a turn edit on/off button for course in a self contained form.
5201 * Used to be an icon, but it's now a simple form button
5205 * @param int $courseid The course to update by id as found in 'course' table
5208 function update_mymoodle_icon() {
5212 if (!empty($USER->editing
)) {
5213 $string = get_string('updatemymoodleoff');
5216 $string = get_string('updatemymoodleon');
5220 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
5222 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5223 "<input type=\"submit\" value=\"$string\" /></div></form>";
5227 * Returns a turn edit on/off button for tag in a self contained form.
5233 function update_tag_button($tagid) {
5237 if (!empty($USER->editing
)) {
5238 $string = get_string('turneditingoff');
5241 $string = get_string('turneditingon');
5245 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/tag/index.php\">".
5247 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5248 "<input type=\"hidden\" name=\"id\" value=\"$tagid\" />".
5249 "<input type=\"submit\" value=\"$string\" /></div></form>";
5253 * Prints the editing button on a module "view" page
5256 * @param type description
5257 * @todo Finish documenting this function
5259 function update_module_button($moduleid, $courseid, $string) {
5262 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE
, $moduleid))) {
5263 $string = get_string('updatethis', '', $string);
5265 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
5267 "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
5268 "<input type=\"hidden\" name=\"return\" value=\"true\" />".
5269 "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
5270 "<input type=\"submit\" value=\"$string\" /></div></form>";
5277 * Prints the editing button on search results listing
5278 * For bulk move courses to another category
5281 function update_categories_search_button($search,$page,$perpage) {
5284 // not sure if this capability is the best here
5285 if (has_capability('moodle/category:manage', get_context_instance(CONTEXT_SYSTEM
))) {
5286 if (!empty($USER->categoryediting
)) {
5287 $string = get_string("turneditingoff");
5291 $string = get_string("turneditingon");
5295 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
5297 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5298 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5299 "<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
5300 "<input type=\"hidden\" name=\"page\" value=\"$page\" />".
5301 "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
5302 "<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
5307 * Given a course and a (current) coursemodule
5308 * This function returns a small popup menu with all the
5309 * course activity modules in it, as a navigation menu
5310 * The data is taken from the serialised array stored in
5313 * @param course $course A {@link $COURSE} object.
5314 * @param course $cm A {@link $COURSE} object.
5315 * @param string $targetwindow ?
5317 * @todo Finish documenting this function
5319 function navmenu($course, $cm=NULL, $targetwindow='self') {
5321 global $CFG, $THEME, $USER;
5323 if (empty($THEME->navmenuwidth
)) {
5326 $width = $THEME->navmenuwidth
;
5333 if ($course->format
== 'weeks') {
5334 $strsection = get_string('week');
5336 $strsection = get_string('topic');
5338 $strjumpto = get_string('jumpto');
5340 $modinfo = get_fast_modinfo($course);
5341 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
5346 $previousmod = NULL;
5353 $menustyle = array();
5355 $sections = get_records('course_sections','course',$course->id
,'section','section,visible,summary');
5357 if (!empty($THEME->makenavmenulist
)) { /// A hack to produce an XHTML navmenu list for use in themes
5358 $THEME->navmenulist
= navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
5361 foreach ($modinfo->cms
as $mod) {
5362 if ($mod->modname
== 'label') {
5366 if ($mod->sectionnum
> $course->numsections
) { /// Don't show excess hidden sections
5370 if (!$mod->uservisible
) { // do not icnlude empty sections at all
5374 if ($mod->sectionnum
> 0 and $section != $mod->sectionnum
) {
5375 $thissection = $sections[$mod->sectionnum
];
5377 if ($thissection->visible
or !$course->hiddensections
or
5378 has_capability('moodle/course:viewhiddensections', $context)) {
5379 $thissection->summary
= strip_tags(format_string($thissection->summary
,true));
5380 if ($course->format
== 'weeks' or empty($thissection->summary
)) {
5381 $menu[] = '--'.$strsection ." ". $mod->sectionnum
;
5383 if (strlen($thissection->summary
) < ($width-3)) {
5384 $menu[] = '--'.$thissection->summary
;
5386 $menu[] = '--'.substr($thissection->summary
, 0, $width).'...';
5389 $section = $mod->sectionnum
;
5391 // no activities from this hidden section shown
5396 $url = $mod->modname
.'/view.php?id='. $mod->id
;
5397 if ($flag) { // the current mod is the "next" mod
5401 $localname = $mod->name
;
5402 if ($cm == $mod->id
) {
5405 $backmod = $previousmod;
5406 $flag = true; // set flag so we know to use next mod for "next"
5407 $localname = $strjumpto;
5410 $localname = strip_tags(format_string($localname,true));
5411 $tl=textlib_get_instance();
5412 if ($tl->strlen($localname) > ($width+
5)) {
5413 $localname = $tl->substr($localname, 0, $width).'...';
5415 if (!$mod->visible
) {
5416 $localname = '('.$localname.')';
5419 $menu[$url] = $localname;
5420 if (empty($THEME->navmenuiconshide
)) {
5421 $menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath
.'/'.$mod->modname
.'/icon.gif);"'; // Unfortunately necessary to do this here
5423 $previousmod = $mod;
5425 //Accessibility: added Alt text, replaced > < with 'silent' character and 'accesshide' text.
5427 if ($selectmod and has_capability('coursereport/log:view', $context)) {
5428 $logstext = get_string('alllogs');
5429 $logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
5430 $CFG->frametarget
.' onclick="this.target=\''.$CFG->framename
.'\';"'.' href="'.
5431 $CFG->wwwroot
.'/course/report/log/index.php?chooselog=1&user=0&date=0&id='.
5432 $course->id
.'&modid='.$selectmod->id
.'">'.
5433 '<img class="icon log" src="'.$CFG->pixpath
.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
5437 $backtext= get_string('activityprev', 'access');
5438 $backmod = '<li><form action="'.$CFG->wwwroot
.'/mod/'.$backmod->modname
.'/view.php" '.$CFG->frametarget
.' '.
5439 'onclick="this.target=\''.$CFG->framename
.'\';"'.'><fieldset class="invisiblefieldset">'.
5440 '<input type="hidden" name="id" value="'.$backmod->id
.'" />'.
5441 '<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
5442 '</button></fieldset></form></li>';
5445 $nexttext= get_string('activitynext', 'access');
5446 $nextmod = '<li><form action="'.$CFG->wwwroot
.'/mod/'.$nextmod->modname
.'/view.php" '.$CFG->frametarget
.' '.
5447 'onclick="this.target=\''.$CFG->framename
.'\';"'.'><fieldset class="invisiblefieldset">'.
5448 '<input type="hidden" name="id" value="'.$nextmod->id
.'" />'.
5449 '<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
5450 '</button></fieldset></form></li>';
5453 return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
5454 '<li>'.popup_form($CFG->wwwroot
.'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
5455 '', '', true, $targetwindow, '', $menustyle).'</li>'.
5456 $nextmod . '</ul>'."\n".'</div>';
5461 * This function returns a small popup menu with all the
5462 * course activity modules in it, as a navigation menu
5463 * outputs a simple list structure in XHTML
5464 * The data is taken from the serialised array stored in
5467 * @param course $course A {@link $COURSE} object.
5469 * @todo Finish documenting this function
5471 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
5478 $doneheading = false;
5480 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
5482 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
5483 foreach ($modinfo->cms
as $mod) {
5484 if ($mod->modname
== 'label') {
5488 if ($mod->sectionnum
> $course->numsections
) { /// Don't show excess hidden sections
5492 if (!$mod->uservisible
) { // do not icnlude empty sections at all
5496 if ($mod->sectionnum
>= 0 and $section != $mod->sectionnum
) {
5497 $thissection = $sections[$mod->sectionnum
];
5499 if ($thissection->visible
or !$course->hiddensections
or
5500 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
5501 $thissection->summary
= strip_tags(format_string($thissection->summary
,true));
5502 if (!$doneheading) {
5503 $menu[] = '</ul></li>';
5505 if ($course->format
== 'weeks' or empty($thissection->summary
)) {
5506 $item = $strsection ." ". $mod->sectionnum
;
5508 if (strlen($thissection->summary
) < ($width-3)) {
5509 $item = $thissection->summary
;
5511 $item = substr($thissection->summary
, 0, $width).'...';
5514 $menu[] = '<li class="section"><span>'.$item.'</span>';
5516 $doneheading = true;
5518 $section = $mod->sectionnum
;
5520 // no activities from this hidden section shown
5525 $url = $mod->modname
.'/view.php?id='. $mod->id
;
5526 $mod->name
= strip_tags(format_string(urldecode($mod->name
),true));
5527 if (strlen($mod->name
) > ($width+
5)) {
5528 $mod->name
= substr($mod->name
, 0, $width).'...';
5530 if (!$mod->visible
) {
5531 $mod->name
= '('.$mod->name
.')';
5533 $class = 'activity '.$mod->modname
;
5534 $class .= ($cmid == $mod->id
) ?
' selected' : '';
5535 $menu[] = '<li class="'.$class.'">'.
5536 '<img src="'.$CFG->modpixpath
.'/'.$mod->modname
.'/icon.gif" alt="" />'.
5537 '<a href="'.$CFG->wwwroot
.'/mod/'.$url.'">'.$mod->name
.'</a></li>';
5541 $menu[] = '</ul></li>';
5543 $menu[] = '</ul></li></ul>';
5545 return implode("\n", $menu);
5549 * Prints form items with the names $day, $month and $year
5551 * @param string $day fieldname
5552 * @param string $month fieldname
5553 * @param string $year fieldname
5554 * @param int $currenttime A default timestamp in GMT
5555 * @param boolean $return
5557 function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
5559 if (!$currenttime) {
5560 $currenttime = time();
5562 $currentdate = usergetdate($currenttime);
5564 for ($i=1; $i<=31; $i++
) {
5567 for ($i=1; $i<=12; $i++
) {
5568 $months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
5570 for ($i=1970; $i<=2020; $i++
) {
5574 // Build or print result
5576 // Note: There should probably be a fieldset around these fields as they are
5577 // clearly grouped. However this causes problems with display. See Mozilla
5579 $result.='<label class="accesshide" for="menu'.$day.'">'.get_string('day','form').'</label>';
5580 $result.=choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', true);
5581 $result.='<label class="accesshide" for="menu'.$month.'">'.get_string('month','form').'</label>';
5582 $result.=choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', true);
5583 $result.='<label class="accesshide" for="menu'.$year.'">'.get_string('year','form').'</label>';
5584 $result.=choose_from_menu($years, $year, $currentdate['year'], '', '', '0', true);
5594 *Prints form items with the names $hour and $minute
5596 * @param string $hour fieldname
5597 * @param string ? $minute fieldname
5598 * @param $currenttime A default timestamp in GMT
5599 * @param int $step minute spacing
5600 * @param boolean $return
5602 function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
5604 if (!$currenttime) {
5605 $currenttime = time();
5607 $currentdate = usergetdate($currenttime);
5609 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
5611 for ($i=0; $i<=23; $i++
) {
5612 $hours[$i] = sprintf("%02d",$i);
5614 for ($i=0; $i<=59; $i+
=$step) {
5615 $minutes[$i] = sprintf("%02d",$i);
5618 // Build or print result
5620 // Note: There should probably be a fieldset around these fields as they are
5621 // clearly grouped. However this causes problems with display. See Mozilla
5623 $result.='<label class="accesshide" for="menu'.$hour.'">'.get_string('hour','form').'</label>';
5624 $result.=choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',true);
5625 $result.='<label class="accesshide" for="menu'.$minute.'">'.get_string('minute','form').'</label>';
5626 $result.=choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',true);
5636 * Prints time limit value selector
5639 * @param int $timelimit default
5640 * @param string $unit
5641 * @param string $name
5642 * @param boolean $return
5644 function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
5652 // Max timelimit is sessiontimeout - 10 minutes.
5653 $maxvalue = ($CFG->sessiontimeout
/ 60) - 10;
5655 for ($i=1; $i<=$maxvalue; $i++
) {
5656 $minutes[$i] = $i.$unit;
5658 return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
5662 * Prints a grade menu (as part of an existing form) with help
5663 * Showing all possible numerical grades and scales
5666 * @param int $courseid ?
5667 * @param string $name ?
5668 * @param string $current ?
5669 * @param boolean $includenograde ?
5670 * @todo Finish documenting this function
5672 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
5677 $strscale = get_string('scale');
5678 $strscales = get_string('scales');
5680 $scales = get_scales_menu($courseid);
5681 foreach ($scales as $i => $scalename) {
5682 $grades[-$i] = $strscale .': '. $scalename;
5684 if ($includenograde) {
5685 $grades[0] = get_string('nograde');
5687 for ($i=100; $i>=1; $i--) {
5690 $output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
5692 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath
.'/help.gif" /></span>';
5693 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&list=true', 'ratingscales',
5694 $linkobject, 400, 500, $strscales, 'none', true);
5704 * Prints a scale menu (as part of an existing form) including help button
5705 * Just like {@link print_grade_menu()} but without the numeric grades
5707 * @param int $courseid ?
5708 * @param string $name ?
5709 * @param string $current ?
5710 * @todo Finish documenting this function
5712 function print_scale_menu($courseid, $name, $current, $return=false) {
5717 $strscales = get_string('scales');
5718 $output .= choose_from_menu(get_scales_menu($courseid), $name, $current, '', '', 0, true);
5720 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath
.'/help.gif" /></span>';
5721 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&list=true', 'ratingscales',
5722 $linkobject, 400, 500, $strscales, 'none', true);
5731 * Prints a help button about a scale
5734 * @param id $courseid ?
5735 * @param object $scale ?
5736 * @todo Finish documenting this function
5738 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
5743 $strscales = get_string('scales');
5745 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name
.'" src="'.$CFG->pixpath
.'/help.gif" /></span>';
5746 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&list=true&scaleid='. $scale->id
, 'ratingscale',
5747 $linkobject, 400, 500, $scale->name
, 'none', true);
5756 * Print an error page displaying an error message. New method - use this for new code.
5760 * @param string $errorcode The name of the string from error.php (or other specified file) to print
5761 * @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.
5762 * @param object $a Extra words and phrases that might be required in the error string
5763 * @param array $extralocations An array of strings with other locations to look for string files
5764 * @return does not return, terminates script
5766 function print_error($errorcode, $module='error', $link='', $a=NULL, $extralocations=NULL) {
5767 global $CFG, $SESSION, $THEME;
5769 if (empty($module) ||
$module === 'moodle' ||
$module === 'core') {
5773 $message = get_string($errorcode, $module, $a, $extralocations);
5774 if ($module === 'error' and strpos($message, '[[') === 0) {
5775 //search in moodle file if error specified - needed for backwards compatibility
5776 $message = get_string($errorcode, 'moodle', $a, $extralocations);
5779 if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
5780 if ( !empty($SESSION->fromurl
) ) {
5781 $link = $SESSION->fromurl
;
5782 unset($SESSION->fromurl
);
5784 $link = $CFG->wwwroot
.'/';
5788 if (!empty($CFG->errordocroot
)) {
5789 $errordocroot = $CFG->errordocroot
;
5790 } else if (!empty($CFG->docroot
)) {
5791 $errordocroot = $CFG->docroot
;
5793 $errordocroot = 'http://docs.moodle.org';
5796 if (defined('FULLME') && FULLME
== 'cron') {
5797 // Errors in cron should be mtrace'd.
5802 if ($module === 'error') {
5803 $modulelink = 'moodle';
5805 $modulelink = $module;
5808 $message = clean_text('<p class="errormessage">'.$message.'</p>'.
5809 '<p class="errorcode">'.
5810 '<a href="'.$errordocroot.'/en/error/'.$modulelink.'/'.$errorcode.'">'.
5811 get_string('moreinformation').'</a></p>');
5813 if (! defined('HEADER_PRINTED')) {
5814 //header not yet printed
5815 @header
('HTTP/1.0 404 Not Found');
5816 print_header(get_string('error'));
5818 print_container_end_all(false, $THEME->open_header_containers
);
5823 print_simple_box($message, '', '', '', '', 'errorbox');
5825 debugging('Stack trace:', DEBUG_DEVELOPER
);
5827 // in case we are logging upgrade in admin/index.php stop it
5828 if (function_exists('upgrade_log_finish')) {
5829 upgrade_log_finish();
5832 if (!empty($link)) {
5833 print_continue($link);
5838 for ($i=0;$i<512;$i++
) { // Padding to help IE work with 404
5845 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
5846 * Default errorcode is 1.
5848 * Very useful for perl-like error-handling:
5850 * do_somethting() or mdie("Something went wrong");
5852 * @param string $msg Error message
5853 * @param integer $errorcode Error code to emit
5855 function mdie($msg='', $errorcode=1) {
5856 trigger_error($msg);
5861 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
5862 * Should be used only with htmleditor or textarea.
5863 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
5867 function editorhelpbutton(){
5868 global $CFG, $SESSION;
5869 $items = func_get_args();
5871 $urlparams = array();
5873 foreach ($items as $item){
5874 if (is_array($item)){
5875 $urlparams[] = "keyword$i=".urlencode($item[0]);
5876 $urlparams[] = "title$i=".urlencode($item[1]);
5877 if (isset($item[2])){
5878 $urlparams[] = "module$i=".urlencode($item[2]);
5880 $titles[] = trim($item[1], ". \t");
5881 }elseif (is_string($item)){
5882 $urlparams[] = "button$i=".urlencode($item);
5885 $titles[] = get_string("helpreading");
5888 $titles[] = get_string("helpwriting");
5891 $titles[] = get_string("helpquestions");
5894 $titles[] = get_string("helpemoticons");
5897 $titles[] = get_string('helprichtext');
5900 $titles[] = get_string('helptext');
5903 error('Unknown help topic '.$item);
5908 if (count($titles)>1){
5909 //join last two items with an 'and'
5911 $a->one
= $titles[count($titles) - 2];
5912 $a->two
= $titles[count($titles) - 1];
5913 $titles[count($titles) - 2] = get_string('and', '', $a);
5914 unset($titles[count($titles) - 1]);
5916 $alttag = join (', ', $titles);
5918 $paramstring = join('&', $urlparams);
5919 $linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath
.'/help.gif" />';
5920 return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), 'popup', $linkobject, 400, 500, $alttag, 'none', true);
5924 * Print a help button.
5927 * @param string $page The keyword that defines a help page
5928 * @param string $title The title of links, rollover tips, alt tags etc
5929 * 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
5930 * @param string $module Which module is the page defined in
5931 * @param mixed $image Use a help image for the link? (true/false/"both")
5932 * @param boolean $linktext If true, display the title next to the help icon.
5933 * @param string $text If defined then this text is used in the page, and
5934 * the $page variable is ignored.
5935 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
5936 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
5938 * @todo Finish documenting this function
5940 function helpbutton ($page, $title, $module='moodle', $image=true, $linktext=false, $text='', $return=false,
5942 global $CFG, $COURSE;
5944 //warning if ever $text parameter is used
5945 //$text option won't work properly because the text needs to be always cleaned and,
5946 // when cleaned... html tags always break, so it's unusable.
5947 if ( isset($text) && $text!='') {
5948 debugging('Warning: it\'s not recommended to use $text parameter in helpbutton ($page=' . $page . ', $module=' . $module . ') function', DEBUG_DEVELOPER
);
5952 if (!empty($COURSE->lang
)) {
5953 $forcelang = $COURSE->lang
;
5958 if ($module == '') {
5962 if ($title == '' && $linktext == '') {
5963 debugging('Error in call to helpbutton function: at least one of $title and $linktext is required');
5966 // Warn users about new window for Accessibility
5967 $tooltip = get_string('helpprefix2', '', trim($title, ". \t")) .' ('.get_string('newwindow').')';
5973 // MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
5974 $linkobject .= $title.' ';
5975 $tooltip = get_string('helpwiththis');
5978 $linkobject .= $imagetext;
5980 $linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
5981 $CFG->pixpath
.'/help.gif" />';
5984 $linkobject .= $tooltip;
5989 $url = '/help.php?module='. $module .'&text='. s(urlencode($text).'&forcelang='.$forcelang);
5991 $url = '/help.php?module='. $module .'&file='. $page .'.html&forcelang='.$forcelang;
5994 $link = '<span class="helplink">'.
5995 link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
6006 * Print a help button.
6008 * Prints a special help button that is a link to the "live" emoticon popup
6011 * @param string $form ?
6012 * @param string $field ?
6013 * @todo Finish documenting this function
6015 function emoticonhelpbutton($form, $field, $return = false) {
6017 global $CFG, $SESSION;
6019 $SESSION->inserttextform
= $form;
6020 $SESSION->inserttextfield
= $field;
6021 $imagetext = '<img src="' . $CFG->pixpath
. '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
6022 $help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
6031 * Print a help button.
6033 * Prints a special help button for html editors (htmlarea in this case)
6036 function editorshortcutshelpbutton() {
6039 $imagetext = '<img src="' . $CFG->httpswwwroot
. '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
6040 get_string('editorshortcutkeys').'" class="iconkbhelp" />';
6042 return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
6046 * Print a message and exit.
6049 * @param string $message ?
6050 * @param string $link ?
6051 * @todo Finish documenting this function
6053 function notice ($message, $link='', $course=NULL) {
6054 global $CFG, $SITE, $THEME, $COURSE;
6056 $message = clean_text($message); // In case nasties are in here
6058 if (defined('FULLME') && FULLME
== 'cron') {
6059 // notices in cron should be mtrace'd.
6064 if (! defined('HEADER_PRINTED')) {
6065 //header not yet printed
6066 print_header(get_string('notice'));
6068 print_container_end_all(false, $THEME->open_header_containers
);
6071 print_box($message, 'generalbox', 'notice');
6072 print_continue($link);
6074 if (empty($course)) {
6075 print_footer($COURSE);
6077 print_footer($course);
6083 * Print a message along with "Yes" and "No" links for the user to continue.
6085 * @param string $message The text to display
6086 * @param string $linkyes The link to take the user to if they choose "Yes"
6087 * @param string $linkno The link to take the user to if they choose "No"
6088 * TODO Document remaining arguments
6090 function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
6094 $message = clean_text($message);
6095 $linkyes = clean_text($linkyes);
6096 $linkno = clean_text($linkno);
6098 print_box_start('generalbox', 'notice');
6099 echo '<p>'. $message .'</p>';
6100 echo '<div class="buttons">';
6101 print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename
);
6102 print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename
);
6108 * Provide an definition of error_get_last for PHP before 5.2.0. This simply
6109 * returns NULL, since there is not way to get the right answer.
6111 if (!function_exists('error_get_last')) {
6112 // the eval is needed to prevent PHP 5.2+ from getting a parse error!
6114 function error_get_last() {
6121 * Redirects the user to another page, after printing a notice
6123 * @param string $url The url to take the user to
6124 * @param string $message The text message to display to the user about the redirect, if any
6125 * @param string $delay How long before refreshing to the new page at $url?
6126 * @todo '&' needs to be encoded into '&' for XHTML compliance,
6127 * however, this is not true for javascript. Therefore we
6128 * first decode all entities in $url (since we cannot rely on)
6129 * the correct input) and then encode for where it's needed
6130 * echo "<script type='text/javascript'>alert('Redirect $url');</script>";
6132 function redirect($url, $message='', $delay=-1) {
6134 global $CFG, $THEME;
6136 if (!empty($CFG->usesid
) && !isset($_COOKIE[session_name()])) {
6137 $url = sid_process_url($url);
6140 $message = clean_text($message);
6142 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $url);
6143 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
6144 $url = str_replace('&', '&', $encodedurl);
6146 /// At developer debug level. Don't redirect if errors have been printed on screen.
6147 /// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
6148 $lasterror = error_get_last();
6149 $error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER
));
6150 $errorprinted = debugging('', DEBUG_ALL
) && $CFG->debugdisplay
&& $error;
6151 if ($errorprinted) {
6152 $message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
6155 $performanceinfo = '';
6156 if (defined('MDL_PERF') ||
(!empty($CFG->perfdebug
) and $CFG->perfdebug
> 7)) {
6157 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
6158 $perf = get_performance_info();
6159 error_log("PERF: " . $perf['txt']);
6163 /// when no message and header printed yet, try to redirect
6164 if (empty($message) and !defined('HEADER_PRINTED')) {
6166 // Technically, HTTP/1.1 requires Location: header to contain
6167 // the absolute path. (In practice browsers accept relative
6168 // paths - but still, might as well do it properly.)
6169 // This code turns relative into absolute.
6170 if (!preg_match('|^[a-z]+:|', $url)) {
6171 // Get host name http://www.wherever.com
6172 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot
);
6173 if (preg_match('|^/|', $url)) {
6174 // URLs beginning with / are relative to web server root so we just add them in
6175 $url = $hostpart.$url;
6177 // URLs not beginning with / are relative to path of current script, so add that on.
6178 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
6182 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
6183 if ($newurl == $url) {
6191 //try header redirection first
6192 @header
($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
6193 @header
('Location: '.$url);
6194 //another way for older browsers and already sent headers (eg trailing whitespace in config.php)
6195 echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
6196 echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
6201 $delay = 3; // if no delay specified wait 3 seconds
6203 if (! defined('HEADER_PRINTED')) {
6204 // this type of redirect might not be working in some browsers - such as lynx :-(
6205 print_header('', '', '', '', $errorprinted ?
'' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
6206 $delay +
= 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
6208 print_container_end_all(false, $THEME->open_header_containers
);
6210 echo '<div id="redirect">';
6211 echo '<div id="message">' . $message . '</div>';
6212 echo '<div id="continue">( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
6215 if (!$errorprinted) {
6217 <script type
="text/javascript">
6220 function redirect() {
6221 document
.location
.replace('<?php echo addslashes_js($url) ?>');
6223 setTimeout("redirect()", <?php
echo ($delay * 1000) ?
>);
6229 $CFG->docroot
= false; // to prevent the link to moodle docs from being displayed on redirect page.
6230 print_footer('none');
6235 * Print a bold message in an optional color.
6237 * @param string $message The message to print out
6238 * @param string $style Optional style to display message text in
6239 * @param string $align Alignment option
6240 * @param bool $return whether to return an output string or echo now
6242 function notify($message, $style='notifyproblem', $align='center', $return=false) {
6243 if ($style == 'green') {
6244 $style = 'notifysuccess'; // backward compatible with old color system
6247 $message = clean_text($message);
6249 $output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."\n";
6259 * Given an email address, this function will return an obfuscated version of it
6261 * @param string $email The email address to obfuscate
6264 function obfuscate_email($email) {
6267 $length = strlen($email);
6269 while ($i < $length) {
6271 $obfuscated.='%'.dechex(ord($email{$i}));
6273 $obfuscated.=$email{$i};
6281 * This function takes some text and replaces about half of the characters
6282 * with HTML entity equivalents. Return string is obviously longer.
6284 * @param string $plaintext The text to be obfuscated
6287 function obfuscate_text($plaintext) {
6290 $length = strlen($plaintext);
6292 $prev_obfuscated = false;
6293 while ($i < $length) {
6294 $c = ord($plaintext{$i});
6295 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
6296 if ($prev_obfuscated and $numerical ) {
6297 $obfuscated.='&#'.ord($plaintext{$i}).';';
6298 } else if (rand(0,2)) {
6299 $obfuscated.='&#'.ord($plaintext{$i}).';';
6300 $prev_obfuscated = true;
6302 $obfuscated.=$plaintext{$i};
6303 $prev_obfuscated = false;
6311 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
6312 * to generate a fully obfuscated email link, ready to use.
6314 * @param string $email The email address to display
6315 * @param string $label The text to dispalyed as hyperlink to $email
6316 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
6319 function obfuscate_mailto($email, $label='', $dimmed=false) {
6321 if (empty($label)) {
6325 $title = get_string('emaildisable');
6326 $dimmed = ' class="dimmed"';
6331 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
6332 obfuscate_text('mailto'), obfuscate_email($email),
6333 obfuscate_text($label));
6337 * Prints a single paging bar to provide access to other pages (usually in a search)
6339 * @param int $totalcount Thetotal number of entries available to be paged through
6340 * @param int $page The page you are currently viewing
6341 * @param int $perpage The number of entries that should be shown per page
6342 * @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.
6343 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
6344 * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
6345 * @param bool $nocurr do not display the current page as a link
6346 * @param bool $return whether to return an output string or echo now
6347 * @return bool or string
6349 function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
6353 if ($totalcount > $perpage) {
6354 $output .= '<div class="paging">';
6355 $output .= get_string('page') .':';
6357 $pagenum = $page - 1;
6358 if (!is_a($baseurl, 'moodle_url')){
6359 $output .= ' (<a class="previous" href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>) ';
6361 $output .= ' (<a class="previous" href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>) ';
6365 $lastpage = ceil($totalcount / $perpage);
6370 $startpage = $page - 10;
6371 if (!is_a($baseurl, 'moodle_url')){
6372 $output .= ' <a href="'. $baseurl . $pagevar .'=0">1</a> ...';
6374 $output .= ' <a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a> ...';
6379 $currpage = $startpage;
6380 $displaycount = $displaypage = 0;
6381 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
6382 $displaypage = $currpage+
1;
6383 if ($page == $currpage && empty($nocurr)) {
6384 $output .= ' '. $displaypage;
6386 if (!is_a($baseurl, 'moodle_url')){
6387 $output .= ' <a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
6389 $output .= ' <a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
6396 if ($currpage < $lastpage) {
6397 $lastpageactual = $lastpage - 1;
6398 if (!is_a($baseurl, 'moodle_url')){
6399 $output .= ' ...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a> ';
6401 $output .= ' ...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a> ';
6404 $pagenum = $page +
1;
6405 if ($pagenum != $displaypage) {
6406 if (!is_a($baseurl, 'moodle_url')){
6407 $output .= ' (<a class="next" href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
6409 $output .= ' (<a class="next" href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
6412 $output .= '</div>';
6424 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
6425 * will transform it to html entities
6427 * @param string $text Text to search for nolink tag in
6430 function rebuildnolinktag($text) {
6432 $text = preg_replace('/<(\/*nolink)>/i','<$1>',$text);
6438 * Prints a nice side block with an optional header. The content can either
6439 * be a block of HTML or a list of text with optional icons.
6441 * @param string $heading Block $title embedded in HTML tags, for example <h2>.
6442 * @param string $content ?
6443 * @param array $list ?
6444 * @param array $icons ?
6445 * @param string $footer ?
6446 * @param array $attributes ?
6447 * @param string $title Plain text title, as embedded in the $heading.
6448 * @todo Finish documenting this function. Show example of various attributes, etc.
6450 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
6452 //Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
6453 static $block_id = 0;
6455 $skip_text = get_string('skipa', 'access', strip_tags($title));
6456 $skip_link = '<a href="#sb-'.$block_id.'" class="skip-block">'.$skip_text.'</a>';
6457 $skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
6459 $strip_title = strip_tags($title);
6460 if (! empty($strip_title)) {
6463 //ELSE: a single link on a page "Skip block 4" is too confusing - ignore.
6465 print_side_block_start($heading, $attributes);
6470 echo '<div class="footer">'. $footer .'</div>';
6475 //Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
6476 echo "\n<ul class='list'>\n";
6477 foreach ($list as $key => $string) {
6478 echo '<li class="r'. $row .'">';
6480 echo '<div class="icon column c0">'. $icons[$key] .'</div>';
6482 echo '<div class="column c1">' . $string . '</div>';
6489 echo '<div class="footer">'. $footer .'</div>';
6494 print_side_block_end($attributes, $title);
6499 * Starts a nice side block with an optional header.
6501 * @param string $heading ?
6502 * @param array $attributes ?
6503 * @todo Finish documenting this function
6505 function print_side_block_start($heading='', $attributes = array()) {
6507 global $CFG, $THEME;
6509 // If there are no special attributes, give a default CSS class
6510 if (empty($attributes) ||
!is_array($attributes)) {
6511 $attributes = array('class' => 'sideblock');
6513 } else if(!isset($attributes['class'])) {
6514 $attributes['class'] = 'sideblock';
6516 } else if(!strpos($attributes['class'], 'sideblock')) {
6517 $attributes['class'] .= ' sideblock';
6520 // OK, the class is surely there and in addition to anything
6521 // else, it's tagged as a sideblock
6525 // IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
6527 // If there is a cookie to hide this thing, start it hidden
6528 if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
6529 $attributes['class'] = 'hidden '.$attributes['class'];
6534 foreach ($attributes as $attr => $val) {
6535 $attrtext .= ' '.$attr.'="'.$val.'"';
6538 echo '<div '.$attrtext.'>';
6540 if (!empty($THEME->customcorners
)) {
6541 echo '<div class="wrap">'."\n";
6544 //Accessibility: H2 more appropriate in moodleblock.class.php: _title_html.
6545 echo '<div class="header">';
6546 if (!empty($THEME->customcorners
)) {
6547 echo '<div class="bt"><div> </div></div>';
6548 echo '<div class="i1"><div class="i2">';
6549 echo '<div class="i3">';
6552 if (!empty($THEME->customcorners
)) {
6553 echo '</div></div></div>';
6557 if (!empty($THEME->customcorners
)) {
6558 echo '<div class="bt"><div> </div></div>';
6562 if (!empty($THEME->customcorners
)) {
6563 echo '<div class="i1"><div class="i2">';
6564 echo '<div class="i3">';
6566 echo '<div class="content">';
6572 * Print table ending tags for a side block box.
6574 function print_side_block_end($attributes = array(), $title='') {
6575 global $CFG, $THEME;
6579 if (!empty($THEME->customcorners
)) {
6580 echo '</div></div></div><div class="bb"><div> </div></div></div>';
6585 $strshow = addslashes_js(get_string('showblocka', 'access', strip_tags($title)));
6586 $strhide = addslashes_js(get_string('hideblocka', 'access', strip_tags($title)));
6588 // IE workaround: if I do it THIS way, it works! WTF?
6589 if (!empty($CFG->allowuserblockhiding
) && isset($attributes['id'])) {
6590 echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].
6591 '","'.$strshow.'","'.$strhide."\");\n//]]>\n".'</script>';
6598 * Prints out code needed for spellchecking.
6599 * Original idea by Ludo (Marc Alier).
6601 * Opening CDATA and <script> are output by weblib::use_html_editor()
6603 * @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
6604 * @param boolean $return If false, echos the code instead of returning it
6605 * @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
6607 function print_speller_code ($usehtmleditor=false, $return=false) {
6611 if(!$usehtmleditor) {
6612 $str .= 'function openSpellChecker() {'."\n";
6613 $str .= "\tvar speller = new spellChecker();\n";
6614 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot
."/lib/speller/spellchecker.html\";\n";
6615 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot
."/lib/speller/server-scripts/spellchecker.php\";\n";
6616 $str .= "\tspeller.spellCheckAll();\n";
6619 $str .= "function spellClickHandler(editor, buttonId) {\n";
6620 $str .= "\teditor._textArea.value = editor.getHTML();\n";
6621 $str .= "\tvar speller = new spellChecker( editor._textArea );\n";
6622 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot
."/lib/speller/spellchecker.html\";\n";
6623 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot
."/lib/speller/server-scripts/spellchecker.php\";\n";
6624 $str .= "\tspeller._moogle_edit=1;\n";
6625 $str .= "\tspeller._editor=editor;\n";
6626 $str .= "\tspeller.openChecker();\n";
6637 * Print button for spellchecking when editor is disabled
6639 function print_speller_button () {
6640 echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
6644 function page_id_and_class(&$getid, &$getclass) {
6645 // Create class and id for this page
6648 static $class = NULL;
6651 if (empty($CFG->pagepath
)) {
6652 $CFG->pagepath
= $ME;
6655 if (empty($class) ||
empty($id)) {
6656 $path = str_replace($CFG->httpswwwroot
.'/', '', $CFG->pagepath
); //Because the page could be HTTPSPAGEREQUIRED
6657 $path = str_replace('.php', '', $path);
6658 if (substr($path, -1) == '/') {
6661 if (empty($path) ||
$path == 'index') {
6664 } else if (substr($path, 0, 5) == 'admin') {
6665 $id = str_replace('/', '-', $path);
6668 $id = str_replace('/', '-', $path);
6669 $class = explode('-', $id);
6671 $class = implode('-', $class);
6680 * Prints a maintenance message from /maintenance.html
6682 function print_maintenance_message () {
6685 $CFG->pagepath
= "index.php";
6686 print_header(strip_tags($SITE->fullname
), $SITE->fullname
, 'home');
6688 print_heading(get_string('sitemaintenance', 'admin'));
6689 @include
($CFG->dataroot
.'/'.SITEID
.'/maintenance.html');
6695 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
6697 function adjust_allowed_tags() {
6699 global $CFG, $ALLOWED_TAGS;
6701 if (!empty($CFG->allowobjectembed
)) {
6702 $ALLOWED_TAGS .= '<embed><object>';
6706 /// Some code to print tabs
6708 /// A class for tabs
6713 var $linkedwhenselected;
6715 /// A constructor just because I like constructors
6716 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
6718 $this->link
= $link;
6719 $this->text
= $text;
6720 $this->title
= $title ?
$title : $text;
6721 $this->linkedwhenselected
= $linkedwhenselected;
6728 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
6730 * @param array $tabrows An array of rows where each row is an array of tab objects
6731 * @param string $selected The id of the selected tab (whatever row it's on)
6732 * @param array $inactive An array of ids of inactive tabs that are not selectable.
6733 * @param array $activated An array of ids of other tabs that are currently activated
6735 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
6738 /// $inactive must be an array
6739 if (!is_array($inactive)) {
6740 $inactive = array();
6743 /// $activated must be an array
6744 if (!is_array($activated)) {
6745 $activated = array();
6748 /// Convert the tab rows into a tree that's easier to process
6749 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
6753 /// Print out the current tree of tabs (this function is recursive)
6755 $output = convert_tree_to_html($tree);
6757 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
6768 function convert_tree_to_html($tree, $row=0) {
6770 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
6773 $count = count($tree);
6775 foreach ($tree as $tab) {
6776 $count--; // countdown to zero
6780 if ($first && ($count == 0)) { // Just one in the row
6781 $liclass = 'first last';
6783 } else if ($first) {
6786 } else if ($count == 0) {
6790 if ((empty($tab->subtree
)) && (!empty($tab->selected
))) {
6791 $liclass .= (empty($liclass)) ?
'onerow' : ' onerow';
6794 if ($tab->inactive ||
$tab->active ||
$tab->selected
) {
6795 if ($tab->selected
) {
6796 $liclass .= (empty($liclass)) ?
'here selected' : ' here selected';
6797 } else if ($tab->active
) {
6798 $liclass .= (empty($liclass)) ?
'here active' : ' here active';
6802 $str .= (!empty($liclass)) ?
'<li class="'.$liclass.'">' : '<li>';
6804 if ($tab->inactive ||
$tab->active ||
($tab->selected
&& !$tab->linkedwhenselected
)) {
6805 // The a tag is used for styling
6806 $str .= '<a class="nolink"><span>'.$tab->text
.'</span></a>';
6808 $str .= '<a href="'.$tab->link
.'" title="'.$tab->title
.'"><span>'.$tab->text
.'</span></a>';
6811 if (!empty($tab->subtree
)) {
6812 $str .= convert_tree_to_html($tab->subtree
, $row+
1);
6813 } else if ($tab->selected
) {
6814 $str .= '<div class="tabrow'.($row+
1).' empty"> </div>'."\n";
6817 $str .= ' </li>'."\n";
6819 $str .= '</ul>'."\n";
6825 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
6827 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
6829 $tabrows = array_reverse($tabrows);
6833 foreach ($tabrows as $row) {
6836 foreach ($row as $tab) {
6837 $tab->inactive
= in_array((string)$tab->id
, $inactive);
6838 $tab->active
= in_array((string)$tab->id
, $activated);
6839 $tab->selected
= (string)$tab->id
== $selected;
6841 if ($tab->active ||
$tab->selected
) {
6843 $tab->subtree
= $subtree;
6856 * Returns a string containing a link to the user documentation for the current
6857 * page. Also contains an icon by default. Shown to teachers and admin only.
6859 * @param string $text The text to be displayed for the link
6860 * @param string $iconpath The path to the icon to be displayed
6862 function page_doc_link($text='', $iconpath='') {
6863 global $ME, $COURSE, $CFG;
6865 if (empty($CFG->docroot
) or empty($CFG->rolesactive
)) {
6869 if (empty($COURSE->id
)) {
6870 $context = get_context_instance(CONTEXT_SYSTEM
);
6872 $context = get_context_instance(CONTEXT_COURSE
, $COURSE->id
);
6875 if (!has_capability('moodle/site:doclinks', $context)) {
6879 if (empty($CFG->pagepath
)) {
6880 $CFG->pagepath
= $ME;
6883 $path = str_replace($CFG->httpswwwroot
.'/','', $CFG->pagepath
); // Because the page could be HTTPSPAGEREQUIRED
6884 $path = str_replace('.php', '', $path);
6886 if (empty($path)) { // Not for home page
6889 return doc_link($path, $text, $iconpath);
6893 * Returns a string containing a link to the user documentation.
6894 * Also contains an icon by default. Shown to teachers and admin only.
6896 * @param string $path The page link after doc root and language, no
6898 * @param string $text The text to be displayed for the link
6899 * @param string $iconpath The path to the icon to be displayed
6901 function doc_link($path='', $text='', $iconpath='') {
6904 if (empty($CFG->docroot
)) {
6909 if (!empty($CFG->doctonewwindow
)) {
6910 $target = ' target="_blank"';
6913 $lang = str_replace('_utf8', '', current_language());
6915 $str = '<a href="' .$CFG->docroot
. '/' .$lang. '/' .$path. '"' .$target. '>';
6917 if (empty($iconpath)) {
6918 $iconpath = $CFG->httpswwwroot
. '/pix/docs.gif';
6921 // alt left blank intentionally to prevent repetition in screenreaders
6922 $str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
6929 * Returns true if the current site debugging settings are equal or above specified level.
6930 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
6931 * routing of notices is controlled by $CFG->debugdisplay
6934 * 1) debugging('a normal debug notice');
6935 * 2) debugging('something really picky', DEBUG_ALL);
6936 * 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
6937 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
6939 * In code blocks controlled by debugging() (such as example 4)
6940 * any output should be routed via debugging() itself, or the lower-level
6941 * trigger_error() or error_log(). Using echo or print will break XHTML
6942 * JS and HTTP headers.
6945 * @param string $message a message to print
6946 * @param int $level the level at which this debugging statement should show
6949 function debugging($message='', $level=DEBUG_NORMAL
) {
6953 if (empty($CFG->debug
)) {
6957 if ($CFG->debug
>= $level) {
6959 $callers = debug_backtrace();
6960 $from = '<ul style="text-align: left">';
6961 foreach ($callers as $caller) {
6962 if (!isset($caller['line'])) {
6963 $caller['line'] = '?'; // probably call_user_func()
6965 if (!isset($caller['file'])) {
6966 $caller['file'] = $CFG->dirroot
.'/unknownfile'; // probably call_user_func()
6968 $from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot
) +
1);
6969 if (isset($caller['function'])) {
6970 $from .= ': call to ';
6971 if (isset($caller['class'])) {
6972 $from .= $caller['class'] . $caller['type'];
6974 $from .= $caller['function'] . '()';
6979 if (!isset($CFG->debugdisplay
)) {
6980 $CFG->debugdisplay
= ini_get_bool('display_errors');
6982 if ($CFG->debugdisplay
) {
6983 if (!defined('DEBUGGING_PRINTED')) {
6984 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
6986 notify($message . $from, 'notifytiny');
6988 trigger_error($message . $from, E_USER_NOTICE
);
6997 * Disable debug messages from debugging(), while keeping PHP error reporting level as is.
6999 function disable_debugging() {
7001 $CFG->debug
= $CFG->debug |
0x80000000; // switch the sign bit in integer number ;-)
7006 * Returns string to add a frame attribute, if required
7008 function frametarget() {
7011 if (empty($CFG->framename
) or ($CFG->framename
== '_top')) {
7014 return ' target="'.$CFG->framename
.'" ';
7019 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
7020 * pages that use bits from many different files in very confusing ways (e.g. blocks).
7021 * @usage print_location_comment(__FILE__, __LINE__);
7022 * @param string $file
7023 * @param integer $line
7024 * @param boolean $return Whether to return or print the comment
7025 * @return mixed Void unless true given as third parameter
7027 function print_location_comment($file, $line, $return = false)
7030 return "<!-- $file at line $line -->\n";
7032 echo "<!-- $file at line $line -->\n";
7038 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
7039 * provide this function with the language strings for sortasc and sortdesc.
7040 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
7041 * @param string $direction 'up' or 'down'
7042 * @param string $strsort The language string used for the alt attribute of this image
7043 * @param bool $return Whether to print directly or return the html string
7044 * @return string HTML for the image
7046 * TODO See if this isn't already defined somewhere. If not, move this to weblib
7048 function print_arrow($direction='up', $strsort=null, $return=false) {
7051 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
7057 switch ($direction) {
7072 // Prepare language string
7074 if (empty($strsort) && !empty($sortdir)) {
7075 $strsort = get_string('sort' . $sortdir, 'grades');
7078 $return = ' <img src="'.$CFG->pixpath
.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
7088 * Returns boolean true if the current language is right-to-left (Hebrew, Arabic etc)
7091 function right_to_left() {
7094 if (isset($result)) {
7097 return $result = (get_string('thisdirection') == 'rtl');
7102 * Returns swapped left<=>right if in RTL environment.
7103 * part of RTL support
7105 * @param string $align align to check
7108 function fix_align_rtl($align) {
7109 if (!right_to_left()) {
7112 if ($align=='left') { return 'right'; }
7113 if ($align=='right') { return 'left'; }
7119 * Returns true if the page is displayed in a popup window.
7120 * Gets the information from the URL parameter inpopup.
7124 * TODO Use a central function to create the popup calls allover Moodle and
7125 * TODO In the moment only works with resources and probably questions.
7127 function is_in_popup() {
7128 $inpopup = optional_param('inpopup', '', PARAM_BOOL
);
7134 * Return the authentication plugin title
7135 * @param string $authtype plugin type
7138 function auth_get_plugin_title ($authtype) {
7139 $authtitle = get_string("auth_{$authtype}title", "auth");
7140 if ($authtitle == "[[auth_{$authtype}title]]") {
7141 $authtitle = get_string("auth_{$authtype}title", "auth_{$authtype}");
7147 * Print password policy.
7151 function print_password_policy(){
7153 $messages = array();
7155 if(!empty($CFG->passwordpolicy
)){
7156 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength
);
7157 if(!empty($CFG->minpassworddigits
)){
7158 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits
);
7160 if(!empty($CFG->minpasswordlower
)){
7161 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower
);
7163 if(!empty($CFG->minpasswordupper
)){
7164 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper
);
7166 if(!empty($CFG->minpasswordnonalphanum
)){
7167 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum
);
7170 $lastmessage = new stdClass
;
7171 $lastmessage->one
= '';
7172 $lastmessage->two
= array_pop($messages);
7173 $messages[] = get_string('and','moodle',$lastmessage);
7174 $message = join(', ', $messages);
7175 $message = '<div class="fitemtitle"> </div><div class="felement ftext">'. get_string('informpasswordpolicy', 'auth', $message) . '</div>';
7181 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: