MDL-10724 Added the help buttons to the item edit form
[moodle-pu.git] / lib / weblib.php
blobb0f15f83aa907fefcab62f4b017e08345f10aa70
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 * @return string If $return is true then the entire form is returned as a string.
1064 * @todo Finish documenting this function<br>
1066 function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
1067 $targetwindow='self', $selectlabel='', $optionsextra=NULL) {
1069 global $CFG;
1070 static $go, $choose; /// Locally cached, in case there's lots on a page
1072 if (empty($options)) {
1073 return '';
1076 if (!isset($go)) {
1077 $go = get_string('go');
1080 if ($nothing == 'choose') {
1081 if (!isset($choose)) {
1082 $choose = get_string('choose');
1084 $nothing = $choose.'...';
1087 // changed reference to document.getElementById('id_abc') instead of document.abc
1088 // MDL-7861
1089 $output = '<form action="'.$CFG->wwwroot.'/course/jumpto.php"'.
1090 ' method="get" '.
1091 $CFG->frametarget.
1092 ' id="'.$formid.'"'.
1093 ' class="popupform">';
1094 if ($help) {
1095 $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
1096 } else {
1097 $button = '';
1100 if ($selectlabel) {
1101 $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
1104 $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";
1106 if ($nothing != '') {
1107 $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
1110 $inoptgroup = false;
1112 foreach ($options as $value => $label) {
1114 if ($label == '--') { /// we are ending previous optgroup
1115 /// Check to see if we already have a valid open optgroup
1116 /// XHTML demands that there be at least 1 option within an optgroup
1117 if ($inoptgroup and (count($optgr) > 1) ) {
1118 $output .= implode('', $optgr);
1119 $output .= ' </optgroup>';
1121 $optgr = array();
1122 $inoptgroup = false;
1123 continue;
1124 } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
1126 /// Check to see if we already have a valid open optgroup
1127 /// XHTML demands that there be at least 1 option within an optgroup
1128 if ($inoptgroup and (count($optgr) > 1) ) {
1129 $output .= implode('', $optgr);
1130 $output .= ' </optgroup>';
1133 unset($optgr);
1134 $optgr = array();
1136 $optgr[] = ' <optgroup label="'. s(format_string(substr($label,2))) .'">'; // Plain labels
1138 $inoptgroup = true; /// everything following will be in an optgroup
1139 continue;
1141 } else {
1142 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()]))
1144 $url=sid_process_url( $common . $value );
1145 } else
1147 $url=$common . $value;
1149 $optstr = ' <option value="' . $url . '"';
1151 if ($value == $selected) {
1152 $optstr .= ' selected="selected"';
1155 if (!empty($optionsextra[$value])) {
1156 $optstr .= ' '.$optionsextra[$value];
1159 if ($label) {
1160 $optstr .= '>'. $label .'</option>' . "\n";
1161 } else {
1162 $optstr .= '>'. $value .'</option>' . "\n";
1165 if ($inoptgroup) {
1166 $optgr[] = $optstr;
1167 } else {
1168 $output .= $optstr;
1174 /// catch the final group if not closed
1175 if ($inoptgroup and count($optgr) > 1) {
1176 $output .= implode('', $optgr);
1177 $output .= ' </optgroup>';
1180 $output .= '</select>';
1181 $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1182 $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
1183 $output .= '<input type="submit" value="'.$go.'" /></div>';
1184 $output .= '<script type="text/javascript">'.
1185 "\n//<![CDATA[\n".
1186 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
1187 "\n//]]>\n".'</script>';
1188 $output .= '</div>';
1189 $output .= '</form>';
1191 if ($return) {
1192 return $output;
1193 } else {
1194 echo $output;
1200 * Prints some red text
1202 * @param string $error The text to be displayed in red
1204 function formerr($error) {
1206 if (!empty($error)) {
1207 echo '<span class="error">'. $error .'</span>';
1212 * Validates an email to make sure it makes sense.
1214 * @param string $address The email address to validate.
1215 * @return boolean
1217 function validate_email($address) {
1219 return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1220 '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1221 '@'.
1222 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1223 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
1224 $address));
1228 * Extracts file argument either from file parameter or PATH_INFO
1230 * @param string $scriptname name of the calling script
1231 * @return string file path (only safe characters)
1233 function get_file_argument($scriptname) {
1234 global $_SERVER;
1236 $relativepath = FALSE;
1238 // first try normal parameter (compatible method == no relative links!)
1239 $relativepath = optional_param('file', FALSE, PARAM_PATH);
1240 if ($relativepath === '/testslasharguments') {
1241 echo 'test -1 : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
1242 die;
1245 // then try extract file from PATH_INFO (slasharguments method)
1246 if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
1247 $path_info = $_SERVER['PATH_INFO'];
1248 // check that PATH_INFO works == must not contain the script name
1249 if (!strpos($path_info, $scriptname)) {
1250 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1251 if ($relativepath === '/testslasharguments') {
1252 echo 'test 1 : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
1253 die;
1258 // now if both fail try the old way
1259 // (for compatibility with misconfigured or older buggy php implementations)
1260 if (!$relativepath) {
1261 $arr = explode($scriptname, me());
1262 if (!empty($arr[1])) {
1263 $path_info = strip_querystring($arr[1]);
1264 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1265 if ($relativepath === '/testslasharguments') {
1266 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
1267 die;
1272 return $relativepath;
1276 * Searches the current environment variables for some slash arguments
1278 * @param string $file ?
1279 * @todo Finish documenting this function
1281 function get_slash_arguments($file='file.php') {
1283 if (!$string = me()) {
1284 return false;
1287 $pathinfo = explode($file, $string);
1289 if (!empty($pathinfo[1])) {
1290 return addslashes($pathinfo[1]);
1291 } else {
1292 return false;
1297 * Extracts arguments from "/foo/bar/something"
1298 * eg http://mysite.com/script.php/foo/bar/something
1300 * @param string $string ?
1301 * @param int $i ?
1302 * @return array|string
1303 * @todo Finish documenting this function
1305 function parse_slash_arguments($string, $i=0) {
1307 if (detect_munged_arguments($string)) {
1308 return false;
1310 $args = explode('/', $string);
1312 if ($i) { // return just the required argument
1313 return $args[$i];
1315 } else { // return the whole array
1316 array_shift($args); // get rid of the empty first one
1317 return $args;
1322 * Just returns an array of text formats suitable for a popup menu
1324 * @uses FORMAT_MOODLE
1325 * @uses FORMAT_HTML
1326 * @uses FORMAT_PLAIN
1327 * @uses FORMAT_MARKDOWN
1328 * @return array
1330 function format_text_menu() {
1332 return array (FORMAT_MOODLE => get_string('formattext'),
1333 FORMAT_HTML => get_string('formathtml'),
1334 FORMAT_PLAIN => get_string('formatplain'),
1335 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1339 * Given text in a variety of format codings, this function returns
1340 * the text as safe HTML.
1342 * @uses $CFG
1343 * @uses FORMAT_MOODLE
1344 * @uses FORMAT_HTML
1345 * @uses FORMAT_PLAIN
1346 * @uses FORMAT_WIKI
1347 * @uses FORMAT_MARKDOWN
1348 * @param string $text The text to be formatted. This is raw text originally from user input.
1349 * @param int $format Identifier of the text format to be used
1350 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1351 * @param array $options ?
1352 * @param int $courseid ?
1353 * @return string
1354 * @todo Finish documenting this function
1356 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1358 global $CFG, $COURSE;
1360 if ($text === '') {
1361 return ''; // no need to do any filters and cleaning
1364 if (!isset($options->trusttext)) {
1365 $options->trusttext = false;
1368 if (!isset($options->noclean)) {
1369 $options->noclean=false;
1371 if (!isset($options->nocache)) {
1372 $options->nocache=false;
1374 if (!isset($options->smiley)) {
1375 $options->smiley=true;
1377 if (!isset($options->filter)) {
1378 $options->filter=true;
1380 if (!isset($options->para)) {
1381 $options->para=true;
1383 if (!isset($options->newlines)) {
1384 $options->newlines=true;
1387 if (empty($courseid)) {
1388 $courseid = $COURSE->id;
1391 if (!empty($CFG->cachetext) and empty($options->nocache)) {
1392 $time = time() - $CFG->cachetext;
1393 $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);
1394 if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
1395 if ($oldcacheitem->timemodified >= $time) {
1396 return $oldcacheitem->formattedtext;
1401 // trusttext overrides the noclean option!
1402 if ($options->trusttext) {
1403 if (trusttext_present($text)) {
1404 $text = trusttext_strip($text);
1405 if (!empty($CFG->enabletrusttext)) {
1406 $options->noclean = true;
1407 } else {
1408 $options->noclean = false;
1410 } else {
1411 $options->noclean = false;
1413 } else if (!debugging('', DEBUG_DEVELOPER)) {
1414 // strip any forgotten trusttext in non-developer mode
1415 // do not forget to disable text cache when debugging trusttext!!
1416 $text = trusttext_strip($text);
1419 $CFG->currenttextiscacheable = true; // Default status - can be changed by any filter
1421 switch ($format) {
1422 case FORMAT_HTML:
1423 if ($options->smiley) {
1424 replace_smilies($text);
1426 if (!$options->noclean) {
1427 $text = clean_text($text, FORMAT_HTML);
1429 if ($options->filter) {
1430 $text = filter_text($text, $courseid);
1432 break;
1434 case FORMAT_PLAIN:
1435 $text = s($text); // cleans dangerous JS
1436 $text = rebuildnolinktag($text);
1437 $text = str_replace(' ', '&nbsp; ', $text);
1438 $text = nl2br($text);
1439 break;
1441 case FORMAT_WIKI:
1442 // this format is deprecated
1443 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1444 this message as all texts should have been converted to Markdown format instead.
1445 Please post a bug report to http://moodle.org/bugs with information about where you
1446 saw this message.</p>'.s($text);
1447 break;
1449 case FORMAT_MARKDOWN:
1450 $text = markdown_to_html($text);
1451 if ($options->smiley) {
1452 replace_smilies($text);
1454 if (!$options->noclean) {
1455 $text = clean_text($text, FORMAT_HTML);
1458 if ($options->filter) {
1459 $text = filter_text($text, $courseid);
1461 break;
1463 default: // FORMAT_MOODLE or anything else
1464 $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
1465 if (!$options->noclean) {
1466 $text = clean_text($text, FORMAT_HTML);
1469 if ($options->filter) {
1470 $text = filter_text($text, $courseid);
1472 break;
1475 if (empty($options->nocache) and !empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
1476 $newcacheitem = new object();
1477 $newcacheitem->md5key = $md5key;
1478 $newcacheitem->formattedtext = addslashes($text);
1479 $newcacheitem->timemodified = time();
1480 if ($oldcacheitem) { // See bug 4677 for discussion
1481 $newcacheitem->id = $oldcacheitem->id;
1482 @update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1483 // It's unlikely that the cron cache cleaner could have
1484 // deleted this entry in the meantime, as it allows
1485 // some extra time to cover these cases.
1486 } else {
1487 @insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1488 // Again, it's possible that another user has caused this
1489 // record to be created already in the time that it took
1490 // to traverse this function. That's OK too, as the
1491 // call above handles duplicate entries, and eventually
1492 // the cron cleaner will delete them.
1496 return $text;
1499 /** Converts the text format from the value to the 'internal'
1500 * name or vice versa. $key can either be the value or the name
1501 * and you get the other back.
1503 * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1504 * @return mixed as above but the other way around!
1506 function text_format_name( $key ) {
1507 $lookup = array();
1508 $lookup[FORMAT_MOODLE] = 'moodle';
1509 $lookup[FORMAT_HTML] = 'html';
1510 $lookup[FORMAT_PLAIN] = 'plain';
1511 $lookup[FORMAT_MARKDOWN] = 'markdown';
1512 $value = "error";
1513 if (!is_numeric($key)) {
1514 $key = strtolower( $key );
1515 $value = array_search( $key, $lookup );
1517 else {
1518 if (isset( $lookup[$key] )) {
1519 $value = $lookup[ $key ];
1522 return $value;
1526 /** Given a simple string, this function returns the string
1527 * processed by enabled filters if $CFG->filterall is enabled
1529 * @param string $string The string to be filtered.
1530 * @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
1531 * @param int $courseid Current course as filters can, potentially, use it
1532 * @return string
1534 function format_string ($string, $striplinks=true, $courseid=NULL ) {
1536 global $CFG, $COURSE;
1538 //We'll use a in-memory cache here to speed up repeated strings
1539 static $strcache = false;
1541 if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
1542 $strcache = array();
1545 //init course id
1546 if (empty($courseid)) {
1547 $courseid = $COURSE->id;
1550 //Calculate md5
1551 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
1553 //Fetch from cache if possible
1554 if (isset($strcache[$md5])) {
1555 return $strcache[$md5];
1558 // First replace all ampersands not followed by html entity code
1559 $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1561 if (!empty($CFG->filterall)) {
1562 $string = filter_string($string, $courseid);
1565 // If the site requires it, strip ALL tags from this string
1566 if (!empty($CFG->formatstringstriptags)) {
1567 $string = strip_tags($string);
1569 // Otherwise strip just links if that is required (default)
1570 } else if ($striplinks) { //strip links in string
1571 $string = preg_replace('/(<a[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1574 //Store to cache
1575 $strcache[$md5] = $string;
1577 return $string;
1581 * Given text in a variety of format codings, this function returns
1582 * the text as plain text suitable for plain email.
1584 * @uses FORMAT_MOODLE
1585 * @uses FORMAT_HTML
1586 * @uses FORMAT_PLAIN
1587 * @uses FORMAT_WIKI
1588 * @uses FORMAT_MARKDOWN
1589 * @param string $text The text to be formatted. This is raw text originally from user input.
1590 * @param int $format Identifier of the text format to be used
1591 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1592 * @return string
1594 function format_text_email($text, $format) {
1596 switch ($format) {
1598 case FORMAT_PLAIN:
1599 return $text;
1600 break;
1602 case FORMAT_WIKI:
1603 $text = wiki_to_html($text);
1604 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1605 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
1606 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1607 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1608 break;
1610 case FORMAT_HTML:
1611 return html_to_text($text);
1612 break;
1614 case FORMAT_MOODLE:
1615 case FORMAT_MARKDOWN:
1616 default:
1617 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1618 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1619 break;
1624 * Given some text in HTML format, this function will pass it
1625 * through any filters that have been defined in $CFG->textfilterx
1626 * The variable defines a filepath to a file containing the
1627 * filter function. The file must contain a variable called
1628 * $textfilter_function which contains the name of the function
1629 * with $courseid and $text parameters
1631 * @param string $text The text to be passed through format filters
1632 * @param int $courseid ?
1633 * @return string
1634 * @todo Finish documenting this function
1636 function filter_text($text, $courseid=NULL) {
1637 global $CFG, $COURSE;
1639 if (empty($courseid)) {
1640 $courseid = $COURSE->id; // (copied from format_text)
1643 if (!empty($CFG->textfilters)) {
1644 require_once($CFG->libdir.'/filterlib.php');
1645 $textfilters = explode(',', $CFG->textfilters);
1646 foreach ($textfilters as $textfilter) {
1647 if (is_readable($CFG->dirroot .'/'. $textfilter .'/filter.php')) {
1648 include_once($CFG->dirroot .'/'. $textfilter .'/filter.php');
1649 $functionname = basename($textfilter).'_filter';
1650 if (function_exists($functionname)) {
1651 $text = $functionname($courseid, $text);
1657 /// <nolink> tags removed for XHTML compatibility
1658 $text = str_replace('<nolink>', '', $text);
1659 $text = str_replace('</nolink>', '', $text);
1661 return $text;
1666 * Given a string (short text) in HTML format, this function will pass it
1667 * through any filters that have been defined in $CFG->stringfilters
1668 * The variable defines a filepath to a file containing the
1669 * filter function. The file must contain a variable called
1670 * $textfilter_function which contains the name of the function
1671 * with $courseid and $text parameters
1673 * @param string $string The text to be passed through format filters
1674 * @param int $courseid The id of a course
1675 * @return string
1677 function filter_string($string, $courseid=NULL) {
1678 global $CFG, $COURSE;
1680 if (empty($CFG->textfilters)) { // All filters are disabled anyway so quit
1681 return $string;
1684 if (empty($courseid)) {
1685 $courseid = $COURSE->id;
1688 require_once($CFG->libdir.'/filterlib.php');
1690 if (isset($CFG->stringfilters)) { // We have a predefined list to use, great!
1691 if (empty($CFG->stringfilters)) { // but it's blank, so finish now
1692 return $string;
1694 $stringfilters = explode(',', $CFG->stringfilters); // ..use the list we have
1696 } else { // Otherwise try to derive a list from textfilters
1697 if (strpos($CFG->textfilters, 'filter/multilang') !== false) { // Multilang is here
1698 $stringfilters = array('filter/multilang'); // Let's use just that
1699 $CFG->stringfilters = 'filter/multilang'; // Save it for next time through
1700 } else {
1701 $CFG->stringfilters = ''; // Save the result and return
1702 return $string;
1707 foreach ($stringfilters as $stringfilter) {
1708 if (is_readable($CFG->dirroot .'/'. $stringfilter .'/filter.php')) {
1709 include_once($CFG->dirroot .'/'. $stringfilter .'/filter.php');
1710 $functionname = basename($stringfilter).'_filter';
1711 if (function_exists($functionname)) {
1712 $string = $functionname($courseid, $string);
1717 /// <nolink> tags removed for XHTML compatibility
1718 $string = str_replace('<nolink>', '', $string);
1719 $string = str_replace('</nolink>', '', $string);
1721 return $string;
1725 * Is the text marked as trusted?
1727 * @param string $text text to be searched for TRUSTTEXT marker
1728 * @return boolean
1730 function trusttext_present($text) {
1731 if (strpos($text, TRUSTTEXT) !== FALSE) {
1732 return true;
1733 } else {
1734 return false;
1739 * This funtion MUST be called before the cleaning or any other
1740 * function that modifies the data! We do not know the origin of trusttext
1741 * in database, if it gets there in tweaked form we must not convert it
1742 * to supported form!!!
1744 * Please be carefull not to use stripslashes on data from database
1745 * or twice stripslashes when processing data recieved from user.
1747 * @param string $text text that may contain TRUSTTEXT marker
1748 * @return text without any TRUSTTEXT marker
1750 function trusttext_strip($text) {
1751 global $CFG;
1753 while (true) { //removing nested TRUSTTEXT
1754 $orig = $text;
1755 $text = str_replace(TRUSTTEXT, '', $text);
1756 if (strcmp($orig, $text) === 0) {
1757 return $text;
1763 * Mark text as trusted, such text may contain any HTML tags because the
1764 * normal text cleaning will be bypassed.
1765 * Please make sure that the text comes from trusted user before storing
1766 * it into database!
1768 function trusttext_mark($text) {
1769 global $CFG;
1770 if (!empty($CFG->enabletrusttext) and (strpos($text, TRUSTTEXT) === FALSE)) {
1771 return TRUSTTEXT.$text;
1772 } else {
1773 return $text;
1776 function trusttext_after_edit(&$text, $context) {
1777 if (has_capability('moodle/site:trustcontent', $context)) {
1778 $text = trusttext_strip($text);
1779 $text = trusttext_mark($text);
1780 } else {
1781 $text = trusttext_strip($text);
1785 function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
1786 global $CFG;
1788 $options = new object();
1789 $options->smiley = false;
1790 $options->filter = false;
1791 if (!empty($CFG->enabletrusttext)
1792 and has_capability('moodle/site:trustcontent', $context)
1793 and trusttext_present($text)) {
1794 $options->noclean = true;
1795 } else {
1796 $options->noclean = false;
1798 $text = trusttext_strip($text);
1799 if ($usehtmleditor) {
1800 $text = format_text($text, $format, $options);
1801 $format = FORMAT_HTML;
1802 } else if (!$options->noclean){
1803 $text = clean_text($text, $format);
1808 * Given raw text (eg typed in by a user), this function cleans it up
1809 * and removes any nasty tags that could mess up Moodle pages.
1811 * @uses FORMAT_MOODLE
1812 * @uses FORMAT_PLAIN
1813 * @uses ALLOWED_TAGS
1814 * @param string $text The text to be cleaned
1815 * @param int $format Identifier of the text format to be used
1816 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1817 * @return string The cleaned up text
1819 function clean_text($text, $format=FORMAT_MOODLE) {
1821 global $ALLOWED_TAGS, $CFG;
1823 if (empty($text) or is_numeric($text)) {
1824 return (string)$text;
1827 switch ($format) {
1828 case FORMAT_PLAIN:
1829 case FORMAT_MARKDOWN:
1830 return $text;
1832 default:
1834 if (!empty($CFG->enablehtmlpurifier)) {
1835 $text = purify_html($text);
1836 } else {
1837 /// Fix non standard entity notations
1838 $text = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $text);
1839 $text = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $text);
1841 /// Remove tags that are not allowed
1842 $text = strip_tags($text, $ALLOWED_TAGS);
1844 /// Clean up embedded scripts and , using kses
1845 $text = cleanAttributes($text);
1847 /// Again remove tags that are not allowed
1848 $text = strip_tags($text, $ALLOWED_TAGS);
1852 /// Remove potential script events - some extra protection for undiscovered bugs in our code
1853 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
1854 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
1856 return $text;
1861 * KSES replacement cleaning function - uses HTML Purifier.
1863 function purify_html($text) {
1864 global $CFG;
1866 static $purifier = false;
1867 if (!$purifier) {
1868 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.auto.php';
1869 $config = HTMLPurifier_Config::createDefault();
1870 $config->set('Core', 'AcceptFullDocuments', false);
1871 //$config->set('HTML', 'Strict', true);
1872 $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));
1873 $purifier = new HTMLPurifier($config);
1875 return $purifier->purify($text);
1879 * This function takes a string and examines it for HTML tags.
1880 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
1881 * which checks for attributes and filters them for malicious content
1882 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
1884 * @param string $str The string to be examined for html tags
1885 * @return string
1887 function cleanAttributes($str){
1888 $result = preg_replace_callback(
1889 '%(<[^>]*(>|$)|>)%m', #search for html tags
1890 "cleanAttributes2",
1891 $str
1893 return $result;
1897 * This function takes a string with an html tag and strips out any unallowed
1898 * protocols e.g. javascript:
1899 * It calls ancillary functions in kses which are prefixed by kses
1900 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
1902 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
1903 * element the html to be cleared
1904 * @return string
1906 function cleanAttributes2($htmlArray){
1908 global $CFG, $ALLOWED_PROTOCOLS;
1909 require_once($CFG->libdir .'/kses.php');
1911 $htmlTag = $htmlArray[1];
1912 if (substr($htmlTag, 0, 1) != '<') {
1913 return '&gt;'; //a single character ">" detected
1915 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
1916 return ''; // It's seriously malformed
1918 $slash = trim($matches[1]); //trailing xhtml slash
1919 $elem = $matches[2]; //the element name
1920 $attrlist = $matches[3]; // the list of attributes as a string
1922 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
1924 $attStr = '';
1925 foreach ($attrArray as $arreach) {
1926 $arreach['name'] = strtolower($arreach['name']);
1927 if ($arreach['name'] == 'style') {
1928 $value = $arreach['value'];
1929 while (true) {
1930 $prevvalue = $value;
1931 $value = kses_no_null($value);
1932 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
1933 $value = kses_decode_entities($value);
1934 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
1935 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
1936 if ($value === $prevvalue) {
1937 $arreach['value'] = $value;
1938 break;
1941 $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']);
1942 $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']);
1943 } else if ($arreach['name'] == 'href') {
1944 //Adobe Acrobat Reader XSS protection
1945 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd))[^a-z0-9_\.\-].*$/i', '$1', $arreach['value']);
1947 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
1950 $xhtml_slash = '';
1951 if (preg_match('%/\s*$%', $attrlist)) {
1952 $xhtml_slash = ' /';
1954 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
1958 * Replaces all known smileys in the text with image equivalents
1960 * @uses $CFG
1961 * @param string $text Passed by reference. The string to search for smily strings.
1962 * @return string
1964 function replace_smilies(&$text) {
1966 global $CFG;
1968 $lang = current_language();
1970 /// this builds the mapping array only once
1971 static $e = array();
1972 static $img = array();
1973 static $emoticons = array(
1974 ':-)' => 'smiley',
1975 ':)' => 'smiley',
1976 ':-D' => 'biggrin',
1977 ';-)' => 'wink',
1978 ':-/' => 'mixed',
1979 'V-.' => 'thoughtful',
1980 ':-P' => 'tongueout',
1981 'B-)' => 'cool',
1982 '^-)' => 'approve',
1983 '8-)' => 'wideeyes',
1984 ':o)' => 'clown',
1985 ':-(' => 'sad',
1986 ':(' => 'sad',
1987 '8-.' => 'shy',
1988 ':-I' => 'blush',
1989 ':-X' => 'kiss',
1990 '8-o' => 'surprise',
1991 'P-|' => 'blackeye',
1992 '8-[' => 'angry',
1993 'xx-P' => 'dead',
1994 '|-.' => 'sleepy',
1995 '}-]' => 'evil',
1996 '(h)' => 'heart',
1997 '(heart)' => 'heart',
1998 '(y)' => 'yes',
1999 '(n)' => 'no',
2000 '(martin)' => 'martin',
2001 '( )' => 'egg'
2004 if (empty($img[$lang])) { /// After the first time this is not run again
2005 $e[$lang] = array();
2006 $img[$lang] = array();
2007 foreach ($emoticons as $emoticon => $image){
2008 $alttext = get_string($image, 'pix');
2010 $e[$lang][] = $emoticon;
2011 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath .'/s/'. $image .'.gif" />';
2015 // Exclude from transformations all the code inside <script> tags
2016 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
2017 // Based on code from glossary fiter by Williams Castillo.
2018 // - Eloy
2020 // Detect all the <script> zones to take out
2021 $excludes = array();
2022 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
2024 // Take out all the <script> zones from text
2025 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
2026 $excludes['<+'.$key.'+>'] = $value;
2028 if ($excludes) {
2029 $text = str_replace($excludes,array_keys($excludes),$text);
2032 /// this is the meat of the code - this is run every time
2033 $text = str_replace($e[$lang], $img[$lang], $text);
2035 // Recover all the <script> zones to text
2036 if ($excludes) {
2037 $text = str_replace(array_keys($excludes),$excludes,$text);
2042 * Given plain text, makes it into HTML as nicely as possible.
2043 * May contain HTML tags already
2045 * @uses $CFG
2046 * @param string $text The string to convert.
2047 * @param boolean $smiley Convert any smiley characters to smiley images?
2048 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
2049 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2050 * @return string
2053 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
2056 global $CFG;
2058 /// Remove any whitespace that may be between HTML tags
2059 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
2061 /// Remove any returns that precede or follow HTML tags
2062 $text = eregi_replace("([\n\r])<", " <", $text);
2063 $text = eregi_replace(">([\n\r])", "> ", $text);
2065 convert_urls_into_links($text);
2067 /// Make returns into HTML newlines.
2068 if ($newlines) {
2069 $text = nl2br($text);
2072 /// Turn smileys into images.
2073 if ($smiley) {
2074 replace_smilies($text);
2077 /// Wrap the whole thing in a paragraph tag if required
2078 if ($para) {
2079 return '<p>'.$text.'</p>';
2080 } else {
2081 return $text;
2086 * Given Markdown formatted text, make it into XHTML using external function
2088 * @uses $CFG
2089 * @param string $text The markdown formatted text to be converted.
2090 * @return string Converted text
2092 function markdown_to_html($text) {
2093 global $CFG;
2095 require_once($CFG->libdir .'/markdown.php');
2097 return Markdown($text);
2101 * Given HTML text, make it into plain text using external function
2103 * @uses $CFG
2104 * @param string $html The text to be converted.
2105 * @return string
2107 function html_to_text($html) {
2109 global $CFG;
2111 require_once($CFG->libdir .'/html2text.php');
2113 return html2text($html);
2117 * Given some text this function converts any URLs it finds into HTML links
2119 * @param string $text Passed in by reference. The string to be searched for urls.
2121 function convert_urls_into_links(&$text) {
2122 /// Make lone URLs into links. eg http://moodle.com/
2123 $text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
2124 "\\1<a href=\"\\2://\\3\\4\" target=\"_blank\">\\2://\\3\\4</a>", $text);
2126 /// eg www.moodle.com
2127 $text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
2128 "\\1<a href=\"http://www.\\2\\3\" target=\"_blank\">www.\\2\\3</a>", $text);
2132 * This function will highlight search words in a given string
2133 * It cares about HTML and will not ruin links. It's best to use
2134 * this function after performing any conversions to HTML.
2135 * Function found here: http://forums.devshed.com/t67822/scdaa2d1c3d4bacb4671d075ad41f0854.html
2137 * @param string $needle The string to search for
2138 * @param string $haystack The string to search for $needle in
2139 * @param int $case whether to do case-sensitive or insensitive matching.
2140 * @return string
2141 * @todo Finish documenting this function
2143 function highlight($needle, $haystack, $case=0,
2144 $left_string='<span class="highlight">', $right_string='</span>') {
2145 if (empty($needle)) {
2146 return $haystack;
2149 //$list_of_words = eregi_replace("[^-a-zA-Z0-9&.']", " ", $needle); // bug 3101
2150 $list_of_words = $needle;
2151 $list_array = explode(' ', $list_of_words);
2152 for ($i=0; $i<sizeof($list_array); $i++) {
2153 if (strlen($list_array[$i]) == 1) {
2154 $list_array[$i] = '';
2157 $list_of_words = implode(' ', $list_array);
2158 $list_of_words_cp = $list_of_words;
2159 $final = array();
2160 preg_match_all('/<(.+?)>/is',$haystack,$list_of_words);
2162 foreach (array_unique($list_of_words[0]) as $key=>$value) {
2163 $final['<|'.$key.'|>'] = $value;
2166 $haystack = str_replace($final,array_keys($final),$haystack);
2167 $list_of_words_cp = eregi_replace(' +', '|', $list_of_words_cp);
2169 if ($list_of_words_cp{0}=='|') {
2170 $list_of_words_cp{0} = '';
2172 if ($list_of_words_cp{strlen($list_of_words_cp)-1}=='|') {
2173 $list_of_words_cp{strlen($list_of_words_cp)-1}='';
2176 $list_of_words_cp = trim($list_of_words_cp);
2178 if ($list_of_words_cp) {
2180 $list_of_words_cp = "(". $list_of_words_cp .")";
2182 if (!$case){
2183 $haystack = eregi_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2184 } else {
2185 $haystack = ereg_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2188 $haystack = str_replace(array_keys($final),$final,$haystack);
2190 return $haystack;
2194 * This function will highlight instances of $needle in $haystack
2195 * It's faster that the above function and doesn't care about
2196 * HTML or anything.
2198 * @param string $needle The string to search for
2199 * @param string $haystack The string to search for $needle in
2200 * @return string
2202 function highlightfast($needle, $haystack) {
2204 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
2206 $pos = 0;
2208 foreach ($parts as $key => $part) {
2209 $parts[$key] = substr($haystack, $pos, strlen($part));
2210 $pos += strlen($part);
2212 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2213 $pos += strlen($needle);
2216 return (join('', $parts));
2220 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2221 * Internationalisation, for print_header and backup/restorelib.
2222 * @param $dir Default false.
2223 * @return string Attributes.
2225 function get_html_lang($dir = false) {
2226 $direction = '';
2227 if ($dir) {
2228 if (get_string('thisdirection') == 'rtl') {
2229 $direction = ' dir="rtl"';
2230 } else {
2231 $direction = ' dir="ltr"';
2234 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2235 $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
2236 @header('Content-Language: '.$language);
2237 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2241 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
2244 * Print a standard header
2246 * @uses $USER
2247 * @uses $CFG
2248 * @uses $SESSION
2249 * @param string $title Appears at the top of the window
2250 * @param string $heading Appears at the top of the page
2251 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2252 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2253 * @param string $meta Meta tags to be added to the header
2254 * @param boolean $cache Should this page be cacheable?
2255 * @param string $button HTML code for a button (usually for module editing)
2256 * @param string $menu HTML code for a popup menu
2257 * @param boolean $usexml use XML for this page
2258 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2259 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2261 function print_header ($title='', $heading='', $navigation='', $focus='',
2262 $meta='', $cache=true, $button='&nbsp;', $menu='',
2263 $usexml=false, $bodytags='', $return=false) {
2265 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
2267 $heading = format_string($heading); // Fix for MDL-8582
2269 /// This makes sure that the header is never repeated twice on a page
2270 if (defined('HEADER_PRINTED')) {
2271 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().');
2272 return;
2274 define('HEADER_PRINTED', 'true');
2277 /// Add the required stylesheets
2278 $stylesheetshtml = '';
2279 foreach ($CFG->stylesheets as $stylesheet) {
2280 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2282 $meta = $stylesheetshtml.$meta;
2285 /// Add the meta page from the themes if any were requested
2287 $metapage = '';
2289 if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
2290 ob_start();
2291 include_once($CFG->dirroot.'/theme/standard/meta.php');
2292 $metapage .= ob_get_contents();
2293 ob_end_clean();
2296 if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
2297 if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
2298 ob_start();
2299 include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
2300 $metapage .= ob_get_contents();
2301 ob_end_clean();
2305 if (!isset($THEME->metainclude) || $THEME->metainclude) {
2306 if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
2307 ob_start();
2308 include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
2309 $metapage .= ob_get_contents();
2310 ob_end_clean();
2314 $meta = $meta."\n".$metapage;
2317 /// Add the required JavaScript Libraries
2318 $meta .= "\n".require_js();
2320 if(is_newnav($navigation)){
2321 $home = false;
2322 } else {
2323 if ($navigation == 'home') {
2324 $home = true;
2325 $navigation = '';
2326 } else {
2327 $home = false;
2331 /// This is another ugly hack to make navigation elements available to print_footer later
2332 $THEME->title = $title;
2333 $THEME->heading = $heading;
2334 $THEME->navigation = $navigation;
2335 $THEME->button = $button;
2336 $THEME->menu = $menu;
2337 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2339 if ($button == '') {
2340 $button = '&nbsp;';
2343 if (!$menu and $navigation) {
2344 if (empty($CFG->loginhttps)) {
2345 $wwwroot = $CFG->wwwroot;
2346 } else {
2347 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
2349 $menu = user_login_string($COURSE);
2352 if (isset($SESSION->justloggedin)) {
2353 unset($SESSION->justloggedin);
2354 if (!empty($CFG->displayloginfailures)) {
2355 if (!empty($USER->username) and $USER->username != 'guest') {
2356 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
2357 $menu .= '&nbsp;<font size="1">';
2358 if (empty($count->accounts)) {
2359 $menu .= get_string('failedloginattempts', '', $count);
2360 } else {
2361 $menu .= get_string('failedloginattemptsall', '', $count);
2363 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
2364 $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
2365 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
2367 $menu .= '</font>';
2374 $meta = '<meta http-equiv="content-type" content="text/html; charset=utf-8" />'. "\n". $meta ."\n";
2375 if (!$usexml) {
2376 @header('Content-type: text/html; charset=utf-8');
2379 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2380 $direction = get_html_lang($dir=true);
2382 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2383 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2384 @header('Pragma: no-cache');
2385 @header('Expires: ');
2386 } else { // Do everything we can to always prevent clients and proxies caching
2387 @header('Cache-Control: no-store, no-cache, must-revalidate');
2388 @header('Cache-Control: post-check=0, pre-check=0', false);
2389 @header('Pragma: no-cache');
2390 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2391 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2393 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2394 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
2396 @header('Accept-Ranges: none');
2398 $currentlanguage = current_language();
2400 if (empty($usexml)) {
2401 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2402 } else {
2403 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2404 if(!$mathplayer) {
2405 header('Content-Type: application/xhtml+xml');
2407 echo '<?xml version="1.0" ?>'."\n";
2408 if (!empty($CFG->xml_stylesheets)) {
2409 $stylesheets = explode(';', $CFG->xml_stylesheets);
2410 foreach ($stylesheets as $stylesheet) {
2411 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
2414 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
2415 if (!empty($CFG->xml_doctype_extra)) {
2416 echo ' plus '. $CFG->xml_doctype_extra;
2418 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
2419 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2420 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
2421 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2422 $direction";
2423 if($mathplayer) {
2424 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
2425 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2426 $meta .= '</object>'."\n";
2427 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2431 // Clean up the title
2433 $title = format_string($title); // fix for MDL-8582
2434 $title = str_replace('"', '&quot;', $title);
2436 // Create class and id for this page
2438 page_id_and_class($pageid, $pageclass);
2440 $pageclass .= ' course-'.$COURSE->id;
2442 if (($pageid != 'site-index') && ($pageid != 'course-view') &&
2443 (strstr($pageid, 'admin') === FALSE)) {
2444 $pageclass .= ' nocoursepage';
2447 if (!isloggedin()) {
2448 $pageclass .= ' notloggedin';
2451 if (!empty($USER->editing)) {
2452 $pageclass .= ' editing';
2455 if (!empty($CFG->blocksdrag)) {
2456 $pageclass .= ' drag';
2459 $pageclass .= ' dir-'.get_string('thisdirection');
2461 $pageclass .= ' lang-'.$currentlanguage;
2463 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
2465 ob_start();
2466 include($CFG->header);
2467 $output = ob_get_contents();
2468 ob_end_clean();
2470 $output = force_strict_header($output);
2472 if (!empty($CFG->messaging)) {
2473 $output .= message_popup_window();
2476 if ($return) {
2477 return $output;
2478 } else {
2479 echo $output;
2484 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2485 * and substitute the XHTML strict document type.
2486 * Note, requires the 'xmlns' fix in function print_header above.
2487 * See: http://tracker.moodle.org/browse/MDL-7883
2488 * TODO:
2490 function force_strict_header($output) {
2491 global $CFG;
2492 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2493 $xsl = '/lib/xhtml.xsl';
2495 if (!headers_sent() && debugging(NULL, DEBUG_DEVELOPER)) { // In developer debugging, the browser will barf
2496 $ctype = 'Content-Type: ';
2497 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2499 if (isset($_SERVER['HTTP_ACCEPT'])
2500 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2501 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2502 // Firefox et al.
2503 $ctype .= 'application/xhtml+xml';
2504 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2506 } else if (file_exists($CFG->dirroot.$xsl)
2507 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2508 // XSL hack for IE 5+ on Windows.
2509 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2510 $www_xsl = $CFG->wwwroot .$xsl;
2511 $ctype .= 'application/xml';
2512 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2513 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2515 } else {
2516 //ELSE: Mac/IE, old/non-XML browsers.
2517 $ctype .= 'text/html';
2518 $prolog = '';
2520 @header($ctype.'; charset=utf-8');
2521 $output = $prolog . $output;
2523 // Test parser error-handling.
2524 if (isset($_GET['error'])) {
2525 $output .= "__ TEST: XML well-formed error < __\n";
2529 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
2531 return $output;
2537 * This version of print_header is simpler because the course name does not have to be
2538 * provided explicitly in the strings. It can be used on the site page as in courses
2539 * Eventually all print_header could be replaced by print_header_simple
2541 * @param string $title Appears at the top of the window
2542 * @param string $heading Appears at the top of the page
2543 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2544 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2545 * @param string $meta Meta tags to be added to the header
2546 * @param boolean $cache Should this page be cacheable?
2547 * @param string $button HTML code for a button (usually for module editing)
2548 * @param string $menu HTML code for a popup menu
2549 * @param boolean $usexml use XML for this page
2550 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2551 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2553 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
2554 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
2556 global $COURSE, $CFG;
2558 $shortname ='';
2559 if ($COURSE->id != SITEID) {
2560 $shortname = '<a href="'.$CFG->wwwroot.'/course/view.php?id='. $COURSE->id .'">'. $COURSE->shortname .'</a> ->';
2563 // If old style nav prepend course short name otherwise leave $navigation object alone
2564 if (!is_newnav($navigation)) {
2565 $navigation = $shortname.' '.$navigation;
2568 $output = print_header($COURSE->shortname .': '. $title, $COURSE->fullname .' '. $heading, $navigation, $focus, $meta,
2569 $cache, $button, $menu, $usexml, $bodytags, true);
2571 if ($return) {
2572 return $output;
2573 } else {
2574 echo $output;
2580 * Can provide a course object to make the footer contain a link to
2581 * to the course home page, otherwise the link will go to the site home
2583 * @uses $CFG
2584 * @uses $USER
2585 * @param course $course {@link $COURSE} object containing course information
2586 * @param ? $usercourse ?
2587 * @todo Finish documenting this function
2589 function print_footer($course=NULL, $usercourse=NULL, $return=false) {
2590 global $USER, $CFG, $THEME, $COURSE;
2592 if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
2593 admin_externalpage_print_footer();
2594 return;
2597 /// Course links
2598 if ($course) {
2599 if (is_string($course) && $course == 'none') { // Don't print any links etc
2600 $homelink = '';
2601 $loggedinas = '';
2602 $home = false;
2603 } else if (is_string($course) && $course == 'home') { // special case for site home page - please do not remove
2604 $course = get_site();
2605 $homelink = '<div class="sitelink">'.
2606 '<a title="moodle '. $CFG->release .' ('. $CFG->version .')" href="http://moodle.org/">'.
2607 '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
2608 $home = true;
2609 } else {
2610 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
2611 '/course/view.php?id='.$course->id.'">'.format_string($course->shortname).'</a></div>';
2612 $home = false;
2614 } else {
2615 $course = get_site(); // Set course as site course by default
2616 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
2617 $home = false;
2620 /// Set up some other navigation links (passed from print_header by ugly hack)
2621 $menu = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
2622 $title = isset($THEME->title) ? $THEME->title : '';
2623 $button = isset($THEME->button) ? $THEME->button : '';
2624 $heading = isset($THEME->heading) ? $THEME->heading : '';
2625 $navigation = isset($THEME->navigation) ? $THEME->navigation : '';
2626 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2629 /// Set the user link if necessary
2630 if (!$usercourse and is_object($course)) {
2631 $usercourse = $course;
2634 if (!isset($loggedinas)) {
2635 $loggedinas = user_login_string($usercourse, $USER);
2638 if ($loggedinas == $menu) {
2639 $menu = '';
2642 /// Provide some performance info if required
2643 $performanceinfo = '';
2644 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2645 $perf = get_performance_info();
2646 if (defined('MDL_PERFTOLOG')) {
2647 error_log("PERF: " . $perf['txt']);
2649 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
2650 $performanceinfo = $perf['html'];
2655 /// Include the actual footer file
2657 ob_start();
2658 include($CFG->footer);
2659 $output = ob_get_contents();
2660 ob_end_clean();
2662 if ($return) {
2663 return $output;
2664 } else {
2665 echo $output;
2670 * Returns the name of the current theme
2672 * @uses $CFG
2673 * @uses $USER
2674 * @uses $SESSION
2675 * @uses $COURSE
2676 * @uses $FULLME
2677 * @return string
2679 function current_theme() {
2680 global $CFG, $USER, $SESSION, $COURSE, $FULLME;
2682 if (empty($CFG->themeorder)) {
2683 $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
2684 } else {
2685 $themeorder = $CFG->themeorder;
2688 $theme = '';
2689 foreach ($themeorder as $themetype) {
2691 if (!empty($theme)) continue;
2693 switch ($themetype) {
2694 case 'page': // Page theme is for special page-only themes set by code
2695 if (!empty($CFG->pagetheme)) {
2696 $theme = $CFG->pagetheme;
2698 break;
2699 case 'course':
2700 if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) {
2701 $theme = $COURSE->theme;
2703 break;
2704 case 'category':
2705 if (!empty($CFG->allowcategorythemes)) {
2706 /// Nasty hack to check if we're in a category page
2707 if (stripos($FULLME, 'course/category.php') !== false) {
2708 global $id;
2709 if (!empty($id)) {
2710 $theme = current_category_theme($id);
2712 /// Otherwise check if we're in a course that has a category theme set
2713 } else if (!empty($COURSE->category)) {
2714 $theme = current_category_theme($COURSE->category);
2717 break;
2718 case 'session':
2719 if (!empty($SESSION->theme)) {
2720 $theme = $SESSION->theme;
2722 break;
2723 case 'user':
2724 if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) {
2725 $theme = $USER->theme;
2727 break;
2728 case 'site':
2729 $theme = $CFG->theme;
2730 break;
2731 default:
2732 /// do nothing
2736 /// A final check in case 'site' was not included in $CFG->themeorder
2737 if (empty($theme)) {
2738 $theme = $CFG->theme;
2741 return $theme;
2745 * Retrieves the category theme if one exists, otherwise checks the parent categories.
2746 * Recursive function.
2748 * @uses $COURSE
2749 * @param integer $categoryid id of the category to check
2750 * @return string theme name
2752 function current_category_theme($categoryid=0) {
2753 global $COURSE;
2755 /// Use the COURSE global if the categoryid not set
2756 if (empty($categoryid)) {
2757 if (!empty($COURSE->category)) {
2758 $categoryid = $COURSE->category;
2759 } else {
2760 return false;
2764 /// Retrieve the current category
2765 if ($category = get_record('course_categories', 'id', $categoryid)) {
2767 /// Return the category theme if it exists
2768 if (!empty($category->theme)) {
2769 return $category->theme;
2771 /// Otherwise try the parent category if one exists
2772 } else if (!empty($category->parent)) {
2773 return current_category_theme($category->parent);
2776 /// Return false if we can't find the category record
2777 } else {
2778 return false;
2783 * This function is called by stylesheets to set up the header
2784 * approriately as well as the current path
2786 * @uses $CFG
2787 * @param int $lastmodified ?
2788 * @param int $lifetime ?
2789 * @param string $thename ?
2791 function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='', $langdir='ltr') {
2793 global $CFG, $THEME;
2795 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
2796 $lastmodified = time();
2798 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
2799 header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
2800 header('Cache-Control: max-age='. $lifetime);
2801 header('Pragma: ');
2802 header('Content-type: text/css'); // Correct MIME type
2804 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
2806 if (empty($themename)) {
2807 $themename = current_theme(); // So we have something. Normally not needed.
2808 } else {
2809 $themename = clean_param($themename, PARAM_SAFEDIR);
2812 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
2813 unset($THEME);
2814 include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
2817 /// If this is the standard theme calling us, then find out what sheets we need
2819 if ($themename == 'standard') {
2820 if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
2821 $THEME->sheets = $DEFAULT_SHEET_LIST;
2822 } else if (empty($THEME->standardsheets)) { // We can stop right now!
2823 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
2824 exit;
2825 } else { // Use the provided subset only
2826 $THEME->sheets = $THEME->standardsheets;
2829 /// If we are a parent theme, then check for parent definitions
2831 } else if (!empty($THEME->parent) && $themename == $THEME->parent) {
2832 if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have
2833 $THEME->sheets = $DEFAULT_SHEET_LIST;
2834 } else if (empty($THEME->parentsheets)) { // We can stop right now!
2835 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
2836 exit;
2837 } else { // Use the provided subset only
2838 $THEME->sheets = $THEME->parentsheets;
2842 /// Work out the last modified date for this theme
2844 foreach ($THEME->sheets as $sheet) {
2845 if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
2846 $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
2847 if ($sheetmodified > $lastmodified) {
2848 $lastmodified = $sheetmodified;
2854 /// Get a list of all the files we want to include
2855 $files = array();
2857 foreach ($THEME->sheets as $sheet) {
2858 $files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
2861 if ($themename == 'standard') { // Add any standard styles included in any modules
2862 if (!empty($THEME->modsheets)) { // Search for styles.php within activity modules
2863 if ($mods = get_list_of_plugins('mod')) {
2864 foreach ($mods as $mod) {
2865 if (file_exists($CFG->dirroot.'/mod/'.$mod.'/styles.php')) {
2866 $files[] = array($CFG->dirroot, '/mod/'.$mod.'/styles.php');
2872 if (!empty($THEME->blocksheets)) { // Search for styles.php within block modules
2873 if ($mods = get_list_of_plugins('blocks')) {
2874 foreach ($mods as $mod) {
2875 if (file_exists($CFG->dirroot.'/blocks/'.$mod.'/styles.php')) {
2876 $files[] = array($CFG->dirroot, '/blocks/'.$mod.'/styles.php');
2882 if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
2883 if ($mods = get_list_of_plugins('format','',$CFG->dirroot.'/course')) {
2884 foreach ($mods as $mod) {
2885 if (file_exists($CFG->dirroot.'/course/format/'.$mod.'/styles.php')) {
2886 $files[] = array($CFG->dirroot, '/course/format/'.$mod.'/styles.php');
2892 if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
2893 if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
2894 $files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
2899 $oppositlangdir = ($langdir == 'rtl') ? '_ltr' : '_rtl';
2901 if ($files) {
2902 /// Produce a list of all the files first
2903 echo '/**************************************'."\n";
2904 echo ' * THEME NAME: '.$themename."\n *\n";
2905 echo ' * Files included in this sheet:'."\n *\n";
2906 foreach ($files as $file) {
2907 if (strstr($file[1], $oppositlangdir)) continue;
2908 echo ' * '.$file[1]."\n";
2910 echo ' **************************************/'."\n\n";
2913 /// check if csscobstants is set
2914 if (!empty($THEME->cssconstants)) {
2915 require_once("$CFG->libdir/cssconstants.php");
2916 /// Actually collect all the files in order.
2917 $css = '';
2918 foreach ($files as $file) {
2919 if (strstr($file[1], $oppositlangdir)) continue;
2920 $css .= '/***** '.$file[1].' start *****/'."\n\n";
2921 $css .= file_get_contents($file[0].'/'.$file[1]);
2922 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
2924 /// replace css_constants with their values
2925 echo replace_cssconstants($css);
2926 } else {
2927 /// Actually output all the files in order.
2928 if (empty($CFG->CSSEdit) && empty($THEME->CSSEdit)) {
2929 foreach ($files as $file) {
2930 if (strstr($file[1], $oppositlangdir)) continue;
2931 echo '/***** '.$file[1].' start *****/'."\n\n";
2932 @include_once($file[0].'/'.$file[1]);
2933 echo '/***** '.$file[1].' end *****/'."\n\n";
2935 } else {
2936 foreach ($files as $file) {
2937 if (strstr($file[1], $oppositlangdir)) continue;
2938 echo '/* @group '.$file[1].' */'."\n\n";
2939 if (strstr($file[1], '.css') !== FALSE) {
2940 echo '@import url("'.$CFG->themewww.'/'.$file[1].'");'."\n\n";
2941 } else {
2942 @include_once($file[0].'/'.$file[1]);
2944 echo '/* @end */'."\n\n";
2950 return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
2954 function theme_setup($theme = '', $params=NULL) {
2955 /// Sets up global variables related to themes
2957 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
2959 if (empty($theme)) {
2960 $theme = current_theme();
2963 /// If the theme doesn't exist for some reason then revert to standardwhite
2964 if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
2965 $CFG->theme = $theme = 'standardwhite';
2968 /// Load up the theme config
2969 $THEME = NULL; // Just to be sure
2970 include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
2972 /// Put together the parameters
2973 if (!$params) {
2974 $params = array();
2977 /// Add parameter for the language direction
2978 $langdir = get_string('thisdirection');
2979 if ($langdir == 'rtl') {
2980 $params[] = 'langdir='.get_string('thisdirection');
2983 if ($theme != $CFG->theme) {
2984 $params[] = 'forceconfig='.$theme;
2987 /// Force language too if required
2988 if (!empty($THEME->langsheets)) {
2989 $params[] = 'lang='.current_language();
2993 /// Convert params to string
2994 if ($params) {
2995 $paramstring = '?'.implode('&', $params);
2996 } else {
2997 $paramstring = '';
3000 /// Set up image paths
3001 if(isset($CFG->smartpix) && $CFG->smartpix==1) {
3002 if($CFG->slasharguments) { // Use this method if possible for better caching
3003 $extra='';
3004 } else {
3005 $extra='?file=';
3008 $CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
3009 $CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
3010 } else if (empty($THEME->custompix)) { // Could be set in the above file
3011 $CFG->pixpath = $CFG->wwwroot .'/pix';
3012 $CFG->modpixpath = $CFG->wwwroot .'/mod';
3013 } else {
3014 $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
3015 $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
3018 /// Header and footer paths
3019 $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
3020 $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
3022 /// Define stylesheet loading order
3023 $CFG->stylesheets = array();
3024 if ($theme != 'standard') { /// The standard sheet is always loaded first
3025 $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
3027 if (!empty($THEME->parent)) { /// Parent stylesheets are loaded next
3028 $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
3030 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
3032 /// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
3033 if (!empty($HTTPSPAGEREQUIRED)) {
3034 $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
3035 $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
3036 $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
3037 foreach ($CFG->stylesheets as $key => $stylesheet) {
3038 $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
3046 * Returns text to be displayed to the user which reflects their login status
3048 * @uses $CFG
3049 * @uses $USER
3050 * @param course $course {@link $COURSE} object containing course information
3051 * @param user $user {@link $USER} object containing user information
3052 * @return string
3054 function user_login_string($course=NULL, $user=NULL) {
3055 global $USER, $CFG, $SITE;
3057 if (empty($user) and !empty($USER->id)) {
3058 $user = $USER;
3061 if (empty($course)) {
3062 $course = $SITE;
3065 if (!empty($user->realuser)) {
3066 if ($realuser = get_record('user', 'id', $user->realuser)) {
3067 $fullname = fullname($realuser, true);
3068 $realuserinfo = " [<a $CFG->frametarget
3069 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=1&amp;sesskey=".sesskey()."\">$fullname</a>] ";
3071 } else {
3072 $realuserinfo = '';
3075 if (empty($CFG->loginhttps)) {
3076 $wwwroot = $CFG->wwwroot;
3077 } else {
3078 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
3081 if (empty($course->id)) {
3082 // $course->id is not defined during installation
3083 return '';
3084 } else if (!empty($user->id)) {
3085 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3087 $fullname = fullname($user, true);
3088 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a>";
3089 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid)) {
3090 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
3092 if (isset($user->username) && $user->username == 'guest') {
3093 $loggedinas = $realuserinfo.get_string('loggedinasguest').
3094 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3095 } else if (!empty($user->switchrole[$context->id])) {
3096 $rolename = '';
3097 if ($role = get_record('role', 'id', $user->switchrole[$context->id])) {
3098 $rolename = ': '.format_string($role->name);
3100 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
3101 " (<a $CFG->frametarget
3102 href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
3103 } else {
3104 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
3105 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
3107 } else {
3108 $loggedinas = get_string('loggedinnot', 'moodle').
3109 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3111 return '<div class="logininfo">'.$loggedinas.'</div>';
3115 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
3116 * If not it applies sensible defaults.
3118 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
3119 * search forum block, etc. Important: these are 'silent' in a screen-reader
3120 * (unlike &gt; &raquo;), and must be accompanied by text.
3121 * @uses $THEME
3123 function check_theme_arrows() {
3124 global $THEME;
3126 if (!isset($THEME->rarrow) and !isset($THEME->larrow)) {
3127 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
3128 // Also OK in Win 9x/2K/IE 5.x
3129 $THEME->rarrow = '&#x25BA;';
3130 $THEME->larrow = '&#x25C4;';
3131 $uagent = $_SERVER['HTTP_USER_AGENT'];
3132 if (false !== strpos($uagent, 'Opera')
3133 || false !== strpos($uagent, 'Mac')) {
3134 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
3135 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
3136 $THEME->rarrow = '&#x25B6;';
3137 $THEME->larrow = '&#x25C0;';
3139 elseif (false !== strpos($uagent, 'Konqueror')) {
3140 $THEME->rarrow = '&rarr;';
3141 $THEME->larrow = '&larr;';
3143 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
3144 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
3145 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
3146 // To be safe, non-Unicode browsers!
3147 $THEME->rarrow = '&gt;';
3148 $THEME->larrow = '&lt;';
3154 * Return the right arrow with text ('next'), and optionally embedded in a link.
3155 * See function above, check_theme_arrows.
3156 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3157 * @param string $url An optional link to use in a surrounding HTML anchor.
3158 * @param bool $accesshide True if text should be hidden (for screen readers only).
3159 * @param string $addclass Additional class names for the link, or the arrow character.
3160 * @return string HTML string.
3162 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
3163 global $THEME;
3164 check_theme_arrows();
3165 $arrowclass = 'arrow ';
3166 if (! $url) {
3167 $arrowclass .= $addclass;
3169 $arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow.'</span>';
3170 $htmltext = '';
3171 if ($text) {
3172 $htmltext = $text.'&nbsp;';
3173 if ($accesshide) {
3174 $htmltext = '<span class="accesshide">'.$htmltext.'</span>';
3177 if ($url) {
3178 $class = '';
3179 if ($addclass) {
3180 $class =" class=\"$addclass\"";
3182 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
3184 return $htmltext.$arrow;
3188 * Return the left arrow with text ('previous'), and optionally embedded in a link.
3189 * See function above, check_theme_arrows.
3190 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3191 * @param string $url An optional link to use in a surrounding HTML anchor.
3192 * @param bool $accesshide True if text should be hidden (for screen readers only).
3193 * @param string $addclass Additional class names for the link, or the arrow character.
3194 * @return string HTML string.
3196 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
3197 global $THEME;
3198 check_theme_arrows();
3199 $arrowclass = 'arrow ';
3200 if (! $url) {
3201 $arrowclass .= $addclass;
3203 $arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow.'</span>';
3204 $htmltext = '';
3205 if ($text) {
3206 $htmltext = '&nbsp;'.$text;
3207 if ($accesshide) {
3208 $htmltext = '<span class="accesshide">'.$htmltext.'</span>';
3211 if ($url) {
3212 $class = '';
3213 if ($addclass) {
3214 $class =" class=\"$addclass\"";
3216 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
3218 return $arrow.$htmltext;
3222 * Return the breadcrumb trail navigation separator.
3223 * @return string HTML string.
3225 function get_separator() {
3226 //Accessibility: the 'hidden' slash is preferred for screen readers.
3227 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
3233 * Prints breadcrumb trail of links, called in theme/-/header.html
3235 * @uses $CFG
3236 * @param mixed $navigation The breadcrumb navigation string to be printed
3237 * @param string $separator The breadcrumb trail separator. The default 0 leads to the use
3238 * of $THEME->rarrow, themes could use '&rarr;', '/', or '' for a style-sheet solution.
3239 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
3241 function print_navigation ($navigation, $separator=0, $return=false) {
3242 global $CFG, $THEME;
3243 $output = '';
3245 if (0 === $separator) {
3246 $separator = get_separator();
3248 else {
3249 $separator = '<span class="sep">'. $separator .'</span>';
3252 if ($navigation) {
3254 if (is_newnav($navigation)) {
3255 if ($return) {
3256 return($navigation['navlinks']);
3257 } else {
3258 echo $navigation['navlinks'];
3259 return;
3261 } else {
3262 debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER);
3265 if (!is_array($navigation)) {
3266 $ar = explode('->', $navigation);
3267 $navigation = array();
3269 foreach ($ar as $a) {
3270 if (strpos($a, '</a>') === false) {
3271 $navigation[] = array('title' => $a, 'url' => '');
3272 } else {
3273 if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
3274 $navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
3280 if (! $site = get_site()) {
3281 $site = new object();
3282 $site->shortname = get_string('home');
3285 //Accessibility: breadcrumb links now in a list, &raquo; replaced with a 'silent' character.
3286 $nav_text = get_string('youarehere','access');
3287 $output .= '<h2 class="accesshide">'.$nav_text."</h2><ul>\n";
3289 $output .= '<li class="first">'."\n".'<a '.$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3290 .$CFG->wwwroot.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))
3291 && !empty($USER->id) && !empty($CFG->mymoodleredirect) && !isguest())
3292 ? '/my' : '') .'/">'. format_string($site->shortname) ."</a>\n</li>\n";
3295 foreach ($navigation as $navitem) {
3296 $title = trim(strip_tags(format_string($navitem['title'], false)));
3297 $url = $navitem['url'];
3299 if (empty($url)) {
3300 $output .= '<li class="first">'."$separator $title</li>\n";
3301 } else {
3302 $output .= '<li class="first">'."$separator\n<a ".$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3303 .$url.'">'."$title</a>\n</li>\n";
3307 $output .= "</ul>\n";
3310 if ($return) {
3311 return $output;
3312 } else {
3313 echo $output;
3318 * Prints a string in a specified size (retained for backward compatibility)
3320 * @param string $text The text to be displayed
3321 * @param int $size The size to set the font for text display.
3323 function print_headline($text, $size=2, $return=false) {
3324 $output = print_heading($text, '', $size, true);
3325 if ($return) {
3326 return $output;
3327 } else {
3328 echo $output;
3333 * Prints text in a format for use in headings.
3335 * @param string $text The text to be displayed
3336 * @param string $align The alignment of the printed paragraph of text
3337 * @param int $size The size to set the font for text display.
3339 function print_heading($text, $align='', $size=2, $class='main', $return=false) {
3340 if ($align) {
3341 $align = ' style="text-align:'.$align.';"';
3343 if ($class) {
3344 $class = ' class="'.$class.'"';
3346 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
3348 if ($return) {
3349 return $output;
3350 } else {
3351 echo $output;
3356 * Centered heading with attached help button (same title text)
3357 * and optional icon attached
3359 * @param string $text The text to be displayed
3360 * @param string $helppage The help page to link to
3361 * @param string $module The module whose help should be linked to
3362 * @param string $icon Image to display if needed
3364 function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
3365 $output = '';
3366 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
3367 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
3368 $output .= '</h2>';
3370 if ($return) {
3371 return $output;
3372 } else {
3373 echo $output;
3378 function print_heading_block($heading, $class='', $return=false) {
3379 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
3380 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
3382 if ($return) {
3383 return $output;
3384 } else {
3385 echo $output;
3391 * Print a link to continue on to another page.
3393 * @uses $CFG
3394 * @param string $link The url to create a link to.
3396 function print_continue($link, $return=false) {
3398 global $CFG;
3400 // in case we are logging upgrade in admin/index.php stop it
3401 if (function_exists('upgrade_log_finish')) {
3402 upgrade_log_finish();
3405 $output = '';
3407 if ($link == '') {
3408 if (!empty($_SERVER['HTTP_REFERER'])) {
3409 $link = $_SERVER['HTTP_REFERER'];
3410 $link = str_replace('&', '&amp;', $link); // make it valid XHTML
3411 } else {
3412 $link = $CFG->wwwroot .'/';
3416 $output .= '<div class="continuebutton">';
3418 $output .= print_single_button($link, NULL, get_string('continue'), 'post', $CFG->framename, true);
3419 $output .= '</div>'."\n";
3421 if ($return) {
3422 return $output;
3423 } else {
3424 echo $output;
3430 * Print a message in a standard themed box.
3431 * Replaces print_simple_box (see deprecatedlib.php)
3433 * @param string $message, the content of the box
3434 * @param string $classes, space-separated class names.
3435 * @param string $ids, space-separated id names.
3436 * @param boolean $return, return as string or just print it
3438 function print_box($message, $classes='generalbox', $ids='', $return=false) {
3440 $output = print_box_start($classes, $ids, true);
3441 $output .= stripslashes_safe($message);
3442 $output .= print_box_end(true);
3444 if ($return) {
3445 return $output;
3446 } else {
3447 echo $output;
3452 * Starts a box using divs
3453 * Replaces print_simple_box_start (see deprecatedlib.php)
3455 * @param string $classes, space-separated class names.
3456 * @param string $ids, space-separated id names.
3457 * @param boolean $return, return as string or just print it
3459 function print_box_start($classes='generalbox', $ids='', $return=false) {
3460 $output = '';
3462 if ($ids) {
3463 $ids = ' id="'.$ids.'"';
3466 $output .= '<div'.$ids.' class="box '.$classes.'">';
3468 if ($return) {
3469 return $output;
3470 } else {
3471 echo $output;
3477 * Simple function to end a box (see above)
3478 * Replaces print_simple_box_end (see deprecatedlib.php)
3480 * @param boolean $return, return as string or just print it
3482 function print_box_end($return=false) {
3483 $output = '</div>';
3484 if ($return) {
3485 return $output;
3486 } else {
3487 echo $output;
3493 * Print a self contained form with a single submit button.
3495 * @param string $link ?
3496 * @param array $options ?
3497 * @param string $label ?
3498 * @param string $method ?
3499 * @todo Finish documenting this function
3501 function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='') {
3502 $output = '';
3503 $link = str_replace('"', '&quot;', $link); //basic XSS protection
3504 $output .= '<div class="singlebutton">';
3505 // taking target out, will need to add later target="'.$target.'"
3506 $output .= '<form action="'. $link .'" method="'. $method .'">';
3507 $output .= '<div>';
3508 if ($options) {
3509 foreach ($options as $name => $value) {
3510 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
3513 if ($tooltip) {
3514 $tooltip = 'title="' . s($tooltip) . '"';
3515 } else {
3516 $tooltip = '';
3518 $output .= '<input type="submit" value="'. s($label) .'" ' . $tooltip . ' /></div></form></div>';
3520 if ($return) {
3521 return $output;
3522 } else {
3523 echo $output;
3529 * Print a spacer image with the option of including a line break.
3531 * @param int $height ?
3532 * @param int $width ?
3533 * @param boolean $br ?
3534 * @todo Finish documenting this function
3536 function print_spacer($height=1, $width=1, $br=true, $return=false) {
3537 global $CFG;
3538 $output = '';
3540 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot .'/pix/spacer.gif" alt="" />';
3541 if ($br) {
3542 $output .= '<br />'."\n";
3545 if ($return) {
3546 return $output;
3547 } else {
3548 echo $output;
3553 * Given the path to a picture file in a course, or a URL,
3554 * this function includes the picture in the page.
3556 * @param string $path ?
3557 * @param int $courseid ?
3558 * @param int $height ?
3559 * @param int $width ?
3560 * @param string $link ?
3561 * @todo Finish documenting this function
3563 function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
3564 global $CFG;
3565 $output = '';
3567 if ($height) {
3568 $height = 'height="'. $height .'"';
3570 if ($width) {
3571 $width = 'width="'. $width .'"';
3573 if ($link) {
3574 $output .= '<a href="'. $link .'">';
3576 if (substr(strtolower($path), 0, 7) == 'http://') {
3577 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
3579 } else if ($courseid) {
3580 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
3581 if ($CFG->slasharguments) { // Use this method if possible for better caching
3582 $output .= $CFG->wwwroot .'/file.php/'. $courseid .'/'. $path;
3583 } else {
3584 $output .= $CFG->wwwroot .'/file.php?file=/'. $courseid .'/'. $path;
3586 $output .= '" />';
3587 } else {
3588 $output .= 'Error: must pass URL or course';
3590 if ($link) {
3591 $output .= '</a>';
3594 if ($return) {
3595 return $output;
3596 } else {
3597 echo $output;
3602 * Print the specified user's avatar.
3604 * @param int $userid ?
3605 * @param int $courseid ?
3606 * @param boolean $picture Print the user picture?
3607 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
3608 * @param boolean $return If false print picture to current page, otherwise return the output as string
3609 * @param boolean $link Enclose printed image in a link to view specified course?
3610 * @param string $target link target attribute
3611 * @param boolean $alttext use username or userspecified text in image alt attribute
3612 * return string
3613 * @todo Finish documenting this function
3615 function print_user_picture($userid, $courseid, $picture, $size=0, $return=false, $link=true, $target='', $alttext=true) {
3616 global $CFG;
3618 if ($link) {
3619 if ($target) {
3620 $target=' target="_blank"';
3622 $output = '<a '.$target.' href="'. $CFG->wwwroot .'/user/view.php?id='. $userid .'&amp;course='. $courseid .'">';
3623 } else {
3624 $output = '';
3626 if (empty($size)) {
3627 $file = 'f2';
3628 $size = 35;
3629 } else if ($size === true or $size == 1) {
3630 $file = 'f1';
3631 $size = 100;
3632 } else if ($size >= 50) {
3633 $file = 'f1';
3634 } else {
3635 $file = 'f2';
3637 $class = "userpicture";
3638 if ($picture) { // Print custom user picture
3639 if ($CFG->slasharguments) { // Use this method if possible for better caching
3640 $src = $CFG->wwwroot .'/user/pix.php/'. $userid .'/'. $file .'.jpg';
3641 } else {
3642 $src = $CFG->wwwroot .'/user/pix.php?file=/'. $userid .'/'. $file .'.jpg';
3644 } else { // Print default user pictures (use theme version if available)
3645 $class .= " defaultuserpic";
3646 $src = "$CFG->pixpath/u/$file.png";
3648 $imagealt = '';
3649 if ($alttext and $user = get_record('user','id',$userid)) {
3650 if (!empty($user->imagealt)) {
3651 $imagealt = $user->imagealt;
3652 } else {
3653 $imagealt = get_string('pictureof','',fullname($user));
3657 $output .= '<img class="'.$class.'" src="'.$src.'" alt="'.s($imagealt).'" />';
3658 if ($link) {
3659 $output .= '</a>';
3662 if ($return) {
3663 return $output;
3664 } else {
3665 echo $output;
3670 * Prints a summary of a user in a nice little box.
3672 * @uses $CFG
3673 * @uses $USER
3674 * @param user $user A {@link $USER} object representing a user
3675 * @param course $course A {@link $COURSE} object representing a course
3677 function print_user($user, $course, $messageselect=false, $return=false) {
3679 global $CFG, $USER;
3681 $output = '';
3683 static $string;
3684 static $datestring;
3685 static $countries;
3687 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3689 if (empty($string)) { // Cache all the strings for the rest of the page
3691 $string->email = get_string('email');
3692 $string->location = get_string('location');
3693 $string->lastaccess = get_string('lastaccess');
3694 $string->activity = get_string('activity');
3695 $string->unenrol = get_string('unenrol');
3696 $string->loginas = get_string('loginas');
3697 $string->fullprofile = get_string('fullprofile');
3698 $string->role = get_string('role');
3699 $string->name = get_string('name');
3700 $string->never = get_string('never');
3702 $datestring->day = get_string('day');
3703 $datestring->days = get_string('days');
3704 $datestring->hour = get_string('hour');
3705 $datestring->hours = get_string('hours');
3706 $datestring->min = get_string('min');
3707 $datestring->mins = get_string('mins');
3708 $datestring->sec = get_string('sec');
3709 $datestring->secs = get_string('secs');
3711 $countries = get_list_of_countries();
3714 /// Get the hidden field list
3715 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
3716 $hiddenfields = array();
3717 } else {
3718 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
3721 $output .= '<table class="userinfobox">';
3722 $output .= '<tr>';
3723 $output .= '<td class="left side">';
3724 $output .= print_user_picture($user->id, $course->id, $user->picture, true, true);
3725 $output .= '</td>';
3726 $output .= '<td class="content">';
3727 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
3728 $output .= '<div class="info">';
3729 if (!empty($user->role) and ($user->role <> $course->teacher)) {
3730 $output .= $string->role .': '. $user->role .'<br />';
3732 if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguest()) or
3733 has_capability('moodle/course:viewhiddenuserfields', $context)) {
3734 $output .= $string->email .': <a href="mailto:'. $user->email .'">'. $user->email .'</a><br />';
3736 if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
3737 $output .= $string->location .': ';
3738 if ($user->city && !isset($hiddenfields['city'])) {
3739 $output .= $user->city;
3741 if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
3742 if ($user->city && !isset($hiddenfields['city'])) {
3743 $output .= ', ';
3745 $output .= $countries[$user->country];
3747 $output .= '<br />';
3750 if (!isset($hiddenfields['lastaccess'])) {
3751 if ($user->lastaccess) {
3752 $output .= $string->lastaccess .': '. userdate($user->lastaccess);
3753 $output .= '&nbsp; ('. format_time(time() - $user->lastaccess, $datestring) .')';
3754 } else {
3755 $output .= $string->lastaccess .': '. $string->never;
3758 $output .= '</div></td><td class="links">';
3759 //link to blogs
3760 if ($CFG->bloglevel > 0) {
3761 $output .= '<a href="'.$CFG->wwwroot.'/blog/index.php?userid='.$user->id.'">'.get_string('blogs','blog').'</a><br />';
3763 //link to notes
3764 if (has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context)) {
3765 $output .= '<a href="'.$CFG->wwwroot.'/notes/index.php?course=' . $course->id. '&amp;user='.$user->id.'">'.get_string('notes','notes').'</a><br />';
3768 if (has_capability('moodle/site:viewreports', $context)) {
3769 $timemidnight = usergetmidnight(time());
3770 $output .= '<a href="'. $CFG->wwwroot .'/course/user.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->activity .'</a><br />';
3772 if (has_capability('moodle/role:assign', $context, NULL)) { // Includes admins
3773 $output .= '<a href="'. $CFG->wwwroot .'/course/unenrol.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->unenrol .'</a><br />';
3775 if ($USER->id != $user->id && empty($USER->realuser) && has_capability('moodle/user:loginas', $context) &&
3776 ! has_capability('moodle/site:doanything', $context, $user->id, false)) {
3777 $output .= '<a href="'. $CFG->wwwroot .'/course/loginas.php?id='. $course->id .'&amp;user='. $user->id .'&amp;sesskey='. sesskey() .'">'. $string->loginas .'</a><br />';
3779 $output .= '<a href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&amp;course='. $course->id .'">'. $string->fullprofile .'...</a>';
3781 if (!empty($messageselect)) {
3782 $output .= '<br /><input type="checkbox" name="user'.$user->id.'" /> ';
3785 $output .= '</td></tr></table>';
3787 if ($return) {
3788 return $output;
3789 } else {
3790 echo $output;
3795 * Print a specified group's avatar.
3797 * @param group $group A single {@link group} object OR array of groups.
3798 * @param int $courseid The course ID.
3799 * @param boolean $large Default small picture, or large.
3800 * @param boolean $return If false print picture, otherwise return the output as string
3801 * @param boolean $link Enclose image in a link to view specified course?
3802 * @return string
3803 * @todo Finish documenting this function
3805 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
3806 global $CFG;
3808 if (is_array($group)) {
3809 $output = '';
3810 foreach($group as $g) {
3811 $output .= print_group_picture($g, $courseid, $large, true, $link);
3813 if ($return) {
3814 return $output;
3815 } else {
3816 echo $output;
3817 return;
3821 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3823 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
3824 return '';
3827 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
3828 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
3829 } else {
3830 $output = '';
3832 if ($large) {
3833 $file = 'f1';
3834 $size = 100;
3835 } else {
3836 $file = 'f2';
3837 $size = 35;
3839 if ($group->picture) { // Print custom group picture
3840 if ($CFG->slasharguments) { // Use this method if possible for better caching
3841 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot.'/user/pixgroup.php/'.$group->id.'/'.$file.'.jpg"'.
3842 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
3843 } else {
3844 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot.'/user/pixgroup.php?file=/'.$group->id.'/'.$file.'.jpg"'.
3845 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
3848 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
3849 $output .= '</a>';
3852 if ($return) {
3853 return $output;
3854 } else {
3855 echo $output;
3860 * Print a png image.
3862 * @param string $url ?
3863 * @param int $sizex ?
3864 * @param int $sizey ?
3865 * @param boolean $return ?
3866 * @param string $parameters ?
3867 * @todo Finish documenting this function
3869 function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
3870 global $CFG;
3871 static $recentIE;
3873 if (!isset($recentIE)) {
3874 $recentIE = check_browser_version('MSIE', '5.0');
3877 if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
3878 $output .= '<img src="'. $CFG->pixpath .'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
3879 ' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
3880 ' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
3881 "'$url', sizingMethod='scale') ".
3882 ' '. $parameters .' />';
3883 } else {
3884 $output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
3887 if ($return) {
3888 return $output;
3889 } else {
3890 echo $output;
3895 * Print a nicely formatted table.
3897 * @param array $table is an object with several properties.
3898 * <ul>
3899 * <li>$table->head - An array of heading names.
3900 * <li>$table->align - An array of column alignments
3901 * <li>$table->size - An array of column sizes
3902 * <li>$table->wrap - An array of "nowrap"s or nothing
3903 * <li>$table->data[] - An array of arrays containing the data.
3904 * <li>$table->width - A percentage of the page
3905 * <li>$table->tablealign - Align the whole table
3906 * <li>$table->cellpadding - Padding on each cell
3907 * <li>$table->cellspacing - Spacing between cells
3908 * <li>$table->class - class attribute to put on the table
3909 * <li>$table->id - id attribute to put on the table.
3910 * <li>$table->rowclass[] - classes to add to particular rows.
3911 * </ul>
3912 * @param bool $return whether to return an output string or echo now
3913 * @return boolean or $string
3914 * @todo Finish documenting this function
3916 function print_table($table, $return=false) {
3917 $output = '';
3919 if (isset($table->align)) {
3920 foreach ($table->align as $key => $aa) {
3921 if ($aa) {
3922 $align[$key] = ' text-align:'. $aa.';';
3923 } else {
3924 $align[$key] = '';
3928 if (isset($table->size)) {
3929 foreach ($table->size as $key => $ss) {
3930 if ($ss) {
3931 $size[$key] = ' width:'. $ss .';';
3932 } else {
3933 $size[$key] = '';
3937 if (isset($table->wrap)) {
3938 foreach ($table->wrap as $key => $ww) {
3939 if ($ww) {
3940 $wrap[$key] = ' white-space:nowrap;';
3941 } else {
3942 $wrap[$key] = '';
3947 if (empty($table->width)) {
3948 $table->width = '80%';
3951 if (empty($table->tablealign)) {
3952 $table->tablealign = 'center';
3955 if (empty($table->cellpadding)) {
3956 $table->cellpadding = '5';
3959 if (empty($table->cellspacing)) {
3960 $table->cellspacing = '1';
3963 if (empty($table->class)) {
3964 $table->class = 'generaltable';
3967 $tableid = empty($table->id) ? '' : 'id="'.$table->id.'"';
3969 $output .= '<table width="'.$table->width.'" ';
3970 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
3972 $countcols = 0;
3974 if (!empty($table->head)) {
3975 $countcols = count($table->head);
3976 $output .= '<tr>';
3977 foreach ($table->head as $key => $heading) {
3979 if (!isset($size[$key])) {
3980 $size[$key] = '';
3982 if (!isset($align[$key])) {
3983 $align[$key] = '';
3986 $output .= '<th class="header c'.$key.'" scope="col">'. $heading .'</th>';
3987 // commenting the following code out as <th style does not validate MDL-7861
3988 //$output .= '<th sytle="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.'" scope="col">'. $heading .'</th>';
3990 $output .= '</tr>'."\n";
3993 if (!empty($table->data)) {
3994 $oddeven = 1;
3995 foreach ($table->data as $key => $row) {
3996 $oddeven = $oddeven ? 0 : 1;
3997 if (!isset($table->rowclass[$key])) {
3998 $table->rowclass[$key] = '';
4000 $output .= '<tr class="r'.$oddeven.' '.$table->rowclass[$key].'">'."\n";
4001 if ($row == 'hr' and $countcols) {
4002 $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
4003 } else { /// it's a normal row of data
4004 foreach ($row as $key => $item) {
4005 if (!isset($size[$key])) {
4006 $size[$key] = '';
4008 if (!isset($align[$key])) {
4009 $align[$key] = '';
4011 if (!isset($wrap[$key])) {
4012 $wrap[$key] = '';
4014 $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.'">'. $item .'</td>';
4017 $output .= '</tr>'."\n";
4020 $output .= '</table>'."\n";
4022 if ($return) {
4023 return $output;
4026 echo $output;
4027 return true;
4031 * Creates a nicely formatted table and returns it.
4033 * @param array $table is an object with several properties.
4034 * <ul<li>$table->head - An array of heading names.
4035 * <li>$table->align - An array of column alignments
4036 * <li>$table->size - An array of column sizes
4037 * <li>$table->wrap - An array of "nowrap"s or nothing
4038 * <li>$table->data[] - An array of arrays containing the data.
4039 * <li>$table->class - A css class name
4040 * <li>$table->fontsize - Is the size of all the text
4041 * <li>$table->tablealign - Align the whole table
4042 * <li>$table->width - A percentage of the page
4043 * <li>$table->cellpadding - Padding on each cell
4044 * <li>$table->cellspacing - Spacing between cells
4045 * </ul>
4046 * @return string
4047 * @todo Finish documenting this function
4049 function make_table($table) {
4051 if (isset($table->align)) {
4052 foreach ($table->align as $key => $aa) {
4053 if ($aa) {
4054 $align[$key] = ' align="'. $aa .'"';
4055 } else {
4056 $align[$key] = '';
4060 if (isset($table->size)) {
4061 foreach ($table->size as $key => $ss) {
4062 if ($ss) {
4063 $size[$key] = ' width="'. $ss .'"';
4064 } else {
4065 $size[$key] = '';
4069 if (isset($table->wrap)) {
4070 foreach ($table->wrap as $key => $ww) {
4071 if ($ww) {
4072 $wrap[$key] = ' style="white-space:nowrap;" ';
4073 } else {
4074 $wrap[$key] = '';
4079 if (empty($table->width)) {
4080 $table->width = '80%';
4083 if (empty($table->tablealign)) {
4084 $table->tablealign = 'center';
4087 if (empty($table->cellpadding)) {
4088 $table->cellpadding = '5';
4091 if (empty($table->cellspacing)) {
4092 $table->cellspacing = '1';
4095 if (empty($table->class)) {
4096 $table->class = 'generaltable';
4099 if (empty($table->fontsize)) {
4100 $fontsize = '';
4101 } else {
4102 $fontsize = '<font size="'. $table->fontsize .'">';
4105 $output = '<table width="'. $table->width .'" align="'. $table->tablealign .'" ';
4106 $output .= ' cellpadding="'. $table->cellpadding .'" cellspacing="'. $table->cellspacing .'" class="'. $table->class .'">'."\n";
4108 if (!empty($table->head)) {
4109 $output .= '<tr valign="top">';
4110 foreach ($table->head as $key => $heading) {
4111 if (!isset($size[$key])) {
4112 $size[$key] = '';
4114 if (!isset($align[$key])) {
4115 $align[$key] = '';
4117 $output .= '<th valign="top" '. $align[$key].$size[$key] .' style="white-space:nowrap;" class="'. $table->class .'header" scope="col">'.$fontsize.$heading.'</th>';
4119 $output .= '</tr>'."\n";
4122 foreach ($table->data as $row) {
4123 $output .= '<tr valign="top">';
4124 foreach ($row as $key => $item) {
4125 if (!isset($size[$key])) {
4126 $size[$key] = '';
4128 if (!isset($align[$key])) {
4129 $align[$key] = '';
4131 if (!isset($wrap[$key])) {
4132 $wrap[$key] = '';
4134 $output .= '<td '. $align[$key].$size[$key].$wrap[$key] .' class="'. $table->class .'cell">'. $fontsize . $item .'</td>';
4136 $output .= '</tr>'."\n";
4138 $output .= '</table>'."\n";
4140 return $output;
4143 function print_recent_activity_note($time, $user, $text, $link, $return=false) {
4144 static $strftimerecent;
4145 $output = '';
4147 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
4148 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
4150 if (empty($strftimerecent)) {
4151 $strftimerecent = get_string('strftimerecent');
4154 $date = userdate($time, $strftimerecent);
4155 $name = fullname($user, $viewfullnames);
4157 $output .= '<div class="head">';
4158 $output .= '<div class="date">'.$date.'</div> '.
4159 '<div class="name">'.fullname($user, $viewfullnames).'</div>';
4160 $output .= '</div>';
4161 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
4163 if ($return) {
4164 return $output;
4165 } else {
4166 echo $output;
4172 * Prints a basic textarea field.
4174 * @uses $CFG
4175 * @param boolean $usehtmleditor ?
4176 * @param int $rows ?
4177 * @param int $cols ?
4178 * @param null $width <b>Legacy field no longer used!</b> Set to zero to get control over mincols
4179 * @param null $height <b>Legacy field no longer used!</b> Set to zero to get control over minrows
4180 * @param string $name ?
4181 * @param string $value ?
4182 * @param int $courseid ?
4183 * @todo Finish documenting this function
4185 function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $courseid=0, $return=false, $id='') {
4186 /// $width and height are legacy fields and no longer used as pixels like they used to be.
4187 /// However, you can set them to zero to override the mincols and minrows values below.
4189 global $CFG, $COURSE, $HTTPSPAGEREQUIRED;
4190 static $scriptcount = 0; // For loading the htmlarea script only once.
4192 $mincols = 65;
4193 $minrows = 10;
4194 $str = '';
4196 if ($id === '') {
4197 $id = 'edit-'.$name;
4200 if ( empty($CFG->editorsrc) ) { // for backward compatibility.
4201 if (empty($courseid)) {
4202 $courseid = $COURSE->id;
4205 if ($usehtmleditor) {
4206 if (!empty($courseid) and has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE, $courseid))) {
4207 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '&ampt;httpsrequired=1';
4208 // needed for course file area browsing in image insert plugin
4209 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4210 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php?id='.$courseid.$httpsrequired.'"></script>'."\n" : '';
4211 } else {
4212 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '?httpsrequired=1';
4213 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4214 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php'.$httpsrequired.'"></script>'."\n" : '';
4217 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4218 $CFG->httpswwwroot .'/lib/editor/htmlarea/lang/en.php"></script>'."\n" : '';
4219 $scriptcount++;
4221 if ($height) { // Usually with legacy calls
4222 if ($rows < $minrows) {
4223 $rows = $minrows;
4226 if ($width) { // Usually with legacy calls
4227 if ($cols < $mincols) {
4228 $cols = $mincols;
4233 $str .= '<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">';
4234 if ($usehtmleditor) {
4235 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
4236 } else {
4237 $str .= s($value);
4239 $str .= '</textarea>'."\n";
4241 if ($usehtmleditor) {
4242 // Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
4243 $str .= '<script type="text/javascript">document.write(\''.
4244 str_replace('\'','\\\'',editorshortcutshelpbutton()).'\'); </script>';
4247 if ($return) {
4248 return $str;
4250 echo $str;
4254 * Sets up the HTML editor on textareas in the current page.
4255 * If a field name is provided, then it will only be
4256 * applied to that field - otherwise it will be used
4257 * on every textarea in the page.
4259 * In most cases no arguments need to be supplied
4261 * @param string $name Form element to replace with HTMl editor by name
4263 function use_html_editor($name='', $editorhidebuttons='', $id='') {
4264 $editor = 'editor_'.md5($name); //name might contain illegal characters
4265 if ($id === '') {
4266 $id = 'edit-'.$name;
4268 echo "\n".'<script type="text/javascript" defer="defer">'."\n";
4269 echo '//<![CDATA['."\n\n"; // Extra \n is to fix odd wiki problem, MDL-8185
4270 echo "$editor = new HTMLArea('$id');\n";
4271 echo "var config = $editor.config;\n";
4273 echo print_editor_config($editorhidebuttons);
4275 if (empty($name)) {
4276 echo "\nHTMLArea.replaceAll($editor.config);\n";
4277 } else {
4278 echo "\n$editor.generate();\n";
4280 echo '//]]>'."\n";
4281 echo '</script>'."\n";
4284 function print_editor_config($editorhidebuttons='', $return=false) {
4285 global $CFG;
4287 $str = "config.pageStyle = \"body {";
4289 if (!(empty($CFG->editorbackgroundcolor))) {
4290 $str .= " background-color: $CFG->editorbackgroundcolor;";
4293 if (!(empty($CFG->editorfontfamily))) {
4294 $str .= " font-family: $CFG->editorfontfamily;";
4297 if (!(empty($CFG->editorfontsize))) {
4298 $str .= " font-size: $CFG->editorfontsize;";
4301 $str .= " }\";\n";
4302 $str .= "config.killWordOnPaste = ";
4303 $str .= (empty($CFG->editorkillword)) ? "false":"true";
4304 $str .= ';'."\n";
4305 $str .= 'config.fontname = {'."\n";
4307 $fontlist = isset($CFG->editorfontlist) ? explode(';', $CFG->editorfontlist) : array();
4308 $i = 1; // Counter is used to get rid of the last comma.
4310 foreach ($fontlist as $fontline) {
4311 if (!empty($fontline)) {
4312 if ($i > 1) {
4313 $str .= ','."\n";
4315 list($fontkey, $fontvalue) = split(':', $fontline);
4316 $str .= '"'. $fontkey ."\":\t'". $fontvalue ."'";
4318 $i++;
4321 $str .= '};';
4323 if (!empty($editorhidebuttons)) {
4324 $str .= "\nconfig.hideSomeButtons(\" ". $editorhidebuttons ." \");\n";
4325 } else if (!empty($CFG->editorhidebuttons)) {
4326 $str .= "\nconfig.hideSomeButtons(\" ". $CFG->editorhidebuttons ." \");\n";
4329 if (!empty($CFG->editorspelling) && !empty($CFG->aspellpath)) {
4330 $str .= print_speller_code($CFG->htmleditor, true);
4333 if ($return) {
4334 return $str;
4336 echo $str;
4340 * Returns a turn edit on/off button for course in a self contained form.
4341 * Used to be an icon, but it's now a simple form button
4343 * @uses $CFG
4344 * @uses $USER
4345 * @param int $courseid The course to update by id as found in 'course' table
4346 * @return string
4348 function update_course_icon($courseid) {
4350 global $CFG, $USER;
4352 $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
4354 $capcheck = false;
4356 if (has_capability('moodle/course:manageactivities', $coursecontext) ||
4357 has_capability('moodle/site:manageblocks', $coursecontext)) {
4358 $capcheck = true;
4359 } else {
4360 // loop through all child context, see if user has moodle/course:manageactivities or moodle/site:manageblocks
4361 if ($children = get_child_contexts($coursecontext)) {
4362 foreach ($children as $child) {
4363 $childcontext = get_record('context', 'id', $child);
4364 if (has_capability('moodle/course:manageactivities', $childcontext) ||
4365 has_capability('moodle/site:manageblocks', $childcontext)) {
4366 $capcheck = true;
4367 break;
4374 if ($capcheck) {
4375 if (!empty($USER->editing)) {
4376 $string = get_string('turneditingoff');
4377 $edit = '0';
4378 } else {
4379 $string = get_string('turneditingon');
4380 $edit = '1';
4383 return '<form '.$CFG->frametarget.' method="get" action="'.$CFG->wwwroot.'/course/view.php">'.
4384 '<div>'.
4385 '<input type="hidden" name="id" value="'.$courseid.'" />'.
4386 '<input type="hidden" name="edit" value="'.$edit.'" />'.
4387 '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
4388 '<input type="submit" value="'.$string.'" />'.
4389 '</div></form>';
4394 * Returns a little popup menu for switching roles
4396 * @uses $CFG
4397 * @uses $USER
4398 * @param int $courseid The course to update by id as found in 'course' table
4399 * @return string
4401 function switchroles_form($courseid) {
4403 global $CFG, $USER;
4406 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
4407 return '';
4410 if (!empty($USER->switchrole[$context->id])){ // Just a button to return to normal
4411 $options = array();
4412 $options['id'] = $courseid;
4413 $options['sesskey'] = sesskey();
4414 $options['switchrole'] = 0;
4416 return print_single_button($CFG->wwwroot.'/course/view.php', $options,
4417 get_string('switchrolereturn'), 'post', '_self', true);
4420 if (has_capability('moodle/role:switchroles', $context)) {
4421 if (!$roles = get_assignable_roles($context)) {
4422 return ''; // Nothing to show!
4424 // unset default user role - it would not work
4425 unset($roles[$CFG->guestroleid]);
4426 return popup_form($CFG->wwwroot.'/course/view.php?id='.$courseid.'&amp;sesskey='.sesskey().'&amp;switchrole=',
4427 $roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
4430 return '';
4435 * Returns a turn edit on/off button for course in a self contained form.
4436 * Used to be an icon, but it's now a simple form button
4438 * @uses $CFG
4439 * @uses $USER
4440 * @param int $courseid The course to update by id as found in 'course' table
4441 * @return string
4443 function update_mymoodle_icon() {
4445 global $CFG, $USER;
4447 if (!empty($USER->editing)) {
4448 $string = get_string('updatemymoodleoff');
4449 $edit = '0';
4450 } else {
4451 $string = get_string('updatemymoodleon');
4452 $edit = '1';
4455 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
4456 "<div>".
4457 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
4458 "<input type=\"submit\" value=\"$string\" /></div></form>";
4462 * Returns a turn edit on/off button for tag in a self contained form.
4464 * @uses $CFG
4465 * @uses $USER
4466 * @return string
4468 function update_tag_button($tagid) {
4470 global $CFG, $USER;
4472 if (!empty($USER->editing)) {
4473 $string = get_string('turneditingoff');
4474 $edit = '0';
4475 } else {
4476 $string = get_string('turneditingon');
4477 $edit = '1';
4480 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/tag/index.php\">".
4481 "<div>".
4482 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
4483 "<input type=\"hidden\" name=\"id\" value=\"$tagid\" />".
4484 "<input type=\"submit\" value=\"$string\" /></div></form>";
4488 * Prints the editing button on a module "view" page
4490 * @uses $CFG
4491 * @param type description
4492 * @todo Finish documenting this function
4494 function update_module_button($moduleid, $courseid, $string) {
4495 global $CFG, $USER;
4497 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $moduleid))) {
4498 $string = get_string('updatethis', '', $string);
4500 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
4501 "<div>".
4502 "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
4503 "<input type=\"hidden\" name=\"return\" value=\"true\" />".
4504 "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
4505 "<input type=\"submit\" value=\"$string\" /></div></form>";
4506 } else {
4507 return '';
4512 * Prints the editing button on a category page
4514 * @uses $CFG
4515 * @uses $USER
4516 * @param int $categoryid ?
4517 * @return string
4518 * @todo Finish documenting this function
4520 function update_category_button($categoryid) {
4521 global $CFG, $USER;
4523 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_COURSECAT, $categoryid))) {
4524 if (!empty($USER->categoryediting)) {
4525 $string = get_string('turneditingoff');
4526 $edit = 'off';
4527 } else {
4528 $string = get_string('turneditingon');
4529 $edit = 'on';
4532 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/category.php\">".
4533 '<div>'.
4534 "<input type=\"hidden\" name=\"id\" value=\"$categoryid\" />".
4535 "<input type=\"hidden\" name=\"categoryedit\" value=\"$edit\" />".
4536 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
4537 "<input type=\"submit\" value=\"$string\" /></div></form>";
4542 * Prints the editing button on categories listing
4544 * @uses $CFG
4545 * @uses $USER
4546 * @return string
4548 function update_categories_button() {
4549 global $CFG, $USER;
4551 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
4552 if (!empty($USER->categoryediting)) {
4553 $string = get_string('turneditingoff');
4554 $categoryedit = 'off';
4555 } else {
4556 $string = get_string('turneditingon');
4557 $categoryedit = 'on';
4560 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/index.php\">".
4561 '<div>'.
4562 '<input type="hidden" name="categoryedit" value="'. $categoryedit .'" />'.
4563 '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />'.
4564 '<input type="submit" value="'. $string .'" /></div></form>';
4569 * Prints the editing button on search results listing
4570 * For bulk move courses to another category
4573 function update_categories_search_button($search,$page,$perpage) {
4574 global $CFG, $USER;
4576 // not sure if this capability is the best here
4577 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
4578 if (!empty($USER->categoryediting)) {
4579 $string = get_string("turneditingoff");
4580 $edit = "off";
4581 $perpage = 30;
4582 } else {
4583 $string = get_string("turneditingon");
4584 $edit = "on";
4587 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
4588 '<div>'.
4589 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
4590 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
4591 "<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
4592 "<input type=\"hidden\" name=\"page\" value=\"$page\" />".
4593 "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
4594 "<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
4599 * Prints the editing button on group page
4601 * @uses $CFG
4602 * @uses $USER
4603 * @param int $courseid The course group is associated with
4604 * @param int $groupid The group to update
4605 * @return string
4607 function update_group_button($courseid, $groupid) {
4608 global $CFG, $USER;
4610 if (has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_GROUP, $groupid))) {
4611 $string = get_string('editgroupprofile');
4613 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/group/edit.php\">".
4614 '<div>'.
4615 '<input type="hidden" name="courseid" value="'. $courseid .'" />'.
4616 '<input type="hidden" name="id" value="'. $groupid .'" />'.
4617 '<input type="hidden" name="grouping" value="-1" />'.
4618 '<input type="hidden" name="edit" value="on" />'.
4619 '<input type="submit" value="'. $string .'" /></div></form>';
4624 * Prints the editing button on groups page
4626 * @uses $CFG
4627 * @uses $USER
4628 * @param int $courseid The id of the course to be edited
4629 * @return string
4630 * @todo Finish documenting this function
4632 function update_groups_button($courseid) {
4633 global $CFG, $USER;
4635 if (has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $courseid))) {
4636 if (!empty($USER->groupsediting)) {
4637 $string = get_string('turneditingoff');
4638 $edit = 'off';
4639 } else {
4640 $string = get_string('turneditingon');
4641 $edit = 'on';
4644 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/group/index.php\">".
4645 '<div>'.
4646 "<input type=\"hidden\" name=\"id\" value=\"$courseid\" />".
4647 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
4648 "<input type=\"submit\" value=\"$string\" /></div></form>";
4653 * Prints an appropriate group selection menu
4655 * @uses VISIBLEGROUPS
4656 * @param array $groups ?
4657 * @param int $groupmode ?
4658 * @param string $currentgroup ?
4659 * @param string $urlroot ?
4660 * @param boolean $showall: if set to 0, it is a student in separate groups, do not display all participants
4661 * @todo Finish documenting this function
4663 function print_group_menu($groups, $groupmode, $currentgroup, $urlroot, $showall=1, $return=false) {
4665 $output = '';
4666 $groupsmenu = array();
4668 /// Add an "All groups" to the start of the menu
4669 if ($showall){
4670 $groupsmenu[0] = get_string('allparticipants');
4672 foreach ($groups as $key => $group) {
4673 $groupsmenu[$key] = format_string($group->name);
4676 if ($groupmode == VISIBLEGROUPS) {
4677 $grouplabel = get_string('groupsvisible');
4678 } else {
4679 $grouplabel = get_string('groupsseparate');
4682 if (count($groupsmenu) == 1) {
4683 $groupname = reset($groupsmenu);
4684 $output .= $grouplabel.': '.$groupname;
4685 } else {
4686 $output .= popup_form($urlroot.'&amp;group=', $groupsmenu, 'selectgroup', $currentgroup, '', '', '', true, 'self', $grouplabel);
4689 if ($return) {
4690 return $output;
4691 } else {
4692 echo $output;
4698 * Given a course and a (current) coursemodule
4699 * This function returns a small popup menu with all the
4700 * course activity modules in it, as a navigation menu
4701 * The data is taken from the serialised array stored in
4702 * the course record
4704 * @param course $course A {@link $COURSE} object.
4705 * @param course $cm A {@link $COURSE} object.
4706 * @param string $targetwindow ?
4707 * @return string
4708 * @todo Finish documenting this function
4710 function navmenu($course, $cm=NULL, $targetwindow='self') {
4712 global $CFG, $THEME, $USER;
4714 if (empty($THEME->navmenuwidth)) {
4715 $width = 50;
4716 } else {
4717 $width = $THEME->navmenuwidth;
4720 if ($cm) {
4721 $cm = $cm->id;
4724 if ($course->format == 'weeks') {
4725 $strsection = get_string('week');
4726 } else {
4727 $strsection = get_string('topic');
4729 $strjumpto = get_string('jumpto');
4731 /// Casting $course->modinfo to string prevents one notice when the field is null
4732 if (!$modinfo = unserialize((string)$course->modinfo)) {
4733 return '';
4735 $context = get_context_instance(CONTEXT_COURSE, $course->id);
4737 $section = -1;
4738 $selected = '';
4739 $url = '';
4740 $previousmod = NULL;
4741 $backmod = NULL;
4742 $nextmod = NULL;
4743 $selectmod = NULL;
4744 $logslink = NULL;
4745 $flag = false;
4746 $menu = array();
4747 $menustyle = array();
4749 $sections = get_records('course_sections','course',$course->id,'section','section,visible,summary');
4751 if (!empty($THEME->makenavmenulist)) { /// A hack to produce an XHTML navmenu list for use in themes
4752 $THEME->navmenulist = navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
4755 foreach ($modinfo as $mod) {
4756 if ($mod->mod == 'label') {
4757 continue;
4760 if ($mod->section > $course->numsections) { /// Don't show excess hidden sections
4761 break;
4764 if ($mod->section > 0 and $section <> $mod->section) {
4765 $thissection = $sections[$mod->section];
4767 if ($thissection->visible or !$course->hiddensections or
4768 has_capability('moodle/course:viewhiddensections', $context)) {
4769 $thissection->summary = strip_tags(format_string($thissection->summary,true));
4770 if ($course->format == 'weeks' or empty($thissection->summary)) {
4771 $menu[] = '--'.$strsection ." ". $mod->section;
4772 } else {
4773 if (strlen($thissection->summary) < ($width-3)) {
4774 $menu[] = '--'.$thissection->summary;
4775 } else {
4776 $menu[] = '--'.substr($thissection->summary, 0, $width).'...';
4782 $section = $mod->section;
4784 //Only add visible or teacher mods to jumpmenu
4785 if ($mod->visible or has_capability('moodle/course:viewhiddenactivities',
4786 get_context_instance(CONTEXT_MODULE, $mod->cm))) {
4787 $url = $mod->mod .'/view.php?id='. $mod->cm;
4788 if ($flag) { // the current mod is the "next" mod
4789 $nextmod = $mod;
4790 $flag = false;
4792 if ($cm == $mod->cm) {
4793 $selected = $url;
4794 $selectmod = $mod;
4795 $backmod = $previousmod;
4796 $flag = true; // set flag so we know to use next mod for "next"
4797 $mod->name = $strjumpto;
4798 $strjumpto = '';
4799 } else {
4800 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
4801 if (strlen($mod->name) > ($width+5)) {
4802 $mod->name = substr($mod->name, 0, $width).'...';
4804 if (!$mod->visible) {
4805 $mod->name = '('.$mod->name.')';
4808 $menu[$url] = $mod->name;
4809 if (empty($THEME->navmenuiconshide)) {
4810 $menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath.'/'.$mod->mod.'/icon.gif);"'; // Unfortunately necessary to do this here
4812 $previousmod = $mod;
4815 //Accessibility: added Alt text, replaced &gt; &lt; with 'silent' character and 'accesshide' text.
4817 if ($selectmod and has_capability('moodle/site:viewreports', $context)) {
4818 $logstext = get_string('alllogs');
4819 $logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
4820 $CFG->frametarget.'onclick="this.target=\''.$CFG->framename.'\';"'.' href="'.
4821 $CFG->wwwroot.'/course/report/log/index.php?chooselog=1&amp;user=0&amp;date=0&amp;id='.
4822 $course->id.'&amp;modid='.$selectmod->cm.'">'.
4823 '<img class="icon log" src="'.$CFG->pixpath.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
4826 if ($backmod) {
4827 $backtext= get_string('activityprev', 'access');
4828 $backmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$backmod->mod.'/view.php" '.
4829 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
4830 '<input type="hidden" name="id" value="'.$backmod->cm.'" />'.
4831 '<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
4832 '</button></fieldset></form></li>';
4834 if ($nextmod) {
4835 $nexttext= get_string('activitynext', 'access');
4836 $nextmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$nextmod->mod.'/view.php" '.
4837 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
4838 '<input type="hidden" name="id" value="'.$nextmod->cm.'" />'.
4839 '<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
4840 '</button></fieldset></form></li>';
4843 return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
4844 '<li>'.popup_form($CFG->wwwroot .'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
4845 '', '', true, $targetwindow, '', $menustyle).'</li>'.
4846 $nextmod . '</ul>'."\n".'</div>';
4850 * Given a course
4851 * This function returns a small popup menu with all the
4852 * course activity modules in it, as a navigation menu
4853 * outputs a simple list structure in XHTML
4854 * The data is taken from the serialised array stored in
4855 * the course record
4857 * @param course $course A {@link $COURSE} object.
4858 * @return string
4859 * @todo Finish documenting this function
4861 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
4863 global $CFG;
4865 $section = -1;
4866 $selected = '';
4867 $url = '';
4868 $previousmod = NULL;
4869 $backmod = NULL;
4870 $nextmod = NULL;
4871 $selectmod = NULL;
4872 $logslink = NULL;
4873 $flag = false;
4874 $menu = array();
4876 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
4878 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
4879 foreach ($modinfo as $mod) {
4880 if ($mod->mod == 'label') {
4881 continue;
4884 if ($mod->section > $course->numsections) { /// Don't show excess hidden sections
4885 break;
4888 if ($mod->section >= 0 and $section <> $mod->section) {
4889 $thissection = $sections[$mod->section];
4891 if ($thissection->visible or !$course->hiddensections or
4892 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
4893 $thissection->summary = strip_tags(format_string($thissection->summary,true));
4894 if (!empty($doneheading)) {
4895 $menu[] = '</ul></li>';
4897 if ($course->format == 'weeks' or empty($thissection->summary)) {
4898 $item = $strsection ." ". $mod->section;
4899 } else {
4900 if (strlen($thissection->summary) < ($width-3)) {
4901 $item = $thissection->summary;
4902 } else {
4903 $item = substr($thissection->summary, 0, $width).'...';
4906 $menu[] = '<li class="section"><span>'.$item.'</span>';
4907 $menu[] = '<ul>';
4908 $doneheading = true;
4912 $section = $mod->section;
4914 //Only add visible or teacher mods to jumpmenu
4915 if ($mod->visible or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_MODULE, $mod->id))) {
4916 $url = $mod->mod .'/view.php?id='. $mod->cm;
4917 if ($flag) { // the current mod is the "next" mod
4918 $nextmod = $mod;
4919 $flag = false;
4921 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
4922 if (strlen($mod->name) > ($width+5)) {
4923 $mod->name = substr($mod->name, 0, $width).'...';
4925 if (!$mod->visible) {
4926 $mod->name = '('.$mod->name.')';
4928 $class = 'activity '.$mod->mod;
4929 $class .= ($cmid == $mod->cm) ? ' selected' : '';
4930 $menu[] = '<li class="'.$class.'">'.
4931 '<img src="'.$CFG->modpixpath.'/'.$mod->mod.'/icon.gif" alt="" />'.
4932 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
4933 $previousmod = $mod;
4936 if ($doneheading) {
4937 $menu[] = '</ul></li>';
4939 $menu[] = '</ul></li></ul>';
4941 return implode("\n", $menu);
4945 * Prints form items with the names $day, $month and $year
4947 * @param string $day fieldname
4948 * @param string $month fieldname
4949 * @param string $year fieldname
4950 * @param int $currenttime A default timestamp in GMT
4951 * @param boolean $return
4953 function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
4955 if (!$currenttime) {
4956 $currenttime = time();
4958 $currentdate = usergetdate($currenttime);
4960 for ($i=1; $i<=31; $i++) {
4961 $days[$i] = $i;
4963 for ($i=1; $i<=12; $i++) {
4964 $months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
4966 for ($i=1970; $i<=2020; $i++) {
4967 $years[$i] = $i;
4969 return choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', $return)
4970 .choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', $return)
4971 .choose_from_menu($years, $year, $currentdate['year'], '', '', '0', $return);
4976 *Prints form items with the names $hour and $minute
4978 * @param string $hour fieldname
4979 * @param string ? $minute fieldname
4980 * @param $currenttime A default timestamp in GMT
4981 * @param int $step minute spacing
4982 * @param boolean $return
4984 function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
4986 if (!$currenttime) {
4987 $currenttime = time();
4989 $currentdate = usergetdate($currenttime);
4990 if ($step != 1) {
4991 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
4993 for ($i=0; $i<=23; $i++) {
4994 $hours[$i] = sprintf("%02d",$i);
4996 for ($i=0; $i<=59; $i+=$step) {
4997 $minutes[$i] = sprintf("%02d",$i);
5000 return choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',$return)
5001 .choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',$return);
5005 * Prints time limit value selector
5007 * @uses $CFG
5008 * @param int $timelimit default
5009 * @param string $unit
5010 * @param string $name
5011 * @param boolean $return
5013 function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
5015 global $CFG;
5017 if ($unit) {
5018 $unit = ' '.$unit;
5021 // Max timelimit is sessiontimeout - 10 minutes.
5022 $maxvalue = ($CFG->sessiontimeout / 60) - 10;
5024 for ($i=1; $i<=$maxvalue; $i++) {
5025 $minutes[$i] = $i.$unit;
5027 return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
5031 * Prints a grade menu (as part of an existing form) with help
5032 * Showing all possible numerical grades and scales
5034 * @uses $CFG
5035 * @param int $courseid ?
5036 * @param string $name ?
5037 * @param string $current ?
5038 * @param boolean $includenograde ?
5039 * @todo Finish documenting this function
5041 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
5043 global $CFG;
5045 $output = '';
5046 $strscale = get_string('scale');
5047 $strscales = get_string('scales');
5049 $scales = get_scales_menu($courseid);
5050 foreach ($scales as $i => $scalename) {
5051 $grades[-$i] = $strscale .': '. $scalename;
5053 if ($includenograde) {
5054 $grades[0] = get_string('nograde');
5056 for ($i=100; $i>=1; $i--) {
5057 $grades[$i] = $i;
5059 $output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
5061 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5062 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5063 $linkobject, 400, 500, $strscales, 'none', true);
5065 if ($return) {
5066 return $output;
5067 } else {
5068 echo $output;
5073 * Prints a scale menu (as part of an existing form) including help button
5074 * Just like {@link print_grade_menu()} but without the numeric grades
5076 * @param int $courseid ?
5077 * @param string $name ?
5078 * @param string $current ?
5079 * @todo Finish documenting this function
5081 function print_scale_menu($courseid, $name, $current, $return=false) {
5083 global $CFG;
5085 $output = '';
5086 $strscales = get_string('scales');
5087 $output .= choose_from_menu(get_scales_menu($courseid), $name, $current, '', '', 0, true);
5089 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5090 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5091 $linkobject, 400, 500, $strscales, 'none', true);
5092 if ($return) {
5093 return $output;
5094 } else {
5095 echo $output;
5100 * Prints a help button about a scale
5102 * @uses $CFG
5103 * @param id $courseid ?
5104 * @param object $scale ?
5105 * @todo Finish documenting this function
5107 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
5109 global $CFG;
5111 $output = '';
5112 $strscales = get_string('scales');
5114 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5115 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true&amp;scaleid='. $scale->id, 'ratingscale',
5116 $linkobject, 400, 500, $scale->name, 'none', true);
5117 if ($return) {
5118 return $output;
5119 } else {
5120 echo $output;
5125 * Print an error page displaying an error message.
5126 * Old method, don't call directly in new code - use print_error instead.
5129 * @uses $SESSION
5130 * @uses $CFG
5131 * @param string $message The message to display to the user about the error.
5132 * @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.
5134 function error ($message, $link='') {
5136 global $CFG, $SESSION;
5137 $message = clean_text($message); // In case nasties are in here
5139 if (defined('FULLME') && FULLME == 'cron') {
5140 // Errors in cron should be mtrace'd.
5141 mtrace($message);
5142 die;
5145 if (! defined('HEADER_PRINTED')) {
5146 //header not yet printed
5147 @header('HTTP/1.0 404 Not Found');
5148 print_header(get_string('error'));
5151 echo '<br />';
5152 print_simple_box($message, '', '', '', '', 'errorbox');
5154 debugging('Stack trace:', DEBUG_DEVELOPER);
5156 // in case we are logging upgrade in admin/index.php stop it
5157 if (function_exists('upgrade_log_finish')) {
5158 upgrade_log_finish();
5161 if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
5162 if ( !empty($SESSION->fromurl) ) {
5163 $link = $SESSION->fromurl;
5164 unset($SESSION->fromurl);
5165 } else {
5166 $link = $CFG->wwwroot .'/';
5170 if (!empty($link)) {
5171 print_continue($link);
5174 print_footer();
5176 for ($i=0;$i<512;$i++) { // Padding to help IE work with 404
5177 echo ' ';
5180 die;
5184 * Print an error page displaying an error message. New method - use this for new code.
5186 * @uses $SESSION
5187 * @uses $CFG
5188 * @param string $errorcode The name of the string from error.php to print
5189 * @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.
5190 * @param object $a Extra words and phrases that might be required in the error string
5192 function print_error ($errorcode, $module='', $link='', $a=NULL) {
5194 global $CFG;
5196 if (empty($module) || $module == 'moodle' || $module == 'core') {
5197 $module = 'error';
5198 $modulelink = 'moodle';
5199 } else {
5200 $modulelink = $module;
5203 if (!empty($CFG->errordocroot)) {
5204 $errordocroot = $CFG->errordocroot;
5205 } else if (!empty($CFG->docroot)) {
5206 $errordocroot = $CFG->docroot;
5207 } else {
5208 $errordocroot = 'http://docs.moodle.org';
5211 $message = '<p class="errormessage">'.get_string($errorcode, $module, $a).'</p>'.
5212 '<p class="errorcode">'.
5213 '<a href="'.$errordocroot.'/en/error/'.$modulelink.'/'.$errorcode.'">'.
5214 get_string('moreinformation').'</a></p>';
5215 error($message, $link);
5218 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
5219 * Should be used only with htmleditor or textarea.
5220 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
5221 * helpbutton.
5222 * @return string
5224 function editorhelpbutton(){
5225 global $CFG, $SESSION;
5226 $items = func_get_args();
5227 $i = 1;
5228 $urlparams = array();
5229 $titles = array();
5230 foreach ($items as $item){
5231 if (is_array($item)){
5232 $urlparams[] = "keyword$i=".urlencode($item[0]);
5233 $urlparams[] = "title$i=".urlencode($item[1]);
5234 if (isset($item[2])){
5235 $urlparams[] = "module$i=".urlencode($item[2]);
5237 $titles[] = trim($item[1], ". \t");
5238 }elseif (is_string($item)){
5239 $urlparams[] = "button$i=".urlencode($item);
5240 switch ($item){
5241 case 'reading' :
5242 $titles[] = get_string("helpreading");
5243 break;
5244 case 'writing' :
5245 $titles[] = get_string("helpwriting");
5246 break;
5247 case 'questions' :
5248 $titles[] = get_string("helpquestions");
5249 break;
5250 case 'emoticons' :
5251 $titles[] = get_string("helpemoticons");
5252 break;
5253 case 'richtext' :
5254 $titles[] = get_string('helprichtext');
5255 break;
5256 case 'text' :
5257 $titles[] = get_string('helptext');
5258 break;
5259 default :
5260 error('Unknown help topic '.$item);
5263 $i++;
5265 if (count($titles)>1){
5266 //join last two items with an 'and'
5267 $a = new object();
5268 $a->one = $titles[count($titles) - 2];
5269 $a->two = $titles[count($titles) - 1];
5270 $titles[count($titles) - 2] = get_string('and', '', $a);
5271 unset($titles[count($titles) - 1]);
5273 $alttag = join (', ', $titles);
5275 $paramstring = join('&', $urlparams);
5276 $linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath .'/help.gif" />';
5277 return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), $alttag, $linkobject, 400, 500, $alttag, 'none', true);
5281 * Print a help button.
5283 * @uses $CFG
5284 * @param string $page The keyword that defines a help page
5285 * @param string $title The title of links, rollover tips, alt tags etc
5286 * 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
5287 * @param string $module Which module is the page defined in
5288 * @param mixed $image Use a help image for the link? (true/false/"both")
5289 * @param boolean $linktext If true, display the title next to the help icon.
5290 * @param string $text If defined then this text is used in the page, and
5291 * the $page variable is ignored.
5292 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
5293 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
5294 * @return string
5295 * @todo Finish documenting this function
5297 function helpbutton ($page, $title='', $module='moodle', $image=true, $linktext=false, $text='', $return=false,
5298 $imagetext='') {
5299 global $CFG, $course;
5301 // fix for MDL-7734
5302 if (!empty($course->lang)) {
5303 $forcelang = $course->lang;
5304 } else {
5305 $forcelang = '';
5308 if ($module == '') {
5309 $module = 'moodle';
5312 $tooltip = get_string('helpprefix2', '', trim($title, ". \t"));
5314 $linkobject = '';
5316 if ($image) {
5317 if ($linktext) {
5318 // MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
5319 $linkobject .= $title.'&nbsp;';
5320 $tooltip = get_string('helpwiththis');
5322 if ($imagetext) {
5323 $linkobject .= $imagetext;
5324 } else {
5325 $linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
5326 $CFG->pixpath .'/help.gif" />';
5328 } else {
5329 $linkobject .= $tooltip;
5332 $tooltip .= ' ('.get_string('newwindow').')'; // Warn users about new window for Accessibility
5334 // fix for MDL-7734
5335 if ($text) {
5336 $url = '/help.php?module='. $module .'&amp;text='. s(urlencode($text).'&amp;forcelang='.$forcelang);
5337 } else {
5338 $url = '/help.php?module='. $module .'&amp;file='. $page .'.html&amp;forcelang='.$forcelang;
5341 $link = '<span class="helplink">'.
5342 link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
5343 '</span>';
5345 if ($return) {
5346 return $link;
5347 } else {
5348 echo $link;
5353 * Print a help button.
5355 * Prints a special help button that is a link to the "live" emoticon popup
5356 * @uses $CFG
5357 * @uses $SESSION
5358 * @param string $form ?
5359 * @param string $field ?
5360 * @todo Finish documenting this function
5362 function emoticonhelpbutton($form, $field, $return = false) {
5364 global $CFG, $SESSION;
5366 $SESSION->inserttextform = $form;
5367 $SESSION->inserttextfield = $field;
5368 $imagetext = '<img src="' . $CFG->pixpath . '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
5369 $help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
5370 if (!$return){
5371 echo $help;
5372 } else {
5373 return $help;
5378 * Print a help button.
5380 * Prints a special help button for html editors (htmlarea in this case)
5381 * @uses $CFG
5383 function editorshortcutshelpbutton() {
5385 global $CFG;
5386 $imagetext = '<img src="' . $CFG->httpswwwroot . '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
5387 get_string('editorshortcutkeys').'" class="iconkbhelp" />';
5389 return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
5393 * Print a message and exit.
5395 * @uses $CFG
5396 * @param string $message ?
5397 * @param string $link ?
5398 * @todo Finish documenting this function
5400 function notice ($message, $link='', $course=NULL) {
5401 global $CFG, $SITE;
5403 $message = clean_text($message);
5405 print_box($message, 'generalbox', 'notice');
5406 print_continue($link);
5408 if (empty($course)) {
5409 print_footer($SITE);
5410 } else {
5411 print_footer($course);
5413 exit;
5417 * Print a message along with "Yes" and "No" links for the user to continue.
5419 * @param string $message The text to display
5420 * @param string $linkyes The link to take the user to if they choose "Yes"
5421 * @param string $linkno The link to take the user to if they choose "No"
5422 * TODO Document remaining arguments
5424 function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
5426 global $CFG;
5428 $message = clean_text($message);
5429 $linkyes = clean_text($linkyes);
5430 $linkno = clean_text($linkno);
5432 print_box_start('generalbox', 'notice');
5433 echo '<p>'. $message .'</p>';
5434 echo '<div class="buttons">';
5435 print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename);
5436 print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename);
5437 echo '</div>';
5438 print_box_end();
5442 * Provide an definition of error_get_last for PHP before 5.2.0. This simply
5443 * returns NULL, since there is not way to get the right answer.
5445 if (!function_exists('error_get_last')) {
5446 // the eval is needed to prevent PHP 5.2+ from getting a parse error!
5447 eval('
5448 function error_get_last() {
5449 return NULL;
5455 * Redirects the user to another page, after printing a notice
5457 * @param string $url The url to take the user to
5458 * @param string $message The text message to display to the user about the redirect, if any
5459 * @param string $delay How long before refreshing to the new page at $url?
5460 * @todo '&' needs to be encoded into '&amp;' for XHTML compliance,
5461 * however, this is not true for javascript. Therefore we
5462 * first decode all entities in $url (since we cannot rely on)
5463 * the correct input) and then encode for where it's needed
5464 * echo "<script type='text/javascript'>alert('Redirect $url');</script>";
5466 function redirect($url, $message='', $delay=-1) {
5468 global $CFG;
5470 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
5471 $url = sid_process_url($url);
5474 $message = clean_text($message);
5476 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
5477 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
5478 $url = str_replace('&amp;', '&', $encodedurl);
5480 /// At developer debug level. Don't redirect if errors have been printed on screen.
5481 /// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
5482 $lasterror = error_get_last();
5483 $error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER));
5484 $errorprinted = debugging('', DEBUG_ALL) && $CFG->debugdisplay && $error;
5485 if ($errorprinted) {
5486 $message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
5489 /// when no message and header printed yet, try to redirect
5490 if (empty($message) and !defined('HEADER_PRINTED')) {
5492 // Technically, HTTP/1.1 requires Location: header to contain
5493 // the absolute path. (In practice browsers accept relative
5494 // paths - but still, might as well do it properly.)
5495 // This code turns relative into absolute.
5496 if (!preg_match('|^[a-z]+:|', $url)) {
5497 // Get host name http://www.wherever.com
5498 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
5499 if (preg_match('|^/|', $url)) {
5500 // URLs beginning with / are relative to web server root so we just add them in
5501 $url = $hostpart.$url;
5502 } else {
5503 // URLs not beginning with / are relative to path of current script, so add that on.
5504 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
5506 // Replace all ..s
5507 while (true) {
5508 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
5509 if ($newurl == $url) {
5510 break;
5512 $url = $newurl;
5516 $delay = 0;
5517 //try header redirection first
5518 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
5519 @header('Location: '.$url);
5520 //another way for older browsers and already sent headers (eg trailing whitespace in config.php)
5521 echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
5522 echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
5523 die;
5526 if ($delay == -1) {
5527 $delay = 3; // if no delay specified wait 3 seconds
5529 if (! defined('HEADER_PRINTED')) {
5530 // this type of redirect might not be working in some browsers - such as lynx :-(
5531 print_header('', '', '', '', $errorprinted ? '' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
5532 $delay += 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
5534 echo '<div style="text-align:center">';
5535 echo '<div>'. $message .'</div>';
5536 echo '<div>( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
5537 echo '</div>';
5539 if (!$errorprinted) {
5541 <script type="text/javascript">
5542 //<![CDATA[
5544 function redirect() {
5545 document.location.replace('<?php echo addslashes_js($url) ?>');
5547 setTimeout("redirect()", <?php echo ($delay * 1000) ?>);
5548 //]]>
5549 </script>
5550 <?php
5553 print_footer('none');
5554 die;
5558 * Print a bold message in an optional color.
5560 * @param string $message The message to print out
5561 * @param string $style Optional style to display message text in
5562 * @param string $align Alignment option
5563 * @param bool $return whether to return an output string or echo now
5565 function notify($message, $style='notifyproblem', $align='center', $return=false) {
5566 if ($style == 'green') {
5567 $style = 'notifysuccess'; // backward compatible with old color system
5570 $message = clean_text($message);
5572 $output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."<br />\n";
5574 if ($return) {
5575 return $output;
5577 echo $output;
5582 * Given an email address, this function will return an obfuscated version of it
5584 * @param string $email The email address to obfuscate
5585 * @return string
5587 function obfuscate_email($email) {
5589 $i = 0;
5590 $length = strlen($email);
5591 $obfuscated = '';
5592 while ($i < $length) {
5593 if (rand(0,2)) {
5594 $obfuscated.='%'.dechex(ord($email{$i}));
5595 } else {
5596 $obfuscated.=$email{$i};
5598 $i++;
5600 return $obfuscated;
5604 * This function takes some text and replaces about half of the characters
5605 * with HTML entity equivalents. Return string is obviously longer.
5607 * @param string $plaintext The text to be obfuscated
5608 * @return string
5610 function obfuscate_text($plaintext) {
5612 $i=0;
5613 $length = strlen($plaintext);
5614 $obfuscated='';
5615 $prev_obfuscated = false;
5616 while ($i < $length) {
5617 $c = ord($plaintext{$i});
5618 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
5619 if ($prev_obfuscated and $numerical ) {
5620 $obfuscated.='&#'.ord($plaintext{$i}).';';
5621 } else if (rand(0,2)) {
5622 $obfuscated.='&#'.ord($plaintext{$i}).';';
5623 $prev_obfuscated = true;
5624 } else {
5625 $obfuscated.=$plaintext{$i};
5626 $prev_obfuscated = false;
5628 $i++;
5630 return $obfuscated;
5634 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
5635 * to generate a fully obfuscated email link, ready to use.
5637 * @param string $email The email address to display
5638 * @param string $label The text to dispalyed as hyperlink to $email
5639 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
5640 * @return string
5642 function obfuscate_mailto($email, $label='', $dimmed=false) {
5644 if (empty($label)) {
5645 $label = $email;
5647 if ($dimmed) {
5648 $title = get_string('emaildisable');
5649 $dimmed = ' class="dimmed"';
5650 } else {
5651 $title = '';
5652 $dimmed = '';
5654 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
5655 obfuscate_text('mailto'), obfuscate_email($email),
5656 obfuscate_text($label));
5660 * Prints a single paging bar to provide access to other pages (usually in a search)
5662 * @param int $totalcount Thetotal number of entries available to be paged through
5663 * @param int $page The page you are currently viewing
5664 * @param int $perpage The number of entries that should be shown per page
5665 * @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.
5666 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
5667 * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
5668 * @param bool $nocurr do not display the current page as a link
5669 * @param bool $return whether to return an output string or echo now
5670 * @return bool or string
5672 function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
5673 $maxdisplay = 18;
5674 $output = '';
5676 if ($totalcount > $perpage) {
5677 $output .= '<div class="paging">';
5678 $output .= get_string('page') .':';
5679 if ($page > 0) {
5680 $pagenum = $page - 1;
5681 if (!is_a($baseurl, 'moodle_url')){
5682 $output .= '&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>)&nbsp;';
5683 } else {
5684 $output .= '&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>)&nbsp;';
5687 $lastpage = ceil($totalcount / $perpage);
5688 if ($page > 15) {
5689 $startpage = $page - 10;
5690 if (!is_a($baseurl, 'moodle_url')){
5691 $output .= '&nbsp;<a href="'. $baseurl . $pagevar .'=0">1</a>&nbsp;...';
5692 } else {
5693 $output .= '&nbsp;<a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a>&nbsp;...';
5695 } else {
5696 $startpage = 0;
5698 $currpage = $startpage;
5699 $displaycount = 0;
5700 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
5701 $displaypage = $currpage+1;
5702 if ($page == $currpage && empty($nocurr)) {
5703 $output .= '&nbsp;&nbsp;'. $displaypage;
5704 } else {
5705 if (!is_a($baseurl, 'moodle_url')){
5706 $output .= '&nbsp;&nbsp;<a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
5707 } else {
5708 $output .= '&nbsp;&nbsp;<a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
5712 $displaycount++;
5713 $currpage++;
5715 if ($currpage < $lastpage) {
5716 $lastpageactual = $lastpage - 1;
5717 if (!is_a($baseurl, 'moodle_url')){
5718 $output .= '&nbsp;...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a>&nbsp;';
5719 } else {
5720 $output .= '&nbsp;...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a>&nbsp;';
5723 $pagenum = $page + 1;
5724 if ($pagenum != $displaypage) {
5725 if (!is_a($baseurl, 'moodle_url')){
5726 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
5727 } else {
5728 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
5731 $output .= '</div>';
5734 if ($return) {
5735 return $output;
5738 echo $output;
5739 return true;
5743 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
5744 * will transform it to html entities
5746 * @param string $text Text to search for nolink tag in
5747 * @return string
5749 function rebuildnolinktag($text) {
5751 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
5753 return $text;
5757 * Prints a nice side block with an optional header. The content can either
5758 * be a block of HTML or a list of text with optional icons.
5760 * @param string $heading Block $title embedded in HTML tags, for example <h2>.
5761 * @param string $content ?
5762 * @param array $list ?
5763 * @param array $icons ?
5764 * @param string $footer ?
5765 * @param array $attributes ?
5766 * @param string $title Plain text title, as embedded in the $heading.
5767 * @todo Finish documenting this function. Show example of various attributes, etc.
5769 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
5771 //Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
5772 static $block_id = 0;
5773 $block_id++;
5774 if (empty($heading)) {
5775 $skip_text = get_string('skipblock', 'access').' '.$block_id;
5777 else {
5778 $skip_text = get_string('skipa', 'access', strip_tags($title));
5780 $skip_link = '<a href="#sb-'.$block_id.'" class="skip-block" title="'.$skip_text.'">'."\n".'<span class="accesshide">'.$skip_text.'</span>'."\n".'</a>';
5781 $skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
5783 if (! empty($heading)) {
5784 $heading = $skip_link . $heading;
5786 /*else { //ELSE: I think a single link on a page, "Skip block 4" is too confusing - don't print.
5787 echo $skip_link;
5790 print_side_block_start($heading, $attributes);
5792 if ($content) {
5793 echo $content;
5794 if ($footer) {
5795 echo '<div class="footer">'. $footer .'</div>';
5797 } else {
5798 if ($list) {
5799 $row = 0;
5800 //Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
5801 echo "\n<ul class='list'>\n";
5802 foreach ($list as $key => $string) {
5803 echo '<li class="r'. $row .'">';
5804 if ($icons) {
5805 echo '<div class="icon column c0">'. $icons[$key] .'</div>';
5807 echo '<div class="column c1">'. $string .'</div>';
5808 echo "</li>\n";
5809 $row = $row ? 0:1;
5811 echo "</ul>\n";
5813 if ($footer) {
5814 echo '<div class="footer">'. $footer .'</div>';
5819 print_side_block_end($attributes);
5820 echo $skip_dest;
5824 * Starts a nice side block with an optional header.
5826 * @param string $heading ?
5827 * @param array $attributes ?
5828 * @todo Finish documenting this function
5830 function print_side_block_start($heading='', $attributes = array()) {
5832 global $CFG, $THEME;
5834 if (!empty($THEME->customcorners)) {
5835 require_once($CFG->dirroot.'/lib/custom_corners_lib.php');
5838 // If there are no special attributes, give a default CSS class
5839 if (empty($attributes) || !is_array($attributes)) {
5840 $attributes = array('class' => 'sideblock');
5842 } else if(!isset($attributes['class'])) {
5843 $attributes['class'] = 'sideblock';
5845 } else if(!strpos($attributes['class'], 'sideblock')) {
5846 $attributes['class'] .= ' sideblock';
5849 // OK, the class is surely there and in addition to anything
5850 // else, it's tagged as a sideblock
5854 // IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
5856 // If there is a cookie to hide this thing, start it hidden
5857 if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
5858 $attributes['class'] = 'hidden '.$attributes['class'];
5862 $attrtext = '';
5863 foreach ($attributes as $attr => $val) {
5864 $attrtext .= ' '.$attr.'="'.$val.'"';
5867 echo '<div '.$attrtext.'>';
5869 if (!empty($THEME->customcorners)) {
5870 echo '<div class="wrap">'."\n";
5872 if ($heading) {
5873 //Accessibility: replaced <div> with H2; no, H2 more appropriate in moodleblock.class.php: _title_html.
5874 // echo '<div class="header">'.$heading.'</div>';
5875 echo '<div class="header">';
5876 if (!empty($THEME->customcorners)) {
5877 echo '<div class="bt"><div>&nbsp;</div></div>';
5878 echo '<div class="i1"><div class="i2">';
5879 echo '<div class="i3">';
5881 echo $heading;
5882 if (!empty($THEME->customcorners)) {
5883 echo '</div></div></div>';
5885 echo '</div>';
5886 } else {
5887 if (!empty($THEME->customcorners)) {
5888 echo '<div class="bt"><div>&nbsp;</div></div>';
5892 if (!empty($THEME->customcorners)) {
5893 echo '<div class="i1"><div class="i2">';
5894 echo '<div class="i3">';
5896 echo '<div class="content">';
5902 * Print table ending tags for a side block box.
5904 function print_side_block_end($attributes = array()) {
5905 global $CFG, $THEME;
5907 echo '</div>';
5909 if (!empty($THEME->customcorners)) {
5910 require_once($CFG->dirroot.'/lib/custom_corners_lib.php');
5911 print_custom_corners_end();
5914 echo '</div>';
5916 // IE workaround: if I do it THIS way, it works! WTF?
5917 if (!empty($CFG->allowuserblockhiding) && isset($attributes['id'])) {
5918 echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].'"); '.
5919 "\n//]]>\n".'</script>';
5926 * Prints out code needed for spellchecking.
5927 * Original idea by Ludo (Marc Alier).
5929 * Opening CDATA and <script> are output by weblib::use_html_editor()
5930 * @uses $CFG
5931 * @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
5932 * @param boolean $return If false, echos the code instead of returning it
5933 * @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
5935 function print_speller_code ($usehtmleditor=false, $return=false) {
5936 global $CFG;
5937 $str = '';
5939 if(!$usehtmleditor) {
5940 $str .= 'function openSpellChecker() {'."\n";
5941 $str .= "\tvar speller = new spellChecker();\n";
5942 $str .= "\tspeller.popUpUrl = \"" . $CFG->wwwroot ."/lib/speller/spellchecker.html\";\n";
5943 $str .= "\tspeller.spellCheckScript = \"". $CFG->wwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
5944 $str .= "\tspeller.spellCheckAll();\n";
5945 $str .= '}'."\n";
5946 } else {
5947 $str .= "function spellClickHandler(editor, buttonId) {\n";
5948 $str .= "\teditor._textArea.value = editor.getHTML();\n";
5949 $str .= "\tvar speller = new spellChecker( editor._textArea );\n";
5950 $str .= "\tspeller.popUpUrl = \"" . $CFG->wwwroot ."/lib/speller/spellchecker.html\";\n";
5951 $str .= "\tspeller.spellCheckScript = \"". $CFG->wwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
5952 $str .= "\tspeller._moogle_edit=1;\n";
5953 $str .= "\tspeller._editor=editor;\n";
5954 $str .= "\tspeller.openChecker();\n";
5955 $str .= '}'."\n";
5958 if ($return) {
5959 return $str;
5961 echo $str;
5965 * Print button for spellchecking when editor is disabled
5967 function print_speller_button () {
5968 echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
5972 function page_id_and_class(&$getid, &$getclass) {
5973 // Create class and id for this page
5974 global $CFG, $ME;
5976 static $class = NULL;
5977 static $id = NULL;
5979 if (empty($CFG->pagepath)) {
5980 $CFG->pagepath = $ME;
5983 if (empty($class) || empty($id)) {
5984 $path = str_replace($CFG->httpswwwroot.'/', '', $CFG->pagepath); //Because the page could be HTTPSPAGEREQUIRED
5985 $path = str_replace('.php', '', $path);
5986 if (substr($path, -1) == '/') {
5987 $path .= 'index';
5989 if (empty($path) || $path == 'index') {
5990 $id = 'site-index';
5991 $class = 'course';
5992 } else if (substr($path, 0, 5) == 'admin') {
5993 $id = str_replace('/', '-', $path);
5994 $class = 'admin';
5995 } else {
5996 $id = str_replace('/', '-', $path);
5997 $class = explode('-', $id);
5998 array_pop($class);
5999 $class = implode('-', $class);
6003 $getid = $id;
6004 $getclass = $class;
6008 * Prints a maintenance message from /maintenance.html
6010 function print_maintenance_message () {
6011 global $CFG, $SITE;
6013 print_header(strip_tags($SITE->fullname), $SITE->fullname, 'home');
6014 print_simple_box_start('center');
6015 print_heading(get_string('sitemaintenance', 'admin'));
6016 @include($CFG->dataroot.'/1/maintenance.html');
6017 print_simple_box_end();
6018 print_footer();
6022 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
6024 function adjust_allowed_tags() {
6026 global $CFG, $ALLOWED_TAGS;
6028 if (!empty($CFG->allowobjectembed)) {
6029 $ALLOWED_TAGS .= '<embed><object>';
6033 /// Some code to print tabs
6035 /// A class for tabs
6036 class tabobject {
6037 var $id;
6038 var $link;
6039 var $text;
6040 var $linkedwhenselected;
6042 /// A constructor just because I like constructors
6043 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
6044 $this->id = $id;
6045 $this->link = $link;
6046 $this->text = $text;
6047 $this->title = $title ? $title : $text;
6048 $this->linkedwhenselected = $linkedwhenselected;
6055 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
6057 * @param array $tabrows An array of rows where each row is an array of tab objects
6058 * @param string $selected The id of the selected tab (whatever row it's on)
6059 * @param array $inactive An array of ids of inactive tabs that are not selectable.
6060 * @param array $activated An array of ids of other tabs that are currently activated
6062 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
6063 global $CFG;
6065 /// $inactive must be an array
6066 if (!is_array($inactive)) {
6067 $inactive = array();
6070 /// $activated must be an array
6071 if (!is_array($activated)) {
6072 $activated = array();
6075 /// Convert the tab rows into a tree that's easier to process
6076 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
6077 return false;
6080 /// Print out the current tree of tabs (this function is recursive)
6082 $output = convert_tree_to_html($tree);
6084 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
6086 /// We're done!
6088 if ($return) {
6089 return $output;
6091 echo $output;
6095 function convert_tree_to_html($tree, $row=0) {
6097 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
6099 $first = true;
6100 $count = count($tree);
6102 foreach ($tree as $tab) {
6103 $count--; // countdown to zero
6105 $liclass = '';
6107 if ($first && ($count == 0)) { // Just one in the row
6108 $liclass = 'first last';
6109 $first = false;
6110 } else if ($first) {
6111 $liclass = 'first';
6112 $first = false;
6113 } else if ($count == 0) {
6114 $liclass = 'last';
6117 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
6118 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
6121 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
6122 if ($tab->selected) {
6123 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
6124 } else if ($tab->active) {
6125 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
6129 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
6131 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
6132 $str .= '<a href="#" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
6133 } else {
6134 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
6137 if (!empty($tab->subtree)) {
6138 $str .= convert_tree_to_html($tab->subtree, $row+1);
6139 } else if ($tab->selected) {
6140 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
6143 $str .= ' </li>'."\n";
6145 $str .= '</ul>'."\n";
6147 return $str;
6151 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
6153 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
6155 $tabrows = array_reverse($tabrows);
6157 $subtree = array();
6159 foreach ($tabrows as $row) {
6160 $tree = array();
6162 foreach ($row as $tab) {
6163 $tab->inactive = in_array((string)$tab->id, $inactive);
6164 $tab->active = in_array((string)$tab->id, $activated);
6165 $tab->selected = (string)$tab->id == $selected;
6167 if ($tab->active || $tab->selected) {
6168 if ($subtree) {
6169 $tab->subtree = $subtree;
6172 $tree[] = $tab;
6174 $subtree = $tree;
6177 return $subtree;
6182 * Returns a string containing a link to the user documentation for the current
6183 * page. Also contains an icon by default. Shown to teachers and admin only.
6185 * @param string $text The text to be displayed for the link
6186 * @param string $iconpath The path to the icon to be displayed
6188 function page_doc_link($text='', $iconpath='') {
6189 global $ME, $COURSE, $CFG;
6191 if (empty($CFG->docroot)) {
6192 return '';
6195 if (empty($COURSE->id)) {
6196 $context = get_context_instance(CONTEXT_SYSTEM);
6197 } else {
6198 $context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
6201 if (!has_capability('moodle/site:doclinks', $context)) {
6202 return '';
6205 if (empty($CFG->pagepath)) {
6206 $CFG->pagepath = $ME;
6209 $path = str_replace($CFG->httpswwwroot.'/','', $CFG->pagepath); // Because the page could be HTTPSPAGEREQUIRED
6210 $path = str_replace('.php', '', $path);
6212 if (empty($path)) { // Not for home page
6213 return '';
6215 return doc_link($path, $text, $iconpath);
6219 * Returns a string containing a link to the user documentation.
6220 * Also contains an icon by default. Shown to teachers and admin only.
6222 * @param string $path The page link after doc root and language, no
6223 * leading slash.
6224 * @param string $text The text to be displayed for the link
6225 * @param string $iconpath The path to the icon to be displayed
6227 function doc_link($path='', $text='', $iconpath='') {
6228 global $CFG;
6230 if (empty($CFG->docroot)) {
6231 return '';
6234 $target = '';
6235 if (!empty($CFG->doctonewwindow)) {
6236 $target = ' target="_blank"';
6239 $lang = str_replace('_utf8', '', current_language());
6241 $str = '<a href="' .$CFG->docroot. '/' .$lang. '/' .$path. '"' .$target. '>';
6243 if (empty($iconpath)) {
6244 $iconpath = $CFG->httpswwwroot . '/pix/docs.gif';
6247 // alt left blank intentionally to prevent repetition in screenreaders
6248 $str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
6250 return $str;
6254 * Returns true if the current site debugging settings are equal or above specified level.
6255 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
6256 * routing of notices is controlled by $CFG->debugdisplay
6257 * eg use like this:
6259 * 1) debugging('a normal debug notice');
6260 * 2) debugging('something really picky', DEBUG_ALL);
6261 * 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
6262 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
6264 * In code blocks controlled by debugging() (such as example 4)
6265 * any output should be routed via debugging() itself, or the lower-level
6266 * trigger_error() or error_log(). Using echo or print will break XHTML
6267 * JS and HTTP headers.
6270 * @param string $message a message to print
6271 * @param int $level the level at which this debugging statement should show
6272 * @return bool
6274 function debugging($message='', $level=DEBUG_NORMAL) {
6276 global $CFG;
6278 if (empty($CFG->debug)) {
6279 return false;
6282 if ($CFG->debug >= $level) {
6283 if ($message) {
6284 $callers = debug_backtrace();
6285 $from = '<ul style="text-align: left">';
6286 foreach ($callers as $caller) {
6287 if (!isset($caller['line'])) {
6288 $caller['line'] = '?'; // probably call_user_func()
6290 if (!isset($caller['file'])) {
6291 $caller['file'] = $CFG->dirroot.'/unknownfile'; // probably call_user_func()
6293 $from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
6294 if (isset($caller['function'])) {
6295 $from .= ': call to ';
6296 if (isset($caller['class'])) {
6297 $from .= $caller['class'] . $caller['type'];
6299 $from .= $caller['function'] . '()';
6301 $from .= '</li>';
6303 $from .= '</ul>';
6304 if (!isset($CFG->debugdisplay)) {
6305 $CFG->debugdisplay = ini_get('display_errors');
6307 if ($CFG->debugdisplay) {
6308 if (!defined('DEBUGGING_PRINTED')) {
6309 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
6311 notify($message . $from, 'notifytiny');
6312 } else {
6313 trigger_error($message . $from, E_USER_NOTICE);
6316 return true;
6318 return false;
6322 * Disable debug messages from debugging(), while keeping PHP error reporting level as is.
6324 function disable_debugging() {
6325 global $CFG;
6326 $CFG->debug = $CFG->debug | 0x80000000; // switch the sign bit in integer number ;-)
6331 * Returns string to add a frame attribute, if required
6333 function frametarget() {
6334 global $CFG;
6336 if (empty($CFG->framename) or ($CFG->framename == '_top')) {
6337 return '';
6338 } else {
6339 return ' target="'.$CFG->framename.'" ';
6344 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
6345 * pages that use bits from many different files in very confusing ways (e.g. blocks).
6346 * @usage print_location_comment(__FILE__, __LINE__);
6347 * @param string $file
6348 * @param integer $line
6349 * @param boolean $return Whether to return or print the comment
6350 * @return mixed Void unless true given as third parameter
6352 function print_location_comment($file, $line, $return = false)
6354 if ($return) {
6355 return "<!-- $file at line $line -->\n";
6356 } else {
6357 echo "<!-- $file at line $line -->\n";
6363 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
6364 * provide this function with the language strings for sortasc and sortdesc.
6365 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
6366 * @param string $direction 'up' or 'down'
6367 * @param string $strsort The language string used for the alt attribute of this image
6368 * @param bool $return Whether to print directly or return the html string
6369 * @return string HTML for the image
6371 * TODO See if this isn't already defined somewhere. If not, move this to weblib
6373 function print_arrow($direction='up', $strsort=null, $return=false) {
6374 global $CFG;
6376 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
6377 return null;
6380 $return = null;
6382 switch ($direction) {
6383 case 'up':
6384 $sortdir = 'asc';
6385 break;
6386 case 'down':
6387 $sortdir = 'desc';
6388 break;
6389 case 'move':
6390 $sortdir = 'asc';
6391 break;
6392 default:
6393 $sortdir = null;
6394 break;
6397 // Prepare language string
6398 $strsort = '';
6399 if (empty($strsort) && !empty($sortdir)) {
6400 $strsort = get_string('sort' . $sortdir, 'grades');
6403 $return = ' <img src="'.$CFG->pixpath.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
6405 if ($return) {
6406 return $return;
6407 } else {
6408 echo $return;
6412 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: