MDL-10689:
[moodle-linuxchix.git] / lib / weblib.php
blob168467667abd925a3ac19b6a6667f00bc6881063
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 array $navigation Array of $navlinks arrays (keys: name, link, type) 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='') {
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 if ($files) {
2900 /// Produce a list of all the files first
2901 echo '/**************************************'."\n";
2902 echo ' * THEME NAME: '.$themename."\n *\n";
2903 echo ' * Files included in this sheet:'."\n *\n";
2904 foreach ($files as $file) {
2905 echo ' * '.$file[1]."\n";
2907 echo ' **************************************/'."\n\n";
2910 /// check if csscobstants is set
2911 if (!empty($THEME->cssconstants)) {
2912 require_once("$CFG->libdir/cssconstants.php");
2913 /// Actually collect all the files in order.
2914 $css = '';
2915 foreach ($files as $file) {
2916 $css .= '/***** '.$file[1].' start *****/'."\n\n";
2917 $css .= file_get_contents($file[0].'/'.$file[1]);
2918 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
2920 /// replace css_constants with their values
2921 echo replace_cssconstants($css);
2922 } else {
2923 /// Actually output all the files in order.
2924 if (empty($CFG->CSSEdit) && empty($THEME->CSSEdit)) {
2925 foreach ($files as $file) {
2926 echo '/***** '.$file[1].' start *****/'."\n\n";
2927 @include_once($file[0].'/'.$file[1]);
2928 echo '/***** '.$file[1].' end *****/'."\n\n";
2930 } else {
2931 foreach ($files as $file) {
2932 echo '/* @group '.$file[1].' */'."\n\n";
2933 if (strstr($file[1], '.css') !== FALSE) {
2934 echo '@import url("'.$CFG->themewww.'/'.$file[1].'");'."\n\n";
2935 } else {
2936 @include_once($file[0].'/'.$file[1]);
2938 echo '/* @end */'."\n\n";
2944 return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
2948 function theme_setup($theme = '', $params=NULL) {
2949 /// Sets up global variables related to themes
2951 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
2953 if (empty($theme)) {
2954 $theme = current_theme();
2957 /// If the theme doesn't exist for some reason then revert to standardwhite
2958 if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
2959 $CFG->theme = $theme = 'standardwhite';
2962 /// Load up the theme config
2963 $THEME = NULL; // Just to be sure
2964 include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
2966 /// Put together the parameters
2967 if (!$params) {
2968 $params = array();
2971 if ($theme != $CFG->theme) {
2972 $params[] = 'forceconfig='.$theme;
2975 /// Force language too if required
2976 if (!empty($THEME->langsheets)) {
2977 $params[] = 'lang='.current_language();
2981 /// Convert params to string
2982 if ($params) {
2983 $paramstring = '?'.implode('&', $params);
2984 } else {
2985 $paramstring = '';
2988 /// Set up image paths
2989 if(isset($CFG->smartpix) && $CFG->smartpix==1) {
2990 if($CFG->slasharguments) { // Use this method if possible for better caching
2991 $extra='';
2992 } else {
2993 $extra='?file=';
2996 $CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
2997 $CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
2998 } else if (empty($THEME->custompix)) { // Could be set in the above file
2999 $CFG->pixpath = $CFG->wwwroot .'/pix';
3000 $CFG->modpixpath = $CFG->wwwroot .'/mod';
3001 } else {
3002 $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
3003 $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
3006 /// Header and footer paths
3007 $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
3008 $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
3010 /// Define stylesheet loading order
3011 $CFG->stylesheets = array();
3012 if ($theme != 'standard') { /// The standard sheet is always loaded first
3013 $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
3015 if (!empty($THEME->parent)) { /// Parent stylesheets are loaded next
3016 $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
3018 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
3020 /// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
3021 if (!empty($HTTPSPAGEREQUIRED)) {
3022 $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
3023 $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
3024 $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
3025 foreach ($CFG->stylesheets as $key => $stylesheet) {
3026 $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
3030 // RTL support - only for RTL languages, add RTL CSS
3031 if (get_string('thisdirection') == 'rtl') {
3032 $CFG->stylesheets[] = $CFG->themewww.'/standard/rtl.css'.$paramstring;
3033 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/rtl.css'.$paramstring;
3039 * Returns text to be displayed to the user which reflects their login status
3041 * @uses $CFG
3042 * @uses $USER
3043 * @param course $course {@link $COURSE} object containing course information
3044 * @param user $user {@link $USER} object containing user information
3045 * @return string
3047 function user_login_string($course=NULL, $user=NULL) {
3048 global $USER, $CFG, $SITE;
3050 if (empty($user) and !empty($USER->id)) {
3051 $user = $USER;
3054 if (empty($course)) {
3055 $course = $SITE;
3058 if (!empty($user->realuser)) {
3059 if ($realuser = get_record('user', 'id', $user->realuser)) {
3060 $fullname = fullname($realuser, true);
3061 $realuserinfo = " [<a $CFG->frametarget
3062 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=1&amp;sesskey=".sesskey()."\">$fullname</a>] ";
3064 } else {
3065 $realuserinfo = '';
3068 if (empty($CFG->loginhttps)) {
3069 $wwwroot = $CFG->wwwroot;
3070 } else {
3071 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
3074 if (empty($course->id)) {
3075 // $course->id is not defined during installation
3076 return '';
3077 } else if (!empty($user->id)) {
3078 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3080 $fullname = fullname($user, true);
3081 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a>";
3082 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid)) {
3083 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
3085 if (isset($user->username) && $user->username == 'guest') {
3086 $loggedinas = $realuserinfo.get_string('loggedinasguest').
3087 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3088 } else if (!empty($user->switchrole[$context->id])) {
3089 $rolename = '';
3090 if ($role = get_record('role', 'id', $user->switchrole[$context->id])) {
3091 $rolename = ': '.format_string($role->name);
3093 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
3094 " (<a $CFG->frametarget
3095 href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
3096 } else {
3097 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
3098 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
3100 } else {
3101 $loggedinas = get_string('loggedinnot', 'moodle').
3102 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3104 return '<div class="logininfo">'.$loggedinas.'</div>';
3108 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
3109 * If not it applies sensible defaults.
3111 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
3112 * search forum block, etc. Important: these are 'silent' in a screen-reader
3113 * (unlike &gt; &raquo;), and must be accompanied by text.
3114 * @uses $THEME
3116 function check_theme_arrows() {
3117 global $THEME;
3119 if (!isset($THEME->rarrow) and !isset($THEME->larrow)) {
3120 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
3121 // Also OK in Win 9x/2K/IE 5.x
3122 $THEME->rarrow = '&#x25BA;';
3123 $THEME->larrow = '&#x25C4;';
3124 $uagent = $_SERVER['HTTP_USER_AGENT'];
3125 if (false !== strpos($uagent, 'Opera')
3126 || false !== strpos($uagent, 'Mac')) {
3127 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
3128 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
3129 $THEME->rarrow = '&#x25B6;';
3130 $THEME->larrow = '&#x25C0;';
3132 elseif (false !== strpos($uagent, 'Konqueror')) {
3133 $THEME->rarrow = '&rarr;';
3134 $THEME->larrow = '&larr;';
3136 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
3137 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
3138 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
3139 // To be safe, non-Unicode browsers!
3140 $THEME->rarrow = '&gt;';
3141 $THEME->larrow = '&lt;';
3144 /// RTL support - in RTL languages, swap r and l arrows
3145 if (right_to_left()) {
3146 $t = $THEME->rarrow;
3147 $THEME->rarrow = $THEME->larrow;
3148 $THEME->larrow = $t;
3155 * Return the right arrow with text ('next'), and optionally embedded in a link.
3156 * See function above, check_theme_arrows.
3157 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3158 * @param string $url An optional link to use in a surrounding HTML anchor.
3159 * @param bool $accesshide True if text should be hidden (for screen readers only).
3160 * @param string $addclass Additional class names for the link, or the arrow character.
3161 * @return string HTML string.
3163 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
3164 global $THEME;
3165 check_theme_arrows();
3166 $arrowclass = 'arrow ';
3167 if (! $url) {
3168 $arrowclass .= $addclass;
3170 $arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow.'</span>';
3171 $htmltext = '';
3172 if ($text) {
3173 $htmltext = $text.'&nbsp;';
3174 if ($accesshide) {
3175 $htmltext = '<span class="accesshide">'.$htmltext.'</span>';
3178 if ($url) {
3179 $class = '';
3180 if ($addclass) {
3181 $class =" class=\"$addclass\"";
3183 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
3185 return $htmltext.$arrow;
3189 * Return the left arrow with text ('previous'), and optionally embedded in a link.
3190 * See function above, check_theme_arrows.
3191 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3192 * @param string $url An optional link to use in a surrounding HTML anchor.
3193 * @param bool $accesshide True if text should be hidden (for screen readers only).
3194 * @param string $addclass Additional class names for the link, or the arrow character.
3195 * @return string HTML string.
3197 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
3198 global $THEME;
3199 check_theme_arrows();
3200 $arrowclass = 'arrow ';
3201 if (! $url) {
3202 $arrowclass .= $addclass;
3204 $arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow.'</span>';
3205 $htmltext = '';
3206 if ($text) {
3207 $htmltext = '&nbsp;'.$text;
3208 if ($accesshide) {
3209 $htmltext = '<span class="accesshide">'.$htmltext.'</span>';
3212 if ($url) {
3213 $class = '';
3214 if ($addclass) {
3215 $class =" class=\"$addclass\"";
3217 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
3219 return $arrow.$htmltext;
3223 * Return the breadcrumb trail navigation separator.
3224 * @return string HTML string.
3226 function get_separator() {
3227 //Accessibility: the 'hidden' slash is preferred for screen readers.
3228 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
3234 * Prints breadcrumb trail of links, called in theme/-/header.html
3236 * @uses $CFG
3237 * @param mixed $navigation The breadcrumb navigation string to be printed
3238 * @param string $separator The breadcrumb trail separator. The default 0 leads to the use
3239 * of $THEME->rarrow, themes could use '&rarr;', '/', or '' for a style-sheet solution.
3240 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
3242 function print_navigation ($navigation, $separator=0, $return=false) {
3243 global $CFG, $THEME;
3244 $output = '';
3246 if (0 === $separator) {
3247 $separator = get_separator();
3249 else {
3250 $separator = '<span class="sep">'. $separator .'</span>';
3253 if ($navigation) {
3255 if (is_newnav($navigation)) {
3256 if ($return) {
3257 return($navigation['navlinks']);
3258 } else {
3259 echo $navigation['navlinks'];
3260 return;
3262 } else {
3263 debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER);
3266 if (!is_array($navigation)) {
3267 $ar = explode('->', $navigation);
3268 $navigation = array();
3270 foreach ($ar as $a) {
3271 if (strpos($a, '</a>') === false) {
3272 $navigation[] = array('title' => $a, 'url' => '');
3273 } else {
3274 if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
3275 $navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
3281 if (! $site = get_site()) {
3282 $site = new object();
3283 $site->shortname = get_string('home');
3286 //Accessibility: breadcrumb links now in a list, &raquo; replaced with a 'silent' character.
3287 $nav_text = get_string('youarehere','access');
3288 $output .= '<h2 class="accesshide">'.$nav_text."</h2><ul>\n";
3290 $output .= '<li class="first">'."\n".'<a '.$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3291 .$CFG->wwwroot.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))
3292 && !empty($USER->id) && !empty($CFG->mymoodleredirect) && !isguest())
3293 ? '/my' : '') .'/">'. format_string($site->shortname) ."</a>\n</li>\n";
3296 foreach ($navigation as $navitem) {
3297 $title = trim(strip_tags(format_string($navitem['title'], false)));
3298 $url = $navitem['url'];
3300 if (empty($url)) {
3301 $output .= '<li class="first">'."$separator $title</li>\n";
3302 } else {
3303 $output .= '<li class="first">'."$separator\n<a ".$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3304 .$url.'">'."$title</a>\n</li>\n";
3308 $output .= "</ul>\n";
3311 if ($return) {
3312 return $output;
3313 } else {
3314 echo $output;
3319 * Prints a string in a specified size (retained for backward compatibility)
3321 * @param string $text The text to be displayed
3322 * @param int $size The size to set the font for text display.
3324 function print_headline($text, $size=2, $return=false) {
3325 $output = print_heading($text, '', $size, true);
3326 if ($return) {
3327 return $output;
3328 } else {
3329 echo $output;
3334 * Prints text in a format for use in headings.
3336 * @param string $text The text to be displayed
3337 * @param string $align The alignment of the printed paragraph of text
3338 * @param int $size The size to set the font for text display.
3340 function print_heading($text, $align='', $size=2, $class='main', $return=false) {
3341 if ($align) {
3342 $align = ' style="text-align:'.$align.';"';
3344 if ($class) {
3345 $class = ' class="'.$class.'"';
3347 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
3349 if ($return) {
3350 return $output;
3351 } else {
3352 echo $output;
3357 * Centered heading with attached help button (same title text)
3358 * and optional icon attached
3360 * @param string $text The text to be displayed
3361 * @param string $helppage The help page to link to
3362 * @param string $module The module whose help should be linked to
3363 * @param string $icon Image to display if needed
3365 function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
3366 $output = '';
3367 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
3368 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
3369 $output .= '</h2>';
3371 if ($return) {
3372 return $output;
3373 } else {
3374 echo $output;
3379 function print_heading_block($heading, $class='', $return=false) {
3380 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
3381 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
3383 if ($return) {
3384 return $output;
3385 } else {
3386 echo $output;
3392 * Print a link to continue on to another page.
3394 * @uses $CFG
3395 * @param string $link The url to create a link to.
3397 function print_continue($link, $return=false) {
3399 global $CFG;
3401 // in case we are logging upgrade in admin/index.php stop it
3402 if (function_exists('upgrade_log_finish')) {
3403 upgrade_log_finish();
3406 $output = '';
3408 if ($link == '') {
3409 if (!empty($_SERVER['HTTP_REFERER'])) {
3410 $link = $_SERVER['HTTP_REFERER'];
3411 $link = str_replace('&', '&amp;', $link); // make it valid XHTML
3412 } else {
3413 $link = $CFG->wwwroot .'/';
3417 $output .= '<div class="continuebutton">';
3419 $output .= print_single_button($link, NULL, get_string('continue'), 'post', $CFG->framename, true);
3420 $output .= '</div>'."\n";
3422 if ($return) {
3423 return $output;
3424 } else {
3425 echo $output;
3431 * Print a message in a standard themed box.
3432 * Replaces print_simple_box (see deprecatedlib.php)
3434 * @param string $message, the content of the box
3435 * @param string $classes, space-separated class names.
3436 * @param string $ids, space-separated id names.
3437 * @param boolean $return, return as string or just print it
3439 function print_box($message, $classes='generalbox', $ids='', $return=false) {
3441 $output = print_box_start($classes, $ids, true);
3442 $output .= stripslashes_safe($message);
3443 $output .= print_box_end(true);
3445 if ($return) {
3446 return $output;
3447 } else {
3448 echo $output;
3453 * Starts a box using divs
3454 * Replaces print_simple_box_start (see deprecatedlib.php)
3456 * @param string $classes, space-separated class names.
3457 * @param string $ids, space-separated id names.
3458 * @param boolean $return, return as string or just print it
3460 function print_box_start($classes='generalbox', $ids='', $return=false) {
3461 $output = '';
3463 if ($ids) {
3464 $ids = ' id="'.$ids.'"';
3467 $output .= '<div'.$ids.' class="box '.$classes.'">';
3469 if ($return) {
3470 return $output;
3471 } else {
3472 echo $output;
3478 * Simple function to end a box (see above)
3479 * Replaces print_simple_box_end (see deprecatedlib.php)
3481 * @param boolean $return, return as string or just print it
3483 function print_box_end($return=false) {
3484 $output = '</div>';
3485 if ($return) {
3486 return $output;
3487 } else {
3488 echo $output;
3494 * Print a self contained form with a single submit button.
3496 * @param string $link ?
3497 * @param array $options ?
3498 * @param string $label ?
3499 * @param string $method ?
3500 * @todo Finish documenting this function
3502 function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='') {
3503 $output = '';
3504 $link = str_replace('"', '&quot;', $link); //basic XSS protection
3505 $output .= '<div class="singlebutton">';
3506 // taking target out, will need to add later target="'.$target.'"
3507 $output .= '<form action="'. $link .'" method="'. $method .'">';
3508 $output .= '<div>';
3509 if ($options) {
3510 foreach ($options as $name => $value) {
3511 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
3514 if ($tooltip) {
3515 $tooltip = 'title="' . s($tooltip) . '"';
3516 } else {
3517 $tooltip = '';
3519 $output .= '<input type="submit" value="'. s($label) .'" ' . $tooltip . ' /></div></form></div>';
3521 if ($return) {
3522 return $output;
3523 } else {
3524 echo $output;
3530 * Print a spacer image with the option of including a line break.
3532 * @param int $height ?
3533 * @param int $width ?
3534 * @param boolean $br ?
3535 * @todo Finish documenting this function
3537 function print_spacer($height=1, $width=1, $br=true, $return=false) {
3538 global $CFG;
3539 $output = '';
3541 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot .'/pix/spacer.gif" alt="" />';
3542 if ($br) {
3543 $output .= '<br />'."\n";
3546 if ($return) {
3547 return $output;
3548 } else {
3549 echo $output;
3554 * Given the path to a picture file in a course, or a URL,
3555 * this function includes the picture in the page.
3557 * @param string $path ?
3558 * @param int $courseid ?
3559 * @param int $height ?
3560 * @param int $width ?
3561 * @param string $link ?
3562 * @todo Finish documenting this function
3564 function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
3565 global $CFG;
3566 $output = '';
3568 if ($height) {
3569 $height = 'height="'. $height .'"';
3571 if ($width) {
3572 $width = 'width="'. $width .'"';
3574 if ($link) {
3575 $output .= '<a href="'. $link .'">';
3577 if (substr(strtolower($path), 0, 7) == 'http://') {
3578 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
3580 } else if ($courseid) {
3581 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
3582 if ($CFG->slasharguments) { // Use this method if possible for better caching
3583 $output .= $CFG->wwwroot .'/file.php/'. $courseid .'/'. $path;
3584 } else {
3585 $output .= $CFG->wwwroot .'/file.php?file=/'. $courseid .'/'. $path;
3587 $output .= '" />';
3588 } else {
3589 $output .= 'Error: must pass URL or course';
3591 if ($link) {
3592 $output .= '</a>';
3595 if ($return) {
3596 return $output;
3597 } else {
3598 echo $output;
3603 * Print the specified user's avatar.
3605 * @param int $userid ?
3606 * @param int $courseid ?
3607 * @param boolean $picture Print the user picture?
3608 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
3609 * @param boolean $return If false print picture to current page, otherwise return the output as string
3610 * @param boolean $link Enclose printed image in a link to view specified course?
3611 * @param string $target link target attribute
3612 * @param boolean $alttext use username or userspecified text in image alt attribute
3613 * return string
3614 * @todo Finish documenting this function
3616 function print_user_picture($userid, $courseid, $picture, $size=0, $return=false, $link=true, $target='', $alttext=true) {
3617 global $CFG;
3619 if ($link) {
3620 if ($target) {
3621 $target=' target="_blank"';
3623 $output = '<a '.$target.' href="'. $CFG->wwwroot .'/user/view.php?id='. $userid .'&amp;course='. $courseid .'">';
3624 } else {
3625 $output = '';
3627 if (empty($size)) {
3628 $file = 'f2';
3629 $size = 35;
3630 } else if ($size === true or $size == 1) {
3631 $file = 'f1';
3632 $size = 100;
3633 } else if ($size >= 50) {
3634 $file = 'f1';
3635 } else {
3636 $file = 'f2';
3638 $class = "userpicture";
3639 if ($picture) { // Print custom user picture
3640 if ($CFG->slasharguments) { // Use this method if possible for better caching
3641 $src = $CFG->wwwroot .'/user/pix.php/'. $userid .'/'. $file .'.jpg';
3642 } else {
3643 $src = $CFG->wwwroot .'/user/pix.php?file=/'. $userid .'/'. $file .'.jpg';
3645 } else { // Print default user pictures (use theme version if available)
3646 $class .= " defaultuserpic";
3647 $src = "$CFG->pixpath/u/$file.png";
3649 $imagealt = '';
3650 if ($alttext and $user = get_record('user','id',$userid)) {
3651 if (!empty($user->imagealt)) {
3652 $imagealt = $user->imagealt;
3653 } else {
3654 $imagealt = get_string('pictureof','',fullname($user));
3658 $output .= '<img class="'.$class.'" src="'.$src.'" alt="'.s($imagealt).'" />';
3659 if ($link) {
3660 $output .= '</a>';
3663 if ($return) {
3664 return $output;
3665 } else {
3666 echo $output;
3671 * Prints a summary of a user in a nice little box.
3673 * @uses $CFG
3674 * @uses $USER
3675 * @param user $user A {@link $USER} object representing a user
3676 * @param course $course A {@link $COURSE} object representing a course
3678 function print_user($user, $course, $messageselect=false, $return=false) {
3680 global $CFG, $USER;
3682 $output = '';
3684 static $string;
3685 static $datestring;
3686 static $countries;
3688 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3690 if (empty($string)) { // Cache all the strings for the rest of the page
3692 $string->email = get_string('email');
3693 $string->location = get_string('location');
3694 $string->lastaccess = get_string('lastaccess');
3695 $string->activity = get_string('activity');
3696 $string->unenrol = get_string('unenrol');
3697 $string->loginas = get_string('loginas');
3698 $string->fullprofile = get_string('fullprofile');
3699 $string->role = get_string('role');
3700 $string->name = get_string('name');
3701 $string->never = get_string('never');
3703 $datestring->day = get_string('day');
3704 $datestring->days = get_string('days');
3705 $datestring->hour = get_string('hour');
3706 $datestring->hours = get_string('hours');
3707 $datestring->min = get_string('min');
3708 $datestring->mins = get_string('mins');
3709 $datestring->sec = get_string('sec');
3710 $datestring->secs = get_string('secs');
3712 $countries = get_list_of_countries();
3715 /// Get the hidden field list
3716 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
3717 $hiddenfields = array();
3718 } else {
3719 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
3722 $output .= '<table class="userinfobox">';
3723 $output .= '<tr>';
3724 $output .= '<td class="left side">';
3725 $output .= print_user_picture($user->id, $course->id, $user->picture, true, true);
3726 $output .= '</td>';
3727 $output .= '<td class="content">';
3728 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
3729 $output .= '<div class="info">';
3730 if (!empty($user->role) and ($user->role <> $course->teacher)) {
3731 $output .= $string->role .': '. $user->role .'<br />';
3733 if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguest()) or
3734 has_capability('moodle/course:viewhiddenuserfields', $context)) {
3735 $output .= $string->email .': <a href="mailto:'. $user->email .'">'. $user->email .'</a><br />';
3737 if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
3738 $output .= $string->location .': ';
3739 if ($user->city && !isset($hiddenfields['city'])) {
3740 $output .= $user->city;
3742 if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
3743 if ($user->city && !isset($hiddenfields['city'])) {
3744 $output .= ', ';
3746 $output .= $countries[$user->country];
3748 $output .= '<br />';
3751 if (!isset($hiddenfields['lastaccess'])) {
3752 if ($user->lastaccess) {
3753 $output .= $string->lastaccess .': '. userdate($user->lastaccess);
3754 $output .= '&nbsp; ('. format_time(time() - $user->lastaccess, $datestring) .')';
3755 } else {
3756 $output .= $string->lastaccess .': '. $string->never;
3759 $output .= '</div></td><td class="links">';
3760 //link to blogs
3761 if ($CFG->bloglevel > 0) {
3762 $output .= '<a href="'.$CFG->wwwroot.'/blog/index.php?userid='.$user->id.'">'.get_string('blogs','blog').'</a><br />';
3764 //link to notes
3765 if (has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context)) {
3766 $output .= '<a href="'.$CFG->wwwroot.'/notes/index.php?course=' . $course->id. '&amp;user='.$user->id.'">'.get_string('notes','notes').'</a><br />';
3769 if (has_capability('moodle/site:viewreports', $context)) {
3770 $timemidnight = usergetmidnight(time());
3771 $output .= '<a href="'. $CFG->wwwroot .'/course/user.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->activity .'</a><br />';
3773 if (has_capability('moodle/role:assign', $context, NULL)) { // Includes admins
3774 $output .= '<a href="'. $CFG->wwwroot .'/course/unenrol.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->unenrol .'</a><br />';
3776 if ($USER->id != $user->id && empty($USER->realuser) && has_capability('moodle/user:loginas', $context) &&
3777 ! has_capability('moodle/site:doanything', $context, $user->id, false)) {
3778 $output .= '<a href="'. $CFG->wwwroot .'/course/loginas.php?id='. $course->id .'&amp;user='. $user->id .'&amp;sesskey='. sesskey() .'">'. $string->loginas .'</a><br />';
3780 $output .= '<a href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&amp;course='. $course->id .'">'. $string->fullprofile .'...</a>';
3782 if (!empty($messageselect)) {
3783 $output .= '<br /><input type="checkbox" name="user'.$user->id.'" /> ';
3786 $output .= '</td></tr></table>';
3788 if ($return) {
3789 return $output;
3790 } else {
3791 echo $output;
3796 * Print a specified group's avatar.
3798 * @param group $group A single {@link group} object OR array of groups.
3799 * @param int $courseid The course ID.
3800 * @param boolean $large Default small picture, or large.
3801 * @param boolean $return If false print picture, otherwise return the output as string
3802 * @param boolean $link Enclose image in a link to view specified course?
3803 * @return string
3804 * @todo Finish documenting this function
3806 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
3807 global $CFG;
3809 if (is_array($group)) {
3810 $output = '';
3811 foreach($group as $g) {
3812 $output .= print_group_picture($g, $courseid, $large, true, $link);
3814 if ($return) {
3815 return $output;
3816 } else {
3817 echo $output;
3818 return;
3822 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3824 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
3825 return '';
3828 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
3829 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
3830 } else {
3831 $output = '';
3833 if ($large) {
3834 $file = 'f1';
3835 $size = 100;
3836 } else {
3837 $file = 'f2';
3838 $size = 35;
3840 if ($group->picture) { // Print custom group picture
3841 if ($CFG->slasharguments) { // Use this method if possible for better caching
3842 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot.'/user/pixgroup.php/'.$group->id.'/'.$file.'.jpg"'.
3843 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
3844 } else {
3845 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot.'/user/pixgroup.php?file=/'.$group->id.'/'.$file.'.jpg"'.
3846 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
3849 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
3850 $output .= '</a>';
3853 if ($return) {
3854 return $output;
3855 } else {
3856 echo $output;
3861 * Print a png image.
3863 * @param string $url ?
3864 * @param int $sizex ?
3865 * @param int $sizey ?
3866 * @param boolean $return ?
3867 * @param string $parameters ?
3868 * @todo Finish documenting this function
3870 function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
3871 global $CFG;
3872 static $recentIE;
3874 if (!isset($recentIE)) {
3875 $recentIE = check_browser_version('MSIE', '5.0');
3878 if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
3879 $output .= '<img src="'. $CFG->pixpath .'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
3880 ' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
3881 ' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
3882 "'$url', sizingMethod='scale') ".
3883 ' '. $parameters .' />';
3884 } else {
3885 $output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
3888 if ($return) {
3889 return $output;
3890 } else {
3891 echo $output;
3896 * Print a nicely formatted table.
3898 * @param array $table is an object with several properties.
3899 * <ul>
3900 * <li>$table->head - An array of heading names.
3901 * <li>$table->align - An array of column alignments
3902 * <li>$table->size - An array of column sizes
3903 * <li>$table->wrap - An array of "nowrap"s or nothing
3904 * <li>$table->data[] - An array of arrays containing the data.
3905 * <li>$table->width - A percentage of the page
3906 * <li>$table->tablealign - Align the whole table
3907 * <li>$table->cellpadding - Padding on each cell
3908 * <li>$table->cellspacing - Spacing between cells
3909 * <li>$table->class - class attribute to put on the table
3910 * <li>$table->id - id attribute to put on the table.
3911 * <li>$table->rowclass[] - classes to add to particular rows.
3912 * </ul>
3913 * @param bool $return whether to return an output string or echo now
3914 * @return boolean or $string
3915 * @todo Finish documenting this function
3917 function print_table($table, $return=false) {
3918 $output = '';
3920 if (isset($table->align)) {
3921 foreach ($table->align as $key => $aa) {
3922 if ($aa) {
3923 $align[$key] = ' text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
3924 } else {
3925 $align[$key] = '';
3929 if (isset($table->size)) {
3930 foreach ($table->size as $key => $ss) {
3931 if ($ss) {
3932 $size[$key] = ' width:'. $ss .';';
3933 } else {
3934 $size[$key] = '';
3938 if (isset($table->wrap)) {
3939 foreach ($table->wrap as $key => $ww) {
3940 if ($ww) {
3941 $wrap[$key] = ' white-space:nowrap;';
3942 } else {
3943 $wrap[$key] = '';
3948 if (empty($table->width)) {
3949 $table->width = '80%';
3952 if (empty($table->tablealign)) {
3953 $table->tablealign = 'center';
3956 if (empty($table->cellpadding)) {
3957 $table->cellpadding = '5';
3960 if (empty($table->cellspacing)) {
3961 $table->cellspacing = '1';
3964 if (empty($table->class)) {
3965 $table->class = 'generaltable';
3968 $tableid = empty($table->id) ? '' : 'id="'.$table->id.'"';
3970 $output .= '<table width="'.$table->width.'" ';
3971 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
3973 $countcols = 0;
3975 if (!empty($table->head)) {
3976 $countcols = count($table->head);
3977 $output .= '<tr>';
3978 foreach ($table->head as $key => $heading) {
3980 if (!isset($size[$key])) {
3981 $size[$key] = '';
3983 if (!isset($align[$key])) {
3984 $align[$key] = '';
3987 $output .= '<th class="header c'.$key.'" scope="col">'. $heading .'</th>';
3988 // commenting the following code out as <th style does not validate MDL-7861
3989 //$output .= '<th sytle="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.'" scope="col">'. $heading .'</th>';
3991 $output .= '</tr>'."\n";
3994 if (!empty($table->data)) {
3995 $oddeven = 1;
3996 foreach ($table->data as $key => $row) {
3997 $oddeven = $oddeven ? 0 : 1;
3998 if (!isset($table->rowclass[$key])) {
3999 $table->rowclass[$key] = '';
4001 $output .= '<tr class="r'.$oddeven.' '.$table->rowclass[$key].'">'."\n";
4002 if ($row == 'hr' and $countcols) {
4003 $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
4004 } else { /// it's a normal row of data
4005 foreach ($row as $key => $item) {
4006 if (!isset($size[$key])) {
4007 $size[$key] = '';
4009 if (!isset($align[$key])) {
4010 $align[$key] = '';
4012 if (!isset($wrap[$key])) {
4013 $wrap[$key] = '';
4015 $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.'">'. $item .'</td>';
4018 $output .= '</tr>'."\n";
4021 $output .= '</table>'."\n";
4023 if ($return) {
4024 return $output;
4027 echo $output;
4028 return true;
4032 * Creates a nicely formatted table and returns it.
4034 * @param array $table is an object with several properties.
4035 * <ul<li>$table->head - An array of heading names.
4036 * <li>$table->align - An array of column alignments
4037 * <li>$table->size - An array of column sizes
4038 * <li>$table->wrap - An array of "nowrap"s or nothing
4039 * <li>$table->data[] - An array of arrays containing the data.
4040 * <li>$table->class - A css class name
4041 * <li>$table->fontsize - Is the size of all the text
4042 * <li>$table->tablealign - Align the whole table
4043 * <li>$table->width - A percentage of the page
4044 * <li>$table->cellpadding - Padding on each cell
4045 * <li>$table->cellspacing - Spacing between cells
4046 * </ul>
4047 * @return string
4048 * @todo Finish documenting this function
4050 function make_table($table) {
4052 if (isset($table->align)) {
4053 foreach ($table->align as $key => $aa) {
4054 if ($aa) {
4055 $align[$key] = ' align="'. $aa .'"';
4056 } else {
4057 $align[$key] = '';
4061 if (isset($table->size)) {
4062 foreach ($table->size as $key => $ss) {
4063 if ($ss) {
4064 $size[$key] = ' width="'. $ss .'"';
4065 } else {
4066 $size[$key] = '';
4070 if (isset($table->wrap)) {
4071 foreach ($table->wrap as $key => $ww) {
4072 if ($ww) {
4073 $wrap[$key] = ' style="white-space:nowrap;" ';
4074 } else {
4075 $wrap[$key] = '';
4080 if (empty($table->width)) {
4081 $table->width = '80%';
4084 if (empty($table->tablealign)) {
4085 $table->tablealign = 'center';
4088 if (empty($table->cellpadding)) {
4089 $table->cellpadding = '5';
4092 if (empty($table->cellspacing)) {
4093 $table->cellspacing = '1';
4096 if (empty($table->class)) {
4097 $table->class = 'generaltable';
4100 if (empty($table->fontsize)) {
4101 $fontsize = '';
4102 } else {
4103 $fontsize = '<font size="'. $table->fontsize .'">';
4106 $output = '<table width="'. $table->width .'" align="'. $table->tablealign .'" ';
4107 $output .= ' cellpadding="'. $table->cellpadding .'" cellspacing="'. $table->cellspacing .'" class="'. $table->class .'">'."\n";
4109 if (!empty($table->head)) {
4110 $output .= '<tr valign="top">';
4111 foreach ($table->head as $key => $heading) {
4112 if (!isset($size[$key])) {
4113 $size[$key] = '';
4115 if (!isset($align[$key])) {
4116 $align[$key] = '';
4118 $output .= '<th valign="top" '. $align[$key].$size[$key] .' style="white-space:nowrap;" class="'. $table->class .'header" scope="col">'.$fontsize.$heading.'</th>';
4120 $output .= '</tr>'."\n";
4123 foreach ($table->data as $row) {
4124 $output .= '<tr valign="top">';
4125 foreach ($row as $key => $item) {
4126 if (!isset($size[$key])) {
4127 $size[$key] = '';
4129 if (!isset($align[$key])) {
4130 $align[$key] = '';
4132 if (!isset($wrap[$key])) {
4133 $wrap[$key] = '';
4135 $output .= '<td '. $align[$key].$size[$key].$wrap[$key] .' class="'. $table->class .'cell">'. $fontsize . $item .'</td>';
4137 $output .= '</tr>'."\n";
4139 $output .= '</table>'."\n";
4141 return $output;
4144 function print_recent_activity_note($time, $user, $text, $link, $return=false) {
4145 static $strftimerecent;
4146 $output = '';
4148 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
4149 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
4151 if (empty($strftimerecent)) {
4152 $strftimerecent = get_string('strftimerecent');
4155 $date = userdate($time, $strftimerecent);
4156 $name = fullname($user, $viewfullnames);
4158 $output .= '<div class="head">';
4159 $output .= '<div class="date">'.$date.'</div> '.
4160 '<div class="name">'.fullname($user, $viewfullnames).'</div>';
4161 $output .= '</div>';
4162 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
4164 if ($return) {
4165 return $output;
4166 } else {
4167 echo $output;
4173 * Prints a basic textarea field.
4175 * @uses $CFG
4176 * @param boolean $usehtmleditor ?
4177 * @param int $rows ?
4178 * @param int $cols ?
4179 * @param null $width <b>Legacy field no longer used!</b> Set to zero to get control over mincols
4180 * @param null $height <b>Legacy field no longer used!</b> Set to zero to get control over minrows
4181 * @param string $name ?
4182 * @param string $value ?
4183 * @param int $courseid ?
4184 * @todo Finish documenting this function
4186 function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $courseid=0, $return=false, $id='') {
4187 /// $width and height are legacy fields and no longer used as pixels like they used to be.
4188 /// However, you can set them to zero to override the mincols and minrows values below.
4190 global $CFG, $COURSE, $HTTPSPAGEREQUIRED;
4191 static $scriptcount = 0; // For loading the htmlarea script only once.
4193 $mincols = 65;
4194 $minrows = 10;
4195 $str = '';
4197 if ($id === '') {
4198 $id = 'edit-'.$name;
4201 if ( empty($CFG->editorsrc) ) { // for backward compatibility.
4202 if (empty($courseid)) {
4203 $courseid = $COURSE->id;
4206 if ($usehtmleditor) {
4207 if (!empty($courseid) and has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE, $courseid))) {
4208 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '&ampt;httpsrequired=1';
4209 // needed for course file area browsing in image insert plugin
4210 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4211 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php?id='.$courseid.$httpsrequired.'"></script>'."\n" : '';
4212 } else {
4213 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '?httpsrequired=1';
4214 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4215 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php'.$httpsrequired.'"></script>'."\n" : '';
4218 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4219 $CFG->httpswwwroot .'/lib/editor/htmlarea/lang/en.php"></script>'."\n" : '';
4220 $scriptcount++;
4222 if ($height) { // Usually with legacy calls
4223 if ($rows < $minrows) {
4224 $rows = $minrows;
4227 if ($width) { // Usually with legacy calls
4228 if ($cols < $mincols) {
4229 $cols = $mincols;
4234 $str .= '<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">';
4235 if ($usehtmleditor) {
4236 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
4237 } else {
4238 $str .= s($value);
4240 $str .= '</textarea>'."\n";
4242 if ($usehtmleditor) {
4243 // Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
4244 $str .= '<script type="text/javascript">document.write(\''.
4245 str_replace('\'','\\\'',editorshortcutshelpbutton()).'\'); </script>';
4248 if ($return) {
4249 return $str;
4251 echo $str;
4255 * Sets up the HTML editor on textareas in the current page.
4256 * If a field name is provided, then it will only be
4257 * applied to that field - otherwise it will be used
4258 * on every textarea in the page.
4260 * In most cases no arguments need to be supplied
4262 * @param string $name Form element to replace with HTMl editor by name
4264 function use_html_editor($name='', $editorhidebuttons='', $id='') {
4265 global $THEME;
4267 $editor = 'editor_'.md5($name); //name might contain illegal characters
4268 if ($id === '') {
4269 $id = 'edit-'.$name;
4271 echo "\n".'<script type="text/javascript" defer="defer">'."\n";
4272 echo '//<![CDATA['."\n\n"; // Extra \n is to fix odd wiki problem, MDL-8185
4273 echo "$editor = new HTMLArea('$id');\n";
4274 echo "var config = $editor.config;\n";
4276 echo print_editor_config($editorhidebuttons);
4278 if (empty($THEME->htmleditorpostprocess)) {
4279 if (empty($name)) {
4280 echo "\nHTMLArea.replaceAll($editor.config);\n";
4281 } else {
4282 echo "\n$editor.generate();\n";
4284 } else {
4285 if (empty($name)) {
4286 echo "\nvar HTML_name = '';";
4287 } else {
4288 echo "\nvar HTML_name = \"$name;\"";
4290 echo "\nvar HTML_editor = $editor;";
4292 echo '//]]>'."\n";
4293 echo '</script>'."\n";
4296 function print_editor_config($editorhidebuttons='', $return=false) {
4297 global $CFG;
4299 $str = "config.pageStyle = \"body {";
4301 if (!(empty($CFG->editorbackgroundcolor))) {
4302 $str .= " background-color: $CFG->editorbackgroundcolor;";
4305 if (!(empty($CFG->editorfontfamily))) {
4306 $str .= " font-family: $CFG->editorfontfamily;";
4309 if (!(empty($CFG->editorfontsize))) {
4310 $str .= " font-size: $CFG->editorfontsize;";
4313 $str .= " }\";\n";
4314 $str .= "config.killWordOnPaste = ";
4315 $str .= (empty($CFG->editorkillword)) ? "false":"true";
4316 $str .= ';'."\n";
4317 $str .= 'config.fontname = {'."\n";
4319 $fontlist = isset($CFG->editorfontlist) ? explode(';', $CFG->editorfontlist) : array();
4320 $i = 1; // Counter is used to get rid of the last comma.
4322 foreach ($fontlist as $fontline) {
4323 if (!empty($fontline)) {
4324 if ($i > 1) {
4325 $str .= ','."\n";
4327 list($fontkey, $fontvalue) = split(':', $fontline);
4328 $str .= '"'. $fontkey ."\":\t'". $fontvalue ."'";
4330 $i++;
4333 $str .= '};';
4335 if (!empty($editorhidebuttons)) {
4336 $str .= "\nconfig.hideSomeButtons(\" ". $editorhidebuttons ." \");\n";
4337 } else if (!empty($CFG->editorhidebuttons)) {
4338 $str .= "\nconfig.hideSomeButtons(\" ". $CFG->editorhidebuttons ." \");\n";
4341 if (!empty($CFG->editorspelling) && !empty($CFG->aspellpath)) {
4342 $str .= print_speller_code($CFG->htmleditor, true);
4345 if ($return) {
4346 return $str;
4348 echo $str;
4352 * Returns a turn edit on/off button for course in a self contained form.
4353 * Used to be an icon, but it's now a simple form button
4355 * @uses $CFG
4356 * @uses $USER
4357 * @param int $courseid The course to update by id as found in 'course' table
4358 * @return string
4360 function update_course_icon($courseid) {
4362 global $CFG, $USER;
4364 $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
4366 $capcheck = false;
4368 if (has_capability('moodle/course:manageactivities', $coursecontext) ||
4369 has_capability('moodle/site:manageblocks', $coursecontext)) {
4370 $capcheck = true;
4371 } else {
4372 // loop through all child context, see if user has moodle/course:manageactivities or moodle/site:manageblocks
4373 if ($children = get_child_contexts($coursecontext)) {
4374 foreach ($children as $child) {
4375 $childcontext = get_record('context', 'id', $child);
4376 if (has_capability('moodle/course:manageactivities', $childcontext) ||
4377 has_capability('moodle/site:manageblocks', $childcontext)) {
4378 $capcheck = true;
4379 break;
4386 if ($capcheck) {
4387 if (!empty($USER->editing)) {
4388 $string = get_string('turneditingoff');
4389 $edit = '0';
4390 } else {
4391 $string = get_string('turneditingon');
4392 $edit = '1';
4395 return '<form '.$CFG->frametarget.' method="get" action="'.$CFG->wwwroot.'/course/view.php">'.
4396 '<div>'.
4397 '<input type="hidden" name="id" value="'.$courseid.'" />'.
4398 '<input type="hidden" name="edit" value="'.$edit.'" />'.
4399 '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
4400 '<input type="submit" value="'.$string.'" />'.
4401 '</div></form>';
4406 * Returns a little popup menu for switching roles
4408 * @uses $CFG
4409 * @uses $USER
4410 * @param int $courseid The course to update by id as found in 'course' table
4411 * @return string
4413 function switchroles_form($courseid) {
4415 global $CFG, $USER;
4418 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
4419 return '';
4422 if (!empty($USER->switchrole[$context->id])){ // Just a button to return to normal
4423 $options = array();
4424 $options['id'] = $courseid;
4425 $options['sesskey'] = sesskey();
4426 $options['switchrole'] = 0;
4428 return print_single_button($CFG->wwwroot.'/course/view.php', $options,
4429 get_string('switchrolereturn'), 'post', '_self', true);
4432 if (has_capability('moodle/role:switchroles', $context)) {
4433 if (!$roles = get_assignable_roles($context)) {
4434 return ''; // Nothing to show!
4436 // unset default user role - it would not work
4437 unset($roles[$CFG->guestroleid]);
4438 return popup_form($CFG->wwwroot.'/course/view.php?id='.$courseid.'&amp;sesskey='.sesskey().'&amp;switchrole=',
4439 $roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
4442 return '';
4447 * Returns a turn edit on/off button for course in a self contained form.
4448 * Used to be an icon, but it's now a simple form button
4450 * @uses $CFG
4451 * @uses $USER
4452 * @param int $courseid The course to update by id as found in 'course' table
4453 * @return string
4455 function update_mymoodle_icon() {
4457 global $CFG, $USER;
4459 if (!empty($USER->editing)) {
4460 $string = get_string('updatemymoodleoff');
4461 $edit = '0';
4462 } else {
4463 $string = get_string('updatemymoodleon');
4464 $edit = '1';
4467 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
4468 "<div>".
4469 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
4470 "<input type=\"submit\" value=\"$string\" /></div></form>";
4474 * Returns a turn edit on/off button for tag in a self contained form.
4476 * @uses $CFG
4477 * @uses $USER
4478 * @return string
4480 function update_tag_button($tagid) {
4482 global $CFG, $USER;
4484 if (!empty($USER->editing)) {
4485 $string = get_string('turneditingoff');
4486 $edit = '0';
4487 } else {
4488 $string = get_string('turneditingon');
4489 $edit = '1';
4492 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/tag/index.php\">".
4493 "<div>".
4494 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
4495 "<input type=\"hidden\" name=\"id\" value=\"$tagid\" />".
4496 "<input type=\"submit\" value=\"$string\" /></div></form>";
4500 * Prints the editing button on a module "view" page
4502 * @uses $CFG
4503 * @param type description
4504 * @todo Finish documenting this function
4506 function update_module_button($moduleid, $courseid, $string) {
4507 global $CFG, $USER;
4509 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $moduleid))) {
4510 $string = get_string('updatethis', '', $string);
4512 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
4513 "<div>".
4514 "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
4515 "<input type=\"hidden\" name=\"return\" value=\"true\" />".
4516 "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
4517 "<input type=\"submit\" value=\"$string\" /></div></form>";
4518 } else {
4519 return '';
4524 * Prints the editing button on a category page
4526 * @uses $CFG
4527 * @uses $USER
4528 * @param int $categoryid ?
4529 * @return string
4530 * @todo Finish documenting this function
4532 function update_category_button($categoryid) {
4533 global $CFG, $USER;
4535 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_COURSECAT, $categoryid))) {
4536 if (!empty($USER->categoryediting)) {
4537 $string = get_string('turneditingoff');
4538 $edit = 'off';
4539 } else {
4540 $string = get_string('turneditingon');
4541 $edit = 'on';
4544 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/category.php\">".
4545 '<div>'.
4546 "<input type=\"hidden\" name=\"id\" value=\"$categoryid\" />".
4547 "<input type=\"hidden\" name=\"categoryedit\" value=\"$edit\" />".
4548 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
4549 "<input type=\"submit\" value=\"$string\" /></div></form>";
4554 * Prints the editing button on categories listing
4556 * @uses $CFG
4557 * @uses $USER
4558 * @return string
4560 function update_categories_button() {
4561 global $CFG, $USER;
4563 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
4564 if (!empty($USER->categoryediting)) {
4565 $string = get_string('turneditingoff');
4566 $categoryedit = 'off';
4567 } else {
4568 $string = get_string('turneditingon');
4569 $categoryedit = 'on';
4572 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/index.php\">".
4573 '<div>'.
4574 '<input type="hidden" name="categoryedit" value="'. $categoryedit .'" />'.
4575 '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />'.
4576 '<input type="submit" value="'. $string .'" /></div></form>';
4581 * Prints the editing button on search results listing
4582 * For bulk move courses to another category
4585 function update_categories_search_button($search,$page,$perpage) {
4586 global $CFG, $USER;
4588 // not sure if this capability is the best here
4589 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
4590 if (!empty($USER->categoryediting)) {
4591 $string = get_string("turneditingoff");
4592 $edit = "off";
4593 $perpage = 30;
4594 } else {
4595 $string = get_string("turneditingon");
4596 $edit = "on";
4599 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
4600 '<div>'.
4601 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
4602 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
4603 "<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
4604 "<input type=\"hidden\" name=\"page\" value=\"$page\" />".
4605 "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
4606 "<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
4612 * Prints the editing button on groups page
4614 * @uses $CFG
4615 * @uses $USER
4616 * @param int $courseid The id of the course to be edited
4617 * @return string
4618 * @todo Finish documenting this function
4620 function update_groups_button($courseid) {
4621 global $CFG, $USER;
4623 if (has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $courseid))) {
4624 if (!empty($USER->groupsediting)) {
4625 $string = get_string('turneditingoff');
4626 $edit = 'off';
4627 } else {
4628 $string = get_string('turneditingon');
4629 $edit = 'on';
4632 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/group/index.php\">".
4633 '<div>'.
4634 "<input type=\"hidden\" name=\"id\" value=\"$courseid\" />".
4635 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
4636 "<input type=\"submit\" value=\"$string\" /></div></form>";
4641 * Prints an appropriate group selection menu
4643 * @uses VISIBLEGROUPS
4644 * @param array $groups ?
4645 * @param int $groupmode ?
4646 * @param string $currentgroup ?
4647 * @param string $urlroot ?
4648 * @param boolean $showall: if set to 0, it is a student in separate groups, do not display all participants
4649 * @todo Finish documenting this function
4651 function print_group_menu($groups, $groupmode, $currentgroup, $urlroot, $showall=1, $return=false) {
4653 $output = '';
4654 $groupsmenu = array();
4656 /// Add an "All groups" to the start of the menu
4657 if ($showall){
4658 $groupsmenu[0] = get_string('allparticipants');
4660 foreach ($groups as $key => $group) {
4661 $groupsmenu[$key] = format_string($group->name);
4664 if ($groupmode == VISIBLEGROUPS) {
4665 $grouplabel = get_string('groupsvisible');
4666 } else {
4667 $grouplabel = get_string('groupsseparate');
4670 if (count($groupsmenu) == 1) {
4671 $groupname = reset($groupsmenu);
4672 $output .= $grouplabel.': '.$groupname;
4673 } else {
4674 $output .= popup_form($urlroot.'&amp;group=', $groupsmenu, 'selectgroup', $currentgroup, '', '', '', true, 'self', $grouplabel);
4677 if ($return) {
4678 return $output;
4679 } else {
4680 echo $output;
4686 * Given a course and a (current) coursemodule
4687 * This function returns a small popup menu with all the
4688 * course activity modules in it, as a navigation menu
4689 * The data is taken from the serialised array stored in
4690 * the course record
4692 * @param course $course A {@link $COURSE} object.
4693 * @param course $cm A {@link $COURSE} object.
4694 * @param string $targetwindow ?
4695 * @return string
4696 * @todo Finish documenting this function
4698 function navmenu($course, $cm=NULL, $targetwindow='self') {
4700 global $CFG, $THEME, $USER;
4702 if (empty($THEME->navmenuwidth)) {
4703 $width = 50;
4704 } else {
4705 $width = $THEME->navmenuwidth;
4708 if ($cm) {
4709 $cm = $cm->id;
4712 if ($course->format == 'weeks') {
4713 $strsection = get_string('week');
4714 } else {
4715 $strsection = get_string('topic');
4717 $strjumpto = get_string('jumpto');
4719 /// Casting $course->modinfo to string prevents one notice when the field is null
4720 if (!$modinfo = unserialize((string)$course->modinfo)) {
4721 return '';
4723 $context = get_context_instance(CONTEXT_COURSE, $course->id);
4725 $section = -1;
4726 $selected = '';
4727 $url = '';
4728 $previousmod = NULL;
4729 $backmod = NULL;
4730 $nextmod = NULL;
4731 $selectmod = NULL;
4732 $logslink = NULL;
4733 $flag = false;
4734 $menu = array();
4735 $menustyle = array();
4737 $sections = get_records('course_sections','course',$course->id,'section','section,visible,summary');
4739 if (!empty($THEME->makenavmenulist)) { /// A hack to produce an XHTML navmenu list for use in themes
4740 $THEME->navmenulist = navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
4743 foreach ($modinfo as $mod) {
4744 if ($mod->mod == 'label') {
4745 continue;
4748 if ($mod->section > $course->numsections) { /// Don't show excess hidden sections
4749 break;
4752 if ($mod->section > 0 and $section <> $mod->section) {
4753 $thissection = $sections[$mod->section];
4755 if ($thissection->visible or !$course->hiddensections or
4756 has_capability('moodle/course:viewhiddensections', $context)) {
4757 $thissection->summary = strip_tags(format_string($thissection->summary,true));
4758 if ($course->format == 'weeks' or empty($thissection->summary)) {
4759 $menu[] = '--'.$strsection ." ". $mod->section;
4760 } else {
4761 if (strlen($thissection->summary) < ($width-3)) {
4762 $menu[] = '--'.$thissection->summary;
4763 } else {
4764 $menu[] = '--'.substr($thissection->summary, 0, $width).'...';
4770 $section = $mod->section;
4772 //Only add visible or teacher mods to jumpmenu
4773 if ($mod->visible or has_capability('moodle/course:viewhiddenactivities',
4774 get_context_instance(CONTEXT_MODULE, $mod->cm))) {
4775 $url = $mod->mod .'/view.php?id='. $mod->cm;
4776 if ($flag) { // the current mod is the "next" mod
4777 $nextmod = $mod;
4778 $flag = false;
4780 if ($cm == $mod->cm) {
4781 $selected = $url;
4782 $selectmod = $mod;
4783 $backmod = $previousmod;
4784 $flag = true; // set flag so we know to use next mod for "next"
4785 $mod->name = $strjumpto;
4786 $strjumpto = '';
4787 } else {
4788 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
4789 if (strlen($mod->name) > ($width+5)) {
4790 $mod->name = substr($mod->name, 0, $width).'...';
4792 if (!$mod->visible) {
4793 $mod->name = '('.$mod->name.')';
4796 $menu[$url] = $mod->name;
4797 if (empty($THEME->navmenuiconshide)) {
4798 $menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath.'/'.$mod->mod.'/icon.gif);"'; // Unfortunately necessary to do this here
4800 $previousmod = $mod;
4803 //Accessibility: added Alt text, replaced &gt; &lt; with 'silent' character and 'accesshide' text.
4805 if ($selectmod and has_capability('moodle/site:viewreports', $context)) {
4806 $logstext = get_string('alllogs');
4807 $logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
4808 $CFG->frametarget.'onclick="this.target=\''.$CFG->framename.'\';"'.' href="'.
4809 $CFG->wwwroot.'/course/report/log/index.php?chooselog=1&amp;user=0&amp;date=0&amp;id='.
4810 $course->id.'&amp;modid='.$selectmod->cm.'">'.
4811 '<img class="icon log" src="'.$CFG->pixpath.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
4814 if ($backmod) {
4815 $backtext= get_string('activityprev', 'access');
4816 $backmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$backmod->mod.'/view.php" '.
4817 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
4818 '<input type="hidden" name="id" value="'.$backmod->cm.'" />'.
4819 '<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
4820 '</button></fieldset></form></li>';
4822 if ($nextmod) {
4823 $nexttext= get_string('activitynext', 'access');
4824 $nextmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$nextmod->mod.'/view.php" '.
4825 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
4826 '<input type="hidden" name="id" value="'.$nextmod->cm.'" />'.
4827 '<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
4828 '</button></fieldset></form></li>';
4831 return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
4832 '<li>'.popup_form($CFG->wwwroot .'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
4833 '', '', true, $targetwindow, '', $menustyle).'</li>'.
4834 $nextmod . '</ul>'."\n".'</div>';
4838 * Given a course
4839 * This function returns a small popup menu with all the
4840 * course activity modules in it, as a navigation menu
4841 * outputs a simple list structure in XHTML
4842 * The data is taken from the serialised array stored in
4843 * the course record
4845 * @param course $course A {@link $COURSE} object.
4846 * @return string
4847 * @todo Finish documenting this function
4849 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
4851 global $CFG;
4853 $section = -1;
4854 $selected = '';
4855 $url = '';
4856 $previousmod = NULL;
4857 $backmod = NULL;
4858 $nextmod = NULL;
4859 $selectmod = NULL;
4860 $logslink = NULL;
4861 $flag = false;
4862 $menu = array();
4864 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
4866 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
4867 foreach ($modinfo as $mod) {
4868 if ($mod->mod == 'label') {
4869 continue;
4872 if ($mod->section > $course->numsections) { /// Don't show excess hidden sections
4873 break;
4876 if ($mod->section >= 0 and $section <> $mod->section) {
4877 $thissection = $sections[$mod->section];
4879 if ($thissection->visible or !$course->hiddensections or
4880 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
4881 $thissection->summary = strip_tags(format_string($thissection->summary,true));
4882 if (!empty($doneheading)) {
4883 $menu[] = '</ul></li>';
4885 if ($course->format == 'weeks' or empty($thissection->summary)) {
4886 $item = $strsection ." ". $mod->section;
4887 } else {
4888 if (strlen($thissection->summary) < ($width-3)) {
4889 $item = $thissection->summary;
4890 } else {
4891 $item = substr($thissection->summary, 0, $width).'...';
4894 $menu[] = '<li class="section"><span>'.$item.'</span>';
4895 $menu[] = '<ul>';
4896 $doneheading = true;
4900 $section = $mod->section;
4902 //Only add visible or teacher mods to jumpmenu
4903 if ($mod->visible or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_MODULE, $mod->cm))) {
4904 $url = $mod->mod .'/view.php?id='. $mod->cm;
4905 if ($flag) { // the current mod is the "next" mod
4906 $nextmod = $mod;
4907 $flag = false;
4909 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
4910 if (strlen($mod->name) > ($width+5)) {
4911 $mod->name = substr($mod->name, 0, $width).'...';
4913 if (!$mod->visible) {
4914 $mod->name = '('.$mod->name.')';
4916 $class = 'activity '.$mod->mod;
4917 $class .= ($cmid == $mod->cm) ? ' selected' : '';
4918 $menu[] = '<li class="'.$class.'">'.
4919 '<img src="'.$CFG->modpixpath.'/'.$mod->mod.'/icon.gif" alt="" />'.
4920 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
4921 $previousmod = $mod;
4924 if ($doneheading) {
4925 $menu[] = '</ul></li>';
4927 $menu[] = '</ul></li></ul>';
4929 return implode("\n", $menu);
4933 * Prints form items with the names $day, $month and $year
4935 * @param string $day fieldname
4936 * @param string $month fieldname
4937 * @param string $year fieldname
4938 * @param int $currenttime A default timestamp in GMT
4939 * @param boolean $return
4941 function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
4943 if (!$currenttime) {
4944 $currenttime = time();
4946 $currentdate = usergetdate($currenttime);
4948 for ($i=1; $i<=31; $i++) {
4949 $days[$i] = $i;
4951 for ($i=1; $i<=12; $i++) {
4952 $months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
4954 for ($i=1970; $i<=2020; $i++) {
4955 $years[$i] = $i;
4957 return choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', $return)
4958 .choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', $return)
4959 .choose_from_menu($years, $year, $currentdate['year'], '', '', '0', $return);
4964 *Prints form items with the names $hour and $minute
4966 * @param string $hour fieldname
4967 * @param string ? $minute fieldname
4968 * @param $currenttime A default timestamp in GMT
4969 * @param int $step minute spacing
4970 * @param boolean $return
4972 function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
4974 if (!$currenttime) {
4975 $currenttime = time();
4977 $currentdate = usergetdate($currenttime);
4978 if ($step != 1) {
4979 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
4981 for ($i=0; $i<=23; $i++) {
4982 $hours[$i] = sprintf("%02d",$i);
4984 for ($i=0; $i<=59; $i+=$step) {
4985 $minutes[$i] = sprintf("%02d",$i);
4988 return choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',$return)
4989 .choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',$return);
4993 * Prints time limit value selector
4995 * @uses $CFG
4996 * @param int $timelimit default
4997 * @param string $unit
4998 * @param string $name
4999 * @param boolean $return
5001 function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
5003 global $CFG;
5005 if ($unit) {
5006 $unit = ' '.$unit;
5009 // Max timelimit is sessiontimeout - 10 minutes.
5010 $maxvalue = ($CFG->sessiontimeout / 60) - 10;
5012 for ($i=1; $i<=$maxvalue; $i++) {
5013 $minutes[$i] = $i.$unit;
5015 return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
5019 * Prints a grade menu (as part of an existing form) with help
5020 * Showing all possible numerical grades and scales
5022 * @uses $CFG
5023 * @param int $courseid ?
5024 * @param string $name ?
5025 * @param string $current ?
5026 * @param boolean $includenograde ?
5027 * @todo Finish documenting this function
5029 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
5031 global $CFG;
5033 $output = '';
5034 $strscale = get_string('scale');
5035 $strscales = get_string('scales');
5037 $scales = get_scales_menu($courseid);
5038 foreach ($scales as $i => $scalename) {
5039 $grades[-$i] = $strscale .': '. $scalename;
5041 if ($includenograde) {
5042 $grades[0] = get_string('nograde');
5044 for ($i=100; $i>=1; $i--) {
5045 $grades[$i] = $i;
5047 $output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
5049 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5050 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5051 $linkobject, 400, 500, $strscales, 'none', true);
5053 if ($return) {
5054 return $output;
5055 } else {
5056 echo $output;
5061 * Prints a scale menu (as part of an existing form) including help button
5062 * Just like {@link print_grade_menu()} but without the numeric grades
5064 * @param int $courseid ?
5065 * @param string $name ?
5066 * @param string $current ?
5067 * @todo Finish documenting this function
5069 function print_scale_menu($courseid, $name, $current, $return=false) {
5071 global $CFG;
5073 $output = '';
5074 $strscales = get_string('scales');
5075 $output .= choose_from_menu(get_scales_menu($courseid), $name, $current, '', '', 0, true);
5077 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5078 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5079 $linkobject, 400, 500, $strscales, 'none', true);
5080 if ($return) {
5081 return $output;
5082 } else {
5083 echo $output;
5088 * Prints a help button about a scale
5090 * @uses $CFG
5091 * @param id $courseid ?
5092 * @param object $scale ?
5093 * @todo Finish documenting this function
5095 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
5097 global $CFG;
5099 $output = '';
5100 $strscales = get_string('scales');
5102 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5103 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true&amp;scaleid='. $scale->id, 'ratingscale',
5104 $linkobject, 400, 500, $scale->name, 'none', true);
5105 if ($return) {
5106 return $output;
5107 } else {
5108 echo $output;
5113 * Print an error page displaying an error message.
5114 * Old method, don't call directly in new code - use print_error instead.
5117 * @uses $SESSION
5118 * @uses $CFG
5119 * @param string $message The message to display to the user about the error.
5120 * @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.
5122 function error ($message, $link='') {
5124 global $CFG, $SESSION;
5125 $message = clean_text($message); // In case nasties are in here
5127 if (defined('FULLME') && FULLME == 'cron') {
5128 // Errors in cron should be mtrace'd.
5129 mtrace($message);
5130 die;
5133 if (! defined('HEADER_PRINTED')) {
5134 //header not yet printed
5135 @header('HTTP/1.0 404 Not Found');
5136 print_header(get_string('error'));
5139 echo '<br />';
5140 print_simple_box($message, '', '', '', '', 'errorbox');
5142 debugging('Stack trace:', DEBUG_DEVELOPER);
5144 // in case we are logging upgrade in admin/index.php stop it
5145 if (function_exists('upgrade_log_finish')) {
5146 upgrade_log_finish();
5149 if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
5150 if ( !empty($SESSION->fromurl) ) {
5151 $link = $SESSION->fromurl;
5152 unset($SESSION->fromurl);
5153 } else {
5154 $link = $CFG->wwwroot .'/';
5158 if (!empty($link)) {
5159 print_continue($link);
5162 print_footer();
5164 for ($i=0;$i<512;$i++) { // Padding to help IE work with 404
5165 echo ' ';
5168 die;
5172 * Print an error page displaying an error message. New method - use this for new code.
5174 * @uses $SESSION
5175 * @uses $CFG
5176 * @param string $errorcode The name of the string from error.php to print
5177 * @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.
5178 * @param object $a Extra words and phrases that might be required in the error string
5180 function print_error ($errorcode, $module='', $link='', $a=NULL) {
5182 global $CFG;
5184 if (empty($module) || $module == 'moodle' || $module == 'core') {
5185 $module = 'error';
5186 $modulelink = 'moodle';
5187 } else {
5188 $modulelink = $module;
5191 if (!empty($CFG->errordocroot)) {
5192 $errordocroot = $CFG->errordocroot;
5193 } else if (!empty($CFG->docroot)) {
5194 $errordocroot = $CFG->docroot;
5195 } else {
5196 $errordocroot = 'http://docs.moodle.org';
5199 $message = '<p class="errormessage">'.get_string($errorcode, $module, $a).'</p>'.
5200 '<p class="errorcode">'.
5201 '<a href="'.$errordocroot.'/en/error/'.$modulelink.'/'.$errorcode.'">'.
5202 get_string('moreinformation').'</a></p>';
5203 error($message, $link);
5206 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
5207 * Should be used only with htmleditor or textarea.
5208 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
5209 * helpbutton.
5210 * @return string
5212 function editorhelpbutton(){
5213 global $CFG, $SESSION;
5214 $items = func_get_args();
5215 $i = 1;
5216 $urlparams = array();
5217 $titles = array();
5218 foreach ($items as $item){
5219 if (is_array($item)){
5220 $urlparams[] = "keyword$i=".urlencode($item[0]);
5221 $urlparams[] = "title$i=".urlencode($item[1]);
5222 if (isset($item[2])){
5223 $urlparams[] = "module$i=".urlencode($item[2]);
5225 $titles[] = trim($item[1], ". \t");
5226 }elseif (is_string($item)){
5227 $urlparams[] = "button$i=".urlencode($item);
5228 switch ($item){
5229 case 'reading' :
5230 $titles[] = get_string("helpreading");
5231 break;
5232 case 'writing' :
5233 $titles[] = get_string("helpwriting");
5234 break;
5235 case 'questions' :
5236 $titles[] = get_string("helpquestions");
5237 break;
5238 case 'emoticons' :
5239 $titles[] = get_string("helpemoticons");
5240 break;
5241 case 'richtext' :
5242 $titles[] = get_string('helprichtext');
5243 break;
5244 case 'text' :
5245 $titles[] = get_string('helptext');
5246 break;
5247 default :
5248 error('Unknown help topic '.$item);
5251 $i++;
5253 if (count($titles)>1){
5254 //join last two items with an 'and'
5255 $a = new object();
5256 $a->one = $titles[count($titles) - 2];
5257 $a->two = $titles[count($titles) - 1];
5258 $titles[count($titles) - 2] = get_string('and', '', $a);
5259 unset($titles[count($titles) - 1]);
5261 $alttag = join (', ', $titles);
5263 $paramstring = join('&', $urlparams);
5264 $linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath .'/help.gif" />';
5265 return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), $alttag, $linkobject, 400, 500, $alttag, 'none', true);
5269 * Print a help button.
5271 * @uses $CFG
5272 * @param string $page The keyword that defines a help page
5273 * @param string $title The title of links, rollover tips, alt tags etc
5274 * 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
5275 * @param string $module Which module is the page defined in
5276 * @param mixed $image Use a help image for the link? (true/false/"both")
5277 * @param boolean $linktext If true, display the title next to the help icon.
5278 * @param string $text If defined then this text is used in the page, and
5279 * the $page variable is ignored.
5280 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
5281 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
5282 * @return string
5283 * @todo Finish documenting this function
5285 function helpbutton ($page, $title='', $module='moodle', $image=true, $linktext=false, $text='', $return=false,
5286 $imagetext='') {
5287 global $CFG, $course;
5289 // fix for MDL-7734
5290 if (!empty($course->lang)) {
5291 $forcelang = $course->lang;
5292 } else {
5293 $forcelang = '';
5296 if ($module == '') {
5297 $module = 'moodle';
5300 $tooltip = get_string('helpprefix2', '', trim($title, ". \t"));
5302 $linkobject = '';
5304 if ($image) {
5305 if ($linktext) {
5306 // MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
5307 $linkobject .= $title.'&nbsp;';
5308 $tooltip = get_string('helpwiththis');
5310 if ($imagetext) {
5311 $linkobject .= $imagetext;
5312 } else {
5313 $linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
5314 $CFG->pixpath .'/help.gif" />';
5316 } else {
5317 $linkobject .= $tooltip;
5320 $tooltip .= ' ('.get_string('newwindow').')'; // Warn users about new window for Accessibility
5322 // fix for MDL-7734
5323 if ($text) {
5324 $url = '/help.php?module='. $module .'&amp;text='. s(urlencode($text).'&amp;forcelang='.$forcelang);
5325 } else {
5326 $url = '/help.php?module='. $module .'&amp;file='. $page .'.html&amp;forcelang='.$forcelang;
5329 $link = '<span class="helplink">'.
5330 link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
5331 '</span>';
5333 if ($return) {
5334 return $link;
5335 } else {
5336 echo $link;
5341 * Print a help button.
5343 * Prints a special help button that is a link to the "live" emoticon popup
5344 * @uses $CFG
5345 * @uses $SESSION
5346 * @param string $form ?
5347 * @param string $field ?
5348 * @todo Finish documenting this function
5350 function emoticonhelpbutton($form, $field, $return = false) {
5352 global $CFG, $SESSION;
5354 $SESSION->inserttextform = $form;
5355 $SESSION->inserttextfield = $field;
5356 $imagetext = '<img src="' . $CFG->pixpath . '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
5357 $help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
5358 if (!$return){
5359 echo $help;
5360 } else {
5361 return $help;
5366 * Print a help button.
5368 * Prints a special help button for html editors (htmlarea in this case)
5369 * @uses $CFG
5371 function editorshortcutshelpbutton() {
5373 global $CFG;
5374 $imagetext = '<img src="' . $CFG->httpswwwroot . '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
5375 get_string('editorshortcutkeys').'" class="iconkbhelp" />';
5377 return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
5381 * Print a message and exit.
5383 * @uses $CFG
5384 * @param string $message ?
5385 * @param string $link ?
5386 * @todo Finish documenting this function
5388 function notice ($message, $link='', $course=NULL) {
5389 global $CFG, $SITE;
5391 $message = clean_text($message);
5393 print_box($message, 'generalbox', 'notice');
5394 print_continue($link);
5396 if (empty($course)) {
5397 print_footer($SITE);
5398 } else {
5399 print_footer($course);
5401 exit;
5405 * Print a message along with "Yes" and "No" links for the user to continue.
5407 * @param string $message The text to display
5408 * @param string $linkyes The link to take the user to if they choose "Yes"
5409 * @param string $linkno The link to take the user to if they choose "No"
5410 * TODO Document remaining arguments
5412 function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
5414 global $CFG;
5416 $message = clean_text($message);
5417 $linkyes = clean_text($linkyes);
5418 $linkno = clean_text($linkno);
5420 print_box_start('generalbox', 'notice');
5421 echo '<p>'. $message .'</p>';
5422 echo '<div class="buttons">';
5423 print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename);
5424 print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename);
5425 echo '</div>';
5426 print_box_end();
5430 * Provide an definition of error_get_last for PHP before 5.2.0. This simply
5431 * returns NULL, since there is not way to get the right answer.
5433 if (!function_exists('error_get_last')) {
5434 // the eval is needed to prevent PHP 5.2+ from getting a parse error!
5435 eval('
5436 function error_get_last() {
5437 return NULL;
5443 * Redirects the user to another page, after printing a notice
5445 * @param string $url The url to take the user to
5446 * @param string $message The text message to display to the user about the redirect, if any
5447 * @param string $delay How long before refreshing to the new page at $url?
5448 * @todo '&' needs to be encoded into '&amp;' for XHTML compliance,
5449 * however, this is not true for javascript. Therefore we
5450 * first decode all entities in $url (since we cannot rely on)
5451 * the correct input) and then encode for where it's needed
5452 * echo "<script type='text/javascript'>alert('Redirect $url');</script>";
5454 function redirect($url, $message='', $delay=-1) {
5456 global $CFG;
5458 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
5459 $url = sid_process_url($url);
5462 $message = clean_text($message);
5464 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
5465 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
5466 $url = str_replace('&amp;', '&', $encodedurl);
5468 /// At developer debug level. Don't redirect if errors have been printed on screen.
5469 /// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
5470 $lasterror = error_get_last();
5471 $error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER));
5472 $errorprinted = debugging('', DEBUG_ALL) && $CFG->debugdisplay && $error;
5473 if ($errorprinted) {
5474 $message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
5477 /// when no message and header printed yet, try to redirect
5478 if (empty($message) and !defined('HEADER_PRINTED')) {
5480 // Technically, HTTP/1.1 requires Location: header to contain
5481 // the absolute path. (In practice browsers accept relative
5482 // paths - but still, might as well do it properly.)
5483 // This code turns relative into absolute.
5484 if (!preg_match('|^[a-z]+:|', $url)) {
5485 // Get host name http://www.wherever.com
5486 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
5487 if (preg_match('|^/|', $url)) {
5488 // URLs beginning with / are relative to web server root so we just add them in
5489 $url = $hostpart.$url;
5490 } else {
5491 // URLs not beginning with / are relative to path of current script, so add that on.
5492 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
5494 // Replace all ..s
5495 while (true) {
5496 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
5497 if ($newurl == $url) {
5498 break;
5500 $url = $newurl;
5504 $delay = 0;
5505 //try header redirection first
5506 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
5507 @header('Location: '.$url);
5508 //another way for older browsers and already sent headers (eg trailing whitespace in config.php)
5509 echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
5510 echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
5511 die;
5514 if ($delay == -1) {
5515 $delay = 3; // if no delay specified wait 3 seconds
5517 if (! defined('HEADER_PRINTED')) {
5518 // this type of redirect might not be working in some browsers - such as lynx :-(
5519 print_header('', '', '', '', $errorprinted ? '' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
5520 $delay += 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
5522 echo '<div style="text-align:center">';
5523 echo '<div>'. $message .'</div>';
5524 echo '<div>( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
5525 echo '</div>';
5527 if (!$errorprinted) {
5529 <script type="text/javascript">
5530 //<![CDATA[
5532 function redirect() {
5533 document.location.replace('<?php echo addslashes_js($url) ?>');
5535 setTimeout("redirect()", <?php echo ($delay * 1000) ?>);
5536 //]]>
5537 </script>
5538 <?php
5541 print_footer('none');
5542 die;
5546 * Print a bold message in an optional color.
5548 * @param string $message The message to print out
5549 * @param string $style Optional style to display message text in
5550 * @param string $align Alignment option
5551 * @param bool $return whether to return an output string or echo now
5553 function notify($message, $style='notifyproblem', $align='center', $return=false) {
5554 if ($style == 'green') {
5555 $style = 'notifysuccess'; // backward compatible with old color system
5558 $message = clean_text($message);
5560 $output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."<br />\n";
5562 if ($return) {
5563 return $output;
5565 echo $output;
5570 * Given an email address, this function will return an obfuscated version of it
5572 * @param string $email The email address to obfuscate
5573 * @return string
5575 function obfuscate_email($email) {
5577 $i = 0;
5578 $length = strlen($email);
5579 $obfuscated = '';
5580 while ($i < $length) {
5581 if (rand(0,2)) {
5582 $obfuscated.='%'.dechex(ord($email{$i}));
5583 } else {
5584 $obfuscated.=$email{$i};
5586 $i++;
5588 return $obfuscated;
5592 * This function takes some text and replaces about half of the characters
5593 * with HTML entity equivalents. Return string is obviously longer.
5595 * @param string $plaintext The text to be obfuscated
5596 * @return string
5598 function obfuscate_text($plaintext) {
5600 $i=0;
5601 $length = strlen($plaintext);
5602 $obfuscated='';
5603 $prev_obfuscated = false;
5604 while ($i < $length) {
5605 $c = ord($plaintext{$i});
5606 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
5607 if ($prev_obfuscated and $numerical ) {
5608 $obfuscated.='&#'.ord($plaintext{$i}).';';
5609 } else if (rand(0,2)) {
5610 $obfuscated.='&#'.ord($plaintext{$i}).';';
5611 $prev_obfuscated = true;
5612 } else {
5613 $obfuscated.=$plaintext{$i};
5614 $prev_obfuscated = false;
5616 $i++;
5618 return $obfuscated;
5622 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
5623 * to generate a fully obfuscated email link, ready to use.
5625 * @param string $email The email address to display
5626 * @param string $label The text to dispalyed as hyperlink to $email
5627 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
5628 * @return string
5630 function obfuscate_mailto($email, $label='', $dimmed=false) {
5632 if (empty($label)) {
5633 $label = $email;
5635 if ($dimmed) {
5636 $title = get_string('emaildisable');
5637 $dimmed = ' class="dimmed"';
5638 } else {
5639 $title = '';
5640 $dimmed = '';
5642 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
5643 obfuscate_text('mailto'), obfuscate_email($email),
5644 obfuscate_text($label));
5648 * Prints a single paging bar to provide access to other pages (usually in a search)
5650 * @param int $totalcount Thetotal number of entries available to be paged through
5651 * @param int $page The page you are currently viewing
5652 * @param int $perpage The number of entries that should be shown per page
5653 * @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.
5654 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
5655 * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
5656 * @param bool $nocurr do not display the current page as a link
5657 * @param bool $return whether to return an output string or echo now
5658 * @return bool or string
5660 function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
5661 $maxdisplay = 18;
5662 $output = '';
5664 if ($totalcount > $perpage) {
5665 $output .= '<div class="paging">';
5666 $output .= get_string('page') .':';
5667 if ($page > 0) {
5668 $pagenum = $page - 1;
5669 if (!is_a($baseurl, 'moodle_url')){
5670 $output .= '&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>)&nbsp;';
5671 } else {
5672 $output .= '&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>)&nbsp;';
5675 $lastpage = ceil($totalcount / $perpage);
5676 if ($page > 15) {
5677 $startpage = $page - 10;
5678 if (!is_a($baseurl, 'moodle_url')){
5679 $output .= '&nbsp;<a href="'. $baseurl . $pagevar .'=0">1</a>&nbsp;...';
5680 } else {
5681 $output .= '&nbsp;<a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a>&nbsp;...';
5683 } else {
5684 $startpage = 0;
5686 $currpage = $startpage;
5687 $displaycount = 0;
5688 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
5689 $displaypage = $currpage+1;
5690 if ($page == $currpage && empty($nocurr)) {
5691 $output .= '&nbsp;&nbsp;'. $displaypage;
5692 } else {
5693 if (!is_a($baseurl, 'moodle_url')){
5694 $output .= '&nbsp;&nbsp;<a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
5695 } else {
5696 $output .= '&nbsp;&nbsp;<a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
5700 $displaycount++;
5701 $currpage++;
5703 if ($currpage < $lastpage) {
5704 $lastpageactual = $lastpage - 1;
5705 if (!is_a($baseurl, 'moodle_url')){
5706 $output .= '&nbsp;...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a>&nbsp;';
5707 } else {
5708 $output .= '&nbsp;...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a>&nbsp;';
5711 $pagenum = $page + 1;
5712 if ($pagenum != $displaypage) {
5713 if (!is_a($baseurl, 'moodle_url')){
5714 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
5715 } else {
5716 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
5719 $output .= '</div>';
5722 if ($return) {
5723 return $output;
5726 echo $output;
5727 return true;
5731 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
5732 * will transform it to html entities
5734 * @param string $text Text to search for nolink tag in
5735 * @return string
5737 function rebuildnolinktag($text) {
5739 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
5741 return $text;
5745 * Prints a nice side block with an optional header. The content can either
5746 * be a block of HTML or a list of text with optional icons.
5748 * @param string $heading Block $title embedded in HTML tags, for example <h2>.
5749 * @param string $content ?
5750 * @param array $list ?
5751 * @param array $icons ?
5752 * @param string $footer ?
5753 * @param array $attributes ?
5754 * @param string $title Plain text title, as embedded in the $heading.
5755 * @todo Finish documenting this function. Show example of various attributes, etc.
5757 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
5759 //Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
5760 static $block_id = 0;
5761 $block_id++;
5762 if (empty($heading)) {
5763 $skip_text = get_string('skipblock', 'access').' '.$block_id;
5765 else {
5766 $skip_text = get_string('skipa', 'access', strip_tags($title));
5768 $skip_link = '<a href="#sb-'.$block_id.'" class="skip-block" title="'.$skip_text.'">'."\n".'<span class="accesshide">'.$skip_text.'</span>'."\n".'</a>';
5769 $skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
5771 if (! empty($heading)) {
5772 $heading = $skip_link . $heading;
5774 /*else { //ELSE: I think a single link on a page, "Skip block 4" is too confusing - don't print.
5775 echo $skip_link;
5778 print_side_block_start($heading, $attributes);
5780 if ($content) {
5781 echo $content;
5782 if ($footer) {
5783 echo '<div class="footer">'. $footer .'</div>';
5785 } else {
5786 if ($list) {
5787 $row = 0;
5788 //Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
5789 echo "\n<ul class='list'>\n";
5790 foreach ($list as $key => $string) {
5791 echo '<li class="r'. $row .'">';
5792 if ($icons) {
5793 echo '<div class="icon column c0">'. $icons[$key] .'</div>';
5795 echo '<div class="column c1">'. $string .'</div>';
5796 echo "</li>\n";
5797 $row = $row ? 0:1;
5799 echo "</ul>\n";
5801 if ($footer) {
5802 echo '<div class="footer">'. $footer .'</div>';
5807 print_side_block_end($attributes);
5808 echo $skip_dest;
5812 * Starts a nice side block with an optional header.
5814 * @param string $heading ?
5815 * @param array $attributes ?
5816 * @todo Finish documenting this function
5818 function print_side_block_start($heading='', $attributes = array()) {
5820 global $CFG, $THEME;
5822 if (!empty($THEME->customcorners)) {
5823 require_once($CFG->dirroot.'/lib/custom_corners_lib.php');
5826 // If there are no special attributes, give a default CSS class
5827 if (empty($attributes) || !is_array($attributes)) {
5828 $attributes = array('class' => 'sideblock');
5830 } else if(!isset($attributes['class'])) {
5831 $attributes['class'] = 'sideblock';
5833 } else if(!strpos($attributes['class'], 'sideblock')) {
5834 $attributes['class'] .= ' sideblock';
5837 // OK, the class is surely there and in addition to anything
5838 // else, it's tagged as a sideblock
5842 // IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
5844 // If there is a cookie to hide this thing, start it hidden
5845 if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
5846 $attributes['class'] = 'hidden '.$attributes['class'];
5850 $attrtext = '';
5851 foreach ($attributes as $attr => $val) {
5852 $attrtext .= ' '.$attr.'="'.$val.'"';
5855 echo '<div '.$attrtext.'>';
5857 if (!empty($THEME->customcorners)) {
5858 echo '<div class="wrap">'."\n";
5860 if ($heading) {
5861 //Accessibility: replaced <div> with H2; no, H2 more appropriate in moodleblock.class.php: _title_html.
5862 // echo '<div class="header">'.$heading.'</div>';
5863 echo '<div class="header">';
5864 if (!empty($THEME->customcorners)) {
5865 echo '<div class="bt"><div>&nbsp;</div></div>';
5866 echo '<div class="i1"><div class="i2">';
5867 echo '<div class="i3">';
5869 echo $heading;
5870 if (!empty($THEME->customcorners)) {
5871 echo '</div></div></div>';
5873 echo '</div>';
5874 } else {
5875 if (!empty($THEME->customcorners)) {
5876 echo '<div class="bt"><div>&nbsp;</div></div>';
5880 if (!empty($THEME->customcorners)) {
5881 echo '<div class="i1"><div class="i2">';
5882 echo '<div class="i3">';
5884 echo '<div class="content">';
5890 * Print table ending tags for a side block box.
5892 function print_side_block_end($attributes = array()) {
5893 global $CFG, $THEME;
5895 echo '</div>';
5897 if (!empty($THEME->customcorners)) {
5898 require_once($CFG->dirroot.'/lib/custom_corners_lib.php');
5899 print_custom_corners_end();
5902 echo '</div>';
5904 // IE workaround: if I do it THIS way, it works! WTF?
5905 if (!empty($CFG->allowuserblockhiding) && isset($attributes['id'])) {
5906 echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].'"); '.
5907 "\n//]]>\n".'</script>';
5914 * Prints out code needed for spellchecking.
5915 * Original idea by Ludo (Marc Alier).
5917 * Opening CDATA and <script> are output by weblib::use_html_editor()
5918 * @uses $CFG
5919 * @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
5920 * @param boolean $return If false, echos the code instead of returning it
5921 * @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
5923 function print_speller_code ($usehtmleditor=false, $return=false) {
5924 global $CFG;
5925 $str = '';
5927 if(!$usehtmleditor) {
5928 $str .= 'function openSpellChecker() {'."\n";
5929 $str .= "\tvar speller = new spellChecker();\n";
5930 $str .= "\tspeller.popUpUrl = \"" . $CFG->wwwroot ."/lib/speller/spellchecker.html\";\n";
5931 $str .= "\tspeller.spellCheckScript = \"". $CFG->wwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
5932 $str .= "\tspeller.spellCheckAll();\n";
5933 $str .= '}'."\n";
5934 } else {
5935 $str .= "function spellClickHandler(editor, buttonId) {\n";
5936 $str .= "\teditor._textArea.value = editor.getHTML();\n";
5937 $str .= "\tvar speller = new spellChecker( editor._textArea );\n";
5938 $str .= "\tspeller.popUpUrl = \"" . $CFG->wwwroot ."/lib/speller/spellchecker.html\";\n";
5939 $str .= "\tspeller.spellCheckScript = \"". $CFG->wwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
5940 $str .= "\tspeller._moogle_edit=1;\n";
5941 $str .= "\tspeller._editor=editor;\n";
5942 $str .= "\tspeller.openChecker();\n";
5943 $str .= '}'."\n";
5946 if ($return) {
5947 return $str;
5949 echo $str;
5953 * Print button for spellchecking when editor is disabled
5955 function print_speller_button () {
5956 echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
5960 function page_id_and_class(&$getid, &$getclass) {
5961 // Create class and id for this page
5962 global $CFG, $ME;
5964 static $class = NULL;
5965 static $id = NULL;
5967 if (empty($CFG->pagepath)) {
5968 $CFG->pagepath = $ME;
5971 if (empty($class) || empty($id)) {
5972 $path = str_replace($CFG->httpswwwroot.'/', '', $CFG->pagepath); //Because the page could be HTTPSPAGEREQUIRED
5973 $path = str_replace('.php', '', $path);
5974 if (substr($path, -1) == '/') {
5975 $path .= 'index';
5977 if (empty($path) || $path == 'index') {
5978 $id = 'site-index';
5979 $class = 'course';
5980 } else if (substr($path, 0, 5) == 'admin') {
5981 $id = str_replace('/', '-', $path);
5982 $class = 'admin';
5983 } else {
5984 $id = str_replace('/', '-', $path);
5985 $class = explode('-', $id);
5986 array_pop($class);
5987 $class = implode('-', $class);
5991 $getid = $id;
5992 $getclass = $class;
5996 * Prints a maintenance message from /maintenance.html
5998 function print_maintenance_message () {
5999 global $CFG, $SITE;
6001 print_header(strip_tags($SITE->fullname), $SITE->fullname, 'home');
6002 print_simple_box_start('center');
6003 print_heading(get_string('sitemaintenance', 'admin'));
6004 @include($CFG->dataroot.'/1/maintenance.html');
6005 print_simple_box_end();
6006 print_footer();
6010 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
6012 function adjust_allowed_tags() {
6014 global $CFG, $ALLOWED_TAGS;
6016 if (!empty($CFG->allowobjectembed)) {
6017 $ALLOWED_TAGS .= '<embed><object>';
6021 /// Some code to print tabs
6023 /// A class for tabs
6024 class tabobject {
6025 var $id;
6026 var $link;
6027 var $text;
6028 var $linkedwhenselected;
6030 /// A constructor just because I like constructors
6031 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
6032 $this->id = $id;
6033 $this->link = $link;
6034 $this->text = $text;
6035 $this->title = $title ? $title : $text;
6036 $this->linkedwhenselected = $linkedwhenselected;
6043 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
6045 * @param array $tabrows An array of rows where each row is an array of tab objects
6046 * @param string $selected The id of the selected tab (whatever row it's on)
6047 * @param array $inactive An array of ids of inactive tabs that are not selectable.
6048 * @param array $activated An array of ids of other tabs that are currently activated
6050 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
6051 global $CFG;
6053 /// $inactive must be an array
6054 if (!is_array($inactive)) {
6055 $inactive = array();
6058 /// $activated must be an array
6059 if (!is_array($activated)) {
6060 $activated = array();
6063 /// Convert the tab rows into a tree that's easier to process
6064 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
6065 return false;
6068 /// Print out the current tree of tabs (this function is recursive)
6070 $output = convert_tree_to_html($tree);
6072 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
6074 /// We're done!
6076 if ($return) {
6077 return $output;
6079 echo $output;
6083 function convert_tree_to_html($tree, $row=0) {
6085 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
6087 $first = true;
6088 $count = count($tree);
6090 foreach ($tree as $tab) {
6091 $count--; // countdown to zero
6093 $liclass = '';
6095 if ($first && ($count == 0)) { // Just one in the row
6096 $liclass = 'first last';
6097 $first = false;
6098 } else if ($first) {
6099 $liclass = 'first';
6100 $first = false;
6101 } else if ($count == 0) {
6102 $liclass = 'last';
6105 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
6106 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
6109 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
6110 if ($tab->selected) {
6111 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
6112 } else if ($tab->active) {
6113 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
6117 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
6119 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
6120 $str .= '<a href="#" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
6121 } else {
6122 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
6125 if (!empty($tab->subtree)) {
6126 $str .= convert_tree_to_html($tab->subtree, $row+1);
6127 } else if ($tab->selected) {
6128 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
6131 $str .= ' </li>'."\n";
6133 $str .= '</ul>'."\n";
6135 return $str;
6139 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
6141 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
6143 $tabrows = array_reverse($tabrows);
6145 $subtree = array();
6147 foreach ($tabrows as $row) {
6148 $tree = array();
6150 foreach ($row as $tab) {
6151 $tab->inactive = in_array((string)$tab->id, $inactive);
6152 $tab->active = in_array((string)$tab->id, $activated);
6153 $tab->selected = (string)$tab->id == $selected;
6155 if ($tab->active || $tab->selected) {
6156 if ($subtree) {
6157 $tab->subtree = $subtree;
6160 $tree[] = $tab;
6162 $subtree = $tree;
6165 return $subtree;
6170 * Returns a string containing a link to the user documentation for the current
6171 * page. Also contains an icon by default. Shown to teachers and admin only.
6173 * @param string $text The text to be displayed for the link
6174 * @param string $iconpath The path to the icon to be displayed
6176 function page_doc_link($text='', $iconpath='') {
6177 global $ME, $COURSE, $CFG;
6179 if (empty($CFG->docroot)) {
6180 return '';
6183 if (empty($COURSE->id)) {
6184 $context = get_context_instance(CONTEXT_SYSTEM);
6185 } else {
6186 $context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
6189 if (!has_capability('moodle/site:doclinks', $context)) {
6190 return '';
6193 if (empty($CFG->pagepath)) {
6194 $CFG->pagepath = $ME;
6197 $path = str_replace($CFG->httpswwwroot.'/','', $CFG->pagepath); // Because the page could be HTTPSPAGEREQUIRED
6198 $path = str_replace('.php', '', $path);
6200 if (empty($path)) { // Not for home page
6201 return '';
6203 return doc_link($path, $text, $iconpath);
6207 * Returns a string containing a link to the user documentation.
6208 * Also contains an icon by default. Shown to teachers and admin only.
6210 * @param string $path The page link after doc root and language, no
6211 * leading slash.
6212 * @param string $text The text to be displayed for the link
6213 * @param string $iconpath The path to the icon to be displayed
6215 function doc_link($path='', $text='', $iconpath='') {
6216 global $CFG;
6218 if (empty($CFG->docroot)) {
6219 return '';
6222 $target = '';
6223 if (!empty($CFG->doctonewwindow)) {
6224 $target = ' target="_blank"';
6227 $lang = str_replace('_utf8', '', current_language());
6229 $str = '<a href="' .$CFG->docroot. '/' .$lang. '/' .$path. '"' .$target. '>';
6231 if (empty($iconpath)) {
6232 $iconpath = $CFG->httpswwwroot . '/pix/docs.gif';
6235 // alt left blank intentionally to prevent repetition in screenreaders
6236 $str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
6238 return $str;
6243 * Returns true if the current site debugging settings are equal or above specified level.
6244 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
6245 * routing of notices is controlled by $CFG->debugdisplay
6246 * eg use like this:
6248 * 1) debugging('a normal debug notice');
6249 * 2) debugging('something really picky', DEBUG_ALL);
6250 * 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
6251 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
6253 * In code blocks controlled by debugging() (such as example 4)
6254 * any output should be routed via debugging() itself, or the lower-level
6255 * trigger_error() or error_log(). Using echo or print will break XHTML
6256 * JS and HTTP headers.
6259 * @param string $message a message to print
6260 * @param int $level the level at which this debugging statement should show
6261 * @return bool
6263 function debugging($message='', $level=DEBUG_NORMAL) {
6265 global $CFG;
6267 if (empty($CFG->debug)) {
6268 return false;
6271 if ($CFG->debug >= $level) {
6272 if ($message) {
6273 $callers = debug_backtrace();
6274 $from = '<ul style="text-align: left">';
6275 foreach ($callers as $caller) {
6276 if (!isset($caller['line'])) {
6277 $caller['line'] = '?'; // probably call_user_func()
6279 if (!isset($caller['file'])) {
6280 $caller['file'] = $CFG->dirroot.'/unknownfile'; // probably call_user_func()
6282 $from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
6283 if (isset($caller['function'])) {
6284 $from .= ': call to ';
6285 if (isset($caller['class'])) {
6286 $from .= $caller['class'] . $caller['type'];
6288 $from .= $caller['function'] . '()';
6290 $from .= '</li>';
6292 $from .= '</ul>';
6293 if (!isset($CFG->debugdisplay)) {
6294 $CFG->debugdisplay = ini_get('display_errors');
6296 if ($CFG->debugdisplay) {
6297 if (!defined('DEBUGGING_PRINTED')) {
6298 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
6300 notify($message . $from, 'notifytiny');
6301 } else {
6302 trigger_error($message . $from, E_USER_NOTICE);
6305 return true;
6307 return false;
6311 * Disable debug messages from debugging(), while keeping PHP error reporting level as is.
6313 function disable_debugging() {
6314 global $CFG;
6315 $CFG->debug = $CFG->debug | 0x80000000; // switch the sign bit in integer number ;-)
6320 * Returns string to add a frame attribute, if required
6322 function frametarget() {
6323 global $CFG;
6325 if (empty($CFG->framename) or ($CFG->framename == '_top')) {
6326 return '';
6327 } else {
6328 return ' target="'.$CFG->framename.'" ';
6333 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
6334 * pages that use bits from many different files in very confusing ways (e.g. blocks).
6335 * @usage print_location_comment(__FILE__, __LINE__);
6336 * @param string $file
6337 * @param integer $line
6338 * @param boolean $return Whether to return or print the comment
6339 * @return mixed Void unless true given as third parameter
6341 function print_location_comment($file, $line, $return = false)
6343 if ($return) {
6344 return "<!-- $file at line $line -->\n";
6345 } else {
6346 echo "<!-- $file at line $line -->\n";
6352 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
6353 * provide this function with the language strings for sortasc and sortdesc.
6354 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
6355 * @param string $direction 'up' or 'down'
6356 * @param string $strsort The language string used for the alt attribute of this image
6357 * @param bool $return Whether to print directly or return the html string
6358 * @return string HTML for the image
6360 * TODO See if this isn't already defined somewhere. If not, move this to weblib
6362 function print_arrow($direction='up', $strsort=null, $return=false) {
6363 global $CFG;
6365 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
6366 return null;
6369 $return = null;
6371 switch ($direction) {
6372 case 'up':
6373 $sortdir = 'asc';
6374 break;
6375 case 'down':
6376 $sortdir = 'desc';
6377 break;
6378 case 'move':
6379 $sortdir = 'asc';
6380 break;
6381 default:
6382 $sortdir = null;
6383 break;
6386 // Prepare language string
6387 $strsort = '';
6388 if (empty($strsort) && !empty($sortdir)) {
6389 $strsort = get_string('sort' . $sortdir, 'grades');
6392 $return = ' <img src="'.$CFG->pixpath.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
6394 if ($return) {
6395 return $return;
6396 } else {
6397 echo $return;
6402 * Returns boolean true if the current language is right-to-left (Hebrew, Arabic etc)
6405 function right_to_left() {
6406 static $result;
6408 if (isset($result)) {
6409 return $result;
6411 return $result = (get_string('thisdirection') == 'rtl');
6416 * Returns swapped left<=>right if in RTL environment.
6417 * part of RTL support
6419 * @param string $align align to check
6420 * @return string
6422 function fix_align_rtl($align) {
6423 if (!right_to_left()) {
6424 return $align;
6426 if ($align=='left') { return 'right'; }
6427 if ($align=='right') { return 'left'; }
6428 return $align;
6432 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: