MDL-11517 reserved word MOD used in table alias in questions backup code
[moodle-pu.git] / lib / weblib.php
blob46dc072553c240f6e1808df930494c72c4bbcbb8
1 <?php // $Id$
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.com //
9 // //
10 // Copyright (C) 2001-2003 Martin Dougiamas http://dougiamas.com //
11 // //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
16 // //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
21 // //
22 // http://www.gnu.org/copyleft/gpl.html //
23 // //
24 ///////////////////////////////////////////////////////////////////////////
26 /**
27 * Library of functions for web output
29 * Library of all general-purpose Moodle PHP functions and constants
30 * that produce HTML output
32 * Other main libraries:
33 * - datalib.php - functions that access the database.
34 * - moodlelib.php - general-purpose Moodle functions.
35 * @author Martin Dougiamas
36 * @version $Id$
37 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
38 * @package moodlecore
41 /// We are going to uses filterlib functions here
42 require_once("$CFG->libdir/filterlib.php");
44 require_once("$CFG->libdir/ajax/ajaxlib.php");
46 /// Constants
48 /// Define text formatting types ... eventually we can add Wiki, BBcode etc
50 /**
51 * Does all sorts of transformations and filtering
53 define('FORMAT_MOODLE', '0'); // Does all sorts of transformations and filtering
55 /**
56 * Plain HTML (with some tags stripped)
58 define('FORMAT_HTML', '1'); // Plain HTML (with some tags stripped)
60 /**
61 * Plain text (even tags are printed in full)
63 define('FORMAT_PLAIN', '2'); // Plain text (even tags are printed in full)
65 /**
66 * Wiki-formatted text
67 * Deprecated: left here just to note that '3' is not used (at the moment)
68 * and to catch any latent wiki-like text (which generates an error)
70 define('FORMAT_WIKI', '3'); // Wiki-formatted text
72 /**
73 * Markdown-formatted text http://daringfireball.net/projects/markdown/
75 define('FORMAT_MARKDOWN', '4'); // Markdown-formatted text http://daringfireball.net/projects/markdown/
77 /**
78 * TRUSTTEXT marker - if present in text, text cleaning should be bypassed
80 define('TRUSTTEXT', '#####TRUSTTEXT#####');
83 /**
84 * Allowed tags - string of html tags that can be tested against for safe html tags
85 * @global string $ALLOWED_TAGS
87 global $ALLOWED_TAGS;
88 $ALLOWED_TAGS =
89 '<p><br><b><i><u><font><table><tbody><span><div><tr><td><th><ol><ul><dl><li><dt><dd><h1><h2><h3><h4><h5><h6><hr><img><a><strong><emphasis><em><sup><sub><address><cite><blockquote><pre><strike><param><acronym><nolink><lang><tex><algebra><math><mi><mn><mo><mtext><mspace><ms><mrow><mfrac><msqrt><mroot><mstyle><merror><mpadded><mphantom><mfenced><msub><msup><msubsup><munder><mover><munderover><mmultiscripts><mtable><mtr><mtd><maligngroup><malignmark><maction><cn><ci><apply><reln><fn><interval><inverse><sep><condition><declare><lambda><compose><ident><quotient><exp><factorial><divide><max><min><minus><plus><power><rem><times><root><gcd><and><or><xor><not><implies><forall><exists><abs><conjugate><eq><neq><gt><lt><geq><leq><ln><log><int><diff><partialdiff><lowlimit><uplimit><bvar><degree><set><list><union><intersect><in><notin><subset><prsubset><notsubset><notprsubset><setdiff><sum><product><limit><tendsto><mean><sdev><variance><median><mode><moment><vector><matrix><matrixrow><determinant><transpose><selector><annotation><semantics><annotation-xml><tt><code>';
91 /**
92 * Allowed protocols - array of protocols that are safe to use in links and so on
93 * @global string $ALLOWED_PROTOCOLS
95 $ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms',
96 'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style',
97 'border', 'margin', 'padding', 'background'); // CSS as well to get through kses
100 /// Functions
103 * Add quotes to HTML characters
105 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
106 * This function is very similar to {@link p()}
108 * @param string $var the string potentially containing HTML characters
109 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
110 * true should be used to print data from forms and false for data from DB.
111 * @return string
113 function s($var, $strip=false) {
115 if ($var == '0') { // for integer 0, boolean false, string '0'
116 return '0';
119 if ($strip) {
120 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars(stripslashes_safe($var)));
121 } else {
122 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars($var));
127 * Add quotes to HTML characters
129 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
130 * This function is very similar to {@link s()}
132 * @param string $var the string potentially containing HTML characters
133 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
134 * true should be used to print data from forms and false for data from DB.
135 * @return string
137 function p($var, $strip=false) {
138 echo s($var, $strip);
142 * Does proper javascript quoting.
143 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
145 * @since 1.8 - 22/02/2007
146 * @param mixed value
147 * @return mixed quoted result
149 function addslashes_js($var) {
150 if (is_string($var)) {
151 $var = str_replace('\\', '\\\\', $var);
152 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
153 $var = str_replace('</', '<\/', $var); // XHTML compliance
154 } else if (is_array($var)) {
155 $var = array_map('addslashes_js', $var);
156 } else if (is_object($var)) {
157 $a = get_object_vars($var);
158 foreach ($a as $key=>$value) {
159 $a[$key] = addslashes_js($value);
161 $var = (object)$a;
163 return $var;
167 * Remove query string from url
169 * Takes in a URL and returns it without the querystring portion
171 * @param string $url the url which may have a query string attached
172 * @return string
174 function strip_querystring($url) {
176 if ($commapos = strpos($url, '?')) {
177 return substr($url, 0, $commapos);
178 } else {
179 return $url;
184 * Returns the URL of the HTTP_REFERER, less the querystring portion if required
185 * @return string
187 function get_referer($stripquery=true) {
188 if (isset($_SERVER['HTTP_REFERER'])) {
189 if ($stripquery) {
190 return strip_querystring($_SERVER['HTTP_REFERER']);
191 } else {
192 return $_SERVER['HTTP_REFERER'];
194 } else {
195 return '';
201 * Returns the name of the current script, WITH the querystring portion.
202 * this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
203 * return different things depending on a lot of things like your OS, Web
204 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
205 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
207 * @return string
209 function me() {
211 if (!empty($_SERVER['REQUEST_URI'])) {
212 return $_SERVER['REQUEST_URI'];
214 } else if (!empty($_SERVER['PHP_SELF'])) {
215 if (!empty($_SERVER['QUERY_STRING'])) {
216 return $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
218 return $_SERVER['PHP_SELF'];
220 } else if (!empty($_SERVER['SCRIPT_NAME'])) {
221 if (!empty($_SERVER['QUERY_STRING'])) {
222 return $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
224 return $_SERVER['SCRIPT_NAME'];
226 } else if (!empty($_SERVER['URL'])) { // May help IIS (not well tested)
227 if (!empty($_SERVER['QUERY_STRING'])) {
228 return $_SERVER['URL'] .'?'. $_SERVER['QUERY_STRING'];
230 return $_SERVER['URL'];
232 } else {
233 notify('Warning: Could not find any of these web server variables: $REQUEST_URI, $PHP_SELF, $SCRIPT_NAME or $URL');
234 return false;
239 * Like {@link me()} but returns a full URL
240 * @see me()
241 * @return string
243 function qualified_me() {
245 global $CFG;
247 if (!empty($CFG->wwwroot)) {
248 $url = parse_url($CFG->wwwroot);
251 if (!empty($url['host'])) {
252 $hostname = $url['host'];
253 } else if (!empty($_SERVER['SERVER_NAME'])) {
254 $hostname = $_SERVER['SERVER_NAME'];
255 } else if (!empty($_ENV['SERVER_NAME'])) {
256 $hostname = $_ENV['SERVER_NAME'];
257 } else if (!empty($_SERVER['HTTP_HOST'])) {
258 $hostname = $_SERVER['HTTP_HOST'];
259 } else if (!empty($_ENV['HTTP_HOST'])) {
260 $hostname = $_ENV['HTTP_HOST'];
261 } else {
262 notify('Warning: could not find the name of this server!');
263 return false;
266 if (!empty($url['port'])) {
267 $hostname .= ':'.$url['port'];
268 } else if (!empty($_SERVER['SERVER_PORT'])) {
269 if ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
270 $hostname .= ':'.$_SERVER['SERVER_PORT'];
274 if (isset($_SERVER['HTTPS'])) {
275 $protocol = ($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
276 } else if (isset($_SERVER['SERVER_PORT'])) { # Apache2 does not export $_SERVER['HTTPS']
277 $protocol = ($_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
278 } else {
279 $protocol = 'http://';
282 $url_prefix = $protocol.$hostname;
283 return $url_prefix . me();
288 * Class for creating and manipulating urls.
290 * See short write up here http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url
292 class moodle_url {
293 var $scheme = '';// e.g. http
294 var $host = '';
295 var $port = '';
296 var $user = '';
297 var $pass = '';
298 var $path = '';
299 var $fragment = '';
300 var $params = array(); //associative array of query string params
303 * Pass no arguments to create a url that refers to this page. Use empty string to create empty url.
305 * @param string $url url default null means use this page url with no query string
306 * empty string means empty url.
307 * if you pass any other type of url it will be parsed into it's bits, including query string
308 * @param array $params these params override anything in the query string where params have the same name.
310 function moodle_url($url = null, $params = array()){
311 global $FULLME;
312 if ($url !== ''){
313 if ($url === null){
314 $url = strip_querystring($FULLME);
316 $parts = parse_url($url);
317 if ($parts === FALSE){
318 error('invalidurl');
320 if (isset($parts['query'])){
321 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
323 unset($parts['query']);
324 foreach ($parts as $key => $value){
325 $this->$key = $value;
327 $this->params($params);
331 * Add an array of params to the params for this page. The added params override existing ones if they
332 * have the same name.
334 * @param array $params
336 function params($params){
337 $this->params = $params + $this->params;
341 * Remove all params if no arguments passed. Or else remove param $arg1, $arg2, etc.
343 * @param string $arg1
344 * @param string $arg2
345 * @param string $arg3
347 function remove_params(){
348 if ($thisargs = func_get_args()){
349 foreach ($thisargs as $arg){
350 if (isset($this->params->$arg)){
351 unset($this->params->$arg);
354 } else { // no args
355 $this->params = array();
360 * Add a param to the params for this page. The added param overrides existing one if they
361 * have the same name.
363 * @param string $paramname name
364 * @param string $param value
366 function param($paramname, $param){
367 $this->params = array($paramname => $param) + $this->params;
371 function get_query_string($overrideparams = array()){
372 $arr = array();
373 $params = $overrideparams + $this->params;
374 foreach ($params as $key => $val){
375 $arr[] = urlencode($key)."=".urlencode($val);
377 return implode($arr, "&amp;");
380 * Outputs params as hidden form elements.
382 * @param array $exclude params to ignore
383 * @param integer $indent indentation
384 * @return string html for form elements.
386 function hidden_params_out($exclude = array(), $indent = 0){
387 $tabindent = str_repeat("\t", $indent);
388 $str = '';
389 foreach ($this->params as $key => $val){
390 if (FALSE === array_search($key, $exclude)) {
391 $val = s($val);
392 $str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
395 return $str;
398 * Output url
400 * @param boolean $noquerystring whether to output page params as a query string in the url.
401 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
402 * @return string url
404 function out($noquerystring = false, $overrideparams = array()) {
405 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
406 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
407 $uri .= $this->host ? $this->host : '';
408 $uri .= $this->port ? ':'.$this->port : '';
409 $uri .= $this->path ? $this->path : '';
410 if (!$noquerystring){
411 $uri .= (count($this->params)||count($overrideparams)) ? '?'.$this->get_query_string($overrideparams) : '';
413 $uri .= $this->fragment ? '#'.$this->fragment : '';
414 return $uri;
417 * Output action url with sesskey
419 * @param boolean $noquerystring whether to output page params as a query string in the url.
420 * @return string url
422 function out_action($overrideparams = array()) {
423 $overrideparams = array('sesskey'=> sesskey()) + $overrideparams;
424 return $this->out(false, $overrideparams);
429 * Determine if there is data waiting to be processed from a form
431 * Used on most forms in Moodle to check for data
432 * Returns the data as an object, if it's found.
433 * This object can be used in foreach loops without
434 * casting because it's cast to (array) automatically
436 * Checks that submitted POST data exists and returns it as object.
438 * @param string $url not used anymore
439 * @return mixed false or object
441 function data_submitted($url='') {
443 if (empty($_POST)) {
444 return false;
445 } else {
446 return (object)$_POST;
451 * Moodle replacement for php stripslashes() function,
452 * works also for objects and arrays.
454 * The standard php stripslashes() removes ALL backslashes
455 * even from strings - so C:\temp becomes C:temp - this isn't good.
456 * This function should work as a fairly safe replacement
457 * to be called on quoted AND unquoted strings (to be sure)
459 * @param mixed something to remove unsafe slashes from
460 * @return mixed
462 function stripslashes_safe($mixed) {
463 // there is no need to remove slashes from int, float and bool types
464 if (empty($mixed)) {
465 //nothing to do...
466 } else if (is_string($mixed)) {
467 if (ini_get_bool('magic_quotes_sybase')) { //only unescape single quotes
468 $mixed = str_replace("''", "'", $mixed);
469 } else { //the rest, simple and double quotes and backslashes
470 $mixed = str_replace("\\'", "'", $mixed);
471 $mixed = str_replace('\\"', '"', $mixed);
472 $mixed = str_replace('\\\\', '\\', $mixed);
474 } else if (is_array($mixed)) {
475 foreach ($mixed as $key => $value) {
476 $mixed[$key] = stripslashes_safe($value);
478 } else if (is_object($mixed)) {
479 $vars = get_object_vars($mixed);
480 foreach ($vars as $key => $value) {
481 $mixed->$key = stripslashes_safe($value);
485 return $mixed;
489 * Recursive implementation of stripslashes()
491 * This function will allow you to strip the slashes from a variable.
492 * If the variable is an array or object, slashes will be stripped
493 * from the items (or properties) it contains, even if they are arrays
494 * or objects themselves.
496 * @param mixed the variable to remove slashes from
497 * @return mixed
499 function stripslashes_recursive($var) {
500 if (is_object($var)) {
501 $new_var = new object();
502 $properties = get_object_vars($var);
503 foreach($properties as $property => $value) {
504 $new_var->$property = stripslashes_recursive($value);
507 } else if(is_array($var)) {
508 $new_var = array();
509 foreach($var as $property => $value) {
510 $new_var[$property] = stripslashes_recursive($value);
513 } else if(is_string($var)) {
514 $new_var = stripslashes($var);
516 } else {
517 $new_var = $var;
520 return $new_var;
524 * Recursive implementation of addslashes()
526 * This function will allow you to add the slashes from a variable.
527 * If the variable is an array or object, slashes will be added
528 * to the items (or properties) it contains, even if they are arrays
529 * or objects themselves.
531 * @param mixed the variable to add slashes from
532 * @return mixed
534 function addslashes_recursive($var) {
535 if (is_object($var)) {
536 $new_var = new object();
537 $properties = get_object_vars($var);
538 foreach($properties as $property => $value) {
539 $new_var->$property = addslashes_recursive($value);
542 } else if (is_array($var)) {
543 $new_var = array();
544 foreach($var as $property => $value) {
545 $new_var[$property] = addslashes_recursive($value);
548 } else if (is_string($var)) {
549 $new_var = addslashes($var);
551 } else { // nulls, integers, etc.
552 $new_var = $var;
555 return $new_var;
559 * Given some normal text this function will break up any
560 * long words to a given size by inserting the given character
562 * It's multibyte savvy and doesn't change anything inside html tags.
564 * @param string $string the string to be modified
565 * @param int $maxsize maximum length of the string to be returned
566 * @param string $cutchar the string used to represent word breaks
567 * @return string
569 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
571 /// Loading the textlib singleton instance. We are going to need it.
572 $textlib = textlib_get_instance();
574 /// First of all, save all the tags inside the text to skip them
575 $tags = array();
576 filter_save_tags($string,$tags);
578 /// Process the string adding the cut when necessary
579 $output = '';
580 $length = $textlib->strlen($string);
581 $wordlength = 0;
583 for ($i=0; $i<$length; $i++) {
584 $char = $textlib->substr($string, $i, 1);
585 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
586 $wordlength = 0;
587 } else {
588 $wordlength++;
589 if ($wordlength > $maxsize) {
590 $output .= $cutchar;
591 $wordlength = 0;
594 $output .= $char;
597 /// Finally load the tags back again
598 if (!empty($tags)) {
599 $output = str_replace(array_keys($tags), $tags, $output);
602 return $output;
606 * This does a search and replace, ignoring case
607 * This function is only used for versions of PHP older than version 5
608 * which do not have a native version of this function.
609 * Taken from the PHP manual, by bradhuizenga @ softhome.net
611 * @param string $find the string to search for
612 * @param string $replace the string to replace $find with
613 * @param string $string the string to search through
614 * return string
616 if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
617 function str_ireplace($find, $replace, $string) {
619 if (!is_array($find)) {
620 $find = array($find);
623 if(!is_array($replace)) {
624 if (!is_array($find)) {
625 $replace = array($replace);
626 } else {
627 // this will duplicate the string into an array the size of $find
628 $c = count($find);
629 $rString = $replace;
630 unset($replace);
631 for ($i = 0; $i < $c; $i++) {
632 $replace[$i] = $rString;
637 foreach ($find as $fKey => $fItem) {
638 $between = explode(strtolower($fItem),strtolower($string));
639 $pos = 0;
640 foreach($between as $bKey => $bItem) {
641 $between[$bKey] = substr($string,$pos,strlen($bItem));
642 $pos += strlen($bItem) + strlen($fItem);
644 $string = implode($replace[$fKey],$between);
646 return ($string);
651 * Locate the position of a string in another string
653 * This function is only used for versions of PHP older than version 5
654 * which do not have a native version of this function.
655 * Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
657 * @param string $haystack The string to be searched
658 * @param string $needle The string to search for
659 * @param int $offset The position in $haystack where the search should begin.
661 if (!function_exists('stripos')) { /// Only exists in PHP 5
662 function stripos($haystack, $needle, $offset=0) {
664 return strpos(strtoupper($haystack), strtoupper($needle), $offset);
669 * This function will create a HTML link that will work on both
670 * Javascript and non-javascript browsers.
671 * Relies on the Javascript function openpopup in javascript.php
673 * $url must be relative to home page eg /mod/survey/stuff.php
674 * @param string $url Web link relative to home page
675 * @param string $name Name to be assigned to the popup window
676 * @param string $linkname Text to be displayed as web link
677 * @param int $height Height to assign to popup window
678 * @param int $width Height to assign to popup window
679 * @param string $title Text to be displayed as popup page title
680 * @param string $options List of additional options for popup window
681 * @todo Add code examples and list of some options that might be used.
682 * @param boolean $return Should the link to the popup window be returned as a string (true) or printed immediately (false)?
683 * @return string
684 * @uses $CFG
686 function link_to_popup_window ($url, $name='popup', $linkname='click here',
687 $height=400, $width=500, $title='Popup window',
688 $options='none', $return=false) {
690 global $CFG;
692 if ($options == 'none') {
693 $options = 'menubar=0,location=0,scrollbars,resizable,width='. $width .',height='. $height;
695 $fullscreen = 0;
697 if (!(strpos($url,$CFG->wwwroot) === false)) { // some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
698 $url = substr($url, strlen($CFG->wwwroot));
701 $link = '<a title="'. s(strip_tags($title)) .'" href="'. $CFG->wwwroot . $url .'" '.
702 "onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
703 if ($return) {
704 return $link;
705 } else {
706 echo $link;
711 * This function will print a button submit form element
712 * that will work on both Javascript and non-javascript browsers.
713 * Relies on the Javascript function openpopup in javascript.php
715 * $url must be relative to home page eg /mod/survey/stuff.php
716 * @param string $url Web link relative to home page
717 * @param string $name Name to be assigned to the popup window
718 * @param string $linkname Text to be displayed as web link
719 * @param int $height Height to assign to popup window
720 * @param int $width Height to assign to popup window
721 * @param string $title Text to be displayed as popup page title
722 * @param string $options List of additional options for popup window
723 * @param string $return If true, return as a string, otherwise print
724 * @return string
725 * @uses $CFG
727 function button_to_popup_window ($url, $name='popup', $linkname='click here',
728 $height=400, $width=500, $title='Popup window', $options='none', $return=false,
729 $id='', $class='') {
731 global $CFG;
733 if ($options == 'none') {
734 $options = 'menubar=0,location=0,scrollbars,resizable,width='. $width .',height='. $height;
737 if ($id) {
738 $id = ' id="'.$id.'" ';
740 if ($class) {
741 $class = ' class="'.$class.'" ';
743 $fullscreen = 0;
745 $button = '<input type="button" name="'.$name.'" title="'. $title .'" value="'. $linkname .' ..." '.$id.$class.
746 "onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
747 if ($return) {
748 return $button;
749 } else {
750 echo $button;
756 * Prints a simple button to close a window
758 function close_window_button($name='closewindow', $return=false) {
759 global $CFG;
761 $output = '';
763 $output .= '<div class="closewindow">' . "\n";
764 $output .= '<form action="'.$CFG->wwwroot.'"><div>'; // We don't use this
765 $output .= '<input type="button" onclick="self.close();" value="'.get_string($name).'" />';
766 $output .= '</div></form>';
767 $output .= '</div>' . "\n";
769 if ($return) {
770 return $output;
771 } else {
772 echo $output;
777 * Try and close the current window immediately using Javascript
779 function close_window($delay=0) {
781 <script type="text/javascript">
782 //<![CDATA[
783 function close_this_window() {
784 self.close();
786 setTimeout("close_this_window()", <?php echo $delay * 1000 ?>);
787 //]]>
788 </script>
789 <noscript><center>
790 <?php print_string('pleaseclose') ?>
791 </center></noscript>
792 <?php
793 die;
798 * Given an array of value, creates a popup menu to be part of a form
799 * $options["value"]["label"]
801 * @param type description
802 * @todo Finish documenting this function
804 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
805 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0, $id='') {
807 if ($nothing == 'choose') {
808 $nothing = get_string('choose') .'...';
811 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
812 if ($disabled) {
813 $attributes .= ' disabled="disabled"';
816 if ($tabindex) {
817 $attributes .= ' tabindex="'.$tabindex.'"';
820 if ($id ==='') {
821 $id = 'menu'.$name;
822 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
823 $id = str_replace('[', '', $id);
824 $id = str_replace(']', '', $id);
827 $output = '<select id="'.$id.'" name="'. $name .'" '. $attributes .'>' . "\n";
828 if ($nothing) {
829 $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
830 if ($nothingvalue === $selected) {
831 $output .= ' selected="selected"';
833 $output .= '>'. $nothing .'</option>' . "\n";
835 if (!empty($options)) {
836 foreach ($options as $value => $label) {
837 $output .= ' <option value="'. s($value) .'"';
838 if ((string)$value == (string)$selected) {
839 $output .= ' selected="selected"';
841 if ($label === '') {
842 $output .= '>'. $value .'</option>' . "\n";
843 } else {
844 $output .= '>'. $label .'</option>' . "\n";
848 $output .= '</select>' . "\n";
850 if ($return) {
851 return $output;
852 } else {
853 echo $output;
858 * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
859 * Other options like choose_from_menu.
861 function choose_from_menu_yesno($name, $selected, $script = '',
862 $return = false, $disabled = false, $tabindex = 0) {
863 return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
864 $selected, '', $script, '0', $return, $disabled, $tabindex);
868 * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
869 * including option headings with the first level.
871 function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
872 $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
874 if ($nothing == 'choose') {
875 $nothing = get_string('choose') .'...';
878 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
879 if ($disabled) {
880 $attributes .= ' disabled="disabled"';
883 if ($tabindex) {
884 $attributes .= ' tabindex="'.$tabindex.'"';
887 $output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
888 if ($nothing) {
889 $output .= ' <option value="'. $nothingvalue .'"'. "\n";
890 if ($nothingvalue === $selected) {
891 $output .= ' selected="selected"';
893 $output .= '>'. $nothing .'</option>' . "\n";
895 if (!empty($options)) {
896 foreach ($options as $section => $values) {
898 $output .= ' <optgroup label="'. s(format_string($section)) .'">'."\n";
899 foreach ($values as $value => $label) {
900 $output .= ' <option value="'. format_string($value) .'"';
901 if ((string)$value == (string)$selected) {
902 $output .= ' selected="selected"';
904 if ($label === '') {
905 $output .= '>'. $value .'</option>' . "\n";
906 } else {
907 $output .= '>'. $label .'</option>' . "\n";
910 $output .= ' </optgroup>'."\n";
913 $output .= '</select>' . "\n";
915 if ($return) {
916 return $output;
917 } else {
918 echo $output;
924 * Given an array of values, creates a group of radio buttons to be part of a form
926 * @param array $options An array of value-label pairs for the radio group (values as keys)
927 * @param string $name Name of the radiogroup (unique in the form)
928 * @param string $checked The value that is already checked
930 function choose_from_radio ($options, $name, $checked='', $return=false) {
932 static $idcounter = 0;
934 if (!$name) {
935 $name = 'unnamed';
938 $output = '<span class="radiogroup '.$name."\">\n";
940 if (!empty($options)) {
941 $currentradio = 0;
942 foreach ($options as $value => $label) {
943 $htmlid = 'auto-rb'.sprintf('%04d', ++$idcounter);
944 $output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
945 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
946 if ($value == $checked) {
947 $output .= ' checked="checked"';
949 if ($label === '') {
950 $output .= ' /> <label for="'.$htmlid.'">'. $value .'</label></span>' . "\n";
951 } else {
952 $output .= ' /> <label for="'.$htmlid.'">'. $label .'</label></span>' . "\n";
954 $currentradio = ($currentradio + 1) % 2;
958 $output .= '</span>' . "\n";
960 if ($return) {
961 return $output;
962 } else {
963 echo $output;
967 /** Display an standard html checkbox with an optional label
969 * @param string $name The name of the checkbox
970 * @param string $value The valus that the checkbox will pass when checked
971 * @param boolean $checked The flag to tell the checkbox initial state
972 * @param string $label The label to be showed near the checkbox
973 * @param string $alt The info to be inserted in the alt tag
975 function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
977 static $idcounter = 0;
979 if (!$name) {
980 $name = 'unnamed';
983 if ($alt) {
984 $alt = strip_tags($alt);
985 } else {
986 $alt = 'checkbox';
989 if ($checked) {
990 $strchecked = ' checked="checked"';
991 } else {
992 $strchecked = '';
995 $htmlid = 'auto-cb'.sprintf('%04d', ++$idcounter);
996 $output = '<span class="checkbox '.$name."\">";
997 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ? ' onclick="'.$script.'" ' : '').' />';
998 if(!empty($label)) {
999 $output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
1001 $output .= '</span>'."\n";
1003 if (empty($return)) {
1004 echo $output;
1005 } else {
1006 return $output;
1011 /** Display an standard html text field with an optional label
1013 * @param string $name The name of the text field
1014 * @param string $value The value of the text field
1015 * @param string $label The label to be showed near the text field
1016 * @param string $alt The info to be inserted in the alt tag
1018 function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
1020 static $idcounter = 0;
1022 if (empty($name)) {
1023 $name = 'unnamed';
1026 if (empty($alt)) {
1027 $alt = 'textfield';
1030 if (!empty($maxlength)) {
1031 $maxlength = ' maxlength="'.$maxlength.'" ';
1034 $htmlid = 'auto-tf'.sprintf('%04d', ++$idcounter);
1035 $output = '<span class="textfield '.$name."\">";
1036 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
1038 $output .= '</span>'."\n";
1040 if (empty($return)) {
1041 echo $output;
1042 } else {
1043 return $output;
1050 * Implements a complete little popup form
1052 * @uses $CFG
1053 * @param string $common The URL up to the point of the variable that changes
1054 * @param array $options Alist of value-label pairs for the popup list
1055 * @param string $formid Id must be unique on the page (originaly $formname)
1056 * @param string $selected The option that is already selected
1057 * @param string $nothing The label for the "no choice" option
1058 * @param string $help The name of a help page if help is required
1059 * @param string $helptext The name of the label for the help button
1060 * @param boolean $return Indicates whether the function should return the text
1061 * as a string or echo it directly to the page being rendered
1062 * @param string $targetwindow The name of the target page to open the linked page in.
1063 * @param string $selectlabel Text to place in a [label] element - preferred for accessibility.
1064 * @param array $optionsextra TODO, an array?
1065 * @return string If $return is true then the entire form is returned as a string.
1066 * @todo Finish documenting this function<br>
1068 function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
1069 $targetwindow='self', $selectlabel='', $optionsextra=NULL) {
1071 global $CFG;
1072 static $go, $choose; /// Locally cached, in case there's lots on a page
1074 if (empty($options)) {
1075 return '';
1078 if (!isset($go)) {
1079 $go = get_string('go');
1082 if ($nothing == 'choose') {
1083 if (!isset($choose)) {
1084 $choose = get_string('choose');
1086 $nothing = $choose.'...';
1089 // changed reference to document.getElementById('id_abc') instead of document.abc
1090 // MDL-7861
1091 $output = '<form action="'.$CFG->wwwroot.'/course/jumpto.php"'.
1092 ' method="get" '.
1093 $CFG->frametarget.
1094 ' id="'.$formid.'"'.
1095 ' class="popupform">';
1096 if ($help) {
1097 $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
1098 } else {
1099 $button = '';
1102 if ($selectlabel) {
1103 $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
1106 $output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" name="jump" onchange="'.$targetwindow.'.location=document.getElementById(\''.$formid.'\').jump.options[document.getElementById(\''.$formid.'\').jump.selectedIndex].value;">'."\n";
1108 if ($nothing != '') {
1109 $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
1112 $inoptgroup = false;
1114 foreach ($options as $value => $label) {
1116 if ($label == '--') { /// we are ending previous optgroup
1117 /// Check to see if we already have a valid open optgroup
1118 /// XHTML demands that there be at least 1 option within an optgroup
1119 if ($inoptgroup and (count($optgr) > 1) ) {
1120 $output .= implode('', $optgr);
1121 $output .= ' </optgroup>';
1123 $optgr = array();
1124 $inoptgroup = false;
1125 continue;
1126 } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
1128 /// Check to see if we already have a valid open optgroup
1129 /// XHTML demands that there be at least 1 option within an optgroup
1130 if ($inoptgroup and (count($optgr) > 1) ) {
1131 $output .= implode('', $optgr);
1132 $output .= ' </optgroup>';
1135 unset($optgr);
1136 $optgr = array();
1138 $optgr[] = ' <optgroup label="'. s(format_string(substr($label,2))) .'">'; // Plain labels
1140 $inoptgroup = true; /// everything following will be in an optgroup
1141 continue;
1143 } else {
1144 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()]))
1146 $url=sid_process_url( $common . $value );
1147 } else
1149 $url=$common . $value;
1151 $optstr = ' <option value="' . $url . '"';
1153 if ($value == $selected) {
1154 $optstr .= ' selected="selected"';
1157 if (!empty($optionsextra[$value])) {
1158 $optstr .= ' '.$optionsextra[$value];
1161 if ($label) {
1162 $optstr .= '>'. $label .'</option>' . "\n";
1163 } else {
1164 $optstr .= '>'. $value .'</option>' . "\n";
1167 if ($inoptgroup) {
1168 $optgr[] = $optstr;
1169 } else {
1170 $output .= $optstr;
1176 /// catch the final group if not closed
1177 if ($inoptgroup and count($optgr) > 1) {
1178 $output .= implode('', $optgr);
1179 $output .= ' </optgroup>';
1182 $output .= '</select>';
1183 $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1184 $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
1185 $output .= '<input type="submit" value="'.$go.'" /></div>';
1186 $output .= '<script type="text/javascript">'.
1187 "\n//<![CDATA[\n".
1188 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
1189 "\n//]]>\n".'</script>';
1190 $output .= '</div>';
1191 $output .= '</form>';
1193 if ($return) {
1194 return $output;
1195 } else {
1196 echo $output;
1202 * Prints some red text
1204 * @param string $error The text to be displayed in red
1206 function formerr($error) {
1208 if (!empty($error)) {
1209 echo '<span class="error">'. $error .'</span>';
1214 * Validates an email to make sure it makes sense.
1216 * @param string $address The email address to validate.
1217 * @return boolean
1219 function validate_email($address) {
1221 return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1222 '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1223 '@'.
1224 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1225 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
1226 $address));
1230 * Extracts file argument either from file parameter or PATH_INFO
1232 * @param string $scriptname name of the calling script
1233 * @return string file path (only safe characters)
1235 function get_file_argument($scriptname) {
1236 global $_SERVER;
1238 $relativepath = FALSE;
1240 // first try normal parameter (compatible method == no relative links!)
1241 $relativepath = optional_param('file', FALSE, PARAM_PATH);
1242 if ($relativepath === '/testslasharguments') {
1243 echo 'test -1 : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
1244 die;
1247 // then try extract file from PATH_INFO (slasharguments method)
1248 if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
1249 $path_info = $_SERVER['PATH_INFO'];
1250 // check that PATH_INFO works == must not contain the script name
1251 if (!strpos($path_info, $scriptname)) {
1252 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1253 if ($relativepath === '/testslasharguments') {
1254 echo 'test 1 : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
1255 die;
1260 // now if both fail try the old way
1261 // (for compatibility with misconfigured or older buggy php implementations)
1262 if (!$relativepath) {
1263 $arr = explode($scriptname, me());
1264 if (!empty($arr[1])) {
1265 $path_info = strip_querystring($arr[1]);
1266 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1267 if ($relativepath === '/testslasharguments') {
1268 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
1269 die;
1274 return $relativepath;
1278 * Searches the current environment variables for some slash arguments
1280 * @param string $file ?
1281 * @todo Finish documenting this function
1283 function get_slash_arguments($file='file.php') {
1285 if (!$string = me()) {
1286 return false;
1289 $pathinfo = explode($file, $string);
1291 if (!empty($pathinfo[1])) {
1292 return addslashes($pathinfo[1]);
1293 } else {
1294 return false;
1299 * Extracts arguments from "/foo/bar/something"
1300 * eg http://mysite.com/script.php/foo/bar/something
1302 * @param string $string ?
1303 * @param int $i ?
1304 * @return array|string
1305 * @todo Finish documenting this function
1307 function parse_slash_arguments($string, $i=0) {
1309 if (detect_munged_arguments($string)) {
1310 return false;
1312 $args = explode('/', $string);
1314 if ($i) { // return just the required argument
1315 return $args[$i];
1317 } else { // return the whole array
1318 array_shift($args); // get rid of the empty first one
1319 return $args;
1324 * Just returns an array of text formats suitable for a popup menu
1326 * @uses FORMAT_MOODLE
1327 * @uses FORMAT_HTML
1328 * @uses FORMAT_PLAIN
1329 * @uses FORMAT_MARKDOWN
1330 * @return array
1332 function format_text_menu() {
1334 return array (FORMAT_MOODLE => get_string('formattext'),
1335 FORMAT_HTML => get_string('formathtml'),
1336 FORMAT_PLAIN => get_string('formatplain'),
1337 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1341 * Given text in a variety of format codings, this function returns
1342 * the text as safe HTML.
1344 * @uses $CFG
1345 * @uses FORMAT_MOODLE
1346 * @uses FORMAT_HTML
1347 * @uses FORMAT_PLAIN
1348 * @uses FORMAT_WIKI
1349 * @uses FORMAT_MARKDOWN
1350 * @param string $text The text to be formatted. This is raw text originally from user input.
1351 * @param int $format Identifier of the text format to be used
1352 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1353 * @param array $options ?
1354 * @param int $courseid ?
1355 * @return string
1356 * @todo Finish documenting this function
1358 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1360 global $CFG, $COURSE;
1362 if ($text === '') {
1363 return ''; // no need to do any filters and cleaning
1366 if (!isset($options->trusttext)) {
1367 $options->trusttext = false;
1370 if (!isset($options->noclean)) {
1371 $options->noclean=false;
1373 if (!isset($options->nocache)) {
1374 $options->nocache=false;
1376 if (!isset($options->smiley)) {
1377 $options->smiley=true;
1379 if (!isset($options->filter)) {
1380 $options->filter=true;
1382 if (!isset($options->para)) {
1383 $options->para=true;
1385 if (!isset($options->newlines)) {
1386 $options->newlines=true;
1389 if (empty($courseid)) {
1390 $courseid = $COURSE->id;
1393 if (!empty($CFG->cachetext) and empty($options->nocache)) {
1394 $time = time() - $CFG->cachetext;
1395 $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);
1396 if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
1397 if ($oldcacheitem->timemodified >= $time) {
1398 return $oldcacheitem->formattedtext;
1403 // trusttext overrides the noclean option!
1404 if ($options->trusttext) {
1405 if (trusttext_present($text)) {
1406 $text = trusttext_strip($text);
1407 if (!empty($CFG->enabletrusttext)) {
1408 $options->noclean = true;
1409 } else {
1410 $options->noclean = false;
1412 } else {
1413 $options->noclean = false;
1415 } else if (!debugging('', DEBUG_DEVELOPER)) {
1416 // strip any forgotten trusttext in non-developer mode
1417 // do not forget to disable text cache when debugging trusttext!!
1418 $text = trusttext_strip($text);
1421 $CFG->currenttextiscacheable = true; // Default status - can be changed by any filter
1423 switch ($format) {
1424 case FORMAT_HTML:
1425 if ($options->smiley) {
1426 replace_smilies($text);
1428 if (!$options->noclean) {
1429 $text = clean_text($text, FORMAT_HTML);
1431 if ($options->filter) {
1432 $text = filter_text($text, $courseid);
1434 break;
1436 case FORMAT_PLAIN:
1437 $text = s($text); // cleans dangerous JS
1438 $text = rebuildnolinktag($text);
1439 $text = str_replace(' ', '&nbsp; ', $text);
1440 $text = nl2br($text);
1441 break;
1443 case FORMAT_WIKI:
1444 // this format is deprecated
1445 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1446 this message as all texts should have been converted to Markdown format instead.
1447 Please post a bug report to http://moodle.org/bugs with information about where you
1448 saw this message.</p>'.s($text);
1449 break;
1451 case FORMAT_MARKDOWN:
1452 $text = markdown_to_html($text);
1453 if ($options->smiley) {
1454 replace_smilies($text);
1456 if (!$options->noclean) {
1457 $text = clean_text($text, FORMAT_HTML);
1460 if ($options->filter) {
1461 $text = filter_text($text, $courseid);
1463 break;
1465 default: // FORMAT_MOODLE or anything else
1466 $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
1467 if (!$options->noclean) {
1468 $text = clean_text($text, FORMAT_HTML);
1471 if ($options->filter) {
1472 $text = filter_text($text, $courseid);
1474 break;
1477 if (empty($options->nocache) and !empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
1478 $newcacheitem = new object();
1479 $newcacheitem->md5key = $md5key;
1480 $newcacheitem->formattedtext = addslashes($text);
1481 $newcacheitem->timemodified = time();
1482 if ($oldcacheitem) { // See bug 4677 for discussion
1483 $newcacheitem->id = $oldcacheitem->id;
1484 @update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1485 // It's unlikely that the cron cache cleaner could have
1486 // deleted this entry in the meantime, as it allows
1487 // some extra time to cover these cases.
1488 } else {
1489 @insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1490 // Again, it's possible that another user has caused this
1491 // record to be created already in the time that it took
1492 // to traverse this function. That's OK too, as the
1493 // call above handles duplicate entries, and eventually
1494 // the cron cleaner will delete them.
1498 return $text;
1501 /** Converts the text format from the value to the 'internal'
1502 * name or vice versa. $key can either be the value or the name
1503 * and you get the other back.
1505 * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1506 * @return mixed as above but the other way around!
1508 function text_format_name( $key ) {
1509 $lookup = array();
1510 $lookup[FORMAT_MOODLE] = 'moodle';
1511 $lookup[FORMAT_HTML] = 'html';
1512 $lookup[FORMAT_PLAIN] = 'plain';
1513 $lookup[FORMAT_MARKDOWN] = 'markdown';
1514 $value = "error";
1515 if (!is_numeric($key)) {
1516 $key = strtolower( $key );
1517 $value = array_search( $key, $lookup );
1519 else {
1520 if (isset( $lookup[$key] )) {
1521 $value = $lookup[ $key ];
1524 return $value;
1528 /** Given a simple string, this function returns the string
1529 * processed by enabled filters if $CFG->filterall is enabled
1531 * @param string $string The string to be filtered.
1532 * @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
1533 * @param int $courseid Current course as filters can, potentially, use it
1534 * @return string
1536 function format_string ($string, $striplinks=true, $courseid=NULL ) {
1538 global $CFG, $COURSE;
1540 //We'll use a in-memory cache here to speed up repeated strings
1541 static $strcache = false;
1543 if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
1544 $strcache = array();
1547 //init course id
1548 if (empty($courseid)) {
1549 $courseid = $COURSE->id;
1552 //Calculate md5
1553 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
1555 //Fetch from cache if possible
1556 if (isset($strcache[$md5])) {
1557 return $strcache[$md5];
1560 // First replace all ampersands not followed by html entity code
1561 $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1563 if (!empty($CFG->filterall)) {
1564 $string = filter_string($string, $courseid);
1567 // If the site requires it, strip ALL tags from this string
1568 if (!empty($CFG->formatstringstriptags)) {
1569 $string = strip_tags($string);
1571 // Otherwise strip just links if that is required (default)
1572 } else if ($striplinks) { //strip links in string
1573 $string = preg_replace('/(<a[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1576 //Store to cache
1577 $strcache[$md5] = $string;
1579 return $string;
1583 * Given text in a variety of format codings, this function returns
1584 * the text as plain text suitable for plain email.
1586 * @uses FORMAT_MOODLE
1587 * @uses FORMAT_HTML
1588 * @uses FORMAT_PLAIN
1589 * @uses FORMAT_WIKI
1590 * @uses FORMAT_MARKDOWN
1591 * @param string $text The text to be formatted. This is raw text originally from user input.
1592 * @param int $format Identifier of the text format to be used
1593 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1594 * @return string
1596 function format_text_email($text, $format) {
1598 switch ($format) {
1600 case FORMAT_PLAIN:
1601 return $text;
1602 break;
1604 case FORMAT_WIKI:
1605 $text = wiki_to_html($text);
1606 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1607 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
1608 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1609 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1610 break;
1612 case FORMAT_HTML:
1613 return html_to_text($text);
1614 break;
1616 case FORMAT_MOODLE:
1617 case FORMAT_MARKDOWN:
1618 default:
1619 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1620 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1621 break;
1626 * Given some text in HTML format, this function will pass it
1627 * through any filters that have been defined in $CFG->textfilterx
1628 * The variable defines a filepath to a file containing the
1629 * filter function. The file must contain a variable called
1630 * $textfilter_function which contains the name of the function
1631 * with $courseid and $text parameters
1633 * @param string $text The text to be passed through format filters
1634 * @param int $courseid ?
1635 * @return string
1636 * @todo Finish documenting this function
1638 function filter_text($text, $courseid=NULL) {
1639 global $CFG, $COURSE;
1641 if (empty($courseid)) {
1642 $courseid = $COURSE->id; // (copied from format_text)
1645 if (!empty($CFG->textfilters)) {
1646 require_once($CFG->libdir.'/filterlib.php');
1647 $textfilters = explode(',', $CFG->textfilters);
1648 foreach ($textfilters as $textfilter) {
1649 if (is_readable($CFG->dirroot .'/'. $textfilter .'/filter.php')) {
1650 include_once($CFG->dirroot .'/'. $textfilter .'/filter.php');
1651 $functionname = basename($textfilter).'_filter';
1652 if (function_exists($functionname)) {
1653 $text = $functionname($courseid, $text);
1659 /// <nolink> tags removed for XHTML compatibility
1660 $text = str_replace('<nolink>', '', $text);
1661 $text = str_replace('</nolink>', '', $text);
1663 return $text;
1668 * Given a string (short text) in HTML format, this function will pass it
1669 * through any filters that have been defined in $CFG->stringfilters
1670 * The variable defines a filepath to a file containing the
1671 * filter function. The file must contain a variable called
1672 * $textfilter_function which contains the name of the function
1673 * with $courseid and $text parameters
1675 * @param string $string The text to be passed through format filters
1676 * @param int $courseid The id of a course
1677 * @return string
1679 function filter_string($string, $courseid=NULL) {
1680 global $CFG, $COURSE;
1682 if (empty($CFG->textfilters)) { // All filters are disabled anyway so quit
1683 return $string;
1686 if (empty($courseid)) {
1687 $courseid = $COURSE->id;
1690 require_once($CFG->libdir.'/filterlib.php');
1692 if (isset($CFG->stringfilters)) { // We have a predefined list to use, great!
1693 if (empty($CFG->stringfilters)) { // but it's blank, so finish now
1694 return $string;
1696 $stringfilters = explode(',', $CFG->stringfilters); // ..use the list we have
1698 } else { // Otherwise try to derive a list from textfilters
1699 if (strpos($CFG->textfilters, 'filter/multilang') !== false) { // Multilang is here
1700 $stringfilters = array('filter/multilang'); // Let's use just that
1701 $CFG->stringfilters = 'filter/multilang'; // Save it for next time through
1702 } else {
1703 $CFG->stringfilters = ''; // Save the result and return
1704 return $string;
1709 foreach ($stringfilters as $stringfilter) {
1710 if (is_readable($CFG->dirroot .'/'. $stringfilter .'/filter.php')) {
1711 include_once($CFG->dirroot .'/'. $stringfilter .'/filter.php');
1712 $functionname = basename($stringfilter).'_filter';
1713 if (function_exists($functionname)) {
1714 $string = $functionname($courseid, $string);
1719 /// <nolink> tags removed for XHTML compatibility
1720 $string = str_replace('<nolink>', '', $string);
1721 $string = str_replace('</nolink>', '', $string);
1723 return $string;
1727 * Is the text marked as trusted?
1729 * @param string $text text to be searched for TRUSTTEXT marker
1730 * @return boolean
1732 function trusttext_present($text) {
1733 if (strpos($text, TRUSTTEXT) !== FALSE) {
1734 return true;
1735 } else {
1736 return false;
1741 * This funtion MUST be called before the cleaning or any other
1742 * function that modifies the data! We do not know the origin of trusttext
1743 * in database, if it gets there in tweaked form we must not convert it
1744 * to supported form!!!
1746 * Please be carefull not to use stripslashes on data from database
1747 * or twice stripslashes when processing data recieved from user.
1749 * @param string $text text that may contain TRUSTTEXT marker
1750 * @return text without any TRUSTTEXT marker
1752 function trusttext_strip($text) {
1753 global $CFG;
1755 while (true) { //removing nested TRUSTTEXT
1756 $orig = $text;
1757 $text = str_replace(TRUSTTEXT, '', $text);
1758 if (strcmp($orig, $text) === 0) {
1759 return $text;
1765 * Mark text as trusted, such text may contain any HTML tags because the
1766 * normal text cleaning will be bypassed.
1767 * Please make sure that the text comes from trusted user before storing
1768 * it into database!
1770 function trusttext_mark($text) {
1771 global $CFG;
1772 if (!empty($CFG->enabletrusttext) and (strpos($text, TRUSTTEXT) === FALSE)) {
1773 return TRUSTTEXT.$text;
1774 } else {
1775 return $text;
1778 function trusttext_after_edit(&$text, $context) {
1779 if (has_capability('moodle/site:trustcontent', $context)) {
1780 $text = trusttext_strip($text);
1781 $text = trusttext_mark($text);
1782 } else {
1783 $text = trusttext_strip($text);
1787 function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
1788 global $CFG;
1790 $options = new object();
1791 $options->smiley = false;
1792 $options->filter = false;
1793 if (!empty($CFG->enabletrusttext)
1794 and has_capability('moodle/site:trustcontent', $context)
1795 and trusttext_present($text)) {
1796 $options->noclean = true;
1797 } else {
1798 $options->noclean = false;
1800 $text = trusttext_strip($text);
1801 if ($usehtmleditor) {
1802 $text = format_text($text, $format, $options);
1803 $format = FORMAT_HTML;
1804 } else if (!$options->noclean){
1805 $text = clean_text($text, $format);
1810 * Given raw text (eg typed in by a user), this function cleans it up
1811 * and removes any nasty tags that could mess up Moodle pages.
1813 * @uses FORMAT_MOODLE
1814 * @uses FORMAT_PLAIN
1815 * @uses ALLOWED_TAGS
1816 * @param string $text The text to be cleaned
1817 * @param int $format Identifier of the text format to be used
1818 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1819 * @return string The cleaned up text
1821 function clean_text($text, $format=FORMAT_MOODLE) {
1823 global $ALLOWED_TAGS, $CFG;
1825 if (empty($text) or is_numeric($text)) {
1826 return (string)$text;
1829 switch ($format) {
1830 case FORMAT_PLAIN:
1831 case FORMAT_MARKDOWN:
1832 return $text;
1834 default:
1836 if (!empty($CFG->enablehtmlpurifier)) {
1837 $text = purify_html($text);
1838 } else {
1839 /// Fix non standard entity notations
1840 $text = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $text);
1841 $text = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $text);
1843 /// Remove tags that are not allowed
1844 $text = strip_tags($text, $ALLOWED_TAGS);
1846 /// Clean up embedded scripts and , using kses
1847 $text = cleanAttributes($text);
1849 /// Again remove tags that are not allowed
1850 $text = strip_tags($text, $ALLOWED_TAGS);
1854 /// Remove potential script events - some extra protection for undiscovered bugs in our code
1855 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
1856 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
1858 return $text;
1863 * KSES replacement cleaning function - uses HTML Purifier.
1865 function purify_html($text) {
1866 global $CFG;
1868 static $purifier = false;
1869 if (!$purifier) {
1870 make_upload_directory('cache/htmlpurifier', false);
1871 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.auto.php';
1872 $config = HTMLPurifier_Config::createDefault();
1873 $config->set('Core', 'AcceptFullDocuments', false);
1874 $config->set('Core', 'Encoding', 'UTF-8');
1875 $config->set('HTML', 'Doctype', 'XHTML 1.0 Transitional');
1876 $config->set('Cache', 'SerializerPath', $CFG->dataroot.'/cache/htmlpurifier');
1877 $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));
1878 $purifier = new HTMLPurifier($config);
1880 return $purifier->purify($text);
1884 * This function takes a string and examines it for HTML tags.
1885 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
1886 * which checks for attributes and filters them for malicious content
1887 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
1889 * @param string $str The string to be examined for html tags
1890 * @return string
1892 function cleanAttributes($str){
1893 $result = preg_replace_callback(
1894 '%(<[^>]*(>|$)|>)%m', #search for html tags
1895 "cleanAttributes2",
1896 $str
1898 return $result;
1902 * This function takes a string with an html tag and strips out any unallowed
1903 * protocols e.g. javascript:
1904 * It calls ancillary functions in kses which are prefixed by kses
1905 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
1907 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
1908 * element the html to be cleared
1909 * @return string
1911 function cleanAttributes2($htmlArray){
1913 global $CFG, $ALLOWED_PROTOCOLS;
1914 require_once($CFG->libdir .'/kses.php');
1916 $htmlTag = $htmlArray[1];
1917 if (substr($htmlTag, 0, 1) != '<') {
1918 return '&gt;'; //a single character ">" detected
1920 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
1921 return ''; // It's seriously malformed
1923 $slash = trim($matches[1]); //trailing xhtml slash
1924 $elem = $matches[2]; //the element name
1925 $attrlist = $matches[3]; // the list of attributes as a string
1927 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
1929 $attStr = '';
1930 foreach ($attrArray as $arreach) {
1931 $arreach['name'] = strtolower($arreach['name']);
1932 if ($arreach['name'] == 'style') {
1933 $value = $arreach['value'];
1934 while (true) {
1935 $prevvalue = $value;
1936 $value = kses_no_null($value);
1937 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
1938 $value = kses_decode_entities($value);
1939 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
1940 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
1941 if ($value === $prevvalue) {
1942 $arreach['value'] = $value;
1943 break;
1946 $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']);
1947 $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']);
1948 } else if ($arreach['name'] == 'href') {
1949 //Adobe Acrobat Reader XSS protection
1950 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd))[^a-z0-9_\.\-].*$/i', '$1', $arreach['value']);
1952 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
1955 $xhtml_slash = '';
1956 if (preg_match('%/\s*$%', $attrlist)) {
1957 $xhtml_slash = ' /';
1959 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
1963 * Replaces all known smileys in the text with image equivalents
1965 * @uses $CFG
1966 * @param string $text Passed by reference. The string to search for smily strings.
1967 * @return string
1969 function replace_smilies(&$text) {
1971 global $CFG;
1973 $lang = current_language();
1975 /// this builds the mapping array only once
1976 static $e = array();
1977 static $img = array();
1978 static $emoticons = array(
1979 ':-)' => 'smiley',
1980 ':)' => 'smiley',
1981 ':-D' => 'biggrin',
1982 ';-)' => 'wink',
1983 ':-/' => 'mixed',
1984 'V-.' => 'thoughtful',
1985 ':-P' => 'tongueout',
1986 'B-)' => 'cool',
1987 '^-)' => 'approve',
1988 '8-)' => 'wideeyes',
1989 ':o)' => 'clown',
1990 ':-(' => 'sad',
1991 ':(' => 'sad',
1992 '8-.' => 'shy',
1993 ':-I' => 'blush',
1994 ':-X' => 'kiss',
1995 '8-o' => 'surprise',
1996 'P-|' => 'blackeye',
1997 '8-[' => 'angry',
1998 'xx-P' => 'dead',
1999 '|-.' => 'sleepy',
2000 '}-]' => 'evil',
2001 '(h)' => 'heart',
2002 '(heart)' => 'heart',
2003 '(y)' => 'yes',
2004 '(n)' => 'no',
2005 '(martin)' => 'martin',
2006 '( )' => 'egg'
2009 if (empty($img[$lang])) { /// After the first time this is not run again
2010 $e[$lang] = array();
2011 $img[$lang] = array();
2012 foreach ($emoticons as $emoticon => $image){
2013 $alttext = get_string($image, 'pix');
2015 $e[$lang][] = $emoticon;
2016 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath .'/s/'. $image .'.gif" />';
2020 // Exclude from transformations all the code inside <script> tags
2021 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
2022 // Based on code from glossary fiter by Williams Castillo.
2023 // - Eloy
2025 // Detect all the <script> zones to take out
2026 $excludes = array();
2027 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
2029 // Take out all the <script> zones from text
2030 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
2031 $excludes['<+'.$key.'+>'] = $value;
2033 if ($excludes) {
2034 $text = str_replace($excludes,array_keys($excludes),$text);
2037 /// this is the meat of the code - this is run every time
2038 $text = str_replace($e[$lang], $img[$lang], $text);
2040 // Recover all the <script> zones to text
2041 if ($excludes) {
2042 $text = str_replace(array_keys($excludes),$excludes,$text);
2047 * Given plain text, makes it into HTML as nicely as possible.
2048 * May contain HTML tags already
2050 * @uses $CFG
2051 * @param string $text The string to convert.
2052 * @param boolean $smiley Convert any smiley characters to smiley images?
2053 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
2054 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2055 * @return string
2058 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
2061 global $CFG;
2063 /// Remove any whitespace that may be between HTML tags
2064 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
2066 /// Remove any returns that precede or follow HTML tags
2067 $text = eregi_replace("([\n\r])<", " <", $text);
2068 $text = eregi_replace(">([\n\r])", "> ", $text);
2070 convert_urls_into_links($text);
2072 /// Make returns into HTML newlines.
2073 if ($newlines) {
2074 $text = nl2br($text);
2077 /// Turn smileys into images.
2078 if ($smiley) {
2079 replace_smilies($text);
2082 /// Wrap the whole thing in a paragraph tag if required
2083 if ($para) {
2084 return '<p>'.$text.'</p>';
2085 } else {
2086 return $text;
2091 * Given Markdown formatted text, make it into XHTML using external function
2093 * @uses $CFG
2094 * @param string $text The markdown formatted text to be converted.
2095 * @return string Converted text
2097 function markdown_to_html($text) {
2098 global $CFG;
2100 require_once($CFG->libdir .'/markdown.php');
2102 return Markdown($text);
2106 * Given HTML text, make it into plain text using external function
2108 * @uses $CFG
2109 * @param string $html The text to be converted.
2110 * @return string
2112 function html_to_text($html) {
2114 global $CFG;
2116 require_once($CFG->libdir .'/html2text.php');
2118 return html2text($html);
2122 * Given some text this function converts any URLs it finds into HTML links
2124 * @param string $text Passed in by reference. The string to be searched for urls.
2126 function convert_urls_into_links(&$text) {
2127 /// Make lone URLs into links. eg http://moodle.com/
2128 $text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
2129 "\\1<a href=\"\\2://\\3\\4\" target=\"_blank\">\\2://\\3\\4</a>", $text);
2131 /// eg www.moodle.com
2132 $text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
2133 "\\1<a href=\"http://www.\\2\\3\" target=\"_blank\">www.\\2\\3</a>", $text);
2137 * This function will highlight search words in a given string
2138 * It cares about HTML and will not ruin links. It's best to use
2139 * this function after performing any conversions to HTML.
2140 * Function found here: http://forums.devshed.com/t67822/scdaa2d1c3d4bacb4671d075ad41f0854.html
2142 * @param string $needle The string to search for
2143 * @param string $haystack The string to search for $needle in
2144 * @param int $case whether to do case-sensitive or insensitive matching.
2145 * @return string
2146 * @todo Finish documenting this function
2148 function highlight($needle, $haystack, $case=0,
2149 $left_string='<span class="highlight">', $right_string='</span>') {
2150 if (empty($needle)) {
2151 return $haystack;
2154 //$list_of_words = eregi_replace("[^-a-zA-Z0-9&.']", " ", $needle); // bug 3101
2155 $list_of_words = $needle;
2156 $list_array = explode(' ', $list_of_words);
2157 for ($i=0; $i<sizeof($list_array); $i++) {
2158 if (strlen($list_array[$i]) == 1) {
2159 $list_array[$i] = '';
2162 $list_of_words = implode(' ', $list_array);
2163 $list_of_words_cp = $list_of_words;
2164 $final = array();
2165 preg_match_all('/<(.+?)>/is',$haystack,$list_of_words);
2167 foreach (array_unique($list_of_words[0]) as $key=>$value) {
2168 $final['<|'.$key.'|>'] = $value;
2171 $haystack = str_replace($final,array_keys($final),$haystack);
2172 $list_of_words_cp = eregi_replace(' +', '|', $list_of_words_cp);
2174 if ($list_of_words_cp{0}=='|') {
2175 $list_of_words_cp{0} = '';
2177 if ($list_of_words_cp{strlen($list_of_words_cp)-1}=='|') {
2178 $list_of_words_cp{strlen($list_of_words_cp)-1}='';
2181 $list_of_words_cp = trim($list_of_words_cp);
2183 if ($list_of_words_cp) {
2185 $list_of_words_cp = "(". $list_of_words_cp .")";
2187 if (!$case){
2188 $haystack = eregi_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2189 } else {
2190 $haystack = ereg_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2193 $haystack = str_replace(array_keys($final),$final,$haystack);
2195 return $haystack;
2199 * This function will highlight instances of $needle in $haystack
2200 * It's faster that the above function and doesn't care about
2201 * HTML or anything.
2203 * @param string $needle The string to search for
2204 * @param string $haystack The string to search for $needle in
2205 * @return string
2207 function highlightfast($needle, $haystack) {
2209 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
2211 $pos = 0;
2213 foreach ($parts as $key => $part) {
2214 $parts[$key] = substr($haystack, $pos, strlen($part));
2215 $pos += strlen($part);
2217 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2218 $pos += strlen($needle);
2221 return (join('', $parts));
2225 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2226 * Internationalisation, for print_header and backup/restorelib.
2227 * @param $dir Default false.
2228 * @return string Attributes.
2230 function get_html_lang($dir = false) {
2231 $direction = '';
2232 if ($dir) {
2233 if (get_string('thisdirection') == 'rtl') {
2234 $direction = ' dir="rtl"';
2235 } else {
2236 $direction = ' dir="ltr"';
2239 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2240 $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
2241 @header('Content-Language: '.$language);
2242 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2246 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
2249 * Print a standard header
2251 * @uses $USER
2252 * @uses $CFG
2253 * @uses $SESSION
2254 * @param string $title Appears at the top of the window
2255 * @param string $heading Appears at the top of the page
2256 * @param array $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
2257 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2258 * @param string $meta Meta tags to be added to the header
2259 * @param boolean $cache Should this page be cacheable?
2260 * @param string $button HTML code for a button (usually for module editing)
2261 * @param string $menu HTML code for a popup menu
2262 * @param boolean $usexml use XML for this page
2263 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2264 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2266 function print_header ($title='', $heading='', $navigation='', $focus='',
2267 $meta='', $cache=true, $button='&nbsp;', $menu='',
2268 $usexml=false, $bodytags='', $return=false) {
2270 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
2272 if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
2273 debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
2274 . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.");
2277 $heading = format_string($heading); // Fix for MDL-8582
2279 /// This makes sure that the header is never repeated twice on a page
2280 if (defined('HEADER_PRINTED')) {
2281 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().');
2282 return;
2284 define('HEADER_PRINTED', 'true');
2287 /// Add the required stylesheets
2288 $stylesheetshtml = '';
2289 foreach ($CFG->stylesheets as $stylesheet) {
2290 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2292 $meta = $stylesheetshtml.$meta;
2295 /// Add the meta page from the themes if any were requested
2297 $metapage = '';
2299 if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
2300 ob_start();
2301 include_once($CFG->dirroot.'/theme/standard/meta.php');
2302 $metapage .= ob_get_contents();
2303 ob_end_clean();
2306 if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
2307 if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
2308 ob_start();
2309 include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
2310 $metapage .= ob_get_contents();
2311 ob_end_clean();
2315 if (!isset($THEME->metainclude) || $THEME->metainclude) {
2316 if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
2317 ob_start();
2318 include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
2319 $metapage .= ob_get_contents();
2320 ob_end_clean();
2324 $meta = $meta."\n".$metapage;
2327 /// Add the required JavaScript Libraries for AJAX
2328 // if (!empty($CFG->enableajax)) { // This is the way all JS should be included, so get rid of the test.
2329 $meta .= "\n".require_js();
2330 // }
2332 /// Set up some navigation variables
2334 if (is_newnav($navigation)){
2335 $home = false;
2336 } else {
2337 if ($navigation == 'home') {
2338 $home = true;
2339 $navigation = '';
2340 } else {
2341 $home = false;
2345 /// This is another ugly hack to make navigation elements available to print_footer later
2346 $THEME->title = $title;
2347 $THEME->heading = $heading;
2348 $THEME->navigation = $navigation;
2349 $THEME->button = $button;
2350 $THEME->menu = $menu;
2351 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2353 if ($button == '') {
2354 $button = '&nbsp;';
2357 if (!$menu and $navigation) {
2358 if (empty($CFG->loginhttps)) {
2359 $wwwroot = $CFG->wwwroot;
2360 } else {
2361 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
2363 $menu = user_login_string($COURSE);
2366 if (isset($SESSION->justloggedin)) {
2367 unset($SESSION->justloggedin);
2368 if (!empty($CFG->displayloginfailures)) {
2369 if (!empty($USER->username) and $USER->username != 'guest') {
2370 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
2371 $menu .= '&nbsp;<font size="1">';
2372 if (empty($count->accounts)) {
2373 $menu .= get_string('failedloginattempts', '', $count);
2374 } else {
2375 $menu .= get_string('failedloginattemptsall', '', $count);
2377 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
2378 $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
2379 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
2381 $menu .= '</font>';
2388 $meta = '<meta http-equiv="content-type" content="text/html; charset=utf-8" />' .
2389 "\n" . $meta . "\n";
2390 if (!$usexml) {
2391 @header('Content-type: text/html; charset=utf-8');
2394 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2395 $direction = get_html_lang($dir=true);
2397 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2398 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2399 @header('Pragma: no-cache');
2400 @header('Expires: ');
2401 } else { // Do everything we can to always prevent clients and proxies caching
2402 @header('Cache-Control: no-store, no-cache, must-revalidate');
2403 @header('Cache-Control: post-check=0, pre-check=0', false);
2404 @header('Pragma: no-cache');
2405 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2406 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2408 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2409 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
2411 @header('Accept-Ranges: none');
2413 $currentlanguage = current_language();
2415 if (empty($usexml)) {
2416 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2417 } else {
2418 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2419 if(!$mathplayer) {
2420 header('Content-Type: application/xhtml+xml');
2422 echo '<?xml version="1.0" ?>'."\n";
2423 if (!empty($CFG->xml_stylesheets)) {
2424 $stylesheets = explode(';', $CFG->xml_stylesheets);
2425 foreach ($stylesheets as $stylesheet) {
2426 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
2429 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
2430 if (!empty($CFG->xml_doctype_extra)) {
2431 echo ' plus '. $CFG->xml_doctype_extra;
2433 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
2434 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2435 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
2436 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2437 $direction";
2438 if($mathplayer) {
2439 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
2440 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2441 $meta .= '</object>'."\n";
2442 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2446 // Clean up the title
2448 $title = format_string($title); // fix for MDL-8582
2449 $title = str_replace('"', '&quot;', $title);
2451 // Create class and id for this page
2453 page_id_and_class($pageid, $pageclass);
2455 $pageclass .= ' course-'.$COURSE->id;
2457 if (($pageid != 'site-index') && ($pageid != 'course-view') &&
2458 (strstr($pageid, 'admin') === FALSE)) {
2459 $pageclass .= ' nocoursepage';
2462 if (!isloggedin()) {
2463 $pageclass .= ' notloggedin';
2466 if (!empty($USER->editing)) {
2467 $pageclass .= ' editing';
2470 if (!empty($CFG->blocksdrag)) {
2471 $pageclass .= ' drag';
2474 $pageclass .= ' dir-'.get_string('thisdirection');
2476 $pageclass .= ' lang-'.$currentlanguage;
2478 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
2480 ob_start();
2481 include($CFG->header);
2482 $output = ob_get_contents();
2483 ob_end_clean();
2485 $output = force_strict_header($output);
2487 if (!empty($CFG->messaging)) {
2488 $output .= message_popup_window();
2491 if ($return) {
2492 return $output;
2493 } else {
2494 echo $output;
2499 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2500 * and substitute the XHTML strict document type.
2501 * Note, requires the 'xmlns' fix in function print_header above.
2502 * See: http://tracker.moodle.org/browse/MDL-7883
2503 * TODO:
2505 function force_strict_header($output) {
2506 global $CFG;
2507 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2508 $xsl = '/lib/xhtml.xsl';
2510 if (!headers_sent() && !empty($CFG->xmlstrictheaders)) { // With xml strict headers, the browser will barf
2511 $ctype = 'Content-Type: ';
2512 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2514 if (isset($_SERVER['HTTP_ACCEPT'])
2515 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2516 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2517 // Firefox et al.
2518 $ctype .= 'application/xhtml+xml';
2519 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2521 } else if (file_exists($CFG->dirroot.$xsl)
2522 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2523 // XSL hack for IE 5+ on Windows.
2524 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2525 $www_xsl = $CFG->wwwroot .$xsl;
2526 $ctype .= 'application/xml';
2527 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2528 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2530 } else {
2531 //ELSE: Mac/IE, old/non-XML browsers.
2532 $ctype .= 'text/html';
2533 $prolog = '';
2535 @header($ctype.'; charset=utf-8');
2536 $output = $prolog . $output;
2538 // Test parser error-handling.
2539 if (isset($_GET['error'])) {
2540 $output .= "__ TEST: XML well-formed error < __\n";
2544 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
2546 return $output;
2552 * This version of print_header is simpler because the course name does not have to be
2553 * provided explicitly in the strings. It can be used on the site page as in courses
2554 * Eventually all print_header could be replaced by print_header_simple
2556 * @param string $title Appears at the top of the window
2557 * @param string $heading Appears at the top of the page
2558 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2559 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2560 * @param string $meta Meta tags to be added to the header
2561 * @param boolean $cache Should this page be cacheable?
2562 * @param string $button HTML code for a button (usually for module editing)
2563 * @param string $menu HTML code for a popup menu
2564 * @param boolean $usexml use XML for this page
2565 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2566 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2568 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
2569 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
2571 global $COURSE, $CFG;
2573 $shortname ='';
2574 if ($COURSE->id != SITEID) {
2575 $shortname = '<a href="'.$CFG->wwwroot.'/course/view.php?id='. $COURSE->id .'">'. $COURSE->shortname .'</a> ->';
2578 // If old style nav prepend course short name otherwise leave $navigation object alone
2579 if (!is_newnav($navigation)) {
2580 $navigation = $shortname.' '.$navigation;
2583 $output = print_header($COURSE->shortname .': '. $title, $COURSE->fullname .' '. $heading, $navigation, $focus, $meta,
2584 $cache, $button, $menu, $usexml, $bodytags, true);
2586 if ($return) {
2587 return $output;
2588 } else {
2589 echo $output;
2595 * Can provide a course object to make the footer contain a link to
2596 * to the course home page, otherwise the link will go to the site home
2598 * @uses $CFG
2599 * @uses $USER
2600 * @param course $course {@link $COURSE} object containing course information
2601 * @param ? $usercourse ?
2602 * @todo Finish documenting this function
2604 function print_footer($course=NULL, $usercourse=NULL, $return=false) {
2605 global $USER, $CFG, $THEME, $COURSE;
2607 if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
2608 admin_externalpage_print_footer();
2609 return;
2612 /// Course links
2613 if ($course) {
2614 if (is_string($course) && $course == 'none') { // Don't print any links etc
2615 $homelink = '';
2616 $loggedinas = '';
2617 $home = false;
2618 } else if (is_string($course) && $course == 'home') { // special case for site home page - please do not remove
2619 $course = get_site();
2620 $homelink = '<div class="sitelink">'.
2621 '<a title="moodle '. $CFG->release .' ('. $CFG->version .')" href="http://moodle.org/">'.
2622 '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
2623 $home = true;
2624 } else {
2625 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
2626 '/course/view.php?id='.$course->id.'">'.format_string($course->shortname).'</a></div>';
2627 $home = false;
2629 } else {
2630 $course = get_site(); // Set course as site course by default
2631 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
2632 $home = false;
2635 /// Set up some other navigation links (passed from print_header by ugly hack)
2636 $menu = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
2637 $title = isset($THEME->title) ? $THEME->title : '';
2638 $button = isset($THEME->button) ? $THEME->button : '';
2639 $heading = isset($THEME->heading) ? $THEME->heading : '';
2640 $navigation = isset($THEME->navigation) ? $THEME->navigation : '';
2641 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2644 /// Set the user link if necessary
2645 if (!$usercourse and is_object($course)) {
2646 $usercourse = $course;
2649 if (!isset($loggedinas)) {
2650 $loggedinas = user_login_string($usercourse, $USER);
2653 if ($loggedinas == $menu) {
2654 $menu = '';
2657 /// Provide some performance info if required
2658 $performanceinfo = '';
2659 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2660 $perf = get_performance_info();
2661 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
2662 error_log("PERF: " . $perf['txt']);
2664 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
2665 $performanceinfo = $perf['html'];
2669 /// Close eventually open custom_corner divs
2670 if ((!empty($THEME->customcorners)) && ($THEME->customcornersopen > 1)) {
2671 require_once($CFG->dirroot.'/lib/custom_corners_lib.php');
2672 while ($THEME->customcornersopen > 1) {
2673 print_custom_corners_end();
2677 /// Include the actual footer file
2679 ob_start();
2680 include($CFG->footer);
2681 $output = ob_get_contents();
2682 ob_end_clean();
2684 if ($return) {
2685 return $output;
2686 } else {
2687 echo $output;
2692 * Returns the name of the current theme
2694 * @uses $CFG
2695 * @uses $USER
2696 * @uses $SESSION
2697 * @uses $COURSE
2698 * @uses $FULLME
2699 * @return string
2701 function current_theme() {
2702 global $CFG, $USER, $SESSION, $COURSE, $FULLME;
2704 if (empty($CFG->themeorder)) {
2705 $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
2706 } else {
2707 $themeorder = $CFG->themeorder;
2710 $theme = '';
2711 foreach ($themeorder as $themetype) {
2713 if (!empty($theme)) continue;
2715 switch ($themetype) {
2716 case 'page': // Page theme is for special page-only themes set by code
2717 if (!empty($CFG->pagetheme)) {
2718 $theme = $CFG->pagetheme;
2720 break;
2721 case 'course':
2722 if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) {
2723 $theme = $COURSE->theme;
2725 break;
2726 case 'category':
2727 if (!empty($CFG->allowcategorythemes)) {
2728 /// Nasty hack to check if we're in a category page
2729 if (stripos($FULLME, 'course/category.php') !== false) {
2730 global $id;
2731 if (!empty($id)) {
2732 $theme = current_category_theme($id);
2734 /// Otherwise check if we're in a course that has a category theme set
2735 } else if (!empty($COURSE->category)) {
2736 $theme = current_category_theme($COURSE->category);
2739 break;
2740 case 'session':
2741 if (!empty($SESSION->theme)) {
2742 $theme = $SESSION->theme;
2744 break;
2745 case 'user':
2746 if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) {
2747 $theme = $USER->theme;
2749 break;
2750 case 'site':
2751 $theme = $CFG->theme;
2752 break;
2753 default:
2754 /// do nothing
2758 /// A final check in case 'site' was not included in $CFG->themeorder
2759 if (empty($theme)) {
2760 $theme = $CFG->theme;
2763 return $theme;
2767 * Retrieves the category theme if one exists, otherwise checks the parent categories.
2768 * Recursive function.
2770 * @uses $COURSE
2771 * @param integer $categoryid id of the category to check
2772 * @return string theme name
2774 function current_category_theme($categoryid=0) {
2775 global $COURSE;
2777 /// Use the COURSE global if the categoryid not set
2778 if (empty($categoryid)) {
2779 if (!empty($COURSE->category)) {
2780 $categoryid = $COURSE->category;
2781 } else {
2782 return false;
2786 /// Retrieve the current category
2787 if ($category = get_record('course_categories', 'id', $categoryid)) {
2789 /// Return the category theme if it exists
2790 if (!empty($category->theme)) {
2791 return $category->theme;
2793 /// Otherwise try the parent category if one exists
2794 } else if (!empty($category->parent)) {
2795 return current_category_theme($category->parent);
2798 /// Return false if we can't find the category record
2799 } else {
2800 return false;
2805 * This function is called by stylesheets to set up the header
2806 * approriately as well as the current path
2808 * @uses $CFG
2809 * @param int $lastmodified ?
2810 * @param int $lifetime ?
2811 * @param string $thename ?
2813 function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
2815 global $CFG, $THEME;
2817 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
2818 $lastmodified = time();
2820 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
2821 header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
2822 header('Cache-Control: max-age='. $lifetime);
2823 header('Pragma: ');
2824 header('Content-type: text/css'); // Correct MIME type
2826 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
2828 if (empty($themename)) {
2829 $themename = current_theme(); // So we have something. Normally not needed.
2830 } else {
2831 $themename = clean_param($themename, PARAM_SAFEDIR);
2834 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
2835 unset($THEME);
2836 include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
2839 /// If this is the standard theme calling us, then find out what sheets we need
2841 if ($themename == 'standard') {
2842 if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
2843 $THEME->sheets = $DEFAULT_SHEET_LIST;
2844 } else if (empty($THEME->standardsheets)) { // We can stop right now!
2845 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
2846 exit;
2847 } else { // Use the provided subset only
2848 $THEME->sheets = $THEME->standardsheets;
2851 /// If we are a parent theme, then check for parent definitions
2853 } else if (!empty($THEME->parent) && $themename == $THEME->parent) {
2854 if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have
2855 $THEME->sheets = $DEFAULT_SHEET_LIST;
2856 } else if (empty($THEME->parentsheets)) { // We can stop right now!
2857 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
2858 exit;
2859 } else { // Use the provided subset only
2860 $THEME->sheets = $THEME->parentsheets;
2864 /// Work out the last modified date for this theme
2866 foreach ($THEME->sheets as $sheet) {
2867 if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
2868 $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
2869 if ($sheetmodified > $lastmodified) {
2870 $lastmodified = $sheetmodified;
2876 /// Get a list of all the files we want to include
2877 $files = array();
2879 foreach ($THEME->sheets as $sheet) {
2880 $files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
2883 if ($themename == 'standard') { // Add any standard styles included in any modules
2884 if (!empty($THEME->modsheets)) { // Search for styles.php within activity modules
2885 if ($mods = get_list_of_plugins('mod')) {
2886 foreach ($mods as $mod) {
2887 if (file_exists($CFG->dirroot.'/mod/'.$mod.'/styles.php')) {
2888 $files[] = array($CFG->dirroot, '/mod/'.$mod.'/styles.php');
2894 if (!empty($THEME->blocksheets)) { // Search for styles.php within block modules
2895 if ($mods = get_list_of_plugins('blocks')) {
2896 foreach ($mods as $mod) {
2897 if (file_exists($CFG->dirroot.'/blocks/'.$mod.'/styles.php')) {
2898 $files[] = array($CFG->dirroot, '/blocks/'.$mod.'/styles.php');
2904 if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
2905 if ($mods = get_list_of_plugins('format','',$CFG->dirroot.'/course')) {
2906 foreach ($mods as $mod) {
2907 if (file_exists($CFG->dirroot.'/course/format/'.$mod.'/styles.php')) {
2908 $files[] = array($CFG->dirroot, '/course/format/'.$mod.'/styles.php');
2914 if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
2915 if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
2916 $files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
2921 if ($files) {
2922 /// Produce a list of all the files first
2923 echo '/**************************************'."\n";
2924 echo ' * THEME NAME: '.$themename."\n *\n";
2925 echo ' * Files included in this sheet:'."\n *\n";
2926 foreach ($files as $file) {
2927 echo ' * '.$file[1]."\n";
2929 echo ' **************************************/'."\n\n";
2932 /// check if csscobstants is set
2933 if (!empty($THEME->cssconstants)) {
2934 require_once("$CFG->libdir/cssconstants.php");
2935 /// Actually collect all the files in order.
2936 $css = '';
2937 foreach ($files as $file) {
2938 $css .= '/***** '.$file[1].' start *****/'."\n\n";
2939 $css .= file_get_contents($file[0].'/'.$file[1]);
2940 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
2942 /// replace css_constants with their values
2943 echo replace_cssconstants($css);
2944 } else {
2945 /// Actually output all the files in order.
2946 if (empty($CFG->CSSEdit) && empty($THEME->CSSEdit)) {
2947 foreach ($files as $file) {
2948 echo '/***** '.$file[1].' start *****/'."\n\n";
2949 @include_once($file[0].'/'.$file[1]);
2950 echo '/***** '.$file[1].' end *****/'."\n\n";
2952 } else {
2953 foreach ($files as $file) {
2954 echo '/* @group '.$file[1].' */'."\n\n";
2955 if (strstr($file[1], '.css') !== FALSE) {
2956 echo '@import url("'.$CFG->themewww.'/'.$file[1].'");'."\n\n";
2957 } else {
2958 @include_once($file[0].'/'.$file[1]);
2960 echo '/* @end */'."\n\n";
2966 return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
2970 function theme_setup($theme = '', $params=NULL) {
2971 /// Sets up global variables related to themes
2973 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
2975 if (empty($theme)) {
2976 $theme = current_theme();
2979 /// If the theme doesn't exist for some reason then revert to standardwhite
2980 if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
2981 $CFG->theme = $theme = 'standardwhite';
2984 /// Load up the theme config
2985 $THEME = NULL; // Just to be sure
2986 include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
2988 /// Put together the parameters
2989 if (!$params) {
2990 $params = array();
2993 if ($theme != $CFG->theme) {
2994 $params[] = 'forceconfig='.$theme;
2997 /// Force language too if required
2998 if (!empty($THEME->langsheets)) {
2999 $params[] = 'lang='.current_language();
3003 /// Convert params to string
3004 if ($params) {
3005 $paramstring = '?'.implode('&', $params);
3006 } else {
3007 $paramstring = '';
3010 /// Set up image paths
3011 if(isset($CFG->smartpix) && $CFG->smartpix==1) {
3012 if($CFG->slasharguments) { // Use this method if possible for better caching
3013 $extra='';
3014 } else {
3015 $extra='?file=';
3018 $CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
3019 $CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
3020 } else if (empty($THEME->custompix)) { // Could be set in the above file
3021 $CFG->pixpath = $CFG->wwwroot .'/pix';
3022 $CFG->modpixpath = $CFG->wwwroot .'/mod';
3023 } else {
3024 $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
3025 $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
3028 /// Header and footer paths
3029 $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
3030 $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
3032 /// Define stylesheet loading order
3033 $CFG->stylesheets = array();
3034 if ($theme != 'standard') { /// The standard sheet is always loaded first
3035 $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
3037 if (!empty($THEME->parent)) { /// Parent stylesheets are loaded next
3038 $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
3040 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
3042 /// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
3043 if (!empty($HTTPSPAGEREQUIRED)) {
3044 $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
3045 $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
3046 $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
3047 foreach ($CFG->stylesheets as $key => $stylesheet) {
3048 $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
3052 // RTL support - only for RTL languages, add RTL CSS
3053 if (get_string('thisdirection') == 'rtl') {
3054 $CFG->stylesheets[] = $CFG->themewww.'/standard/rtl.css'.$paramstring;
3055 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/rtl.css'.$paramstring;
3061 * Returns text to be displayed to the user which reflects their login status
3063 * @uses $CFG
3064 * @uses $USER
3065 * @param course $course {@link $COURSE} object containing course information
3066 * @param user $user {@link $USER} object containing user information
3067 * @return string
3069 function user_login_string($course=NULL, $user=NULL) {
3070 global $USER, $CFG, $SITE;
3072 if (empty($user) and !empty($USER->id)) {
3073 $user = $USER;
3076 if (empty($course)) {
3077 $course = $SITE;
3080 if (!empty($user->realuser)) {
3081 if ($realuser = get_record('user', 'id', $user->realuser)) {
3082 $fullname = fullname($realuser, true);
3083 $realuserinfo = " [<a $CFG->frametarget
3084 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=1&amp;sesskey=".sesskey()."\">$fullname</a>] ";
3086 } else {
3087 $realuserinfo = '';
3090 if (empty($CFG->loginhttps)) {
3091 $wwwroot = $CFG->wwwroot;
3092 } else {
3093 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
3096 if (empty($course->id)) {
3097 // $course->id is not defined during installation
3098 return '';
3099 } else if (!empty($user->id)) {
3100 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3102 $fullname = fullname($user, true);
3103 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a>";
3104 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid)) {
3105 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
3107 if (isset($user->username) && $user->username == 'guest') {
3108 $loggedinas = $realuserinfo.get_string('loggedinasguest').
3109 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3110 } else if (!empty($user->access['rsw'][$context->path])) {
3111 $rolename = '';
3112 if ($role = get_record('role', 'id', $user->access['rsw'][$context->path])) {
3113 $rolename = ': '.format_string($role->name);
3115 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
3116 " (<a $CFG->frametarget
3117 href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
3118 } else {
3119 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
3120 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
3122 } else {
3123 $loggedinas = get_string('loggedinnot', 'moodle').
3124 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3126 return '<div class="logininfo">'.$loggedinas.'</div>';
3130 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
3131 * If not it applies sensible defaults.
3133 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
3134 * search forum block, etc. Important: these are 'silent' in a screen-reader
3135 * (unlike &gt; &raquo;), and must be accompanied by text.
3136 * @uses $THEME
3138 function check_theme_arrows() {
3139 global $THEME;
3141 if (!isset($THEME->rarrow) and !isset($THEME->larrow)) {
3142 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
3143 // Also OK in Win 9x/2K/IE 5.x
3144 $THEME->rarrow = '&#x25BA;';
3145 $THEME->larrow = '&#x25C4;';
3146 $uagent = $_SERVER['HTTP_USER_AGENT'];
3147 if (false !== strpos($uagent, 'Opera')
3148 || false !== strpos($uagent, 'Mac')) {
3149 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
3150 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
3151 $THEME->rarrow = '&#x25B6;';
3152 $THEME->larrow = '&#x25C0;';
3154 elseif (false !== strpos($uagent, 'Konqueror')) {
3155 $THEME->rarrow = '&rarr;';
3156 $THEME->larrow = '&larr;';
3158 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
3159 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
3160 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
3161 // To be safe, non-Unicode browsers!
3162 $THEME->rarrow = '&gt;';
3163 $THEME->larrow = '&lt;';
3166 /// RTL support - in RTL languages, swap r and l arrows
3167 if (right_to_left()) {
3168 $t = $THEME->rarrow;
3169 $THEME->rarrow = $THEME->larrow;
3170 $THEME->larrow = $t;
3177 * Return the right arrow with text ('next'), and optionally embedded in a link.
3178 * See function above, check_theme_arrows.
3179 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3180 * @param string $url An optional link to use in a surrounding HTML anchor.
3181 * @param bool $accesshide True if text should be hidden (for screen readers only).
3182 * @param string $addclass Additional class names for the link, or the arrow character.
3183 * @return string HTML string.
3185 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
3186 global $THEME;
3187 check_theme_arrows();
3188 $arrowclass = 'arrow ';
3189 if (! $url) {
3190 $arrowclass .= $addclass;
3192 $arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow.'</span>';
3193 $htmltext = '';
3194 if ($text) {
3195 $htmltext = $text.'&nbsp;';
3196 if ($accesshide) {
3197 $htmltext = get_accesshide($htmltext);
3200 if ($url) {
3201 $class = '';
3202 if ($addclass) {
3203 $class =" class=\"$addclass\"";
3205 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
3207 return $htmltext.$arrow;
3211 * Return the left arrow with text ('previous'), and optionally embedded in a link.
3212 * See function above, check_theme_arrows.
3213 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3214 * @param string $url An optional link to use in a surrounding HTML anchor.
3215 * @param bool $accesshide True if text should be hidden (for screen readers only).
3216 * @param string $addclass Additional class names for the link, or the arrow character.
3217 * @return string HTML string.
3219 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
3220 global $THEME;
3221 check_theme_arrows();
3222 $arrowclass = 'arrow ';
3223 if (! $url) {
3224 $arrowclass .= $addclass;
3226 $arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow.'</span>';
3227 $htmltext = '';
3228 if ($text) {
3229 $htmltext = '&nbsp;'.$text;
3230 if ($accesshide) {
3231 $htmltext = get_accesshide($htmltext);
3234 if ($url) {
3235 $class = '';
3236 if ($addclass) {
3237 $class =" class=\"$addclass\"";
3239 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
3241 return $arrow.$htmltext;
3245 * Return a HTML element with the class "accesshide", for accessibility.
3246 * Please use cautiously - where possible, text should be visible!
3247 * @param string $text Plain text.
3248 * @param string $elem Lowercase element name, default "span".
3249 * @param string $class Additional classes for the element.
3250 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
3251 * @return string HTML string.
3253 function get_accesshide($text, $elem='span', $class='', $attrs='') {
3254 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
3258 * Return the breadcrumb trail navigation separator.
3259 * @return string HTML string.
3261 function get_separator() {
3262 //Accessibility: the 'hidden' slash is preferred for screen readers.
3263 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
3267 * Prints breadcrumb trail of links, called in theme/-/header.html
3269 * @uses $CFG
3270 * @param mixed $navigation The breadcrumb navigation string to be printed
3271 * @param string $separator The breadcrumb trail separator. The default 0 leads to the use
3272 * of $THEME->rarrow, themes could use '&rarr;', '/', or '' for a style-sheet solution.
3273 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
3275 function print_navigation ($navigation, $separator=0, $return=false) {
3276 global $CFG, $THEME;
3277 $output = '';
3279 if (0 === $separator) {
3280 $separator = get_separator();
3282 else {
3283 $separator = '<span class="sep">'. $separator .'</span>';
3286 if ($navigation) {
3288 if (is_newnav($navigation)) {
3289 if ($return) {
3290 return($navigation['navlinks']);
3291 } else {
3292 echo $navigation['navlinks'];
3293 return;
3295 } else {
3296 debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER);
3299 if (!is_array($navigation)) {
3300 $ar = explode('->', $navigation);
3301 $navigation = array();
3303 foreach ($ar as $a) {
3304 if (strpos($a, '</a>') === false) {
3305 $navigation[] = array('title' => $a, 'url' => '');
3306 } else {
3307 if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
3308 $navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
3314 if (! $site = get_site()) {
3315 $site = new object();
3316 $site->shortname = get_string('home');
3319 //Accessibility: breadcrumb links now in a list, &raquo; replaced with a 'silent' character.
3320 $output .= get_accesshide(get_string('youarehere','access'), 'h2')."<ul>\n";
3322 $output .= '<li class="first">'."\n".'<a '.$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3323 .$CFG->wwwroot.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))
3324 && !empty($USER->id) && !empty($CFG->mymoodleredirect) && !isguest())
3325 ? '/my' : '') .'/">'. format_string($site->shortname) ."</a>\n</li>\n";
3328 foreach ($navigation as $navitem) {
3329 $title = trim(strip_tags(format_string($navitem['title'], false)));
3330 $url = $navitem['url'];
3332 if (empty($url)) {
3333 $output .= '<li class="first">'."$separator $title</li>\n";
3334 } else {
3335 $output .= '<li class="first">'."$separator\n<a ".$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3336 .$url.'">'."$title</a>\n</li>\n";
3340 $output .= "</ul>\n";
3343 if ($return) {
3344 return $output;
3345 } else {
3346 echo $output;
3351 * This function will build the navigation string to be used by print_header
3352 * and others
3353 * @uses $CFG
3354 * @uses $THEME
3355 * @param $extranavlinks - array of associative arrays, keys: name, link, type
3356 * @return $navigation as an object so it can be differentiated from old style
3357 * navigation strings.
3359 function build_navigation($extranavlinks) {
3360 global $CFG, $COURSE;
3362 $navigation = '';
3363 $navlinks = array();
3365 //Site name
3366 if ($site = get_site()) {
3367 $navlinks[] = array('name' => format_string($site->shortname),
3368 'link' => "$CFG->wwwroot/",
3369 'type' => 'home');
3373 if ($COURSE) {
3374 if ($COURSE->id != SITEID) {
3375 //Course
3376 $navlinks[] = array('name' => format_string($COURSE->shortname),
3377 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",
3378 'type' => 'course');
3382 //Merge in extra navigation links
3383 $navlinks = array_merge($navlinks, $extranavlinks);
3385 //Construct an unordered list from $navlinks
3386 //Accessibility: heading hidden from visual browsers by default.
3387 $navigation = '<h2 class="accesshide">'.get_string('youarehere','access')."</h2> <ul>\n";
3388 $countlinks = count($navlinks);
3389 $i = 0;
3390 foreach ($navlinks as $navlink) {
3391 if ($i >= $countlinks || !is_array($navlink)) {
3392 continue;
3394 // Check the link type to see if this link should appear in the trail
3396 // NOTE: we should move capchecks _out_ to the callers. build_navigation() is
3397 // called from many places -- install & upgrade for example -- where we cannot
3398 // count on the roles infrastructure to be defined.
3400 $cap = 0;
3401 if (!empty($COURSE->id) && $COURSE->id != SITEID) {
3402 if (!isset($COURSE->context)) {
3403 $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
3405 $cap = has_capability('moodle/course:manageactivities', $COURSE->context);
3407 $hidetype_is2 = isset($CFG->hideactivitytypenavlink) && $CFG->hideactivitytypenavlink == 2;
3408 $hidetype_is1 = isset($CFG->hideactivitytypenavlink) && $CFG->hideactivitytypenavlink == 1;
3410 if ($navlink['type'] == 'activity' &&
3411 $i+1 < $countlinks &&
3412 ($hidetype_is2 || ($hidetype_is1 && !$cap))) {
3413 continue;
3415 $navigation .= '<li class="first">';
3416 if ($i > 0) {
3417 $navigation .= get_separator();
3419 if ((!empty($navlink['link'])) && $i+1 < $countlinks) {
3420 $navigation .= "<a onclick=\"this.target='$CFG->framename'\" href=\"{$navlink['link']}\">";
3422 $navigation .= "{$navlink['name']}";
3423 if ((!empty($navlink['link'])) && $i+1 < $countlinks) {
3424 $navigation .= "</a>";
3427 $navigation .= "</li>";
3428 $i++;
3431 $navigation .= "</ul>";
3433 return(array('newnav' => true, 'navlinks' => $navigation));
3438 * Prints a string in a specified size (retained for backward compatibility)
3440 * @param string $text The text to be displayed
3441 * @param int $size The size to set the font for text display.
3443 function print_headline($text, $size=2, $return=false) {
3444 $output = print_heading($text, '', $size, true);
3445 if ($return) {
3446 return $output;
3447 } else {
3448 echo $output;
3453 * Prints text in a format for use in headings.
3455 * @param string $text The text to be displayed
3456 * @param string $align The alignment of the printed paragraph of text
3457 * @param int $size The size to set the font for text display.
3459 function print_heading($text, $align='', $size=2, $class='main', $return=false) {
3460 if ($align) {
3461 $align = ' style="text-align:'.$align.';"';
3463 if ($class) {
3464 $class = ' class="'.$class.'"';
3466 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
3468 if ($return) {
3469 return $output;
3470 } else {
3471 echo $output;
3476 * Centered heading with attached help button (same title text)
3477 * and optional icon attached
3479 * @param string $text The text to be displayed
3480 * @param string $helppage The help page to link to
3481 * @param string $module The module whose help should be linked to
3482 * @param string $icon Image to display if needed
3484 function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
3485 $output = '';
3486 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
3487 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
3488 $output .= '</h2>';
3490 if ($return) {
3491 return $output;
3492 } else {
3493 echo $output;
3498 function print_heading_block($heading, $class='', $return=false) {
3499 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
3500 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
3502 if ($return) {
3503 return $output;
3504 } else {
3505 echo $output;
3511 * Print a link to continue on to another page.
3513 * @uses $CFG
3514 * @param string $link The url to create a link to.
3516 function print_continue($link, $return=false) {
3518 global $CFG;
3520 // in case we are logging upgrade in admin/index.php stop it
3521 if (function_exists('upgrade_log_finish')) {
3522 upgrade_log_finish();
3525 $output = '';
3527 if ($link == '') {
3528 if (!empty($_SERVER['HTTP_REFERER'])) {
3529 $link = $_SERVER['HTTP_REFERER'];
3530 $link = str_replace('&', '&amp;', $link); // make it valid XHTML
3531 } else {
3532 $link = $CFG->wwwroot .'/';
3536 $output .= '<div class="continuebutton">';
3538 $output .= print_single_button($link, NULL, get_string('continue'), 'post', $CFG->framename, true);
3539 $output .= '</div>'."\n";
3541 if ($return) {
3542 return $output;
3543 } else {
3544 echo $output;
3550 * Print a message in a standard themed box.
3551 * Replaces print_simple_box (see deprecatedlib.php)
3553 * @param string $message, the content of the box
3554 * @param string $classes, space-separated class names.
3555 * @param string $ids, space-separated id names.
3556 * @param boolean $return, return as string or just print it
3558 function print_box($message, $classes='generalbox', $ids='', $return=false) {
3560 $output = print_box_start($classes, $ids, true);
3561 $output .= stripslashes_safe($message);
3562 $output .= print_box_end(true);
3564 if ($return) {
3565 return $output;
3566 } else {
3567 echo $output;
3572 * Starts a box using divs
3573 * Replaces print_simple_box_start (see deprecatedlib.php)
3575 * @param string $classes, space-separated class names.
3576 * @param string $ids, space-separated id names.
3577 * @param boolean $return, return as string or just print it
3579 function print_box_start($classes='generalbox', $ids='', $return=false) {
3580 $output = '';
3582 if ($ids) {
3583 $ids = ' id="'.$ids.'"';
3586 $output .= '<div'.$ids.' class="box '.$classes.'">';
3588 if ($return) {
3589 return $output;
3590 } else {
3591 echo $output;
3597 * Simple function to end a box (see above)
3598 * Replaces print_simple_box_end (see deprecatedlib.php)
3600 * @param boolean $return, return as string or just print it
3602 function print_box_end($return=false) {
3603 $output = '</div>';
3604 if ($return) {
3605 return $output;
3606 } else {
3607 echo $output;
3613 * Print a self contained form with a single submit button.
3615 * @param string $link ?
3616 * @param array $options ?
3617 * @param string $label ?
3618 * @param string $method ?
3619 * @todo Finish documenting this function
3621 function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='') {
3622 $output = '';
3623 $link = str_replace('"', '&quot;', $link); //basic XSS protection
3624 $output .= '<div class="singlebutton">';
3625 // taking target out, will need to add later target="'.$target.'"
3626 $output .= '<form action="'. $link .'" method="'. $method .'">';
3627 $output .= '<div>';
3628 if ($options) {
3629 foreach ($options as $name => $value) {
3630 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
3633 if ($tooltip) {
3634 $tooltip = 'title="' . s($tooltip) . '"';
3635 } else {
3636 $tooltip = '';
3638 $output .= '<input type="submit" value="'. s($label) .'" ' . $tooltip . ' /></div></form></div>';
3640 if ($return) {
3641 return $output;
3642 } else {
3643 echo $output;
3649 * Print a spacer image with the option of including a line break.
3651 * @param int $height ?
3652 * @param int $width ?
3653 * @param boolean $br ?
3654 * @todo Finish documenting this function
3656 function print_spacer($height=1, $width=1, $br=true, $return=false) {
3657 global $CFG;
3658 $output = '';
3660 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot .'/pix/spacer.gif" alt="" />';
3661 if ($br) {
3662 $output .= '<br />'."\n";
3665 if ($return) {
3666 return $output;
3667 } else {
3668 echo $output;
3673 * Given the path to a picture file in a course, or a URL,
3674 * this function includes the picture in the page.
3676 * @param string $path ?
3677 * @param int $courseid ?
3678 * @param int $height ?
3679 * @param int $width ?
3680 * @param string $link ?
3681 * @todo Finish documenting this function
3683 function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
3684 global $CFG;
3685 $output = '';
3687 if ($height) {
3688 $height = 'height="'. $height .'"';
3690 if ($width) {
3691 $width = 'width="'. $width .'"';
3693 if ($link) {
3694 $output .= '<a href="'. $link .'">';
3696 if (substr(strtolower($path), 0, 7) == 'http://') {
3697 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
3699 } else if ($courseid) {
3700 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
3701 if ($CFG->slasharguments) { // Use this method if possible for better caching
3702 $output .= $CFG->wwwroot .'/file.php/'. $courseid .'/'. $path;
3703 } else {
3704 $output .= $CFG->wwwroot .'/file.php?file=/'. $courseid .'/'. $path;
3706 $output .= '" />';
3707 } else {
3708 $output .= 'Error: must pass URL or course';
3710 if ($link) {
3711 $output .= '</a>';
3714 if ($return) {
3715 return $output;
3716 } else {
3717 echo $output;
3722 * Print the specified user's avatar.
3724 * If you pass a $user object that has id, picture, imagealt, firstname, lastname
3725 * you save a DB query.
3727 * @param int $user takes a userid, or a userobj
3728 * @param int $courseid ?
3729 * @param boolean $picture Print the user picture?
3730 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
3731 * @param boolean $return If false print picture to current page, otherwise return the output as string
3732 * @param boolean $link Enclose printed image in a link to view specified course?
3733 * @param string $target link target attribute
3734 * @param boolean $alttext use username or userspecified text in image alt attribute
3735 * return string
3736 * @todo Finish documenting this function
3738 function print_user_picture($user, $courseid, $picture=NULL, $size=0, $return=false, $link=true, $target='', $alttext=true) {
3739 global $CFG;
3741 $needrec = false;
3742 // only touch the DB if we are missing data...
3743 if (is_object($user)) {
3744 // Note - both picture and imagealt _can_ be empty
3745 // what we are trying to see here is if they have been fetched
3746 // from the DB. We should use isset() _except_ that some installs
3747 // have those fields as nullable, and isset() will return false
3748 // on null. The only safe thing is to ask array_key_exists()
3749 // which works on objects. property_exists() isn't quite
3750 // what we want here...
3751 if (! (array_key_exists('picture', $user)
3752 && ($alttext && array_key_exists('imagealt', $user)
3753 || (isset($user->firstname) && isset($user->lastname)))) ) {
3754 $needrec = true;
3755 $user = $user->id;
3757 } else {
3758 if ($alttext) {
3759 // we need firstname, lastname, imagealt, can't escape...
3760 $needrec = true;
3761 } else {
3762 $userobj = new StdClass; // fake it to save DB traffic
3763 $userobj->id = $user;
3764 $userobj->picture = $picture;
3765 $user = $userobj;
3766 unset($userobj);
3769 if ($needrec) {
3770 $user = get_record('user','id',$user);
3773 if ($link) {
3774 if ($target) {
3775 $target=' target="_blank"';
3777 $output = '<a '.$target.' href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&amp;course='. $courseid .'">';
3778 } else {
3779 $output = '';
3781 if (empty($size)) {
3782 $file = 'f2';
3783 $size = 35;
3784 } else if ($size === true or $size == 1) {
3785 $file = 'f1';
3786 $size = 100;
3787 } else if ($size >= 50) {
3788 $file = 'f1';
3789 } else {
3790 $file = 'f2';
3792 $class = "userpicture";
3793 if (!empty($HTTPSPAGEREQUIRED)) {
3794 $wwwroot = $CFG->httpswwwroot;
3795 } else {
3796 $wwwroot = $CFG->wwwroot;
3799 if (is_null($picture)) {
3800 $picture = $user->picture;
3803 if ($picture) { // Print custom user picture
3804 if ($CFG->slasharguments) { // Use this method if possible for better caching
3805 $src = $wwwroot .'/user/pix.php/'. $user->id .'/'. $file .'.jpg';
3806 } else {
3807 $src = $wwwroot .'/user/pix.php?file=/'. $user->id .'/'. $file .'.jpg';
3809 } else { // Print default user pictures (use theme version if available)
3810 $class .= " defaultuserpic";
3811 $src = "$CFG->pixpath/u/$file.png";
3813 $imagealt = '';
3814 if ($alttext) {
3815 if (!empty($user->imagealt)) {
3816 $imagealt = $user->imagealt;
3817 } else {
3818 $imagealt = get_string('pictureof','',fullname($user));
3822 $output .= '<img class="'.$class.'" src="'.$src.'" alt="'.s($imagealt).'" />';
3823 if ($link) {
3824 $output .= '</a>';
3827 if ($return) {
3828 return $output;
3829 } else {
3830 echo $output;
3835 * Prints a summary of a user in a nice little box.
3837 * @uses $CFG
3838 * @uses $USER
3839 * @param user $user A {@link $USER} object representing a user
3840 * @param course $course A {@link $COURSE} object representing a course
3842 function print_user($user, $course, $messageselect=false, $return=false) {
3844 global $CFG, $USER;
3846 $output = '';
3848 static $string;
3849 static $datestring;
3850 static $countries;
3852 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3854 if (empty($string)) { // Cache all the strings for the rest of the page
3856 $string->email = get_string('email');
3857 $string->location = get_string('location');
3858 $string->lastaccess = get_string('lastaccess');
3859 $string->activity = get_string('activity');
3860 $string->unenrol = get_string('unenrol');
3861 $string->loginas = get_string('loginas');
3862 $string->fullprofile = get_string('fullprofile');
3863 $string->role = get_string('role');
3864 $string->name = get_string('name');
3865 $string->never = get_string('never');
3867 $datestring->day = get_string('day');
3868 $datestring->days = get_string('days');
3869 $datestring->hour = get_string('hour');
3870 $datestring->hours = get_string('hours');
3871 $datestring->min = get_string('min');
3872 $datestring->mins = get_string('mins');
3873 $datestring->sec = get_string('sec');
3874 $datestring->secs = get_string('secs');
3875 $datestring->year = get_string('year');
3876 $datestring->years = get_string('years');
3878 $countries = get_list_of_countries();
3881 /// Get the hidden field list
3882 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
3883 $hiddenfields = array();
3884 } else {
3885 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
3888 $output .= '<table class="userinfobox">';
3889 $output .= '<tr>';
3890 $output .= '<td class="left side">';
3891 $output .= print_user_picture($user, $course->id, $user->picture, true, true);
3892 $output .= '</td>';
3893 $output .= '<td class="content">';
3894 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
3895 $output .= '<div class="info">';
3896 if (!empty($user->role) and ($user->role <> $course->teacher)) {
3897 $output .= $string->role .': '. $user->role .'<br />';
3899 if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguest()) or
3900 has_capability('moodle/course:viewhiddenuserfields', $context)) {
3901 $output .= $string->email .': <a href="mailto:'. $user->email .'">'. $user->email .'</a><br />';
3903 if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
3904 $output .= $string->location .': ';
3905 if ($user->city && !isset($hiddenfields['city'])) {
3906 $output .= $user->city;
3908 if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
3909 if ($user->city && !isset($hiddenfields['city'])) {
3910 $output .= ', ';
3912 $output .= $countries[$user->country];
3914 $output .= '<br />';
3917 if (!isset($hiddenfields['lastaccess'])) {
3918 if ($user->lastaccess) {
3919 $output .= $string->lastaccess .': '. userdate($user->lastaccess);
3920 $output .= '&nbsp; ('. format_time(time() - $user->lastaccess, $datestring) .')';
3921 } else {
3922 $output .= $string->lastaccess .': '. $string->never;
3925 $output .= '</div></td><td class="links">';
3926 //link to blogs
3927 if ($CFG->bloglevel > 0) {
3928 $output .= '<a href="'.$CFG->wwwroot.'/blog/index.php?userid='.$user->id.'">'.get_string('blogs','blog').'</a><br />';
3930 //link to notes
3931 if (has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context)) {
3932 $output .= '<a href="'.$CFG->wwwroot.'/notes/index.php?course=' . $course->id. '&amp;user='.$user->id.'">'.get_string('notes','notes').'</a><br />';
3935 if (has_capability('moodle/site:viewreports', $context)) {
3936 $timemidnight = usergetmidnight(time());
3937 $output .= '<a href="'. $CFG->wwwroot .'/course/user.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->activity .'</a><br />';
3939 if (has_capability('moodle/role:assign', $context, NULL)) { // Includes admins
3940 $output .= '<a href="'. $CFG->wwwroot .'/course/unenrol.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->unenrol .'</a><br />';
3942 if ($USER->id != $user->id && empty($USER->realuser) && has_capability('moodle/user:loginas', $context) &&
3943 ! has_capability('moodle/site:doanything', $context, $user->id, false)) {
3944 $output .= '<a href="'. $CFG->wwwroot .'/course/loginas.php?id='. $course->id .'&amp;user='. $user->id .'&amp;sesskey='. sesskey() .'">'. $string->loginas .'</a><br />';
3946 $output .= '<a href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&amp;course='. $course->id .'">'. $string->fullprofile .'...</a>';
3948 if (!empty($messageselect)) {
3949 $output .= '<br /><input type="checkbox" name="user'.$user->id.'" /> ';
3952 $output .= '</td></tr></table>';
3954 if ($return) {
3955 return $output;
3956 } else {
3957 echo $output;
3962 * Print a specified group's avatar.
3964 * @param group $group A single {@link group} object OR array of groups.
3965 * @param int $courseid The course ID.
3966 * @param boolean $large Default small picture, or large.
3967 * @param boolean $return If false print picture, otherwise return the output as string
3968 * @param boolean $link Enclose image in a link to view specified course?
3969 * @return string
3970 * @todo Finish documenting this function
3972 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
3973 global $CFG;
3975 if (is_array($group)) {
3976 $output = '';
3977 foreach($group as $g) {
3978 $output .= print_group_picture($g, $courseid, $large, true, $link);
3980 if ($return) {
3981 return $output;
3982 } else {
3983 echo $output;
3984 return;
3988 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3990 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
3991 return '';
3994 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
3995 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
3996 } else {
3997 $output = '';
3999 if ($large) {
4000 $file = 'f1';
4001 $size = 100;
4002 } else {
4003 $file = 'f2';
4004 $size = 35;
4006 if ($group->picture) { // Print custom group picture
4007 if ($CFG->slasharguments) { // Use this method if possible for better caching
4008 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot.'/user/pixgroup.php/'.$group->id.'/'.$file.'.jpg"'.
4009 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
4010 } else {
4011 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot.'/user/pixgroup.php?file=/'.$group->id.'/'.$file.'.jpg"'.
4012 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
4015 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4016 $output .= '</a>';
4019 if ($return) {
4020 return $output;
4021 } else {
4022 echo $output;
4027 * Print a png image.
4029 * @param string $url ?
4030 * @param int $sizex ?
4031 * @param int $sizey ?
4032 * @param boolean $return ?
4033 * @param string $parameters ?
4034 * @todo Finish documenting this function
4036 function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
4037 global $CFG;
4038 static $recentIE;
4040 if (!isset($recentIE)) {
4041 $recentIE = check_browser_version('MSIE', '5.0');
4044 if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
4045 $output .= '<img src="'. $CFG->pixpath .'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
4046 ' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
4047 ' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
4048 "'$url', sizingMethod='scale') ".
4049 ' '. $parameters .' />';
4050 } else {
4051 $output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
4054 if ($return) {
4055 return $output;
4056 } else {
4057 echo $output;
4062 * Print a nicely formatted table.
4064 * @param array $table is an object with several properties.
4065 * <ul>
4066 * <li>$table->head - An array of heading names.
4067 * <li>$table->align - An array of column alignments
4068 * <li>$table->size - An array of column sizes
4069 * <li>$table->wrap - An array of "nowrap"s or nothing
4070 * <li>$table->data[] - An array of arrays containing the data.
4071 * <li>$table->width - A percentage of the page
4072 * <li>$table->tablealign - Align the whole table
4073 * <li>$table->cellpadding - Padding on each cell
4074 * <li>$table->cellspacing - Spacing between cells
4075 * <li>$table->class - class attribute to put on the table
4076 * <li>$table->id - id attribute to put on the table.
4077 * <li>$table->rowclass[] - classes to add to particular rows.
4078 * </ul>
4079 * @param bool $return whether to return an output string or echo now
4080 * @return boolean or $string
4081 * @todo Finish documenting this function
4083 function print_table($table, $return=false) {
4084 $output = '';
4086 if (isset($table->align)) {
4087 foreach ($table->align as $key => $aa) {
4088 if ($aa) {
4089 $align[$key] = ' text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
4090 } else {
4091 $align[$key] = '';
4095 if (isset($table->size)) {
4096 foreach ($table->size as $key => $ss) {
4097 if ($ss) {
4098 $size[$key] = ' width:'. $ss .';';
4099 } else {
4100 $size[$key] = '';
4104 if (isset($table->wrap)) {
4105 foreach ($table->wrap as $key => $ww) {
4106 if ($ww) {
4107 $wrap[$key] = ' white-space:nowrap;';
4108 } else {
4109 $wrap[$key] = '';
4114 if (empty($table->width)) {
4115 $table->width = '80%';
4118 if (empty($table->tablealign)) {
4119 $table->tablealign = 'center';
4122 if (empty($table->cellpadding)) {
4123 $table->cellpadding = '5';
4126 if (empty($table->cellspacing)) {
4127 $table->cellspacing = '1';
4130 if (empty($table->class)) {
4131 $table->class = 'generaltable';
4134 $tableid = empty($table->id) ? '' : 'id="'.$table->id.'"';
4136 $output .= '<table width="'.$table->width.'" ';
4137 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
4139 $countcols = 0;
4141 if (!empty($table->head)) {
4142 $countcols = count($table->head);
4143 $output .= '<tr>';
4144 foreach ($table->head as $key => $heading) {
4146 if (!isset($size[$key])) {
4147 $size[$key] = '';
4149 if (!isset($align[$key])) {
4150 $align[$key] = '';
4153 $output .= '<th class="header c'.$key.'" scope="col">'. $heading .'</th>';
4154 // commenting the following code out as <th style does not validate MDL-7861
4155 //$output .= '<th sytle="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.'" scope="col">'. $heading .'</th>';
4157 $output .= '</tr>'."\n";
4160 if (!empty($table->data)) {
4161 $oddeven = 1;
4162 foreach ($table->data as $key => $row) {
4163 $oddeven = $oddeven ? 0 : 1;
4164 if (!isset($table->rowclass[$key])) {
4165 $table->rowclass[$key] = '';
4167 $output .= '<tr class="r'.$oddeven.' '.$table->rowclass[$key].'">'."\n";
4168 if ($row == 'hr' and $countcols) {
4169 $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
4170 } else { /// it's a normal row of data
4171 foreach ($row as $key => $item) {
4172 if (!isset($size[$key])) {
4173 $size[$key] = '';
4175 if (!isset($align[$key])) {
4176 $align[$key] = '';
4178 if (!isset($wrap[$key])) {
4179 $wrap[$key] = '';
4181 $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.'">'. $item .'</td>';
4184 $output .= '</tr>'."\n";
4187 $output .= '</table>'."\n";
4189 if ($return) {
4190 return $output;
4193 echo $output;
4194 return true;
4198 * Creates a nicely formatted table and returns it.
4200 * @param array $table is an object with several properties.
4201 * <ul<li>$table->head - An array of heading names.
4202 * <li>$table->align - An array of column alignments
4203 * <li>$table->size - An array of column sizes
4204 * <li>$table->wrap - An array of "nowrap"s or nothing
4205 * <li>$table->data[] - An array of arrays containing the data.
4206 * <li>$table->class - A css class name
4207 * <li>$table->fontsize - Is the size of all the text
4208 * <li>$table->tablealign - Align the whole table
4209 * <li>$table->width - A percentage of the page
4210 * <li>$table->cellpadding - Padding on each cell
4211 * <li>$table->cellspacing - Spacing between cells
4212 * </ul>
4213 * @return string
4214 * @todo Finish documenting this function
4216 function make_table($table) {
4218 if (isset($table->align)) {
4219 foreach ($table->align as $key => $aa) {
4220 if ($aa) {
4221 $align[$key] = ' align="'. $aa .'"';
4222 } else {
4223 $align[$key] = '';
4227 if (isset($table->size)) {
4228 foreach ($table->size as $key => $ss) {
4229 if ($ss) {
4230 $size[$key] = ' width="'. $ss .'"';
4231 } else {
4232 $size[$key] = '';
4236 if (isset($table->wrap)) {
4237 foreach ($table->wrap as $key => $ww) {
4238 if ($ww) {
4239 $wrap[$key] = ' style="white-space:nowrap;" ';
4240 } else {
4241 $wrap[$key] = '';
4246 if (empty($table->width)) {
4247 $table->width = '80%';
4250 if (empty($table->tablealign)) {
4251 $table->tablealign = 'center';
4254 if (empty($table->cellpadding)) {
4255 $table->cellpadding = '5';
4258 if (empty($table->cellspacing)) {
4259 $table->cellspacing = '1';
4262 if (empty($table->class)) {
4263 $table->class = 'generaltable';
4266 if (empty($table->fontsize)) {
4267 $fontsize = '';
4268 } else {
4269 $fontsize = '<font size="'. $table->fontsize .'">';
4272 $output = '<table width="'. $table->width .'" align="'. $table->tablealign .'" ';
4273 $output .= ' cellpadding="'. $table->cellpadding .'" cellspacing="'. $table->cellspacing .'" class="'. $table->class .'">'."\n";
4275 if (!empty($table->head)) {
4276 $output .= '<tr valign="top">';
4277 foreach ($table->head as $key => $heading) {
4278 if (!isset($size[$key])) {
4279 $size[$key] = '';
4281 if (!isset($align[$key])) {
4282 $align[$key] = '';
4284 $output .= '<th valign="top" '. $align[$key].$size[$key] .' style="white-space:nowrap;" class="'. $table->class .'header" scope="col">'.$fontsize.$heading.'</th>';
4286 $output .= '</tr>'."\n";
4289 foreach ($table->data as $row) {
4290 $output .= '<tr valign="top">';
4291 foreach ($row as $key => $item) {
4292 if (!isset($size[$key])) {
4293 $size[$key] = '';
4295 if (!isset($align[$key])) {
4296 $align[$key] = '';
4298 if (!isset($wrap[$key])) {
4299 $wrap[$key] = '';
4301 $output .= '<td '. $align[$key].$size[$key].$wrap[$key] .' class="'. $table->class .'cell">'. $fontsize . $item .'</td>';
4303 $output .= '</tr>'."\n";
4305 $output .= '</table>'."\n";
4307 return $output;
4310 function print_recent_activity_note($time, $user, $text, $link, $return=false) {
4311 static $strftimerecent;
4312 $output = '';
4314 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
4315 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
4317 if (empty($strftimerecent)) {
4318 $strftimerecent = get_string('strftimerecent');
4321 $date = userdate($time, $strftimerecent);
4322 $name = fullname($user, $viewfullnames);
4324 $output .= '<div class="head">';
4325 $output .= '<div class="date">'.$date.'</div> '.
4326 '<div class="name">'.fullname($user, $viewfullnames).'</div>';
4327 $output .= '</div>';
4328 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
4330 if ($return) {
4331 return $output;
4332 } else {
4333 echo $output;
4339 * Prints a basic textarea field.
4341 * @uses $CFG
4342 * @param boolean $usehtmleditor ?
4343 * @param int $rows ?
4344 * @param int $cols ?
4345 * @param null $width <b>Legacy field no longer used!</b> Set to zero to get control over mincols
4346 * @param null $height <b>Legacy field no longer used!</b> Set to zero to get control over minrows
4347 * @param string $name ?
4348 * @param string $value ?
4349 * @param int $courseid ?
4350 * @todo Finish documenting this function
4352 function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $courseid=0, $return=false, $id='') {
4353 /// $width and height are legacy fields and no longer used as pixels like they used to be.
4354 /// However, you can set them to zero to override the mincols and minrows values below.
4356 global $CFG, $COURSE, $HTTPSPAGEREQUIRED;
4357 static $scriptcount = 0; // For loading the htmlarea script only once.
4359 $mincols = 65;
4360 $minrows = 10;
4361 $str = '';
4363 if ($id === '') {
4364 $id = 'edit-'.$name;
4367 if ( empty($CFG->editorsrc) ) { // for backward compatibility.
4368 if (empty($courseid)) {
4369 $courseid = $COURSE->id;
4372 if ($usehtmleditor) {
4373 if (!empty($courseid) and has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE, $courseid))) {
4374 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '&ampt;httpsrequired=1';
4375 // needed for course file area browsing in image insert plugin
4376 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4377 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php?id='.$courseid.$httpsrequired.'"></script>'."\n" : '';
4378 } else {
4379 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '?httpsrequired=1';
4380 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4381 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php'.$httpsrequired.'"></script>'."\n" : '';
4384 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4385 $CFG->httpswwwroot .'/lib/editor/htmlarea/lang/en.php"></script>'."\n" : '';
4386 $scriptcount++;
4388 if ($height) { // Usually with legacy calls
4389 if ($rows < $minrows) {
4390 $rows = $minrows;
4393 if ($width) { // Usually with legacy calls
4394 if ($cols < $mincols) {
4395 $cols = $mincols;
4400 $str .= '<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">';
4401 if ($usehtmleditor) {
4402 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
4403 } else {
4404 $str .= s($value);
4406 $str .= '</textarea>'."\n";
4408 if ($usehtmleditor) {
4409 // Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
4410 $str .= '<script type="text/javascript">
4411 //<![CDATA[
4412 document.write(\''.addslashes_js(editorshortcutshelpbutton()).'\');
4413 //]]>
4414 </script>';
4417 if ($return) {
4418 return $str;
4420 echo $str;
4424 * Sets up the HTML editor on textareas in the current page.
4425 * If a field name is provided, then it will only be
4426 * applied to that field - otherwise it will be used
4427 * on every textarea in the page.
4429 * In most cases no arguments need to be supplied
4431 * @param string $name Form element to replace with HTMl editor by name
4433 function use_html_editor($name='', $editorhidebuttons='', $id='') {
4434 global $THEME;
4436 $editor = 'editor_'.md5($name); //name might contain illegal characters
4437 if ($id === '') {
4438 $id = 'edit-'.$name;
4440 echo "\n".'<script type="text/javascript" defer="defer">'."\n";
4441 echo '//<![CDATA['."\n\n"; // Extra \n is to fix odd wiki problem, MDL-8185
4442 echo "$editor = new HTMLArea('$id');\n";
4443 echo "var config = $editor.config;\n";
4445 echo print_editor_config($editorhidebuttons);
4447 if (empty($THEME->htmleditorpostprocess)) {
4448 if (empty($name)) {
4449 echo "\nHTMLArea.replaceAll($editor.config);\n";
4450 } else {
4451 echo "\n$editor.generate();\n";
4453 } else {
4454 if (empty($name)) {
4455 echo "\nvar HTML_name = '';";
4456 } else {
4457 echo "\nvar HTML_name = \"$name;\"";
4459 echo "\nvar HTML_editor = $editor;";
4461 echo '//]]>'."\n";
4462 echo '</script>'."\n";
4465 function print_editor_config($editorhidebuttons='', $return=false) {
4466 global $CFG;
4468 $str = "config.pageStyle = \"body {";
4470 if (!(empty($CFG->editorbackgroundcolor))) {
4471 $str .= " background-color: $CFG->editorbackgroundcolor;";
4474 if (!(empty($CFG->editorfontfamily))) {
4475 $str .= " font-family: $CFG->editorfontfamily;";
4478 if (!(empty($CFG->editorfontsize))) {
4479 $str .= " font-size: $CFG->editorfontsize;";
4482 $str .= " }\";\n";
4483 $str .= "config.killWordOnPaste = ";
4484 $str .= (empty($CFG->editorkillword)) ? "false":"true";
4485 $str .= ';'."\n";
4486 $str .= 'config.fontname = {'."\n";
4488 $fontlist = isset($CFG->editorfontlist) ? explode(';', $CFG->editorfontlist) : array();
4489 $i = 1; // Counter is used to get rid of the last comma.
4491 foreach ($fontlist as $fontline) {
4492 if (!empty($fontline)) {
4493 if ($i > 1) {
4494 $str .= ','."\n";
4496 list($fontkey, $fontvalue) = split(':', $fontline);
4497 $str .= '"'. $fontkey ."\":\t'". $fontvalue ."'";
4499 $i++;
4502 $str .= '};';
4504 if (!empty($editorhidebuttons)) {
4505 $str .= "\nconfig.hideSomeButtons(\" ". $editorhidebuttons ." \");\n";
4506 } else if (!empty($CFG->editorhidebuttons)) {
4507 $str .= "\nconfig.hideSomeButtons(\" ". $CFG->editorhidebuttons ." \");\n";
4510 if (!empty($CFG->editorspelling) && !empty($CFG->aspellpath)) {
4511 $str .= print_speller_code($CFG->htmleditor, true);
4514 if ($return) {
4515 return $str;
4517 echo $str;
4521 * Returns a turn edit on/off button for course in a self contained form.
4522 * Used to be an icon, but it's now a simple form button
4524 * Note that the caller is responsible for capchecks.
4526 * @uses $CFG
4527 * @uses $USER
4528 * @param int $courseid The course to update by id as found in 'course' table
4529 * @return string
4531 function update_course_icon($courseid) {
4532 global $CFG, $USER;
4534 if (!empty($USER->editing)) {
4535 $string = get_string('turneditingoff');
4536 $edit = '0';
4537 } else {
4538 $string = get_string('turneditingon');
4539 $edit = '1';
4542 return '<form '.$CFG->frametarget.' method="get" action="'.$CFG->wwwroot.'/course/view.php">'.
4543 '<div>'.
4544 '<input type="hidden" name="id" value="'.$courseid.'" />'.
4545 '<input type="hidden" name="edit" value="'.$edit.'" />'.
4546 '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
4547 '<input type="submit" value="'.$string.'" />'.
4548 '</div></form>';
4552 * Returns a little popup menu for switching roles
4554 * @uses $CFG
4555 * @uses $USER
4556 * @param int $courseid The course to update by id as found in 'course' table
4557 * @return string
4559 function switchroles_form($courseid) {
4561 global $CFG, $USER;
4564 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
4565 return '';
4568 if (!empty($user->access['rsw'][$context->path])){ // Just a button to return to normal
4569 $options = array();
4570 $options['id'] = $courseid;
4571 $options['sesskey'] = sesskey();
4572 $options['switchrole'] = 0;
4574 return print_single_button($CFG->wwwroot.'/course/view.php', $options,
4575 get_string('switchrolereturn'), 'post', '_self', true);
4578 if (has_capability('moodle/role:switchroles', $context)) {
4579 if (!$roles = get_assignable_roles($context)) {
4580 return ''; // Nothing to show!
4582 // unset default user role - it would not work
4583 unset($roles[$CFG->guestroleid]);
4584 return popup_form($CFG->wwwroot.'/course/view.php?id='.$courseid.'&amp;sesskey='.sesskey().'&amp;switchrole=',
4585 $roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
4588 return '';
4593 * Returns a turn edit on/off button for course in a self contained form.
4594 * Used to be an icon, but it's now a simple form button
4596 * @uses $CFG
4597 * @uses $USER
4598 * @param int $courseid The course to update by id as found in 'course' table
4599 * @return string
4601 function update_mymoodle_icon() {
4603 global $CFG, $USER;
4605 if (!empty($USER->editing)) {
4606 $string = get_string('updatemymoodleoff');
4607 $edit = '0';
4608 } else {
4609 $string = get_string('updatemymoodleon');
4610 $edit = '1';
4613 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
4614 "<div>".
4615 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
4616 "<input type=\"submit\" value=\"$string\" /></div></form>";
4620 * Returns a turn edit on/off button for tag in a self contained form.
4622 * @uses $CFG
4623 * @uses $USER
4624 * @return string
4626 function update_tag_button($tagid) {
4628 global $CFG, $USER;
4630 if (!empty($USER->editing)) {
4631 $string = get_string('turneditingoff');
4632 $edit = '0';
4633 } else {
4634 $string = get_string('turneditingon');
4635 $edit = '1';
4638 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/tag/index.php\">".
4639 "<div>".
4640 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
4641 "<input type=\"hidden\" name=\"id\" value=\"$tagid\" />".
4642 "<input type=\"submit\" value=\"$string\" /></div></form>";
4646 * Prints the editing button on a module "view" page
4648 * @uses $CFG
4649 * @param type description
4650 * @todo Finish documenting this function
4652 function update_module_button($moduleid, $courseid, $string) {
4653 global $CFG, $USER;
4655 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $moduleid))) {
4656 $string = get_string('updatethis', '', $string);
4658 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
4659 "<div>".
4660 "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
4661 "<input type=\"hidden\" name=\"return\" value=\"true\" />".
4662 "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
4663 "<input type=\"submit\" value=\"$string\" /></div></form>";
4664 } else {
4665 return '';
4670 * Prints the editing button on a category page
4672 * @uses $CFG
4673 * @uses $USER
4674 * @param int $categoryid ?
4675 * @return string
4676 * @todo Finish documenting this function
4678 function update_category_button($categoryid) {
4679 global $CFG, $USER;
4681 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_COURSECAT, $categoryid))) {
4682 if (!empty($USER->categoryediting)) {
4683 $string = get_string('turneditingoff');
4684 $edit = 'off';
4685 } else {
4686 $string = get_string('turneditingon');
4687 $edit = 'on';
4690 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/category.php\">".
4691 '<div>'.
4692 "<input type=\"hidden\" name=\"id\" value=\"$categoryid\" />".
4693 "<input type=\"hidden\" name=\"categoryedit\" value=\"$edit\" />".
4694 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
4695 "<input type=\"submit\" value=\"$string\" /></div></form>";
4700 * Prints the editing button on categories listing
4702 * @uses $CFG
4703 * @uses $USER
4704 * @return string
4706 function update_categories_button() {
4707 global $CFG, $USER;
4709 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
4710 if (!empty($USER->categoryediting)) {
4711 $string = get_string('turneditingoff');
4712 $categoryedit = 'off';
4713 } else {
4714 $string = get_string('turneditingon');
4715 $categoryedit = 'on';
4718 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/index.php\">".
4719 '<div>'.
4720 '<input type="hidden" name="categoryedit" value="'. $categoryedit .'" />'.
4721 '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />'.
4722 '<input type="submit" value="'. $string .'" /></div></form>';
4727 * Prints the editing button on search results listing
4728 * For bulk move courses to another category
4731 function update_categories_search_button($search,$page,$perpage) {
4732 global $CFG, $USER;
4734 // not sure if this capability is the best here
4735 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
4736 if (!empty($USER->categoryediting)) {
4737 $string = get_string("turneditingoff");
4738 $edit = "off";
4739 $perpage = 30;
4740 } else {
4741 $string = get_string("turneditingon");
4742 $edit = "on";
4745 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
4746 '<div>'.
4747 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
4748 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
4749 "<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
4750 "<input type=\"hidden\" name=\"page\" value=\"$page\" />".
4751 "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
4752 "<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
4757 * Given a course and a (current) coursemodule
4758 * This function returns a small popup menu with all the
4759 * course activity modules in it, as a navigation menu
4760 * The data is taken from the serialised array stored in
4761 * the course record
4763 * @param course $course A {@link $COURSE} object.
4764 * @param course $cm A {@link $COURSE} object.
4765 * @param string $targetwindow ?
4766 * @return string
4767 * @todo Finish documenting this function
4769 function navmenu($course, $cm=NULL, $targetwindow='self') {
4771 global $CFG, $THEME, $USER;
4773 if (empty($THEME->navmenuwidth)) {
4774 $width = 50;
4775 } else {
4776 $width = $THEME->navmenuwidth;
4779 if ($cm) {
4780 $cm = $cm->id;
4783 if ($course->format == 'weeks') {
4784 $strsection = get_string('week');
4785 } else {
4786 $strsection = get_string('topic');
4788 $strjumpto = get_string('jumpto');
4790 /// Casting $course->modinfo to string prevents one notice when the field is null
4791 if (!$modinfo = unserialize((string)$course->modinfo)) {
4792 return '';
4794 $context = get_context_instance(CONTEXT_COURSE, $course->id);
4796 $section = -1;
4797 $selected = '';
4798 $url = '';
4799 $previousmod = NULL;
4800 $backmod = NULL;
4801 $nextmod = NULL;
4802 $selectmod = NULL;
4803 $logslink = NULL;
4804 $flag = false;
4805 $menu = array();
4806 $menustyle = array();
4808 $sections = get_records('course_sections','course',$course->id,'section','section,visible,summary');
4810 if (!empty($THEME->makenavmenulist)) { /// A hack to produce an XHTML navmenu list for use in themes
4811 $THEME->navmenulist = navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
4814 foreach ($modinfo as $mod) {
4815 if ($mod->mod == 'label') {
4816 continue;
4819 if ($mod->section > $course->numsections) { /// Don't show excess hidden sections
4820 break;
4822 $mod->id = $mod->cm;
4823 $mod->course = $course->id;
4824 if (!groups_course_module_visible($mod)) {
4825 continue;
4828 if ($mod->section > 0 and $section <> $mod->section) {
4829 $thissection = $sections[$mod->section];
4831 if ($thissection->visible or !$course->hiddensections or
4832 has_capability('moodle/course:viewhiddensections', $context)) {
4833 $thissection->summary = strip_tags(format_string($thissection->summary,true));
4834 if ($course->format == 'weeks' or empty($thissection->summary)) {
4835 $menu[] = '--'.$strsection ." ". $mod->section;
4836 } else {
4837 if (strlen($thissection->summary) < ($width-3)) {
4838 $menu[] = '--'.$thissection->summary;
4839 } else {
4840 $menu[] = '--'.substr($thissection->summary, 0, $width).'...';
4846 $section = $mod->section;
4848 //Only add visible or teacher mods to jumpmenu
4849 if ($mod->visible or has_capability('moodle/course:viewhiddenactivities',
4850 get_context_instance(CONTEXT_MODULE, $mod->cm))) {
4851 $url = $mod->mod .'/view.php?id='. $mod->cm;
4852 if ($flag) { // the current mod is the "next" mod
4853 $nextmod = $mod;
4854 $flag = false;
4856 if ($cm == $mod->cm) {
4857 $selected = $url;
4858 $selectmod = $mod;
4859 $backmod = $previousmod;
4860 $flag = true; // set flag so we know to use next mod for "next"
4861 $mod->name = $strjumpto;
4862 $strjumpto = '';
4863 } else {
4864 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
4865 if (strlen($mod->name) > ($width+5)) {
4866 $mod->name = substr($mod->name, 0, $width).'...';
4868 if (!$mod->visible) {
4869 $mod->name = '('.$mod->name.')';
4872 $menu[$url] = $mod->name;
4873 if (empty($THEME->navmenuiconshide)) {
4874 $menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath.'/'.$mod->mod.'/icon.gif);"'; // Unfortunately necessary to do this here
4876 $previousmod = $mod;
4879 //Accessibility: added Alt text, replaced &gt; &lt; with 'silent' character and 'accesshide' text.
4881 if ($selectmod and has_capability('moodle/site:viewreports', $context)) {
4882 $logstext = get_string('alllogs');
4883 $logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
4884 $CFG->frametarget.'onclick="this.target=\''.$CFG->framename.'\';"'.' href="'.
4885 $CFG->wwwroot.'/course/report/log/index.php?chooselog=1&amp;user=0&amp;date=0&amp;id='.
4886 $course->id.'&amp;modid='.$selectmod->cm.'">'.
4887 '<img class="icon log" src="'.$CFG->pixpath.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
4890 if ($backmod) {
4891 $backtext= get_string('activityprev', 'access');
4892 $backmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$backmod->mod.'/view.php" '.
4893 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
4894 '<input type="hidden" name="id" value="'.$backmod->cm.'" />'.
4895 '<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
4896 '</button></fieldset></form></li>';
4898 if ($nextmod) {
4899 $nexttext= get_string('activitynext', 'access');
4900 $nextmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$nextmod->mod.'/view.php" '.
4901 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
4902 '<input type="hidden" name="id" value="'.$nextmod->cm.'" />'.
4903 '<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
4904 '</button></fieldset></form></li>';
4907 return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
4908 '<li>'.popup_form($CFG->wwwroot .'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
4909 '', '', true, $targetwindow, '', $menustyle).'</li>'.
4910 $nextmod . '</ul>'."\n".'</div>';
4914 * Given a course
4915 * This function returns a small popup menu with all the
4916 * course activity modules in it, as a navigation menu
4917 * outputs a simple list structure in XHTML
4918 * The data is taken from the serialised array stored in
4919 * the course record
4921 * @param course $course A {@link $COURSE} object.
4922 * @return string
4923 * @todo Finish documenting this function
4925 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
4927 global $CFG;
4929 $section = -1;
4930 $selected = '';
4931 $url = '';
4932 $previousmod = NULL;
4933 $backmod = NULL;
4934 $nextmod = NULL;
4935 $selectmod = NULL;
4936 $logslink = NULL;
4937 $flag = false;
4938 $menu = array();
4940 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
4942 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
4943 foreach ($modinfo as $mod) {
4944 if ($mod->mod == 'label') {
4945 continue;
4948 if ($mod->section > $course->numsections) { /// Don't show excess hidden sections
4949 break;
4952 if ($mod->section >= 0 and $section <> $mod->section) {
4953 $thissection = $sections[$mod->section];
4955 if ($thissection->visible or !$course->hiddensections or
4956 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
4957 $thissection->summary = strip_tags(format_string($thissection->summary,true));
4958 if (!empty($doneheading)) {
4959 $menu[] = '</ul></li>';
4961 if ($course->format == 'weeks' or empty($thissection->summary)) {
4962 $item = $strsection ." ". $mod->section;
4963 } else {
4964 if (strlen($thissection->summary) < ($width-3)) {
4965 $item = $thissection->summary;
4966 } else {
4967 $item = substr($thissection->summary, 0, $width).'...';
4970 $menu[] = '<li class="section"><span>'.$item.'</span>';
4971 $menu[] = '<ul>';
4972 $doneheading = true;
4976 $section = $mod->section;
4978 //Only add visible or teacher mods to jumpmenu
4979 if ($mod->visible or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_MODULE, $mod->cm))) {
4980 $url = $mod->mod .'/view.php?id='. $mod->cm;
4981 if ($flag) { // the current mod is the "next" mod
4982 $nextmod = $mod;
4983 $flag = false;
4985 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
4986 if (strlen($mod->name) > ($width+5)) {
4987 $mod->name = substr($mod->name, 0, $width).'...';
4989 if (!$mod->visible) {
4990 $mod->name = '('.$mod->name.')';
4992 $class = 'activity '.$mod->mod;
4993 $class .= ($cmid == $mod->cm) ? ' selected' : '';
4994 $menu[] = '<li class="'.$class.'">'.
4995 '<img src="'.$CFG->modpixpath.'/'.$mod->mod.'/icon.gif" alt="" />'.
4996 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
4997 $previousmod = $mod;
5000 if ($doneheading) {
5001 $menu[] = '</ul></li>';
5003 $menu[] = '</ul></li></ul>';
5005 return implode("\n", $menu);
5009 * Prints form items with the names $day, $month and $year
5011 * @param string $day fieldname
5012 * @param string $month fieldname
5013 * @param string $year fieldname
5014 * @param int $currenttime A default timestamp in GMT
5015 * @param boolean $return
5017 function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
5019 if (!$currenttime) {
5020 $currenttime = time();
5022 $currentdate = usergetdate($currenttime);
5024 for ($i=1; $i<=31; $i++) {
5025 $days[$i] = $i;
5027 for ($i=1; $i<=12; $i++) {
5028 $months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
5030 for ($i=1970; $i<=2020; $i++) {
5031 $years[$i] = $i;
5033 return choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', $return)
5034 .choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', $return)
5035 .choose_from_menu($years, $year, $currentdate['year'], '', '', '0', $return);
5040 *Prints form items with the names $hour and $minute
5042 * @param string $hour fieldname
5043 * @param string ? $minute fieldname
5044 * @param $currenttime A default timestamp in GMT
5045 * @param int $step minute spacing
5046 * @param boolean $return
5048 function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
5050 if (!$currenttime) {
5051 $currenttime = time();
5053 $currentdate = usergetdate($currenttime);
5054 if ($step != 1) {
5055 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
5057 for ($i=0; $i<=23; $i++) {
5058 $hours[$i] = sprintf("%02d",$i);
5060 for ($i=0; $i<=59; $i+=$step) {
5061 $minutes[$i] = sprintf("%02d",$i);
5064 return choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',$return)
5065 .choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',$return);
5069 * Prints time limit value selector
5071 * @uses $CFG
5072 * @param int $timelimit default
5073 * @param string $unit
5074 * @param string $name
5075 * @param boolean $return
5077 function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
5079 global $CFG;
5081 if ($unit) {
5082 $unit = ' '.$unit;
5085 // Max timelimit is sessiontimeout - 10 minutes.
5086 $maxvalue = ($CFG->sessiontimeout / 60) - 10;
5088 for ($i=1; $i<=$maxvalue; $i++) {
5089 $minutes[$i] = $i.$unit;
5091 return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
5095 * Prints a grade menu (as part of an existing form) with help
5096 * Showing all possible numerical grades and scales
5098 * @uses $CFG
5099 * @param int $courseid ?
5100 * @param string $name ?
5101 * @param string $current ?
5102 * @param boolean $includenograde ?
5103 * @todo Finish documenting this function
5105 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
5107 global $CFG;
5109 $output = '';
5110 $strscale = get_string('scale');
5111 $strscales = get_string('scales');
5113 $scales = get_scales_menu($courseid);
5114 foreach ($scales as $i => $scalename) {
5115 $grades[-$i] = $strscale .': '. $scalename;
5117 if ($includenograde) {
5118 $grades[0] = get_string('nograde');
5120 for ($i=100; $i>=1; $i--) {
5121 $grades[$i] = $i;
5123 $output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
5125 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5126 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5127 $linkobject, 400, 500, $strscales, 'none', true);
5129 if ($return) {
5130 return $output;
5131 } else {
5132 echo $output;
5137 * Prints a scale menu (as part of an existing form) including help button
5138 * Just like {@link print_grade_menu()} but without the numeric grades
5140 * @param int $courseid ?
5141 * @param string $name ?
5142 * @param string $current ?
5143 * @todo Finish documenting this function
5145 function print_scale_menu($courseid, $name, $current, $return=false) {
5147 global $CFG;
5149 $output = '';
5150 $strscales = get_string('scales');
5151 $output .= choose_from_menu(get_scales_menu($courseid), $name, $current, '', '', 0, true);
5153 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5154 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5155 $linkobject, 400, 500, $strscales, 'none', true);
5156 if ($return) {
5157 return $output;
5158 } else {
5159 echo $output;
5164 * Prints a help button about a scale
5166 * @uses $CFG
5167 * @param id $courseid ?
5168 * @param object $scale ?
5169 * @todo Finish documenting this function
5171 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
5173 global $CFG;
5175 $output = '';
5176 $strscales = get_string('scales');
5178 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5179 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true&amp;scaleid='. $scale->id, 'ratingscale',
5180 $linkobject, 400, 500, $scale->name, 'none', true);
5181 if ($return) {
5182 return $output;
5183 } else {
5184 echo $output;
5189 * Print an error page displaying an error message.
5190 * Old method, don't call directly in new code - use print_error instead.
5193 * @uses $SESSION
5194 * @uses $CFG
5195 * @param string $message The message to display to the user about the error.
5196 * @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.
5198 function error ($message, $link='') {
5200 global $CFG, $SESSION;
5201 $message = clean_text($message); // In case nasties are in here
5203 if (defined('FULLME') && FULLME == 'cron') {
5204 // Errors in cron should be mtrace'd.
5205 mtrace($message);
5206 die;
5209 if (! defined('HEADER_PRINTED')) {
5210 //header not yet printed
5211 @header('HTTP/1.0 404 Not Found');
5212 print_header(get_string('error'));
5215 echo '<br />';
5216 print_simple_box($message, '', '', '', '', 'errorbox');
5218 debugging('Stack trace:', DEBUG_DEVELOPER);
5220 // in case we are logging upgrade in admin/index.php stop it
5221 if (function_exists('upgrade_log_finish')) {
5222 upgrade_log_finish();
5225 if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
5226 if ( !empty($SESSION->fromurl) ) {
5227 $link = $SESSION->fromurl;
5228 unset($SESSION->fromurl);
5229 } else {
5230 $link = $CFG->wwwroot .'/';
5234 if (!empty($link)) {
5235 print_continue($link);
5238 print_footer();
5240 for ($i=0;$i<512;$i++) { // Padding to help IE work with 404
5241 echo ' ';
5244 die;
5248 * Print an error page displaying an error message. New method - use this for new code.
5250 * @uses $SESSION
5251 * @uses $CFG
5252 * @param string $errorcode The name of the string from error.php to print
5253 * @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.
5254 * @param object $a Extra words and phrases that might be required in the error string
5256 function print_error ($errorcode, $module='', $link='', $a=NULL) {
5258 global $CFG;
5260 if (empty($module) || $module == 'moodle' || $module == 'core') {
5261 $module = 'error';
5262 $modulelink = 'moodle';
5263 } else {
5264 $modulelink = $module;
5267 if (!empty($CFG->errordocroot)) {
5268 $errordocroot = $CFG->errordocroot;
5269 } else if (!empty($CFG->docroot)) {
5270 $errordocroot = $CFG->docroot;
5271 } else {
5272 $errordocroot = 'http://docs.moodle.org';
5275 $message = '<p class="errormessage">'.get_string($errorcode, $module, $a).'</p>'.
5276 '<p class="errorcode">'.
5277 '<a href="'.$errordocroot.'/en/error/'.$modulelink.'/'.$errorcode.'">'.
5278 get_string('moreinformation').'</a></p>';
5279 error($message, $link);
5282 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
5283 * Should be used only with htmleditor or textarea.
5284 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
5285 * helpbutton.
5286 * @return string
5288 function editorhelpbutton(){
5289 global $CFG, $SESSION;
5290 $items = func_get_args();
5291 $i = 1;
5292 $urlparams = array();
5293 $titles = array();
5294 foreach ($items as $item){
5295 if (is_array($item)){
5296 $urlparams[] = "keyword$i=".urlencode($item[0]);
5297 $urlparams[] = "title$i=".urlencode($item[1]);
5298 if (isset($item[2])){
5299 $urlparams[] = "module$i=".urlencode($item[2]);
5301 $titles[] = trim($item[1], ". \t");
5302 }elseif (is_string($item)){
5303 $urlparams[] = "button$i=".urlencode($item);
5304 switch ($item){
5305 case 'reading' :
5306 $titles[] = get_string("helpreading");
5307 break;
5308 case 'writing' :
5309 $titles[] = get_string("helpwriting");
5310 break;
5311 case 'questions' :
5312 $titles[] = get_string("helpquestions");
5313 break;
5314 case 'emoticons' :
5315 $titles[] = get_string("helpemoticons");
5316 break;
5317 case 'richtext' :
5318 $titles[] = get_string('helprichtext');
5319 break;
5320 case 'text' :
5321 $titles[] = get_string('helptext');
5322 break;
5323 default :
5324 error('Unknown help topic '.$item);
5327 $i++;
5329 if (count($titles)>1){
5330 //join last two items with an 'and'
5331 $a = new object();
5332 $a->one = $titles[count($titles) - 2];
5333 $a->two = $titles[count($titles) - 1];
5334 $titles[count($titles) - 2] = get_string('and', '', $a);
5335 unset($titles[count($titles) - 1]);
5337 $alttag = join (', ', $titles);
5339 $paramstring = join('&', $urlparams);
5340 $linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath .'/help.gif" />';
5341 return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), $alttag, $linkobject, 400, 500, $alttag, 'none', true);
5345 * Print a help button.
5347 * @uses $CFG
5348 * @param string $page The keyword that defines a help page
5349 * @param string $title The title of links, rollover tips, alt tags etc
5350 * 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
5351 * @param string $module Which module is the page defined in
5352 * @param mixed $image Use a help image for the link? (true/false/"both")
5353 * @param boolean $linktext If true, display the title next to the help icon.
5354 * @param string $text If defined then this text is used in the page, and
5355 * the $page variable is ignored.
5356 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
5357 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
5358 * @return string
5359 * @todo Finish documenting this function
5361 function helpbutton ($page, $title='', $module='moodle', $image=true, $linktext=false, $text='', $return=false,
5362 $imagetext='') {
5363 global $CFG, $COURSE;
5365 // fix for MDL-7734
5366 if (!empty($COURSE->lang)) {
5367 $forcelang = $COURSE->lang;
5368 } else {
5369 $forcelang = '';
5372 if ($module == '') {
5373 $module = 'moodle';
5376 $tooltip = get_string('helpprefix2', '', trim($title, ". \t"));
5378 $linkobject = '';
5380 if ($image) {
5381 if ($linktext) {
5382 // MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
5383 $linkobject .= $title.'&nbsp;';
5384 $tooltip = get_string('helpwiththis');
5386 if ($imagetext) {
5387 $linkobject .= $imagetext;
5388 } else {
5389 $linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
5390 $CFG->pixpath .'/help.gif" />';
5392 } else {
5393 $linkobject .= $tooltip;
5396 $tooltip .= ' ('.get_string('newwindow').')'; // Warn users about new window for Accessibility
5398 // fix for MDL-7734
5399 if ($text) {
5400 $url = '/help.php?module='. $module .'&amp;text='. s(urlencode($text).'&amp;forcelang='.$forcelang);
5401 } else {
5402 $url = '/help.php?module='. $module .'&amp;file='. $page .'.html&amp;forcelang='.$forcelang;
5405 $link = '<span class="helplink">'.
5406 link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
5407 '</span>';
5409 if ($return) {
5410 return $link;
5411 } else {
5412 echo $link;
5417 * Print a help button.
5419 * Prints a special help button that is a link to the "live" emoticon popup
5420 * @uses $CFG
5421 * @uses $SESSION
5422 * @param string $form ?
5423 * @param string $field ?
5424 * @todo Finish documenting this function
5426 function emoticonhelpbutton($form, $field, $return = false) {
5428 global $CFG, $SESSION;
5430 $SESSION->inserttextform = $form;
5431 $SESSION->inserttextfield = $field;
5432 $imagetext = '<img src="' . $CFG->pixpath . '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
5433 $help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
5434 if (!$return){
5435 echo $help;
5436 } else {
5437 return $help;
5442 * Print a help button.
5444 * Prints a special help button for html editors (htmlarea in this case)
5445 * @uses $CFG
5447 function editorshortcutshelpbutton() {
5449 global $CFG;
5450 $imagetext = '<img src="' . $CFG->httpswwwroot . '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
5451 get_string('editorshortcutkeys').'" class="iconkbhelp" />';
5453 return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
5457 * Print a message and exit.
5459 * @uses $CFG
5460 * @param string $message ?
5461 * @param string $link ?
5462 * @todo Finish documenting this function
5464 function notice ($message, $link='', $course=NULL) {
5465 global $CFG, $SITE;
5467 $message = clean_text($message);
5469 print_box($message, 'generalbox', 'notice');
5470 print_continue($link);
5472 if (empty($course)) {
5473 print_footer($SITE);
5474 } else {
5475 print_footer($course);
5477 exit;
5481 * Print a message along with "Yes" and "No" links for the user to continue.
5483 * @param string $message The text to display
5484 * @param string $linkyes The link to take the user to if they choose "Yes"
5485 * @param string $linkno The link to take the user to if they choose "No"
5486 * TODO Document remaining arguments
5488 function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
5490 global $CFG;
5492 $message = clean_text($message);
5493 $linkyes = clean_text($linkyes);
5494 $linkno = clean_text($linkno);
5496 print_box_start('generalbox', 'notice');
5497 echo '<p>'. $message .'</p>';
5498 echo '<div class="buttons">';
5499 print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename);
5500 print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename);
5501 echo '</div>';
5502 print_box_end();
5506 * Provide an definition of error_get_last for PHP before 5.2.0. This simply
5507 * returns NULL, since there is not way to get the right answer.
5509 if (!function_exists('error_get_last')) {
5510 // the eval is needed to prevent PHP 5.2+ from getting a parse error!
5511 eval('
5512 function error_get_last() {
5513 return NULL;
5519 * Redirects the user to another page, after printing a notice
5521 * @param string $url The url to take the user to
5522 * @param string $message The text message to display to the user about the redirect, if any
5523 * @param string $delay How long before refreshing to the new page at $url?
5524 * @todo '&' needs to be encoded into '&amp;' for XHTML compliance,
5525 * however, this is not true for javascript. Therefore we
5526 * first decode all entities in $url (since we cannot rely on)
5527 * the correct input) and then encode for where it's needed
5528 * echo "<script type='text/javascript'>alert('Redirect $url');</script>";
5530 function redirect($url, $message='', $delay=-1) {
5532 global $CFG;
5534 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
5535 $url = sid_process_url($url);
5538 $message = clean_text($message);
5540 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
5541 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
5542 $url = str_replace('&amp;', '&', $encodedurl);
5544 /// At developer debug level. Don't redirect if errors have been printed on screen.
5545 /// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
5546 $lasterror = error_get_last();
5547 $error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER));
5548 $errorprinted = debugging('', DEBUG_ALL) && $CFG->debugdisplay && $error;
5549 if ($errorprinted) {
5550 $message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
5553 $performanceinfo = '';
5554 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
5555 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
5556 $perf = get_performance_info();
5557 error_log("PERF: " . $perf['txt']);
5561 /// when no message and header printed yet, try to redirect
5562 if (empty($message) and !defined('HEADER_PRINTED')) {
5564 // Technically, HTTP/1.1 requires Location: header to contain
5565 // the absolute path. (In practice browsers accept relative
5566 // paths - but still, might as well do it properly.)
5567 // This code turns relative into absolute.
5568 if (!preg_match('|^[a-z]+:|', $url)) {
5569 // Get host name http://www.wherever.com
5570 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
5571 if (preg_match('|^/|', $url)) {
5572 // URLs beginning with / are relative to web server root so we just add them in
5573 $url = $hostpart.$url;
5574 } else {
5575 // URLs not beginning with / are relative to path of current script, so add that on.
5576 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
5578 // Replace all ..s
5579 while (true) {
5580 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
5581 if ($newurl == $url) {
5582 break;
5584 $url = $newurl;
5588 $delay = 0;
5589 //try header redirection first
5590 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
5591 @header('Location: '.$url);
5592 //another way for older browsers and already sent headers (eg trailing whitespace in config.php)
5593 echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
5594 echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
5595 die;
5598 if ($delay == -1) {
5599 $delay = 3; // if no delay specified wait 3 seconds
5601 if (! defined('HEADER_PRINTED')) {
5602 // this type of redirect might not be working in some browsers - such as lynx :-(
5603 print_header('', '', '', '', $errorprinted ? '' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
5604 $delay += 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
5606 echo '<div style="text-align:center">';
5607 echo '<div>'. $message .'</div>';
5608 echo '<div>( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
5609 echo '</div>';
5611 if (!$errorprinted) {
5613 <script type="text/javascript">
5614 //<![CDATA[
5616 function redirect() {
5617 document.location.replace('<?php echo addslashes_js($url) ?>');
5619 setTimeout("redirect()", <?php echo ($delay * 1000) ?>);
5620 //]]>
5621 </script>
5622 <?php
5625 print_footer('none');
5626 die;
5630 * Print a bold message in an optional color.
5632 * @param string $message The message to print out
5633 * @param string $style Optional style to display message text in
5634 * @param string $align Alignment option
5635 * @param bool $return whether to return an output string or echo now
5637 function notify($message, $style='notifyproblem', $align='center', $return=false) {
5638 if ($style == 'green') {
5639 $style = 'notifysuccess'; // backward compatible with old color system
5642 $message = clean_text($message);
5644 $output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."\n";
5646 if ($return) {
5647 return $output;
5649 echo $output;
5654 * Given an email address, this function will return an obfuscated version of it
5656 * @param string $email The email address to obfuscate
5657 * @return string
5659 function obfuscate_email($email) {
5661 $i = 0;
5662 $length = strlen($email);
5663 $obfuscated = '';
5664 while ($i < $length) {
5665 if (rand(0,2)) {
5666 $obfuscated.='%'.dechex(ord($email{$i}));
5667 } else {
5668 $obfuscated.=$email{$i};
5670 $i++;
5672 return $obfuscated;
5676 * This function takes some text and replaces about half of the characters
5677 * with HTML entity equivalents. Return string is obviously longer.
5679 * @param string $plaintext The text to be obfuscated
5680 * @return string
5682 function obfuscate_text($plaintext) {
5684 $i=0;
5685 $length = strlen($plaintext);
5686 $obfuscated='';
5687 $prev_obfuscated = false;
5688 while ($i < $length) {
5689 $c = ord($plaintext{$i});
5690 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
5691 if ($prev_obfuscated and $numerical ) {
5692 $obfuscated.='&#'.ord($plaintext{$i}).';';
5693 } else if (rand(0,2)) {
5694 $obfuscated.='&#'.ord($plaintext{$i}).';';
5695 $prev_obfuscated = true;
5696 } else {
5697 $obfuscated.=$plaintext{$i};
5698 $prev_obfuscated = false;
5700 $i++;
5702 return $obfuscated;
5706 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
5707 * to generate a fully obfuscated email link, ready to use.
5709 * @param string $email The email address to display
5710 * @param string $label The text to dispalyed as hyperlink to $email
5711 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
5712 * @return string
5714 function obfuscate_mailto($email, $label='', $dimmed=false) {
5716 if (empty($label)) {
5717 $label = $email;
5719 if ($dimmed) {
5720 $title = get_string('emaildisable');
5721 $dimmed = ' class="dimmed"';
5722 } else {
5723 $title = '';
5724 $dimmed = '';
5726 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
5727 obfuscate_text('mailto'), obfuscate_email($email),
5728 obfuscate_text($label));
5732 * Prints a single paging bar to provide access to other pages (usually in a search)
5734 * @param int $totalcount Thetotal number of entries available to be paged through
5735 * @param int $page The page you are currently viewing
5736 * @param int $perpage The number of entries that should be shown per page
5737 * @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.
5738 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
5739 * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
5740 * @param bool $nocurr do not display the current page as a link
5741 * @param bool $return whether to return an output string or echo now
5742 * @return bool or string
5744 function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
5745 $maxdisplay = 18;
5746 $output = '';
5748 if ($totalcount > $perpage) {
5749 $output .= '<div class="paging">';
5750 $output .= get_string('page') .':';
5751 if ($page > 0) {
5752 $pagenum = $page - 1;
5753 if (!is_a($baseurl, 'moodle_url')){
5754 $output .= '&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>)&nbsp;';
5755 } else {
5756 $output .= '&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>)&nbsp;';
5759 if ($perpage > 0) {
5760 $lastpage = ceil($totalcount / $perpage);
5761 } else {
5762 $lastpage = 1;
5764 if ($page > 15) {
5765 $startpage = $page - 10;
5766 if (!is_a($baseurl, 'moodle_url')){
5767 $output .= '&nbsp;<a href="'. $baseurl . $pagevar .'=0">1</a>&nbsp;...';
5768 } else {
5769 $output .= '&nbsp;<a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a>&nbsp;...';
5771 } else {
5772 $startpage = 0;
5774 $currpage = $startpage;
5775 $displaycount = 0;
5776 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
5777 $displaypage = $currpage+1;
5778 if ($page == $currpage && empty($nocurr)) {
5779 $output .= '&nbsp;&nbsp;'. $displaypage;
5780 } else {
5781 if (!is_a($baseurl, 'moodle_url')){
5782 $output .= '&nbsp;&nbsp;<a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
5783 } else {
5784 $output .= '&nbsp;&nbsp;<a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
5788 $displaycount++;
5789 $currpage++;
5791 if ($currpage < $lastpage) {
5792 $lastpageactual = $lastpage - 1;
5793 if (!is_a($baseurl, 'moodle_url')){
5794 $output .= '&nbsp;...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a>&nbsp;';
5795 } else {
5796 $output .= '&nbsp;...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a>&nbsp;';
5799 $pagenum = $page + 1;
5800 if ($pagenum != $displaypage) {
5801 if (!is_a($baseurl, 'moodle_url')){
5802 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
5803 } else {
5804 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
5807 $output .= '</div>';
5810 if ($return) {
5811 return $output;
5814 echo $output;
5815 return true;
5819 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
5820 * will transform it to html entities
5822 * @param string $text Text to search for nolink tag in
5823 * @return string
5825 function rebuildnolinktag($text) {
5827 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
5829 return $text;
5833 * Prints a nice side block with an optional header. The content can either
5834 * be a block of HTML or a list of text with optional icons.
5836 * @param string $heading Block $title embedded in HTML tags, for example <h2>.
5837 * @param string $content ?
5838 * @param array $list ?
5839 * @param array $icons ?
5840 * @param string $footer ?
5841 * @param array $attributes ?
5842 * @param string $title Plain text title, as embedded in the $heading.
5843 * @todo Finish documenting this function. Show example of various attributes, etc.
5845 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
5847 //Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
5848 static $block_id = 0;
5849 $block_id++;
5850 if (empty($heading)) {
5851 $skip_text = get_string('skipblock', 'access').' '.$block_id;
5853 else {
5854 $skip_text = get_string('skipa', 'access', strip_tags($title));
5856 $skip_link = '<a href="#sb-'.$block_id.'" class="skip-block" title="'.$skip_text.'">'."\n".get_accesshide($skip_text)."\n".'</a>';
5857 $skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
5859 if (! empty($heading)) {
5860 $heading = $skip_link . $heading;
5862 /*else { //ELSE: I think a single link on a page, "Skip block 4" is too confusing - don't print.
5863 echo $skip_link;
5866 print_side_block_start($heading, $attributes);
5868 if ($content) {
5869 echo $content;
5870 if ($footer) {
5871 echo '<div class="footer">'. $footer .'</div>';
5873 } else {
5874 if ($list) {
5875 $row = 0;
5876 //Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
5877 echo "\n<ul class='list'>\n";
5878 foreach ($list as $key => $string) {
5879 echo '<li class="r'. $row .'">';
5880 if ($icons) {
5881 echo '<div class="icon column c0">'. $icons[$key] .'</div>';
5883 echo '<div class="column c1">'. $string .'</div>';
5884 echo "</li>\n";
5885 $row = $row ? 0:1;
5887 echo "</ul>\n";
5889 if ($footer) {
5890 echo '<div class="footer">'. $footer .'</div>';
5895 print_side_block_end($attributes);
5896 echo $skip_dest;
5900 * Starts a nice side block with an optional header.
5902 * @param string $heading ?
5903 * @param array $attributes ?
5904 * @todo Finish documenting this function
5906 function print_side_block_start($heading='', $attributes = array()) {
5908 global $CFG, $THEME;
5910 if (!empty($THEME->customcorners)) {
5911 require_once($CFG->dirroot.'/lib/custom_corners_lib.php');
5914 // If there are no special attributes, give a default CSS class
5915 if (empty($attributes) || !is_array($attributes)) {
5916 $attributes = array('class' => 'sideblock');
5918 } else if(!isset($attributes['class'])) {
5919 $attributes['class'] = 'sideblock';
5921 } else if(!strpos($attributes['class'], 'sideblock')) {
5922 $attributes['class'] .= ' sideblock';
5925 // OK, the class is surely there and in addition to anything
5926 // else, it's tagged as a sideblock
5930 // IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
5932 // If there is a cookie to hide this thing, start it hidden
5933 if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
5934 $attributes['class'] = 'hidden '.$attributes['class'];
5938 $attrtext = '';
5939 foreach ($attributes as $attr => $val) {
5940 $attrtext .= ' '.$attr.'="'.$val.'"';
5943 echo '<div '.$attrtext.'>';
5945 if (!empty($THEME->customcorners)) {
5946 echo '<div class="wrap">'."\n";
5948 if ($heading) {
5949 //Accessibility: replaced <div> with H2; no, H2 more appropriate in moodleblock.class.php: _title_html.
5950 // echo '<div class="header">'.$heading.'</div>';
5951 echo '<div class="header">';
5952 if (!empty($THEME->customcorners)) {
5953 echo '<div class="bt"><div>&nbsp;</div></div>';
5954 echo '<div class="i1"><div class="i2">';
5955 echo '<div class="i3">';
5957 echo $heading;
5958 if (!empty($THEME->customcorners)) {
5959 echo '</div></div></div>';
5961 echo '</div>';
5962 } else {
5963 if (!empty($THEME->customcorners)) {
5964 echo '<div class="bt"><div>&nbsp;</div></div>';
5968 if (!empty($THEME->customcorners)) {
5969 echo '<div class="i1"><div class="i2">';
5970 echo '<div class="i3">';
5971 $THEME->customcornersopen += 1;
5973 echo '<div class="content">';
5979 * Print table ending tags for a side block box.
5981 function print_side_block_end($attributes = array()) {
5982 global $CFG, $THEME;
5984 echo '</div>';
5986 if (!empty($THEME->customcorners)) {
5987 require_once($CFG->dirroot.'/lib/custom_corners_lib.php');
5988 print_custom_corners_end();
5991 echo '</div>';
5993 // IE workaround: if I do it THIS way, it works! WTF?
5994 if (!empty($CFG->allowuserblockhiding) && isset($attributes['id'])) {
5995 echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].'"); '.
5996 "\n//]]>\n".'</script>';
6003 * Prints out code needed for spellchecking.
6004 * Original idea by Ludo (Marc Alier).
6006 * Opening CDATA and <script> are output by weblib::use_html_editor()
6007 * @uses $CFG
6008 * @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
6009 * @param boolean $return If false, echos the code instead of returning it
6010 * @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
6012 function print_speller_code ($usehtmleditor=false, $return=false) {
6013 global $CFG;
6014 $str = '';
6016 if(!$usehtmleditor) {
6017 $str .= 'function openSpellChecker() {'."\n";
6018 $str .= "\tvar speller = new spellChecker();\n";
6019 $str .= "\tspeller.popUpUrl = \"" . $CFG->wwwroot ."/lib/speller/spellchecker.html\";\n";
6020 $str .= "\tspeller.spellCheckScript = \"". $CFG->wwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
6021 $str .= "\tspeller.spellCheckAll();\n";
6022 $str .= '}'."\n";
6023 } else {
6024 $str .= "function spellClickHandler(editor, buttonId) {\n";
6025 $str .= "\teditor._textArea.value = editor.getHTML();\n";
6026 $str .= "\tvar speller = new spellChecker( editor._textArea );\n";
6027 $str .= "\tspeller.popUpUrl = \"" . $CFG->wwwroot ."/lib/speller/spellchecker.html\";\n";
6028 $str .= "\tspeller.spellCheckScript = \"". $CFG->wwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
6029 $str .= "\tspeller._moogle_edit=1;\n";
6030 $str .= "\tspeller._editor=editor;\n";
6031 $str .= "\tspeller.openChecker();\n";
6032 $str .= '}'."\n";
6035 if ($return) {
6036 return $str;
6038 echo $str;
6042 * Print button for spellchecking when editor is disabled
6044 function print_speller_button () {
6045 echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
6049 function page_id_and_class(&$getid, &$getclass) {
6050 // Create class and id for this page
6051 global $CFG, $ME;
6053 static $class = NULL;
6054 static $id = NULL;
6056 if (empty($CFG->pagepath)) {
6057 $CFG->pagepath = $ME;
6060 if (empty($class) || empty($id)) {
6061 $path = str_replace($CFG->httpswwwroot.'/', '', $CFG->pagepath); //Because the page could be HTTPSPAGEREQUIRED
6062 $path = str_replace('.php', '', $path);
6063 if (substr($path, -1) == '/') {
6064 $path .= 'index';
6066 if (empty($path) || $path == 'index') {
6067 $id = 'site-index';
6068 $class = 'course';
6069 } else if (substr($path, 0, 5) == 'admin') {
6070 $id = str_replace('/', '-', $path);
6071 $class = 'admin';
6072 } else {
6073 $id = str_replace('/', '-', $path);
6074 $class = explode('-', $id);
6075 array_pop($class);
6076 $class = implode('-', $class);
6080 $getid = $id;
6081 $getclass = $class;
6085 * Prints a maintenance message from /maintenance.html
6087 function print_maintenance_message () {
6088 global $CFG, $SITE;
6090 print_header(strip_tags($SITE->fullname), $SITE->fullname, 'home');
6091 print_simple_box_start('center');
6092 print_heading(get_string('sitemaintenance', 'admin'));
6093 @include($CFG->dataroot.'/1/maintenance.html');
6094 print_simple_box_end();
6095 print_footer();
6099 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
6101 function adjust_allowed_tags() {
6103 global $CFG, $ALLOWED_TAGS;
6105 if (!empty($CFG->allowobjectembed)) {
6106 $ALLOWED_TAGS .= '<embed><object>';
6110 /// Some code to print tabs
6112 /// A class for tabs
6113 class tabobject {
6114 var $id;
6115 var $link;
6116 var $text;
6117 var $linkedwhenselected;
6119 /// A constructor just because I like constructors
6120 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
6121 $this->id = $id;
6122 $this->link = $link;
6123 $this->text = $text;
6124 $this->title = $title ? $title : $text;
6125 $this->linkedwhenselected = $linkedwhenselected;
6132 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
6134 * @param array $tabrows An array of rows where each row is an array of tab objects
6135 * @param string $selected The id of the selected tab (whatever row it's on)
6136 * @param array $inactive An array of ids of inactive tabs that are not selectable.
6137 * @param array $activated An array of ids of other tabs that are currently activated
6139 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
6140 global $CFG;
6142 /// $inactive must be an array
6143 if (!is_array($inactive)) {
6144 $inactive = array();
6147 /// $activated must be an array
6148 if (!is_array($activated)) {
6149 $activated = array();
6152 /// Convert the tab rows into a tree that's easier to process
6153 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
6154 return false;
6157 /// Print out the current tree of tabs (this function is recursive)
6159 $output = convert_tree_to_html($tree);
6161 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
6163 /// We're done!
6165 if ($return) {
6166 return $output;
6168 echo $output;
6172 function convert_tree_to_html($tree, $row=0) {
6174 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
6176 $first = true;
6177 $count = count($tree);
6179 foreach ($tree as $tab) {
6180 $count--; // countdown to zero
6182 $liclass = '';
6184 if ($first && ($count == 0)) { // Just one in the row
6185 $liclass = 'first last';
6186 $first = false;
6187 } else if ($first) {
6188 $liclass = 'first';
6189 $first = false;
6190 } else if ($count == 0) {
6191 $liclass = 'last';
6194 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
6195 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
6198 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
6199 if ($tab->selected) {
6200 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
6201 } else if ($tab->active) {
6202 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
6206 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
6208 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
6209 $str .= '<a href="#" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
6210 } else {
6211 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
6214 if (!empty($tab->subtree)) {
6215 $str .= convert_tree_to_html($tab->subtree, $row+1);
6216 } else if ($tab->selected) {
6217 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
6220 $str .= ' </li>'."\n";
6222 $str .= '</ul>'."\n";
6224 return $str;
6228 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
6230 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
6232 $tabrows = array_reverse($tabrows);
6234 $subtree = array();
6236 foreach ($tabrows as $row) {
6237 $tree = array();
6239 foreach ($row as $tab) {
6240 $tab->inactive = in_array((string)$tab->id, $inactive);
6241 $tab->active = in_array((string)$tab->id, $activated);
6242 $tab->selected = (string)$tab->id == $selected;
6244 if ($tab->active || $tab->selected) {
6245 if ($subtree) {
6246 $tab->subtree = $subtree;
6249 $tree[] = $tab;
6251 $subtree = $tree;
6254 return $subtree;
6259 * Returns a string containing a link to the user documentation for the current
6260 * page. Also contains an icon by default. Shown to teachers and admin only.
6262 * @param string $text The text to be displayed for the link
6263 * @param string $iconpath The path to the icon to be displayed
6265 function page_doc_link($text='', $iconpath='') {
6266 global $ME, $COURSE, $CFG;
6268 if (empty($CFG->docroot)) {
6269 return '';
6272 if (empty($COURSE->id)) {
6273 $context = get_context_instance(CONTEXT_SYSTEM);
6274 } else {
6275 $context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
6278 if (!has_capability('moodle/site:doclinks', $context)) {
6279 return '';
6282 if (empty($CFG->pagepath)) {
6283 $CFG->pagepath = $ME;
6286 $path = str_replace($CFG->httpswwwroot.'/','', $CFG->pagepath); // Because the page could be HTTPSPAGEREQUIRED
6287 $path = str_replace('.php', '', $path);
6289 if (empty($path)) { // Not for home page
6290 return '';
6292 return doc_link($path, $text, $iconpath);
6296 * Returns a string containing a link to the user documentation.
6297 * Also contains an icon by default. Shown to teachers and admin only.
6299 * @param string $path The page link after doc root and language, no
6300 * leading slash.
6301 * @param string $text The text to be displayed for the link
6302 * @param string $iconpath The path to the icon to be displayed
6304 function doc_link($path='', $text='', $iconpath='') {
6305 global $CFG;
6307 if (empty($CFG->docroot)) {
6308 return '';
6311 $target = '';
6312 if (!empty($CFG->doctonewwindow)) {
6313 $target = ' target="_blank"';
6316 $lang = str_replace('_utf8', '', current_language());
6318 $str = '<a href="' .$CFG->docroot. '/' .$lang. '/' .$path. '"' .$target. '>';
6320 if (empty($iconpath)) {
6321 $iconpath = $CFG->httpswwwroot . '/pix/docs.gif';
6324 // alt left blank intentionally to prevent repetition in screenreaders
6325 $str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
6327 return $str;
6332 * Returns true if the current site debugging settings are equal or above specified level.
6333 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
6334 * routing of notices is controlled by $CFG->debugdisplay
6335 * eg use like this:
6337 * 1) debugging('a normal debug notice');
6338 * 2) debugging('something really picky', DEBUG_ALL);
6339 * 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
6340 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
6342 * In code blocks controlled by debugging() (such as example 4)
6343 * any output should be routed via debugging() itself, or the lower-level
6344 * trigger_error() or error_log(). Using echo or print will break XHTML
6345 * JS and HTTP headers.
6348 * @param string $message a message to print
6349 * @param int $level the level at which this debugging statement should show
6350 * @return bool
6352 function debugging($message='', $level=DEBUG_NORMAL) {
6354 global $CFG;
6356 if (empty($CFG->debug)) {
6357 return false;
6360 if ($CFG->debug >= $level) {
6361 if ($message) {
6362 $callers = debug_backtrace();
6363 $from = '<ul style="text-align: left">';
6364 foreach ($callers as $caller) {
6365 if (!isset($caller['line'])) {
6366 $caller['line'] = '?'; // probably call_user_func()
6368 if (!isset($caller['file'])) {
6369 $caller['file'] = $CFG->dirroot.'/unknownfile'; // probably call_user_func()
6371 $from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
6372 if (isset($caller['function'])) {
6373 $from .= ': call to ';
6374 if (isset($caller['class'])) {
6375 $from .= $caller['class'] . $caller['type'];
6377 $from .= $caller['function'] . '()';
6379 $from .= '</li>';
6381 $from .= '</ul>';
6382 if (!isset($CFG->debugdisplay)) {
6383 $CFG->debugdisplay = ini_get('display_errors');
6385 if ($CFG->debugdisplay) {
6386 if (!defined('DEBUGGING_PRINTED')) {
6387 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
6389 notify($message . $from, 'notifytiny');
6390 } else {
6391 trigger_error($message . $from, E_USER_NOTICE);
6394 return true;
6396 return false;
6400 * Disable debug messages from debugging(), while keeping PHP error reporting level as is.
6402 function disable_debugging() {
6403 global $CFG;
6404 $CFG->debug = $CFG->debug | 0x80000000; // switch the sign bit in integer number ;-)
6409 * Returns string to add a frame attribute, if required
6411 function frametarget() {
6412 global $CFG;
6414 if (empty($CFG->framename) or ($CFG->framename == '_top')) {
6415 return '';
6416 } else {
6417 return ' target="'.$CFG->framename.'" ';
6422 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
6423 * pages that use bits from many different files in very confusing ways (e.g. blocks).
6424 * @usage print_location_comment(__FILE__, __LINE__);
6425 * @param string $file
6426 * @param integer $line
6427 * @param boolean $return Whether to return or print the comment
6428 * @return mixed Void unless true given as third parameter
6430 function print_location_comment($file, $line, $return = false)
6432 if ($return) {
6433 return "<!-- $file at line $line -->\n";
6434 } else {
6435 echo "<!-- $file at line $line -->\n";
6441 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
6442 * provide this function with the language strings for sortasc and sortdesc.
6443 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
6444 * @param string $direction 'up' or 'down'
6445 * @param string $strsort The language string used for the alt attribute of this image
6446 * @param bool $return Whether to print directly or return the html string
6447 * @return string HTML for the image
6449 * TODO See if this isn't already defined somewhere. If not, move this to weblib
6451 function print_arrow($direction='up', $strsort=null, $return=false) {
6452 global $CFG;
6454 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
6455 return null;
6458 $return = null;
6460 switch ($direction) {
6461 case 'up':
6462 $sortdir = 'asc';
6463 break;
6464 case 'down':
6465 $sortdir = 'desc';
6466 break;
6467 case 'move':
6468 $sortdir = 'asc';
6469 break;
6470 default:
6471 $sortdir = null;
6472 break;
6475 // Prepare language string
6476 $strsort = '';
6477 if (empty($strsort) && !empty($sortdir)) {
6478 $strsort = get_string('sort' . $sortdir, 'grades');
6481 $return = ' <img src="'.$CFG->pixpath.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
6483 if ($return) {
6484 return $return;
6485 } else {
6486 echo $return;
6491 * Returns boolean true if the current language is right-to-left (Hebrew, Arabic etc)
6494 function right_to_left() {
6495 static $result;
6497 if (isset($result)) {
6498 return $result;
6500 return $result = (get_string('thisdirection') == 'rtl');
6505 * Returns swapped left<=>right if in RTL environment.
6506 * part of RTL support
6508 * @param string $align align to check
6509 * @return string
6511 function fix_align_rtl($align) {
6512 if (!right_to_left()) {
6513 return $align;
6515 if ($align=='left') { return 'right'; }
6516 if ($align=='right') { return 'left'; }
6517 return $align;
6521 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: