MDL-11082 Improved groups upgrade performance 1.8x -> 1.9; thanks Eloy for telling...
[moodle-pu.git] / lib / weblib.php
blobba05f98d13ea077ebab009c41c590fca43912f1b
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 make_upload_directory('cache/htmlpurifier', false);
1869 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.auto.php';
1870 $config = HTMLPurifier_Config::createDefault();
1871 $config->set('Core', 'AcceptFullDocuments', false);
1872 $config->set('Core', 'Encoding', 'UTF-8');
1873 $config->set('HTML', 'Doctype', 'XHTML 1.0 Transitional');
1874 $config->set('Cache', 'SerializerPath', $CFG->dataroot.'/cache/htmlpurifier');
1875 $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));
1876 $purifier = new HTMLPurifier($config);
1878 return $purifier->purify($text);
1882 * This function takes a string and examines it for HTML tags.
1883 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
1884 * which checks for attributes and filters them for malicious content
1885 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
1887 * @param string $str The string to be examined for html tags
1888 * @return string
1890 function cleanAttributes($str){
1891 $result = preg_replace_callback(
1892 '%(<[^>]*(>|$)|>)%m', #search for html tags
1893 "cleanAttributes2",
1894 $str
1896 return $result;
1900 * This function takes a string with an html tag and strips out any unallowed
1901 * protocols e.g. javascript:
1902 * It calls ancillary functions in kses which are prefixed by kses
1903 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
1905 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
1906 * element the html to be cleared
1907 * @return string
1909 function cleanAttributes2($htmlArray){
1911 global $CFG, $ALLOWED_PROTOCOLS;
1912 require_once($CFG->libdir .'/kses.php');
1914 $htmlTag = $htmlArray[1];
1915 if (substr($htmlTag, 0, 1) != '<') {
1916 return '&gt;'; //a single character ">" detected
1918 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
1919 return ''; // It's seriously malformed
1921 $slash = trim($matches[1]); //trailing xhtml slash
1922 $elem = $matches[2]; //the element name
1923 $attrlist = $matches[3]; // the list of attributes as a string
1925 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
1927 $attStr = '';
1928 foreach ($attrArray as $arreach) {
1929 $arreach['name'] = strtolower($arreach['name']);
1930 if ($arreach['name'] == 'style') {
1931 $value = $arreach['value'];
1932 while (true) {
1933 $prevvalue = $value;
1934 $value = kses_no_null($value);
1935 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
1936 $value = kses_decode_entities($value);
1937 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
1938 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
1939 if ($value === $prevvalue) {
1940 $arreach['value'] = $value;
1941 break;
1944 $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']);
1945 $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']);
1946 } else if ($arreach['name'] == 'href') {
1947 //Adobe Acrobat Reader XSS protection
1948 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd))[^a-z0-9_\.\-].*$/i', '$1', $arreach['value']);
1950 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
1953 $xhtml_slash = '';
1954 if (preg_match('%/\s*$%', $attrlist)) {
1955 $xhtml_slash = ' /';
1957 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
1961 * Replaces all known smileys in the text with image equivalents
1963 * @uses $CFG
1964 * @param string $text Passed by reference. The string to search for smily strings.
1965 * @return string
1967 function replace_smilies(&$text) {
1969 global $CFG;
1971 $lang = current_language();
1973 /// this builds the mapping array only once
1974 static $e = array();
1975 static $img = array();
1976 static $emoticons = array(
1977 ':-)' => 'smiley',
1978 ':)' => 'smiley',
1979 ':-D' => 'biggrin',
1980 ';-)' => 'wink',
1981 ':-/' => 'mixed',
1982 'V-.' => 'thoughtful',
1983 ':-P' => 'tongueout',
1984 'B-)' => 'cool',
1985 '^-)' => 'approve',
1986 '8-)' => 'wideeyes',
1987 ':o)' => 'clown',
1988 ':-(' => 'sad',
1989 ':(' => 'sad',
1990 '8-.' => 'shy',
1991 ':-I' => 'blush',
1992 ':-X' => 'kiss',
1993 '8-o' => 'surprise',
1994 'P-|' => 'blackeye',
1995 '8-[' => 'angry',
1996 'xx-P' => 'dead',
1997 '|-.' => 'sleepy',
1998 '}-]' => 'evil',
1999 '(h)' => 'heart',
2000 '(heart)' => 'heart',
2001 '(y)' => 'yes',
2002 '(n)' => 'no',
2003 '(martin)' => 'martin',
2004 '( )' => 'egg'
2007 if (empty($img[$lang])) { /// After the first time this is not run again
2008 $e[$lang] = array();
2009 $img[$lang] = array();
2010 foreach ($emoticons as $emoticon => $image){
2011 $alttext = get_string($image, 'pix');
2013 $e[$lang][] = $emoticon;
2014 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath .'/s/'. $image .'.gif" />';
2018 // Exclude from transformations all the code inside <script> tags
2019 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
2020 // Based on code from glossary fiter by Williams Castillo.
2021 // - Eloy
2023 // Detect all the <script> zones to take out
2024 $excludes = array();
2025 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
2027 // Take out all the <script> zones from text
2028 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
2029 $excludes['<+'.$key.'+>'] = $value;
2031 if ($excludes) {
2032 $text = str_replace($excludes,array_keys($excludes),$text);
2035 /// this is the meat of the code - this is run every time
2036 $text = str_replace($e[$lang], $img[$lang], $text);
2038 // Recover all the <script> zones to text
2039 if ($excludes) {
2040 $text = str_replace(array_keys($excludes),$excludes,$text);
2045 * Given plain text, makes it into HTML as nicely as possible.
2046 * May contain HTML tags already
2048 * @uses $CFG
2049 * @param string $text The string to convert.
2050 * @param boolean $smiley Convert any smiley characters to smiley images?
2051 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
2052 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2053 * @return string
2056 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
2059 global $CFG;
2061 /// Remove any whitespace that may be between HTML tags
2062 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
2064 /// Remove any returns that precede or follow HTML tags
2065 $text = eregi_replace("([\n\r])<", " <", $text);
2066 $text = eregi_replace(">([\n\r])", "> ", $text);
2068 convert_urls_into_links($text);
2070 /// Make returns into HTML newlines.
2071 if ($newlines) {
2072 $text = nl2br($text);
2075 /// Turn smileys into images.
2076 if ($smiley) {
2077 replace_smilies($text);
2080 /// Wrap the whole thing in a paragraph tag if required
2081 if ($para) {
2082 return '<p>'.$text.'</p>';
2083 } else {
2084 return $text;
2089 * Given Markdown formatted text, make it into XHTML using external function
2091 * @uses $CFG
2092 * @param string $text The markdown formatted text to be converted.
2093 * @return string Converted text
2095 function markdown_to_html($text) {
2096 global $CFG;
2098 require_once($CFG->libdir .'/markdown.php');
2100 return Markdown($text);
2104 * Given HTML text, make it into plain text using external function
2106 * @uses $CFG
2107 * @param string $html The text to be converted.
2108 * @return string
2110 function html_to_text($html) {
2112 global $CFG;
2114 require_once($CFG->libdir .'/html2text.php');
2116 return html2text($html);
2120 * Given some text this function converts any URLs it finds into HTML links
2122 * @param string $text Passed in by reference. The string to be searched for urls.
2124 function convert_urls_into_links(&$text) {
2125 /// Make lone URLs into links. eg http://moodle.com/
2126 $text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
2127 "\\1<a href=\"\\2://\\3\\4\" target=\"_blank\">\\2://\\3\\4</a>", $text);
2129 /// eg www.moodle.com
2130 $text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
2131 "\\1<a href=\"http://www.\\2\\3\" target=\"_blank\">www.\\2\\3</a>", $text);
2135 * This function will highlight search words in a given string
2136 * It cares about HTML and will not ruin links. It's best to use
2137 * this function after performing any conversions to HTML.
2138 * Function found here: http://forums.devshed.com/t67822/scdaa2d1c3d4bacb4671d075ad41f0854.html
2140 * @param string $needle The string to search for
2141 * @param string $haystack The string to search for $needle in
2142 * @param int $case whether to do case-sensitive or insensitive matching.
2143 * @return string
2144 * @todo Finish documenting this function
2146 function highlight($needle, $haystack, $case=0,
2147 $left_string='<span class="highlight">', $right_string='</span>') {
2148 if (empty($needle)) {
2149 return $haystack;
2152 //$list_of_words = eregi_replace("[^-a-zA-Z0-9&.']", " ", $needle); // bug 3101
2153 $list_of_words = $needle;
2154 $list_array = explode(' ', $list_of_words);
2155 for ($i=0; $i<sizeof($list_array); $i++) {
2156 if (strlen($list_array[$i]) == 1) {
2157 $list_array[$i] = '';
2160 $list_of_words = implode(' ', $list_array);
2161 $list_of_words_cp = $list_of_words;
2162 $final = array();
2163 preg_match_all('/<(.+?)>/is',$haystack,$list_of_words);
2165 foreach (array_unique($list_of_words[0]) as $key=>$value) {
2166 $final['<|'.$key.'|>'] = $value;
2169 $haystack = str_replace($final,array_keys($final),$haystack);
2170 $list_of_words_cp = eregi_replace(' +', '|', $list_of_words_cp);
2172 if ($list_of_words_cp{0}=='|') {
2173 $list_of_words_cp{0} = '';
2175 if ($list_of_words_cp{strlen($list_of_words_cp)-1}=='|') {
2176 $list_of_words_cp{strlen($list_of_words_cp)-1}='';
2179 $list_of_words_cp = trim($list_of_words_cp);
2181 if ($list_of_words_cp) {
2183 $list_of_words_cp = "(". $list_of_words_cp .")";
2185 if (!$case){
2186 $haystack = eregi_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2187 } else {
2188 $haystack = ereg_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2191 $haystack = str_replace(array_keys($final),$final,$haystack);
2193 return $haystack;
2197 * This function will highlight instances of $needle in $haystack
2198 * It's faster that the above function and doesn't care about
2199 * HTML or anything.
2201 * @param string $needle The string to search for
2202 * @param string $haystack The string to search for $needle in
2203 * @return string
2205 function highlightfast($needle, $haystack) {
2207 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
2209 $pos = 0;
2211 foreach ($parts as $key => $part) {
2212 $parts[$key] = substr($haystack, $pos, strlen($part));
2213 $pos += strlen($part);
2215 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2216 $pos += strlen($needle);
2219 return (join('', $parts));
2223 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2224 * Internationalisation, for print_header and backup/restorelib.
2225 * @param $dir Default false.
2226 * @return string Attributes.
2228 function get_html_lang($dir = false) {
2229 $direction = '';
2230 if ($dir) {
2231 if (get_string('thisdirection') == 'rtl') {
2232 $direction = ' dir="rtl"';
2233 } else {
2234 $direction = ' dir="ltr"';
2237 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2238 $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
2239 @header('Content-Language: '.$language);
2240 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2244 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
2247 * Print a standard header
2249 * @uses $USER
2250 * @uses $CFG
2251 * @uses $SESSION
2252 * @param string $title Appears at the top of the window
2253 * @param string $heading Appears at the top of the page
2254 * @param array $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
2255 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2256 * @param string $meta Meta tags to be added to the header
2257 * @param boolean $cache Should this page be cacheable?
2258 * @param string $button HTML code for a button (usually for module editing)
2259 * @param string $menu HTML code for a popup menu
2260 * @param boolean $usexml use XML for this page
2261 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2262 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2264 function print_header ($title='', $heading='', $navigation='', $focus='',
2265 $meta='', $cache=true, $button='&nbsp;', $menu='',
2266 $usexml=false, $bodytags='', $return=false) {
2268 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
2270 if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
2271 debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
2272 . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.");
2275 $heading = format_string($heading); // Fix for MDL-8582
2277 /// This makes sure that the header is never repeated twice on a page
2278 if (defined('HEADER_PRINTED')) {
2279 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().');
2280 return;
2282 define('HEADER_PRINTED', 'true');
2285 /// Add the required stylesheets
2286 $stylesheetshtml = '';
2287 foreach ($CFG->stylesheets as $stylesheet) {
2288 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2290 $meta = $stylesheetshtml.$meta;
2293 /// Add the meta page from the themes if any were requested
2295 $metapage = '';
2297 if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
2298 ob_start();
2299 include_once($CFG->dirroot.'/theme/standard/meta.php');
2300 $metapage .= ob_get_contents();
2301 ob_end_clean();
2304 if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
2305 if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
2306 ob_start();
2307 include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
2308 $metapage .= ob_get_contents();
2309 ob_end_clean();
2313 if (!isset($THEME->metainclude) || $THEME->metainclude) {
2314 if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
2315 ob_start();
2316 include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
2317 $metapage .= ob_get_contents();
2318 ob_end_clean();
2322 $meta = $meta."\n".$metapage;
2325 /// Add the required JavaScript Libraries for AJAX
2326 if (!empty($CFG->enableajax)) {
2327 $meta .= "\n".require_js();
2330 /// Set up some navigation variables
2332 if (is_newnav($navigation)){
2333 $home = false;
2334 } else {
2335 if ($navigation == 'home') {
2336 $home = true;
2337 $navigation = '';
2338 } else {
2339 $home = false;
2343 /// This is another ugly hack to make navigation elements available to print_footer later
2344 $THEME->title = $title;
2345 $THEME->heading = $heading;
2346 $THEME->navigation = $navigation;
2347 $THEME->button = $button;
2348 $THEME->menu = $menu;
2349 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2351 if ($button == '') {
2352 $button = '&nbsp;';
2355 if (!$menu and $navigation) {
2356 if (empty($CFG->loginhttps)) {
2357 $wwwroot = $CFG->wwwroot;
2358 } else {
2359 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
2361 $menu = user_login_string($COURSE);
2364 if (isset($SESSION->justloggedin)) {
2365 unset($SESSION->justloggedin);
2366 if (!empty($CFG->displayloginfailures)) {
2367 if (!empty($USER->username) and $USER->username != 'guest') {
2368 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
2369 $menu .= '&nbsp;<font size="1">';
2370 if (empty($count->accounts)) {
2371 $menu .= get_string('failedloginattempts', '', $count);
2372 } else {
2373 $menu .= get_string('failedloginattemptsall', '', $count);
2375 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
2376 $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
2377 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
2379 $menu .= '</font>';
2386 $meta = '<meta http-equiv="content-type" content="text/html; charset=utf-8" />'. "\n". $meta ."\n";
2387 if (!$usexml) {
2388 @header('Content-type: text/html; charset=utf-8');
2391 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2392 $direction = get_html_lang($dir=true);
2394 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2395 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2396 @header('Pragma: no-cache');
2397 @header('Expires: ');
2398 } else { // Do everything we can to always prevent clients and proxies caching
2399 @header('Cache-Control: no-store, no-cache, must-revalidate');
2400 @header('Cache-Control: post-check=0, pre-check=0', false);
2401 @header('Pragma: no-cache');
2402 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2403 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2405 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2406 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
2408 @header('Accept-Ranges: none');
2410 $currentlanguage = current_language();
2412 if (empty($usexml)) {
2413 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2414 } else {
2415 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2416 if(!$mathplayer) {
2417 header('Content-Type: application/xhtml+xml');
2419 echo '<?xml version="1.0" ?>'."\n";
2420 if (!empty($CFG->xml_stylesheets)) {
2421 $stylesheets = explode(';', $CFG->xml_stylesheets);
2422 foreach ($stylesheets as $stylesheet) {
2423 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
2426 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
2427 if (!empty($CFG->xml_doctype_extra)) {
2428 echo ' plus '. $CFG->xml_doctype_extra;
2430 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
2431 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2432 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
2433 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2434 $direction";
2435 if($mathplayer) {
2436 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
2437 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2438 $meta .= '</object>'."\n";
2439 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2443 // Clean up the title
2445 $title = format_string($title); // fix for MDL-8582
2446 $title = str_replace('"', '&quot;', $title);
2448 // Create class and id for this page
2450 page_id_and_class($pageid, $pageclass);
2452 $pageclass .= ' course-'.$COURSE->id;
2454 if (($pageid != 'site-index') && ($pageid != 'course-view') &&
2455 (strstr($pageid, 'admin') === FALSE)) {
2456 $pageclass .= ' nocoursepage';
2459 if (!isloggedin()) {
2460 $pageclass .= ' notloggedin';
2463 if (!empty($USER->editing)) {
2464 $pageclass .= ' editing';
2467 if (!empty($CFG->blocksdrag)) {
2468 $pageclass .= ' drag';
2471 $pageclass .= ' dir-'.get_string('thisdirection');
2473 $pageclass .= ' lang-'.$currentlanguage;
2475 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
2477 ob_start();
2478 include($CFG->header);
2479 $output = ob_get_contents();
2480 ob_end_clean();
2482 $output = force_strict_header($output);
2484 if (!empty($CFG->messaging)) {
2485 $output .= message_popup_window();
2488 if ($return) {
2489 return $output;
2490 } else {
2491 echo $output;
2496 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2497 * and substitute the XHTML strict document type.
2498 * Note, requires the 'xmlns' fix in function print_header above.
2499 * See: http://tracker.moodle.org/browse/MDL-7883
2500 * TODO:
2502 function force_strict_header($output) {
2503 global $CFG;
2504 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2505 $xsl = '/lib/xhtml.xsl';
2507 if (!headers_sent() && debugging(NULL, DEBUG_DEVELOPER)) { // In developer debugging, the browser will barf
2508 $ctype = 'Content-Type: ';
2509 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2511 if (isset($_SERVER['HTTP_ACCEPT'])
2512 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2513 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2514 // Firefox et al.
2515 $ctype .= 'application/xhtml+xml';
2516 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2518 } else if (file_exists($CFG->dirroot.$xsl)
2519 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2520 // XSL hack for IE 5+ on Windows.
2521 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2522 $www_xsl = $CFG->wwwroot .$xsl;
2523 $ctype .= 'application/xml';
2524 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2525 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2527 } else {
2528 //ELSE: Mac/IE, old/non-XML browsers.
2529 $ctype .= 'text/html';
2530 $prolog = '';
2532 @header($ctype.'; charset=utf-8');
2533 $output = $prolog . $output;
2535 // Test parser error-handling.
2536 if (isset($_GET['error'])) {
2537 $output .= "__ TEST: XML well-formed error < __\n";
2541 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
2543 return $output;
2549 * This version of print_header is simpler because the course name does not have to be
2550 * provided explicitly in the strings. It can be used on the site page as in courses
2551 * Eventually all print_header could be replaced by print_header_simple
2553 * @param string $title Appears at the top of the window
2554 * @param string $heading Appears at the top of the page
2555 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2556 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2557 * @param string $meta Meta tags to be added to the header
2558 * @param boolean $cache Should this page be cacheable?
2559 * @param string $button HTML code for a button (usually for module editing)
2560 * @param string $menu HTML code for a popup menu
2561 * @param boolean $usexml use XML for this page
2562 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2563 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2565 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
2566 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
2568 global $COURSE, $CFG;
2570 $shortname ='';
2571 if ($COURSE->id != SITEID) {
2572 $shortname = '<a href="'.$CFG->wwwroot.'/course/view.php?id='. $COURSE->id .'">'. $COURSE->shortname .'</a> ->';
2575 // If old style nav prepend course short name otherwise leave $navigation object alone
2576 if (!is_newnav($navigation)) {
2577 $navigation = $shortname.' '.$navigation;
2580 $output = print_header($COURSE->shortname .': '. $title, $COURSE->fullname .' '. $heading, $navigation, $focus, $meta,
2581 $cache, $button, $menu, $usexml, $bodytags, true);
2583 if ($return) {
2584 return $output;
2585 } else {
2586 echo $output;
2592 * Can provide a course object to make the footer contain a link to
2593 * to the course home page, otherwise the link will go to the site home
2595 * @uses $CFG
2596 * @uses $USER
2597 * @param course $course {@link $COURSE} object containing course information
2598 * @param ? $usercourse ?
2599 * @todo Finish documenting this function
2601 function print_footer($course=NULL, $usercourse=NULL, $return=false) {
2602 global $USER, $CFG, $THEME, $COURSE;
2604 if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
2605 admin_externalpage_print_footer();
2606 return;
2609 /// Course links
2610 if ($course) {
2611 if (is_string($course) && $course == 'none') { // Don't print any links etc
2612 $homelink = '';
2613 $loggedinas = '';
2614 $home = false;
2615 } else if (is_string($course) && $course == 'home') { // special case for site home page - please do not remove
2616 $course = get_site();
2617 $homelink = '<div class="sitelink">'.
2618 '<a title="moodle '. $CFG->release .' ('. $CFG->version .')" href="http://moodle.org/">'.
2619 '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
2620 $home = true;
2621 } else {
2622 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
2623 '/course/view.php?id='.$course->id.'">'.format_string($course->shortname).'</a></div>';
2624 $home = false;
2626 } else {
2627 $course = get_site(); // Set course as site course by default
2628 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
2629 $home = false;
2632 /// Set up some other navigation links (passed from print_header by ugly hack)
2633 $menu = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
2634 $title = isset($THEME->title) ? $THEME->title : '';
2635 $button = isset($THEME->button) ? $THEME->button : '';
2636 $heading = isset($THEME->heading) ? $THEME->heading : '';
2637 $navigation = isset($THEME->navigation) ? $THEME->navigation : '';
2638 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2641 /// Set the user link if necessary
2642 if (!$usercourse and is_object($course)) {
2643 $usercourse = $course;
2646 if (!isset($loggedinas)) {
2647 $loggedinas = user_login_string($usercourse, $USER);
2650 if ($loggedinas == $menu) {
2651 $menu = '';
2654 /// Provide some performance info if required
2655 $performanceinfo = '';
2656 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2657 $perf = get_performance_info();
2658 if (defined('MDL_PERFTOLOG')) {
2659 error_log("PERF: " . $perf['txt']);
2661 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
2662 $performanceinfo = $perf['html'];
2667 /// Include the actual footer file
2669 ob_start();
2670 include($CFG->footer);
2671 $output = ob_get_contents();
2672 ob_end_clean();
2674 if ($return) {
2675 return $output;
2676 } else {
2677 echo $output;
2682 * Returns the name of the current theme
2684 * @uses $CFG
2685 * @uses $USER
2686 * @uses $SESSION
2687 * @uses $COURSE
2688 * @uses $FULLME
2689 * @return string
2691 function current_theme() {
2692 global $CFG, $USER, $SESSION, $COURSE, $FULLME;
2694 if (empty($CFG->themeorder)) {
2695 $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
2696 } else {
2697 $themeorder = $CFG->themeorder;
2700 $theme = '';
2701 foreach ($themeorder as $themetype) {
2703 if (!empty($theme)) continue;
2705 switch ($themetype) {
2706 case 'page': // Page theme is for special page-only themes set by code
2707 if (!empty($CFG->pagetheme)) {
2708 $theme = $CFG->pagetheme;
2710 break;
2711 case 'course':
2712 if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) {
2713 $theme = $COURSE->theme;
2715 break;
2716 case 'category':
2717 if (!empty($CFG->allowcategorythemes)) {
2718 /// Nasty hack to check if we're in a category page
2719 if (stripos($FULLME, 'course/category.php') !== false) {
2720 global $id;
2721 if (!empty($id)) {
2722 $theme = current_category_theme($id);
2724 /// Otherwise check if we're in a course that has a category theme set
2725 } else if (!empty($COURSE->category)) {
2726 $theme = current_category_theme($COURSE->category);
2729 break;
2730 case 'session':
2731 if (!empty($SESSION->theme)) {
2732 $theme = $SESSION->theme;
2734 break;
2735 case 'user':
2736 if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) {
2737 $theme = $USER->theme;
2739 break;
2740 case 'site':
2741 $theme = $CFG->theme;
2742 break;
2743 default:
2744 /// do nothing
2748 /// A final check in case 'site' was not included in $CFG->themeorder
2749 if (empty($theme)) {
2750 $theme = $CFG->theme;
2753 return $theme;
2757 * Retrieves the category theme if one exists, otherwise checks the parent categories.
2758 * Recursive function.
2760 * @uses $COURSE
2761 * @param integer $categoryid id of the category to check
2762 * @return string theme name
2764 function current_category_theme($categoryid=0) {
2765 global $COURSE;
2767 /// Use the COURSE global if the categoryid not set
2768 if (empty($categoryid)) {
2769 if (!empty($COURSE->category)) {
2770 $categoryid = $COURSE->category;
2771 } else {
2772 return false;
2776 /// Retrieve the current category
2777 if ($category = get_record('course_categories', 'id', $categoryid)) {
2779 /// Return the category theme if it exists
2780 if (!empty($category->theme)) {
2781 return $category->theme;
2783 /// Otherwise try the parent category if one exists
2784 } else if (!empty($category->parent)) {
2785 return current_category_theme($category->parent);
2788 /// Return false if we can't find the category record
2789 } else {
2790 return false;
2795 * This function is called by stylesheets to set up the header
2796 * approriately as well as the current path
2798 * @uses $CFG
2799 * @param int $lastmodified ?
2800 * @param int $lifetime ?
2801 * @param string $thename ?
2803 function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
2805 global $CFG, $THEME;
2807 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
2808 $lastmodified = time();
2810 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
2811 header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
2812 header('Cache-Control: max-age='. $lifetime);
2813 header('Pragma: ');
2814 header('Content-type: text/css'); // Correct MIME type
2816 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
2818 if (empty($themename)) {
2819 $themename = current_theme(); // So we have something. Normally not needed.
2820 } else {
2821 $themename = clean_param($themename, PARAM_SAFEDIR);
2824 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
2825 unset($THEME);
2826 include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
2829 /// If this is the standard theme calling us, then find out what sheets we need
2831 if ($themename == 'standard') {
2832 if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
2833 $THEME->sheets = $DEFAULT_SHEET_LIST;
2834 } else if (empty($THEME->standardsheets)) { // We can stop right now!
2835 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
2836 exit;
2837 } else { // Use the provided subset only
2838 $THEME->sheets = $THEME->standardsheets;
2841 /// If we are a parent theme, then check for parent definitions
2843 } else if (!empty($THEME->parent) && $themename == $THEME->parent) {
2844 if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have
2845 $THEME->sheets = $DEFAULT_SHEET_LIST;
2846 } else if (empty($THEME->parentsheets)) { // We can stop right now!
2847 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
2848 exit;
2849 } else { // Use the provided subset only
2850 $THEME->sheets = $THEME->parentsheets;
2854 /// Work out the last modified date for this theme
2856 foreach ($THEME->sheets as $sheet) {
2857 if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
2858 $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
2859 if ($sheetmodified > $lastmodified) {
2860 $lastmodified = $sheetmodified;
2866 /// Get a list of all the files we want to include
2867 $files = array();
2869 foreach ($THEME->sheets as $sheet) {
2870 $files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
2873 if ($themename == 'standard') { // Add any standard styles included in any modules
2874 if (!empty($THEME->modsheets)) { // Search for styles.php within activity modules
2875 if ($mods = get_list_of_plugins('mod')) {
2876 foreach ($mods as $mod) {
2877 if (file_exists($CFG->dirroot.'/mod/'.$mod.'/styles.php')) {
2878 $files[] = array($CFG->dirroot, '/mod/'.$mod.'/styles.php');
2884 if (!empty($THEME->blocksheets)) { // Search for styles.php within block modules
2885 if ($mods = get_list_of_plugins('blocks')) {
2886 foreach ($mods as $mod) {
2887 if (file_exists($CFG->dirroot.'/blocks/'.$mod.'/styles.php')) {
2888 $files[] = array($CFG->dirroot, '/blocks/'.$mod.'/styles.php');
2894 if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
2895 if ($mods = get_list_of_plugins('format','',$CFG->dirroot.'/course')) {
2896 foreach ($mods as $mod) {
2897 if (file_exists($CFG->dirroot.'/course/format/'.$mod.'/styles.php')) {
2898 $files[] = array($CFG->dirroot, '/course/format/'.$mod.'/styles.php');
2904 if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
2905 if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
2906 $files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
2911 if ($files) {
2912 /// Produce a list of all the files first
2913 echo '/**************************************'."\n";
2914 echo ' * THEME NAME: '.$themename."\n *\n";
2915 echo ' * Files included in this sheet:'."\n *\n";
2916 foreach ($files as $file) {
2917 echo ' * '.$file[1]."\n";
2919 echo ' **************************************/'."\n\n";
2922 /// check if csscobstants is set
2923 if (!empty($THEME->cssconstants)) {
2924 require_once("$CFG->libdir/cssconstants.php");
2925 /// Actually collect all the files in order.
2926 $css = '';
2927 foreach ($files as $file) {
2928 $css .= '/***** '.$file[1].' start *****/'."\n\n";
2929 $css .= file_get_contents($file[0].'/'.$file[1]);
2930 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
2932 /// replace css_constants with their values
2933 echo replace_cssconstants($css);
2934 } else {
2935 /// Actually output all the files in order.
2936 if (empty($CFG->CSSEdit) && empty($THEME->CSSEdit)) {
2937 foreach ($files as $file) {
2938 echo '/***** '.$file[1].' start *****/'."\n\n";
2939 @include_once($file[0].'/'.$file[1]);
2940 echo '/***** '.$file[1].' end *****/'."\n\n";
2942 } else {
2943 foreach ($files as $file) {
2944 echo '/* @group '.$file[1].' */'."\n\n";
2945 if (strstr($file[1], '.css') !== FALSE) {
2946 echo '@import url("'.$CFG->themewww.'/'.$file[1].'");'."\n\n";
2947 } else {
2948 @include_once($file[0].'/'.$file[1]);
2950 echo '/* @end */'."\n\n";
2956 return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
2960 function theme_setup($theme = '', $params=NULL) {
2961 /// Sets up global variables related to themes
2963 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
2965 if (empty($theme)) {
2966 $theme = current_theme();
2969 /// If the theme doesn't exist for some reason then revert to standardwhite
2970 if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
2971 $CFG->theme = $theme = 'standardwhite';
2974 /// Load up the theme config
2975 $THEME = NULL; // Just to be sure
2976 include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
2978 /// Put together the parameters
2979 if (!$params) {
2980 $params = array();
2983 if ($theme != $CFG->theme) {
2984 $params[] = 'forceconfig='.$theme;
2987 /// Force language too if required
2988 if (!empty($THEME->langsheets)) {
2989 $params[] = 'lang='.current_language();
2993 /// Convert params to string
2994 if ($params) {
2995 $paramstring = '?'.implode('&', $params);
2996 } else {
2997 $paramstring = '';
3000 /// Set up image paths
3001 if(isset($CFG->smartpix) && $CFG->smartpix==1) {
3002 if($CFG->slasharguments) { // Use this method if possible for better caching
3003 $extra='';
3004 } else {
3005 $extra='?file=';
3008 $CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
3009 $CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
3010 } else if (empty($THEME->custompix)) { // Could be set in the above file
3011 $CFG->pixpath = $CFG->wwwroot .'/pix';
3012 $CFG->modpixpath = $CFG->wwwroot .'/mod';
3013 } else {
3014 $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
3015 $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
3018 /// Header and footer paths
3019 $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
3020 $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
3022 /// Define stylesheet loading order
3023 $CFG->stylesheets = array();
3024 if ($theme != 'standard') { /// The standard sheet is always loaded first
3025 $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
3027 if (!empty($THEME->parent)) { /// Parent stylesheets are loaded next
3028 $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
3030 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
3032 /// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
3033 if (!empty($HTTPSPAGEREQUIRED)) {
3034 $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
3035 $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
3036 $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
3037 foreach ($CFG->stylesheets as $key => $stylesheet) {
3038 $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
3042 // RTL support - only for RTL languages, add RTL CSS
3043 if (get_string('thisdirection') == 'rtl') {
3044 $CFG->stylesheets[] = $CFG->themewww.'/standard/rtl.css'.$paramstring;
3045 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/rtl.css'.$paramstring;
3051 * Returns text to be displayed to the user which reflects their login status
3053 * @uses $CFG
3054 * @uses $USER
3055 * @param course $course {@link $COURSE} object containing course information
3056 * @param user $user {@link $USER} object containing user information
3057 * @return string
3059 function user_login_string($course=NULL, $user=NULL) {
3060 global $USER, $CFG, $SITE;
3062 if (empty($user) and !empty($USER->id)) {
3063 $user = $USER;
3066 if (empty($course)) {
3067 $course = $SITE;
3070 if (!empty($user->realuser)) {
3071 if ($realuser = get_record('user', 'id', $user->realuser)) {
3072 $fullname = fullname($realuser, true);
3073 $realuserinfo = " [<a $CFG->frametarget
3074 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=1&amp;sesskey=".sesskey()."\">$fullname</a>] ";
3076 } else {
3077 $realuserinfo = '';
3080 if (empty($CFG->loginhttps)) {
3081 $wwwroot = $CFG->wwwroot;
3082 } else {
3083 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
3086 if (empty($course->id)) {
3087 // $course->id is not defined during installation
3088 return '';
3089 } else if (!empty($user->id)) {
3090 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3092 $fullname = fullname($user, true);
3093 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a>";
3094 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid)) {
3095 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
3097 if (isset($user->username) && $user->username == 'guest') {
3098 $loggedinas = $realuserinfo.get_string('loggedinasguest').
3099 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3100 } else if (!empty($user->switchrole[$context->id])) {
3101 $rolename = '';
3102 if ($role = get_record('role', 'id', $user->switchrole[$context->id])) {
3103 $rolename = ': '.format_string($role->name);
3105 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
3106 " (<a $CFG->frametarget
3107 href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
3108 } else {
3109 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
3110 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
3112 } else {
3113 $loggedinas = get_string('loggedinnot', 'moodle').
3114 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3116 return '<div class="logininfo">'.$loggedinas.'</div>';
3120 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
3121 * If not it applies sensible defaults.
3123 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
3124 * search forum block, etc. Important: these are 'silent' in a screen-reader
3125 * (unlike &gt; &raquo;), and must be accompanied by text.
3126 * @uses $THEME
3128 function check_theme_arrows() {
3129 global $THEME;
3131 if (!isset($THEME->rarrow) and !isset($THEME->larrow)) {
3132 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
3133 // Also OK in Win 9x/2K/IE 5.x
3134 $THEME->rarrow = '&#x25BA;';
3135 $THEME->larrow = '&#x25C4;';
3136 $uagent = $_SERVER['HTTP_USER_AGENT'];
3137 if (false !== strpos($uagent, 'Opera')
3138 || false !== strpos($uagent, 'Mac')) {
3139 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
3140 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
3141 $THEME->rarrow = '&#x25B6;';
3142 $THEME->larrow = '&#x25C0;';
3144 elseif (false !== strpos($uagent, 'Konqueror')) {
3145 $THEME->rarrow = '&rarr;';
3146 $THEME->larrow = '&larr;';
3148 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
3149 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
3150 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
3151 // To be safe, non-Unicode browsers!
3152 $THEME->rarrow = '&gt;';
3153 $THEME->larrow = '&lt;';
3156 /// RTL support - in RTL languages, swap r and l arrows
3157 if (right_to_left()) {
3158 $t = $THEME->rarrow;
3159 $THEME->rarrow = $THEME->larrow;
3160 $THEME->larrow = $t;
3167 * Return the right arrow with text ('next'), and optionally embedded in a link.
3168 * See function above, check_theme_arrows.
3169 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3170 * @param string $url An optional link to use in a surrounding HTML anchor.
3171 * @param bool $accesshide True if text should be hidden (for screen readers only).
3172 * @param string $addclass Additional class names for the link, or the arrow character.
3173 * @return string HTML string.
3175 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
3176 global $THEME;
3177 check_theme_arrows();
3178 $arrowclass = 'arrow ';
3179 if (! $url) {
3180 $arrowclass .= $addclass;
3182 $arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow.'</span>';
3183 $htmltext = '';
3184 if ($text) {
3185 $htmltext = $text.'&nbsp;';
3186 if ($accesshide) {
3187 $htmltext = '<span class="accesshide">'.$htmltext.'</span>';
3190 if ($url) {
3191 $class = '';
3192 if ($addclass) {
3193 $class =" class=\"$addclass\"";
3195 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
3197 return $htmltext.$arrow;
3201 * Return the left arrow with text ('previous'), and optionally embedded in a link.
3202 * See function above, check_theme_arrows.
3203 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3204 * @param string $url An optional link to use in a surrounding HTML anchor.
3205 * @param bool $accesshide True if text should be hidden (for screen readers only).
3206 * @param string $addclass Additional class names for the link, or the arrow character.
3207 * @return string HTML string.
3209 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
3210 global $THEME;
3211 check_theme_arrows();
3212 $arrowclass = 'arrow ';
3213 if (! $url) {
3214 $arrowclass .= $addclass;
3216 $arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow.'</span>';
3217 $htmltext = '';
3218 if ($text) {
3219 $htmltext = '&nbsp;'.$text;
3220 if ($accesshide) {
3221 $htmltext = '<span class="accesshide">'.$htmltext.'</span>';
3224 if ($url) {
3225 $class = '';
3226 if ($addclass) {
3227 $class =" class=\"$addclass\"";
3229 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
3231 return $arrow.$htmltext;
3235 * Return the breadcrumb trail navigation separator.
3236 * @return string HTML string.
3238 function get_separator() {
3239 //Accessibility: the 'hidden' slash is preferred for screen readers.
3240 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
3244 * Prints breadcrumb trail of links, called in theme/-/header.html
3246 * @uses $CFG
3247 * @param mixed $navigation The breadcrumb navigation string to be printed
3248 * @param string $separator The breadcrumb trail separator. The default 0 leads to the use
3249 * of $THEME->rarrow, themes could use '&rarr;', '/', or '' for a style-sheet solution.
3250 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
3252 function print_navigation ($navigation, $separator=0, $return=false) {
3253 global $CFG, $THEME;
3254 $output = '';
3256 if (0 === $separator) {
3257 $separator = get_separator();
3259 else {
3260 $separator = '<span class="sep">'. $separator .'</span>';
3263 if ($navigation) {
3265 if (is_newnav($navigation)) {
3266 if ($return) {
3267 return($navigation['navlinks']);
3268 } else {
3269 echo $navigation['navlinks'];
3270 return;
3272 } else {
3273 debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER);
3276 if (!is_array($navigation)) {
3277 $ar = explode('->', $navigation);
3278 $navigation = array();
3280 foreach ($ar as $a) {
3281 if (strpos($a, '</a>') === false) {
3282 $navigation[] = array('title' => $a, 'url' => '');
3283 } else {
3284 if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
3285 $navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
3291 if (! $site = get_site()) {
3292 $site = new object();
3293 $site->shortname = get_string('home');
3296 //Accessibility: breadcrumb links now in a list, &raquo; replaced with a 'silent' character.
3297 $nav_text = get_string('youarehere','access');
3298 $output .= '<h2 class="accesshide">'.$nav_text."</h2><ul>\n";
3300 $output .= '<li class="first">'."\n".'<a '.$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3301 .$CFG->wwwroot.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))
3302 && !empty($USER->id) && !empty($CFG->mymoodleredirect) && !isguest())
3303 ? '/my' : '') .'/">'. format_string($site->shortname) ."</a>\n</li>\n";
3306 foreach ($navigation as $navitem) {
3307 $title = trim(strip_tags(format_string($navitem['title'], false)));
3308 $url = $navitem['url'];
3310 if (empty($url)) {
3311 $output .= '<li class="first">'."$separator $title</li>\n";
3312 } else {
3313 $output .= '<li class="first">'."$separator\n<a ".$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3314 .$url.'">'."$title</a>\n</li>\n";
3318 $output .= "</ul>\n";
3321 if ($return) {
3322 return $output;
3323 } else {
3324 echo $output;
3329 * This function will build the navigation string to be used by print_header
3330 * and others
3331 * @uses $CFG
3332 * @uses $THEME
3333 * @param $extranavlinks - array of associative arrays, keys: name, link, type
3334 * @return $navigation as an object so it can be differentiated from old style
3335 * navigation strings.
3337 function build_navigation($extranavlinks) {
3338 global $CFG, $COURSE;
3340 $navigation = '';
3341 $navlinks = array();
3343 //Site name
3344 if ($site = get_site()) {
3345 $navlinks[] = array('name' => format_string($site->shortname),
3346 'link' => "$CFG->wwwroot/",
3347 'type' => 'home');
3351 if ($COURSE) {
3352 if ($COURSE->id != SITEID) {
3353 //Course
3354 $navlinks[] = array('name' => format_string($COURSE->shortname),
3355 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",
3356 'type' => 'course');
3360 //Merge in extra navigation links
3361 $navlinks = array_merge($navlinks, $extranavlinks);
3363 //Construct an unordered list from $navlinks
3364 //Accessibility: heading hidden from visual browsers by default.
3365 $navigation = '<h2 class="accesshide">'.get_string('youarehere','access')."</h2> <ul>\n";
3366 $countlinks = count($navlinks);
3367 $i = 0;
3368 foreach ($navlinks as $navlink) {
3369 if ($i >= $countlinks || !is_array($navlink)) {
3370 continue;
3372 // Check the link type to see if this link should appear in the trail
3373 $cap = has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $COURSE->id));
3374 $hidetype_is2 = $CFG->hideactivitytypenavlink == 2;
3375 $hidetype_is1 = $CFG->hideactivitytypenavlink == 1;
3377 if ($navlink['type'] == 'activity' &&
3378 $i+1 < $countlinks &&
3379 ($hidetype_is2 || ($hidetype_is1 && !$cap))) {
3380 continue;
3382 $navigation .= '<li class="first">';
3383 if ($i > 0) {
3384 $navigation .= get_separator();
3386 if ((!empty($navlink['link'])) && $i+1 < $countlinks) {
3387 $navigation .= "<a onclick=\"this.target='$CFG->framename'\" href=\"{$navlink['link']}\">";
3389 $navigation .= "{$navlink['name']}";
3390 if ((!empty($navlink['link'])) && $i+1 < $countlinks) {
3391 $navigation .= "</a>";
3394 $navigation .= "</li>";
3395 $i++;
3398 $navigation .= "</ul>";
3400 return(array('newnav' => true, 'navlinks' => $navigation));
3405 * Prints a string in a specified size (retained for backward compatibility)
3407 * @param string $text The text to be displayed
3408 * @param int $size The size to set the font for text display.
3410 function print_headline($text, $size=2, $return=false) {
3411 $output = print_heading($text, '', $size, true);
3412 if ($return) {
3413 return $output;
3414 } else {
3415 echo $output;
3420 * Prints text in a format for use in headings.
3422 * @param string $text The text to be displayed
3423 * @param string $align The alignment of the printed paragraph of text
3424 * @param int $size The size to set the font for text display.
3426 function print_heading($text, $align='', $size=2, $class='main', $return=false) {
3427 if ($align) {
3428 $align = ' style="text-align:'.$align.';"';
3430 if ($class) {
3431 $class = ' class="'.$class.'"';
3433 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
3435 if ($return) {
3436 return $output;
3437 } else {
3438 echo $output;
3443 * Centered heading with attached help button (same title text)
3444 * and optional icon attached
3446 * @param string $text The text to be displayed
3447 * @param string $helppage The help page to link to
3448 * @param string $module The module whose help should be linked to
3449 * @param string $icon Image to display if needed
3451 function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
3452 $output = '';
3453 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
3454 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
3455 $output .= '</h2>';
3457 if ($return) {
3458 return $output;
3459 } else {
3460 echo $output;
3465 function print_heading_block($heading, $class='', $return=false) {
3466 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
3467 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
3469 if ($return) {
3470 return $output;
3471 } else {
3472 echo $output;
3478 * Print a link to continue on to another page.
3480 * @uses $CFG
3481 * @param string $link The url to create a link to.
3483 function print_continue($link, $return=false) {
3485 global $CFG;
3487 // in case we are logging upgrade in admin/index.php stop it
3488 if (function_exists('upgrade_log_finish')) {
3489 upgrade_log_finish();
3492 $output = '';
3494 if ($link == '') {
3495 if (!empty($_SERVER['HTTP_REFERER'])) {
3496 $link = $_SERVER['HTTP_REFERER'];
3497 $link = str_replace('&', '&amp;', $link); // make it valid XHTML
3498 } else {
3499 $link = $CFG->wwwroot .'/';
3503 $output .= '<div class="continuebutton">';
3505 $output .= print_single_button($link, NULL, get_string('continue'), 'post', $CFG->framename, true);
3506 $output .= '</div>'."\n";
3508 if ($return) {
3509 return $output;
3510 } else {
3511 echo $output;
3517 * Print a message in a standard themed box.
3518 * Replaces print_simple_box (see deprecatedlib.php)
3520 * @param string $message, the content of the box
3521 * @param string $classes, space-separated class names.
3522 * @param string $ids, space-separated id names.
3523 * @param boolean $return, return as string or just print it
3525 function print_box($message, $classes='generalbox', $ids='', $return=false) {
3527 $output = print_box_start($classes, $ids, true);
3528 $output .= stripslashes_safe($message);
3529 $output .= print_box_end(true);
3531 if ($return) {
3532 return $output;
3533 } else {
3534 echo $output;
3539 * Starts a box using divs
3540 * Replaces print_simple_box_start (see deprecatedlib.php)
3542 * @param string $classes, space-separated class names.
3543 * @param string $ids, space-separated id names.
3544 * @param boolean $return, return as string or just print it
3546 function print_box_start($classes='generalbox', $ids='', $return=false) {
3547 $output = '';
3549 if ($ids) {
3550 $ids = ' id="'.$ids.'"';
3553 $output .= '<div'.$ids.' class="box '.$classes.'">';
3555 if ($return) {
3556 return $output;
3557 } else {
3558 echo $output;
3564 * Simple function to end a box (see above)
3565 * Replaces print_simple_box_end (see deprecatedlib.php)
3567 * @param boolean $return, return as string or just print it
3569 function print_box_end($return=false) {
3570 $output = '</div>';
3571 if ($return) {
3572 return $output;
3573 } else {
3574 echo $output;
3580 * Print a self contained form with a single submit button.
3582 * @param string $link ?
3583 * @param array $options ?
3584 * @param string $label ?
3585 * @param string $method ?
3586 * @todo Finish documenting this function
3588 function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='') {
3589 $output = '';
3590 $link = str_replace('"', '&quot;', $link); //basic XSS protection
3591 $output .= '<div class="singlebutton">';
3592 // taking target out, will need to add later target="'.$target.'"
3593 $output .= '<form action="'. $link .'" method="'. $method .'">';
3594 $output .= '<div>';
3595 if ($options) {
3596 foreach ($options as $name => $value) {
3597 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
3600 if ($tooltip) {
3601 $tooltip = 'title="' . s($tooltip) . '"';
3602 } else {
3603 $tooltip = '';
3605 $output .= '<input type="submit" value="'. s($label) .'" ' . $tooltip . ' /></div></form></div>';
3607 if ($return) {
3608 return $output;
3609 } else {
3610 echo $output;
3616 * Print a spacer image with the option of including a line break.
3618 * @param int $height ?
3619 * @param int $width ?
3620 * @param boolean $br ?
3621 * @todo Finish documenting this function
3623 function print_spacer($height=1, $width=1, $br=true, $return=false) {
3624 global $CFG;
3625 $output = '';
3627 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot .'/pix/spacer.gif" alt="" />';
3628 if ($br) {
3629 $output .= '<br />'."\n";
3632 if ($return) {
3633 return $output;
3634 } else {
3635 echo $output;
3640 * Given the path to a picture file in a course, or a URL,
3641 * this function includes the picture in the page.
3643 * @param string $path ?
3644 * @param int $courseid ?
3645 * @param int $height ?
3646 * @param int $width ?
3647 * @param string $link ?
3648 * @todo Finish documenting this function
3650 function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
3651 global $CFG;
3652 $output = '';
3654 if ($height) {
3655 $height = 'height="'. $height .'"';
3657 if ($width) {
3658 $width = 'width="'. $width .'"';
3660 if ($link) {
3661 $output .= '<a href="'. $link .'">';
3663 if (substr(strtolower($path), 0, 7) == 'http://') {
3664 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
3666 } else if ($courseid) {
3667 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
3668 if ($CFG->slasharguments) { // Use this method if possible for better caching
3669 $output .= $CFG->wwwroot .'/file.php/'. $courseid .'/'. $path;
3670 } else {
3671 $output .= $CFG->wwwroot .'/file.php?file=/'. $courseid .'/'. $path;
3673 $output .= '" />';
3674 } else {
3675 $output .= 'Error: must pass URL or course';
3677 if ($link) {
3678 $output .= '</a>';
3681 if ($return) {
3682 return $output;
3683 } else {
3684 echo $output;
3689 * Print the specified user's avatar.
3691 * @param int $userid ?
3692 * @param int $courseid ?
3693 * @param boolean $picture Print the user picture?
3694 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
3695 * @param boolean $return If false print picture to current page, otherwise return the output as string
3696 * @param boolean $link Enclose printed image in a link to view specified course?
3697 * @param string $target link target attribute
3698 * @param boolean $alttext use username or userspecified text in image alt attribute
3699 * return string
3700 * @todo Finish documenting this function
3702 function print_user_picture($userid, $courseid, $picture, $size=0, $return=false, $link=true, $target='', $alttext=true) {
3703 global $CFG;
3705 if ($link) {
3706 if ($target) {
3707 $target=' target="_blank"';
3709 $output = '<a '.$target.' href="'. $CFG->wwwroot .'/user/view.php?id='. $userid .'&amp;course='. $courseid .'">';
3710 } else {
3711 $output = '';
3713 if (empty($size)) {
3714 $file = 'f2';
3715 $size = 35;
3716 } else if ($size === true or $size == 1) {
3717 $file = 'f1';
3718 $size = 100;
3719 } else if ($size >= 50) {
3720 $file = 'f1';
3721 } else {
3722 $file = 'f2';
3724 $class = "userpicture";
3725 if ($picture) { // Print custom user picture
3726 if ($CFG->slasharguments) { // Use this method if possible for better caching
3727 $src = $CFG->wwwroot .'/user/pix.php/'. $userid .'/'. $file .'.jpg';
3728 } else {
3729 $src = $CFG->wwwroot .'/user/pix.php?file=/'. $userid .'/'. $file .'.jpg';
3731 } else { // Print default user pictures (use theme version if available)
3732 $class .= " defaultuserpic";
3733 $src = "$CFG->pixpath/u/$file.png";
3735 $imagealt = '';
3736 if ($alttext and $user = get_record('user','id',$userid)) {
3737 if (!empty($user->imagealt)) {
3738 $imagealt = $user->imagealt;
3739 } else {
3740 $imagealt = get_string('pictureof','',fullname($user));
3744 $output .= '<img class="'.$class.'" src="'.$src.'" alt="'.s($imagealt).'" />';
3745 if ($link) {
3746 $output .= '</a>';
3749 if ($return) {
3750 return $output;
3751 } else {
3752 echo $output;
3757 * Prints a summary of a user in a nice little box.
3759 * @uses $CFG
3760 * @uses $USER
3761 * @param user $user A {@link $USER} object representing a user
3762 * @param course $course A {@link $COURSE} object representing a course
3764 function print_user($user, $course, $messageselect=false, $return=false) {
3766 global $CFG, $USER;
3768 $output = '';
3770 static $string;
3771 static $datestring;
3772 static $countries;
3774 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3776 if (empty($string)) { // Cache all the strings for the rest of the page
3778 $string->email = get_string('email');
3779 $string->location = get_string('location');
3780 $string->lastaccess = get_string('lastaccess');
3781 $string->activity = get_string('activity');
3782 $string->unenrol = get_string('unenrol');
3783 $string->loginas = get_string('loginas');
3784 $string->fullprofile = get_string('fullprofile');
3785 $string->role = get_string('role');
3786 $string->name = get_string('name');
3787 $string->never = get_string('never');
3789 $datestring->day = get_string('day');
3790 $datestring->days = get_string('days');
3791 $datestring->hour = get_string('hour');
3792 $datestring->hours = get_string('hours');
3793 $datestring->min = get_string('min');
3794 $datestring->mins = get_string('mins');
3795 $datestring->sec = get_string('sec');
3796 $datestring->secs = get_string('secs');
3798 $countries = get_list_of_countries();
3801 /// Get the hidden field list
3802 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
3803 $hiddenfields = array();
3804 } else {
3805 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
3808 $output .= '<table class="userinfobox">';
3809 $output .= '<tr>';
3810 $output .= '<td class="left side">';
3811 $output .= print_user_picture($user->id, $course->id, $user->picture, true, true);
3812 $output .= '</td>';
3813 $output .= '<td class="content">';
3814 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
3815 $output .= '<div class="info">';
3816 if (!empty($user->role) and ($user->role <> $course->teacher)) {
3817 $output .= $string->role .': '. $user->role .'<br />';
3819 if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguest()) or
3820 has_capability('moodle/course:viewhiddenuserfields', $context)) {
3821 $output .= $string->email .': <a href="mailto:'. $user->email .'">'. $user->email .'</a><br />';
3823 if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
3824 $output .= $string->location .': ';
3825 if ($user->city && !isset($hiddenfields['city'])) {
3826 $output .= $user->city;
3828 if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
3829 if ($user->city && !isset($hiddenfields['city'])) {
3830 $output .= ', ';
3832 $output .= $countries[$user->country];
3834 $output .= '<br />';
3837 if (!isset($hiddenfields['lastaccess'])) {
3838 if ($user->lastaccess) {
3839 $output .= $string->lastaccess .': '. userdate($user->lastaccess);
3840 $output .= '&nbsp; ('. format_time(time() - $user->lastaccess, $datestring) .')';
3841 } else {
3842 $output .= $string->lastaccess .': '. $string->never;
3845 $output .= '</div></td><td class="links">';
3846 //link to blogs
3847 if ($CFG->bloglevel > 0) {
3848 $output .= '<a href="'.$CFG->wwwroot.'/blog/index.php?userid='.$user->id.'">'.get_string('blogs','blog').'</a><br />';
3850 //link to notes
3851 if (has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context)) {
3852 $output .= '<a href="'.$CFG->wwwroot.'/notes/index.php?course=' . $course->id. '&amp;user='.$user->id.'">'.get_string('notes','notes').'</a><br />';
3855 if (has_capability('moodle/site:viewreports', $context)) {
3856 $timemidnight = usergetmidnight(time());
3857 $output .= '<a href="'. $CFG->wwwroot .'/course/user.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->activity .'</a><br />';
3859 if (has_capability('moodle/role:assign', $context, NULL)) { // Includes admins
3860 $output .= '<a href="'. $CFG->wwwroot .'/course/unenrol.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->unenrol .'</a><br />';
3862 if ($USER->id != $user->id && empty($USER->realuser) && has_capability('moodle/user:loginas', $context) &&
3863 ! has_capability('moodle/site:doanything', $context, $user->id, false)) {
3864 $output .= '<a href="'. $CFG->wwwroot .'/course/loginas.php?id='. $course->id .'&amp;user='. $user->id .'&amp;sesskey='. sesskey() .'">'. $string->loginas .'</a><br />';
3866 $output .= '<a href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&amp;course='. $course->id .'">'. $string->fullprofile .'...</a>';
3868 if (!empty($messageselect)) {
3869 $output .= '<br /><input type="checkbox" name="user'.$user->id.'" /> ';
3872 $output .= '</td></tr></table>';
3874 if ($return) {
3875 return $output;
3876 } else {
3877 echo $output;
3882 * Print a specified group's avatar.
3884 * @param group $group A single {@link group} object OR array of groups.
3885 * @param int $courseid The course ID.
3886 * @param boolean $large Default small picture, or large.
3887 * @param boolean $return If false print picture, otherwise return the output as string
3888 * @param boolean $link Enclose image in a link to view specified course?
3889 * @return string
3890 * @todo Finish documenting this function
3892 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
3893 global $CFG;
3895 if (is_array($group)) {
3896 $output = '';
3897 foreach($group as $g) {
3898 $output .= print_group_picture($g, $courseid, $large, true, $link);
3900 if ($return) {
3901 return $output;
3902 } else {
3903 echo $output;
3904 return;
3908 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3910 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
3911 return '';
3914 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
3915 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
3916 } else {
3917 $output = '';
3919 if ($large) {
3920 $file = 'f1';
3921 $size = 100;
3922 } else {
3923 $file = 'f2';
3924 $size = 35;
3926 if ($group->picture) { // Print custom group picture
3927 if ($CFG->slasharguments) { // Use this method if possible for better caching
3928 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot.'/user/pixgroup.php/'.$group->id.'/'.$file.'.jpg"'.
3929 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
3930 } else {
3931 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot.'/user/pixgroup.php?file=/'.$group->id.'/'.$file.'.jpg"'.
3932 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
3935 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
3936 $output .= '</a>';
3939 if ($return) {
3940 return $output;
3941 } else {
3942 echo $output;
3947 * Print a png image.
3949 * @param string $url ?
3950 * @param int $sizex ?
3951 * @param int $sizey ?
3952 * @param boolean $return ?
3953 * @param string $parameters ?
3954 * @todo Finish documenting this function
3956 function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
3957 global $CFG;
3958 static $recentIE;
3960 if (!isset($recentIE)) {
3961 $recentIE = check_browser_version('MSIE', '5.0');
3964 if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
3965 $output .= '<img src="'. $CFG->pixpath .'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
3966 ' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
3967 ' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
3968 "'$url', sizingMethod='scale') ".
3969 ' '. $parameters .' />';
3970 } else {
3971 $output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
3974 if ($return) {
3975 return $output;
3976 } else {
3977 echo $output;
3982 * Print a nicely formatted table.
3984 * @param array $table is an object with several properties.
3985 * <ul>
3986 * <li>$table->head - An array of heading names.
3987 * <li>$table->align - An array of column alignments
3988 * <li>$table->size - An array of column sizes
3989 * <li>$table->wrap - An array of "nowrap"s or nothing
3990 * <li>$table->data[] - An array of arrays containing the data.
3991 * <li>$table->width - A percentage of the page
3992 * <li>$table->tablealign - Align the whole table
3993 * <li>$table->cellpadding - Padding on each cell
3994 * <li>$table->cellspacing - Spacing between cells
3995 * <li>$table->class - class attribute to put on the table
3996 * <li>$table->id - id attribute to put on the table.
3997 * <li>$table->rowclass[] - classes to add to particular rows.
3998 * </ul>
3999 * @param bool $return whether to return an output string or echo now
4000 * @return boolean or $string
4001 * @todo Finish documenting this function
4003 function print_table($table, $return=false) {
4004 $output = '';
4006 if (isset($table->align)) {
4007 foreach ($table->align as $key => $aa) {
4008 if ($aa) {
4009 $align[$key] = ' text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
4010 } else {
4011 $align[$key] = '';
4015 if (isset($table->size)) {
4016 foreach ($table->size as $key => $ss) {
4017 if ($ss) {
4018 $size[$key] = ' width:'. $ss .';';
4019 } else {
4020 $size[$key] = '';
4024 if (isset($table->wrap)) {
4025 foreach ($table->wrap as $key => $ww) {
4026 if ($ww) {
4027 $wrap[$key] = ' white-space:nowrap;';
4028 } else {
4029 $wrap[$key] = '';
4034 if (empty($table->width)) {
4035 $table->width = '80%';
4038 if (empty($table->tablealign)) {
4039 $table->tablealign = 'center';
4042 if (empty($table->cellpadding)) {
4043 $table->cellpadding = '5';
4046 if (empty($table->cellspacing)) {
4047 $table->cellspacing = '1';
4050 if (empty($table->class)) {
4051 $table->class = 'generaltable';
4054 $tableid = empty($table->id) ? '' : 'id="'.$table->id.'"';
4056 $output .= '<table width="'.$table->width.'" ';
4057 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
4059 $countcols = 0;
4061 if (!empty($table->head)) {
4062 $countcols = count($table->head);
4063 $output .= '<tr>';
4064 foreach ($table->head as $key => $heading) {
4066 if (!isset($size[$key])) {
4067 $size[$key] = '';
4069 if (!isset($align[$key])) {
4070 $align[$key] = '';
4073 $output .= '<th class="header c'.$key.'" scope="col">'. $heading .'</th>';
4074 // commenting the following code out as <th style does not validate MDL-7861
4075 //$output .= '<th sytle="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.'" scope="col">'. $heading .'</th>';
4077 $output .= '</tr>'."\n";
4080 if (!empty($table->data)) {
4081 $oddeven = 1;
4082 foreach ($table->data as $key => $row) {
4083 $oddeven = $oddeven ? 0 : 1;
4084 if (!isset($table->rowclass[$key])) {
4085 $table->rowclass[$key] = '';
4087 $output .= '<tr class="r'.$oddeven.' '.$table->rowclass[$key].'">'."\n";
4088 if ($row == 'hr' and $countcols) {
4089 $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
4090 } else { /// it's a normal row of data
4091 foreach ($row as $key => $item) {
4092 if (!isset($size[$key])) {
4093 $size[$key] = '';
4095 if (!isset($align[$key])) {
4096 $align[$key] = '';
4098 if (!isset($wrap[$key])) {
4099 $wrap[$key] = '';
4101 $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.'">'. $item .'</td>';
4104 $output .= '</tr>'."\n";
4107 $output .= '</table>'."\n";
4109 if ($return) {
4110 return $output;
4113 echo $output;
4114 return true;
4118 * Creates a nicely formatted table and returns it.
4120 * @param array $table is an object with several properties.
4121 * <ul<li>$table->head - An array of heading names.
4122 * <li>$table->align - An array of column alignments
4123 * <li>$table->size - An array of column sizes
4124 * <li>$table->wrap - An array of "nowrap"s or nothing
4125 * <li>$table->data[] - An array of arrays containing the data.
4126 * <li>$table->class - A css class name
4127 * <li>$table->fontsize - Is the size of all the text
4128 * <li>$table->tablealign - Align the whole table
4129 * <li>$table->width - A percentage of the page
4130 * <li>$table->cellpadding - Padding on each cell
4131 * <li>$table->cellspacing - Spacing between cells
4132 * </ul>
4133 * @return string
4134 * @todo Finish documenting this function
4136 function make_table($table) {
4138 if (isset($table->align)) {
4139 foreach ($table->align as $key => $aa) {
4140 if ($aa) {
4141 $align[$key] = ' align="'. $aa .'"';
4142 } else {
4143 $align[$key] = '';
4147 if (isset($table->size)) {
4148 foreach ($table->size as $key => $ss) {
4149 if ($ss) {
4150 $size[$key] = ' width="'. $ss .'"';
4151 } else {
4152 $size[$key] = '';
4156 if (isset($table->wrap)) {
4157 foreach ($table->wrap as $key => $ww) {
4158 if ($ww) {
4159 $wrap[$key] = ' style="white-space:nowrap;" ';
4160 } else {
4161 $wrap[$key] = '';
4166 if (empty($table->width)) {
4167 $table->width = '80%';
4170 if (empty($table->tablealign)) {
4171 $table->tablealign = 'center';
4174 if (empty($table->cellpadding)) {
4175 $table->cellpadding = '5';
4178 if (empty($table->cellspacing)) {
4179 $table->cellspacing = '1';
4182 if (empty($table->class)) {
4183 $table->class = 'generaltable';
4186 if (empty($table->fontsize)) {
4187 $fontsize = '';
4188 } else {
4189 $fontsize = '<font size="'. $table->fontsize .'">';
4192 $output = '<table width="'. $table->width .'" align="'. $table->tablealign .'" ';
4193 $output .= ' cellpadding="'. $table->cellpadding .'" cellspacing="'. $table->cellspacing .'" class="'. $table->class .'">'."\n";
4195 if (!empty($table->head)) {
4196 $output .= '<tr valign="top">';
4197 foreach ($table->head as $key => $heading) {
4198 if (!isset($size[$key])) {
4199 $size[$key] = '';
4201 if (!isset($align[$key])) {
4202 $align[$key] = '';
4204 $output .= '<th valign="top" '. $align[$key].$size[$key] .' style="white-space:nowrap;" class="'. $table->class .'header" scope="col">'.$fontsize.$heading.'</th>';
4206 $output .= '</tr>'."\n";
4209 foreach ($table->data as $row) {
4210 $output .= '<tr valign="top">';
4211 foreach ($row as $key => $item) {
4212 if (!isset($size[$key])) {
4213 $size[$key] = '';
4215 if (!isset($align[$key])) {
4216 $align[$key] = '';
4218 if (!isset($wrap[$key])) {
4219 $wrap[$key] = '';
4221 $output .= '<td '. $align[$key].$size[$key].$wrap[$key] .' class="'. $table->class .'cell">'. $fontsize . $item .'</td>';
4223 $output .= '</tr>'."\n";
4225 $output .= '</table>'."\n";
4227 return $output;
4230 function print_recent_activity_note($time, $user, $text, $link, $return=false) {
4231 static $strftimerecent;
4232 $output = '';
4234 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
4235 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
4237 if (empty($strftimerecent)) {
4238 $strftimerecent = get_string('strftimerecent');
4241 $date = userdate($time, $strftimerecent);
4242 $name = fullname($user, $viewfullnames);
4244 $output .= '<div class="head">';
4245 $output .= '<div class="date">'.$date.'</div> '.
4246 '<div class="name">'.fullname($user, $viewfullnames).'</div>';
4247 $output .= '</div>';
4248 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
4250 if ($return) {
4251 return $output;
4252 } else {
4253 echo $output;
4259 * Prints a basic textarea field.
4261 * @uses $CFG
4262 * @param boolean $usehtmleditor ?
4263 * @param int $rows ?
4264 * @param int $cols ?
4265 * @param null $width <b>Legacy field no longer used!</b> Set to zero to get control over mincols
4266 * @param null $height <b>Legacy field no longer used!</b> Set to zero to get control over minrows
4267 * @param string $name ?
4268 * @param string $value ?
4269 * @param int $courseid ?
4270 * @todo Finish documenting this function
4272 function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $courseid=0, $return=false, $id='') {
4273 /// $width and height are legacy fields and no longer used as pixels like they used to be.
4274 /// However, you can set them to zero to override the mincols and minrows values below.
4276 global $CFG, $COURSE, $HTTPSPAGEREQUIRED;
4277 static $scriptcount = 0; // For loading the htmlarea script only once.
4279 $mincols = 65;
4280 $minrows = 10;
4281 $str = '';
4283 if ($id === '') {
4284 $id = 'edit-'.$name;
4287 if ( empty($CFG->editorsrc) ) { // for backward compatibility.
4288 if (empty($courseid)) {
4289 $courseid = $COURSE->id;
4292 if ($usehtmleditor) {
4293 if (!empty($courseid) and has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE, $courseid))) {
4294 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '&ampt;httpsrequired=1';
4295 // needed for course file area browsing in image insert plugin
4296 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4297 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php?id='.$courseid.$httpsrequired.'"></script>'."\n" : '';
4298 } else {
4299 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '?httpsrequired=1';
4300 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4301 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php'.$httpsrequired.'"></script>'."\n" : '';
4304 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4305 $CFG->httpswwwroot .'/lib/editor/htmlarea/lang/en.php"></script>'."\n" : '';
4306 $scriptcount++;
4308 if ($height) { // Usually with legacy calls
4309 if ($rows < $minrows) {
4310 $rows = $minrows;
4313 if ($width) { // Usually with legacy calls
4314 if ($cols < $mincols) {
4315 $cols = $mincols;
4320 $str .= '<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">';
4321 if ($usehtmleditor) {
4322 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
4323 } else {
4324 $str .= s($value);
4326 $str .= '</textarea>'."\n";
4328 if ($usehtmleditor) {
4329 // Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
4330 $str .= '<script type="text/javascript">document.write(\''.
4331 str_replace('\'','\\\'',editorshortcutshelpbutton()).'\'); </script>';
4334 if ($return) {
4335 return $str;
4337 echo $str;
4341 * Sets up the HTML editor on textareas in the current page.
4342 * If a field name is provided, then it will only be
4343 * applied to that field - otherwise it will be used
4344 * on every textarea in the page.
4346 * In most cases no arguments need to be supplied
4348 * @param string $name Form element to replace with HTMl editor by name
4350 function use_html_editor($name='', $editorhidebuttons='', $id='') {
4351 global $THEME;
4353 $editor = 'editor_'.md5($name); //name might contain illegal characters
4354 if ($id === '') {
4355 $id = 'edit-'.$name;
4357 echo "\n".'<script type="text/javascript" defer="defer">'."\n";
4358 echo '//<![CDATA['."\n\n"; // Extra \n is to fix odd wiki problem, MDL-8185
4359 echo "$editor = new HTMLArea('$id');\n";
4360 echo "var config = $editor.config;\n";
4362 echo print_editor_config($editorhidebuttons);
4364 if (empty($THEME->htmleditorpostprocess)) {
4365 if (empty($name)) {
4366 echo "\nHTMLArea.replaceAll($editor.config);\n";
4367 } else {
4368 echo "\n$editor.generate();\n";
4370 } else {
4371 if (empty($name)) {
4372 echo "\nvar HTML_name = '';";
4373 } else {
4374 echo "\nvar HTML_name = \"$name;\"";
4376 echo "\nvar HTML_editor = $editor;";
4378 echo '//]]>'."\n";
4379 echo '</script>'."\n";
4382 function print_editor_config($editorhidebuttons='', $return=false) {
4383 global $CFG;
4385 $str = "config.pageStyle = \"body {";
4387 if (!(empty($CFG->editorbackgroundcolor))) {
4388 $str .= " background-color: $CFG->editorbackgroundcolor;";
4391 if (!(empty($CFG->editorfontfamily))) {
4392 $str .= " font-family: $CFG->editorfontfamily;";
4395 if (!(empty($CFG->editorfontsize))) {
4396 $str .= " font-size: $CFG->editorfontsize;";
4399 $str .= " }\";\n";
4400 $str .= "config.killWordOnPaste = ";
4401 $str .= (empty($CFG->editorkillword)) ? "false":"true";
4402 $str .= ';'."\n";
4403 $str .= 'config.fontname = {'."\n";
4405 $fontlist = isset($CFG->editorfontlist) ? explode(';', $CFG->editorfontlist) : array();
4406 $i = 1; // Counter is used to get rid of the last comma.
4408 foreach ($fontlist as $fontline) {
4409 if (!empty($fontline)) {
4410 if ($i > 1) {
4411 $str .= ','."\n";
4413 list($fontkey, $fontvalue) = split(':', $fontline);
4414 $str .= '"'. $fontkey ."\":\t'". $fontvalue ."'";
4416 $i++;
4419 $str .= '};';
4421 if (!empty($editorhidebuttons)) {
4422 $str .= "\nconfig.hideSomeButtons(\" ". $editorhidebuttons ." \");\n";
4423 } else if (!empty($CFG->editorhidebuttons)) {
4424 $str .= "\nconfig.hideSomeButtons(\" ". $CFG->editorhidebuttons ." \");\n";
4427 if (!empty($CFG->editorspelling) && !empty($CFG->aspellpath)) {
4428 $str .= print_speller_code($CFG->htmleditor, true);
4431 if ($return) {
4432 return $str;
4434 echo $str;
4438 * Returns a turn edit on/off button for course in a self contained form.
4439 * Used to be an icon, but it's now a simple form button
4441 * @uses $CFG
4442 * @uses $USER
4443 * @param int $courseid The course to update by id as found in 'course' table
4444 * @return string
4446 function update_course_icon($courseid) {
4447 global $CFG, $USER;
4449 if (editcourseallowed($courseid)) {
4450 if (!empty($USER->editing)) {
4451 $string = get_string('turneditingoff');
4452 $edit = '0';
4453 } else {
4454 $string = get_string('turneditingon');
4455 $edit = '1';
4458 return '<form '.$CFG->frametarget.' method="get" action="'.$CFG->wwwroot.'/course/view.php">'.
4459 '<div>'.
4460 '<input type="hidden" name="id" value="'.$courseid.'" />'.
4461 '<input type="hidden" name="edit" value="'.$edit.'" />'.
4462 '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
4463 '<input type="submit" value="'.$string.'" />'.
4464 '</div></form>';
4469 * Returns a little popup menu for switching roles
4471 * @uses $CFG
4472 * @uses $USER
4473 * @param int $courseid The course to update by id as found in 'course' table
4474 * @return string
4476 function switchroles_form($courseid) {
4478 global $CFG, $USER;
4481 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
4482 return '';
4485 if (!empty($USER->switchrole[$context->id])){ // Just a button to return to normal
4486 $options = array();
4487 $options['id'] = $courseid;
4488 $options['sesskey'] = sesskey();
4489 $options['switchrole'] = 0;
4491 return print_single_button($CFG->wwwroot.'/course/view.php', $options,
4492 get_string('switchrolereturn'), 'post', '_self', true);
4495 if (has_capability('moodle/role:switchroles', $context)) {
4496 if (!$roles = get_assignable_roles($context)) {
4497 return ''; // Nothing to show!
4499 // unset default user role - it would not work
4500 unset($roles[$CFG->guestroleid]);
4501 return popup_form($CFG->wwwroot.'/course/view.php?id='.$courseid.'&amp;sesskey='.sesskey().'&amp;switchrole=',
4502 $roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
4505 return '';
4510 * Returns a turn edit on/off button for course in a self contained form.
4511 * Used to be an icon, but it's now a simple form button
4513 * @uses $CFG
4514 * @uses $USER
4515 * @param int $courseid The course to update by id as found in 'course' table
4516 * @return string
4518 function update_mymoodle_icon() {
4520 global $CFG, $USER;
4522 if (!empty($USER->editing)) {
4523 $string = get_string('updatemymoodleoff');
4524 $edit = '0';
4525 } else {
4526 $string = get_string('updatemymoodleon');
4527 $edit = '1';
4530 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
4531 "<div>".
4532 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
4533 "<input type=\"submit\" value=\"$string\" /></div></form>";
4537 * Returns a turn edit on/off button for tag in a self contained form.
4539 * @uses $CFG
4540 * @uses $USER
4541 * @return string
4543 function update_tag_button($tagid) {
4545 global $CFG, $USER;
4547 if (!empty($USER->editing)) {
4548 $string = get_string('turneditingoff');
4549 $edit = '0';
4550 } else {
4551 $string = get_string('turneditingon');
4552 $edit = '1';
4555 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/tag/index.php\">".
4556 "<div>".
4557 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
4558 "<input type=\"hidden\" name=\"id\" value=\"$tagid\" />".
4559 "<input type=\"submit\" value=\"$string\" /></div></form>";
4563 * Prints the editing button on a module "view" page
4565 * @uses $CFG
4566 * @param type description
4567 * @todo Finish documenting this function
4569 function update_module_button($moduleid, $courseid, $string) {
4570 global $CFG, $USER;
4572 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $moduleid))) {
4573 $string = get_string('updatethis', '', $string);
4575 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
4576 "<div>".
4577 "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
4578 "<input type=\"hidden\" name=\"return\" value=\"true\" />".
4579 "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
4580 "<input type=\"submit\" value=\"$string\" /></div></form>";
4581 } else {
4582 return '';
4587 * Prints the editing button on a category page
4589 * @uses $CFG
4590 * @uses $USER
4591 * @param int $categoryid ?
4592 * @return string
4593 * @todo Finish documenting this function
4595 function update_category_button($categoryid) {
4596 global $CFG, $USER;
4598 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_COURSECAT, $categoryid))) {
4599 if (!empty($USER->categoryediting)) {
4600 $string = get_string('turneditingoff');
4601 $edit = 'off';
4602 } else {
4603 $string = get_string('turneditingon');
4604 $edit = 'on';
4607 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/category.php\">".
4608 '<div>'.
4609 "<input type=\"hidden\" name=\"id\" value=\"$categoryid\" />".
4610 "<input type=\"hidden\" name=\"categoryedit\" value=\"$edit\" />".
4611 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
4612 "<input type=\"submit\" value=\"$string\" /></div></form>";
4617 * Prints the editing button on categories listing
4619 * @uses $CFG
4620 * @uses $USER
4621 * @return string
4623 function update_categories_button() {
4624 global $CFG, $USER;
4626 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
4627 if (!empty($USER->categoryediting)) {
4628 $string = get_string('turneditingoff');
4629 $categoryedit = 'off';
4630 } else {
4631 $string = get_string('turneditingon');
4632 $categoryedit = 'on';
4635 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/index.php\">".
4636 '<div>'.
4637 '<input type="hidden" name="categoryedit" value="'. $categoryedit .'" />'.
4638 '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />'.
4639 '<input type="submit" value="'. $string .'" /></div></form>';
4644 * Prints the editing button on search results listing
4645 * For bulk move courses to another category
4648 function update_categories_search_button($search,$page,$perpage) {
4649 global $CFG, $USER;
4651 // not sure if this capability is the best here
4652 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
4653 if (!empty($USER->categoryediting)) {
4654 $string = get_string("turneditingoff");
4655 $edit = "off";
4656 $perpage = 30;
4657 } else {
4658 $string = get_string("turneditingon");
4659 $edit = "on";
4662 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
4663 '<div>'.
4664 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
4665 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
4666 "<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
4667 "<input type=\"hidden\" name=\"page\" value=\"$page\" />".
4668 "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
4669 "<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
4674 * Given a course and a (current) coursemodule
4675 * This function returns a small popup menu with all the
4676 * course activity modules in it, as a navigation menu
4677 * The data is taken from the serialised array stored in
4678 * the course record
4680 * @param course $course A {@link $COURSE} object.
4681 * @param course $cm A {@link $COURSE} object.
4682 * @param string $targetwindow ?
4683 * @return string
4684 * @todo Finish documenting this function
4686 function navmenu($course, $cm=NULL, $targetwindow='self') {
4688 global $CFG, $THEME, $USER;
4690 if (empty($THEME->navmenuwidth)) {
4691 $width = 50;
4692 } else {
4693 $width = $THEME->navmenuwidth;
4696 if ($cm) {
4697 $cm = $cm->id;
4700 if ($course->format == 'weeks') {
4701 $strsection = get_string('week');
4702 } else {
4703 $strsection = get_string('topic');
4705 $strjumpto = get_string('jumpto');
4707 /// Casting $course->modinfo to string prevents one notice when the field is null
4708 if (!$modinfo = unserialize((string)$course->modinfo)) {
4709 return '';
4711 $context = get_context_instance(CONTEXT_COURSE, $course->id);
4713 $section = -1;
4714 $selected = '';
4715 $url = '';
4716 $previousmod = NULL;
4717 $backmod = NULL;
4718 $nextmod = NULL;
4719 $selectmod = NULL;
4720 $logslink = NULL;
4721 $flag = false;
4722 $menu = array();
4723 $menustyle = array();
4725 $sections = get_records('course_sections','course',$course->id,'section','section,visible,summary');
4727 if (!empty($THEME->makenavmenulist)) { /// A hack to produce an XHTML navmenu list for use in themes
4728 $THEME->navmenulist = navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
4731 foreach ($modinfo as $mod) {
4732 if ($mod->mod == 'label') {
4733 continue;
4736 if ($mod->section > $course->numsections) { /// Don't show excess hidden sections
4737 break;
4739 $mod->id = $mod->cm;
4740 $mod->course = $course->id;
4741 if (!groups_course_module_visible($mod)) {
4742 continue;
4745 if ($mod->section > 0 and $section <> $mod->section) {
4746 $thissection = $sections[$mod->section];
4748 if ($thissection->visible or !$course->hiddensections or
4749 has_capability('moodle/course:viewhiddensections', $context)) {
4750 $thissection->summary = strip_tags(format_string($thissection->summary,true));
4751 if ($course->format == 'weeks' or empty($thissection->summary)) {
4752 $menu[] = '--'.$strsection ." ". $mod->section;
4753 } else {
4754 if (strlen($thissection->summary) < ($width-3)) {
4755 $menu[] = '--'.$thissection->summary;
4756 } else {
4757 $menu[] = '--'.substr($thissection->summary, 0, $width).'...';
4763 $section = $mod->section;
4765 //Only add visible or teacher mods to jumpmenu
4766 if ($mod->visible or has_capability('moodle/course:viewhiddenactivities',
4767 get_context_instance(CONTEXT_MODULE, $mod->cm))) {
4768 $url = $mod->mod .'/view.php?id='. $mod->cm;
4769 if ($flag) { // the current mod is the "next" mod
4770 $nextmod = $mod;
4771 $flag = false;
4773 if ($cm == $mod->cm) {
4774 $selected = $url;
4775 $selectmod = $mod;
4776 $backmod = $previousmod;
4777 $flag = true; // set flag so we know to use next mod for "next"
4778 $mod->name = $strjumpto;
4779 $strjumpto = '';
4780 } else {
4781 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
4782 if (strlen($mod->name) > ($width+5)) {
4783 $mod->name = substr($mod->name, 0, $width).'...';
4785 if (!$mod->visible) {
4786 $mod->name = '('.$mod->name.')';
4789 $menu[$url] = $mod->name;
4790 if (empty($THEME->navmenuiconshide)) {
4791 $menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath.'/'.$mod->mod.'/icon.gif);"'; // Unfortunately necessary to do this here
4793 $previousmod = $mod;
4796 //Accessibility: added Alt text, replaced &gt; &lt; with 'silent' character and 'accesshide' text.
4798 if ($selectmod and has_capability('moodle/site:viewreports', $context)) {
4799 $logstext = get_string('alllogs');
4800 $logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
4801 $CFG->frametarget.'onclick="this.target=\''.$CFG->framename.'\';"'.' href="'.
4802 $CFG->wwwroot.'/course/report/log/index.php?chooselog=1&amp;user=0&amp;date=0&amp;id='.
4803 $course->id.'&amp;modid='.$selectmod->cm.'">'.
4804 '<img class="icon log" src="'.$CFG->pixpath.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
4807 if ($backmod) {
4808 $backtext= get_string('activityprev', 'access');
4809 $backmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$backmod->mod.'/view.php" '.
4810 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
4811 '<input type="hidden" name="id" value="'.$backmod->cm.'" />'.
4812 '<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
4813 '</button></fieldset></form></li>';
4815 if ($nextmod) {
4816 $nexttext= get_string('activitynext', 'access');
4817 $nextmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$nextmod->mod.'/view.php" '.
4818 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
4819 '<input type="hidden" name="id" value="'.$nextmod->cm.'" />'.
4820 '<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
4821 '</button></fieldset></form></li>';
4824 return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
4825 '<li>'.popup_form($CFG->wwwroot .'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
4826 '', '', true, $targetwindow, '', $menustyle).'</li>'.
4827 $nextmod . '</ul>'."\n".'</div>';
4831 * Given a course
4832 * This function returns a small popup menu with all the
4833 * course activity modules in it, as a navigation menu
4834 * outputs a simple list structure in XHTML
4835 * The data is taken from the serialised array stored in
4836 * the course record
4838 * @param course $course A {@link $COURSE} object.
4839 * @return string
4840 * @todo Finish documenting this function
4842 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
4844 global $CFG;
4846 $section = -1;
4847 $selected = '';
4848 $url = '';
4849 $previousmod = NULL;
4850 $backmod = NULL;
4851 $nextmod = NULL;
4852 $selectmod = NULL;
4853 $logslink = NULL;
4854 $flag = false;
4855 $menu = array();
4857 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
4859 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
4860 foreach ($modinfo as $mod) {
4861 if ($mod->mod == 'label') {
4862 continue;
4865 if ($mod->section > $course->numsections) { /// Don't show excess hidden sections
4866 break;
4869 if ($mod->section >= 0 and $section <> $mod->section) {
4870 $thissection = $sections[$mod->section];
4872 if ($thissection->visible or !$course->hiddensections or
4873 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
4874 $thissection->summary = strip_tags(format_string($thissection->summary,true));
4875 if (!empty($doneheading)) {
4876 $menu[] = '</ul></li>';
4878 if ($course->format == 'weeks' or empty($thissection->summary)) {
4879 $item = $strsection ." ". $mod->section;
4880 } else {
4881 if (strlen($thissection->summary) < ($width-3)) {
4882 $item = $thissection->summary;
4883 } else {
4884 $item = substr($thissection->summary, 0, $width).'...';
4887 $menu[] = '<li class="section"><span>'.$item.'</span>';
4888 $menu[] = '<ul>';
4889 $doneheading = true;
4893 $section = $mod->section;
4895 //Only add visible or teacher mods to jumpmenu
4896 if ($mod->visible or has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_MODULE, $mod->cm))) {
4897 $url = $mod->mod .'/view.php?id='. $mod->cm;
4898 if ($flag) { // the current mod is the "next" mod
4899 $nextmod = $mod;
4900 $flag = false;
4902 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
4903 if (strlen($mod->name) > ($width+5)) {
4904 $mod->name = substr($mod->name, 0, $width).'...';
4906 if (!$mod->visible) {
4907 $mod->name = '('.$mod->name.')';
4909 $class = 'activity '.$mod->mod;
4910 $class .= ($cmid == $mod->cm) ? ' selected' : '';
4911 $menu[] = '<li class="'.$class.'">'.
4912 '<img src="'.$CFG->modpixpath.'/'.$mod->mod.'/icon.gif" alt="" />'.
4913 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
4914 $previousmod = $mod;
4917 if ($doneheading) {
4918 $menu[] = '</ul></li>';
4920 $menu[] = '</ul></li></ul>';
4922 return implode("\n", $menu);
4926 * Prints form items with the names $day, $month and $year
4928 * @param string $day fieldname
4929 * @param string $month fieldname
4930 * @param string $year fieldname
4931 * @param int $currenttime A default timestamp in GMT
4932 * @param boolean $return
4934 function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
4936 if (!$currenttime) {
4937 $currenttime = time();
4939 $currentdate = usergetdate($currenttime);
4941 for ($i=1; $i<=31; $i++) {
4942 $days[$i] = $i;
4944 for ($i=1; $i<=12; $i++) {
4945 $months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
4947 for ($i=1970; $i<=2020; $i++) {
4948 $years[$i] = $i;
4950 return choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', $return)
4951 .choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', $return)
4952 .choose_from_menu($years, $year, $currentdate['year'], '', '', '0', $return);
4957 *Prints form items with the names $hour and $minute
4959 * @param string $hour fieldname
4960 * @param string ? $minute fieldname
4961 * @param $currenttime A default timestamp in GMT
4962 * @param int $step minute spacing
4963 * @param boolean $return
4965 function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
4967 if (!$currenttime) {
4968 $currenttime = time();
4970 $currentdate = usergetdate($currenttime);
4971 if ($step != 1) {
4972 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
4974 for ($i=0; $i<=23; $i++) {
4975 $hours[$i] = sprintf("%02d",$i);
4977 for ($i=0; $i<=59; $i+=$step) {
4978 $minutes[$i] = sprintf("%02d",$i);
4981 return choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',$return)
4982 .choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',$return);
4986 * Prints time limit value selector
4988 * @uses $CFG
4989 * @param int $timelimit default
4990 * @param string $unit
4991 * @param string $name
4992 * @param boolean $return
4994 function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
4996 global $CFG;
4998 if ($unit) {
4999 $unit = ' '.$unit;
5002 // Max timelimit is sessiontimeout - 10 minutes.
5003 $maxvalue = ($CFG->sessiontimeout / 60) - 10;
5005 for ($i=1; $i<=$maxvalue; $i++) {
5006 $minutes[$i] = $i.$unit;
5008 return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
5012 * Prints a grade menu (as part of an existing form) with help
5013 * Showing all possible numerical grades and scales
5015 * @uses $CFG
5016 * @param int $courseid ?
5017 * @param string $name ?
5018 * @param string $current ?
5019 * @param boolean $includenograde ?
5020 * @todo Finish documenting this function
5022 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
5024 global $CFG;
5026 $output = '';
5027 $strscale = get_string('scale');
5028 $strscales = get_string('scales');
5030 $scales = get_scales_menu($courseid);
5031 foreach ($scales as $i => $scalename) {
5032 $grades[-$i] = $strscale .': '. $scalename;
5034 if ($includenograde) {
5035 $grades[0] = get_string('nograde');
5037 for ($i=100; $i>=1; $i--) {
5038 $grades[$i] = $i;
5040 $output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
5042 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5043 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5044 $linkobject, 400, 500, $strscales, 'none', true);
5046 if ($return) {
5047 return $output;
5048 } else {
5049 echo $output;
5054 * Prints a scale menu (as part of an existing form) including help button
5055 * Just like {@link print_grade_menu()} but without the numeric grades
5057 * @param int $courseid ?
5058 * @param string $name ?
5059 * @param string $current ?
5060 * @todo Finish documenting this function
5062 function print_scale_menu($courseid, $name, $current, $return=false) {
5064 global $CFG;
5066 $output = '';
5067 $strscales = get_string('scales');
5068 $output .= choose_from_menu(get_scales_menu($courseid), $name, $current, '', '', 0, true);
5070 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5071 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5072 $linkobject, 400, 500, $strscales, 'none', true);
5073 if ($return) {
5074 return $output;
5075 } else {
5076 echo $output;
5081 * Prints a help button about a scale
5083 * @uses $CFG
5084 * @param id $courseid ?
5085 * @param object $scale ?
5086 * @todo Finish documenting this function
5088 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
5090 global $CFG;
5092 $output = '';
5093 $strscales = get_string('scales');
5095 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5096 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true&amp;scaleid='. $scale->id, 'ratingscale',
5097 $linkobject, 400, 500, $scale->name, 'none', true);
5098 if ($return) {
5099 return $output;
5100 } else {
5101 echo $output;
5106 * Print an error page displaying an error message.
5107 * Old method, don't call directly in new code - use print_error instead.
5110 * @uses $SESSION
5111 * @uses $CFG
5112 * @param string $message The message to display to the user about the error.
5113 * @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.
5115 function error ($message, $link='') {
5117 global $CFG, $SESSION;
5118 $message = clean_text($message); // In case nasties are in here
5120 if (defined('FULLME') && FULLME == 'cron') {
5121 // Errors in cron should be mtrace'd.
5122 mtrace($message);
5123 die;
5126 if (! defined('HEADER_PRINTED')) {
5127 //header not yet printed
5128 @header('HTTP/1.0 404 Not Found');
5129 print_header(get_string('error'));
5132 echo '<br />';
5133 print_simple_box($message, '', '', '', '', 'errorbox');
5135 debugging('Stack trace:', DEBUG_DEVELOPER);
5137 // in case we are logging upgrade in admin/index.php stop it
5138 if (function_exists('upgrade_log_finish')) {
5139 upgrade_log_finish();
5142 if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
5143 if ( !empty($SESSION->fromurl) ) {
5144 $link = $SESSION->fromurl;
5145 unset($SESSION->fromurl);
5146 } else {
5147 $link = $CFG->wwwroot .'/';
5151 if (!empty($link)) {
5152 print_continue($link);
5155 print_footer();
5157 for ($i=0;$i<512;$i++) { // Padding to help IE work with 404
5158 echo ' ';
5161 die;
5165 * Print an error page displaying an error message. New method - use this for new code.
5167 * @uses $SESSION
5168 * @uses $CFG
5169 * @param string $errorcode The name of the string from error.php to print
5170 * @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.
5171 * @param object $a Extra words and phrases that might be required in the error string
5173 function print_error ($errorcode, $module='', $link='', $a=NULL) {
5175 global $CFG;
5177 if (empty($module) || $module == 'moodle' || $module == 'core') {
5178 $module = 'error';
5179 $modulelink = 'moodle';
5180 } else {
5181 $modulelink = $module;
5184 if (!empty($CFG->errordocroot)) {
5185 $errordocroot = $CFG->errordocroot;
5186 } else if (!empty($CFG->docroot)) {
5187 $errordocroot = $CFG->docroot;
5188 } else {
5189 $errordocroot = 'http://docs.moodle.org';
5192 $message = '<p class="errormessage">'.get_string($errorcode, $module, $a).'</p>'.
5193 '<p class="errorcode">'.
5194 '<a href="'.$errordocroot.'/en/error/'.$modulelink.'/'.$errorcode.'">'.
5195 get_string('moreinformation').'</a></p>';
5196 error($message, $link);
5199 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
5200 * Should be used only with htmleditor or textarea.
5201 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
5202 * helpbutton.
5203 * @return string
5205 function editorhelpbutton(){
5206 global $CFG, $SESSION;
5207 $items = func_get_args();
5208 $i = 1;
5209 $urlparams = array();
5210 $titles = array();
5211 foreach ($items as $item){
5212 if (is_array($item)){
5213 $urlparams[] = "keyword$i=".urlencode($item[0]);
5214 $urlparams[] = "title$i=".urlencode($item[1]);
5215 if (isset($item[2])){
5216 $urlparams[] = "module$i=".urlencode($item[2]);
5218 $titles[] = trim($item[1], ". \t");
5219 }elseif (is_string($item)){
5220 $urlparams[] = "button$i=".urlencode($item);
5221 switch ($item){
5222 case 'reading' :
5223 $titles[] = get_string("helpreading");
5224 break;
5225 case 'writing' :
5226 $titles[] = get_string("helpwriting");
5227 break;
5228 case 'questions' :
5229 $titles[] = get_string("helpquestions");
5230 break;
5231 case 'emoticons' :
5232 $titles[] = get_string("helpemoticons");
5233 break;
5234 case 'richtext' :
5235 $titles[] = get_string('helprichtext');
5236 break;
5237 case 'text' :
5238 $titles[] = get_string('helptext');
5239 break;
5240 default :
5241 error('Unknown help topic '.$item);
5244 $i++;
5246 if (count($titles)>1){
5247 //join last two items with an 'and'
5248 $a = new object();
5249 $a->one = $titles[count($titles) - 2];
5250 $a->two = $titles[count($titles) - 1];
5251 $titles[count($titles) - 2] = get_string('and', '', $a);
5252 unset($titles[count($titles) - 1]);
5254 $alttag = join (', ', $titles);
5256 $paramstring = join('&', $urlparams);
5257 $linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath .'/help.gif" />';
5258 return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), $alttag, $linkobject, 400, 500, $alttag, 'none', true);
5262 * Print a help button.
5264 * @uses $CFG
5265 * @param string $page The keyword that defines a help page
5266 * @param string $title The title of links, rollover tips, alt tags etc
5267 * 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
5268 * @param string $module Which module is the page defined in
5269 * @param mixed $image Use a help image for the link? (true/false/"both")
5270 * @param boolean $linktext If true, display the title next to the help icon.
5271 * @param string $text If defined then this text is used in the page, and
5272 * the $page variable is ignored.
5273 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
5274 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
5275 * @return string
5276 * @todo Finish documenting this function
5278 function helpbutton ($page, $title='', $module='moodle', $image=true, $linktext=false, $text='', $return=false,
5279 $imagetext='') {
5280 global $CFG, $course;
5282 // fix for MDL-7734
5283 if (!empty($course->lang)) {
5284 $forcelang = $course->lang;
5285 } else {
5286 $forcelang = '';
5289 if ($module == '') {
5290 $module = 'moodle';
5293 $tooltip = get_string('helpprefix2', '', trim($title, ". \t"));
5295 $linkobject = '';
5297 if ($image) {
5298 if ($linktext) {
5299 // MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
5300 $linkobject .= $title.'&nbsp;';
5301 $tooltip = get_string('helpwiththis');
5303 if ($imagetext) {
5304 $linkobject .= $imagetext;
5305 } else {
5306 $linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
5307 $CFG->pixpath .'/help.gif" />';
5309 } else {
5310 $linkobject .= $tooltip;
5313 $tooltip .= ' ('.get_string('newwindow').')'; // Warn users about new window for Accessibility
5315 // fix for MDL-7734
5316 if ($text) {
5317 $url = '/help.php?module='. $module .'&amp;text='. s(urlencode($text).'&amp;forcelang='.$forcelang);
5318 } else {
5319 $url = '/help.php?module='. $module .'&amp;file='. $page .'.html&amp;forcelang='.$forcelang;
5322 $link = '<span class="helplink">'.
5323 link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
5324 '</span>';
5326 if ($return) {
5327 return $link;
5328 } else {
5329 echo $link;
5334 * Print a help button.
5336 * Prints a special help button that is a link to the "live" emoticon popup
5337 * @uses $CFG
5338 * @uses $SESSION
5339 * @param string $form ?
5340 * @param string $field ?
5341 * @todo Finish documenting this function
5343 function emoticonhelpbutton($form, $field, $return = false) {
5345 global $CFG, $SESSION;
5347 $SESSION->inserttextform = $form;
5348 $SESSION->inserttextfield = $field;
5349 $imagetext = '<img src="' . $CFG->pixpath . '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
5350 $help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
5351 if (!$return){
5352 echo $help;
5353 } else {
5354 return $help;
5359 * Print a help button.
5361 * Prints a special help button for html editors (htmlarea in this case)
5362 * @uses $CFG
5364 function editorshortcutshelpbutton() {
5366 global $CFG;
5367 $imagetext = '<img src="' . $CFG->httpswwwroot . '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
5368 get_string('editorshortcutkeys').'" class="iconkbhelp" />';
5370 return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
5374 * Print a message and exit.
5376 * @uses $CFG
5377 * @param string $message ?
5378 * @param string $link ?
5379 * @todo Finish documenting this function
5381 function notice ($message, $link='', $course=NULL) {
5382 global $CFG, $SITE;
5384 $message = clean_text($message);
5386 print_box($message, 'generalbox', 'notice');
5387 print_continue($link);
5389 if (empty($course)) {
5390 print_footer($SITE);
5391 } else {
5392 print_footer($course);
5394 exit;
5398 * Print a message along with "Yes" and "No" links for the user to continue.
5400 * @param string $message The text to display
5401 * @param string $linkyes The link to take the user to if they choose "Yes"
5402 * @param string $linkno The link to take the user to if they choose "No"
5403 * TODO Document remaining arguments
5405 function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
5407 global $CFG;
5409 $message = clean_text($message);
5410 $linkyes = clean_text($linkyes);
5411 $linkno = clean_text($linkno);
5413 print_box_start('generalbox', 'notice');
5414 echo '<p>'. $message .'</p>';
5415 echo '<div class="buttons">';
5416 print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename);
5417 print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename);
5418 echo '</div>';
5419 print_box_end();
5423 * Provide an definition of error_get_last for PHP before 5.2.0. This simply
5424 * returns NULL, since there is not way to get the right answer.
5426 if (!function_exists('error_get_last')) {
5427 // the eval is needed to prevent PHP 5.2+ from getting a parse error!
5428 eval('
5429 function error_get_last() {
5430 return NULL;
5436 * Redirects the user to another page, after printing a notice
5438 * @param string $url The url to take the user to
5439 * @param string $message The text message to display to the user about the redirect, if any
5440 * @param string $delay How long before refreshing to the new page at $url?
5441 * @todo '&' needs to be encoded into '&amp;' for XHTML compliance,
5442 * however, this is not true for javascript. Therefore we
5443 * first decode all entities in $url (since we cannot rely on)
5444 * the correct input) and then encode for where it's needed
5445 * echo "<script type='text/javascript'>alert('Redirect $url');</script>";
5447 function redirect($url, $message='', $delay=-1) {
5449 global $CFG;
5451 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
5452 $url = sid_process_url($url);
5455 $message = clean_text($message);
5457 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
5458 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
5459 $url = str_replace('&amp;', '&', $encodedurl);
5461 /// At developer debug level. Don't redirect if errors have been printed on screen.
5462 /// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
5463 $lasterror = error_get_last();
5464 $error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER));
5465 $errorprinted = debugging('', DEBUG_ALL) && $CFG->debugdisplay && $error;
5466 if ($errorprinted) {
5467 $message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
5470 /// when no message and header printed yet, try to redirect
5471 if (empty($message) and !defined('HEADER_PRINTED')) {
5473 // Technically, HTTP/1.1 requires Location: header to contain
5474 // the absolute path. (In practice browsers accept relative
5475 // paths - but still, might as well do it properly.)
5476 // This code turns relative into absolute.
5477 if (!preg_match('|^[a-z]+:|', $url)) {
5478 // Get host name http://www.wherever.com
5479 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
5480 if (preg_match('|^/|', $url)) {
5481 // URLs beginning with / are relative to web server root so we just add them in
5482 $url = $hostpart.$url;
5483 } else {
5484 // URLs not beginning with / are relative to path of current script, so add that on.
5485 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
5487 // Replace all ..s
5488 while (true) {
5489 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
5490 if ($newurl == $url) {
5491 break;
5493 $url = $newurl;
5497 $delay = 0;
5498 //try header redirection first
5499 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
5500 @header('Location: '.$url);
5501 //another way for older browsers and already sent headers (eg trailing whitespace in config.php)
5502 echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
5503 echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
5504 die;
5507 if ($delay == -1) {
5508 $delay = 3; // if no delay specified wait 3 seconds
5510 if (! defined('HEADER_PRINTED')) {
5511 // this type of redirect might not be working in some browsers - such as lynx :-(
5512 print_header('', '', '', '', $errorprinted ? '' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
5513 $delay += 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
5515 echo '<div style="text-align:center">';
5516 echo '<div>'. $message .'</div>';
5517 echo '<div>( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
5518 echo '</div>';
5520 if (!$errorprinted) {
5522 <script type="text/javascript">
5523 //<![CDATA[
5525 function redirect() {
5526 document.location.replace('<?php echo addslashes_js($url) ?>');
5528 setTimeout("redirect()", <?php echo ($delay * 1000) ?>);
5529 //]]>
5530 </script>
5531 <?php
5534 print_footer('none');
5535 die;
5539 * Print a bold message in an optional color.
5541 * @param string $message The message to print out
5542 * @param string $style Optional style to display message text in
5543 * @param string $align Alignment option
5544 * @param bool $return whether to return an output string or echo now
5546 function notify($message, $style='notifyproblem', $align='center', $return=false) {
5547 if ($style == 'green') {
5548 $style = 'notifysuccess'; // backward compatible with old color system
5551 $message = clean_text($message);
5553 $output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."\n";
5555 if ($return) {
5556 return $output;
5558 echo $output;
5563 * Given an email address, this function will return an obfuscated version of it
5565 * @param string $email The email address to obfuscate
5566 * @return string
5568 function obfuscate_email($email) {
5570 $i = 0;
5571 $length = strlen($email);
5572 $obfuscated = '';
5573 while ($i < $length) {
5574 if (rand(0,2)) {
5575 $obfuscated.='%'.dechex(ord($email{$i}));
5576 } else {
5577 $obfuscated.=$email{$i};
5579 $i++;
5581 return $obfuscated;
5585 * This function takes some text and replaces about half of the characters
5586 * with HTML entity equivalents. Return string is obviously longer.
5588 * @param string $plaintext The text to be obfuscated
5589 * @return string
5591 function obfuscate_text($plaintext) {
5593 $i=0;
5594 $length = strlen($plaintext);
5595 $obfuscated='';
5596 $prev_obfuscated = false;
5597 while ($i < $length) {
5598 $c = ord($plaintext{$i});
5599 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
5600 if ($prev_obfuscated and $numerical ) {
5601 $obfuscated.='&#'.ord($plaintext{$i}).';';
5602 } else if (rand(0,2)) {
5603 $obfuscated.='&#'.ord($plaintext{$i}).';';
5604 $prev_obfuscated = true;
5605 } else {
5606 $obfuscated.=$plaintext{$i};
5607 $prev_obfuscated = false;
5609 $i++;
5611 return $obfuscated;
5615 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
5616 * to generate a fully obfuscated email link, ready to use.
5618 * @param string $email The email address to display
5619 * @param string $label The text to dispalyed as hyperlink to $email
5620 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
5621 * @return string
5623 function obfuscate_mailto($email, $label='', $dimmed=false) {
5625 if (empty($label)) {
5626 $label = $email;
5628 if ($dimmed) {
5629 $title = get_string('emaildisable');
5630 $dimmed = ' class="dimmed"';
5631 } else {
5632 $title = '';
5633 $dimmed = '';
5635 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
5636 obfuscate_text('mailto'), obfuscate_email($email),
5637 obfuscate_text($label));
5641 * Prints a single paging bar to provide access to other pages (usually in a search)
5643 * @param int $totalcount Thetotal number of entries available to be paged through
5644 * @param int $page The page you are currently viewing
5645 * @param int $perpage The number of entries that should be shown per page
5646 * @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.
5647 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
5648 * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
5649 * @param bool $nocurr do not display the current page as a link
5650 * @param bool $return whether to return an output string or echo now
5651 * @return bool or string
5653 function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
5654 $maxdisplay = 18;
5655 $output = '';
5657 if ($totalcount > $perpage) {
5658 $output .= '<div class="paging">';
5659 $output .= get_string('page') .':';
5660 if ($page > 0) {
5661 $pagenum = $page - 1;
5662 if (!is_a($baseurl, 'moodle_url')){
5663 $output .= '&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>)&nbsp;';
5664 } else {
5665 $output .= '&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>)&nbsp;';
5668 if ($perpage > 0) {
5669 $lastpage = ceil($totalcount / $perpage);
5670 } else {
5671 $lastpage = 1;
5673 if ($page > 15) {
5674 $startpage = $page - 10;
5675 if (!is_a($baseurl, 'moodle_url')){
5676 $output .= '&nbsp;<a href="'. $baseurl . $pagevar .'=0">1</a>&nbsp;...';
5677 } else {
5678 $output .= '&nbsp;<a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a>&nbsp;...';
5680 } else {
5681 $startpage = 0;
5683 $currpage = $startpage;
5684 $displaycount = 0;
5685 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
5686 $displaypage = $currpage+1;
5687 if ($page == $currpage && empty($nocurr)) {
5688 $output .= '&nbsp;&nbsp;'. $displaypage;
5689 } else {
5690 if (!is_a($baseurl, 'moodle_url')){
5691 $output .= '&nbsp;&nbsp;<a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
5692 } else {
5693 $output .= '&nbsp;&nbsp;<a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
5697 $displaycount++;
5698 $currpage++;
5700 if ($currpage < $lastpage) {
5701 $lastpageactual = $lastpage - 1;
5702 if (!is_a($baseurl, 'moodle_url')){
5703 $output .= '&nbsp;...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a>&nbsp;';
5704 } else {
5705 $output .= '&nbsp;...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a>&nbsp;';
5708 $pagenum = $page + 1;
5709 if ($pagenum != $displaypage) {
5710 if (!is_a($baseurl, 'moodle_url')){
5711 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
5712 } else {
5713 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
5716 $output .= '</div>';
5719 if ($return) {
5720 return $output;
5723 echo $output;
5724 return true;
5728 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
5729 * will transform it to html entities
5731 * @param string $text Text to search for nolink tag in
5732 * @return string
5734 function rebuildnolinktag($text) {
5736 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
5738 return $text;
5742 * Prints a nice side block with an optional header. The content can either
5743 * be a block of HTML or a list of text with optional icons.
5745 * @param string $heading Block $title embedded in HTML tags, for example <h2>.
5746 * @param string $content ?
5747 * @param array $list ?
5748 * @param array $icons ?
5749 * @param string $footer ?
5750 * @param array $attributes ?
5751 * @param string $title Plain text title, as embedded in the $heading.
5752 * @todo Finish documenting this function. Show example of various attributes, etc.
5754 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
5756 //Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
5757 static $block_id = 0;
5758 $block_id++;
5759 if (empty($heading)) {
5760 $skip_text = get_string('skipblock', 'access').' '.$block_id;
5762 else {
5763 $skip_text = get_string('skipa', 'access', strip_tags($title));
5765 $skip_link = '<a href="#sb-'.$block_id.'" class="skip-block" title="'.$skip_text.'">'."\n".'<span class="accesshide">'.$skip_text.'</span>'."\n".'</a>';
5766 $skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
5768 if (! empty($heading)) {
5769 $heading = $skip_link . $heading;
5771 /*else { //ELSE: I think a single link on a page, "Skip block 4" is too confusing - don't print.
5772 echo $skip_link;
5775 print_side_block_start($heading, $attributes);
5777 if ($content) {
5778 echo $content;
5779 if ($footer) {
5780 echo '<div class="footer">'. $footer .'</div>';
5782 } else {
5783 if ($list) {
5784 $row = 0;
5785 //Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
5786 echo "\n<ul class='list'>\n";
5787 foreach ($list as $key => $string) {
5788 echo '<li class="r'. $row .'">';
5789 if ($icons) {
5790 echo '<div class="icon column c0">'. $icons[$key] .'</div>';
5792 echo '<div class="column c1">'. $string .'</div>';
5793 echo "</li>\n";
5794 $row = $row ? 0:1;
5796 echo "</ul>\n";
5798 if ($footer) {
5799 echo '<div class="footer">'. $footer .'</div>';
5804 print_side_block_end($attributes);
5805 echo $skip_dest;
5809 * Starts a nice side block with an optional header.
5811 * @param string $heading ?
5812 * @param array $attributes ?
5813 * @todo Finish documenting this function
5815 function print_side_block_start($heading='', $attributes = array()) {
5817 global $CFG, $THEME;
5819 if (!empty($THEME->customcorners)) {
5820 require_once($CFG->dirroot.'/lib/custom_corners_lib.php');
5823 // If there are no special attributes, give a default CSS class
5824 if (empty($attributes) || !is_array($attributes)) {
5825 $attributes = array('class' => 'sideblock');
5827 } else if(!isset($attributes['class'])) {
5828 $attributes['class'] = 'sideblock';
5830 } else if(!strpos($attributes['class'], 'sideblock')) {
5831 $attributes['class'] .= ' sideblock';
5834 // OK, the class is surely there and in addition to anything
5835 // else, it's tagged as a sideblock
5839 // IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
5841 // If there is a cookie to hide this thing, start it hidden
5842 if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
5843 $attributes['class'] = 'hidden '.$attributes['class'];
5847 $attrtext = '';
5848 foreach ($attributes as $attr => $val) {
5849 $attrtext .= ' '.$attr.'="'.$val.'"';
5852 echo '<div '.$attrtext.'>';
5854 if (!empty($THEME->customcorners)) {
5855 echo '<div class="wrap">'."\n";
5857 if ($heading) {
5858 //Accessibility: replaced <div> with H2; no, H2 more appropriate in moodleblock.class.php: _title_html.
5859 // echo '<div class="header">'.$heading.'</div>';
5860 echo '<div class="header">';
5861 if (!empty($THEME->customcorners)) {
5862 echo '<div class="bt"><div>&nbsp;</div></div>';
5863 echo '<div class="i1"><div class="i2">';
5864 echo '<div class="i3">';
5866 echo $heading;
5867 if (!empty($THEME->customcorners)) {
5868 echo '</div></div></div>';
5870 echo '</div>';
5871 } else {
5872 if (!empty($THEME->customcorners)) {
5873 echo '<div class="bt"><div>&nbsp;</div></div>';
5877 if (!empty($THEME->customcorners)) {
5878 echo '<div class="i1"><div class="i2">';
5879 echo '<div class="i3">';
5881 echo '<div class="content">';
5887 * Print table ending tags for a side block box.
5889 function print_side_block_end($attributes = array()) {
5890 global $CFG, $THEME;
5892 echo '</div>';
5894 if (!empty($THEME->customcorners)) {
5895 require_once($CFG->dirroot.'/lib/custom_corners_lib.php');
5896 print_custom_corners_end();
5899 echo '</div>';
5901 // IE workaround: if I do it THIS way, it works! WTF?
5902 if (!empty($CFG->allowuserblockhiding) && isset($attributes['id'])) {
5903 echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].'"); '.
5904 "\n//]]>\n".'</script>';
5911 * Prints out code needed for spellchecking.
5912 * Original idea by Ludo (Marc Alier).
5914 * Opening CDATA and <script> are output by weblib::use_html_editor()
5915 * @uses $CFG
5916 * @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
5917 * @param boolean $return If false, echos the code instead of returning it
5918 * @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
5920 function print_speller_code ($usehtmleditor=false, $return=false) {
5921 global $CFG;
5922 $str = '';
5924 if(!$usehtmleditor) {
5925 $str .= 'function openSpellChecker() {'."\n";
5926 $str .= "\tvar speller = new spellChecker();\n";
5927 $str .= "\tspeller.popUpUrl = \"" . $CFG->wwwroot ."/lib/speller/spellchecker.html\";\n";
5928 $str .= "\tspeller.spellCheckScript = \"". $CFG->wwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
5929 $str .= "\tspeller.spellCheckAll();\n";
5930 $str .= '}'."\n";
5931 } else {
5932 $str .= "function spellClickHandler(editor, buttonId) {\n";
5933 $str .= "\teditor._textArea.value = editor.getHTML();\n";
5934 $str .= "\tvar speller = new spellChecker( editor._textArea );\n";
5935 $str .= "\tspeller.popUpUrl = \"" . $CFG->wwwroot ."/lib/speller/spellchecker.html\";\n";
5936 $str .= "\tspeller.spellCheckScript = \"". $CFG->wwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
5937 $str .= "\tspeller._moogle_edit=1;\n";
5938 $str .= "\tspeller._editor=editor;\n";
5939 $str .= "\tspeller.openChecker();\n";
5940 $str .= '}'."\n";
5943 if ($return) {
5944 return $str;
5946 echo $str;
5950 * Print button for spellchecking when editor is disabled
5952 function print_speller_button () {
5953 echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
5957 function page_id_and_class(&$getid, &$getclass) {
5958 // Create class and id for this page
5959 global $CFG, $ME;
5961 static $class = NULL;
5962 static $id = NULL;
5964 if (empty($CFG->pagepath)) {
5965 $CFG->pagepath = $ME;
5968 if (empty($class) || empty($id)) {
5969 $path = str_replace($CFG->httpswwwroot.'/', '', $CFG->pagepath); //Because the page could be HTTPSPAGEREQUIRED
5970 $path = str_replace('.php', '', $path);
5971 if (substr($path, -1) == '/') {
5972 $path .= 'index';
5974 if (empty($path) || $path == 'index') {
5975 $id = 'site-index';
5976 $class = 'course';
5977 } else if (substr($path, 0, 5) == 'admin') {
5978 $id = str_replace('/', '-', $path);
5979 $class = 'admin';
5980 } else {
5981 $id = str_replace('/', '-', $path);
5982 $class = explode('-', $id);
5983 array_pop($class);
5984 $class = implode('-', $class);
5988 $getid = $id;
5989 $getclass = $class;
5993 * Prints a maintenance message from /maintenance.html
5995 function print_maintenance_message () {
5996 global $CFG, $SITE;
5998 print_header(strip_tags($SITE->fullname), $SITE->fullname, 'home');
5999 print_simple_box_start('center');
6000 print_heading(get_string('sitemaintenance', 'admin'));
6001 @include($CFG->dataroot.'/1/maintenance.html');
6002 print_simple_box_end();
6003 print_footer();
6007 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
6009 function adjust_allowed_tags() {
6011 global $CFG, $ALLOWED_TAGS;
6013 if (!empty($CFG->allowobjectembed)) {
6014 $ALLOWED_TAGS .= '<embed><object>';
6018 /// Some code to print tabs
6020 /// A class for tabs
6021 class tabobject {
6022 var $id;
6023 var $link;
6024 var $text;
6025 var $linkedwhenselected;
6027 /// A constructor just because I like constructors
6028 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
6029 $this->id = $id;
6030 $this->link = $link;
6031 $this->text = $text;
6032 $this->title = $title ? $title : $text;
6033 $this->linkedwhenselected = $linkedwhenselected;
6040 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
6042 * @param array $tabrows An array of rows where each row is an array of tab objects
6043 * @param string $selected The id of the selected tab (whatever row it's on)
6044 * @param array $inactive An array of ids of inactive tabs that are not selectable.
6045 * @param array $activated An array of ids of other tabs that are currently activated
6047 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
6048 global $CFG;
6050 /// $inactive must be an array
6051 if (!is_array($inactive)) {
6052 $inactive = array();
6055 /// $activated must be an array
6056 if (!is_array($activated)) {
6057 $activated = array();
6060 /// Convert the tab rows into a tree that's easier to process
6061 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
6062 return false;
6065 /// Print out the current tree of tabs (this function is recursive)
6067 $output = convert_tree_to_html($tree);
6069 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
6071 /// We're done!
6073 if ($return) {
6074 return $output;
6076 echo $output;
6080 function convert_tree_to_html($tree, $row=0) {
6082 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
6084 $first = true;
6085 $count = count($tree);
6087 foreach ($tree as $tab) {
6088 $count--; // countdown to zero
6090 $liclass = '';
6092 if ($first && ($count == 0)) { // Just one in the row
6093 $liclass = 'first last';
6094 $first = false;
6095 } else if ($first) {
6096 $liclass = 'first';
6097 $first = false;
6098 } else if ($count == 0) {
6099 $liclass = 'last';
6102 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
6103 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
6106 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
6107 if ($tab->selected) {
6108 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
6109 } else if ($tab->active) {
6110 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
6114 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
6116 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
6117 $str .= '<a href="#" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
6118 } else {
6119 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
6122 if (!empty($tab->subtree)) {
6123 $str .= convert_tree_to_html($tab->subtree, $row+1);
6124 } else if ($tab->selected) {
6125 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
6128 $str .= ' </li>'."\n";
6130 $str .= '</ul>'."\n";
6132 return $str;
6136 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
6138 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
6140 $tabrows = array_reverse($tabrows);
6142 $subtree = array();
6144 foreach ($tabrows as $row) {
6145 $tree = array();
6147 foreach ($row as $tab) {
6148 $tab->inactive = in_array((string)$tab->id, $inactive);
6149 $tab->active = in_array((string)$tab->id, $activated);
6150 $tab->selected = (string)$tab->id == $selected;
6152 if ($tab->active || $tab->selected) {
6153 if ($subtree) {
6154 $tab->subtree = $subtree;
6157 $tree[] = $tab;
6159 $subtree = $tree;
6162 return $subtree;
6167 * Returns a string containing a link to the user documentation for the current
6168 * page. Also contains an icon by default. Shown to teachers and admin only.
6170 * @param string $text The text to be displayed for the link
6171 * @param string $iconpath The path to the icon to be displayed
6173 function page_doc_link($text='', $iconpath='') {
6174 global $ME, $COURSE, $CFG;
6176 if (empty($CFG->docroot)) {
6177 return '';
6180 if (empty($COURSE->id)) {
6181 $context = get_context_instance(CONTEXT_SYSTEM);
6182 } else {
6183 $context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
6186 if (!has_capability('moodle/site:doclinks', $context)) {
6187 return '';
6190 if (empty($CFG->pagepath)) {
6191 $CFG->pagepath = $ME;
6194 $path = str_replace($CFG->httpswwwroot.'/','', $CFG->pagepath); // Because the page could be HTTPSPAGEREQUIRED
6195 $path = str_replace('.php', '', $path);
6197 if (empty($path)) { // Not for home page
6198 return '';
6200 return doc_link($path, $text, $iconpath);
6204 * Returns a string containing a link to the user documentation.
6205 * Also contains an icon by default. Shown to teachers and admin only.
6207 * @param string $path The page link after doc root and language, no
6208 * leading slash.
6209 * @param string $text The text to be displayed for the link
6210 * @param string $iconpath The path to the icon to be displayed
6212 function doc_link($path='', $text='', $iconpath='') {
6213 global $CFG;
6215 if (empty($CFG->docroot)) {
6216 return '';
6219 $target = '';
6220 if (!empty($CFG->doctonewwindow)) {
6221 $target = ' target="_blank"';
6224 $lang = str_replace('_utf8', '', current_language());
6226 $str = '<a href="' .$CFG->docroot. '/' .$lang. '/' .$path. '"' .$target. '>';
6228 if (empty($iconpath)) {
6229 $iconpath = $CFG->httpswwwroot . '/pix/docs.gif';
6232 // alt left blank intentionally to prevent repetition in screenreaders
6233 $str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
6235 return $str;
6240 * Returns true if the current site debugging settings are equal or above specified level.
6241 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
6242 * routing of notices is controlled by $CFG->debugdisplay
6243 * eg use like this:
6245 * 1) debugging('a normal debug notice');
6246 * 2) debugging('something really picky', DEBUG_ALL);
6247 * 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
6248 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
6250 * In code blocks controlled by debugging() (such as example 4)
6251 * any output should be routed via debugging() itself, or the lower-level
6252 * trigger_error() or error_log(). Using echo or print will break XHTML
6253 * JS and HTTP headers.
6256 * @param string $message a message to print
6257 * @param int $level the level at which this debugging statement should show
6258 * @return bool
6260 function debugging($message='', $level=DEBUG_NORMAL) {
6262 global $CFG;
6264 if (empty($CFG->debug)) {
6265 return false;
6268 if ($CFG->debug >= $level) {
6269 if ($message) {
6270 $callers = debug_backtrace();
6271 $from = '<ul style="text-align: left">';
6272 foreach ($callers as $caller) {
6273 if (!isset($caller['line'])) {
6274 $caller['line'] = '?'; // probably call_user_func()
6276 if (!isset($caller['file'])) {
6277 $caller['file'] = $CFG->dirroot.'/unknownfile'; // probably call_user_func()
6279 $from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
6280 if (isset($caller['function'])) {
6281 $from .= ': call to ';
6282 if (isset($caller['class'])) {
6283 $from .= $caller['class'] . $caller['type'];
6285 $from .= $caller['function'] . '()';
6287 $from .= '</li>';
6289 $from .= '</ul>';
6290 if (!isset($CFG->debugdisplay)) {
6291 $CFG->debugdisplay = ini_get('display_errors');
6293 if ($CFG->debugdisplay) {
6294 if (!defined('DEBUGGING_PRINTED')) {
6295 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
6297 notify($message . $from, 'notifytiny');
6298 } else {
6299 trigger_error($message . $from, E_USER_NOTICE);
6302 return true;
6304 return false;
6308 * Disable debug messages from debugging(), while keeping PHP error reporting level as is.
6310 function disable_debugging() {
6311 global $CFG;
6312 $CFG->debug = $CFG->debug | 0x80000000; // switch the sign bit in integer number ;-)
6317 * Returns string to add a frame attribute, if required
6319 function frametarget() {
6320 global $CFG;
6322 if (empty($CFG->framename) or ($CFG->framename == '_top')) {
6323 return '';
6324 } else {
6325 return ' target="'.$CFG->framename.'" ';
6330 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
6331 * pages that use bits from many different files in very confusing ways (e.g. blocks).
6332 * @usage print_location_comment(__FILE__, __LINE__);
6333 * @param string $file
6334 * @param integer $line
6335 * @param boolean $return Whether to return or print the comment
6336 * @return mixed Void unless true given as third parameter
6338 function print_location_comment($file, $line, $return = false)
6340 if ($return) {
6341 return "<!-- $file at line $line -->\n";
6342 } else {
6343 echo "<!-- $file at line $line -->\n";
6349 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
6350 * provide this function with the language strings for sortasc and sortdesc.
6351 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
6352 * @param string $direction 'up' or 'down'
6353 * @param string $strsort The language string used for the alt attribute of this image
6354 * @param bool $return Whether to print directly or return the html string
6355 * @return string HTML for the image
6357 * TODO See if this isn't already defined somewhere. If not, move this to weblib
6359 function print_arrow($direction='up', $strsort=null, $return=false) {
6360 global $CFG;
6362 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
6363 return null;
6366 $return = null;
6368 switch ($direction) {
6369 case 'up':
6370 $sortdir = 'asc';
6371 break;
6372 case 'down':
6373 $sortdir = 'desc';
6374 break;
6375 case 'move':
6376 $sortdir = 'asc';
6377 break;
6378 default:
6379 $sortdir = null;
6380 break;
6383 // Prepare language string
6384 $strsort = '';
6385 if (empty($strsort) && !empty($sortdir)) {
6386 $strsort = get_string('sort' . $sortdir, 'grades');
6389 $return = ' <img src="'.$CFG->pixpath.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
6391 if ($return) {
6392 return $return;
6393 } else {
6394 echo $return;
6399 * Returns boolean true if the current language is right-to-left (Hebrew, Arabic etc)
6402 function right_to_left() {
6403 static $result;
6405 if (isset($result)) {
6406 return $result;
6408 return $result = (get_string('thisdirection') == 'rtl');
6413 * Returns swapped left<=>right if in RTL environment.
6414 * part of RTL support
6416 * @param string $align align to check
6417 * @return string
6419 function fix_align_rtl($align) {
6420 if (!right_to_left()) {
6421 return $align;
6423 if ($align=='left') { return 'right'; }
6424 if ($align=='right') { return 'left'; }
6425 return $align;
6429 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: