Whoops - parameters need to match category check and display of course.
[moodle-linuxchix.git] / lib / weblib.php
blob2d2bad076072757d95fd6198d74940dc079e9ace
1 <?php // $Id$
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.com //
9 // //
10 // Copyright (C) 2001-2003 Martin Dougiamas http://dougiamas.com //
11 // //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
16 // //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
21 // //
22 // http://www.gnu.org/copyleft/gpl.html //
23 // //
24 ///////////////////////////////////////////////////////////////////////////
26 /**
27 * Library of functions for web output
29 * Library of all general-purpose Moodle PHP functions and constants
30 * that produce HTML output
32 * Other main libraries:
33 * - datalib.php - functions that access the database.
34 * - moodlelib.php - general-purpose Moodle functions.
35 * @author Martin Dougiamas
36 * @version $Id$
37 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
38 * @package moodlecore
41 /// We are going to uses filterlib functions here
42 require_once("$CFG->libdir/filterlib.php");
44 require_once("$CFG->libdir/ajax/ajaxlib.php");
46 /// Constants
48 /// Define text formatting types ... eventually we can add Wiki, BBcode etc
50 /**
51 * Does all sorts of transformations and filtering
53 define('FORMAT_MOODLE', '0'); // Does all sorts of transformations and filtering
55 /**
56 * Plain HTML (with some tags stripped)
58 define('FORMAT_HTML', '1'); // Plain HTML (with some tags stripped)
60 /**
61 * Plain text (even tags are printed in full)
63 define('FORMAT_PLAIN', '2'); // Plain text (even tags are printed in full)
65 /**
66 * Wiki-formatted text
67 * Deprecated: left here just to note that '3' is not used (at the moment)
68 * and to catch any latent wiki-like text (which generates an error)
70 define('FORMAT_WIKI', '3'); // Wiki-formatted text
72 /**
73 * Markdown-formatted text http://daringfireball.net/projects/markdown/
75 define('FORMAT_MARKDOWN', '4'); // Markdown-formatted text http://daringfireball.net/projects/markdown/
77 /**
78 * TRUSTTEXT marker - if present in text, text cleaning should be bypassed
80 define('TRUSTTEXT', '#####TRUSTTEXT#####');
83 /**
84 * Allowed tags - string of html tags that can be tested against for safe html tags
85 * @global string $ALLOWED_TAGS
87 global $ALLOWED_TAGS;
88 $ALLOWED_TAGS =
89 '<p><br><b><i><u><font><table><tbody><span><div><tr><td><th><ol><ul><dl><li><dt><dd><h1><h2><h3><h4><h5><h6><hr><img><a><strong><emphasis><em><sup><sub><address><cite><blockquote><pre><strike><param><acronym><nolink><lang><tex><algebra><math><mi><mn><mo><mtext><mspace><ms><mrow><mfrac><msqrt><mroot><mstyle><merror><mpadded><mphantom><mfenced><msub><msup><msubsup><munder><mover><munderover><mmultiscripts><mtable><mtr><mtd><maligngroup><malignmark><maction><cn><ci><apply><reln><fn><interval><inverse><sep><condition><declare><lambda><compose><ident><quotient><exp><factorial><divide><max><min><minus><plus><power><rem><times><root><gcd><and><or><xor><not><implies><forall><exists><abs><conjugate><eq><neq><gt><lt><geq><leq><ln><log><int><diff><partialdiff><lowlimit><uplimit><bvar><degree><set><list><union><intersect><in><notin><subset><prsubset><notsubset><notprsubset><setdiff><sum><product><limit><tendsto><mean><sdev><variance><median><mode><moment><vector><matrix><matrixrow><determinant><transpose><selector><annotation><semantics><annotation-xml><tt><code>';
91 /**
92 * Allowed protocols - array of protocols that are safe to use in links and so on
93 * @global string $ALLOWED_PROTOCOLS
95 $ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms',
96 'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style',
97 'border', 'margin', 'padding', 'background'); // CSS as well to get through kses
100 /// Functions
103 * Add quotes to HTML characters
105 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
106 * This function is very similar to {@link p()}
108 * @param string $var the string potentially containing HTML characters
109 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
110 * true should be used to print data from forms and false for data from DB.
111 * @return string
113 function s($var, $strip=false) {
115 if ($var == '0') { // for integer 0, boolean false, string '0'
116 return '0';
119 if ($strip) {
120 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars(stripslashes_safe($var)));
121 } else {
122 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars($var));
127 * Add quotes to HTML characters
129 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
130 * This function is very similar to {@link s()}
132 * @param string $var the string potentially containing HTML characters
133 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
134 * true should be used to print data from forms and false for data from DB.
135 * @return string
137 function p($var, $strip=false) {
138 echo s($var, $strip);
142 * Does proper javascript quoting.
143 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
145 * @since 1.8 - 22/02/2007
146 * @param mixed value
147 * @return mixed quoted result
149 function addslashes_js($var) {
150 if (is_string($var)) {
151 $var = str_replace('\\', '\\\\', $var);
152 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
153 $var = str_replace('</', '<\/', $var); // XHTML compliance
154 } else if (is_array($var)) {
155 $var = array_map('addslashes_js', $var);
156 } else if (is_object($var)) {
157 $a = get_object_vars($var);
158 foreach ($a as $key=>$value) {
159 $a[$key] = addslashes_js($value);
161 $var = (object)$a;
163 return $var;
167 * Remove query string from url
169 * Takes in a URL and returns it without the querystring portion
171 * @param string $url the url which may have a query string attached
172 * @return string
174 function strip_querystring($url) {
176 if ($commapos = strpos($url, '?')) {
177 return substr($url, 0, $commapos);
178 } else {
179 return $url;
184 * Returns the URL of the HTTP_REFERER, less the querystring portion if required
185 * @return string
187 function get_referer($stripquery=true) {
188 if (isset($_SERVER['HTTP_REFERER'])) {
189 if ($stripquery) {
190 return strip_querystring($_SERVER['HTTP_REFERER']);
191 } else {
192 return $_SERVER['HTTP_REFERER'];
194 } else {
195 return '';
201 * Returns the name of the current script, WITH the querystring portion.
202 * this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
203 * return different things depending on a lot of things like your OS, Web
204 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
205 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
207 * @return string
209 function me() {
211 if (!empty($_SERVER['REQUEST_URI'])) {
212 return $_SERVER['REQUEST_URI'];
214 } else if (!empty($_SERVER['PHP_SELF'])) {
215 if (!empty($_SERVER['QUERY_STRING'])) {
216 return $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
218 return $_SERVER['PHP_SELF'];
220 } else if (!empty($_SERVER['SCRIPT_NAME'])) {
221 if (!empty($_SERVER['QUERY_STRING'])) {
222 return $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
224 return $_SERVER['SCRIPT_NAME'];
226 } else if (!empty($_SERVER['URL'])) { // May help IIS (not well tested)
227 if (!empty($_SERVER['QUERY_STRING'])) {
228 return $_SERVER['URL'] .'?'. $_SERVER['QUERY_STRING'];
230 return $_SERVER['URL'];
232 } else {
233 notify('Warning: Could not find any of these web server variables: $REQUEST_URI, $PHP_SELF, $SCRIPT_NAME or $URL');
234 return false;
239 * Like {@link me()} but returns a full URL
240 * @see me()
241 * @return string
243 function qualified_me() {
245 global $CFG;
247 if (!empty($CFG->wwwroot)) {
248 $url = parse_url($CFG->wwwroot);
251 if (!empty($url['host'])) {
252 $hostname = $url['host'];
253 } else if (!empty($_SERVER['SERVER_NAME'])) {
254 $hostname = $_SERVER['SERVER_NAME'];
255 } else if (!empty($_ENV['SERVER_NAME'])) {
256 $hostname = $_ENV['SERVER_NAME'];
257 } else if (!empty($_SERVER['HTTP_HOST'])) {
258 $hostname = $_SERVER['HTTP_HOST'];
259 } else if (!empty($_ENV['HTTP_HOST'])) {
260 $hostname = $_ENV['HTTP_HOST'];
261 } else {
262 notify('Warning: could not find the name of this server!');
263 return false;
266 if (!empty($url['port'])) {
267 $hostname .= ':'.$url['port'];
268 } else if (!empty($_SERVER['SERVER_PORT'])) {
269 if ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
270 $hostname .= ':'.$_SERVER['SERVER_PORT'];
274 if (isset($_SERVER['HTTPS'])) {
275 $protocol = ($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
276 } else if (isset($_SERVER['SERVER_PORT'])) { # Apache2 does not export $_SERVER['HTTPS']
277 $protocol = ($_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
278 } else {
279 $protocol = 'http://';
282 $url_prefix = $protocol.$hostname;
283 return $url_prefix . me();
288 * Class for creating and manipulating urls.
290 * See short write up here http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url
292 class moodle_url {
293 var $scheme = '';// e.g. http
294 var $host = '';
295 var $port = '';
296 var $user = '';
297 var $pass = '';
298 var $path = '';
299 var $fragment = '';
300 var $params = array(); //associative array of query string params
303 * Pass no arguments to create a url that refers to this page. Use empty string to create empty url.
305 * @param string $url url default null means use this page url with no query string
306 * empty string means empty url.
307 * if you pass any other type of url it will be parsed into it's bits, including query string
308 * @param array $params these params override anything in the query string where params have the same name.
310 function moodle_url($url = null, $params = array()){
311 global $FULLME;
312 if ($url !== ''){
313 if ($url === null){
314 $url = strip_querystring($FULLME);
316 $parts = parse_url($url);
317 if ($parts === FALSE){
318 error('invalidurl');
320 if (isset($parts['query'])){
321 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
323 unset($parts['query']);
324 foreach ($parts as $key => $value){
325 $this->$key = $value;
327 $this->params($params);
331 * Add an array of params to the params for this page. The added params override existing ones if they
332 * have the same name.
334 * @param array $params
336 function params($params){
337 $this->params = $params + $this->params;
341 * Remove all params if no arguments passed. Or else remove param $arg1, $arg2, etc.
343 * @param string $arg1
344 * @param string $arg2
345 * @param string $arg3
347 function remove_params(){
348 if ($thisargs = func_get_args()){
349 foreach ($thisargs as $arg){
350 if (isset($this->params->$arg)){
351 unset($this->params->$arg);
354 } else { // no args
355 $this->params = array();
360 * Add a param to the params for this page. The added param overrides existing one if they
361 * have the same name.
363 * @param string $paramname name
364 * @param string $param value
366 function param($paramname, $param){
367 $this->params = array($paramname => $param) + $this->params;
371 function get_query_string($overrideparams = array()){
372 $arr = array();
373 $params = $overrideparams + $this->params;
374 foreach ($params as $key => $val){
375 $arr[] = urlencode($key)."=".urlencode($val);
377 return implode($arr, "&amp;");
380 * Outputs params as hidden form elements.
382 * @param array $exclude params to ignore
383 * @param integer $indent indentation
384 * @return string html for form elements.
386 function hidden_params_out($exclude = array(), $indent = 0){
387 $tabindent = str_repeat("\t", $indent);
388 $str = '';
389 foreach ($this->params as $key => $val){
390 if (FALSE === array_search($key, $exclude)) {
391 $val = s($val);
392 $str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
395 return $str;
398 * Output url
400 * @param boolean $noquerystring whether to output page params as a query string in the url.
401 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
402 * @return string url
404 function out($noquerystring = false, $overrideparams = array()) {
405 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
406 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
407 $uri .= $this->host ? $this->host : '';
408 $uri .= $this->port ? ':'.$this->port : '';
409 $uri .= $this->path ? $this->path : '';
410 if (!$noquerystring){
411 $uri .= (count($this->params)||count($overrideparams)) ? '?'.$this->get_query_string($overrideparams) : '';
413 $uri .= $this->fragment ? '#'.$this->fragment : '';
414 return $uri;
417 * Output action url with sesskey
419 * @param boolean $noquerystring whether to output page params as a query string in the url.
420 * @return string url
422 function out_action($overrideparams = array()) {
423 $overrideparams = array('sesskey'=> sesskey()) + $overrideparams;
424 return $this->out(false, $overrideparams);
429 * Determine if there is data waiting to be processed from a form
431 * Used on most forms in Moodle to check for data
432 * Returns the data as an object, if it's found.
433 * This object can be used in foreach loops without
434 * casting because it's cast to (array) automatically
436 * Checks that submitted POST data exists and returns it as object.
438 * @param string $url not used anymore
439 * @return mixed false or object
441 function data_submitted($url='') {
443 if (empty($_POST)) {
444 return false;
445 } else {
446 return (object)$_POST;
451 * Moodle replacement for php stripslashes() function,
452 * works also for objects and arrays.
454 * The standard php stripslashes() removes ALL backslashes
455 * even from strings - so C:\temp becomes C:temp - this isn't good.
456 * This function should work as a fairly safe replacement
457 * to be called on quoted AND unquoted strings (to be sure)
459 * @param mixed something to remove unsafe slashes from
460 * @return mixed
462 function stripslashes_safe($mixed) {
463 // there is no need to remove slashes from int, float and bool types
464 if (empty($mixed)) {
465 //nothing to do...
466 } else if (is_string($mixed)) {
467 if (ini_get_bool('magic_quotes_sybase')) { //only unescape single quotes
468 $mixed = str_replace("''", "'", $mixed);
469 } else { //the rest, simple and double quotes and backslashes
470 $mixed = str_replace("\\'", "'", $mixed);
471 $mixed = str_replace('\\"', '"', $mixed);
472 $mixed = str_replace('\\\\', '\\', $mixed);
474 } else if (is_array($mixed)) {
475 foreach ($mixed as $key => $value) {
476 $mixed[$key] = stripslashes_safe($value);
478 } else if (is_object($mixed)) {
479 $vars = get_object_vars($mixed);
480 foreach ($vars as $key => $value) {
481 $mixed->$key = stripslashes_safe($value);
485 return $mixed;
489 * Recursive implementation of stripslashes()
491 * This function will allow you to strip the slashes from a variable.
492 * If the variable is an array or object, slashes will be stripped
493 * from the items (or properties) it contains, even if they are arrays
494 * or objects themselves.
496 * @param mixed the variable to remove slashes from
497 * @return mixed
499 function stripslashes_recursive($var) {
500 if (is_object($var)) {
501 $new_var = new object();
502 $properties = get_object_vars($var);
503 foreach($properties as $property => $value) {
504 $new_var->$property = stripslashes_recursive($value);
507 } else if(is_array($var)) {
508 $new_var = array();
509 foreach($var as $property => $value) {
510 $new_var[$property] = stripslashes_recursive($value);
513 } else if(is_string($var)) {
514 $new_var = stripslashes($var);
516 } else {
517 $new_var = $var;
520 return $new_var;
524 * Recursive implementation of addslashes()
526 * This function will allow you to add the slashes from a variable.
527 * If the variable is an array or object, slashes will be added
528 * to the items (or properties) it contains, even if they are arrays
529 * or objects themselves.
531 * @param mixed the variable to add slashes from
532 * @return mixed
534 function addslashes_recursive($var) {
535 if (is_object($var)) {
536 $new_var = new object();
537 $properties = get_object_vars($var);
538 foreach($properties as $property => $value) {
539 $new_var->$property = addslashes_recursive($value);
542 } else if (is_array($var)) {
543 $new_var = array();
544 foreach($var as $property => $value) {
545 $new_var[$property] = addslashes_recursive($value);
548 } else if (is_string($var)) {
549 $new_var = addslashes($var);
551 } else { // nulls, integers, etc.
552 $new_var = $var;
555 return $new_var;
559 * Given some normal text this function will break up any
560 * long words to a given size by inserting the given character
562 * It's multibyte savvy and doesn't change anything inside html tags.
564 * @param string $string the string to be modified
565 * @param int $maxsize maximum length of the string to be returned
566 * @param string $cutchar the string used to represent word breaks
567 * @return string
569 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
571 /// Loading the textlib singleton instance. We are going to need it.
572 $textlib = textlib_get_instance();
574 /// First of all, save all the tags inside the text to skip them
575 $tags = array();
576 filter_save_tags($string,$tags);
578 /// Process the string adding the cut when necessary
579 $output = '';
580 $length = $textlib->strlen($string);
581 $wordlength = 0;
583 for ($i=0; $i<$length; $i++) {
584 $char = $textlib->substr($string, $i, 1);
585 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
586 $wordlength = 0;
587 } else {
588 $wordlength++;
589 if ($wordlength > $maxsize) {
590 $output .= $cutchar;
591 $wordlength = 0;
594 $output .= $char;
597 /// Finally load the tags back again
598 if (!empty($tags)) {
599 $output = str_replace(array_keys($tags), $tags, $output);
602 return $output;
606 * This does a search and replace, ignoring case
607 * This function is only used for versions of PHP older than version 5
608 * which do not have a native version of this function.
609 * Taken from the PHP manual, by bradhuizenga @ softhome.net
611 * @param string $find the string to search for
612 * @param string $replace the string to replace $find with
613 * @param string $string the string to search through
614 * return string
616 if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
617 function str_ireplace($find, $replace, $string) {
619 if (!is_array($find)) {
620 $find = array($find);
623 if(!is_array($replace)) {
624 if (!is_array($find)) {
625 $replace = array($replace);
626 } else {
627 // this will duplicate the string into an array the size of $find
628 $c = count($find);
629 $rString = $replace;
630 unset($replace);
631 for ($i = 0; $i < $c; $i++) {
632 $replace[$i] = $rString;
637 foreach ($find as $fKey => $fItem) {
638 $between = explode(strtolower($fItem),strtolower($string));
639 $pos = 0;
640 foreach($between as $bKey => $bItem) {
641 $between[$bKey] = substr($string,$pos,strlen($bItem));
642 $pos += strlen($bItem) + strlen($fItem);
644 $string = implode($replace[$fKey],$between);
646 return ($string);
651 * Locate the position of a string in another string
653 * This function is only used for versions of PHP older than version 5
654 * which do not have a native version of this function.
655 * Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
657 * @param string $haystack The string to be searched
658 * @param string $needle The string to search for
659 * @param int $offset The position in $haystack where the search should begin.
661 if (!function_exists('stripos')) { /// Only exists in PHP 5
662 function stripos($haystack, $needle, $offset=0) {
664 return strpos(strtoupper($haystack), strtoupper($needle), $offset);
669 * This function will create a HTML link that will work on both
670 * Javascript and non-javascript browsers.
671 * Relies on the Javascript function openpopup in javascript.php
673 * $url must be relative to home page eg /mod/survey/stuff.php
674 * @param string $url Web link relative to home page
675 * @param string $name Name to be assigned to the popup window
676 * @param string $linkname Text to be displayed as web link
677 * @param int $height Height to assign to popup window
678 * @param int $width Height to assign to popup window
679 * @param string $title Text to be displayed as popup page title
680 * @param string $options List of additional options for popup window
681 * @todo Add code examples and list of some options that might be used.
682 * @param boolean $return Should the link to the popup window be returned as a string (true) or printed immediately (false)?
683 * @return string
684 * @uses $CFG
686 function link_to_popup_window ($url, $name='popup', $linkname='click here',
687 $height=400, $width=500, $title='Popup window',
688 $options='none', $return=false) {
690 global $CFG;
692 if ($options == 'none') {
693 $options = 'menubar=0,location=0,scrollbars,resizable,width='. $width .',height='. $height;
695 $fullscreen = 0;
697 if (!(strpos($url,$CFG->wwwroot) === false)) { // some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
698 $url = substr($url, strlen($CFG->wwwroot));
701 $link = '<a title="'. s(strip_tags($title)) .'" href="'. $CFG->wwwroot . $url .'" '.
702 "onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
703 if ($return) {
704 return $link;
705 } else {
706 echo $link;
711 * This function will print a button submit form element
712 * that will work on both Javascript and non-javascript browsers.
713 * Relies on the Javascript function openpopup in javascript.php
715 * $url must be relative to home page eg /mod/survey/stuff.php
716 * @param string $url Web link relative to home page
717 * @param string $name Name to be assigned to the popup window
718 * @param string $linkname Text to be displayed as web link
719 * @param int $height Height to assign to popup window
720 * @param int $width Height to assign to popup window
721 * @param string $title Text to be displayed as popup page title
722 * @param string $options List of additional options for popup window
723 * @param string $return If true, return as a string, otherwise print
724 * @return string
725 * @uses $CFG
727 function button_to_popup_window ($url, $name='popup', $linkname='click here',
728 $height=400, $width=500, $title='Popup window', $options='none', $return=false,
729 $id='', $class='') {
731 global $CFG;
733 if ($options == 'none') {
734 $options = 'menubar=0,location=0,scrollbars,resizable,width='. $width .',height='. $height;
737 if ($id) {
738 $id = ' id="'.$id.'" ';
740 if ($class) {
741 $class = ' class="'.$class.'" ';
743 $fullscreen = 0;
745 $button = '<input type="button" name="'.$name.'" title="'. $title .'" value="'. $linkname .' ..." '.$id.$class.
746 "onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
747 if ($return) {
748 return $button;
749 } else {
750 echo $button;
756 * Prints a simple button to close a window
758 function close_window_button($name='closewindow', $return=false) {
759 global $CFG;
761 $output = '';
763 $output .= '<div class="closewindow">' . "\n";
764 $output .= '<form action="'.$CFG->wwwroot.'"><div>'; // We don't use this
765 $output .= '<input type="button" onclick="self.close();" value="'.get_string($name).'" />';
766 $output .= '</div></form>';
767 $output .= '</div>' . "\n";
769 if ($return) {
770 return $output;
771 } else {
772 echo $output;
777 * Try and close the current window immediately using Javascript
779 function close_window($delay=0) {
781 <script type="text/javascript">
782 //<![CDATA[
783 function close_this_window() {
784 self.close();
786 setTimeout("close_this_window()", <?php echo $delay * 1000 ?>);
787 //]]>
788 </script>
789 <noscript><center>
790 <?php print_string('pleaseclose') ?>
791 </center></noscript>
792 <?php
793 die;
798 * Given an array of value, creates a popup menu to be part of a form
799 * $options["value"]["label"]
801 * @param type description
802 * @todo Finish documenting this function
804 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
805 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0, $id='') {
807 if ($nothing == 'choose') {
808 $nothing = get_string('choose') .'...';
811 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
812 if ($disabled) {
813 $attributes .= ' disabled="disabled"';
816 if ($tabindex) {
817 $attributes .= ' tabindex="'.$tabindex.'"';
820 if ($id ==='') {
821 $id = 'menu'.$name;
822 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
823 $id = str_replace('[', '', $id);
824 $id = str_replace(']', '', $id);
827 $output = '<select id="'.$id.'" name="'. $name .'" '. $attributes .'>' . "\n";
828 if ($nothing) {
829 $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
830 if ($nothingvalue === $selected) {
831 $output .= ' selected="selected"';
833 $output .= '>'. $nothing .'</option>' . "\n";
835 if (!empty($options)) {
836 foreach ($options as $value => $label) {
837 $output .= ' <option value="'. s($value) .'"';
838 if ((string)$value == (string)$selected) {
839 $output .= ' selected="selected"';
841 if ($label === '') {
842 $output .= '>'. $value .'</option>' . "\n";
843 } else {
844 $output .= '>'. $label .'</option>' . "\n";
848 $output .= '</select>' . "\n";
850 if ($return) {
851 return $output;
852 } else {
853 echo $output;
858 * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
859 * Other options like choose_from_menu.
861 function choose_from_menu_yesno($name, $selected, $script = '',
862 $return = false, $disabled = false, $tabindex = 0) {
863 return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
864 $selected, '', $script, '0', $return, $disabled, $tabindex);
868 * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
869 * including option headings with the first level.
871 function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
872 $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
874 if ($nothing == 'choose') {
875 $nothing = get_string('choose') .'...';
878 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
879 if ($disabled) {
880 $attributes .= ' disabled="disabled"';
883 if ($tabindex) {
884 $attributes .= ' tabindex="'.$tabindex.'"';
887 $output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
888 if ($nothing) {
889 $output .= ' <option value="'. $nothingvalue .'"'. "\n";
890 if ($nothingvalue === $selected) {
891 $output .= ' selected="selected"';
893 $output .= '>'. $nothing .'</option>' . "\n";
895 if (!empty($options)) {
896 foreach ($options as $section => $values) {
898 $output .= ' <optgroup label="'. s(format_string($section)) .'">'."\n";
899 foreach ($values as $value => $label) {
900 $output .= ' <option value="'. format_string($value) .'"';
901 if ((string)$value == (string)$selected) {
902 $output .= ' selected="selected"';
904 if ($label === '') {
905 $output .= '>'. $value .'</option>' . "\n";
906 } else {
907 $output .= '>'. $label .'</option>' . "\n";
910 $output .= ' </optgroup>'."\n";
913 $output .= '</select>' . "\n";
915 if ($return) {
916 return $output;
917 } else {
918 echo $output;
924 * Given an array of values, creates a group of radio buttons to be part of a form
926 * @param array $options An array of value-label pairs for the radio group (values as keys)
927 * @param string $name Name of the radiogroup (unique in the form)
928 * @param string $checked The value that is already checked
930 function choose_from_radio ($options, $name, $checked='', $return=false) {
932 static $idcounter = 0;
934 if (!$name) {
935 $name = 'unnamed';
938 $output = '<span class="radiogroup '.$name."\">\n";
940 if (!empty($options)) {
941 $currentradio = 0;
942 foreach ($options as $value => $label) {
943 $htmlid = 'auto-rb'.sprintf('%04d', ++$idcounter);
944 $output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
945 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
946 if ($value == $checked) {
947 $output .= ' checked="checked"';
949 if ($label === '') {
950 $output .= ' /> <label for="'.$htmlid.'">'. $value .'</label></span>' . "\n";
951 } else {
952 $output .= ' /> <label for="'.$htmlid.'">'. $label .'</label></span>' . "\n";
954 $currentradio = ($currentradio + 1) % 2;
958 $output .= '</span>' . "\n";
960 if ($return) {
961 return $output;
962 } else {
963 echo $output;
967 /** Display an standard html checkbox with an optional label
969 * @param string $name The name of the checkbox
970 * @param string $value The valus that the checkbox will pass when checked
971 * @param boolean $checked The flag to tell the checkbox initial state
972 * @param string $label The label to be showed near the checkbox
973 * @param string $alt The info to be inserted in the alt tag
975 function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
977 static $idcounter = 0;
979 if (!$name) {
980 $name = 'unnamed';
983 if ($alt) {
984 $alt = strip_tags($alt);
985 } else {
986 $alt = 'checkbox';
989 if ($checked) {
990 $strchecked = ' checked="checked"';
991 } else {
992 $strchecked = '';
995 $htmlid = 'auto-cb'.sprintf('%04d', ++$idcounter);
996 $output = '<span class="checkbox '.$name."\">";
997 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ? ' onclick="'.$script.'" ' : '').' />';
998 if(!empty($label)) {
999 $output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
1001 $output .= '</span>'."\n";
1003 if (empty($return)) {
1004 echo $output;
1005 } else {
1006 return $output;
1011 /** Display an standard html text field with an optional label
1013 * @param string $name The name of the text field
1014 * @param string $value The value of the text field
1015 * @param string $label The label to be showed near the text field
1016 * @param string $alt The info to be inserted in the alt tag
1018 function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
1020 static $idcounter = 0;
1022 if (empty($name)) {
1023 $name = 'unnamed';
1026 if (empty($alt)) {
1027 $alt = 'textfield';
1030 if (!empty($maxlength)) {
1031 $maxlength = ' maxlength="'.$maxlength.'" ';
1034 $htmlid = 'auto-tf'.sprintf('%04d', ++$idcounter);
1035 $output = '<span class="textfield '.$name."\">";
1036 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
1038 $output .= '</span>'."\n";
1040 if (empty($return)) {
1041 echo $output;
1042 } else {
1043 return $output;
1050 * Implements a complete little popup form
1052 * @uses $CFG
1053 * @param string $common The URL up to the point of the variable that changes
1054 * @param array $options Alist of value-label pairs for the popup list
1055 * @param string $formid Id must be unique on the page (originaly $formname)
1056 * @param string $selected The option that is already selected
1057 * @param string $nothing The label for the "no choice" option
1058 * @param string $help The name of a help page if help is required
1059 * @param string $helptext The name of the label for the help button
1060 * @param boolean $return Indicates whether the function should return the text
1061 * as a string or echo it directly to the page being rendered
1062 * @param string $targetwindow The name of the target page to open the linked page in.
1063 * @return string If $return is true then the entire form is returned as a string.
1064 * @todo Finish documenting this function<br>
1066 function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
1067 $targetwindow='self', $selectlabel='', $optionsextra=NULL) {
1069 global $CFG;
1070 static $go, $choose; /// Locally cached, in case there's lots on a page
1072 if (empty($options)) {
1073 return '';
1076 if (!isset($go)) {
1077 $go = get_string('go');
1080 if ($nothing == 'choose') {
1081 if (!isset($choose)) {
1082 $choose = get_string('choose');
1084 $nothing = $choose.'...';
1087 // changed reference to document.getElementById('id_abc') instead of document.abc
1088 // MDL-7861
1089 $output = '<form action="'.$CFG->wwwroot.'/course/jumpto.php"'.
1090 ' method="get" '.
1091 $CFG->frametarget.
1092 ' id="'.$formid.'"'.
1093 ' class="popupform">';
1094 if ($help) {
1095 $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
1096 } else {
1097 $button = '';
1100 if ($selectlabel) {
1101 $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
1104 $output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" name="jump" onchange="'.$targetwindow.'.location=document.getElementById(\''.$formid.'\').jump.options[document.getElementById(\''.$formid.'\').jump.selectedIndex].value;">'."\n";
1106 if ($nothing != '') {
1107 $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
1110 $inoptgroup = false;
1112 foreach ($options as $value => $label) {
1114 if ($label == '--') { /// we are ending previous optgroup
1115 /// Check to see if we already have a valid open optgroup
1116 /// XHTML demands that there be at least 1 option within an optgroup
1117 if ($inoptgroup and (count($optgr) > 1) ) {
1118 $output .= implode('', $optgr);
1119 $output .= ' </optgroup>';
1121 $optgr = array();
1122 $inoptgroup = false;
1123 continue;
1124 } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
1126 /// Check to see if we already have a valid open optgroup
1127 /// XHTML demands that there be at least 1 option within an optgroup
1128 if ($inoptgroup and (count($optgr) > 1) ) {
1129 $output .= implode('', $optgr);
1130 $output .= ' </optgroup>';
1133 unset($optgr);
1134 $optgr = array();
1136 $optgr[] = ' <optgroup label="'. s(format_string(substr($label,2))) .'">'; // Plain labels
1138 $inoptgroup = true; /// everything following will be in an optgroup
1139 continue;
1141 } else {
1142 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()]))
1144 $url=sid_process_url( $common . $value );
1145 } else
1147 $url=$common . $value;
1149 $optstr = ' <option value="' . $url . '"';
1151 if ($value == $selected) {
1152 $optstr .= ' selected="selected"';
1155 if (!empty($optionsextra[$value])) {
1156 $optstr .= ' '.$optionsextra[$value];
1159 if ($label) {
1160 $optstr .= '>'. $label .'</option>' . "\n";
1161 } else {
1162 $optstr .= '>'. $value .'</option>' . "\n";
1165 if ($inoptgroup) {
1166 $optgr[] = $optstr;
1167 } else {
1168 $output .= $optstr;
1174 /// catch the final group if not closed
1175 if ($inoptgroup and count($optgr) > 1) {
1176 $output .= implode('', $optgr);
1177 $output .= ' </optgroup>';
1180 $output .= '</select>';
1181 $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1182 $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
1183 $output .= '<input type="submit" value="'.$go.'" /></div>';
1184 $output .= '<script type="text/javascript">'.
1185 "\n//<![CDATA[\n".
1186 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
1187 "\n//]]>\n".'</script>';
1188 $output .= '</div>';
1189 $output .= '</form>';
1191 if ($return) {
1192 return $output;
1193 } else {
1194 echo $output;
1200 * Prints some red text
1202 * @param string $error The text to be displayed in red
1204 function formerr($error) {
1206 if (!empty($error)) {
1207 echo '<span class="error">'. $error .'</span>';
1212 * Validates an email to make sure it makes sense.
1214 * @param string $address The email address to validate.
1215 * @return boolean
1217 function validate_email($address) {
1219 return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1220 '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1221 '@'.
1222 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1223 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
1224 $address));
1228 * Extracts file argument either from file parameter or PATH_INFO
1230 * @param string $scriptname name of the calling script
1231 * @return string file path (only safe characters)
1233 function get_file_argument($scriptname) {
1234 global $_SERVER;
1236 $relativepath = FALSE;
1238 // first try normal parameter (compatible method == no relative links!)
1239 $relativepath = optional_param('file', FALSE, PARAM_PATH);
1240 if ($relativepath === '/testslasharguments') {
1241 echo 'test -1 : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
1242 die;
1245 // then try extract file from PATH_INFO (slasharguments method)
1246 if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
1247 $path_info = $_SERVER['PATH_INFO'];
1248 // check that PATH_INFO works == must not contain the script name
1249 if (!strpos($path_info, $scriptname)) {
1250 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1251 if ($relativepath === '/testslasharguments') {
1252 echo 'test 1 : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
1253 die;
1258 // now if both fail try the old way
1259 // (for compatibility with misconfigured or older buggy php implementations)
1260 if (!$relativepath) {
1261 $arr = explode($scriptname, me());
1262 if (!empty($arr[1])) {
1263 $path_info = strip_querystring($arr[1]);
1264 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1265 if ($relativepath === '/testslasharguments') {
1266 echo 'test 2 : Slasharguments test passed (compatibility hack). Server confguration may be compatible with file.php/1/pic.jpg slashargument setting'; //indicate ok for health center
1267 die;
1272 return $relativepath;
1276 * Searches the current environment variables for some slash arguments
1278 * @param string $file ?
1279 * @todo Finish documenting this function
1281 function get_slash_arguments($file='file.php') {
1283 if (!$string = me()) {
1284 return false;
1287 $pathinfo = explode($file, $string);
1289 if (!empty($pathinfo[1])) {
1290 return addslashes($pathinfo[1]);
1291 } else {
1292 return false;
1297 * Extracts arguments from "/foo/bar/something"
1298 * eg http://mysite.com/script.php/foo/bar/something
1300 * @param string $string ?
1301 * @param int $i ?
1302 * @return array|string
1303 * @todo Finish documenting this function
1305 function parse_slash_arguments($string, $i=0) {
1307 if (detect_munged_arguments($string)) {
1308 return false;
1310 $args = explode('/', $string);
1312 if ($i) { // return just the required argument
1313 return $args[$i];
1315 } else { // return the whole array
1316 array_shift($args); // get rid of the empty first one
1317 return $args;
1322 * Just returns an array of text formats suitable for a popup menu
1324 * @uses FORMAT_MOODLE
1325 * @uses FORMAT_HTML
1326 * @uses FORMAT_PLAIN
1327 * @uses FORMAT_MARKDOWN
1328 * @return array
1330 function format_text_menu() {
1332 return array (FORMAT_MOODLE => get_string('formattext'),
1333 FORMAT_HTML => get_string('formathtml'),
1334 FORMAT_PLAIN => get_string('formatplain'),
1335 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1339 * Given text in a variety of format codings, this function returns
1340 * the text as safe HTML.
1342 * @uses $CFG
1343 * @uses FORMAT_MOODLE
1344 * @uses FORMAT_HTML
1345 * @uses FORMAT_PLAIN
1346 * @uses FORMAT_WIKI
1347 * @uses FORMAT_MARKDOWN
1348 * @param string $text The text to be formatted. This is raw text originally from user input.
1349 * @param int $format Identifier of the text format to be used
1350 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1351 * @param array $options ?
1352 * @param int $courseid ?
1353 * @return string
1354 * @todo Finish documenting this function
1356 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1358 global $CFG, $COURSE;
1360 if ($text === '') {
1361 return ''; // no need to do any filters and cleaning
1364 if (!isset($options->trusttext)) {
1365 $options->trusttext = false;
1368 if (!isset($options->noclean)) {
1369 $options->noclean=false;
1371 if (!isset($options->nocache)) {
1372 $options->nocache=false;
1374 if (!isset($options->smiley)) {
1375 $options->smiley=true;
1377 if (!isset($options->filter)) {
1378 $options->filter=true;
1380 if (!isset($options->para)) {
1381 $options->para=true;
1383 if (!isset($options->newlines)) {
1384 $options->newlines=true;
1387 if (empty($courseid)) {
1388 $courseid = $COURSE->id;
1391 if (!empty($CFG->cachetext) and empty($options->nocache)) {
1392 $time = time() - $CFG->cachetext;
1393 $md5key = md5($text.'-'.(int)$courseid.'-'.current_language().'-'.(int)$format.(int)$options->trusttext.(int)$options->noclean.(int)$options->smiley.(int)$options->filter.(int)$options->para.(int)$options->newlines);
1394 if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
1395 if ($oldcacheitem->timemodified >= $time) {
1396 return $oldcacheitem->formattedtext;
1401 // trusttext overrides the noclean option!
1402 if ($options->trusttext) {
1403 if (trusttext_present($text)) {
1404 $text = trusttext_strip($text);
1405 if (!empty($CFG->enabletrusttext)) {
1406 $options->noclean = true;
1407 } else {
1408 $options->noclean = false;
1410 } else {
1411 $options->noclean = false;
1413 } else if (!debugging('', DEBUG_DEVELOPER)) {
1414 // strip any forgotten trusttext in non-developer mode
1415 // do not forget to disable text cache when debugging trusttext!!
1416 $text = trusttext_strip($text);
1419 $CFG->currenttextiscacheable = true; // Default status - can be changed by any filter
1421 switch ($format) {
1422 case FORMAT_HTML:
1423 if ($options->smiley) {
1424 replace_smilies($text);
1426 if (!$options->noclean) {
1427 $text = clean_text($text, FORMAT_HTML);
1429 if ($options->filter) {
1430 $text = filter_text($text, $courseid);
1432 break;
1434 case FORMAT_PLAIN:
1435 $text = s($text); // cleans dangerous JS
1436 $text = rebuildnolinktag($text);
1437 $text = str_replace(' ', '&nbsp; ', $text);
1438 $text = nl2br($text);
1439 break;
1441 case FORMAT_WIKI:
1442 // this format is deprecated
1443 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1444 this message as all texts should have been converted to Markdown format instead.
1445 Please post a bug report to http://moodle.org/bugs with information about where you
1446 saw this message.</p>'.s($text);
1447 break;
1449 case FORMAT_MARKDOWN:
1450 $text = markdown_to_html($text);
1451 if ($options->smiley) {
1452 replace_smilies($text);
1454 if (!$options->noclean) {
1455 $text = clean_text($text, FORMAT_HTML);
1458 if ($options->filter) {
1459 $text = filter_text($text, $courseid);
1461 break;
1463 default: // FORMAT_MOODLE or anything else
1464 $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
1465 if (!$options->noclean) {
1466 $text = clean_text($text, FORMAT_HTML);
1469 if ($options->filter) {
1470 $text = filter_text($text, $courseid);
1472 break;
1475 if (empty($options->nocache) and !empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
1476 $newcacheitem = new object();
1477 $newcacheitem->md5key = $md5key;
1478 $newcacheitem->formattedtext = addslashes($text);
1479 $newcacheitem->timemodified = time();
1480 if ($oldcacheitem) { // See bug 4677 for discussion
1481 $newcacheitem->id = $oldcacheitem->id;
1482 @update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1483 // It's unlikely that the cron cache cleaner could have
1484 // deleted this entry in the meantime, as it allows
1485 // some extra time to cover these cases.
1486 } else {
1487 @insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1488 // Again, it's possible that another user has caused this
1489 // record to be created already in the time that it took
1490 // to traverse this function. That's OK too, as the
1491 // call above handles duplicate entries, and eventually
1492 // the cron cleaner will delete them.
1496 return $text;
1499 /** Converts the text format from the value to the 'internal'
1500 * name or vice versa. $key can either be the value or the name
1501 * and you get the other back.
1503 * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1504 * @return mixed as above but the other way around!
1506 function text_format_name( $key ) {
1507 $lookup = array();
1508 $lookup[FORMAT_MOODLE] = 'moodle';
1509 $lookup[FORMAT_HTML] = 'html';
1510 $lookup[FORMAT_PLAIN] = 'plain';
1511 $lookup[FORMAT_MARKDOWN] = 'markdown';
1512 $value = "error";
1513 if (!is_numeric($key)) {
1514 $key = strtolower( $key );
1515 $value = array_search( $key, $lookup );
1517 else {
1518 if (isset( $lookup[$key] )) {
1519 $value = $lookup[ $key ];
1522 return $value;
1526 /** Given a simple string, this function returns the string
1527 * processed by enabled filters if $CFG->filterall is enabled
1529 * @param string $string The string to be filtered.
1530 * @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
1531 * @param int $courseid Current course as filters can, potentially, use it
1532 * @return string
1534 function format_string ($string, $striplinks=true, $courseid=NULL ) {
1536 global $CFG, $COURSE;
1538 //We'll use a in-memory cache here to speed up repeated strings
1539 static $strcache = false;
1541 if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
1542 $strcache = array();
1545 //init course id
1546 if (empty($courseid)) {
1547 $courseid = $COURSE->id;
1550 //Calculate md5
1551 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
1553 //Fetch from cache if possible
1554 if (isset($strcache[$md5])) {
1555 return $strcache[$md5];
1558 // First replace all ampersands not followed by html entity code
1559 $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1561 if (!empty($CFG->filterall)) {
1562 $string = filter_string($string, $courseid);
1565 // If the site requires it, strip ALL tags from this string
1566 if (!empty($CFG->formatstringstriptags)) {
1567 $string = strip_tags($string);
1569 // Otherwise strip just links if that is required (default)
1570 } else if ($striplinks) { //strip links in string
1571 $string = preg_replace('/(<a[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1574 //Store to cache
1575 $strcache[$md5] = $string;
1577 return $string;
1581 * Given text in a variety of format codings, this function returns
1582 * the text as plain text suitable for plain email.
1584 * @uses FORMAT_MOODLE
1585 * @uses FORMAT_HTML
1586 * @uses FORMAT_PLAIN
1587 * @uses FORMAT_WIKI
1588 * @uses FORMAT_MARKDOWN
1589 * @param string $text The text to be formatted. This is raw text originally from user input.
1590 * @param int $format Identifier of the text format to be used
1591 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1592 * @return string
1594 function format_text_email($text, $format) {
1596 switch ($format) {
1598 case FORMAT_PLAIN:
1599 return $text;
1600 break;
1602 case FORMAT_WIKI:
1603 $text = wiki_to_html($text);
1604 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1605 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
1606 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1607 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1608 break;
1610 case FORMAT_HTML:
1611 return html_to_text($text);
1612 break;
1614 case FORMAT_MOODLE:
1615 case FORMAT_MARKDOWN:
1616 default:
1617 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1618 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1619 break;
1624 * Given some text in HTML format, this function will pass it
1625 * through any filters that have been defined in $CFG->textfilterx
1626 * The variable defines a filepath to a file containing the
1627 * filter function. The file must contain a variable called
1628 * $textfilter_function which contains the name of the function
1629 * with $courseid and $text parameters
1631 * @param string $text The text to be passed through format filters
1632 * @param int $courseid ?
1633 * @return string
1634 * @todo Finish documenting this function
1636 function filter_text($text, $courseid=NULL) {
1637 global $CFG, $COURSE;
1639 if (empty($courseid)) {
1640 $courseid = $COURSE->id; // (copied from format_text)
1643 if (!empty($CFG->textfilters)) {
1644 require_once($CFG->libdir.'/filterlib.php');
1645 $textfilters = explode(',', $CFG->textfilters);
1646 foreach ($textfilters as $textfilter) {
1647 if (is_readable($CFG->dirroot .'/'. $textfilter .'/filter.php')) {
1648 include_once($CFG->dirroot .'/'. $textfilter .'/filter.php');
1649 $functionname = basename($textfilter).'_filter';
1650 if (function_exists($functionname)) {
1651 $text = $functionname($courseid, $text);
1657 /// <nolink> tags removed for XHTML compatibility
1658 $text = str_replace('<nolink>', '', $text);
1659 $text = str_replace('</nolink>', '', $text);
1661 return $text;
1666 * Given a string (short text) in HTML format, this function will pass it
1667 * through any filters that have been defined in $CFG->stringfilters
1668 * The variable defines a filepath to a file containing the
1669 * filter function. The file must contain a variable called
1670 * $textfilter_function which contains the name of the function
1671 * with $courseid and $text parameters
1673 * @param string $string The text to be passed through format filters
1674 * @param int $courseid The id of a course
1675 * @return string
1677 function filter_string($string, $courseid=NULL) {
1678 global $CFG, $COURSE;
1680 if (empty($CFG->textfilters)) { // All filters are disabled anyway so quit
1681 return $string;
1684 if (empty($courseid)) {
1685 $courseid = $COURSE->id;
1688 require_once($CFG->libdir.'/filterlib.php');
1690 if (isset($CFG->stringfilters)) { // We have a predefined list to use, great!
1691 if (empty($CFG->stringfilters)) { // but it's blank, so finish now
1692 return $string;
1694 $stringfilters = explode(',', $CFG->stringfilters); // ..use the list we have
1696 } else { // Otherwise try to derive a list from textfilters
1697 if (strpos($CFG->textfilters, 'filter/multilang') !== false) { // Multilang is here
1698 $stringfilters = array('filter/multilang'); // Let's use just that
1699 $CFG->stringfilters = 'filter/multilang'; // Save it for next time through
1700 } else {
1701 $CFG->stringfilters = ''; // Save the result and return
1702 return $string;
1707 foreach ($stringfilters as $stringfilter) {
1708 if (is_readable($CFG->dirroot .'/'. $stringfilter .'/filter.php')) {
1709 include_once($CFG->dirroot .'/'. $stringfilter .'/filter.php');
1710 $functionname = basename($stringfilter).'_filter';
1711 if (function_exists($functionname)) {
1712 $string = $functionname($courseid, $string);
1717 /// <nolink> tags removed for XHTML compatibility
1718 $string = str_replace('<nolink>', '', $string);
1719 $string = str_replace('</nolink>', '', $string);
1721 return $string;
1725 * Is the text marked as trusted?
1727 * @param string $text text to be searched for TRUSTTEXT marker
1728 * @return boolean
1730 function trusttext_present($text) {
1731 if (strpos($text, TRUSTTEXT) !== FALSE) {
1732 return true;
1733 } else {
1734 return false;
1739 * This funtion MUST be called before the cleaning or any other
1740 * function that modifies the data! We do not know the origin of trusttext
1741 * in database, if it gets there in tweaked form we must not convert it
1742 * to supported form!!!
1744 * Please be carefull not to use stripslashes on data from database
1745 * or twice stripslashes when processing data recieved from user.
1747 * @param string $text text that may contain TRUSTTEXT marker
1748 * @return text without any TRUSTTEXT marker
1750 function trusttext_strip($text) {
1751 global $CFG;
1753 while (true) { //removing nested TRUSTTEXT
1754 $orig = $text;
1755 $text = str_replace(TRUSTTEXT, '', $text);
1756 if (strcmp($orig, $text) === 0) {
1757 return $text;
1763 * Mark text as trusted, such text may contain any HTML tags because the
1764 * normal text cleaning will be bypassed.
1765 * Please make sure that the text comes from trusted user before storing
1766 * it into database!
1768 function trusttext_mark($text) {
1769 global $CFG;
1770 if (!empty($CFG->enabletrusttext) and (strpos($text, TRUSTTEXT) === FALSE)) {
1771 return TRUSTTEXT.$text;
1772 } else {
1773 return $text;
1776 function trusttext_after_edit(&$text, $context) {
1777 if (has_capability('moodle/site:trustcontent', $context)) {
1778 $text = trusttext_strip($text);
1779 $text = trusttext_mark($text);
1780 } else {
1781 $text = trusttext_strip($text);
1785 function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
1786 global $CFG;
1788 $options = new object();
1789 $options->smiley = false;
1790 $options->filter = false;
1791 if (!empty($CFG->enabletrusttext)
1792 and has_capability('moodle/site:trustcontent', $context)
1793 and trusttext_present($text)) {
1794 $options->noclean = true;
1795 } else {
1796 $options->noclean = false;
1798 $text = trusttext_strip($text);
1799 if ($usehtmleditor) {
1800 $text = format_text($text, $format, $options);
1801 $format = FORMAT_HTML;
1802 } else if (!$options->noclean){
1803 $text = clean_text($text, $format);
1808 * Given raw text (eg typed in by a user), this function cleans it up
1809 * and removes any nasty tags that could mess up Moodle pages.
1811 * @uses FORMAT_MOODLE
1812 * @uses FORMAT_PLAIN
1813 * @uses ALLOWED_TAGS
1814 * @param string $text The text to be cleaned
1815 * @param int $format Identifier of the text format to be used
1816 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1817 * @return string The cleaned up text
1819 function clean_text($text, $format=FORMAT_MOODLE) {
1821 global $ALLOWED_TAGS, $CFG;
1823 if (empty($text) or is_numeric($text)) {
1824 return (string)$text;
1827 switch ($format) {
1828 case FORMAT_PLAIN:
1829 case FORMAT_MARKDOWN:
1830 return $text;
1832 default:
1834 if (!empty($CFG->enablehtmlpurifier)) {
1835 $text = purify_html($text);
1836 } else {
1837 /// Fix non standard entity notations
1838 $text = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $text);
1839 $text = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $text);
1841 /// Remove tags that are not allowed
1842 $text = strip_tags($text, $ALLOWED_TAGS);
1844 /// Clean up embedded scripts and , using kses
1845 $text = cleanAttributes($text);
1847 /// Again remove tags that are not allowed
1848 $text = strip_tags($text, $ALLOWED_TAGS);
1852 /// Remove potential script events - some extra protection for undiscovered bugs in our code
1853 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
1854 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
1856 return $text;
1861 * KSES replacement cleaning function - uses HTML Purifier.
1863 function purify_html($text) {
1864 global $CFG;
1866 static $purifier = false;
1867 if (!$purifier) {
1868 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.auto.php';
1869 $config = HTMLPurifier_Config::createDefault();
1870 $config->set('Core', 'AcceptFullDocuments', false);
1871 //$config->set('HTML', 'Strict', true);
1872 $config->set('URI', 'AllowedSchemes', array('http'=>1, 'https'=>1, 'ftp'=>1, 'irc'=>1, 'nntp'=>1, 'news'=>1, 'rtsp'=>1, 'teamspeak'=>1, 'gopher'=>1, 'mms'=>1));
1873 $purifier = new HTMLPurifier($config);
1875 return $purifier->purify($text);
1879 * This function takes a string and examines it for HTML tags.
1880 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
1881 * which checks for attributes and filters them for malicious content
1882 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
1884 * @param string $str The string to be examined for html tags
1885 * @return string
1887 function cleanAttributes($str){
1888 $result = preg_replace_callback(
1889 '%(<[^>]*(>|$)|>)%m', #search for html tags
1890 "cleanAttributes2",
1891 $str
1893 return $result;
1897 * This function takes a string with an html tag and strips out any unallowed
1898 * protocols e.g. javascript:
1899 * It calls ancillary functions in kses which are prefixed by kses
1900 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
1902 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
1903 * element the html to be cleared
1904 * @return string
1906 function cleanAttributes2($htmlArray){
1908 global $CFG, $ALLOWED_PROTOCOLS;
1909 require_once($CFG->libdir .'/kses.php');
1911 $htmlTag = $htmlArray[1];
1912 if (substr($htmlTag, 0, 1) != '<') {
1913 return '&gt;'; //a single character ">" detected
1915 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
1916 return ''; // It's seriously malformed
1918 $slash = trim($matches[1]); //trailing xhtml slash
1919 $elem = $matches[2]; //the element name
1920 $attrlist = $matches[3]; // the list of attributes as a string
1922 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
1924 $attStr = '';
1925 foreach ($attrArray as $arreach) {
1926 $arreach['name'] = strtolower($arreach['name']);
1927 if ($arreach['name'] == 'style') {
1928 $value = $arreach['value'];
1929 while (true) {
1930 $prevvalue = $value;
1931 $value = kses_no_null($value);
1932 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
1933 $value = kses_decode_entities($value);
1934 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
1935 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
1936 if ($value === $prevvalue) {
1937 $arreach['value'] = $value;
1938 break;
1941 $arreach['value'] = preg_replace("/j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xjavascript", $arreach['value']);
1942 $arreach['value'] = preg_replace("/e\s*x\s*p\s*r\s*e\s*s\s*s\s*i\s*o\s*n/i", "Xexpression", $arreach['value']);
1943 } else if ($arreach['name'] == 'href') {
1944 //Adobe Acrobat Reader XSS protection
1945 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd))[^a-z0-9_\.\-].*$/i', '$1', $arreach['value']);
1947 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
1950 $xhtml_slash = '';
1951 if (preg_match('%/\s*$%', $attrlist)) {
1952 $xhtml_slash = ' /';
1954 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
1958 * Replaces all known smileys in the text with image equivalents
1960 * @uses $CFG
1961 * @param string $text Passed by reference. The string to search for smily strings.
1962 * @return string
1964 function replace_smilies(&$text) {
1966 global $CFG;
1968 $lang = current_language();
1970 /// this builds the mapping array only once
1971 static $e = array();
1972 static $img = array();
1973 static $emoticons = array(
1974 ':-)' => 'smiley',
1975 ':)' => 'smiley',
1976 ':-D' => 'biggrin',
1977 ';-)' => 'wink',
1978 ':-/' => 'mixed',
1979 'V-.' => 'thoughtful',
1980 ':-P' => 'tongueout',
1981 'B-)' => 'cool',
1982 '^-)' => 'approve',
1983 '8-)' => 'wideeyes',
1984 ':o)' => 'clown',
1985 ':-(' => 'sad',
1986 ':(' => 'sad',
1987 '8-.' => 'shy',
1988 ':-I' => 'blush',
1989 ':-X' => 'kiss',
1990 '8-o' => 'surprise',
1991 'P-|' => 'blackeye',
1992 '8-[' => 'angry',
1993 'xx-P' => 'dead',
1994 '|-.' => 'sleepy',
1995 '}-]' => 'evil',
1996 '(h)' => 'heart',
1997 '(heart)' => 'heart',
1998 '(y)' => 'yes',
1999 '(n)' => 'no',
2000 '(martin)' => 'martin',
2001 '( )' => 'egg'
2004 if (empty($img[$lang])) { /// After the first time this is not run again
2005 $e[$lang] = array();
2006 $img[$lang] = array();
2007 foreach ($emoticons as $emoticon => $image){
2008 $alttext = get_string($image, 'pix');
2010 $e[$lang][] = $emoticon;
2011 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath .'/s/'. $image .'.gif" />';
2015 // Exclude from transformations all the code inside <script> tags
2016 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
2017 // Based on code from glossary fiter by Williams Castillo.
2018 // - Eloy
2020 // Detect all the <script> zones to take out
2021 $excludes = array();
2022 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
2024 // Take out all the <script> zones from text
2025 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
2026 $excludes['<+'.$key.'+>'] = $value;
2028 if ($excludes) {
2029 $text = str_replace($excludes,array_keys($excludes),$text);
2032 /// this is the meat of the code - this is run every time
2033 $text = str_replace($e[$lang], $img[$lang], $text);
2035 // Recover all the <script> zones to text
2036 if ($excludes) {
2037 $text = str_replace(array_keys($excludes),$excludes,$text);
2042 * Given plain text, makes it into HTML as nicely as possible.
2043 * May contain HTML tags already
2045 * @uses $CFG
2046 * @param string $text The string to convert.
2047 * @param boolean $smiley Convert any smiley characters to smiley images?
2048 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
2049 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2050 * @return string
2053 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
2056 global $CFG;
2058 /// Remove any whitespace that may be between HTML tags
2059 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
2061 /// Remove any returns that precede or follow HTML tags
2062 $text = eregi_replace("([\n\r])<", " <", $text);
2063 $text = eregi_replace(">([\n\r])", "> ", $text);
2065 convert_urls_into_links($text);
2067 /// Make returns into HTML newlines.
2068 if ($newlines) {
2069 $text = nl2br($text);
2072 /// Turn smileys into images.
2073 if ($smiley) {
2074 replace_smilies($text);
2077 /// Wrap the whole thing in a paragraph tag if required
2078 if ($para) {
2079 return '<p>'.$text.'</p>';
2080 } else {
2081 return $text;
2086 * Given Markdown formatted text, make it into XHTML using external function
2088 * @uses $CFG
2089 * @param string $text The markdown formatted text to be converted.
2090 * @return string Converted text
2092 function markdown_to_html($text) {
2093 global $CFG;
2095 require_once($CFG->libdir .'/markdown.php');
2097 return Markdown($text);
2101 * Given HTML text, make it into plain text using external function
2103 * @uses $CFG
2104 * @param string $html The text to be converted.
2105 * @return string
2107 function html_to_text($html) {
2109 global $CFG;
2111 require_once($CFG->libdir .'/html2text.php');
2113 return html2text($html);
2117 * Given some text this function converts any URLs it finds into HTML links
2119 * @param string $text Passed in by reference. The string to be searched for urls.
2121 function convert_urls_into_links(&$text) {
2122 /// Make lone URLs into links. eg http://moodle.com/
2123 $text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
2124 "\\1<a href=\"\\2://\\3\\4\" target=\"_blank\">\\2://\\3\\4</a>", $text);
2126 /// eg www.moodle.com
2127 $text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
2128 "\\1<a href=\"http://www.\\2\\3\" target=\"_blank\">www.\\2\\3</a>", $text);
2132 * This function will highlight search words in a given string
2133 * It cares about HTML and will not ruin links. It's best to use
2134 * this function after performing any conversions to HTML.
2135 * Function found here: http://forums.devshed.com/t67822/scdaa2d1c3d4bacb4671d075ad41f0854.html
2137 * @param string $needle The string to search for
2138 * @param string $haystack The string to search for $needle in
2139 * @param int $case whether to do case-sensitive or insensitive matching.
2140 * @return string
2141 * @todo Finish documenting this function
2143 function highlight($needle, $haystack, $case=0,
2144 $left_string='<span class="highlight">', $right_string='</span>') {
2145 if (empty($needle)) {
2146 return $haystack;
2149 //$list_of_words = eregi_replace("[^-a-zA-Z0-9&.']", " ", $needle); // bug 3101
2150 $list_of_words = $needle;
2151 $list_array = explode(' ', $list_of_words);
2152 for ($i=0; $i<sizeof($list_array); $i++) {
2153 if (strlen($list_array[$i]) == 1) {
2154 $list_array[$i] = '';
2157 $list_of_words = implode(' ', $list_array);
2158 $list_of_words_cp = $list_of_words;
2159 $final = array();
2160 preg_match_all('/<(.+?)>/is',$haystack,$list_of_words);
2162 foreach (array_unique($list_of_words[0]) as $key=>$value) {
2163 $final['<|'.$key.'|>'] = $value;
2166 $haystack = str_replace($final,array_keys($final),$haystack);
2167 $list_of_words_cp = eregi_replace(' +', '|', $list_of_words_cp);
2169 if ($list_of_words_cp{0}=='|') {
2170 $list_of_words_cp{0} = '';
2172 if ($list_of_words_cp{strlen($list_of_words_cp)-1}=='|') {
2173 $list_of_words_cp{strlen($list_of_words_cp)-1}='';
2176 $list_of_words_cp = trim($list_of_words_cp);
2178 if ($list_of_words_cp) {
2180 $list_of_words_cp = "(". $list_of_words_cp .")";
2182 if (!$case){
2183 $haystack = eregi_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2184 } else {
2185 $haystack = ereg_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2188 $haystack = str_replace(array_keys($final),$final,$haystack);
2190 return $haystack;
2194 * This function will highlight instances of $needle in $haystack
2195 * It's faster that the above function and doesn't care about
2196 * HTML or anything.
2198 * @param string $needle The string to search for
2199 * @param string $haystack The string to search for $needle in
2200 * @return string
2202 function highlightfast($needle, $haystack) {
2204 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
2206 $pos = 0;
2208 foreach ($parts as $key => $part) {
2209 $parts[$key] = substr($haystack, $pos, strlen($part));
2210 $pos += strlen($part);
2212 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2213 $pos += strlen($needle);
2216 return (join('', $parts));
2220 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2221 * Internationalisation, for print_header and backup/restorelib.
2222 * @param $dir Default false.
2223 * @return string Attributes.
2225 function get_html_lang($dir = false) {
2226 $direction = '';
2227 if ($dir) {
2228 if (get_string('thisdirection') == 'rtl') {
2229 $direction = ' dir="rtl"';
2230 } else {
2231 $direction = ' dir="ltr"';
2234 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2235 $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
2236 @header('Content-Language: '.$language);
2237 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2241 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
2244 * Print a standard header
2246 * @uses $USER
2247 * @uses $CFG
2248 * @uses $SESSION
2249 * @param string $title Appears at the top of the window
2250 * @param string $heading Appears at the top of the page
2251 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2252 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2253 * @param string $meta Meta tags to be added to the header
2254 * @param boolean $cache Should this page be cacheable?
2255 * @param string $button HTML code for a button (usually for module editing)
2256 * @param string $menu HTML code for a popup menu
2257 * @param boolean $usexml use XML for this page
2258 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2259 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2261 function print_header ($title='', $heading='', $navigation='', $focus='',
2262 $meta='', $cache=true, $button='&nbsp;', $menu='',
2263 $usexml=false, $bodytags='', $return=false) {
2265 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
2267 $heading = format_string($heading); // Fix for MDL-8582
2269 /// This makes sure that the header is never repeated twice on a page
2270 if (defined('HEADER_PRINTED')) {
2271 debugging('print_header() was called more than once - this should not happen. Please check the code for this page closely. Note: error() and redirect() are now safe to call after print_header().');
2272 return;
2274 define('HEADER_PRINTED', 'true');
2277 /// Add the required stylesheets
2278 $stylesheetshtml = '';
2279 foreach ($CFG->stylesheets as $stylesheet) {
2280 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2282 $meta = $stylesheetshtml.$meta;
2285 /// Add the meta page from the themes if any were requested
2287 $metapage = '';
2289 if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
2290 ob_start();
2291 include_once($CFG->dirroot.'/theme/standard/meta.php');
2292 $metapage .= ob_get_contents();
2293 ob_end_clean();
2296 if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
2297 if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
2298 ob_start();
2299 include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
2300 $metapage .= ob_get_contents();
2301 ob_end_clean();
2305 if (!isset($THEME->metainclude) || $THEME->metainclude) {
2306 if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
2307 ob_start();
2308 include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
2309 $metapage .= ob_get_contents();
2310 ob_end_clean();
2314 $meta = $meta."\n".$metapage;
2317 /// Add the required JavaScript Libraries
2318 $meta .= "\n".require_js();
2320 if(is_newnav($navigation)){
2321 $home = false;
2322 } else {
2323 if ($navigation == 'home') {
2324 $home = true;
2325 $navigation = '';
2326 } else {
2327 $home = false;
2331 /// This is another ugly hack to make navigation elements available to print_footer later
2332 $THEME->title = $title;
2333 $THEME->heading = $heading;
2334 $THEME->navigation = $navigation;
2335 $THEME->button = $button;
2336 $THEME->menu = $menu;
2337 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2339 if ($button == '') {
2340 $button = '&nbsp;';
2343 if (!$menu and $navigation) {
2344 if (empty($CFG->loginhttps)) {
2345 $wwwroot = $CFG->wwwroot;
2346 } else {
2347 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
2349 $menu = user_login_string($COURSE);
2352 if (isset($SESSION->justloggedin)) {
2353 unset($SESSION->justloggedin);
2354 if (!empty($CFG->displayloginfailures)) {
2355 if (!empty($USER->username) and $USER->username != 'guest') {
2356 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
2357 $menu .= '&nbsp;<font size="1">';
2358 if (empty($count->accounts)) {
2359 $menu .= get_string('failedloginattempts', '', $count);
2360 } else {
2361 $menu .= get_string('failedloginattemptsall', '', $count);
2363 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
2364 $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
2365 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
2367 $menu .= '</font>';
2374 $meta = '<meta http-equiv="content-type" content="text/html; charset=utf-8" />'. "\n". $meta ."\n";
2375 if (!$usexml) {
2376 @header('Content-type: text/html; charset=utf-8');
2379 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2380 $direction = get_html_lang($dir=true);
2382 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2383 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2384 @header('Pragma: no-cache');
2385 @header('Expires: ');
2386 } else { // Do everything we can to always prevent clients and proxies caching
2387 @header('Cache-Control: no-store, no-cache, must-revalidate');
2388 @header('Cache-Control: post-check=0, pre-check=0', false);
2389 @header('Pragma: no-cache');
2390 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2391 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2393 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2394 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
2396 @header('Accept-Ranges: none');
2398 $currentlanguage = current_language();
2400 if (empty($usexml)) {
2401 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2402 } else {
2403 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2404 if(!$mathplayer) {
2405 header('Content-Type: application/xhtml+xml');
2407 echo '<?xml version="1.0" ?>'."\n";
2408 if (!empty($CFG->xml_stylesheets)) {
2409 $stylesheets = explode(';', $CFG->xml_stylesheets);
2410 foreach ($stylesheets as $stylesheet) {
2411 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
2414 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
2415 if (!empty($CFG->xml_doctype_extra)) {
2416 echo ' plus '. $CFG->xml_doctype_extra;
2418 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
2419 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2420 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
2421 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2422 $direction";
2423 if($mathplayer) {
2424 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
2425 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2426 $meta .= '</object>'."\n";
2427 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2431 // Clean up the title
2433 $title = format_string($title); // fix for MDL-8582
2434 $title = str_replace('"', '&quot;', $title);
2436 // Create class and id for this page
2438 page_id_and_class($pageid, $pageclass);
2440 $pageclass .= ' course-'.$COURSE->id;
2442 if (($pageid != 'site-index') && ($pageid != 'course-view') &&
2443 (strstr($pageid, 'admin') === FALSE)) {
2444 $pageclass .= ' nocoursepage';
2447 if (!isloggedin()) {
2448 $pageclass .= ' notloggedin';
2451 if (!empty($USER->editing)) {
2452 $pageclass .= ' editing';
2455 if (!empty($CFG->blocksdrag)) {
2456 $pageclass .= ' drag';
2459 if (!empty($CFG->langdirection)) {
2460 $pageclass .= ' ' . $CFG->langdirection;
2463 $pageclass .= ' lang-'.$currentlanguage;
2465 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
2467 ob_start();
2468 include($CFG->header);
2469 $output = ob_get_contents();
2470 ob_end_clean();
2472 $output = force_strict_header($output);
2474 if (!empty($CFG->messaging)) {
2475 $output .= message_popup_window();
2478 if ($return) {
2479 return $output;
2480 } else {
2481 echo $output;
2486 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2487 * and substitute the XHTML strict document type.
2488 * Note, requires the 'xmlns' fix in function print_header above.
2489 * See: http://tracker.moodle.org/browse/MDL-7883
2490 * TODO:
2492 function force_strict_header($output) {
2493 global $CFG;
2494 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2495 $xsl = '/lib/xhtml.xsl';
2497 if (!headers_sent() && debugging(NULL, DEBUG_DEVELOPER)) { // In developer debugging, the browser will barf
2498 $ctype = 'Content-Type: ';
2499 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2501 if (isset($_SERVER['HTTP_ACCEPT'])
2502 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2503 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2504 // Firefox et al.
2505 $ctype .= 'application/xhtml+xml';
2506 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2508 } else if (file_exists($CFG->dirroot.$xsl)
2509 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2510 // XSL hack for IE 5+ on Windows.
2511 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2512 $www_xsl = $CFG->wwwroot .$xsl;
2513 $ctype .= 'application/xml';
2514 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2515 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2517 } else {
2518 //ELSE: Mac/IE, old/non-XML browsers.
2519 $ctype .= 'text/html';
2520 $prolog = '';
2522 @header($ctype.'; charset=utf-8');
2523 $output = $prolog . $output;
2525 // Test parser error-handling.
2526 if (isset($_GET['error'])) {
2527 $output .= "__ TEST: XML well-formed error < __\n";
2531 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
2533 return $output;
2539 * This version of print_header is simpler because the course name does not have to be
2540 * provided explicitly in the strings. It can be used on the site page as in courses
2541 * Eventually all print_header could be replaced by print_header_simple
2543 * @param string $title Appears at the top of the window
2544 * @param string $heading Appears at the top of the page
2545 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2546 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2547 * @param string $meta Meta tags to be added to the header
2548 * @param boolean $cache Should this page be cacheable?
2549 * @param string $button HTML code for a button (usually for module editing)
2550 * @param string $menu HTML code for a popup menu
2551 * @param boolean $usexml use XML for this page
2552 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2553 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2555 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
2556 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
2558 global $COURSE, $CFG;
2560 $shortname ='';
2561 if ($COURSE->id != SITEID) {
2562 $shortname = '<a href="'.$CFG->wwwroot.'/course/view.php?id='. $COURSE->id .'">'. $COURSE->shortname .'</a> ->';
2565 // If old style nav prepend course short name otherwise leave $navigation object alone
2566 if (!is_newnav($navigation)) {
2567 $navigation = $shortname.' '.$navigation;
2570 $output = print_header($COURSE->shortname .': '. $title, $COURSE->fullname .' '. $heading, $navigation, $focus, $meta,
2571 $cache, $button, $menu, $usexml, $bodytags, true);
2573 if ($return) {
2574 return $output;
2575 } else {
2576 echo $output;
2582 * Can provide a course object to make the footer contain a link to
2583 * to the course home page, otherwise the link will go to the site home
2585 * @uses $CFG
2586 * @uses $USER
2587 * @param course $course {@link $COURSE} object containing course information
2588 * @param ? $usercourse ?
2589 * @todo Finish documenting this function
2591 function print_footer($course=NULL, $usercourse=NULL, $return=false) {
2592 global $USER, $CFG, $THEME, $COURSE;
2594 if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
2595 admin_externalpage_print_footer();
2596 return;
2599 /// Course links
2600 if ($course) {
2601 if (is_string($course) && $course == 'none') { // Don't print any links etc
2602 $homelink = '';
2603 $loggedinas = '';
2604 $home = false;
2605 } else if (is_string($course) && $course == 'home') { // special case for site home page - please do not remove
2606 $course = get_site();
2607 $homelink = '<div class="sitelink">'.
2608 '<a title="moodle '. $CFG->release .' ('. $CFG->version .')" href="http://moodle.org/">'.
2609 '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
2610 $home = true;
2611 } else {
2612 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
2613 '/course/view.php?id='.$course->id.'">'.format_string($course->shortname).'</a></div>';
2614 $home = false;
2616 } else {
2617 $course = get_site(); // Set course as site course by default
2618 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
2619 $home = false;
2622 /// Set up some other navigation links (passed from print_header by ugly hack)
2623 $menu = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
2624 $title = isset($THEME->title) ? $THEME->title : '';
2625 $button = isset($THEME->button) ? $THEME->button : '';
2626 $heading = isset($THEME->heading) ? $THEME->heading : '';
2627 $navigation = isset($THEME->navigation) ? $THEME->navigation : '';
2628 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2631 /// Set the user link if necessary
2632 if (!$usercourse and is_object($course)) {
2633 $usercourse = $course;
2636 if (!isset($loggedinas)) {
2637 $loggedinas = user_login_string($usercourse, $USER);
2640 if ($loggedinas == $menu) {
2641 $menu = '';
2644 /// Provide some performance info if required
2645 $performanceinfo = '';
2646 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2647 $perf = get_performance_info();
2648 if (defined('MDL_PERFTOLOG')) {
2649 error_log("PERF: " . $perf['txt']);
2651 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
2652 $performanceinfo = $perf['html'];
2657 /// Include the actual footer file
2659 ob_start();
2660 include($CFG->footer);
2661 $output = ob_get_contents();
2662 ob_end_clean();
2664 if ($return) {
2665 return $output;
2666 } else {
2667 echo $output;
2672 * Returns the name of the current theme
2674 * @uses $CFG
2675 * @uses $USER
2676 * @uses $SESSION
2677 * @uses $COURSE
2678 * @uses $FULLME
2679 * @return string
2681 function current_theme() {
2682 global $CFG, $USER, $SESSION, $COURSE, $FULLME;
2684 if (empty($CFG->themeorder)) {
2685 $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
2686 } else {
2687 $themeorder = $CFG->themeorder;
2690 $theme = '';
2691 foreach ($themeorder as $themetype) {
2693 if (!empty($theme)) continue;
2695 switch ($themetype) {
2696 case 'page': // Page theme is for special page-only themes set by code
2697 if (!empty($CFG->pagetheme)) {
2698 $theme = $CFG->pagetheme;
2700 break;
2701 case 'course':
2702 if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) {
2703 $theme = $COURSE->theme;
2705 break;
2706 case 'category':
2707 if (!empty($CFG->allowcategorythemes)) {
2708 /// Nasty hack to check if we're in a category page
2709 if (stripos($FULLME, 'course/category.php') !== false) {
2710 global $id;
2711 if (!empty($id)) {
2712 $theme = current_category_theme($id);
2714 /// Otherwise check if we're in a course that has a category theme set
2715 } else if (!empty($COURSE->category)) {
2716 $theme = current_category_theme($COURSE->category);
2719 break;
2720 case 'session':
2721 if (!empty($SESSION->theme)) {
2722 $theme = $SESSION->theme;
2724 break;
2725 case 'user':
2726 if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) {
2727 $theme = $USER->theme;
2729 break;
2730 case 'site':
2731 $theme = $CFG->theme;
2732 break;
2733 default:
2734 /// do nothing
2738 /// A final check in case 'site' was not included in $CFG->themeorder
2739 if (empty($theme)) {
2740 $theme = $CFG->theme;
2743 return $theme;
2747 * Retrieves the category theme if one exists, otherwise checks the parent categories.
2748 * Recursive function.
2750 * @uses $COURSE
2751 * @param integer $categoryid id of the category to check
2752 * @return string theme name
2754 function current_category_theme($categoryid=0) {
2755 global $COURSE;
2757 /// Use the COURSE global if the categoryid not set
2758 if (empty($categoryid)) {
2759 if (!empty($COURSE->category)) {
2760 $categoryid = $COURSE->category;
2761 } else {
2762 return false;
2766 /// Retrieve the current category
2767 if ($category = get_record('course_categories', 'id', $categoryid)) {
2769 /// Return the category theme if it exists
2770 if (!empty($category->theme)) {
2771 return $category->theme;
2773 /// Otherwise try the parent category if one exists
2774 } else if (!empty($category->parent)) {
2775 return current_category_theme($category->parent);
2778 /// Return false if we can't find the category record
2779 } else {
2780 return false;
2785 * This function is called by stylesheets to set up the header
2786 * approriately as well as the current path
2788 * @uses $CFG
2789 * @param int $lastmodified ?
2790 * @param int $lifetime ?
2791 * @param string $thename ?
2793 function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='', $langdir='') {
2795 global $CFG, $THEME;
2797 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
2798 $lastmodified = time();
2800 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
2801 header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
2802 header('Cache-Control: max-age='. $lifetime);
2803 header('Pragma: ');
2804 header('Content-type: text/css'); // Correct MIME type
2806 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
2808 if (empty($themename)) {
2809 $themename = current_theme(); // So we have something. Normally not needed.
2810 } else {
2811 $themename = clean_param($themename, PARAM_SAFEDIR);
2814 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
2815 unset($THEME);
2816 include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
2819 /// If this is the standard theme calling us, then find out what sheets we need
2821 if ($themename == 'standard') {
2822 if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
2823 $THEME->sheets = $DEFAULT_SHEET_LIST;
2824 } else if (empty($THEME->standardsheets)) { // We can stop right now!
2825 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
2826 exit;
2827 } else { // Use the provided subset only
2828 $THEME->sheets = $THEME->standardsheets;
2831 /// If we are a parent theme, then check for parent definitions
2833 } else if (!empty($THEME->parent) && $themename == $THEME->parent) {
2834 if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have
2835 $THEME->sheets = $DEFAULT_SHEET_LIST;
2836 } else if (empty($THEME->parentsheets)) { // We can stop right now!
2837 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
2838 exit;
2839 } else { // Use the provided subset only
2840 $THEME->sheets = $THEME->parentsheets;
2844 /// Work out the last modified date for this theme
2846 foreach ($THEME->sheets as $sheet) {
2847 if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
2848 $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
2849 if ($sheetmodified > $lastmodified) {
2850 $lastmodified = $sheetmodified;
2856 /// Get a list of all the files we want to include
2857 $files = array();
2859 foreach ($THEME->sheets as $sheet) {
2860 $files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
2863 if ($themename == 'standard') { // Add any standard styles included in any modules
2864 if (!empty($THEME->modsheets)) { // Search for styles.php within activity modules
2865 if ($mods = get_list_of_plugins('mod')) {
2866 foreach ($mods as $mod) {
2867 if (file_exists($CFG->dirroot.'/mod/'.$mod.'/styles.php')) {
2868 $files[] = array($CFG->dirroot, '/mod/'.$mod.'/styles.php');
2874 if (!empty($THEME->blocksheets)) { // Search for styles.php within block modules
2875 if ($mods = get_list_of_plugins('blocks')) {
2876 foreach ($mods as $mod) {
2877 if (file_exists($CFG->dirroot.'/blocks/'.$mod.'/styles.php')) {
2878 $files[] = array($CFG->dirroot, '/blocks/'.$mod.'/styles.php');
2884 if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
2885 if ($mods = get_list_of_plugins('format','',$CFG->dirroot.'/course')) {
2886 foreach ($mods as $mod) {
2887 if (file_exists($CFG->dirroot.'/course/format/'.$mod.'/styles.php')) {
2888 $files[] = array($CFG->dirroot, '/course/format/'.$mod.'/styles.php');
2894 if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
2895 if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
2896 $files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
2901 $oppositlangdir = ($langdir == 'rtl') ? '_ltr' : '_rtl';
2903 if ($files) {
2904 /// Produce a list of all the files first
2905 echo '/**************************************'."\n";
2906 echo ' * THEME NAME: '.$themename."\n *\n";
2907 echo ' * Files included in this sheet:'."\n *\n";
2908 foreach ($files as $file) {
2909 if (strstr($file[1], $oppositlangdir)) continue;
2910 echo ' * '.$file[1]."\n";
2912 echo ' **************************************/'."\n\n";
2915 /// check if csscobstants is set
2916 if (!empty($THEME->cssconstants)) {
2917 require_once("$CFG->libdir/cssconstants.php");
2918 /// Actually collect all the files in order.
2919 $css = '';
2920 foreach ($files as $file) {
2921 if (strstr($file[1], $oppositlangdir)) continue;
2922 $css .= '/***** '.$file[1].' start *****/'."\n\n";
2923 $css .= file_get_contents($file[0].'/'.$file[1]);
2924 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
2926 /// replace css_constants with their values
2927 echo replace_cssconstants($css);
2928 } else {
2929 /// Actually output all the files in order.
2930 if (empty($CFG->CSSEdit) && empty($THEME->CSSEdit)) {
2931 foreach ($files as $file) {
2932 if (strstr($file[1], $oppositlangdir)) continue;
2933 echo '/***** '.$file[1].' start *****/'."\n\n";
2934 @include_once($file[0].'/'.$file[1]);
2935 echo '/***** '.$file[1].' end *****/'."\n\n";
2937 } else {
2938 foreach ($files as $file) {
2939 if (strstr($file[1], $oppositlangdir)) continue;
2940 echo '/* @group '.$file[1].' */'."\n\n";
2941 if (strstr($file[1], '.css') !== FALSE) {
2942 echo '@import url("'.$CFG->themewww.'/'.$file[1].'");'."\n\n";
2943 } else {
2944 @include_once($file[0].'/'.$file[1]);
2946 echo '/* @end */'."\n\n";
2952 return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
2956 function theme_setup($theme = '', $params=NULL) {
2957 /// Sets up global variables related to themes
2959 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
2961 if (empty($theme)) {
2962 $theme = current_theme();
2965 /// If the theme doesn't exist for some reason then revert to standardwhite
2966 if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
2967 $CFG->theme = $theme = 'standardwhite';
2970 /// Load up the theme config
2971 $THEME = NULL; // Just to be sure
2972 include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
2974 /// Put together the parameters
2975 if (!$params) {
2976 $params = array();
2979 /// Add parameter for the language direction
2980 $params[] = 'langdir='.get_string('thisdirection');
2982 if ($theme != $CFG->theme) {
2983 $params[] = 'forceconfig='.$theme;
2986 /// Force language too if required
2987 if (!empty($THEME->langsheets)) {
2988 $params[] = 'lang='.current_language();
2992 /// Convert params to string
2993 if ($params) {
2994 $paramstring = '?'.implode('&', $params);
2995 } else {
2996 $paramstring = '';
2999 /// Set up image paths
3000 if(isset($CFG->smartpix) && $CFG->smartpix==1) {
3001 if($CFG->slasharguments) { // Use this method if possible for better caching
3002 $extra='';
3003 } else {
3004 $extra='?file=';
3007 $CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
3008 $CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
3009 } else if (empty($THEME->custompix)) { // Could be set in the above file
3010 $CFG->pixpath = $CFG->wwwroot .'/pix';
3011 $CFG->modpixpath = $CFG->wwwroot .'/mod';
3012 } else {
3013 $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
3014 $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
3017 /// Header and footer paths
3018 $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
3019 $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
3021 /// Define stylesheet loading order
3022 $CFG->stylesheets = array();
3023 if ($theme != 'standard') { /// The standard sheet is always loaded first
3024 $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
3026 if (!empty($THEME->parent)) { /// Parent stylesheets are loaded next
3027 $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
3029 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
3031 /// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
3032 if (!empty($HTTPSPAGEREQUIRED)) {
3033 $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
3034 $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
3035 $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
3036 foreach ($CFG->stylesheets as $key => $stylesheet) {
3037 $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
3045 * Returns text to be displayed to the user which reflects their login status
3047 * @uses $CFG
3048 * @uses $USER
3049 * @param course $course {@link $COURSE} object containing course information
3050 * @param user $user {@link $USER} object containing user information
3051 * @return string
3053 function user_login_string($course=NULL, $user=NULL) {
3054 global $USER, $CFG, $SITE;
3056 if (empty($user) and !empty($USER->id)) {
3057 $user = $USER;
3060 if (empty($course)) {
3061 $course = $SITE;
3064 if (!empty($user->realuser)) {
3065 if ($realuser = get_record('user', 'id', $user->realuser)) {
3066 $fullname = fullname($realuser, true);
3067 $realuserinfo = " [<a $CFG->frametarget
3068 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=1&amp;sesskey=".sesskey()."\">$fullname</a>] ";
3070 } else {
3071 $realuserinfo = '';
3074 if (empty($CFG->loginhttps)) {
3075 $wwwroot = $CFG->wwwroot;
3076 } else {
3077 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
3080 if (empty($course->id)) {
3081 // $course->id is not defined during installation
3082 return '';
3083 } else if (!empty($user->id)) {
3084 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3086 $fullname = fullname($user, true);
3087 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a>";
3088 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid)) {
3089 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
3091 if (isset($user->username) && $user->username == 'guest') {
3092 $loggedinas = $realuserinfo.get_string('loggedinasguest').
3093 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3094 } else if (!empty($user->switchrole[$context->id])) {
3095 $rolename = '';
3096 if ($role = get_record('role', 'id', $user->switchrole[$context->id])) {
3097 $rolename = ': '.format_string($role->name);
3099 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
3100 " (<a $CFG->frametarget
3101 href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
3102 } else {
3103 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
3104 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
3106 } else {
3107 $loggedinas = get_string('loggedinnot', 'moodle').
3108 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3110 return '<div class="logininfo">'.$loggedinas.'</div>';
3114 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
3115 * If not it applies sensible defaults.
3117 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
3118 * search forum block, etc. Important: these are 'silent' in a screen-reader
3119 * (unlike &gt; &raquo;), and must be accompanied by text.
3120 * @uses $THEME
3122 function check_theme_arrows() {
3123 global $THEME;
3125 if (!isset($THEME->rarrow) and !isset($THEME->larrow)) {
3126 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
3127 // Also OK in Win 9x/2K/IE 5.x
3128 $THEME->rarrow = '&#x25BA;';
3129 $THEME->larrow = '&#x25C4;';
3130 $uagent = $_SERVER['HTTP_USER_AGENT'];
3131 if (false !== strpos($uagent, 'Opera')
3132 || false !== strpos($uagent, 'Mac')) {
3133 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
3134 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
3135 $THEME->rarrow = '&#x25B6;';
3136 $THEME->larrow = '&#x25C0;';
3138 elseif (false !== strpos($uagent, 'Konqueror')) {
3139 $THEME->rarrow = '&rarr;';
3140 $THEME->larrow = '&larr;';
3142 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
3143 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
3144 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
3145 // To be safe, non-Unicode browsers!
3146 $THEME->rarrow = '&gt;';
3147 $THEME->larrow = '&lt;';
3153 * Return the right arrow with text ('next'), and optionally embedded in a link.
3154 * See function above, check_theme_arrows.
3155 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3156 * @param string $url An optional link to use in a surrounding HTML anchor.
3157 * @param bool $accesshide True if text should be hidden (for screen readers only).
3158 * @param string $addclass Additional class names for the link, or the arrow character.
3159 * @return string HTML string.
3161 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
3162 global $THEME;
3163 check_theme_arrows();
3164 $arrowclass = 'arrow ';
3165 if (! $url) {
3166 $arrowclass .= $addclass;
3168 $arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow.'</span>';
3169 $htmltext = '';
3170 if ($text) {
3171 $htmltext = $text.'&nbsp;';
3172 if ($accesshide) {
3173 $htmltext = '<span class="accesshide">'.$htmltext.'</span>';
3176 if ($url) {
3177 $class = '';
3178 if ($addclass) {
3179 $class =" class=\"$addclass\"";
3181 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
3183 return $htmltext.$arrow;
3187 * Return the left arrow with text ('previous'), and optionally embedded in a link.
3188 * See function above, check_theme_arrows.
3189 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3190 * @param string $url An optional link to use in a surrounding HTML anchor.
3191 * @param bool $accesshide True if text should be hidden (for screen readers only).
3192 * @param string $addclass Additional class names for the link, or the arrow character.
3193 * @return string HTML string.
3195 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
3196 global $THEME;
3197 check_theme_arrows();
3198 $arrowclass = 'arrow ';
3199 if (! $url) {
3200 $arrowclass .= $addclass;
3202 $arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow.'</span>';
3203 $htmltext = '';
3204 if ($text) {
3205 $htmltext = '&nbsp;'.$text;
3206 if ($accesshide) {
3207 $htmltext = '<span class="accesshide">'.$htmltext.'</span>';
3210 if ($url) {
3211 $class = '';
3212 if ($addclass) {
3213 $class =" class=\"$addclass\"";
3215 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
3217 return $arrow.$htmltext;
3221 * Return the breadcrumb trail navigation separator.
3222 * @return string HTML string.
3224 function get_separator() {
3225 //Accessibility: the 'hidden' slash is preferred for screen readers.
3226 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
3232 * Prints breadcrumb trail of links, called in theme/-/header.html
3234 * @uses $CFG
3235 * @param mixed $navigation The breadcrumb navigation string to be printed
3236 * @param string $separator The breadcrumb trail separator. The default 0 leads to the use
3237 * of $THEME->rarrow, themes could use '&rarr;', '/', or '' for a style-sheet solution.
3238 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
3240 function print_navigation ($navigation, $separator=0, $return=false) {
3241 global $CFG, $THEME;
3242 $output = '';
3244 if (0 === $separator) {
3245 $separator = get_separator();
3247 else {
3248 $separator = '<span class="sep">'. $separator .'</span>';
3251 if ($navigation) {
3253 if (is_newnav($navigation)) {
3254 if ($return) {
3255 return($navigation['navlinks']);
3256 } else {
3257 echo $navigation['navlinks'];
3258 return;
3260 } else {
3261 debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER);
3264 if (!is_array($navigation)) {
3265 $ar = explode('->', $navigation);
3266 $navigation = array();
3268 foreach ($ar as $a) {
3269 if (strpos($a, '</a>') === false) {
3270 $navigation[] = array('title' => $a, 'url' => '');
3271 } else {
3272 if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
3273 $navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
3279 if (! $site = get_site()) {
3280 $site = new object();
3281 $site->shortname = get_string('home');
3284 //Accessibility: breadcrumb links now in a list, &raquo; replaced with a 'silent' character.
3285 $nav_text = get_string('youarehere','access');
3286 $output .= '<h2 class="accesshide">'.$nav_text."</h2><ul>\n";
3288 $output .= '<li class="first">'."\n".'<a '.$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3289 .$CFG->wwwroot.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))
3290 && !empty($USER->id) && !empty($CFG->mymoodleredirect) && !isguest())
3291 ? '/my' : '') .'/">'. format_string($site->shortname) ."</a>\n</li>\n";
3294 foreach ($navigation as $navitem) {
3295 $title = trim(strip_tags(format_string($navitem['title'], false)));
3296 $url = $navitem['url'];
3298 if (empty($url)) {
3299 $output .= '<li class="first">'."$separator $title</li>\n";
3300 } else {
3301 $output .= '<li class="first">'."$separator\n<a ".$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3302 .$url.'">'."$title</a>\n</li>\n";
3306 $output .= "</ul>\n";
3309 if ($return) {
3310 return $output;
3311 } else {
3312 echo $output;
3317 * Prints a string in a specified size (retained for backward compatibility)
3319 * @param string $text The text to be displayed
3320 * @param int $size The size to set the font for text display.
3322 function print_headline($text, $size=2, $return=false) {
3323 $output = print_heading($text, '', $size, true);
3324 if ($return) {
3325 return $output;
3326 } else {
3327 echo $output;
3332 * Prints text in a format for use in headings.
3334 * @param string $text The text to be displayed
3335 * @param string $align The alignment of the printed paragraph of text
3336 * @param int $size The size to set the font for text display.
3338 function print_heading($text, $align='', $size=2, $class='main', $return=false) {
3339 if ($align) {
3340 $align = ' style="text-align:'.$align.';"';
3342 if ($class) {
3343 $class = ' class="'.$class.'"';
3345 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
3347 if ($return) {
3348 return $output;
3349 } else {
3350 echo $output;
3355 * Centered heading with attached help button (same title text)
3356 * and optional icon attached
3358 * @param string $text The text to be displayed
3359 * @param string $helppage The help page to link to
3360 * @param string $module The module whose help should be linked to
3361 * @param string $icon Image to display if needed
3363 function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
3364 $output = '';
3365 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
3366 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
3367 $output .= '</h2>';
3369 if ($return) {
3370 return $output;
3371 } else {
3372 echo $output;
3377 function print_heading_block($heading, $class='', $return=false) {
3378 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
3379 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
3381 if ($return) {
3382 return $output;
3383 } else {
3384 echo $output;
3390 * Print a link to continue on to another page.
3392 * @uses $CFG
3393 * @param string $link The url to create a link to.
3395 function print_continue($link, $return=false) {
3397 global $CFG;
3399 // in case we are logging upgrade in admin/index.php stop it
3400 if (function_exists('upgrade_log_finish')) {
3401 upgrade_log_finish();
3404 $output = '';
3406 if ($link == '') {
3407 if (!empty($_SERVER['HTTP_REFERER'])) {
3408 $link = $_SERVER['HTTP_REFERER'];
3409 $link = str_replace('&', '&amp;', $link); // make it valid XHTML
3410 } else {
3411 $link = $CFG->wwwroot .'/';
3415 $output .= '<div class="continuebutton">';
3417 $output .= print_single_button($link, NULL, get_string('continue'), 'post', $CFG->framename, true);
3418 $output .= '</div>'."\n";
3420 if ($return) {
3421 return $output;
3422 } else {
3423 echo $output;
3429 * Print a message in a standard themed box.
3430 * Replaces print_simple_box (see deprecatedlib.php)
3432 * @param string $message, the content of the box
3433 * @param string $classes, space-separated class names.
3434 * @param string $ids, space-separated id names.
3435 * @param boolean $return, return as string or just print it
3437 function print_box($message, $classes='generalbox', $ids='', $return=false) {
3439 $output = print_box_start($classes, $ids, true);
3440 $output .= stripslashes_safe($message);
3441 $output .= print_box_end(true);
3443 if ($return) {
3444 return $output;
3445 } else {
3446 echo $output;
3451 * Starts a box using divs
3452 * Replaces print_simple_box_start (see deprecatedlib.php)
3454 * @param string $classes, space-separated class names.
3455 * @param string $ids, space-separated id names.
3456 * @param boolean $return, return as string or just print it
3458 function print_box_start($classes='generalbox', $ids='', $return=false) {
3459 $output = '';
3461 if ($ids) {
3462 $ids = ' id="'.$ids.'"';
3465 $output .= '<div'.$ids.' class="box '.$classes.'">';
3467 if ($return) {
3468 return $output;
3469 } else {
3470 echo $output;
3476 * Simple function to end a box (see above)
3477 * Replaces print_simple_box_end (see deprecatedlib.php)
3479 * @param boolean $return, return as string or just print it
3481 function print_box_end($return=false) {
3482 $output = '</div>';
3483 if ($return) {
3484 return $output;
3485 } else {
3486 echo $output;
3492 * Print a self contained form with a single submit button.
3494 * @param string $link ?
3495 * @param array $options ?
3496 * @param string $label ?
3497 * @param string $method ?
3498 * @todo Finish documenting this function
3500 function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='') {
3501 $output = '';
3502 $link = str_replace('"', '&quot;', $link); //basic XSS protection
3503 $output .= '<div class="singlebutton">';
3504 // taking target out, will need to add later target="'.$target.'"
3505 $output .= '<form action="'. $link .'" method="'. $method .'">';
3506 $output .= '<div>';
3507 if ($options) {
3508 foreach ($options as $name => $value) {
3509 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
3512 if ($tooltip) {
3513 $tooltip = 'title="' . s($tooltip) . '"';
3514 } else {
3515 $tooltip = '';
3517 $output .= '<input type="submit" value="'. s($label) .'" ' . $tooltip . ' /></div></form></div>';
3519 if ($return) {
3520 return $output;
3521 } else {
3522 echo $output;
3528 * Print a spacer image with the option of including a line break.
3530 * @param int $height ?
3531 * @param int $width ?
3532 * @param boolean $br ?
3533 * @todo Finish documenting this function
3535 function print_spacer($height=1, $width=1, $br=true, $return=false) {
3536 global $CFG;
3537 $output = '';
3539 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot .'/pix/spacer.gif" alt="" />';
3540 if ($br) {
3541 $output .= '<br />'."\n";
3544 if ($return) {
3545 return $output;
3546 } else {
3547 echo $output;
3552 * Given the path to a picture file in a course, or a URL,
3553 * this function includes the picture in the page.
3555 * @param string $path ?
3556 * @param int $courseid ?
3557 * @param int $height ?
3558 * @param int $width ?
3559 * @param string $link ?
3560 * @todo Finish documenting this function
3562 function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
3563 global $CFG;
3564 $output = '';
3566 if ($height) {
3567 $height = 'height="'. $height .'"';
3569 if ($width) {
3570 $width = 'width="'. $width .'"';
3572 if ($link) {
3573 $output .= '<a href="'. $link .'">';
3575 if (substr(strtolower($path), 0, 7) == 'http://') {
3576 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
3578 } else if ($courseid) {
3579 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
3580 if ($CFG->slasharguments) { // Use this method if possible for better caching
3581 $output .= $CFG->wwwroot .'/file.php/'. $courseid .'/'. $path;
3582 } else {
3583 $output .= $CFG->wwwroot .'/file.php?file=/'. $courseid .'/'. $path;
3585 $output .= '" />';
3586 } else {
3587 $output .= 'Error: must pass URL or course';
3589 if ($link) {
3590 $output .= '</a>';
3593 if ($return) {
3594 return $output;
3595 } else {
3596 echo $output;
3601 * Print the specified user's avatar.
3603 * @param int $userid ?
3604 * @param int $courseid ?
3605 * @param boolean $picture Print the user picture?
3606 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
3607 * @param boolean $return If false print picture to current page, otherwise return the output as string
3608 * @param boolean $link Enclose printed image in a link to view specified course?
3609 * @param string $target link target attribute
3610 * @param boolean $alttext use username or userspecified text in image alt attribute
3611 * return string
3612 * @todo Finish documenting this function
3614 function print_user_picture($userid, $courseid, $picture, $size=0, $return=false, $link=true, $target='', $alttext=true) {
3615 global $CFG;
3617 if ($link) {
3618 if ($target) {
3619 $target=' target="_blank"';
3621 $output = '<a '.$target.' href="'. $CFG->wwwroot .'/user/view.php?id='. $userid .'&amp;course='. $courseid .'">';
3622 } else {
3623 $output = '';
3625 if (empty($size)) {
3626 $file = 'f2';
3627 $size = 35;
3628 } else if ($size === true or $size == 1) {
3629 $file = 'f1';
3630 $size = 100;
3631 } else if ($size >= 50) {
3632 $file = 'f1';
3633 } else {
3634 $file = 'f2';
3636 $class = "userpicture";
3637 if ($picture) { // Print custom user picture
3638 if ($CFG->slasharguments) { // Use this method if possible for better caching
3639 $src = $CFG->wwwroot .'/user/pix.php/'. $userid .'/'. $file .'.jpg';
3640 } else {
3641 $src = $CFG->wwwroot .'/user/pix.php?file=/'. $userid .'/'. $file .'.jpg';
3643 } else { // Print default user pictures (use theme version if available)
3644 $class .= " defaultuserpic";
3645 $src = "$CFG->pixpath/u/$file.png";
3647 $imagealt = '';
3648 if ($alttext and $user = get_record('user','id',$userid)) {
3649 if (!empty($user->imagealt)) {
3650 $imagealt = $user->imagealt;
3651 } else {
3652 $imagealt = get_string('pictureof','',fullname($user));
3656 $output .= '<img class="'.$class.'" src="'.$src.'" alt="'.s($imagealt).'" />';
3657 if ($link) {
3658 $output .= '</a>';
3661 if ($return) {
3662 return $output;
3663 } else {
3664 echo $output;
3669 * Prints a summary of a user in a nice little box.
3671 * @uses $CFG
3672 * @uses $USER
3673 * @param user $user A {@link $USER} object representing a user
3674 * @param course $course A {@link $COURSE} object representing a course
3676 function print_user($user, $course, $messageselect=false, $return=false) {
3678 global $CFG, $USER;
3680 $output = '';
3682 static $string;
3683 static $datestring;
3684 static $countries;
3686 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3688 if (empty($string)) { // Cache all the strings for the rest of the page
3690 $string->email = get_string('email');
3691 $string->location = get_string('location');
3692 $string->lastaccess = get_string('lastaccess');
3693 $string->activity = get_string('activity');
3694 $string->unenrol = get_string('unenrol');
3695 $string->loginas = get_string('loginas');
3696 $string->fullprofile = get_string('fullprofile');
3697 $string->role = get_string('role');
3698 $string->name = get_string('name');
3699 $string->never = get_string('never');
3701 $datestring->day = get_string('day');
3702 $datestring->days = get_string('days');
3703 $datestring->hour = get_string('hour');
3704 $datestring->hours = get_string('hours');
3705 $datestring->min = get_string('min');
3706 $datestring->mins = get_string('mins');
3707 $datestring->sec = get_string('sec');
3708 $datestring->secs = get_string('secs');
3710 $countries = get_list_of_countries();
3713 /// Get the hidden field list
3714 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
3715 $hiddenfields = array();
3716 } else {
3717 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
3720 $output .= '<table class="userinfobox">';
3721 $output .= '<tr>';
3722 $output .= '<td class="left side">';
3723 $output .= print_user_picture($user->id, $course->id, $user->picture, true, true);
3724 $output .= '</td>';
3725 $output .= '<td class="content">';
3726 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
3727 $output .= '<div class="info">';
3728 if (!empty($user->role) and ($user->role <> $course->teacher)) {
3729 $output .= $string->role .': '. $user->role .'<br />';
3731 if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguest()) or
3732 has_capability('moodle/course:viewhiddenuserfields', $context)) {
3733 $output .= $string->email .': <a href="mailto:'. $user->email .'">'. $user->email .'</a><br />';
3735 if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
3736 $output .= $string->location .': ';
3737 if ($user->city && !isset($hiddenfields['city'])) {
3738 $output .= $user->city;
3740 if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
3741 if ($user->city && !isset($hiddenfields['city'])) {
3742 $output .= ', ';
3744 $output .= $countries[$user->country];
3746 $output .= '<br />';
3749 if (!isset($hiddenfields['lastaccess'])) {
3750 if ($user->lastaccess) {
3751 $output .= $string->lastaccess .': '. userdate($user->lastaccess);
3752 $output .= '&nbsp; ('. format_time(time() - $user->lastaccess, $datestring) .')';
3753 } else {
3754 $output .= $string->lastaccess .': '. $string->never;
3757 $output .= '</div></td><td class="links">';
3758 //link to blogs
3759 if ($CFG->bloglevel > 0) {
3760 $output .= '<a href="'.$CFG->wwwroot.'/blog/index.php?userid='.$user->id.'">'.get_string('blogs','blog').'</a><br />';
3762 //link to notes
3763 if (has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context)) {
3764 $output .= '<a href="'.$CFG->wwwroot.'/notes/index.php?course=' . $course->id. '&amp;user='.$user->id.'">'.get_string('notes','notes').'</a><br />';
3767 if (has_capability('moodle/site:viewreports', $context)) {
3768 $timemidnight = usergetmidnight(time());
3769 $output .= '<a href="'. $CFG->wwwroot .'/course/user.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->activity .'</a><br />';
3771 if (has_capability('moodle/role:assign', $context, NULL)) { // Includes admins
3772 $output .= '<a href="'. $CFG->wwwroot .'/course/unenrol.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->unenrol .'</a><br />';
3774 if ($USER->id != $user->id && empty($USER->realuser) && has_capability('moodle/user:loginas', $context) &&
3775 ! has_capability('moodle/site:doanything', $context, $user->id, false)) {
3776 $output .= '<a href="'. $CFG->wwwroot .'/course/loginas.php?id='. $course->id .'&amp;user='. $user->id .'&amp;sesskey='. sesskey() .'">'. $string->loginas .'</a><br />';
3778 $output .= '<a href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&amp;course='. $course->id .'">'. $string->fullprofile .'...</a>';
3780 if (!empty($messageselect)) {
3781 $output .= '<br /><input type="checkbox" name="user'.$user->id.'" /> ';
3784 $output .= '</td></tr></table>';
3786 if ($return) {
3787 return $output;
3788 } else {
3789 echo $output;
3794 * Print a specified group's avatar.
3796 * @param group $group A single {@link group} object OR array of groups.
3797 * @param int $courseid The course ID.
3798 * @param boolean $large Default small picture, or large.
3799 * @param boolean $return If false print picture, otherwise return the output as string
3800 * @param boolean $link Enclose image in a link to view specified course?
3801 * @return string
3802 * @todo Finish documenting this function
3804 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
3805 global $CFG;
3807 if (is_array($group)) {
3808 $output = '';
3809 foreach($group as $g) {
3810 $output .= print_group_picture($g, $courseid, $large, true, $link);
3812 if ($return) {
3813 return $output;
3814 } else {
3815 echo $output;
3816 return;
3820 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3822 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
3823 return '';
3826 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
3827 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
3828 } else {
3829 $output = '';
3831 if ($large) {
3832 $file = 'f1';
3833 $size = 100;
3834 } else {
3835 $file = 'f2';
3836 $size = 35;
3838 if ($group->picture) { // Print custom group picture
3839 if ($CFG->slasharguments) { // Use this method if possible for better caching
3840 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot.'/user/pixgroup.php/'.$group->id.'/'.$file.'.jpg"'.
3841 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
3842 } else {
3843 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot.'/user/pixgroup.php?file=/'.$group->id.'/'.$file.'.jpg"'.
3844 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
3847 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
3848 $output .= '</a>';
3851 if ($return) {
3852 return $output;
3853 } else {
3854 echo $output;
3859 * Print a png image.
3861 * @param string $url ?
3862 * @param int $sizex ?
3863 * @param int $sizey ?
3864 * @param boolean $return ?
3865 * @param string $parameters ?
3866 * @todo Finish documenting this function
3868 function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
3869 global $CFG;
3870 static $recentIE;
3872 if (!isset($recentIE)) {
3873 $recentIE = check_browser_version('MSIE', '5.0');
3876 if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
3877 $output .= '<img src="'. $CFG->pixpath .'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
3878 ' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
3879 ' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
3880 "'$url', sizingMethod='scale') ".
3881 ' '. $parameters .' />';
3882 } else {
3883 $output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
3886 if ($return) {
3887 return $output;
3888 } else {
3889 echo $output;
3894 * Print a nicely formatted table.
3896 * @param array $table is an object with several properties.
3897 * <ul>
3898 * <li>$table->head - An array of heading names.
3899 * <li>$table->align - An array of column alignments
3900 * <li>$table->size - An array of column sizes
3901 * <li>$table->wrap - An array of "nowrap"s or nothing
3902 * <li>$table->data[] - An array of arrays containing the data.
3903 * <li>$table->width - A percentage of the page
3904 * <li>$table->tablealign - Align the whole table
3905 * <li>$table->cellpadding - Padding on each cell
3906 * <li>$table->cellspacing - Spacing between cells
3907 * <li>$table->class - class attribute to put on the table
3908 * <li>$table->id - id attribute to put on the table.
3909 * <li>$table->rowclass[] - classes to add to particular rows.
3910 * </ul>
3911 * @param bool $return whether to return an output string or echo now
3912 * @return boolean or $string
3913 * @todo Finish documenting this function
3915 function print_table($table, $return=false) {
3916 $output = '';
3918 if (isset($table->align)) {
3919 foreach ($table->align as $key => $aa) {
3920 if ($aa) {
3921 $align[$key] = ' text-align:'. $aa.';';
3922 } else {
3923 $align[$key] = '';
3927 if (isset($table->size)) {
3928 foreach ($table->size as $key => $ss) {
3929 if ($ss) {
3930 $size[$key] = ' width:'. $ss .';';
3931 } else {
3932 $size[$key] = '';
3936 if (isset($table->wrap)) {
3937 foreach ($table->wrap as $key => $ww) {
3938 if ($ww) {
3939 $wrap[$key] = ' white-space:nowrap;';
3940 } else {
3941 $wrap[$key] = '';
3946 if (empty($table->width)) {
3947 $table->width = '80%';
3950 if (empty($table->tablealign)) {
3951 $table->tablealign = 'center';
3954 if (empty($table->cellpadding)) {
3955 $table->cellpadding = '5';
3958 if (empty($table->cellspacing)) {
3959 $table->cellspacing = '1';
3962 if (empty($table->class)) {
3963 $table->class = 'generaltable';
3966 $tableid = empty($table->id) ? '' : 'id="'.$table->id.'"';
3968 $output .= '<table width="'.$table->width.'" ';
3969 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
3971 $countcols = 0;
3973 if (!empty($table->head)) {
3974 $countcols = count($table->head);
3975 $output .= '<tr>';
3976 foreach ($table->head as $key => $heading) {
3978 if (!isset($size[$key])) {
3979 $size[$key] = '';
3981 if (!isset($align[$key])) {
3982 $align[$key] = '';
3985 $output .= '<th class="header c'.$key.'" scope="col">'. $heading .'</th>';
3986 // commenting the following code out as <th style does not validate MDL-7861
3987 //$output .= '<th sytle="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.'" scope="col">'. $heading .'</th>';
3989 $output .= '</tr>'."\n";
3992 if (!empty($table->data)) {
3993 $oddeven = 1;
3994 foreach ($table->data as $key => $row) {
3995 $oddeven = $oddeven ? 0 : 1;
3996 if (!isset($table->rowclass[$key])) {
3997 $table->rowclass[$key] = '';
3999 $output .= '<tr class="r'.$oddeven.' '.$table->rowclass[$key].'">'."\n";
4000 if ($row == 'hr' and $countcols) {
4001 $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
4002 } else { /// it's a normal row of data
4003 foreach ($row as $key => $item) {
4004 if (!isset($size[$key])) {
4005 $size[$key] = '';
4007 if (!isset($align[$key])) {
4008 $align[$key] = '';
4010 if (!isset($wrap[$key])) {
4011 $wrap[$key] = '';
4013 $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.'">'. $item .'</td>';
4016 $output .= '</tr>'."\n";
4019 $output .= '</table>'."\n";
4021 if ($return) {
4022 return $output;
4025 echo $output;
4026 return true;
4030 * Creates a nicely formatted table and returns it.
4032 * @param array $table is an object with several properties.
4033 * <ul<li>$table->head - An array of heading names.
4034 * <li>$table->align - An array of column alignments
4035 * <li>$table->size - An array of column sizes
4036 * <li>$table->wrap - An array of "nowrap"s or nothing
4037 * <li>$table->data[] - An array of arrays containing the data.
4038 * <li>$table->class - A css class name
4039 * <li>$table->fontsize - Is the size of all the text
4040 * <li>$table->tablealign - Align the whole table
4041 * <li>$table->width - A percentage of the page
4042 * <li>$table->cellpadding - Padding on each cell
4043 * <li>$table->cellspacing - Spacing between cells
4044 * </ul>
4045 * @return string
4046 * @todo Finish documenting this function
4048 function make_table($table) {
4050 if (isset($table->align)) {
4051 foreach ($table->align as $key => $aa) {
4052 if ($aa) {
4053 $align[$key] = ' align="'. $aa .'"';
4054 } else {
4055 $align[$key] = '';
4059 if (isset($table->size)) {
4060 foreach ($table->size as $key => $ss) {
4061 if ($ss) {
4062 $size[$key] = ' width="'. $ss .'"';
4063 } else {
4064 $size[$key] = '';
4068 if (isset($table->wrap)) {
4069 foreach ($table->wrap as $key => $ww) {
4070 if ($ww) {
4071 $wrap[$key] = ' style="white-space:nowrap;" ';
4072 } else {
4073 $wrap[$key] = '';
4078 if (empty($table->width)) {
4079 $table->width = '80%';
4082 if (empty($table->tablealign)) {
4083 $table->tablealign = 'center';
4086 if (empty($table->cellpadding)) {
4087 $table->cellpadding = '5';
4090 if (empty($table->cellspacing)) {
4091 $table->cellspacing = '1';
4094 if (empty($table->class)) {
4095 $table->class = 'generaltable';
4098 if (empty($table->fontsize)) {
4099 $fontsize = '';
4100 } else {
4101 $fontsize = '<font size="'. $table->fontsize .'">';
4104 $output = '<table width="'. $table->width .'" align="'. $table->tablealign .'" ';
4105 $output .= ' cellpadding="'. $table->cellpadding .'" cellspacing="'. $table->cellspacing .'" class="'. $table->class .'">'."\n";
4107 if (!empty($table->head)) {
4108 $output .= '<tr valign="top">';
4109 foreach ($table->head as $key => $heading) {
4110 if (!isset($size[$key])) {
4111 $size[$key] = '';
4113 if (!isset($align[$key])) {
4114 $align[$key] = '';
4116 $output .= '<th valign="top" '. $align[$key].$size[$key] .' style="white-space:nowrap;" class="'. $table->class .'header" scope="col">'.$fontsize.$heading.'</th>';
4118 $output .= '</tr>'."\n";
4121 foreach ($table->data as $row) {
4122 $output .= '<tr valign="top">';
4123 foreach ($row as $key => $item) {
4124 if (!isset($size[$key])) {
4125 $size[$key] = '';
4127 if (!isset($align[$key])) {
4128 $align[$key] = '';
4130 if (!isset($wrap[$key])) {
4131 $wrap[$key] = '';
4133 $output .= '<td '. $align[$key].$size[$key].$wrap[$key] .' class="'. $table->class .'cell">'. $fontsize . $item .'</td>';
4135 $output .= '</tr>'."\n";
4137 $output .= '</table>'."\n";
4139 return $output;
4142 function print_recent_activity_note($time, $user, $text, $link, $return=false) {
4143 static $strftimerecent;
4144 $output = '';
4146 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
4147 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
4149 if (empty($strftimerecent)) {
4150 $strftimerecent = get_string('strftimerecent');
4153 $date = userdate($time, $strftimerecent);
4154 $name = fullname($user, $viewfullnames);
4156 $output .= '<div class="head">';
4157 $output .= '<div class="date">'.$date.'</div> '.
4158 '<div class="name">'.fullname($user, $viewfullnames).'</div>';
4159 $output .= '</div>';
4160 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
4162 if ($return) {
4163 return $output;
4164 } else {
4165 echo $output;
4171 * Prints a basic textarea field.
4173 * @uses $CFG
4174 * @param boolean $usehtmleditor ?
4175 * @param int $rows ?
4176 * @param int $cols ?
4177 * @param null $width <b>Legacy field no longer used!</b> Set to zero to get control over mincols
4178 * @param null $height <b>Legacy field no longer used!</b> Set to zero to get control over minrows
4179 * @param string $name ?
4180 * @param string $value ?
4181 * @param int $courseid ?
4182 * @todo Finish documenting this function
4184 function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $courseid=0, $return=false, $id='') {
4185 /// $width and height are legacy fields and no longer used as pixels like they used to be.
4186 /// However, you can set them to zero to override the mincols and minrows values below.
4188 global $CFG, $COURSE, $HTTPSPAGEREQUIRED;
4189 static $scriptcount = 0; // For loading the htmlarea script only once.
4191 $mincols = 65;
4192 $minrows = 10;
4193 $str = '';
4195 if ($id === '') {
4196 $id = 'edit-'.$name;
4199 if ( empty($CFG->editorsrc) ) { // for backward compatibility.
4200 if (empty($courseid)) {
4201 $courseid = $COURSE->id;
4204 if ($usehtmleditor) {
4205 if (!empty($courseid) and has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE, $courseid))) {
4206 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '&ampt;httpsrequired=1';
4207 // needed for course file area browsing in image insert plugin
4208 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4209 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php?id='.$courseid.$httpsrequired.'"></script>'."\n" : '';
4210 } else {
4211 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '?httpsrequired=1';
4212 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4213 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php'.$httpsrequired.'"></script>'."\n" : '';
4216 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4217 $CFG->httpswwwroot .'/lib/editor/htmlarea/lang/en.php"></script>'."\n" : '';
4218 $scriptcount++;
4220 if ($height) { // Usually with legacy calls
4221 if ($rows < $minrows) {
4222 $rows = $minrows;
4225 if ($width) { // Usually with legacy calls
4226 if ($cols < $mincols) {
4227 $cols = $mincols;
4232 $str .= '<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">';
4233 if ($usehtmleditor) {
4234 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
4235 } else {
4236 $str .= s($value);
4238 $str .= '</textarea>'."\n";
4240 if ($usehtmleditor) {
4241 // Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
4242 $str .= '<script type="text/javascript">document.write(\''.
4243 str_replace('\'','\\\'',editorshortcutshelpbutton()).'\'); </script>';
4246 if ($return) {
4247 return $str;
4249 echo $str;
4253 * Sets up the HTML editor on textareas in the current page.
4254 * If a field name is provided, then it will only be
4255 * applied to that field - otherwise it will be used
4256 * on every textarea in the page.
4258 * In most cases no arguments need to be supplied
4260 * @param string $name Form element to replace with HTMl editor by name
4262 function use_html_editor($name='', $editorhidebuttons='', $id='') {
4263 $editor = 'editor_'.md5($name); //name might contain illegal characters
4264 if ($id === '') {
4265 $id = 'edit-'.$name;
4267 echo "\n".'<script type="text/javascript" defer="defer">'."\n";
4268 echo '//<![CDATA['."\n\n"; // Extra \n is to fix odd wiki problem, MDL-8185
4269 echo "$editor = new HTMLArea('$id');\n";
4270 echo "var config = $editor.config;\n";
4272 echo print_editor_config($editorhidebuttons);
4274 if (empty($name)) {
4275 echo "\nHTMLArea.replaceAll($editor.config);\n";
4276 } else {
4277 echo "\n$editor.generate();\n";
4279 echo '//]]>'."\n";
4280 echo '</script>'."\n";
4283 function print_editor_config($editorhidebuttons='', $return=false) {
4284 global $CFG;
4286 $str = "config.pageStyle = \"body {";
4288 if (!(empty($CFG->editorbackgroundcolor))) {
4289 $str .= " background-color: $CFG->editorbackgroundcolor;";
4292 if (!(empty($CFG->editorfontfamily))) {
4293 $str .= " font-family: $CFG->editorfontfamily;";
4296 if (!(empty($CFG->editorfontsize))) {
4297 $str .= " font-size: $CFG->editorfontsize;";
4300 $str .= " }\";\n";
4301 $str .= "config.killWordOnPaste = ";
4302 $str .= (empty($CFG->editorkillword)) ? "false":"true";
4303 $str .= ';'."\n";
4304 $str .= 'config.fontname = {'."\n";
4306 $fontlist = isset($CFG->editorfontlist) ? explode(';', $CFG->editorfontlist) : array();
4307 $i = 1; // Counter is used to get rid of the last comma.
4309 foreach ($fontlist as $fontline) {
4310 if (!empty($fontline)) {
4311 if ($i > 1) {
4312 $str .= ','."\n";
4314 list($fontkey, $fontvalue) = split(':', $fontline);
4315 $str .= '"'. $fontkey ."\":\t'". $fontvalue ."'";
4317 $i++;
4320 $str .= '};';
4322 if (!empty($editorhidebuttons)) {
4323 $str .= "\nconfig.hideSomeButtons(\" ". $editorhidebuttons ." \");\n";
4324 } else if (!empty($CFG->editorhidebuttons)) {
4325 $str .= "\nconfig.hideSomeButtons(\" ". $CFG->editorhidebuttons ." \");\n";
4328 if (!empty($CFG->editorspelling) && !empty($CFG->aspellpath)) {
4329 $str .= print_speller_code($CFG->htmleditor, true);
4332 if ($return) {
4333 return $str;
4335 echo $str;
4339 * Returns a turn edit on/off button for course in a self contained form.
4340 * Used to be an icon, but it's now a simple form button
4342 * @uses $CFG
4343 * @uses $USER
4344 * @param int $courseid The course to update by id as found in 'course' table
4345 * @return string
4347 function update_course_icon($courseid) {
4349 global $CFG, $USER;
4351 $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
4353 $capcheck = false;
4355 if (has_capability('moodle/course:manageactivities', $coursecontext) ||
4356 has_capability('moodle/site:manageblocks', $coursecontext)) {
4357 $capcheck = true;
4358 } else {
4359 // loop through all child context, see if user has moodle/course:manageactivities or moodle/site:manageblocks
4360 if ($children = get_child_contexts($coursecontext)) {
4361 foreach ($children as $child) {
4362 $childcontext = get_record('context', 'id', $child);
4363 if (has_capability('moodle/course:manageactivities', $childcontext) ||
4364 has_capability('moodle/site:manageblocks', $childcontext)) {
4365 $capcheck = true;
4366 break;
4373 if ($capcheck) {
4374 if (!empty($USER->editing)) {
4375 $string = get_string('turneditingoff');
4376 $edit = '0';
4377 } else {
4378 $string = get_string('turneditingon');
4379 $edit = '1';
4382 return '<form '.$CFG->frametarget.' method="get" action="'.$CFG->wwwroot.'/course/view.php">'.
4383 '<div>'.
4384 '<input type="hidden" name="id" value="'.$courseid.'" />'.
4385 '<input type="hidden" name="edit" value="'.$edit.'" />'.
4386 '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
4387 '<input type="submit" value="'.$string.'" />'.
4388 '</div></form>';
4393 * Returns a little popup menu for switching roles
4395 * @uses $CFG
4396 * @uses $USER
4397 * @param int $courseid The course to update by id as found in 'course' table
4398 * @return string
4400 function switchroles_form($courseid) {
4402 global $CFG, $USER;
4405 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
4406 return '';
4409 if (!empty($USER->switchrole[$context->id])){ // Just a button to return to normal
4410 $options = array();
4411 $options['id'] = $courseid;
4412 $options['sesskey'] = sesskey();
4413 $options['switchrole'] = 0;
4415 return print_single_button($CFG->wwwroot.'/course/view.php', $options,
4416 get_string('switchrolereturn'), 'post', '_self', true);
4419 if (has_capability('moodle/role:switchroles', $context)) {
4420 if (!$roles = get_assignable_roles($context)) {
4421 return ''; // Nothing to show!
4423 // unset default user role - it would not work
4424 unset($roles[$CFG->guestroleid]);
4425 return popup_form($CFG->wwwroot.'/course/view.php?id='.$courseid.'&amp;sesskey='.sesskey().'&amp;switchrole=',
4426 $roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
4429 return '';
4434 * Returns a turn edit on/off button for course in a self contained form.
4435 * Used to be an icon, but it's now a simple form button
4437 * @uses $CFG
4438 * @uses $USER
4439 * @param int $courseid The course to update by id as found in 'course' table
4440 * @return string
4442 function update_mymoodle_icon() {
4444 global $CFG, $USER;
4446 if (!empty($USER->editing)) {
4447 $string = get_string('updatemymoodleoff');
4448 $edit = '0';
4449 } else {
4450 $string = get_string('updatemymoodleon');
4451 $edit = '1';
4454 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
4455 "<div>".
4456 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
4457 "<input type=\"submit\" value=\"$string\" /></div></form>";
4461 * Prints the editing button on a module "view" page
4463 * @uses $CFG
4464 * @param type description
4465 * @todo Finish documenting this function
4467 function update_module_button($moduleid, $courseid, $string) {
4468 global $CFG, $USER;
4470 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $moduleid))) {
4471 $string = get_string('updatethis', '', $string);
4473 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
4474 "<div>".
4475 "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
4476 "<input type=\"hidden\" name=\"return\" value=\"true\" />".
4477 "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
4478 "<input type=\"submit\" value=\"$string\" /></div></form>";
4479 } else {
4480 return '';
4485 * Prints the editing button on a category page
4487 * @uses $CFG
4488 * @uses $USER
4489 * @param int $categoryid ?
4490 * @return string
4491 * @todo Finish documenting this function
4493 function update_category_button($categoryid) {
4494 global $CFG, $USER;
4496 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_COURSECAT, $categoryid))) {
4497 if (!empty($USER->categoryediting)) {
4498 $string = get_string('turneditingoff');
4499 $edit = 'off';
4500 } else {
4501 $string = get_string('turneditingon');
4502 $edit = 'on';
4505 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/category.php\">".
4506 '<div>'.
4507 "<input type=\"hidden\" name=\"id\" value=\"$categoryid\" />".
4508 "<input type=\"hidden\" name=\"categoryedit\" value=\"$edit\" />".
4509 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
4510 "<input type=\"submit\" value=\"$string\" /></div></form>";
4515 * Prints the editing button on categories listing
4517 * @uses $CFG
4518 * @uses $USER
4519 * @return string
4521 function update_categories_button() {
4522 global $CFG, $USER;
4524 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
4525 if (!empty($USER->categoryediting)) {
4526 $string = get_string('turneditingoff');
4527 $categoryedit = 'off';
4528 } else {
4529 $string = get_string('turneditingon');
4530 $categoryedit = 'on';
4533 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/index.php\">".
4534 '<div>'.
4535 '<input type="hidden" name="categoryedit" value="'. $categoryedit .'" />'.
4536 '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />'.
4537 '<input type="submit" value="'. $string .'" /></div></form>';
4542 * Prints the editing button on search results listing
4543 * For bulk move courses to another category
4546 function update_categories_search_button($search,$page,$perpage) {
4547 global $CFG, $USER;
4549 // not sure if this capability is the best here
4550 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
4551 if (!empty($USER->categoryediting)) {
4552 $string = get_string("turneditingoff");
4553 $edit = "off";
4554 $perpage = 30;
4555 } else {
4556 $string = get_string("turneditingon");
4557 $edit = "on";
4560 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
4561 '<div>'.
4562 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
4563 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
4564 "<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
4565 "<input type=\"hidden\" name=\"page\" value=\"$page\" />".
4566 "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
4567 "<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
4572 * Prints the editing button on group page
4574 * @uses $CFG
4575 * @uses $USER
4576 * @param int $courseid The course group is associated with
4577 * @param int $groupid The group to update
4578 * @return string
4580 function update_group_button($courseid, $groupid) {
4581 global $CFG, $USER;
4583 if (has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_GROUP, $groupid))) {
4584 $string = get_string('editgroupprofile');
4586 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/group/edit.php\">".
4587 '<div>'.
4588 '<input type="hidden" name="courseid" value="'. $courseid .'" />'.
4589 '<input type="hidden" name="id" value="'. $groupid .'" />'.
4590 '<input type="hidden" name="grouping" value="-1" />'.
4591 '<input type="hidden" name="edit" value="on" />'.
4592 '<input type="submit" value="'. $string .'" /></div></form>';
4597 * Prints the editing button on groups page
4599 * @uses $CFG
4600 * @uses $USER
4601 * @param int $courseid The id of the course to be edited
4602 * @return string
4603 * @todo Finish documenting this function
4605 function update_groups_button($courseid) {
4606 global $CFG, $USER;
4608 if (has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $courseid))) {
4609 if (!empty($USER->groupsediting)) {
4610 $string = get_string('turneditingoff');
4611 $edit = 'off';
4612 } else {
4613 $string = get_string('turneditingon');
4614 $edit = 'on';
4617 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/group/index.php\">".
4618 '<div>'.
4619 "<input type=\"hidden\" name=\"id\" value=\"$courseid\" />".
4620 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
4621 "<input type=\"submit\" value=\"$string\" /></div></form>";
4626 * Prints an appropriate group selection menu
4628 * @uses VISIBLEGROUPS
4629 * @param array $groups ?
4630 * @param int $groupmode ?
4631 * @param string $currentgroup ?
4632 * @param string $urlroot ?
4633 * @param boolean $showall: if set to 0, it is a student in separate groups, do not display all participants
4634 * @todo Finish documenting this function
4636 function print_group_menu($groups, $groupmode, $currentgroup, $urlroot, $showall=1, $return=false) {
4638 $output = '';
4639 $groupsmenu = array();
4641 /// Add an "All groups" to the start of the menu
4642 if ($showall){
4643 $groupsmenu[0] = get_string('allparticipants');
4645 foreach ($groups as $key => $group) {
4646 $groupsmenu[$key] = format_string($group->name);
4649 if ($groupmode == VISIBLEGROUPS) {
4650 $grouplabel = get_string('groupsvisible');
4651 } else {
4652 $grouplabel = get_string('groupsseparate');
4655 if (count($groupsmenu) == 1) {
4656 $groupname = reset($groupsmenu);
4657 $output .= $grouplabel.': '.$groupname;
4658 } else {
4659 $output .= popup_form($urlroot.'&amp;group=', $groupsmenu, 'selectgroup', $currentgroup, '', '', '', true, 'self', $grouplabel);
4662 if ($return) {
4663 return $output;
4664 } else {
4665 echo $output;
4671 * Given a course and a (current) coursemodule
4672 * This function returns a small popup menu with all the
4673 * course activity modules in it, as a navigation menu
4674 * The data is taken from the serialised array stored in
4675 * the course record
4677 * @param course $course A {@link $COURSE} object.
4678 * @param course $cm A {@link $COURSE} object.
4679 * @param string $targetwindow ?
4680 * @return string
4681 * @todo Finish documenting this function
4683 function navmenu($course, $cm=NULL, $targetwindow='self') {
4685 global $CFG, $THEME, $USER;
4687 if (empty($THEME->navmenuwidth)) {
4688 $width = 50;
4689 } else {
4690 $width = $THEME->navmenuwidth;
4693 if ($cm) {
4694 $cm = $cm->id;
4697 if ($course->format == 'weeks') {
4698 $strsection = get_string('week');
4699 } else {
4700 $strsection = get_string('topic');
4702 $strjumpto = get_string('jumpto');
4704 /// Casting $course->modinfo to string prevents one notice when the field is null
4705 if (!$modinfo = unserialize((string)$course->modinfo)) {
4706 return '';
4708 $context = get_context_instance(CONTEXT_COURSE, $course->id);
4710 $section = -1;
4711 $selected = '';
4712 $url = '';
4713 $previousmod = NULL;
4714 $backmod = NULL;
4715 $nextmod = NULL;
4716 $selectmod = NULL;
4717 $logslink = NULL;
4718 $flag = false;
4719 $menu = array();
4720 $menustyle = array();
4722 $sections = get_records('course_sections','course',$course->id,'section','section,visible,summary');
4724 if (!empty($THEME->makenavmenulist)) { /// A hack to produce an XHTML navmenu list for use in themes
4725 $THEME->navmenulist = navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
4728 foreach ($modinfo as $mod) {
4729 if ($mod->mod == 'label') {
4730 continue;
4733 if ($mod->section > $course->numsections) { /// Don't show excess hidden sections
4734 break;
4737 if ($mod->section > 0 and $section <> $mod->section) {
4738 $thissection = $sections[$mod->section];
4740 if ($thissection->visible or !$course->hiddensections or
4741 has_capability('moodle/course:viewhiddensections', $context)) {
4742 $thissection->summary = strip_tags(format_string($thissection->summary,true));
4743 if ($course->format == 'weeks' or empty($thissection->summary)) {
4744 $menu[] = '--'.$strsection ." ". $mod->section;
4745 } else {
4746 if (strlen($thissection->summary) < ($width-3)) {
4747 $menu[] = '--'.$thissection->summary;
4748 } else {
4749 $menu[] = '--'.substr($thissection->summary, 0, $width).'...';
4755 $section = $mod->section;
4757 //Only add visible or teacher mods to jumpmenu
4758 if ($mod->visible or has_capability('moodle/course:viewhiddenactivities',
4759 get_context_instance(CONTEXT_MODULE, $mod->cm))) {
4760 $url = $mod->mod .'/view.php?id='. $mod->cm;
4761 if ($flag) { // the current mod is the "next" mod
4762 $nextmod = $mod;
4763 $flag = false;
4765 if ($cm == $mod->cm) {
4766 $selected = $url;
4767 $selectmod = $mod;
4768 $backmod = $previousmod;
4769 $flag = true; // set flag so we know to use next mod for "next"
4770 $mod->name = $strjumpto;
4771 $strjumpto = '';
4772 } else {
4773 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
4774 if (strlen($mod->name) > ($width+5)) {
4775 $mod->name = substr($mod->name, 0, $width).'...';
4777 if (!$mod->visible) {
4778 $mod->name = '('.$mod->name.')';
4781 $menu[$url] = $mod->name;
4782 if (empty($THEME->navmenuiconshide)) {
4783 $menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath.'/'.$mod->mod.'/icon.gif);"'; // Unfortunately necessary to do this here
4785 $previousmod = $mod;
4788 //Accessibility: added Alt text, replaced &gt; &lt; with 'silent' character and 'accesshide' text.
4790 if ($selectmod and has_capability('moodle/site:viewreports', $context)) {
4791 $logstext = get_string('alllogs');
4792 $logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
4793 $CFG->frametarget.'onclick="this.target=\''.$CFG->framename.'\';"'.' href="'.
4794 $CFG->wwwroot.'/course/report/log/index.php?chooselog=1&amp;user=0&amp;date=0&amp;id='.
4795 $course->id.'&amp;modid='.$selectmod->cm.'">'.
4796 '<img class="icon log" src="'.$CFG->pixpath.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
4799 if ($backmod) {
4800 $backtext= get_string('activityprev', 'access');
4801 $backmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$backmod->mod.'/view.php" '.
4802 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
4803 '<input type="hidden" name="id" value="'.$backmod->cm.'" />'.
4804 '<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
4805 '</button></fieldset></form></li>';
4807 if ($nextmod) {
4808 $nexttext= get_string('activitynext', 'access');
4809 $nextmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$nextmod->mod.'/view.php" '.
4810 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
4811 '<input type="hidden" name="id" value="'.$nextmod->cm.'" />'.
4812 '<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
4813 '</button></fieldset></form></li>';
4816 return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
4817 '<li>'.popup_form($CFG->wwwroot .'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
4818 '', '', true, $targetwindow, '', $menustyle).'</li>'.
4819 $nextmod . '</ul>'."\n".'</div>';
4823 * Given a course
4824 * This function returns a small popup menu with all the
4825 * course activity modules in it, as a navigation menu
4826 * outputs a simple list structure in XHTML
4827 * The data is taken from the serialised array stored in
4828 * the course record
4830 * @param course $course A {@link $COURSE} object.
4831 * @return string
4832 * @todo Finish documenting this function
4834 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
4836 global $CFG;
4838 $section = -1;
4839 $selected = '';
4840 $url = '';
4841 $previousmod = NULL;
4842 $backmod = NULL;
4843 $nextmod = NULL;
4844 $selectmod = NULL;
4845 $logslink = NULL;
4846 $flag = false;
4847 $menu = array();
4849 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
4851 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
4852 foreach ($modinfo as $mod) {
4853 if ($mod->mod == 'label') {
4854 continue;
4857 if ($mod->section > $course->numsections) { /// Don't show excess hidden sections
4858 break;
4861 if ($mod->section >= 0 and $section <> $mod->section) {
4862 $thissection = $sections[$mod->section];
4864 if ($thissection->visible or !$course->hiddensections or
4865 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
4866 $thissection->summary = strip_tags(format_string($thissection->summary,true));
4867 if (!empty($doneheading)) {
4868 $menu[] = '</ul></li>';
4870 if ($course->format == 'weeks' or empty($thissection->summary)) {
4871 $item = $strsection ." ". $mod->section;
4872 } else {
4873 if (strlen($thissection->summary) < ($width-3)) {
4874 $item = $thissection->summary;
4875 } else {
4876 $item = substr($thissection->summary, 0, $width).'...';
4879 $menu[] = '<li class="section"><span>'.$item.'</span>';
4880 $menu[] = '<ul>';
4881 $doneheading = true;
4885 $section = $mod->section;
4887 //Only add visible or teacher mods to jumpmenu
4888 if ($mod->visible or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_MODULE, $mod->id))) {
4889 $url = $mod->mod .'/view.php?id='. $mod->cm;
4890 if ($flag) { // the current mod is the "next" mod
4891 $nextmod = $mod;
4892 $flag = false;
4894 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
4895 if (strlen($mod->name) > ($width+5)) {
4896 $mod->name = substr($mod->name, 0, $width).'...';
4898 if (!$mod->visible) {
4899 $mod->name = '('.$mod->name.')';
4901 $class = 'activity '.$mod->mod;
4902 $class .= ($cmid == $mod->cm) ? ' selected' : '';
4903 $menu[] = '<li class="'.$class.'">'.
4904 '<img src="'.$CFG->modpixpath.'/'.$mod->mod.'/icon.gif" alt="" />'.
4905 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
4906 $previousmod = $mod;
4909 if ($doneheading) {
4910 $menu[] = '</ul></li>';
4912 $menu[] = '</ul></li></ul>';
4914 return implode("\n", $menu);
4918 * Prints form items with the names $day, $month and $year
4920 * @param string $day fieldname
4921 * @param string $month fieldname
4922 * @param string $year fieldname
4923 * @param int $currenttime A default timestamp in GMT
4924 * @param boolean $return
4926 function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
4928 if (!$currenttime) {
4929 $currenttime = time();
4931 $currentdate = usergetdate($currenttime);
4933 for ($i=1; $i<=31; $i++) {
4934 $days[$i] = $i;
4936 for ($i=1; $i<=12; $i++) {
4937 $months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
4939 for ($i=1970; $i<=2020; $i++) {
4940 $years[$i] = $i;
4942 return choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', $return)
4943 .choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', $return)
4944 .choose_from_menu($years, $year, $currentdate['year'], '', '', '0', $return);
4949 *Prints form items with the names $hour and $minute
4951 * @param string $hour fieldname
4952 * @param string ? $minute fieldname
4953 * @param $currenttime A default timestamp in GMT
4954 * @param int $step minute spacing
4955 * @param boolean $return
4957 function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
4959 if (!$currenttime) {
4960 $currenttime = time();
4962 $currentdate = usergetdate($currenttime);
4963 if ($step != 1) {
4964 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
4966 for ($i=0; $i<=23; $i++) {
4967 $hours[$i] = sprintf("%02d",$i);
4969 for ($i=0; $i<=59; $i+=$step) {
4970 $minutes[$i] = sprintf("%02d",$i);
4973 return choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',$return)
4974 .choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',$return);
4978 * Prints time limit value selector
4980 * @uses $CFG
4981 * @param int $timelimit default
4982 * @param string $unit
4983 * @param string $name
4984 * @param boolean $return
4986 function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
4988 global $CFG;
4990 if ($unit) {
4991 $unit = ' '.$unit;
4994 // Max timelimit is sessiontimeout - 10 minutes.
4995 $maxvalue = ($CFG->sessiontimeout / 60) - 10;
4997 for ($i=1; $i<=$maxvalue; $i++) {
4998 $minutes[$i] = $i.$unit;
5000 return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
5004 * Prints a grade menu (as part of an existing form) with help
5005 * Showing all possible numerical grades and scales
5007 * @uses $CFG
5008 * @param int $courseid ?
5009 * @param string $name ?
5010 * @param string $current ?
5011 * @param boolean $includenograde ?
5012 * @todo Finish documenting this function
5014 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
5016 global $CFG;
5018 $output = '';
5019 $strscale = get_string('scale');
5020 $strscales = get_string('scales');
5022 $scales = get_scales_menu($courseid);
5023 foreach ($scales as $i => $scalename) {
5024 $grades[-$i] = $strscale .': '. $scalename;
5026 if ($includenograde) {
5027 $grades[0] = get_string('nograde');
5029 for ($i=100; $i>=1; $i--) {
5030 $grades[$i] = $i;
5032 $output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
5034 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5035 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5036 $linkobject, 400, 500, $strscales, 'none', true);
5038 if ($return) {
5039 return $output;
5040 } else {
5041 echo $output;
5046 * Prints a scale menu (as part of an existing form) including help button
5047 * Just like {@link print_grade_menu()} but without the numeric grades
5049 * @param int $courseid ?
5050 * @param string $name ?
5051 * @param string $current ?
5052 * @todo Finish documenting this function
5054 function print_scale_menu($courseid, $name, $current, $return=false) {
5056 global $CFG;
5058 $output = '';
5059 $strscales = get_string('scales');
5060 $output .= choose_from_menu(get_scales_menu($courseid), $name, $current, '', '', 0, true);
5062 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5063 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5064 $linkobject, 400, 500, $strscales, 'none', true);
5065 if ($return) {
5066 return $output;
5067 } else {
5068 echo $output;
5073 * Prints a help button about a scale
5075 * @uses $CFG
5076 * @param id $courseid ?
5077 * @param object $scale ?
5078 * @todo Finish documenting this function
5080 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
5082 global $CFG;
5084 $output = '';
5085 $strscales = get_string('scales');
5087 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5088 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true&amp;scaleid='. $scale->id, 'ratingscale',
5089 $linkobject, 400, 500, $scale->name, 'none', true);
5090 if ($return) {
5091 return $output;
5092 } else {
5093 echo $output;
5098 * Print an error page displaying an error message.
5099 * Old method, don't call directly in new code - use print_error instead.
5102 * @uses $SESSION
5103 * @uses $CFG
5104 * @param string $message The message to display to the user about the error.
5105 * @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.
5107 function error ($message, $link='') {
5109 global $CFG, $SESSION;
5110 $message = clean_text($message); // In case nasties are in here
5112 if (defined('FULLME') && FULLME == 'cron') {
5113 // Errors in cron should be mtrace'd.
5114 mtrace($message);
5115 die;
5118 if (! defined('HEADER_PRINTED')) {
5119 //header not yet printed
5120 @header('HTTP/1.0 404 Not Found');
5121 print_header(get_string('error'));
5124 echo '<br />';
5125 print_simple_box($message, '', '', '', '', 'errorbox');
5127 debugging('Stack trace:', DEBUG_DEVELOPER);
5129 // in case we are logging upgrade in admin/index.php stop it
5130 if (function_exists('upgrade_log_finish')) {
5131 upgrade_log_finish();
5134 if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
5135 if ( !empty($SESSION->fromurl) ) {
5136 $link = $SESSION->fromurl;
5137 unset($SESSION->fromurl);
5138 } else {
5139 $link = $CFG->wwwroot .'/';
5143 if (!empty($link)) {
5144 print_continue($link);
5147 print_footer();
5149 for ($i=0;$i<512;$i++) { // Padding to help IE work with 404
5150 echo ' ';
5153 die;
5157 * Print an error page displaying an error message. New method - use this for new code.
5159 * @uses $SESSION
5160 * @uses $CFG
5161 * @param string $errorcode The name of the string from error.php to print
5162 * @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.
5163 * @param object $a Extra words and phrases that might be required in the error string
5165 function print_error ($errorcode, $module='', $link='', $a=NULL) {
5167 global $CFG;
5169 if (empty($module) || $module == 'moodle' || $module == 'core') {
5170 $module = 'error';
5171 $modulelink = 'moodle';
5172 } else {
5173 $modulelink = $module;
5176 if (!empty($CFG->errordocroot)) {
5177 $errordocroot = $CFG->errordocroot;
5178 } else if (!empty($CFG->docroot)) {
5179 $errordocroot = $CFG->docroot;
5180 } else {
5181 $errordocroot = 'http://docs.moodle.org';
5184 $message = '<p class="errormessage">'.get_string($errorcode, $module, $a).'</p>'.
5185 '<p class="errorcode">'.
5186 '<a href="'.$errordocroot.'/en/error/'.$modulelink.'/'.$errorcode.'">'.
5187 get_string('moreinformation').'</a></p>';
5188 error($message, $link);
5191 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
5192 * Should be used only with htmleditor or textarea.
5193 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
5194 * helpbutton.
5195 * @return string
5197 function editorhelpbutton(){
5198 global $CFG, $SESSION;
5199 $items = func_get_args();
5200 $i = 1;
5201 $urlparams = array();
5202 $titles = array();
5203 foreach ($items as $item){
5204 if (is_array($item)){
5205 $urlparams[] = "keyword$i=".urlencode($item[0]);
5206 $urlparams[] = "title$i=".urlencode($item[1]);
5207 if (isset($item[2])){
5208 $urlparams[] = "module$i=".urlencode($item[2]);
5210 $titles[] = trim($item[1], ". \t");
5211 }elseif (is_string($item)){
5212 $urlparams[] = "button$i=".urlencode($item);
5213 switch ($item){
5214 case 'reading' :
5215 $titles[] = get_string("helpreading");
5216 break;
5217 case 'writing' :
5218 $titles[] = get_string("helpwriting");
5219 break;
5220 case 'questions' :
5221 $titles[] = get_string("helpquestions");
5222 break;
5223 case 'emoticons' :
5224 $titles[] = get_string("helpemoticons");
5225 break;
5226 case 'richtext' :
5227 $titles[] = get_string('helprichtext');
5228 break;
5229 case 'text' :
5230 $titles[] = get_string('helptext');
5231 break;
5232 default :
5233 error('Unknown help topic '.$item);
5236 $i++;
5238 if (count($titles)>1){
5239 //join last two items with an 'and'
5240 $a = new object();
5241 $a->one = $titles[count($titles) - 2];
5242 $a->two = $titles[count($titles) - 1];
5243 $titles[count($titles) - 2] = get_string('and', '', $a);
5244 unset($titles[count($titles) - 1]);
5246 $alttag = join (', ', $titles);
5248 $paramstring = join('&', $urlparams);
5249 $linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath .'/help.gif" />';
5250 return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), $alttag, $linkobject, 400, 500, $alttag, 'none', true);
5254 * Print a help button.
5256 * @uses $CFG
5257 * @param string $page The keyword that defines a help page
5258 * @param string $title The title of links, rollover tips, alt tags etc
5259 * 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
5260 * @param string $module Which module is the page defined in
5261 * @param mixed $image Use a help image for the link? (true/false/"both")
5262 * @param boolean $linktext If true, display the title next to the help icon.
5263 * @param string $text If defined then this text is used in the page, and
5264 * the $page variable is ignored.
5265 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
5266 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
5267 * @return string
5268 * @todo Finish documenting this function
5270 function helpbutton ($page, $title='', $module='moodle', $image=true, $linktext=false, $text='', $return=false,
5271 $imagetext='') {
5272 global $CFG, $course;
5274 // fix for MDL-7734
5275 if (!empty($course->lang)) {
5276 $forcelang = $course->lang;
5277 } else {
5278 $forcelang = '';
5281 if ($module == '') {
5282 $module = 'moodle';
5285 $tooltip = get_string('helpprefix2', '', trim($title, ". \t"));
5287 $linkobject = '';
5289 if ($image) {
5290 if ($linktext) {
5291 // MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
5292 $linkobject .= $title.'&nbsp;';
5293 $tooltip = get_string('helpwiththis');
5295 if ($imagetext) {
5296 $linkobject .= $imagetext;
5297 } else {
5298 $linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
5299 $CFG->pixpath .'/help.gif" />';
5301 } else {
5302 $linkobject .= $tooltip;
5305 $tooltip .= ' ('.get_string('newwindow').')'; // Warn users about new window for Accessibility
5307 // fix for MDL-7734
5308 if ($text) {
5309 $url = '/help.php?module='. $module .'&amp;text='. s(urlencode($text).'&amp;forcelang='.$forcelang);
5310 } else {
5311 $url = '/help.php?module='. $module .'&amp;file='. $page .'.html&amp;forcelang='.$forcelang;
5314 $link = '<span class="helplink">'.
5315 link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
5316 '</span>';
5318 if ($return) {
5319 return $link;
5320 } else {
5321 echo $link;
5326 * Print a help button.
5328 * Prints a special help button that is a link to the "live" emoticon popup
5329 * @uses $CFG
5330 * @uses $SESSION
5331 * @param string $form ?
5332 * @param string $field ?
5333 * @todo Finish documenting this function
5335 function emoticonhelpbutton($form, $field, $return = false) {
5337 global $CFG, $SESSION;
5339 $SESSION->inserttextform = $form;
5340 $SESSION->inserttextfield = $field;
5341 $imagetext = '<img src="' . $CFG->pixpath . '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
5342 $help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
5343 if (!$return){
5344 echo $help;
5345 } else {
5346 return $help;
5351 * Print a help button.
5353 * Prints a special help button for html editors (htmlarea in this case)
5354 * @uses $CFG
5356 function editorshortcutshelpbutton() {
5358 global $CFG;
5359 $imagetext = '<img src="' . $CFG->httpswwwroot . '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
5360 get_string('editorshortcutkeys').'" class="iconkbhelp" />';
5362 return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
5366 * Print a message and exit.
5368 * @uses $CFG
5369 * @param string $message ?
5370 * @param string $link ?
5371 * @todo Finish documenting this function
5373 function notice ($message, $link='', $course=NULL) {
5374 global $CFG, $SITE;
5376 $message = clean_text($message);
5378 print_box($message, 'generalbox', 'notice');
5379 print_continue($link);
5381 if (empty($course)) {
5382 print_footer($SITE);
5383 } else {
5384 print_footer($course);
5386 exit;
5390 * Print a message along with "Yes" and "No" links for the user to continue.
5392 * @param string $message The text to display
5393 * @param string $linkyes The link to take the user to if they choose "Yes"
5394 * @param string $linkno The link to take the user to if they choose "No"
5395 * TODO Document remaining arguments
5397 function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
5399 global $CFG;
5401 $message = clean_text($message);
5402 $linkyes = clean_text($linkyes);
5403 $linkno = clean_text($linkno);
5405 print_box_start('generalbox', 'notice');
5406 echo '<p>'. $message .'</p>';
5407 echo '<div class="buttons">';
5408 print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename);
5409 print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename);
5410 echo '</div>';
5411 print_box_end();
5415 * Provide an definition of error_get_last for PHP before 5.2.0. This simply
5416 * returns NULL, since there is not way to get the right answer.
5418 if (!function_exists('error_get_last')) {
5419 // the eval is needed to prevent PHP 5.2+ from getting a parse error!
5420 eval('
5421 function error_get_last() {
5422 return NULL;
5428 * Redirects the user to another page, after printing a notice
5430 * @param string $url The url to take the user to
5431 * @param string $message The text message to display to the user about the redirect, if any
5432 * @param string $delay How long before refreshing to the new page at $url?
5433 * @todo '&' needs to be encoded into '&amp;' for XHTML compliance,
5434 * however, this is not true for javascript. Therefore we
5435 * first decode all entities in $url (since we cannot rely on)
5436 * the correct input) and then encode for where it's needed
5437 * echo "<script type='text/javascript'>alert('Redirect $url');</script>";
5439 function redirect($url, $message='', $delay=-1) {
5441 global $CFG;
5443 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
5444 $url = sid_process_url($url);
5447 $message = clean_text($message);
5449 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
5450 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
5451 $url = str_replace('&amp;', '&', $encodedurl);
5453 /// At developer debug level. Don't redirect if errors have been printed on screen.
5454 /// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
5455 $lasterror = error_get_last();
5456 $error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER));
5457 $errorprinted = debugging('', DEBUG_ALL) && $CFG->debugdisplay && $error;
5458 if ($errorprinted) {
5459 $message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
5462 /// when no message and header printed yet, try to redirect
5463 if (empty($message) and !defined('HEADER_PRINTED')) {
5465 // Technically, HTTP/1.1 requires Location: header to contain
5466 // the absolute path. (In practice browsers accept relative
5467 // paths - but still, might as well do it properly.)
5468 // This code turns relative into absolute.
5469 if (!preg_match('|^[a-z]+:|', $url)) {
5470 // Get host name http://www.wherever.com
5471 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
5472 if (preg_match('|^/|', $url)) {
5473 // URLs beginning with / are relative to web server root so we just add them in
5474 $url = $hostpart.$url;
5475 } else {
5476 // URLs not beginning with / are relative to path of current script, so add that on.
5477 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
5479 // Replace all ..s
5480 while (true) {
5481 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
5482 if ($newurl == $url) {
5483 break;
5485 $url = $newurl;
5489 $delay = 0;
5490 //try header redirection first
5491 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
5492 @header('Location: '.$url);
5493 //another way for older browsers and already sent headers (eg trailing whitespace in config.php)
5494 echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
5495 echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
5496 die;
5499 if ($delay == -1) {
5500 $delay = 3; // if no delay specified wait 3 seconds
5502 if (! defined('HEADER_PRINTED')) {
5503 // this type of redirect might not be working in some browsers - such as lynx :-(
5504 print_header('', '', '', '', $errorprinted ? '' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
5505 $delay += 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
5507 echo '<div style="text-align:center">';
5508 echo '<div>'. $message .'</div>';
5509 echo '<div>( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
5510 echo '</div>';
5512 if (!$errorprinted) {
5514 <script type="text/javascript">
5515 //<![CDATA[
5517 function redirect() {
5518 document.location.replace('<?php echo addslashes_js($url) ?>');
5520 setTimeout("redirect()", <?php echo ($delay * 1000) ?>);
5521 //]]>
5522 </script>
5523 <?php
5526 print_footer('none');
5527 die;
5531 * Print a bold message in an optional color.
5533 * @param string $message The message to print out
5534 * @param string $style Optional style to display message text in
5535 * @param string $align Alignment option
5536 * @param bool $return whether to return an output string or echo now
5538 function notify($message, $style='notifyproblem', $align='center', $return=false) {
5539 if ($style == 'green') {
5540 $style = 'notifysuccess'; // backward compatible with old color system
5543 $message = clean_text($message);
5545 $output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."<br />\n";
5547 if ($return) {
5548 return $output;
5550 echo $output;
5555 * Given an email address, this function will return an obfuscated version of it
5557 * @param string $email The email address to obfuscate
5558 * @return string
5560 function obfuscate_email($email) {
5562 $i = 0;
5563 $length = strlen($email);
5564 $obfuscated = '';
5565 while ($i < $length) {
5566 if (rand(0,2)) {
5567 $obfuscated.='%'.dechex(ord($email{$i}));
5568 } else {
5569 $obfuscated.=$email{$i};
5571 $i++;
5573 return $obfuscated;
5577 * This function takes some text and replaces about half of the characters
5578 * with HTML entity equivalents. Return string is obviously longer.
5580 * @param string $plaintext The text to be obfuscated
5581 * @return string
5583 function obfuscate_text($plaintext) {
5585 $i=0;
5586 $length = strlen($plaintext);
5587 $obfuscated='';
5588 $prev_obfuscated = false;
5589 while ($i < $length) {
5590 $c = ord($plaintext{$i});
5591 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
5592 if ($prev_obfuscated and $numerical ) {
5593 $obfuscated.='&#'.ord($plaintext{$i}).';';
5594 } else if (rand(0,2)) {
5595 $obfuscated.='&#'.ord($plaintext{$i}).';';
5596 $prev_obfuscated = true;
5597 } else {
5598 $obfuscated.=$plaintext{$i};
5599 $prev_obfuscated = false;
5601 $i++;
5603 return $obfuscated;
5607 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
5608 * to generate a fully obfuscated email link, ready to use.
5610 * @param string $email The email address to display
5611 * @param string $label The text to dispalyed as hyperlink to $email
5612 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
5613 * @return string
5615 function obfuscate_mailto($email, $label='', $dimmed=false) {
5617 if (empty($label)) {
5618 $label = $email;
5620 if ($dimmed) {
5621 $title = get_string('emaildisable');
5622 $dimmed = ' class="dimmed"';
5623 } else {
5624 $title = '';
5625 $dimmed = '';
5627 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
5628 obfuscate_text('mailto'), obfuscate_email($email),
5629 obfuscate_text($label));
5633 * Prints a single paging bar to provide access to other pages (usually in a search)
5635 * @param int $totalcount Thetotal number of entries available to be paged through
5636 * @param int $page The page you are currently viewing
5637 * @param int $perpage The number of entries that should be shown per page
5638 * @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.
5639 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
5640 * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
5641 * @param bool $nocurr do not display the current page as a link
5642 * @param bool $return whether to return an output string or echo now
5643 * @return bool or string
5645 function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
5646 $maxdisplay = 18;
5647 $output = '';
5649 if ($totalcount > $perpage) {
5650 $output .= '<div class="paging">';
5651 $output .= get_string('page') .':';
5652 if ($page > 0) {
5653 $pagenum = $page - 1;
5654 if (!is_a($baseurl, 'moodle_url')){
5655 $output .= '&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>)&nbsp;';
5656 } else {
5657 $output .= '&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>)&nbsp;';
5660 $lastpage = ceil($totalcount / $perpage);
5661 if ($page > 15) {
5662 $startpage = $page - 10;
5663 if (!is_a($baseurl, 'moodle_url')){
5664 $output .= '&nbsp;<a href="'. $baseurl . $pagevar .'=0">1</a>&nbsp;...';
5665 } else {
5666 $output .= '&nbsp;<a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a>&nbsp;...';
5668 } else {
5669 $startpage = 0;
5671 $currpage = $startpage;
5672 $displaycount = 0;
5673 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
5674 $displaypage = $currpage+1;
5675 if ($page == $currpage && empty($nocurr)) {
5676 $output .= '&nbsp;&nbsp;'. $displaypage;
5677 } else {
5678 if (!is_a($baseurl, 'moodle_url')){
5679 $output .= '&nbsp;&nbsp;<a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
5680 } else {
5681 $output .= '&nbsp;&nbsp;<a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
5685 $displaycount++;
5686 $currpage++;
5688 if ($currpage < $lastpage) {
5689 $lastpageactual = $lastpage - 1;
5690 if (!is_a($baseurl, 'moodle_url')){
5691 $output .= '&nbsp;...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a>&nbsp;';
5692 } else {
5693 $output .= '&nbsp;...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a>&nbsp;';
5696 $pagenum = $page + 1;
5697 if ($pagenum != $displaypage) {
5698 if (!is_a($baseurl, 'moodle_url')){
5699 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
5700 } else {
5701 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
5704 $output .= '</div>';
5707 if ($return) {
5708 return $output;
5711 echo $output;
5712 return true;
5716 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
5717 * will transform it to html entities
5719 * @param string $text Text to search for nolink tag in
5720 * @return string
5722 function rebuildnolinktag($text) {
5724 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
5726 return $text;
5730 * Prints a nice side block with an optional header. The content can either
5731 * be a block of HTML or a list of text with optional icons.
5733 * @param string $heading Block $title embedded in HTML tags, for example <h2>.
5734 * @param string $content ?
5735 * @param array $list ?
5736 * @param array $icons ?
5737 * @param string $footer ?
5738 * @param array $attributes ?
5739 * @param string $title Plain text title, as embedded in the $heading.
5740 * @todo Finish documenting this function. Show example of various attributes, etc.
5742 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
5744 //Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
5745 static $block_id = 0;
5746 $block_id++;
5747 if (empty($heading)) {
5748 $skip_text = get_string('skipblock', 'access').' '.$block_id;
5750 else {
5751 $skip_text = get_string('skipa', 'access', strip_tags($title));
5753 $skip_link = '<a href="#sb-'.$block_id.'" class="skip-block" title="'.$skip_text.'">'."\n".'<span class="accesshide">'.$skip_text.'</span>'."\n".'</a>';
5754 $skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
5756 if (! empty($heading)) {
5757 $heading = $skip_link . $heading;
5759 /*else { //ELSE: I think a single link on a page, "Skip block 4" is too confusing - don't print.
5760 echo $skip_link;
5763 print_side_block_start($heading, $attributes);
5765 if ($content) {
5766 echo $content;
5767 if ($footer) {
5768 echo '<div class="footer">'. $footer .'</div>';
5770 } else {
5771 if ($list) {
5772 $row = 0;
5773 //Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
5774 echo "\n<ul class='list'>\n";
5775 foreach ($list as $key => $string) {
5776 echo '<li class="r'. $row .'">';
5777 if ($icons) {
5778 echo '<div class="icon column c0">'. $icons[$key] .'</div>';
5780 echo '<div class="column c1">'. $string .'</div>';
5781 echo "</li>\n";
5782 $row = $row ? 0:1;
5784 echo "</ul>\n";
5786 if ($footer) {
5787 echo '<div class="footer">'. $footer .'</div>';
5792 print_side_block_end($attributes);
5793 echo $skip_dest;
5797 * Starts a nice side block with an optional header.
5799 * @param string $heading ?
5800 * @param array $attributes ?
5801 * @todo Finish documenting this function
5803 function print_side_block_start($heading='', $attributes = array()) {
5805 global $CFG, $THEME;
5807 if (!empty($THEME->customcorners)) {
5808 require_once($CFG->dirroot.'/lib/custom_corners_lib.php');
5811 // If there are no special attributes, give a default CSS class
5812 if (empty($attributes) || !is_array($attributes)) {
5813 $attributes = array('class' => 'sideblock');
5815 } else if(!isset($attributes['class'])) {
5816 $attributes['class'] = 'sideblock';
5818 } else if(!strpos($attributes['class'], 'sideblock')) {
5819 $attributes['class'] .= ' sideblock';
5822 // OK, the class is surely there and in addition to anything
5823 // else, it's tagged as a sideblock
5827 // IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
5829 // If there is a cookie to hide this thing, start it hidden
5830 if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
5831 $attributes['class'] = 'hidden '.$attributes['class'];
5835 $attrtext = '';
5836 foreach ($attributes as $attr => $val) {
5837 $attrtext .= ' '.$attr.'="'.$val.'"';
5840 echo '<div '.$attrtext.'>';
5842 if (!empty($THEME->customcorners)) {
5843 echo '<div class="wrap">'."\n";
5845 if ($heading) {
5846 //Accessibility: replaced <div> with H2; no, H2 more appropriate in moodleblock.class.php: _title_html.
5847 // echo '<div class="header">'.$heading.'</div>';
5848 echo '<div class="header">';
5849 if (!empty($THEME->customcorners)) {
5850 echo '<div class="bt"><div></div></div>';
5851 echo '<div class="i1"><div class="i2">';
5852 echo '<div class="i3">';
5854 echo $heading;
5855 if (!empty($THEME->customcorners)) {
5856 echo '</div></div></div>';
5858 echo '</div>';
5859 } else {
5860 if (!empty($THEME->customcorners)) {
5861 echo '<div class="bt"><div></div></div>';
5865 if (!empty($THEME->customcorners)) {
5866 echo '<div class="i1"><div class="i2">';
5867 echo '<div class="i3">';
5869 echo '<div class="content">';
5875 * Print table ending tags for a side block box.
5877 function print_side_block_end($attributes = array()) {
5878 global $CFG, $THEME;
5880 echo '</div>';
5882 if (!empty($THEME->customcorners)) {
5883 require_once($CFG->dirroot.'/lib/custom_corners_lib.php');
5884 print_custom_corners_end();
5887 echo '</div>';
5889 // IE workaround: if I do it THIS way, it works! WTF?
5890 if (!empty($CFG->allowuserblockhiding) && isset($attributes['id'])) {
5891 echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].'"); '.
5892 "\n//]]>\n".'</script>';
5899 * Prints out code needed for spellchecking.
5900 * Original idea by Ludo (Marc Alier).
5902 * Opening CDATA and <script> are output by weblib::use_html_editor()
5903 * @uses $CFG
5904 * @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
5905 * @param boolean $return If false, echos the code instead of returning it
5906 * @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
5908 function print_speller_code ($usehtmleditor=false, $return=false) {
5909 global $CFG;
5910 $str = '';
5912 if(!$usehtmleditor) {
5913 $str .= 'function openSpellChecker() {'."\n";
5914 $str .= "\tvar speller = new spellChecker();\n";
5915 $str .= "\tspeller.popUpUrl = \"" . $CFG->wwwroot ."/lib/speller/spellchecker.html\";\n";
5916 $str .= "\tspeller.spellCheckScript = \"". $CFG->wwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
5917 $str .= "\tspeller.spellCheckAll();\n";
5918 $str .= '}'."\n";
5919 } else {
5920 $str .= "function spellClickHandler(editor, buttonId) {\n";
5921 $str .= "\teditor._textArea.value = editor.getHTML();\n";
5922 $str .= "\tvar speller = new spellChecker( editor._textArea );\n";
5923 $str .= "\tspeller.popUpUrl = \"" . $CFG->wwwroot ."/lib/speller/spellchecker.html\";\n";
5924 $str .= "\tspeller.spellCheckScript = \"". $CFG->wwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
5925 $str .= "\tspeller._moogle_edit=1;\n";
5926 $str .= "\tspeller._editor=editor;\n";
5927 $str .= "\tspeller.openChecker();\n";
5928 $str .= '}'."\n";
5931 if ($return) {
5932 return $str;
5934 echo $str;
5938 * Print button for spellchecking when editor is disabled
5940 function print_speller_button () {
5941 echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
5945 function page_id_and_class(&$getid, &$getclass) {
5946 // Create class and id for this page
5947 global $CFG, $ME;
5949 static $class = NULL;
5950 static $id = NULL;
5952 if (empty($CFG->pagepath)) {
5953 $CFG->pagepath = $ME;
5956 if (empty($class) || empty($id)) {
5957 $path = str_replace($CFG->httpswwwroot.'/', '', $CFG->pagepath); //Because the page could be HTTPSPAGEREQUIRED
5958 $path = str_replace('.php', '', $path);
5959 if (substr($path, -1) == '/') {
5960 $path .= 'index';
5962 if (empty($path) || $path == 'index') {
5963 $id = 'site-index';
5964 $class = 'course';
5965 } else if (substr($path, 0, 5) == 'admin') {
5966 $id = str_replace('/', '-', $path);
5967 $class = 'admin';
5968 } else {
5969 $id = str_replace('/', '-', $path);
5970 $class = explode('-', $id);
5971 array_pop($class);
5972 $class = implode('-', $class);
5976 $getid = $id;
5977 $getclass = $class;
5981 * Prints a maintenance message from /maintenance.html
5983 function print_maintenance_message () {
5984 global $CFG, $SITE;
5986 print_header(strip_tags($SITE->fullname), $SITE->fullname, 'home');
5987 print_simple_box_start('center');
5988 print_heading(get_string('sitemaintenance', 'admin'));
5989 @include($CFG->dataroot.'/1/maintenance.html');
5990 print_simple_box_end();
5991 print_footer();
5995 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
5997 function adjust_allowed_tags() {
5999 global $CFG, $ALLOWED_TAGS;
6001 if (!empty($CFG->allowobjectembed)) {
6002 $ALLOWED_TAGS .= '<embed><object>';
6006 /// Some code to print tabs
6008 /// A class for tabs
6009 class tabobject {
6010 var $id;
6011 var $link;
6012 var $text;
6013 var $linkedwhenselected;
6015 /// A constructor just because I like constructors
6016 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
6017 $this->id = $id;
6018 $this->link = $link;
6019 $this->text = $text;
6020 $this->title = $title ? $title : $text;
6021 $this->linkedwhenselected = $linkedwhenselected;
6028 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
6030 * @param array $tabrows An array of rows where each row is an array of tab objects
6031 * @param string $selected The id of the selected tab (whatever row it's on)
6032 * @param array $inactive An array of ids of inactive tabs that are not selectable.
6033 * @param array $activated An array of ids of other tabs that are currently activated
6035 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
6036 global $CFG;
6038 /// $inactive must be an array
6039 if (!is_array($inactive)) {
6040 $inactive = array();
6043 /// $activated must be an array
6044 if (!is_array($activated)) {
6045 $activated = array();
6048 /// Convert the tab rows into a tree that's easier to process
6049 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
6050 return false;
6053 /// Print out the current tree of tabs (this function is recursive)
6055 $output = convert_tree_to_html($tree);
6057 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
6059 /// We're done!
6061 if ($return) {
6062 return $output;
6064 echo $output;
6068 function convert_tree_to_html($tree, $row=0) {
6070 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
6072 $first = true;
6073 $count = count($tree);
6075 foreach ($tree as $tab) {
6076 $count--; // countdown to zero
6078 $liclass = '';
6080 if ($first && ($count == 0)) { // Just one in the row
6081 $liclass = 'first last';
6082 $first = false;
6083 } else if ($first) {
6084 $liclass = 'first';
6085 $first = false;
6086 } else if ($count == 0) {
6087 $liclass = 'last';
6090 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
6091 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
6094 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
6095 if ($tab->selected) {
6096 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
6097 } else if ($tab->active) {
6098 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
6102 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
6104 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
6105 $str .= '<a href="#" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
6106 } else {
6107 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
6110 if (!empty($tab->subtree)) {
6111 $str .= convert_tree_to_html($tab->subtree, $row+1);
6112 } else if ($tab->selected) {
6113 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
6116 $str .= ' </li>'."\n";
6118 $str .= '</ul>'."\n";
6120 return $str;
6124 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
6126 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
6128 $tabrows = array_reverse($tabrows);
6130 $subtree = array();
6132 foreach ($tabrows as $row) {
6133 $tree = array();
6135 foreach ($row as $tab) {
6136 $tab->inactive = in_array((string)$tab->id, $inactive);
6137 $tab->active = in_array((string)$tab->id, $activated);
6138 $tab->selected = (string)$tab->id == $selected;
6140 if ($tab->active || $tab->selected) {
6141 if ($subtree) {
6142 $tab->subtree = $subtree;
6145 $tree[] = $tab;
6147 $subtree = $tree;
6150 return $subtree;
6155 * Returns a string containing a link to the user documentation for the current
6156 * page. Also contains an icon by default. Shown to teachers and admin only.
6158 * @param string $text The text to be displayed for the link
6159 * @param string $iconpath The path to the icon to be displayed
6161 function page_doc_link($text='', $iconpath='') {
6162 global $ME, $CFG;
6164 if (empty($CFG->pagepath)) {
6165 $CFG->pagepath = $ME;
6168 $path = str_replace($CFG->httpswwwroot.'/','', $CFG->pagepath); // Because the page could be HTTPSPAGEREQUIRED
6169 $path = str_replace('.php', '', $path);
6171 if (empty($path)) { // Not for home page
6172 return '';
6174 return doc_link($path, $text, $iconpath);
6178 * Returns a string containing a link to the user documentation.
6179 * Also contains an icon by default. Shown to teachers and admin only.
6181 * @param string $path The page link after doc root and language, no
6182 * leading slash.
6183 * @param string $text The text to be displayed for the link
6184 * @param string $iconpath The path to the icon to be displayed
6186 function doc_link($path='', $text='', $iconpath='') {
6187 global $CFG;
6189 if (empty($CFG->docroot) || !has_capability('moodle/site:doclinks')) {
6190 return '';
6193 $target = '';
6194 if (!empty($CFG->doctonewwindow)) {
6195 $target = ' target="_blank"';
6198 $lang = str_replace('_utf8', '', current_language());
6200 $str = '<a href="' .$CFG->docroot. '/' .$lang. '/' .$path. '"' .$target. '>';
6202 if (empty($iconpath)) {
6203 $iconpath = $CFG->httpswwwroot . '/pix/docs.gif';
6206 // alt left blank intentionally to prevent repetition in screenreaders
6207 $str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
6209 return $str;
6213 * Returns true if the current site debugging settings are equal or above specified level.
6214 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
6215 * routing of notices is controlled by $CFG->debugdisplay
6216 * eg use like this:
6218 * 1) debugging('a normal debug notice');
6219 * 2) debugging('something really picky', DEBUG_ALL);
6220 * 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
6221 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
6223 * In code blocks controlled by debugging() (such as example 4)
6224 * any output should be routed via debugging() itself, or the lower-level
6225 * trigger_error() or error_log(). Using echo or print will break XHTML
6226 * JS and HTTP headers.
6229 * @param string $message a message to print
6230 * @param int $level the level at which this debugging statement should show
6231 * @return bool
6233 function debugging($message='', $level=DEBUG_NORMAL) {
6235 global $CFG;
6237 if (empty($CFG->debug)) {
6238 return false;
6241 if ($CFG->debug >= $level) {
6242 if ($message) {
6243 $callers = debug_backtrace();
6244 $from = '<ul style="text-align: left">';
6245 foreach ($callers as $caller) {
6246 if (!isset($caller['line'])) {
6247 $caller['line'] = '?'; // probably call_user_func()
6249 if (!isset($caller['file'])) {
6250 $caller['file'] = $CFG->dirroot.'/unknownfile'; // probably call_user_func()
6252 $from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
6253 if (isset($caller['function'])) {
6254 $from .= ': call to ';
6255 if (isset($caller['class'])) {
6256 $from .= $caller['class'] . $caller['type'];
6258 $from .= $caller['function'] . '()';
6260 $from .= '</li>';
6262 $from .= '</ul>';
6263 if (!isset($CFG->debugdisplay)) {
6264 $CFG->debugdisplay = ini_get('display_errors');
6266 if ($CFG->debugdisplay) {
6267 if (!defined('DEBUGGING_PRINTED')) {
6268 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
6270 notify($message . $from, 'notifytiny');
6271 } else {
6272 trigger_error($message . $from, E_USER_NOTICE);
6275 return true;
6277 return false;
6281 * Disable debug messages from debugging(), while keeping PHP error reporting level as is.
6283 function disable_debugging() {
6284 global $CFG;
6285 $CFG->debug = $CFG->debug | 0x80000000; // switch the sign bit in integer number ;-)
6290 * Returns string to add a frame attribute, if required
6292 function frametarget() {
6293 global $CFG;
6295 if (empty($CFG->framename) or ($CFG->framename == '_top')) {
6296 return '';
6297 } else {
6298 return ' target="'.$CFG->framename.'" ';
6303 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
6304 * pages that use bits from many different files in very confusing ways (e.g. blocks).
6305 * @usage print_location_comment(__FILE__, __LINE__);
6306 * @param string $file
6307 * @param integer $line
6308 * @param boolean $return Whether to return or print the comment
6309 * @return mixed Void unless true given as third parameter
6311 function print_location_comment($file, $line, $return = false)
6313 if ($return) {
6314 return "<!-- $file at line $line -->\n";
6315 } else {
6316 echo "<!-- $file at line $line -->\n";
6322 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
6323 * provide this function with the language strings for sortasc and sortdesc.
6324 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
6325 * @param string $direction 'up' or 'down'
6326 * @param string $strsort The language string used for the alt attribute of this image
6327 * @param bool $return Whether to print directly or return the html string
6328 * @return string HTML for the image
6330 * TODO See if this isn't already defined somewhere. If not, move this to weblib
6332 function print_arrow($direction='up', $strsort=null, $return=false) {
6333 global $CFG;
6335 if (!in_array($direction, array('up', 'down', 'right', 'left'))) {
6336 return null;
6339 $return = null;
6341 switch ($direction) {
6342 case 'up':
6343 $sortdir = 'asc';
6344 break;
6345 case 'down':
6346 $sortdir = 'desc';
6347 break;
6348 default:
6349 $sortdir = null;
6350 break;
6353 // Prepare language string
6354 $strsort = '';
6355 if (empty($strsort) && !empty($sortdir)) {
6356 $strsort = get_string('sort' . $sortdir, 'grades');
6359 $return = ' <img src="'.$CFG->pixpath.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
6361 if ($return) {
6362 return $return;
6363 } else {
6364 echo $return;
6368 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: