MDL-15476
[moodle-linuxchix.git] / lib / weblib.php
blob389488e9fdefde1b52b9609b6e4ed3537a2ca08d
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) 1999 onwards 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 * Javascript related defines
86 define('REQUIREJS_BEFOREHEADER', 0);
87 define('REQUIREJS_INHEADER', 1);
88 define('REQUIREJS_AFTERHEADER', 2);
90 /**
91 * Allowed tags - string of html tags that can be tested against for safe html tags
92 * @global string $ALLOWED_TAGS
94 global $ALLOWED_TAGS;
95 $ALLOWED_TAGS =
96 '<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>';
98 /**
99 * Allowed protocols - array of protocols that are safe to use in links and so on
100 * @global string $ALLOWED_PROTOCOLS
102 $ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms',
103 'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style',
104 'border', 'margin', 'padding', 'background', 'text-decoration'); // CSS as well to get through kses
107 /// Functions
110 * Add quotes to HTML characters
112 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
113 * This function is very similar to {@link p()}
115 * @param string $var the string potentially containing HTML characters
116 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
117 * true should be used to print data from forms and false for data from DB.
118 * @return string
120 function s($var, $strip=false) {
122 if ($var == '0') { // for integer 0, boolean false, string '0'
123 return '0';
126 if ($strip) {
127 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars(stripslashes_safe($var)));
128 } else {
129 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars($var));
134 * Add quotes to HTML characters
136 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
137 * This function is very similar to {@link s()}
139 * @param string $var the string potentially containing HTML characters
140 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
141 * true should be used to print data from forms and false for data from DB.
142 * @return string
144 function p($var, $strip=false) {
145 echo s($var, $strip);
149 * Does proper javascript quoting.
150 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
152 * @since 1.8 - 22/02/2007
153 * @param mixed value
154 * @return mixed quoted result
156 function addslashes_js($var) {
157 if (is_string($var)) {
158 $var = str_replace('\\', '\\\\', $var);
159 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
160 $var = str_replace('</', '<\/', $var); // XHTML compliance
161 } else if (is_array($var)) {
162 $var = array_map('addslashes_js', $var);
163 } else if (is_object($var)) {
164 $a = get_object_vars($var);
165 foreach ($a as $key=>$value) {
166 $a[$key] = addslashes_js($value);
168 $var = (object)$a;
170 return $var;
174 * Remove query string from url
176 * Takes in a URL and returns it without the querystring portion
178 * @param string $url the url which may have a query string attached
179 * @return string
181 function strip_querystring($url) {
183 if ($commapos = strpos($url, '?')) {
184 return substr($url, 0, $commapos);
185 } else {
186 return $url;
191 * Returns the URL of the HTTP_REFERER, less the querystring portion if required
192 * @param boolean $stripquery if true, also removes the query part of the url.
193 * @return string
195 function get_referer($stripquery=true) {
196 if (isset($_SERVER['HTTP_REFERER'])) {
197 if ($stripquery) {
198 return strip_querystring($_SERVER['HTTP_REFERER']);
199 } else {
200 return $_SERVER['HTTP_REFERER'];
202 } else {
203 return '';
209 * Returns the name of the current script, WITH the querystring portion.
210 * this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
211 * return different things depending on a lot of things like your OS, Web
212 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
213 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
215 * @return string
217 function me() {
219 if (!empty($_SERVER['REQUEST_URI'])) {
220 return $_SERVER['REQUEST_URI'];
222 } else if (!empty($_SERVER['PHP_SELF'])) {
223 if (!empty($_SERVER['QUERY_STRING'])) {
224 return $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
226 return $_SERVER['PHP_SELF'];
228 } else if (!empty($_SERVER['SCRIPT_NAME'])) {
229 if (!empty($_SERVER['QUERY_STRING'])) {
230 return $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
232 return $_SERVER['SCRIPT_NAME'];
234 } else if (!empty($_SERVER['URL'])) { // May help IIS (not well tested)
235 if (!empty($_SERVER['QUERY_STRING'])) {
236 return $_SERVER['URL'] .'?'. $_SERVER['QUERY_STRING'];
238 return $_SERVER['URL'];
240 } else {
241 notify('Warning: Could not find any of these web server variables: $REQUEST_URI, $PHP_SELF, $SCRIPT_NAME or $URL');
242 return false;
247 * Like {@link me()} but returns a full URL
248 * @see me()
249 * @return string
251 function qualified_me() {
253 global $CFG;
255 if (!empty($CFG->wwwroot)) {
256 $url = parse_url($CFG->wwwroot);
259 if (!empty($url['host'])) {
260 $hostname = $url['host'];
261 } else if (!empty($_SERVER['SERVER_NAME'])) {
262 $hostname = $_SERVER['SERVER_NAME'];
263 } else if (!empty($_ENV['SERVER_NAME'])) {
264 $hostname = $_ENV['SERVER_NAME'];
265 } else if (!empty($_SERVER['HTTP_HOST'])) {
266 $hostname = $_SERVER['HTTP_HOST'];
267 } else if (!empty($_ENV['HTTP_HOST'])) {
268 $hostname = $_ENV['HTTP_HOST'];
269 } else {
270 notify('Warning: could not find the name of this server!');
271 return false;
274 if (!empty($url['port'])) {
275 $hostname .= ':'.$url['port'];
276 } else if (!empty($_SERVER['SERVER_PORT'])) {
277 if ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
278 $hostname .= ':'.$_SERVER['SERVER_PORT'];
282 // TODO, this does not work in the situation described in MDL-11061, but
283 // I don't know how to fix it. Possibly believe $CFG->wwwroot ahead of what
284 // the server reports.
285 if (isset($_SERVER['HTTPS'])) {
286 $protocol = ($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
287 } else if (isset($_SERVER['SERVER_PORT'])) { # Apache2 does not export $_SERVER['HTTPS']
288 $protocol = ($_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
289 } else {
290 $protocol = 'http://';
293 $url_prefix = $protocol.$hostname;
294 return $url_prefix . me();
299 * Class for creating and manipulating urls.
301 * See short write up here http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url
303 class moodle_url {
304 var $scheme = '';// e.g. http
305 var $host = '';
306 var $port = '';
307 var $user = '';
308 var $pass = '';
309 var $path = '';
310 var $fragment = '';
311 var $params = array(); //associative array of query string params
314 * Pass no arguments to create a url that refers to this page. Use empty string to create empty url.
316 * @param string $url url default null means use this page url with no query string
317 * empty string means empty url.
318 * if you pass any other type of url it will be parsed into it's bits, including query string
319 * @param array $params these params override anything in the query string where params have the same name.
321 function moodle_url($url = null, $params = array()){
322 global $FULLME;
323 if ($url !== ''){
324 if ($url === null){
325 $url = strip_querystring($FULLME);
327 $parts = parse_url($url);
328 if ($parts === FALSE){
329 error('invalidurl');
331 if (isset($parts['query'])){
332 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
334 unset($parts['query']);
335 foreach ($parts as $key => $value){
336 $this->$key = $value;
338 $this->params($params);
342 * Add an array of params to the params for this page. The added params override existing ones if they
343 * have the same name.
345 * @param array $params
347 function params($params){
348 $this->params = $params + $this->params;
352 * Remove all params if no arguments passed. Or else remove param $arg1, $arg2, etc.
354 * @param string $arg1
355 * @param string $arg2
356 * @param string $arg3
358 function remove_params(){
359 if ($thisargs = func_get_args()){
360 foreach ($thisargs as $arg){
361 if (isset($this->params[$arg])){
362 unset($this->params[$arg]);
365 } else { // no args
366 $this->params = array();
371 * Add a param to the params for this page. The added param overrides existing one if they
372 * have the same name.
374 * @param string $paramname name
375 * @param string $param value
377 function param($paramname, $param){
378 $this->params = array($paramname => $param) + $this->params;
382 function get_query_string($overrideparams = array()){
383 $arr = array();
384 $params = $overrideparams + $this->params;
385 foreach ($params as $key => $val){
386 $arr[] = urlencode($key)."=".urlencode($val);
388 return implode($arr, "&amp;");
391 * Outputs params as hidden form elements.
393 * @param array $exclude params to ignore
394 * @param integer $indent indentation
395 * @param array $overrideparams params to add to the output params, these
396 * override existing ones with the same name.
397 * @return string html for form elements.
399 function hidden_params_out($exclude = array(), $indent = 0, $overrideparams=array()){
400 $tabindent = str_repeat("\t", $indent);
401 $str = '';
402 $params = $overrideparams + $this->params;
403 foreach ($params as $key => $val){
404 if (FALSE === array_search($key, $exclude)) {
405 $val = s($val);
406 $str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
409 return $str;
412 * Output url
414 * @param boolean $noquerystring whether to output page params as a query string in the url.
415 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
416 * @return string url
418 function out($noquerystring = false, $overrideparams = array()) {
419 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
420 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
421 $uri .= $this->host ? $this->host : '';
422 $uri .= $this->port ? ':'.$this->port : '';
423 $uri .= $this->path ? $this->path : '';
424 if (!$noquerystring){
425 $uri .= (count($this->params)||count($overrideparams)) ? '?'.$this->get_query_string($overrideparams) : '';
427 $uri .= $this->fragment ? '#'.$this->fragment : '';
428 return $uri;
431 * Output action url with sesskey
433 * @param boolean $noquerystring whether to output page params as a query string in the url.
434 * @return string url
436 function out_action($overrideparams = array()) {
437 $overrideparams = array('sesskey'=> sesskey()) + $overrideparams;
438 return $this->out(false, $overrideparams);
443 * Determine if there is data waiting to be processed from a form
445 * Used on most forms in Moodle to check for data
446 * Returns the data as an object, if it's found.
447 * This object can be used in foreach loops without
448 * casting because it's cast to (array) automatically
450 * Checks that submitted POST data exists and returns it as object.
452 * @param string $url not used anymore
453 * @return mixed false or object
455 function data_submitted($url='') {
457 if (empty($_POST)) {
458 return false;
459 } else {
460 return (object)$_POST;
465 * Moodle replacement for php stripslashes() function,
466 * works also for objects and arrays.
468 * The standard php stripslashes() removes ALL backslashes
469 * even from strings - so C:\temp becomes C:temp - this isn't good.
470 * This function should work as a fairly safe replacement
471 * to be called on quoted AND unquoted strings (to be sure)
473 * @param mixed something to remove unsafe slashes from
474 * @return mixed
476 function stripslashes_safe($mixed) {
477 // there is no need to remove slashes from int, float and bool types
478 if (empty($mixed)) {
479 //nothing to do...
480 } else if (is_string($mixed)) {
481 if (ini_get_bool('magic_quotes_sybase')) { //only unescape single quotes
482 $mixed = str_replace("''", "'", $mixed);
483 } else { //the rest, simple and double quotes and backslashes
484 $mixed = str_replace("\\'", "'", $mixed);
485 $mixed = str_replace('\\"', '"', $mixed);
486 $mixed = str_replace('\\\\', '\\', $mixed);
488 } else if (is_array($mixed)) {
489 foreach ($mixed as $key => $value) {
490 $mixed[$key] = stripslashes_safe($value);
492 } else if (is_object($mixed)) {
493 $vars = get_object_vars($mixed);
494 foreach ($vars as $key => $value) {
495 $mixed->$key = stripslashes_safe($value);
499 return $mixed;
503 * Recursive implementation of stripslashes()
505 * This function will allow you to strip the slashes from a variable.
506 * If the variable is an array or object, slashes will be stripped
507 * from the items (or properties) it contains, even if they are arrays
508 * or objects themselves.
510 * @param mixed the variable to remove slashes from
511 * @return mixed
513 function stripslashes_recursive($var) {
514 if (is_object($var)) {
515 $new_var = new object();
516 $properties = get_object_vars($var);
517 foreach($properties as $property => $value) {
518 $new_var->$property = stripslashes_recursive($value);
521 } else if(is_array($var)) {
522 $new_var = array();
523 foreach($var as $property => $value) {
524 $new_var[$property] = stripslashes_recursive($value);
527 } else if(is_string($var)) {
528 $new_var = stripslashes($var);
530 } else {
531 $new_var = $var;
534 return $new_var;
538 * Recursive implementation of addslashes()
540 * This function will allow you to add the slashes from a variable.
541 * If the variable is an array or object, slashes will be added
542 * to the items (or properties) it contains, even if they are arrays
543 * or objects themselves.
545 * @param mixed the variable to add slashes from
546 * @return mixed
548 function addslashes_recursive($var) {
549 if (is_object($var)) {
550 $new_var = new object();
551 $properties = get_object_vars($var);
552 foreach($properties as $property => $value) {
553 $new_var->$property = addslashes_recursive($value);
556 } else if (is_array($var)) {
557 $new_var = array();
558 foreach($var as $property => $value) {
559 $new_var[$property] = addslashes_recursive($value);
562 } else if (is_string($var)) {
563 $new_var = addslashes($var);
565 } else { // nulls, integers, etc.
566 $new_var = $var;
569 return $new_var;
573 * Given some normal text this function will break up any
574 * long words to a given size by inserting the given character
576 * It's multibyte savvy and doesn't change anything inside html tags.
578 * @param string $string the string to be modified
579 * @param int $maxsize maximum length of the string to be returned
580 * @param string $cutchar the string used to represent word breaks
581 * @return string
583 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
585 /// Loading the textlib singleton instance. We are going to need it.
586 $textlib = textlib_get_instance();
588 /// First of all, save all the tags inside the text to skip them
589 $tags = array();
590 filter_save_tags($string,$tags);
592 /// Process the string adding the cut when necessary
593 $output = '';
594 $length = $textlib->strlen($string);
595 $wordlength = 0;
597 for ($i=0; $i<$length; $i++) {
598 $char = $textlib->substr($string, $i, 1);
599 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
600 $wordlength = 0;
601 } else {
602 $wordlength++;
603 if ($wordlength > $maxsize) {
604 $output .= $cutchar;
605 $wordlength = 0;
608 $output .= $char;
611 /// Finally load the tags back again
612 if (!empty($tags)) {
613 $output = str_replace(array_keys($tags), $tags, $output);
616 return $output;
620 * This does a search and replace, ignoring case
621 * This function is only used for versions of PHP older than version 5
622 * which do not have a native version of this function.
623 * Taken from the PHP manual, by bradhuizenga @ softhome.net
625 * @param string $find the string to search for
626 * @param string $replace the string to replace $find with
627 * @param string $string the string to search through
628 * return string
630 if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
631 function str_ireplace($find, $replace, $string) {
633 if (!is_array($find)) {
634 $find = array($find);
637 if(!is_array($replace)) {
638 if (!is_array($find)) {
639 $replace = array($replace);
640 } else {
641 // this will duplicate the string into an array the size of $find
642 $c = count($find);
643 $rString = $replace;
644 unset($replace);
645 for ($i = 0; $i < $c; $i++) {
646 $replace[$i] = $rString;
651 foreach ($find as $fKey => $fItem) {
652 $between = explode(strtolower($fItem),strtolower($string));
653 $pos = 0;
654 foreach($between as $bKey => $bItem) {
655 $between[$bKey] = substr($string,$pos,strlen($bItem));
656 $pos += strlen($bItem) + strlen($fItem);
658 $string = implode($replace[$fKey],$between);
660 return ($string);
665 * Locate the position of a string in another string
667 * This function is only used for versions of PHP older than version 5
668 * which do not have a native version of this function.
669 * Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
671 * @param string $haystack The string to be searched
672 * @param string $needle The string to search for
673 * @param int $offset The position in $haystack where the search should begin.
675 if (!function_exists('stripos')) { /// Only exists in PHP 5
676 function stripos($haystack, $needle, $offset=0) {
678 return strpos(strtoupper($haystack), strtoupper($needle), $offset);
683 * This function will print a button/link/etc. form element
684 * that will work on both Javascript and non-javascript browsers.
685 * Relies on the Javascript function openpopup in javascript.php
687 * All parameters default to null, only $type and $url are mandatory.
689 * $url must be relative to home page eg /mod/survey/stuff.php
690 * @param string $url Web link relative to home page
691 * @param string $name Name to be assigned to the popup window (this is used by
692 * client-side scripts to "talk" to the popup window)
693 * @param string $linkname Text to be displayed as web link
694 * @param int $height Height to assign to popup window
695 * @param int $width Height to assign to popup window
696 * @param string $title Text to be displayed as popup page title
697 * @param string $options List of additional options for popup window
698 * @param string $return If true, return as a string, otherwise print
699 * @param string $id id added to the element
700 * @param string $class class added to the element
701 * @return string
702 * @uses $CFG
704 function element_to_popup_window ($type=null, $url=null, $name=null, $linkname=null,
705 $height=400, $width=500, $title=null,
706 $options=null, $return=false, $id=null, $class=null) {
708 if (is_null($url)) {
709 debugging('You must give the url to display in the popup. URL is missing - can\'t create popup window.', DEBUG_DEVELOPER);
712 global $CFG;
714 if ($options == 'none') { // 'none' is legacy, should be removed in v2.0
715 $options = null;
718 // add some sane default options for popup windows
719 if (!$options) {
720 $options = 'menubar=0,location=0,scrollbars,resizable';
722 if ($width) {
723 $options .= ',width='. $width;
725 if ($height) {
726 $options .= ',height='. $height;
728 if ($id) {
729 $id = ' id="'.$id.'" ';
731 if ($class) {
732 $class = ' class="'.$class.'" ';
734 if ($name) {
735 $_name = $name;
736 if (($name = preg_replace("/\s/", '_', $name)) != $_name) {
737 debugging('The $name of a popup window shouldn\'t contain spaces - string modified. '. $_name .' changed to '. $name, DEBUG_DEVELOPER);
739 } else {
740 $name = 'popup';
743 // get some default string, using the localized version of legacy defaults
744 if (is_null($linkname) || $linkname === '') {
745 $linkname = get_string('clickhere');
747 if (!$title) {
748 $title = get_string('popupwindowname');
751 $fullscreen = 0; // must be passed to openpopup
752 $element = '';
754 switch ($type) {
755 case 'button' :
756 $element = '<input type="button" name="'. $name .'" title="'. $title .'" value="'. $linkname .'" '. $id . $class .
757 "onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
758 break;
759 case 'link' :
760 // some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
761 if (!(strpos($url,$CFG->wwwroot) === false)) {
762 $url = substr($url, strlen($CFG->wwwroot));
764 $element = '<a title="'. s(strip_tags($title)) .'" href="'. $CFG->wwwroot . $url .'" '.
765 "onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
766 break;
767 default :
768 error('Undefined element - can\'t create popup window.');
769 break;
772 if ($return) {
773 return $element;
774 } else {
775 echo $element;
780 * Creates and displays (or returns) a link to a popup window, using element_to_popup_window function.
782 * @return string html code to display a link to a popup window.
783 * @see element_to_popup_window()
785 function link_to_popup_window ($url, $name=null, $linkname=null,
786 $height=400, $width=500, $title=null,
787 $options=null, $return=false) {
789 return element_to_popup_window('link', $url, $name, $linkname, $height, $width, $title, $options, $return, null, null);
793 * Creates and displays (or returns) a buttons to a popup window, using element_to_popup_window function.
795 * @return string html code to display a button to a popup window.
796 * @see element_to_popup_window()
798 function button_to_popup_window ($url, $name=null, $linkname=null,
799 $height=400, $width=500, $title=null, $options=null, $return=false,
800 $id=null, $class=null) {
802 return element_to_popup_window('button', $url, $name, $linkname, $height, $width, $title, $options, $return, $id, $class);
807 * Prints a simple button to close a window
808 * @param string $name name of the window to close
809 * @param boolean $return whether this function should return a string or output it
810 * @return string if $return is true, nothing otherwise
812 function close_window_button($name='closewindow', $return=false) {
813 global $CFG;
815 $output = '';
817 $output .= '<div class="closewindow">' . "\n";
818 $output .= '<form action="#"><div>';
819 $output .= '<input type="button" onclick="self.close();" value="'.get_string($name).'" />';
820 $output .= '</div></form>';
821 $output .= '</div>' . "\n";
823 if ($return) {
824 return $output;
825 } else {
826 echo $output;
831 * Try and close the current window immediately using Javascript
832 * @param int $delay the delay in seconds before closing the window
834 function close_window($delay=0) {
836 <script type="text/javascript">
837 //<![CDATA[
838 function close_this_window() {
839 self.close();
841 setTimeout("close_this_window()", <?php echo $delay * 1000 ?>);
842 //]]>
843 </script>
844 <noscript><center>
845 <?php print_string('pleaseclose') ?>
846 </center></noscript>
847 <?php
848 die;
853 * Given an array of values, output the HTML for a select element with those options.
854 * Normally, you only need to use the first few parameters.
856 * @param array $options The options to offer. An array of the form
857 * $options[{value}] = {text displayed for that option};
858 * @param string $name the name of this form control, as in &lt;select name="..." ...
859 * @param string $selected the option to select initially, default none.
860 * @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
861 * Set this to '' if you don't want a 'nothing is selected' option.
862 * @param string $script in not '', then this is added to the &lt;select> element as an onchange handler.
863 * @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
864 * @param boolean $return if false (the default) the the output is printed directly, If true, the
865 * generated HTML is returned as a string.
866 * @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
867 * @param int $tabindex if give, sets the tabindex attribute on the &lt;select> element. Default none.
868 * @param string $id value to use for the id attribute of the &lt;select> element. If none is given,
869 * then a suitable one is constructed.
871 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
872 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0, $id='') {
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 if ($id ==='') {
888 $id = 'menu'.$name;
889 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
890 $id = str_replace('[', '', $id);
891 $id = str_replace(']', '', $id);
894 $output = '<select id="'.$id.'" name="'. $name .'" '. $attributes .'>' . "\n";
895 if ($nothing) {
896 $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
897 if ($nothingvalue === $selected) {
898 $output .= ' selected="selected"';
900 $output .= '>'. $nothing .'</option>' . "\n";
902 if (!empty($options)) {
903 foreach ($options as $value => $label) {
904 $output .= ' <option value="'. s($value) .'"';
905 if ((string)$value == (string)$selected) {
906 $output .= ' selected="selected"';
908 if ($label === '') {
909 $output .= '>'. $value .'</option>' . "\n";
910 } else {
911 $output .= '>'. $label .'</option>' . "\n";
915 $output .= '</select>' . "\n";
917 if ($return) {
918 return $output;
919 } else {
920 echo $output;
925 * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
926 * Other options like choose_from_menu.
927 * @param string $name
928 * @param string $selected
929 * @param string $string (defaults to '')
930 * @param boolean $return whether this function should return a string or output it (defaults to false)
931 * @param boolean $disabled (defaults to false)
932 * @param int $tabindex
934 function choose_from_menu_yesno($name, $selected, $script = '',
935 $return = false, $disabled = false, $tabindex = 0) {
936 return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
937 $selected, '', $script, '0', $return, $disabled, $tabindex);
941 * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
942 * including option headings with the first level.
944 function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
945 $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
947 if ($nothing == 'choose') {
948 $nothing = get_string('choose') .'...';
951 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
952 if ($disabled) {
953 $attributes .= ' disabled="disabled"';
956 if ($tabindex) {
957 $attributes .= ' tabindex="'.$tabindex.'"';
960 $output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
961 if ($nothing) {
962 $output .= ' <option value="'. $nothingvalue .'"'. "\n";
963 if ($nothingvalue === $selected) {
964 $output .= ' selected="selected"';
966 $output .= '>'. $nothing .'</option>' . "\n";
968 if (!empty($options)) {
969 foreach ($options as $section => $values) {
971 $output .= ' <optgroup label="'. s(format_string($section)) .'">'."\n";
972 foreach ($values as $value => $label) {
973 $output .= ' <option value="'. format_string($value) .'"';
974 if ((string)$value == (string)$selected) {
975 $output .= ' selected="selected"';
977 if ($label === '') {
978 $output .= '>'. $value .'</option>' . "\n";
979 } else {
980 $output .= '>'. $label .'</option>' . "\n";
983 $output .= ' </optgroup>'."\n";
986 $output .= '</select>' . "\n";
988 if ($return) {
989 return $output;
990 } else {
991 echo $output;
997 * Given an array of values, creates a group of radio buttons to be part of a form
999 * @param array $options An array of value-label pairs for the radio group (values as keys)
1000 * @param string $name Name of the radiogroup (unique in the form)
1001 * @param string $checked The value that is already checked
1003 function choose_from_radio ($options, $name, $checked='', $return=false) {
1005 static $idcounter = 0;
1007 if (!$name) {
1008 $name = 'unnamed';
1011 $output = '<span class="radiogroup '.$name."\">\n";
1013 if (!empty($options)) {
1014 $currentradio = 0;
1015 foreach ($options as $value => $label) {
1016 $htmlid = 'auto-rb'.sprintf('%04d', ++$idcounter);
1017 $output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
1018 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
1019 if ($value == $checked) {
1020 $output .= ' checked="checked"';
1022 if ($label === '') {
1023 $output .= ' /> <label for="'.$htmlid.'">'. $value .'</label></span>' . "\n";
1024 } else {
1025 $output .= ' /> <label for="'.$htmlid.'">'. $label .'</label></span>' . "\n";
1027 $currentradio = ($currentradio + 1) % 2;
1031 $output .= '</span>' . "\n";
1033 if ($return) {
1034 return $output;
1035 } else {
1036 echo $output;
1040 /** Display an standard html checkbox with an optional label
1042 * @param string $name The name of the checkbox
1043 * @param string $value The valus that the checkbox will pass when checked
1044 * @param boolean $checked The flag to tell the checkbox initial state
1045 * @param string $label The label to be showed near the checkbox
1046 * @param string $alt The info to be inserted in the alt tag
1048 function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
1050 static $idcounter = 0;
1052 if (!$name) {
1053 $name = 'unnamed';
1056 if ($alt) {
1057 $alt = strip_tags($alt);
1058 } else {
1059 $alt = 'checkbox';
1062 if ($checked) {
1063 $strchecked = ' checked="checked"';
1064 } else {
1065 $strchecked = '';
1068 $htmlid = 'auto-cb'.sprintf('%04d', ++$idcounter);
1069 $output = '<span class="checkbox '.$name."\">";
1070 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ? ' onclick="'.$script.'" ' : '').' />';
1071 if(!empty($label)) {
1072 $output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
1074 $output .= '</span>'."\n";
1076 if (empty($return)) {
1077 echo $output;
1078 } else {
1079 return $output;
1084 /** Display an standard html text field with an optional label
1086 * @param string $name The name of the text field
1087 * @param string $value The value of the text field
1088 * @param string $label The label to be showed near the text field
1089 * @param string $alt The info to be inserted in the alt tag
1091 function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
1093 static $idcounter = 0;
1095 if (empty($name)) {
1096 $name = 'unnamed';
1099 if (empty($alt)) {
1100 $alt = 'textfield';
1103 if (!empty($maxlength)) {
1104 $maxlength = ' maxlength="'.$maxlength.'" ';
1107 $htmlid = 'auto-tf'.sprintf('%04d', ++$idcounter);
1108 $output = '<span class="textfield '.$name."\">";
1109 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
1111 $output .= '</span>'."\n";
1113 if (empty($return)) {
1114 echo $output;
1115 } else {
1116 return $output;
1123 * Implements a complete little popup form
1125 * @uses $CFG
1126 * @param string $common The URL up to the point of the variable that changes
1127 * @param array $options Alist of value-label pairs for the popup list
1128 * @param string $formid Id must be unique on the page (originaly $formname)
1129 * @param string $selected The option that is already selected
1130 * @param string $nothing The label for the "no choice" option
1131 * @param string $help The name of a help page if help is required
1132 * @param string $helptext The name of the label for the help button
1133 * @param boolean $return Indicates whether the function should return the text
1134 * as a string or echo it directly to the page being rendered
1135 * @param string $targetwindow The name of the target page to open the linked page in.
1136 * @param string $selectlabel Text to place in a [label] element - preferred for accessibility.
1137 * @param array $optionsextra TODO, an array?
1138 * @return string If $return is true then the entire form is returned as a string.
1139 * @todo Finish documenting this function<br>
1141 function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
1142 $targetwindow='self', $selectlabel='', $optionsextra=NULL) {
1144 global $CFG;
1145 static $go, $choose; /// Locally cached, in case there's lots on a page
1147 if (empty($options)) {
1148 return '';
1151 if (!isset($go)) {
1152 $go = get_string('go');
1155 if ($nothing == 'choose') {
1156 if (!isset($choose)) {
1157 $choose = get_string('choose');
1159 $nothing = $choose.'...';
1162 // changed reference to document.getElementById('id_abc') instead of document.abc
1163 // MDL-7861
1164 $output = '<form action="'.$CFG->wwwroot.'/course/jumpto.php"'.
1165 ' method="get" '.
1166 $CFG->frametarget.
1167 ' id="'.$formid.'"'.
1168 ' class="popupform">';
1169 if ($help) {
1170 $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
1171 } else {
1172 $button = '';
1175 if ($selectlabel) {
1176 $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
1179 //IE and Opera fire the onchange when ever you move into a dropdwown list with the keyboard.
1180 //onfocus will call a function inside dropdown.js. It fixes this IE/Opera behavior.
1181 //Note: There is a bug on Opera+Linux with the javascript code (first mouse selection is inactive),
1182 //so we do not fix the Opera behavior on Linux
1183 if (check_browser_version('MSIE') || (check_browser_version('Opera') && !check_browser_operating_system("Linux"))) {
1184 $output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" onfocus="initSelect(\''.$formid.'\','.$targetwindow.')" name="jump">'."\n";
1186 //Other browser
1187 else {
1188 $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";
1191 if ($nothing != '') {
1192 $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
1195 $inoptgroup = false;
1197 foreach ($options as $value => $label) {
1199 if ($label == '--') { /// we are ending previous optgroup
1200 /// Check to see if we already have a valid open optgroup
1201 /// XHTML demands that there be at least 1 option within an optgroup
1202 if ($inoptgroup and (count($optgr) > 1) ) {
1203 $output .= implode('', $optgr);
1204 $output .= ' </optgroup>';
1206 $optgr = array();
1207 $inoptgroup = false;
1208 continue;
1209 } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
1211 /// Check to see if we already have a valid open optgroup
1212 /// XHTML demands that there be at least 1 option within an optgroup
1213 if ($inoptgroup and (count($optgr) > 1) ) {
1214 $output .= implode('', $optgr);
1215 $output .= ' </optgroup>';
1218 unset($optgr);
1219 $optgr = array();
1221 $optgr[] = ' <optgroup label="'. s(format_string(substr($label,2))) .'">'; // Plain labels
1223 $inoptgroup = true; /// everything following will be in an optgroup
1224 continue;
1226 } else {
1227 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()]))
1229 $url=sid_process_url( $common . $value );
1230 } else
1232 $url=$common . $value;
1234 $optstr = ' <option value="' . $url . '"';
1236 if ($value == $selected) {
1237 $optstr .= ' selected="selected"';
1240 if (!empty($optionsextra[$value])) {
1241 $optstr .= ' '.$optionsextra[$value];
1244 if ($label) {
1245 $optstr .= '>'. $label .'</option>' . "\n";
1246 } else {
1247 $optstr .= '>'. $value .'</option>' . "\n";
1250 if ($inoptgroup) {
1251 $optgr[] = $optstr;
1252 } else {
1253 $output .= $optstr;
1259 /// catch the final group if not closed
1260 if ($inoptgroup and count($optgr) > 1) {
1261 $output .= implode('', $optgr);
1262 $output .= ' </optgroup>';
1265 $output .= '</select>';
1266 $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1267 $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
1268 $output .= '<input type="submit" value="'.$go.'" /></div>';
1269 $output .= '<script type="text/javascript">'.
1270 "\n//<![CDATA[\n".
1271 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
1272 "\n//]]>\n".'</script>';
1273 $output .= '</div>';
1274 $output .= '</form>';
1276 if ($return) {
1277 return $output;
1278 } else {
1279 echo $output;
1285 * Prints some red text
1287 * @param string $error The text to be displayed in red
1289 function formerr($error) {
1291 if (!empty($error)) {
1292 echo '<span class="error">'. $error .'</span>';
1297 * Validates an email to make sure it makes sense.
1299 * @param string $address The email address to validate.
1300 * @return boolean
1302 function validate_email($address) {
1304 return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1305 '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1306 '@'.
1307 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1308 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
1309 $address));
1313 * Extracts file argument either from file parameter or PATH_INFO
1315 * @param string $scriptname name of the calling script
1316 * @return string file path (only safe characters)
1318 function get_file_argument($scriptname) {
1319 global $_SERVER;
1321 $relativepath = FALSE;
1323 // first try normal parameter (compatible method == no relative links!)
1324 $relativepath = optional_param('file', FALSE, PARAM_PATH);
1325 if ($relativepath === '/testslasharguments') {
1326 echo 'test -1 : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
1327 die;
1330 // then try extract file from PATH_INFO (slasharguments method)
1331 if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
1332 $path_info = $_SERVER['PATH_INFO'];
1333 // check that PATH_INFO works == must not contain the script name
1334 if (!strpos($path_info, $scriptname)) {
1335 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1336 if ($relativepath === '/testslasharguments') {
1337 echo 'test 1 : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
1338 die;
1343 // now if both fail try the old way
1344 // (for compatibility with misconfigured or older buggy php implementations)
1345 if (!$relativepath) {
1346 $arr = explode($scriptname, me());
1347 if (!empty($arr[1])) {
1348 $path_info = strip_querystring($arr[1]);
1349 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1350 if ($relativepath === '/testslasharguments') {
1351 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
1352 die;
1357 return $relativepath;
1361 * Searches the current environment variables for some slash arguments
1363 * @param string $file ?
1364 * @todo Finish documenting this function
1366 function get_slash_arguments($file='file.php') {
1368 if (!$string = me()) {
1369 return false;
1372 $pathinfo = explode($file, $string);
1374 if (!empty($pathinfo[1])) {
1375 return addslashes($pathinfo[1]);
1376 } else {
1377 return false;
1382 * Extracts arguments from "/foo/bar/something"
1383 * eg http://mysite.com/script.php/foo/bar/something
1385 * @param string $string ?
1386 * @param int $i ?
1387 * @return array|string
1388 * @todo Finish documenting this function
1390 function parse_slash_arguments($string, $i=0) {
1392 if (detect_munged_arguments($string)) {
1393 return false;
1395 $args = explode('/', $string);
1397 if ($i) { // return just the required argument
1398 return $args[$i];
1400 } else { // return the whole array
1401 array_shift($args); // get rid of the empty first one
1402 return $args;
1407 * Just returns an array of text formats suitable for a popup menu
1409 * @uses FORMAT_MOODLE
1410 * @uses FORMAT_HTML
1411 * @uses FORMAT_PLAIN
1412 * @uses FORMAT_MARKDOWN
1413 * @return array
1415 function format_text_menu() {
1417 return array (FORMAT_MOODLE => get_string('formattext'),
1418 FORMAT_HTML => get_string('formathtml'),
1419 FORMAT_PLAIN => get_string('formatplain'),
1420 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1424 * Given text in a variety of format codings, this function returns
1425 * the text as safe HTML.
1427 * This function should mainly be used for long strings like posts,
1428 * answers, glossary items etc. For short strings @see format_string().
1430 * @uses $CFG
1431 * @uses FORMAT_MOODLE
1432 * @uses FORMAT_HTML
1433 * @uses FORMAT_PLAIN
1434 * @uses FORMAT_WIKI
1435 * @uses FORMAT_MARKDOWN
1436 * @param string $text The text to be formatted. This is raw text originally from user input.
1437 * @param int $format Identifier of the text format to be used
1438 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1439 * @param array $options ?
1440 * @param int $courseid ?
1441 * @return string
1442 * @todo Finish documenting this function
1444 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1446 global $CFG, $COURSE;
1448 static $croncache = array();
1450 if ($text === '') {
1451 return ''; // no need to do any filters and cleaning
1454 if (!isset($options->trusttext)) {
1455 $options->trusttext = false;
1458 if (!isset($options->noclean)) {
1459 $options->noclean=false;
1461 if (!isset($options->nocache)) {
1462 $options->nocache=false;
1464 if (!isset($options->smiley)) {
1465 $options->smiley=true;
1467 if (!isset($options->filter)) {
1468 $options->filter=true;
1470 if (!isset($options->para)) {
1471 $options->para=true;
1473 if (!isset($options->newlines)) {
1474 $options->newlines=true;
1477 if (empty($courseid)) {
1478 $courseid = $COURSE->id;
1481 if (!empty($CFG->cachetext) and empty($options->nocache)) {
1482 $time = time() - $CFG->cachetext;
1483 $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);
1485 if (defined('FULLME') and FULLME == 'cron') {
1486 if (isset($croncache[$md5key])) {
1487 return $croncache[$md5key];
1491 if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
1492 if ($oldcacheitem->timemodified >= $time) {
1493 if (defined('FULLME') and FULLME == 'cron') {
1494 if (count($croncache) > 150) {
1495 reset($croncache);
1496 $key = key($croncache);
1497 unset($croncache[$key]);
1499 $croncache[$md5key] = $oldcacheitem->formattedtext;
1501 return $oldcacheitem->formattedtext;
1506 // trusttext overrides the noclean option!
1507 if ($options->trusttext) {
1508 if (trusttext_present($text)) {
1509 $text = trusttext_strip($text);
1510 if (!empty($CFG->enabletrusttext)) {
1511 $options->noclean = true;
1512 } else {
1513 $options->noclean = false;
1515 } else {
1516 $options->noclean = false;
1518 } else if (!debugging('', DEBUG_DEVELOPER)) {
1519 // strip any forgotten trusttext in non-developer mode
1520 // do not forget to disable text cache when debugging trusttext!!
1521 $text = trusttext_strip($text);
1524 $CFG->currenttextiscacheable = true; // Default status - can be changed by any filter
1526 switch ($format) {
1527 case FORMAT_HTML:
1528 if ($options->smiley) {
1529 replace_smilies($text);
1531 if (!$options->noclean) {
1532 $text = clean_text($text, FORMAT_HTML);
1534 if ($options->filter) {
1535 $text = filter_text($text, $courseid);
1537 break;
1539 case FORMAT_PLAIN:
1540 $text = s($text); // cleans dangerous JS
1541 $text = rebuildnolinktag($text);
1542 $text = str_replace(' ', '&nbsp; ', $text);
1543 $text = nl2br($text);
1544 break;
1546 case FORMAT_WIKI:
1547 // this format is deprecated
1548 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1549 this message as all texts should have been converted to Markdown format instead.
1550 Please post a bug report to http://moodle.org/bugs with information about where you
1551 saw this message.</p>'.s($text);
1552 break;
1554 case FORMAT_MARKDOWN:
1555 $text = markdown_to_html($text);
1556 if ($options->smiley) {
1557 replace_smilies($text);
1559 if (!$options->noclean) {
1560 $text = clean_text($text, FORMAT_HTML);
1563 if ($options->filter) {
1564 $text = filter_text($text, $courseid);
1566 break;
1568 default: // FORMAT_MOODLE or anything else
1569 $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
1570 if (!$options->noclean) {
1571 $text = clean_text($text, FORMAT_HTML);
1574 if ($options->filter) {
1575 $text = filter_text($text, $courseid);
1577 break;
1580 if (empty($options->nocache) and !empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
1581 if (defined('FULLME') and FULLME == 'cron') {
1582 // special static cron cache - no need to store it in db if its not already there
1583 if (count($croncache) > 150) {
1584 reset($croncache);
1585 $key = key($croncache);
1586 unset($croncache[$key]);
1588 $croncache[$md5key] = $text;
1589 return $text;
1592 $newcacheitem = new object();
1593 $newcacheitem->md5key = $md5key;
1594 $newcacheitem->formattedtext = addslashes($text);
1595 $newcacheitem->timemodified = time();
1596 if ($oldcacheitem) { // See bug 4677 for discussion
1597 $newcacheitem->id = $oldcacheitem->id;
1598 @update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1599 // It's unlikely that the cron cache cleaner could have
1600 // deleted this entry in the meantime, as it allows
1601 // some extra time to cover these cases.
1602 } else {
1603 @insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1604 // Again, it's possible that another user has caused this
1605 // record to be created already in the time that it took
1606 // to traverse this function. That's OK too, as the
1607 // call above handles duplicate entries, and eventually
1608 // the cron cleaner will delete them.
1612 return $text;
1615 /** Converts the text format from the value to the 'internal'
1616 * name or vice versa. $key can either be the value or the name
1617 * and you get the other back.
1619 * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1620 * @return mixed as above but the other way around!
1622 function text_format_name( $key ) {
1623 $lookup = array();
1624 $lookup[FORMAT_MOODLE] = 'moodle';
1625 $lookup[FORMAT_HTML] = 'html';
1626 $lookup[FORMAT_PLAIN] = 'plain';
1627 $lookup[FORMAT_MARKDOWN] = 'markdown';
1628 $value = "error";
1629 if (!is_numeric($key)) {
1630 $key = strtolower( $key );
1631 $value = array_search( $key, $lookup );
1633 else {
1634 if (isset( $lookup[$key] )) {
1635 $value = $lookup[ $key ];
1638 return $value;
1642 * Resets all data related to filters, called during upgrade or when filter settings change.
1643 * @return void
1645 function reset_text_filters_cache() {
1646 global $CFG;
1648 delete_records('cache_text');
1649 $purifdir = $CFG->dataroot.'/cache/htmlpurifier';
1650 remove_dir($purifdir, true);
1653 /** Given a simple string, this function returns the string
1654 * processed by enabled string filters if $CFG->filterall is enabled
1656 * This function should be used to print short strings (non html) that
1657 * need filter processing e.g. activity titles, post subjects,
1658 * glossary concepts.
1660 * @param string $string The string to be filtered.
1661 * @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
1662 * @param int $courseid Current course as filters can, potentially, use it
1663 * @return string
1665 function format_string ($string, $striplinks=true, $courseid=NULL ) {
1667 global $CFG, $COURSE;
1669 //We'll use a in-memory cache here to speed up repeated strings
1670 static $strcache = false;
1672 if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
1673 $strcache = array();
1676 //init course id
1677 if (empty($courseid)) {
1678 $courseid = $COURSE->id;
1681 //Calculate md5
1682 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
1684 //Fetch from cache if possible
1685 if (isset($strcache[$md5])) {
1686 return $strcache[$md5];
1689 // First replace all ampersands not followed by html entity code
1690 $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1692 if (!empty($CFG->filterall)) {
1693 $string = filter_string($string, $courseid);
1696 // If the site requires it, strip ALL tags from this string
1697 if (!empty($CFG->formatstringstriptags)) {
1698 $string = strip_tags($string);
1700 // Otherwise strip just links if that is required (default)
1701 } else if ($striplinks) { //strip links in string
1702 $string = preg_replace('/(<a[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1705 //Store to cache
1706 $strcache[$md5] = $string;
1708 return $string;
1712 * Given text in a variety of format codings, this function returns
1713 * the text as plain text suitable for plain email.
1715 * @uses FORMAT_MOODLE
1716 * @uses FORMAT_HTML
1717 * @uses FORMAT_PLAIN
1718 * @uses FORMAT_WIKI
1719 * @uses FORMAT_MARKDOWN
1720 * @param string $text The text to be formatted. This is raw text originally from user input.
1721 * @param int $format Identifier of the text format to be used
1722 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1723 * @return string
1725 function format_text_email($text, $format) {
1727 switch ($format) {
1729 case FORMAT_PLAIN:
1730 return $text;
1731 break;
1733 case FORMAT_WIKI:
1734 $text = wiki_to_html($text);
1735 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1736 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
1737 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1738 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1739 break;
1741 case FORMAT_HTML:
1742 return html_to_text($text);
1743 break;
1745 case FORMAT_MOODLE:
1746 case FORMAT_MARKDOWN:
1747 default:
1748 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1749 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1750 break;
1755 * Given some text in HTML format, this function will pass it
1756 * through any filters that have been defined in $CFG->textfilterx
1757 * The variable defines a filepath to a file containing the
1758 * filter function. The file must contain a variable called
1759 * $textfilter_function which contains the name of the function
1760 * with $courseid and $text parameters
1762 * @param string $text The text to be passed through format filters
1763 * @param int $courseid ?
1764 * @return string
1765 * @todo Finish documenting this function
1767 function filter_text($text, $courseid=NULL) {
1768 global $CFG, $COURSE;
1770 if (empty($courseid)) {
1771 $courseid = $COURSE->id; // (copied from format_text)
1774 if (!empty($CFG->textfilters)) {
1775 require_once($CFG->libdir.'/filterlib.php');
1776 $textfilters = explode(',', $CFG->textfilters);
1777 foreach ($textfilters as $textfilter) {
1778 if (is_readable($CFG->dirroot .'/'. $textfilter .'/filter.php')) {
1779 include_once($CFG->dirroot .'/'. $textfilter .'/filter.php');
1780 $functionname = basename($textfilter).'_filter';
1781 if (function_exists($functionname)) {
1782 $text = $functionname($courseid, $text);
1788 /// <nolink> tags removed for XHTML compatibility
1789 $text = str_replace('<nolink>', '', $text);
1790 $text = str_replace('</nolink>', '', $text);
1792 return $text;
1797 * Given a string (short text) in HTML format, this function will pass it
1798 * through any filters that have been defined in $CFG->stringfilters
1799 * The variable defines a filepath to a file containing the
1800 * filter function. The file must contain a variable called
1801 * $textfilter_function which contains the name of the function
1802 * with $courseid and $text parameters
1804 * @param string $string The text to be passed through format filters
1805 * @param int $courseid The id of a course
1806 * @return string
1808 function filter_string($string, $courseid=NULL) {
1809 global $CFG, $COURSE;
1811 if (empty($CFG->textfilters)) { // All filters are disabled anyway so quit
1812 return $string;
1815 if (empty($courseid)) {
1816 $courseid = $COURSE->id;
1819 require_once($CFG->libdir.'/filterlib.php');
1821 if (isset($CFG->stringfilters)) { // We have a predefined list to use, great!
1822 if (empty($CFG->stringfilters)) { // but it's blank, so finish now
1823 return $string;
1825 $stringfilters = explode(',', $CFG->stringfilters); // ..use the list we have
1827 } else { // Otherwise try to derive a list from textfilters
1828 if (strpos($CFG->textfilters, 'filter/multilang') !== false) { // Multilang is here
1829 $stringfilters = array('filter/multilang'); // Let's use just that
1830 $CFG->stringfilters = 'filter/multilang'; // Save it for next time through
1831 } else {
1832 $CFG->stringfilters = ''; // Save the result and return
1833 return $string;
1838 foreach ($stringfilters as $stringfilter) {
1839 if (is_readable($CFG->dirroot .'/'. $stringfilter .'/filter.php')) {
1840 include_once($CFG->dirroot .'/'. $stringfilter .'/filter.php');
1841 $functionname = basename($stringfilter).'_filter';
1842 if (function_exists($functionname)) {
1843 $string = $functionname($courseid, $string);
1848 /// <nolink> tags removed for XHTML compatibility
1849 $string = str_replace('<nolink>', '', $string);
1850 $string = str_replace('</nolink>', '', $string);
1852 return $string;
1856 * Is the text marked as trusted?
1858 * @param string $text text to be searched for TRUSTTEXT marker
1859 * @return boolean
1861 function trusttext_present($text) {
1862 if (strpos($text, TRUSTTEXT) !== FALSE) {
1863 return true;
1864 } else {
1865 return false;
1870 * This funtion MUST be called before the cleaning or any other
1871 * function that modifies the data! We do not know the origin of trusttext
1872 * in database, if it gets there in tweaked form we must not convert it
1873 * to supported form!!!
1875 * Please be carefull not to use stripslashes on data from database
1876 * or twice stripslashes when processing data recieved from user.
1878 * @param string $text text that may contain TRUSTTEXT marker
1879 * @return text without any TRUSTTEXT marker
1881 function trusttext_strip($text) {
1882 global $CFG;
1884 while (true) { //removing nested TRUSTTEXT
1885 $orig = $text;
1886 $text = str_replace(TRUSTTEXT, '', $text);
1887 if (strcmp($orig, $text) === 0) {
1888 return $text;
1894 * Mark text as trusted, such text may contain any HTML tags because the
1895 * normal text cleaning will be bypassed.
1896 * Please make sure that the text comes from trusted user before storing
1897 * it into database!
1899 function trusttext_mark($text) {
1900 global $CFG;
1901 if (!empty($CFG->enabletrusttext) and (strpos($text, TRUSTTEXT) === FALSE)) {
1902 return TRUSTTEXT.$text;
1903 } else {
1904 return $text;
1907 function trusttext_after_edit(&$text, $context) {
1908 if (has_capability('moodle/site:trustcontent', $context)) {
1909 $text = trusttext_strip($text);
1910 $text = trusttext_mark($text);
1911 } else {
1912 $text = trusttext_strip($text);
1916 function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
1917 global $CFG;
1919 $options = new object();
1920 $options->smiley = false;
1921 $options->filter = false;
1922 if (!empty($CFG->enabletrusttext)
1923 and has_capability('moodle/site:trustcontent', $context)
1924 and trusttext_present($text)) {
1925 $options->noclean = true;
1926 } else {
1927 $options->noclean = false;
1929 $text = trusttext_strip($text);
1930 if ($usehtmleditor) {
1931 $text = format_text($text, $format, $options);
1932 $format = FORMAT_HTML;
1933 } else if (!$options->noclean){
1934 $text = clean_text($text, $format);
1939 * Given raw text (eg typed in by a user), this function cleans it up
1940 * and removes any nasty tags that could mess up Moodle pages.
1942 * @uses FORMAT_MOODLE
1943 * @uses FORMAT_PLAIN
1944 * @uses ALLOWED_TAGS
1945 * @param string $text The text to be cleaned
1946 * @param int $format Identifier of the text format to be used
1947 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1948 * @return string The cleaned up text
1950 function clean_text($text, $format=FORMAT_MOODLE) {
1952 global $ALLOWED_TAGS, $CFG;
1954 if (empty($text) or is_numeric($text)) {
1955 return (string)$text;
1958 switch ($format) {
1959 case FORMAT_PLAIN:
1960 case FORMAT_MARKDOWN:
1961 return $text;
1963 default:
1965 if (!empty($CFG->enablehtmlpurifier)) {
1966 $text = purify_html($text);
1967 } else {
1968 /// Fix non standard entity notations
1969 $text = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $text);
1970 $text = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $text);
1972 /// Remove tags that are not allowed
1973 $text = strip_tags($text, $ALLOWED_TAGS);
1975 /// Clean up embedded scripts and , using kses
1976 $text = cleanAttributes($text);
1978 /// Again remove tags that are not allowed
1979 $text = strip_tags($text, $ALLOWED_TAGS);
1983 /// Remove potential script events - some extra protection for undiscovered bugs in our code
1984 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
1985 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
1987 return $text;
1992 * KSES replacement cleaning function - uses HTML Purifier.
1994 function purify_html($text) {
1995 global $CFG;
1997 // this can not be done only once because we sometimes need to reset the cache
1998 $cachedir = $CFG->dataroot.'/cache/htmlpurifier/';
1999 $status = check_dir_exists($cachedir, true, true);
2001 static $purifier = false;
2002 if ($purifier === false) {
2003 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.auto.php';
2004 $config = HTMLPurifier_Config::createDefault();
2005 $config->set('Core', 'AcceptFullDocuments', false);
2006 $config->set('Core', 'Encoding', 'UTF-8');
2007 $config->set('HTML', 'Doctype', 'XHTML 1.0 Transitional');
2008 $config->set('Cache', 'SerializerPath', $cachedir);
2009 $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));
2010 $purifier = new HTMLPurifier($config);
2012 return $purifier->purify($text);
2016 * This function takes a string and examines it for HTML tags.
2017 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
2018 * which checks for attributes and filters them for malicious content
2019 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2021 * @param string $str The string to be examined for html tags
2022 * @return string
2024 function cleanAttributes($str){
2025 $result = preg_replace_callback(
2026 '%(<[^>]*(>|$)|>)%m', #search for html tags
2027 "cleanAttributes2",
2028 $str
2030 return $result;
2034 * This function takes a string with an html tag and strips out any unallowed
2035 * protocols e.g. javascript:
2036 * It calls ancillary functions in kses which are prefixed by kses
2037 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2039 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
2040 * element the html to be cleared
2041 * @return string
2043 function cleanAttributes2($htmlArray){
2045 global $CFG, $ALLOWED_PROTOCOLS;
2046 require_once($CFG->libdir .'/kses.php');
2048 $htmlTag = $htmlArray[1];
2049 if (substr($htmlTag, 0, 1) != '<') {
2050 return '&gt;'; //a single character ">" detected
2052 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
2053 return ''; // It's seriously malformed
2055 $slash = trim($matches[1]); //trailing xhtml slash
2056 $elem = $matches[2]; //the element name
2057 $attrlist = $matches[3]; // the list of attributes as a string
2059 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
2061 $attStr = '';
2062 foreach ($attrArray as $arreach) {
2063 $arreach['name'] = strtolower($arreach['name']);
2064 if ($arreach['name'] == 'style') {
2065 $value = $arreach['value'];
2066 while (true) {
2067 $prevvalue = $value;
2068 $value = kses_no_null($value);
2069 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
2070 $value = kses_decode_entities($value);
2071 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
2072 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
2073 if ($value === $prevvalue) {
2074 $arreach['value'] = $value;
2075 break;
2078 $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']);
2079 $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']);
2080 $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
2081 } else if ($arreach['name'] == 'href') {
2082 //Adobe Acrobat Reader XSS protection
2083 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd))[^a-z0-9_\.\-].*$/i', '$1', $arreach['value']);
2085 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
2088 $xhtml_slash = '';
2089 if (preg_match('%/\s*$%', $attrlist)) {
2090 $xhtml_slash = ' /';
2092 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
2096 * Replaces all known smileys in the text with image equivalents
2098 * @uses $CFG
2099 * @param string $text Passed by reference. The string to search for smily strings.
2100 * @return string
2102 function replace_smilies(&$text) {
2104 global $CFG;
2106 if (empty($CFG->emoticons)) { /// No emoticons defined, nothing to process here
2107 return;
2110 $lang = current_language();
2111 $emoticonstring = $CFG->emoticons;
2112 static $e = array();
2113 static $img = array();
2114 static $emoticons = null;
2116 if (is_null($emoticons)) {
2117 $emoticons = array();
2118 if ($emoticonstring) {
2119 $items = explode('{;}', $CFG->emoticons);
2120 foreach ($items as $item) {
2121 $item = explode('{:}', $item);
2122 $emoticons[$item[0]] = $item[1];
2128 if (empty($img[$lang])) { /// After the first time this is not run again
2129 $e[$lang] = array();
2130 $img[$lang] = array();
2131 foreach ($emoticons as $emoticon => $image){
2132 $alttext = get_string($image, 'pix');
2133 $e[$lang][] = $emoticon;
2134 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath .'/s/'. $image .'.gif" />';
2138 // Exclude from transformations all the code inside <script> tags
2139 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
2140 // Based on code from glossary fiter by Williams Castillo.
2141 // - Eloy
2143 // Detect all the <script> zones to take out
2144 $excludes = array();
2145 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
2147 // Take out all the <script> zones from text
2148 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
2149 $excludes['<+'.$key.'+>'] = $value;
2151 if ($excludes) {
2152 $text = str_replace($excludes,array_keys($excludes),$text);
2155 /// this is the meat of the code - this is run every time
2156 $text = str_replace($e[$lang], $img[$lang], $text);
2158 // Recover all the <script> zones to text
2159 if ($excludes) {
2160 $text = str_replace(array_keys($excludes),$excludes,$text);
2165 * Given plain text, makes it into HTML as nicely as possible.
2166 * May contain HTML tags already
2168 * @uses $CFG
2169 * @param string $text The string to convert.
2170 * @param boolean $smiley Convert any smiley characters to smiley images?
2171 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
2172 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2173 * @return string
2176 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
2179 global $CFG;
2181 /// Remove any whitespace that may be between HTML tags
2182 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
2184 /// Remove any returns that precede or follow HTML tags
2185 $text = eregi_replace("([\n\r])<", " <", $text);
2186 $text = eregi_replace(">([\n\r])", "> ", $text);
2188 convert_urls_into_links($text);
2190 /// Make returns into HTML newlines.
2191 if ($newlines) {
2192 $text = nl2br($text);
2195 /// Turn smileys into images.
2196 if ($smiley) {
2197 replace_smilies($text);
2200 /// Wrap the whole thing in a paragraph tag if required
2201 if ($para) {
2202 return '<p>'.$text.'</p>';
2203 } else {
2204 return $text;
2209 * Given Markdown formatted text, make it into XHTML using external function
2211 * @uses $CFG
2212 * @param string $text The markdown formatted text to be converted.
2213 * @return string Converted text
2215 function markdown_to_html($text) {
2216 global $CFG;
2218 require_once($CFG->libdir .'/markdown.php');
2220 return Markdown($text);
2224 * Given HTML text, make it into plain text using external function
2226 * @uses $CFG
2227 * @param string $html The text to be converted.
2228 * @return string
2230 function html_to_text($html) {
2232 global $CFG;
2234 require_once($CFG->libdir .'/html2text.php');
2236 $result = html2text($html);
2238 // html2text does not fix numerical entities so handle those here.
2239 $tl=textlib_get_instance();
2240 $result = $tl->entities_to_utf8($result,false);
2242 return $result;
2246 * Given some text this function converts any URLs it finds into HTML links
2248 * @param string $text Passed in by reference. The string to be searched for urls.
2250 function convert_urls_into_links(&$text) {
2251 /// Make lone URLs into links. eg http://moodle.com/
2252 $text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
2253 "\\1<a href=\"\\2://\\3\\4\" target=\"_blank\">\\2://\\3\\4</a>", $text);
2255 /// eg www.moodle.com
2256 $text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
2257 "\\1<a href=\"http://www.\\2\\3\" target=\"_blank\">www.\\2\\3</a>", $text);
2261 * This function will highlight search words in a given string
2262 * It cares about HTML and will not ruin links. It's best to use
2263 * this function after performing any conversions to HTML.
2264 * Function found here: http://forums.devshed.com/t67822/scdaa2d1c3d4bacb4671d075ad41f0854.html
2266 * @param string $needle The string to search for
2267 * @param string $haystack The string to search for $needle in
2268 * @param int $case whether to do case-sensitive or insensitive matching.
2269 * @return string
2270 * @todo Finish documenting this function
2272 function highlight($needle, $haystack, $case=0,
2273 $left_string='<span class="highlight">', $right_string='</span>') {
2275 if (empty($needle) or empty($haystack)) {
2276 return $haystack;
2279 //$list_of_words = eregi_replace("[^-a-zA-Z0-9&.']", " ", $needle); // bug 3101
2280 $list_of_words = $needle;
2281 $list_array = explode(' ', $list_of_words);
2282 for ($i=0; $i<sizeof($list_array); $i++) {
2283 if (strlen($list_array[$i]) == 1) {
2284 $list_array[$i] = '';
2287 $list_of_words = implode(' ', $list_array);
2288 $list_of_words_cp = $list_of_words;
2289 $final = array();
2290 preg_match_all('/<(.+?)>/is',$haystack,$list_of_words);
2292 foreach (array_unique($list_of_words[0]) as $key=>$value) {
2293 $final['<|'.$key.'|>'] = $value;
2296 $haystack = str_replace($final,array_keys($final),$haystack);
2297 $list_of_words_cp = eregi_replace(' +', '|', $list_of_words_cp);
2299 if ($list_of_words_cp{0}=='|') {
2300 $list_of_words_cp{0} = '';
2302 if ($list_of_words_cp{strlen($list_of_words_cp)-1}=='|') {
2303 $list_of_words_cp{strlen($list_of_words_cp)-1}='';
2306 $list_of_words_cp = trim($list_of_words_cp);
2308 if ($list_of_words_cp) {
2310 $list_of_words_cp = "(". $list_of_words_cp .")";
2312 if (!$case){
2313 $haystack = eregi_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2314 } else {
2315 $haystack = ereg_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2318 $haystack = str_replace(array_keys($final),$final,$haystack);
2320 return $haystack;
2324 * This function will highlight instances of $needle in $haystack
2325 * It's faster that the above function and doesn't care about
2326 * HTML or anything.
2328 * @param string $needle The string to search for
2329 * @param string $haystack The string to search for $needle in
2330 * @return string
2332 function highlightfast($needle, $haystack) {
2334 if (empty($needle) or empty($haystack)) {
2335 return $haystack;
2338 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
2340 if (count($parts) === 1) {
2341 return $haystack;
2344 $pos = 0;
2346 foreach ($parts as $key => $part) {
2347 $parts[$key] = substr($haystack, $pos, strlen($part));
2348 $pos += strlen($part);
2350 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2351 $pos += strlen($needle);
2354 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2358 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2359 * Internationalisation, for print_header and backup/restorelib.
2360 * @param $dir Default false.
2361 * @return string Attributes.
2363 function get_html_lang($dir = false) {
2364 $direction = '';
2365 if ($dir) {
2366 if (get_string('thisdirection') == 'rtl') {
2367 $direction = ' dir="rtl"';
2368 } else {
2369 $direction = ' dir="ltr"';
2372 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2373 $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
2374 @header('Content-Language: '.$language);
2375 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2379 * Return the markup for the destination of the 'Skip to main content' links.
2380 * Accessibility improvement for keyboard-only users.
2381 * Used in course formats, /index.php and /course/index.php
2382 * @return string HTML element.
2384 function skip_main_destination() {
2385 return '<span id="maincontent"></span>';
2389 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
2392 * Print a standard header
2394 * @uses $USER
2395 * @uses $CFG
2396 * @uses $SESSION
2397 * @param string $title Appears at the top of the window
2398 * @param string $heading Appears at the top of the page
2399 * @param array $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
2400 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2401 * @param string $meta Meta tags to be added to the header
2402 * @param boolean $cache Should this page be cacheable?
2403 * @param string $button HTML code for a button (usually for module editing)
2404 * @param string $menu HTML code for a popup menu
2405 * @param boolean $usexml use XML for this page
2406 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2407 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2409 function print_header ($title='', $heading='', $navigation='', $focus='',
2410 $meta='', $cache=true, $button='&nbsp;', $menu='',
2411 $usexml=false, $bodytags='', $return=false) {
2413 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
2415 if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
2416 debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
2417 . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.", DEBUG_DEVELOPER);
2420 $heading = format_string($heading); // Fix for MDL-8582
2422 /// This makes sure that the header is never repeated twice on a page
2423 if (defined('HEADER_PRINTED')) {
2424 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().');
2425 return;
2427 define('HEADER_PRINTED', 'true');
2430 /// Add the required stylesheets
2431 $stylesheetshtml = '';
2432 foreach ($CFG->stylesheets as $stylesheet) {
2433 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2435 $meta = $stylesheetshtml.$meta;
2438 /// Add the meta page from the themes if any were requested
2440 $metapage = '';
2442 if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
2443 ob_start();
2444 include_once($CFG->dirroot.'/theme/standard/meta.php');
2445 $metapage .= ob_get_contents();
2446 ob_end_clean();
2449 if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
2450 if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
2451 ob_start();
2452 include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
2453 $metapage .= ob_get_contents();
2454 ob_end_clean();
2458 if (!isset($THEME->metainclude) || $THEME->metainclude) {
2459 if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
2460 ob_start();
2461 include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
2462 $metapage .= ob_get_contents();
2463 ob_end_clean();
2467 $meta = $meta."\n".$metapage;
2469 $meta .= "\n".require_js('',1);
2471 /// Set up some navigation variables
2473 if (is_newnav($navigation)){
2474 $home = false;
2475 } else {
2476 if ($navigation == 'home') {
2477 $home = true;
2478 $navigation = '';
2479 } else {
2480 $home = false;
2484 /// This is another ugly hack to make navigation elements available to print_footer later
2485 $THEME->title = $title;
2486 $THEME->heading = $heading;
2487 $THEME->navigation = $navigation;
2488 $THEME->button = $button;
2489 $THEME->menu = $menu;
2490 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2492 if ($button == '') {
2493 $button = '&nbsp;';
2496 if (!$menu and $navigation) {
2497 if (empty($CFG->loginhttps)) {
2498 $wwwroot = $CFG->wwwroot;
2499 } else {
2500 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
2502 $menu = user_login_string($COURSE);
2505 if (isset($SESSION->justloggedin)) {
2506 unset($SESSION->justloggedin);
2507 if (!empty($CFG->displayloginfailures)) {
2508 if (!empty($USER->username) and $USER->username != 'guest') {
2509 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
2510 $menu .= '&nbsp;<font size="1">';
2511 if (empty($count->accounts)) {
2512 $menu .= get_string('failedloginattempts', '', $count);
2513 } else {
2514 $menu .= get_string('failedloginattemptsall', '', $count);
2516 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_SYSTEM))) {
2517 $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
2518 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
2520 $menu .= '</font>';
2527 $meta = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' .
2528 "\n" . $meta . "\n";
2529 if (!$usexml) {
2530 @header('Content-Type: text/html; charset=utf-8');
2532 @header('Content-Script-Type: text/javascript');
2533 @header('Content-Style-Type: text/css');
2535 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2536 $direction = get_html_lang($dir=true);
2538 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2539 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2540 @header('Pragma: no-cache');
2541 @header('Expires: ');
2542 } else { // Do everything we can to always prevent clients and proxies caching
2543 @header('Cache-Control: no-store, no-cache, must-revalidate');
2544 @header('Cache-Control: post-check=0, pre-check=0', false);
2545 @header('Pragma: no-cache');
2546 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2547 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2549 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2550 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
2552 @header('Accept-Ranges: none');
2554 $currentlanguage = current_language();
2556 if (empty($usexml)) {
2557 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2558 } else {
2559 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2560 if(!$mathplayer) {
2561 header('Content-Type: application/xhtml+xml');
2563 echo '<?xml version="1.0" ?>'."\n";
2564 if (!empty($CFG->xml_stylesheets)) {
2565 $stylesheets = explode(';', $CFG->xml_stylesheets);
2566 foreach ($stylesheets as $stylesheet) {
2567 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
2570 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
2571 if (!empty($CFG->xml_doctype_extra)) {
2572 echo ' plus '. $CFG->xml_doctype_extra;
2574 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
2575 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2576 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
2577 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2578 $direction";
2579 if($mathplayer) {
2580 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
2581 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2582 $meta .= '</object>'."\n";
2583 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2587 // Clean up the title
2589 $title = format_string($title); // fix for MDL-8582
2590 $title = str_replace('"', '&quot;', $title);
2592 // Create class and id for this page
2594 page_id_and_class($pageid, $pageclass);
2596 $pageclass .= ' course-'.$COURSE->id;
2598 if (!isloggedin()) {
2599 $pageclass .= ' notloggedin';
2602 if (!empty($USER->editing)) {
2603 $pageclass .= ' editing';
2606 if (!empty($CFG->blocksdrag)) {
2607 $pageclass .= ' drag';
2610 $pageclass .= ' dir-'.get_string('thisdirection');
2612 $pageclass .= ' lang-'.$currentlanguage;
2614 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
2616 ob_start();
2617 include($CFG->header);
2618 $output = ob_get_contents();
2619 ob_end_clean();
2621 // container debugging info
2622 $THEME->open_header_containers = open_containers();
2624 // Skip to main content, see skip_main_destination().
2625 if ($pageid=='course-view' or $pageid=='site-index' or $pageid=='course-index') {
2626 $skiplink = '<a class="skip" href="#maincontent">'.get_string('tocontent', 'access').'</a>';
2627 if (! preg_match('/(.*<div[^>]+id="page"[^>]*>)(.*)/s', $output, $matches)) {
2628 preg_match('/(.*<body.*?>)(.*)/s', $output, $matches);
2630 $output = $matches[1]."\n". $skiplink .$matches[2];
2633 $output = force_strict_header($output);
2635 if (!empty($CFG->messaging)) {
2636 $output .= message_popup_window();
2639 // Add in any extra JavaScript libraries that occurred during the header
2640 $output .= require_js('', 2);
2642 if ($return) {
2643 return $output;
2644 } else {
2645 echo $output;
2650 * Used to include JavaScript libraries.
2652 * When the $lib parameter is given, the function will ensure that the
2653 * named library is loaded onto the page - either in the HTML <head>,
2654 * just after the header, or at an arbitrary later point in the page,
2655 * depending on where this function is called.
2657 * Libraries will not be included more than once, so this works like
2658 * require_once in PHP.
2660 * There are two special-case calls to this function which are both used only
2661 * by weblib print_header:
2662 * $extracthtml = 1: this is used before printing the header.
2663 * It returns the script tag code that should go inside the <head>.
2664 * $extracthtml = 2: this is used after printing the header and handles any
2665 * require_js calls that occurred within the header itself.
2667 * @param mixed $lib - string or array of strings
2668 * string(s) should be the shortname for the library or the
2669 * full path to the library file.
2670 * @param int $extracthtml Do not set this parameter usually (leave 0), only
2671 * weblib should set this to 1 or 2 in print_header function.
2672 * @return mixed No return value, except when using $extracthtml it returns the html code.
2674 function require_js($lib,$extracthtml=0) {
2675 global $CFG;
2676 static $loadlibs = array();
2678 static $state = REQUIREJS_BEFOREHEADER;
2679 static $latecode = '';
2681 if (!empty($lib)) {
2682 // Add the lib to the list of libs to be loaded, if it isn't already
2683 // in the list.
2684 if (is_array($lib)) {
2685 foreach($lib as $singlelib) {
2686 require_js($singlelib);
2688 } else {
2689 $libpath = ajax_get_lib($lib);
2690 if (array_search($libpath, $loadlibs) === false) {
2691 $loadlibs[] = $libpath;
2693 // For state other than 0 we need to take action as well as just
2694 // adding it to loadlibs
2695 if($state != REQUIREJS_BEFOREHEADER) {
2696 // Get the script statement for this library
2697 $scriptstatement=get_require_js_code(array($libpath));
2699 if($state == REQUIREJS_AFTERHEADER) {
2700 // After the header, print it immediately
2701 print $scriptstatement;
2702 } else {
2703 // Haven't finished the header yet. Add it after the
2704 // header
2705 $latecode .= $scriptstatement;
2710 } else if($extracthtml==1) {
2711 if($state !== REQUIREJS_BEFOREHEADER) {
2712 debugging('Incorrect state in require_js (expected BEFOREHEADER): be careful not to call with empty $lib (except in print_header)');
2713 } else {
2714 $state = REQUIREJS_INHEADER;
2717 return get_require_js_code($loadlibs);
2718 } else if($extracthtml==2) {
2719 if($state !== REQUIREJS_INHEADER) {
2720 debugging('Incorrect state in require_js (expected INHEADER): be careful not to call with empty $lib (except in print_header)');
2721 return '';
2722 } else {
2723 $state = REQUIREJS_AFTERHEADER;
2724 return $latecode;
2726 } else {
2727 debugging('Unexpected value for $extracthtml');
2732 * Should not be called directly - use require_js. This function obtains the code
2733 * (script tags) needed to include JavaScript libraries.
2734 * @param array $loadlibs Array of library files to include
2735 * @return string HTML code to include them
2737 function get_require_js_code($loadlibs) {
2738 global $CFG;
2739 // Return the html needed to load the JavaScript files defined in
2740 // our list of libs to be loaded.
2741 $output = '';
2742 foreach ($loadlibs as $loadlib) {
2743 $output .= '<script type="text/javascript" ';
2744 $output .= " src=\"$loadlib\"></script>\n";
2745 if ($loadlib == $CFG->wwwroot.'/lib/yui/logger/logger-min.js') {
2746 // Special case, we need the CSS too.
2747 $output .= '<link type="text/css" rel="stylesheet" ';
2748 $output .= " href=\"{$CFG->wwwroot}/lib/yui/logger/assets/logger.css\" />\n";
2751 return $output;
2756 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2757 * and substitute the XHTML strict document type.
2758 * Note, requires the 'xmlns' fix in function print_header above.
2759 * See: http://tracker.moodle.org/browse/MDL-7883
2760 * TODO:
2762 function force_strict_header($output) {
2763 global $CFG;
2764 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2765 $xsl = '/lib/xhtml.xsl';
2767 if (!headers_sent() && !empty($CFG->xmlstrictheaders)) { // With xml strict headers, the browser will barf
2768 $ctype = 'Content-Type: ';
2769 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2771 if (isset($_SERVER['HTTP_ACCEPT'])
2772 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2773 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2774 // Firefox et al.
2775 $ctype .= 'application/xhtml+xml';
2776 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2778 } else if (file_exists($CFG->dirroot.$xsl)
2779 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2780 // XSL hack for IE 5+ on Windows.
2781 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2782 $www_xsl = $CFG->wwwroot .$xsl;
2783 $ctype .= 'application/xml';
2784 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2785 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2787 } else {
2788 //ELSE: Mac/IE, old/non-XML browsers.
2789 $ctype .= 'text/html';
2790 $prolog = '';
2792 @header($ctype.'; charset=utf-8');
2793 $output = $prolog . $output;
2795 // Test parser error-handling.
2796 if (isset($_GET['error'])) {
2797 $output .= "__ TEST: XML well-formed error < __\n";
2801 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
2803 return $output;
2809 * This version of print_header is simpler because the course name does not have to be
2810 * provided explicitly in the strings. It can be used on the site page as in courses
2811 * Eventually all print_header could be replaced by print_header_simple
2813 * @param string $title Appears at the top of the window
2814 * @param string $heading Appears at the top of the page
2815 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2816 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2817 * @param string $meta Meta tags to be added to the header
2818 * @param boolean $cache Should this page be cacheable?
2819 * @param string $button HTML code for a button (usually for module editing)
2820 * @param string $menu HTML code for a popup menu
2821 * @param boolean $usexml use XML for this page
2822 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2823 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2825 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
2826 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
2828 global $COURSE, $CFG;
2830 // if we have no navigation specified, build it
2831 if( empty($navigation) ){
2832 $navigation = build_navigation('');
2835 // If old style nav prepend course short name otherwise leave $navigation object alone
2836 if (!is_newnav($navigation)) {
2837 if ($COURSE->id != SITEID) {
2838 $shortname = '<a href="'.$CFG->wwwroot.'/course/view.php?id='. $COURSE->id .'">'. $COURSE->shortname .'</a> ->';
2839 $navigation = $shortname.' '.$navigation;
2843 $output = print_header($COURSE->shortname .': '. $title, $COURSE->fullname .' '. $heading, $navigation, $focus, $meta,
2844 $cache, $button, $menu, $usexml, $bodytags, true);
2846 if ($return) {
2847 return $output;
2848 } else {
2849 echo $output;
2855 * Can provide a course object to make the footer contain a link to
2856 * to the course home page, otherwise the link will go to the site home
2857 * @uses $USER
2858 * @param mixed $course course object, used for course link button or
2859 * 'none' means no user link, only docs link
2860 * 'empty' means nothing printed in footer
2861 * 'home' special frontpage footer
2862 * @param object $usercourse course used in user link
2863 * @param boolean $return output as string
2864 * @return mixed string or void
2866 function print_footer($course=NULL, $usercourse=NULL, $return=false) {
2867 global $USER, $CFG, $THEME, $COURSE;
2869 if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
2870 admin_externalpage_print_footer();
2871 return;
2874 /// Course links or special footer
2875 if ($course) {
2876 if ($course === 'empty') {
2877 // special hack - sometimes we do not want even the docs link in footer
2878 $output = '';
2879 if (!empty($THEME->open_header_containers)) {
2880 for ($i=0; $i<$THEME->open_header_containers; $i++) {
2881 $output .= print_container_end_all(); // containers opened from header
2883 } else {
2884 //1.8 theme compatibility
2885 $output .= "\n</div>"; // content div
2887 $output .= "\n</div>\n</body>\n</html>"; // close page div started in header
2888 if ($return) {
2889 return $output;
2890 } else {
2891 echo $output;
2892 return;
2895 } else if ($course === 'none') { // Don't print any links etc
2896 $homelink = '';
2897 $loggedinas = '';
2898 $home = false;
2900 } else if ($course === 'home') { // special case for site home page - please do not remove
2901 $course = get_site();
2902 $homelink = '<div class="sitelink">'.
2903 '<a title="Moodle '. $CFG->release .'" href="http://moodle.org/">'.
2904 '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
2905 $home = true;
2907 } else {
2908 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
2909 '/course/view.php?id='.$course->id.'">'.format_string($course->shortname).'</a></div>';
2910 $home = false;
2913 } else {
2914 $course = get_site(); // Set course as site course by default
2915 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
2916 $home = false;
2919 /// Set up some other navigation links (passed from print_header by ugly hack)
2920 $menu = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
2921 $title = isset($THEME->title) ? $THEME->title : '';
2922 $button = isset($THEME->button) ? $THEME->button : '';
2923 $heading = isset($THEME->heading) ? $THEME->heading : '';
2924 $navigation = isset($THEME->navigation) ? $THEME->navigation : '';
2925 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2928 /// Set the user link if necessary
2929 if (!$usercourse and is_object($course)) {
2930 $usercourse = $course;
2933 if (!isset($loggedinas)) {
2934 $loggedinas = user_login_string($usercourse, $USER);
2937 if ($loggedinas == $menu) {
2938 $menu = '';
2941 /// there should be exactly the same number of open containers as after the header
2942 if ($THEME->open_header_containers != open_containers()) {
2943 debugging('Unexpected number of open containers: '.open_containers().', expecting '.$THEME->open_header_containers, DEBUG_DEVELOPER);
2946 /// Provide some performance info if required
2947 $performanceinfo = '';
2948 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2949 $perf = get_performance_info();
2950 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
2951 error_log("PERF: " . $perf['txt']);
2953 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
2954 $performanceinfo = $perf['html'];
2958 /// Include the actual footer file
2960 ob_start();
2961 include($CFG->footer);
2962 $output = ob_get_contents();
2963 ob_end_clean();
2965 if ($return) {
2966 return $output;
2967 } else {
2968 echo $output;
2973 * Returns the name of the current theme
2975 * @uses $CFG
2976 * @uses $USER
2977 * @uses $SESSION
2978 * @uses $COURSE
2979 * @uses $FULLME
2980 * @return string
2982 function current_theme() {
2983 global $CFG, $USER, $SESSION, $COURSE, $FULLME;
2985 if (empty($CFG->themeorder)) {
2986 $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
2987 } else {
2988 $themeorder = $CFG->themeorder;
2991 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id) {
2992 require_once($CFG->dirroot.'/mnet/peer.php');
2993 $mnet_peer = new mnet_peer();
2994 $mnet_peer->set_id($USER->mnethostid);
2997 $theme = '';
2998 foreach ($themeorder as $themetype) {
3000 if (!empty($theme)) continue;
3002 switch ($themetype) {
3003 case 'page': // Page theme is for special page-only themes set by code
3004 if (!empty($CFG->pagetheme)) {
3005 $theme = $CFG->pagetheme;
3007 break;
3008 case 'course':
3009 if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) {
3010 $theme = $COURSE->theme;
3012 break;
3013 case 'category':
3014 if (!empty($CFG->allowcategorythemes)) {
3015 /// Nasty hack to check if we're in a category page
3016 if (stripos($FULLME, 'course/category.php') !== false) {
3017 global $id;
3018 if (!empty($id)) {
3019 $theme = current_category_theme($id);
3021 /// Otherwise check if we're in a course that has a category theme set
3022 } else if (!empty($COURSE->category)) {
3023 $theme = current_category_theme($COURSE->category);
3026 break;
3027 case 'session':
3028 if (!empty($SESSION->theme)) {
3029 $theme = $SESSION->theme;
3031 break;
3032 case 'user':
3033 if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) {
3034 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
3035 $theme = $mnet_peer->theme;
3036 } else {
3037 $theme = $USER->theme;
3040 break;
3041 case 'site':
3042 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
3043 $theme = $mnet_peer->theme;
3044 } else {
3045 $theme = $CFG->theme;
3047 break;
3048 default:
3049 /// do nothing
3053 /// A final check in case 'site' was not included in $CFG->themeorder
3054 if (empty($theme)) {
3055 $theme = $CFG->theme;
3058 return $theme;
3062 * Retrieves the category theme if one exists, otherwise checks the parent categories.
3063 * Recursive function.
3065 * @uses $COURSE
3066 * @param integer $categoryid id of the category to check
3067 * @return string theme name
3069 function current_category_theme($categoryid=0) {
3070 global $COURSE;
3072 /// Use the COURSE global if the categoryid not set
3073 if (empty($categoryid)) {
3074 if (!empty($COURSE->category)) {
3075 $categoryid = $COURSE->category;
3076 } else {
3077 return false;
3081 /// Retrieve the current category
3082 if ($category = get_record('course_categories', 'id', $categoryid)) {
3084 /// Return the category theme if it exists
3085 if (!empty($category->theme)) {
3086 return $category->theme;
3088 /// Otherwise try the parent category if one exists
3089 } else if (!empty($category->parent)) {
3090 return current_category_theme($category->parent);
3093 /// Return false if we can't find the category record
3094 } else {
3095 return false;
3100 * This function is called by stylesheets to set up the header
3101 * approriately as well as the current path
3103 * @uses $CFG
3104 * @param int $lastmodified ?
3105 * @param int $lifetime ?
3106 * @param string $thename ?
3108 function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
3110 global $CFG, $THEME;
3112 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
3113 $lastmodified = time();
3115 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
3116 header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
3117 header('Cache-Control: max-age='. $lifetime);
3118 header('Pragma: ');
3119 header('Content-type: text/css'); // Correct MIME type
3121 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
3123 if (empty($themename)) {
3124 $themename = current_theme(); // So we have something. Normally not needed.
3125 } else {
3126 $themename = clean_param($themename, PARAM_SAFEDIR);
3129 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
3130 unset($THEME);
3131 include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
3134 /// If this is the standard theme calling us, then find out what sheets we need
3136 if ($themename == 'standard') {
3137 if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
3138 $THEME->sheets = $DEFAULT_SHEET_LIST;
3139 } else if (empty($THEME->standardsheets)) { // We can stop right now!
3140 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3141 exit;
3142 } else { // Use the provided subset only
3143 $THEME->sheets = $THEME->standardsheets;
3146 /// If we are a parent theme, then check for parent definitions
3148 } else if (!empty($THEME->parent) && $themename == $THEME->parent) {
3149 if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have
3150 $THEME->sheets = $DEFAULT_SHEET_LIST;
3151 } else if (empty($THEME->parentsheets)) { // We can stop right now!
3152 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3153 exit;
3154 } else { // Use the provided subset only
3155 $THEME->sheets = $THEME->parentsheets;
3159 /// Work out the last modified date for this theme
3161 foreach ($THEME->sheets as $sheet) {
3162 if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
3163 $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
3164 if ($sheetmodified > $lastmodified) {
3165 $lastmodified = $sheetmodified;
3171 /// Get a list of all the files we want to include
3172 $files = array();
3174 foreach ($THEME->sheets as $sheet) {
3175 $files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
3178 if ($themename == 'standard') { // Add any standard styles included in any modules
3179 if (!empty($THEME->modsheets)) { // Search for styles.php within activity modules
3180 if ($mods = get_list_of_plugins('mod')) {
3181 foreach ($mods as $mod) {
3182 if (file_exists($CFG->dirroot.'/mod/'.$mod.'/styles.php')) {
3183 $files[] = array($CFG->dirroot, '/mod/'.$mod.'/styles.php');
3189 if (!empty($THEME->blocksheets)) { // Search for styles.php within block modules
3190 if ($mods = get_list_of_plugins('blocks')) {
3191 foreach ($mods as $mod) {
3192 if (file_exists($CFG->dirroot.'/blocks/'.$mod.'/styles.php')) {
3193 $files[] = array($CFG->dirroot, '/blocks/'.$mod.'/styles.php');
3199 if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
3200 if ($mods = get_list_of_plugins('format','',$CFG->dirroot.'/course')) {
3201 foreach ($mods as $mod) {
3202 if (file_exists($CFG->dirroot.'/course/format/'.$mod.'/styles.php')) {
3203 $files[] = array($CFG->dirroot, '/course/format/'.$mod.'/styles.php');
3209 if (!isset($THEME->gradereportsheets) || $THEME->gradereportsheets) { // Search for styles.php in grade reports
3210 if ($reports = get_list_of_plugins('grade/report')) {
3211 foreach ($reports as $report) {
3212 if (file_exists($CFG->dirroot.'/grade/report/'.$report.'/styles.php')) {
3213 $files[] = array($CFG->dirroot, '/grade/report/'.$report.'/styles.php');
3219 if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
3220 if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
3221 $files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
3226 if ($files) {
3227 /// Produce a list of all the files first
3228 echo '/**************************************'."\n";
3229 echo ' * THEME NAME: '.$themename."\n *\n";
3230 echo ' * Files included in this sheet:'."\n *\n";
3231 foreach ($files as $file) {
3232 echo ' * '.$file[1]."\n";
3234 echo ' **************************************/'."\n\n";
3237 /// check if csscobstants is set
3238 if (!empty($THEME->cssconstants)) {
3239 require_once("$CFG->libdir/cssconstants.php");
3240 /// Actually collect all the files in order.
3241 $css = '';
3242 foreach ($files as $file) {
3243 $css .= '/***** '.$file[1].' start *****/'."\n\n";
3244 $css .= file_get_contents($file[0].'/'.$file[1]);
3245 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
3247 /// replace css_constants with their values
3248 echo replace_cssconstants($css);
3249 } else {
3250 /// Actually output all the files in order.
3251 if (empty($CFG->CSSEdit) && empty($THEME->CSSEdit)) {
3252 foreach ($files as $file) {
3253 echo '/***** '.$file[1].' start *****/'."\n\n";
3254 @include_once($file[0].'/'.$file[1]);
3255 echo '/***** '.$file[1].' end *****/'."\n\n";
3257 } else {
3258 foreach ($files as $file) {
3259 echo '/* @group '.$file[1].' */'."\n\n";
3260 if (strstr($file[1], '.css') !== FALSE) {
3261 echo '@import url("'.$CFG->themewww.'/'.$file[1].'");'."\n\n";
3262 } else {
3263 @include_once($file[0].'/'.$file[1]);
3265 echo '/* @end */'."\n\n";
3271 return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
3275 function theme_setup($theme = '', $params=NULL) {
3276 /// Sets up global variables related to themes
3278 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
3280 /// Do not mess with THEME if header already printed - this would break all the extra stuff in global $THEME from print_header()!!
3281 if (defined('HEADER_PRINTED')) {
3282 return;
3285 if (empty($theme)) {
3286 $theme = current_theme();
3289 /// If the theme doesn't exist for some reason then revert to standardwhite
3290 if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
3291 $CFG->theme = $theme = 'standardwhite';
3294 /// Load up the theme config
3295 $THEME = NULL; // Just to be sure
3296 include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
3298 /// Put together the parameters
3299 if (!$params) {
3300 $params = array();
3303 if ($theme != $CFG->theme) {
3304 $params[] = 'forceconfig='.$theme;
3307 /// Force language too if required
3308 if (!empty($THEME->langsheets)) {
3309 $params[] = 'lang='.current_language();
3313 /// Convert params to string
3314 if ($params) {
3315 $paramstring = '?'.implode('&', $params);
3316 } else {
3317 $paramstring = '';
3320 /// Set up image paths
3321 if(isset($CFG->smartpix) && $CFG->smartpix==1) {
3322 if($CFG->slasharguments) { // Use this method if possible for better caching
3323 $extra='';
3324 } else {
3325 $extra='?file=';
3328 $CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
3329 $CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
3330 } else if (empty($THEME->custompix)) { // Could be set in the above file
3331 $CFG->pixpath = $CFG->wwwroot .'/pix';
3332 $CFG->modpixpath = $CFG->wwwroot .'/mod';
3333 } else {
3334 $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
3335 $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
3338 /// Header and footer paths
3339 $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
3340 $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
3342 /// Define stylesheet loading order
3343 $CFG->stylesheets = array();
3344 if ($theme != 'standard') { /// The standard sheet is always loaded first
3345 $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
3347 if (!empty($THEME->parent)) { /// Parent stylesheets are loaded next
3348 $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
3350 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
3352 /// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
3353 if (!empty($HTTPSPAGEREQUIRED)) {
3354 $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
3355 $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
3356 $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
3357 foreach ($CFG->stylesheets as $key => $stylesheet) {
3358 $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
3362 // RTL support - only for RTL languages, add RTL CSS
3363 if (get_string('thisdirection') == 'rtl') {
3364 $CFG->stylesheets[] = $CFG->themewww.'/standard/rtl.css'.$paramstring;
3365 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/rtl.css'.$paramstring;
3371 * Returns text to be displayed to the user which reflects their login status
3373 * @uses $CFG
3374 * @uses $USER
3375 * @param course $course {@link $COURSE} object containing course information
3376 * @param user $user {@link $USER} object containing user information
3377 * @return string
3379 function user_login_string($course=NULL, $user=NULL) {
3380 global $USER, $CFG, $SITE;
3382 if (empty($user) and !empty($USER->id)) {
3383 $user = $USER;
3386 if (empty($course)) {
3387 $course = $SITE;
3390 if (!empty($user->realuser)) {
3391 if ($realuser = get_record('user', 'id', $user->realuser)) {
3392 $fullname = fullname($realuser, true);
3393 $realuserinfo = " [<a $CFG->frametarget
3394 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=1&amp;sesskey=".sesskey()."\">$fullname</a>] ";
3396 } else {
3397 $realuserinfo = '';
3400 if (empty($CFG->loginhttps)) {
3401 $wwwroot = $CFG->wwwroot;
3402 } else {
3403 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
3406 if (empty($course->id)) {
3407 // $course->id is not defined during installation
3408 return '';
3409 } else if (!empty($user->id)) {
3410 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3412 $fullname = fullname($user, true);
3413 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a>";
3414 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid)) {
3415 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
3417 if (isset($user->username) && $user->username == 'guest') {
3418 $loggedinas = $realuserinfo.get_string('loggedinasguest').
3419 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3420 } else if (!empty($user->access['rsw'][$context->path])) {
3421 $rolename = '';
3422 if ($role = get_record('role', 'id', $user->access['rsw'][$context->path])) {
3423 $rolename = ': '.format_string($role->name);
3425 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
3426 " (<a $CFG->frametarget
3427 href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
3428 } else {
3429 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
3430 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
3432 } else {
3433 $loggedinas = get_string('loggedinnot', 'moodle').
3434 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3436 return '<div class="logininfo">'.$loggedinas.'</div>';
3440 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
3441 * If not it applies sensible defaults.
3443 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
3444 * search forum block, etc. Important: these are 'silent' in a screen-reader
3445 * (unlike &gt; &raquo;), and must be accompanied by text.
3446 * @uses $THEME
3448 function check_theme_arrows() {
3449 global $THEME;
3451 if (!isset($THEME->rarrow) and !isset($THEME->larrow)) {
3452 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
3453 // Also OK in Win 9x/2K/IE 5.x
3454 $THEME->rarrow = '&#x25BA;';
3455 $THEME->larrow = '&#x25C4;';
3456 $uagent = $_SERVER['HTTP_USER_AGENT'];
3457 if (false !== strpos($uagent, 'Opera')
3458 || false !== strpos($uagent, 'Mac')) {
3459 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
3460 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
3461 $THEME->rarrow = '&#x25B6;';
3462 $THEME->larrow = '&#x25C0;';
3464 elseif (false !== strpos($uagent, 'Konqueror')) {
3465 $THEME->rarrow = '&rarr;';
3466 $THEME->larrow = '&larr;';
3468 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
3469 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
3470 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
3471 // To be safe, non-Unicode browsers!
3472 $THEME->rarrow = '&gt;';
3473 $THEME->larrow = '&lt;';
3476 /// RTL support - in RTL languages, swap r and l arrows
3477 if (right_to_left()) {
3478 $t = $THEME->rarrow;
3479 $THEME->rarrow = $THEME->larrow;
3480 $THEME->larrow = $t;
3487 * Return the right arrow with text ('next'), and optionally embedded in a link.
3488 * See function above, check_theme_arrows.
3489 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3490 * @param string $url An optional link to use in a surrounding HTML anchor.
3491 * @param bool $accesshide True if text should be hidden (for screen readers only).
3492 * @param string $addclass Additional class names for the link, or the arrow character.
3493 * @return string HTML string.
3495 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
3496 global $THEME;
3497 check_theme_arrows();
3498 $arrowclass = 'arrow ';
3499 if (! $url) {
3500 $arrowclass .= $addclass;
3502 $arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow.'</span>';
3503 $htmltext = '';
3504 if ($text) {
3505 $htmltext = $text.'&nbsp;';
3506 if ($accesshide) {
3507 $htmltext = get_accesshide($htmltext);
3510 if ($url) {
3511 $class = '';
3512 if ($addclass) {
3513 $class =" class=\"$addclass\"";
3515 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
3517 return $htmltext.$arrow;
3521 * Return the left arrow with text ('previous'), and optionally embedded in a link.
3522 * See function above, check_theme_arrows.
3523 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3524 * @param string $url An optional link to use in a surrounding HTML anchor.
3525 * @param bool $accesshide True if text should be hidden (for screen readers only).
3526 * @param string $addclass Additional class names for the link, or the arrow character.
3527 * @return string HTML string.
3529 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
3530 global $THEME;
3531 check_theme_arrows();
3532 $arrowclass = 'arrow ';
3533 if (! $url) {
3534 $arrowclass .= $addclass;
3536 $arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow.'</span>';
3537 $htmltext = '';
3538 if ($text) {
3539 $htmltext = '&nbsp;'.$text;
3540 if ($accesshide) {
3541 $htmltext = get_accesshide($htmltext);
3544 if ($url) {
3545 $class = '';
3546 if ($addclass) {
3547 $class =" class=\"$addclass\"";
3549 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
3551 return $arrow.$htmltext;
3555 * Return a HTML element with the class "accesshide", for accessibility.
3556 * Please use cautiously - where possible, text should be visible!
3557 * @param string $text Plain text.
3558 * @param string $elem Lowercase element name, default "span".
3559 * @param string $class Additional classes for the element.
3560 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
3561 * @return string HTML string.
3563 function get_accesshide($text, $elem='span', $class='', $attrs='') {
3564 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
3568 * Return the breadcrumb trail navigation separator.
3569 * @return string HTML string.
3571 function get_separator() {
3572 //Accessibility: the 'hidden' slash is preferred for screen readers.
3573 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
3577 * Prints breadcrumb trail of links, called in theme/-/header.html
3579 * @uses $CFG
3580 * @param mixed $navigation The breadcrumb navigation string to be printed
3581 * @param string $separator The breadcrumb trail separator. The default 0 leads to the use
3582 * of $THEME->rarrow, themes could use '&rarr;', '/', or '' for a style-sheet solution.
3583 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
3585 function print_navigation ($navigation, $separator=0, $return=false) {
3586 global $CFG, $THEME;
3587 $output = '';
3589 if (0 === $separator) {
3590 $separator = get_separator();
3592 else {
3593 $separator = '<span class="sep">'. $separator .'</span>';
3596 if ($navigation) {
3598 if (is_newnav($navigation)) {
3599 if ($return) {
3600 return($navigation['navlinks']);
3601 } else {
3602 echo $navigation['navlinks'];
3603 return;
3605 } else {
3606 debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER);
3609 if (!is_array($navigation)) {
3610 $ar = explode('->', $navigation);
3611 $navigation = array();
3613 foreach ($ar as $a) {
3614 if (strpos($a, '</a>') === false) {
3615 $navigation[] = array('title' => $a, 'url' => '');
3616 } else {
3617 if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
3618 $navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
3624 if (! $site = get_site()) {
3625 $site = new object();
3626 $site->shortname = get_string('home');
3629 //Accessibility: breadcrumb links now in a list, &raquo; replaced with a 'silent' character.
3630 $output .= get_accesshide(get_string('youarehere','access'), 'h2')."<ul>\n";
3632 $output .= '<li class="first">'."\n".'<a '.$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3633 .$CFG->wwwroot.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))
3634 && !empty($USER->id) && !empty($CFG->mymoodleredirect) && !isguest())
3635 ? '/my' : '') .'/">'. format_string($site->shortname) ."</a>\n</li>\n";
3638 foreach ($navigation as $navitem) {
3639 $title = trim(strip_tags(format_string($navitem['title'], false)));
3640 $url = $navitem['url'];
3642 if (empty($url)) {
3643 $output .= '<li class="first">'."$separator $title</li>\n";
3644 } else {
3645 $output .= '<li class="first">'."$separator\n<a ".$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3646 .$url.'">'."$title</a>\n</li>\n";
3650 $output .= "</ul>\n";
3653 if ($return) {
3654 return $output;
3655 } else {
3656 echo $output;
3661 * This function will build the navigation string to be used by print_header
3662 * and others.
3664 * It automatically generates the site and course level (if appropriate) links.
3666 * If you pass in a $cm object, the method will also generate the activity (e.g. 'Forums')
3667 * and activityinstances (e.g. 'General Developer Forum') navigation levels.
3669 * If you want to add any further navigation links after the ones this function generates,
3670 * the pass an array of extra link arrays like this:
3671 * array(
3672 * array('name' => $linktext1, 'link' => $url1, 'type' => $linktype1),
3673 * array('name' => $linktext2, 'link' => $url2, 'type' => $linktype2)
3675 * The normal case is to just add one further link, for example 'Editing forum' after
3676 * 'General Developer Forum', with no link.
3677 * To do that, you need to pass
3678 * array(array('name' => $linktext, 'link' => '', 'type' => 'title'))
3679 * However, becuase this is a very common case, you can use a shortcut syntax, and just
3680 * pass the string 'Editing forum', instead of an array as $extranavlinks.
3682 * At the moment, the link types only have limited significance. Type 'activity' is
3683 * recognised in order to implement the $CFG->hideactivitytypenavlink feature. Types
3684 * that are known to appear are 'home', 'course', 'activity', 'activityinstance' and 'title'.
3685 * This really needs to be documented better. In the mean time, try to be consistent, it will
3686 * enable people to customise the navigation more in future.
3688 * When passing a $cm object, the fields used are $cm->modname, $cm->name and $cm->course.
3689 * If you get the $cm object using the function get_coursemodule_from_instance or
3690 * get_coursemodule_from_id (as recommended) then this will be done for you automatically.
3691 * If you don't have $cm->modname or $cm->name, this fuction will attempt to find them using
3692 * the $cm->module and $cm->instance fields, but this takes extra database queries, so a
3693 * warning is printed in developer debug mode.
3695 * @uses $CFG
3696 * @uses $THEME
3698 * @param mixed $extranavlinks - Normally an array of arrays, keys: name, link, type. If you
3699 * only want one extra item with no link, you can pass a string instead. If you don't want
3700 * any extra links, pass an empty string.
3701 * @param mixed $cm - optionally the $cm object, if you want this function to generate the
3702 * activity and activityinstance levels of navigation too.
3704 * @return $navigation as an object so it can be differentiated from old style
3705 * navigation strings.
3707 function build_navigation($extranavlinks, $cm = null) {
3708 global $CFG, $COURSE;
3710 if (is_string($extranavlinks)) {
3711 if ($extranavlinks == '') {
3712 $extranavlinks = array();
3713 } else {
3714 $extranavlinks = array(array('name' => $extranavlinks, 'link' => '', 'type' => 'title'));
3718 $navlinks = array();
3720 //Site name
3721 if ($site = get_site()) {
3722 $navlinks[] = array(
3723 'name' => format_string($site->shortname),
3724 'link' => "$CFG->wwwroot/",
3725 'type' => 'home');
3728 // Course name, if appropriate.
3729 if (isset($COURSE) && $COURSE->id != SITEID) {
3730 $navlinks[] = array(
3731 'name' => format_string($COURSE->shortname),
3732 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",
3733 'type' => 'course');
3736 // Activity type and instance, if appropriate.
3737 if (is_object($cm)) {
3738 if (!isset($cm->modname)) {
3739 debugging('The field $cm->modname should be set if you call build_navigation with '.
3740 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3741 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
3742 if (!$cm->modname = get_field('modules', 'name', 'id', $cm->module)) {
3743 error('Cannot get the module type in build navigation.');
3746 if (!isset($cm->name)) {
3747 debugging('The field $cm->name should be set if you call build_navigation with '.
3748 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3749 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
3750 if (!$cm->name = get_field($cm->modname, 'name', 'id', $cm->instance)) {
3751 error('Cannot get the module name in build navigation.');
3754 $navlinks[] = array(
3755 'name' => get_string('modulenameplural', $cm->modname),
3756 'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/index.php?id=' . $cm->course,
3757 'type' => 'activity');
3758 $navlinks[] = array(
3759 'name' => format_string($cm->name),
3760 'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/view.php?id=' . $cm->id,
3761 'type' => 'activityinstance');
3764 //Merge in extra navigation links
3765 $navlinks = array_merge($navlinks, $extranavlinks);
3767 // Work out whether we should be showing the activity (e.g. Forums) link.
3768 // Note: build_navigation() is called from many places --
3769 // install & upgrade for example -- where we cannot count on the
3770 // roles infrastructure to be defined. Hence the $CFG->rolesactive check.
3771 if (!isset($CFG->hideactivitytypenavlink)) {
3772 $CFG->hideactivitytypenavlink = 0;
3774 if ($CFG->hideactivitytypenavlink == 2) {
3775 $hideactivitylink = true;
3776 } else if ($CFG->hideactivitytypenavlink == 1 && $CFG->rolesactive &&
3777 !empty($COURSE->id) && $COURSE->id != SITEID) {
3778 if (!isset($COURSE->context)) {
3779 $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
3781 $hideactivitylink = !has_capability('moodle/course:manageactivities', $COURSE->context);
3782 } else {
3783 $hideactivitylink = false;
3786 //Construct an unordered list from $navlinks
3787 //Accessibility: heading hidden from visual browsers by default.
3788 $navigation = get_accesshide(get_string('youarehere','access'), 'h2')." <ul>\n";
3789 $lastindex = count($navlinks) - 1;
3790 $i = -1; // Used to count the times, so we know when we get to the last item.
3791 $first = true;
3792 foreach ($navlinks as $navlink) {
3793 $i++;
3794 $last = ($i == $lastindex);
3795 if (!is_array($navlink)) {
3796 continue;
3798 if ($navlink['type'] == 'activity' && !$last && $hideactivitylink) {
3799 continue;
3801 $navigation .= '<li class="first">';
3802 if (!$first) {
3803 $navigation .= get_separator();
3805 if ((!empty($navlink['link'])) && !$last) {
3806 $navigation .= "<a onclick=\"this.target='$CFG->framename'\" href=\"{$navlink['link']}\">";
3808 $navigation .= "{$navlink['name']}";
3809 if ((!empty($navlink['link'])) && !$last) {
3810 $navigation .= "</a>";
3813 $navigation .= "</li>";
3814 $first = false;
3816 $navigation .= "</ul>";
3818 return(array('newnav' => true, 'navlinks' => $navigation));
3823 * Prints a string in a specified size (retained for backward compatibility)
3825 * @param string $text The text to be displayed
3826 * @param int $size The size to set the font for text display.
3828 function print_headline($text, $size=2, $return=false) {
3829 $output = print_heading($text, '', $size, true);
3830 if ($return) {
3831 return $output;
3832 } else {
3833 echo $output;
3838 * Prints text in a format for use in headings.
3840 * @param string $text The text to be displayed
3841 * @param string $align The alignment of the printed paragraph of text
3842 * @param int $size The size to set the font for text display.
3844 function print_heading($text, $align='', $size=2, $class='main', $return=false) {
3845 if ($align) {
3846 $align = ' style="text-align:'.$align.';"';
3848 if ($class) {
3849 $class = ' class="'.$class.'"';
3851 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
3853 if ($return) {
3854 return $output;
3855 } else {
3856 echo $output;
3861 * Centered heading with attached help button (same title text)
3862 * and optional icon attached
3864 * @param string $text The text to be displayed
3865 * @param string $helppage The help page to link to
3866 * @param string $module The module whose help should be linked to
3867 * @param string $icon Image to display if needed
3869 function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
3870 $output = '';
3871 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
3872 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
3873 $output .= '</h2>';
3875 if ($return) {
3876 return $output;
3877 } else {
3878 echo $output;
3883 function print_heading_block($heading, $class='', $return=false) {
3884 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
3885 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
3887 if ($return) {
3888 return $output;
3889 } else {
3890 echo $output;
3896 * Print a link to continue on to another page.
3898 * @uses $CFG
3899 * @param string $link The url to create a link to.
3901 function print_continue($link, $return=false) {
3903 global $CFG;
3905 // in case we are logging upgrade in admin/index.php stop it
3906 if (function_exists('upgrade_log_finish')) {
3907 upgrade_log_finish();
3910 $output = '';
3912 if ($link == '') {
3913 if (!empty($_SERVER['HTTP_REFERER'])) {
3914 $link = $_SERVER['HTTP_REFERER'];
3915 $link = str_replace('&', '&amp;', $link); // make it valid XHTML
3916 } else {
3917 $link = $CFG->wwwroot .'/';
3921 $options = array();
3922 $linkparts = parse_url(str_replace('&amp;', '&', $link));
3923 if (isset($linkparts['query'])) {
3924 parse_str($linkparts['query'], $options);
3927 $output .= '<div class="continuebutton">';
3929 $output .= print_single_button($link, $options, get_string('continue'), 'get', $CFG->framename, true);
3930 $output .= '</div>'."\n";
3932 if ($return) {
3933 return $output;
3934 } else {
3935 echo $output;
3941 * Print a message in a standard themed box.
3942 * Replaces print_simple_box (see deprecatedlib.php)
3944 * @param string $message, the content of the box
3945 * @param string $classes, space-separated class names.
3946 * @param string $idbase
3947 * @param boolean $return, return as string or just print it
3948 * @return mixed string or void
3950 function print_box($message, $classes='generalbox', $ids='', $return=false) {
3952 $output = print_box_start($classes, $ids, true);
3953 $output .= stripslashes_safe($message);
3954 $output .= print_box_end(true);
3956 if ($return) {
3957 return $output;
3958 } else {
3959 echo $output;
3964 * Starts a box using divs
3965 * Replaces print_simple_box_start (see deprecatedlib.php)
3967 * @param string $classes, space-separated class names.
3968 * @param string $idbase
3969 * @param boolean $return, return as string or just print it
3970 * @return mixed string or void
3972 function print_box_start($classes='generalbox', $ids='', $return=false) {
3973 global $THEME;
3975 if (strpos($classes, 'clearfix') !== false) {
3976 $clearfix = true;
3977 $classes = trim(str_replace('clearfix', '', $classes));
3978 } else {
3979 $clearfix = false;
3982 if (!empty($THEME->customcorners)) {
3983 $classes .= ' ccbox box';
3984 } else {
3985 $classes .= ' box';
3988 return print_container_start($clearfix, $classes, $ids, $return);
3992 * Simple function to end a box (see above)
3993 * Replaces print_simple_box_end (see deprecatedlib.php)
3995 * @param boolean $return, return as string or just print it
3997 function print_box_end($return=false) {
3998 return print_container_end($return);
4002 * Print a message in a standard themed container.
4004 * @param string $message, the content of the container
4005 * @param boolean $clearfix clear both sides
4006 * @param string $classes, space-separated class names.
4007 * @param string $idbase
4008 * @param boolean $return, return as string or just print it
4009 * @return string or void
4011 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
4013 $output = print_container_start($clearfix, $classes, $idbase, true);
4014 $output .= stripslashes_safe($message);
4015 $output .= print_container_end(true);
4017 if ($return) {
4018 return $output;
4019 } else {
4020 echo $output;
4025 * Starts a container using divs
4027 * @param boolean $clearfix clear both sides
4028 * @param string $classes, space-separated class names.
4029 * @param string $idbase
4030 * @param boolean $return, return as string or just print it
4031 * @return mixed string or void
4033 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
4034 global $THEME;
4036 if (!isset($THEME->open_containers)) {
4037 $THEME->open_containers = array();
4039 $THEME->open_containers[] = $idbase;
4042 if (!empty($THEME->customcorners)) {
4043 $output = _print_custom_corners_start($clearfix, $classes, $idbase);
4044 } else {
4045 if ($idbase) {
4046 $id = ' id="'.$idbase.'"';
4047 } else {
4048 $id = '';
4050 if ($clearfix) {
4051 $clearfix = ' clearfix';
4052 } else {
4053 $clearfix = '';
4055 if ($classes or $clearfix) {
4056 $class = ' class="'.$classes.$clearfix.'"';
4057 } else {
4058 $class = '';
4060 $output = '<div'.$id.$class.'>';
4063 if ($return) {
4064 return $output;
4065 } else {
4066 echo $output;
4071 * Simple function to end a container (see above)
4072 * @param boolean $return, return as string or just print it
4073 * @return mixed string or void
4075 function print_container_end($return=false) {
4076 global $THEME;
4078 if (empty($THEME->open_containers)) {
4079 debugging('Incorrect request to end container - no more open containers.', DEBUG_DEVELOPER);
4080 $idbase = '';
4081 } else {
4082 $idbase = array_pop($THEME->open_containers);
4085 if (!empty($THEME->customcorners)) {
4086 $output = _print_custom_corners_end($idbase);
4087 } else {
4088 $output = '</div>';
4091 if ($return) {
4092 return $output;
4093 } else {
4094 echo $output;
4099 * Returns number of currently open containers
4100 * @return int number of open containers
4102 function open_containers() {
4103 global $THEME;
4105 if (!isset($THEME->open_containers)) {
4106 $THEME->open_containers = array();
4109 return count($THEME->open_containers);
4113 * Force closing of open containers
4114 * @param boolean $return, return as string or just print it
4115 * @param int $keep number of containers to be kept open - usually theme or page containers
4116 * @return mixed string or void
4118 function print_container_end_all($return=false, $keep=0) {
4119 $output = '';
4120 while (open_containers() > $keep) {
4121 $output .= print_container_end($return);
4124 if ($return) {
4125 return $output;
4126 } else {
4127 echo $output;
4132 * Internal function - do not use directly!
4133 * Starting part of the surrounding divs for custom corners
4135 * @param boolean $clearfix, add CLASS "clearfix" to the inner div against collapsing
4136 * @param string $classes
4137 * @param mixed $idbase, optionally, define one idbase to be added to all the elements in the corners
4138 * @return string
4140 function _print_custom_corners_start($clearfix=false, $classes='', $idbase='') {
4141 /// Analise if we want ids for the custom corner elements
4142 $id = '';
4143 $idbt = '';
4144 $idi1 = '';
4145 $idi2 = '';
4146 $idi3 = '';
4148 if ($idbase) {
4149 $id = 'id="'.$idbase.'" ';
4150 $idbt = 'id="'.$idbase.'-bt" ';
4151 $idi1 = 'id="'.$idbase.'-i1" ';
4152 $idi2 = 'id="'.$idbase.'-i2" ';
4153 $idi3 = 'id="'.$idbase.'-i3" ';
4156 /// Calculate current level
4157 $level = open_containers();
4159 /// Output begins
4160 $output = '<div '.$id.'class="wrap wraplevel'.$level.' '.$classes.'">'."\n";
4161 $output .= '<div '.$idbt.'class="bt"><div>&nbsp;</div></div>';
4162 $output .= "\n";
4163 $output .= '<div '.$idi1.'class="i1"><div '.$idi2.'class="i2">';
4164 $output .= (!empty($clearfix)) ? '<div '.$idi3.'class="i3 clearfix">' : '<div '.$idi3.'class="i3">';
4166 return $output;
4171 * Internal function - do not use directly!
4172 * Ending part of the surrounding divs for custom corners
4173 * @param string $idbase
4174 * @return string
4176 function _print_custom_corners_end($idbase) {
4177 /// Analise if we want ids for the custom corner elements
4178 $idbb = '';
4180 if ($idbase) {
4181 $idbb = 'id="' . $idbase . '-bb" ';
4184 /// Output begins
4185 $output = '</div></div></div>';
4186 $output .= "\n";
4187 $output .= '<div '.$idbb.'class="bb"><div>&nbsp;</div></div>'."\n";
4188 $output .= '</div>';
4190 return $output;
4195 * Print a self contained form with a single submit button.
4197 * @param string $link used as the action attribute on the form, so the URL that will be hit if the button is clicked.
4198 * @param array $options these become hidden form fields, so these options get passed to the script at $link.
4199 * @param string $label the caption that appears on the button.
4200 * @param string $method HTTP method used on the request of the button is clicked. 'get' or 'post'.
4201 * @param string $target no longer used.
4202 * @param boolean $return if false, output the form directly, otherwise return the HTML as a string.
4203 * @param string $tooltip a tooltip to add to the button as a title attribute.
4204 * @param boolean $disabled if true, the button will be disabled.
4205 * @param string $jsconfirmmessage if not empty then display a confirm dialogue with this string as the question.
4206 * @return string / nothing depending on the $return paramter.
4208 function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='', $disabled = false, $jsconfirmmessage='') {
4209 $output = '';
4210 $link = str_replace('"', '&quot;', $link); //basic XSS protection
4211 $output .= '<div class="singlebutton">';
4212 // taking target out, will need to add later target="'.$target.'"
4213 $output .= '<form action="'. $link .'" method="'. $method .'">';
4214 $output .= '<div>';
4215 if ($options) {
4216 foreach ($options as $name => $value) {
4217 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
4220 if ($tooltip) {
4221 $tooltip = 'title="' . s($tooltip) . '"';
4222 } else {
4223 $tooltip = '';
4225 if ($disabled) {
4226 $disabled = 'disabled="disabled"';
4227 } else {
4228 $disabled = '';
4230 if ($jsconfirmmessage){
4231 $jsconfirmmessage = addslashes_js($jsconfirmmessage);
4232 $jsconfirmmessage = 'onclick="return confirm(\''. $jsconfirmmessage .'\');" ';
4234 $output .= '<input type="submit" value="'. s($label) ."\" $tooltip $disabled $jsconfirmmessage/></div></form></div>";
4236 if ($return) {
4237 return $output;
4238 } else {
4239 echo $output;
4245 * Print a spacer image with the option of including a line break.
4247 * @param int $height ?
4248 * @param int $width ?
4249 * @param boolean $br ?
4250 * @todo Finish documenting this function
4252 function print_spacer($height=1, $width=1, $br=true, $return=false) {
4253 global $CFG;
4254 $output = '';
4256 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot .'/pix/spacer.gif" alt="" />';
4257 if ($br) {
4258 $output .= '<br />'."\n";
4261 if ($return) {
4262 return $output;
4263 } else {
4264 echo $output;
4269 * Given the path to a picture file in a course, or a URL,
4270 * this function includes the picture in the page.
4272 * @param string $path ?
4273 * @param int $courseid ?
4274 * @param int $height ?
4275 * @param int $width ?
4276 * @param string $link ?
4277 * @todo Finish documenting this function
4279 function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
4280 global $CFG;
4281 $output = '';
4283 if ($height) {
4284 $height = 'height="'. $height .'"';
4286 if ($width) {
4287 $width = 'width="'. $width .'"';
4289 if ($link) {
4290 $output .= '<a href="'. $link .'">';
4292 if (substr(strtolower($path), 0, 7) == 'http://') {
4293 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
4295 } else if ($courseid) {
4296 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
4297 if ($CFG->slasharguments) { // Use this method if possible for better caching
4298 $output .= $CFG->wwwroot .'/file.php/'. $courseid .'/'. $path;
4299 } else {
4300 $output .= $CFG->wwwroot .'/file.php?file=/'. $courseid .'/'. $path;
4302 $output .= '" />';
4303 } else {
4304 $output .= 'Error: must pass URL or course';
4306 if ($link) {
4307 $output .= '</a>';
4310 if ($return) {
4311 return $output;
4312 } else {
4313 echo $output;
4318 * Print the specified user's avatar.
4320 * If you pass a $user object that has id, picture, imagealt, firstname, lastname
4321 * you save a DB query.
4323 * @param int $user takes a userid, or a userobj
4324 * @param int $courseid ?
4325 * @param boolean $picture Print the user picture?
4326 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
4327 * @param boolean $return If false print picture to current page, otherwise return the output as string
4328 * @param boolean $link Enclose printed image in a link to view specified course?
4329 * @param string $target link target attribute
4330 * @param boolean $alttext use username or userspecified text in image alt attribute
4331 * return string
4332 * @todo Finish documenting this function
4334 function print_user_picture($user, $courseid, $picture=NULL, $size=0, $return=false, $link=true, $target='', $alttext=true) {
4335 global $CFG, $HTTPSPAGEREQUIRED;
4337 $needrec = false;
4338 // only touch the DB if we are missing data...
4339 if (is_object($user)) {
4340 // Note - both picture and imagealt _can_ be empty
4341 // what we are trying to see here is if they have been fetched
4342 // from the DB. We should use isset() _except_ that some installs
4343 // have those fields as nullable, and isset() will return false
4344 // on null. The only safe thing is to ask array_key_exists()
4345 // which works on objects. property_exists() isn't quite
4346 // what we want here...
4347 if (! (array_key_exists('picture', $user)
4348 && ($alttext && array_key_exists('imagealt', $user)
4349 || (isset($user->firstname) && isset($user->lastname)))) ) {
4350 $needrec = true;
4351 $user = $user->id;
4353 } else {
4354 if ($alttext) {
4355 // we need firstname, lastname, imagealt, can't escape...
4356 $needrec = true;
4357 } else {
4358 $userobj = new StdClass; // fake it to save DB traffic
4359 $userobj->id = $user;
4360 $userobj->picture = $picture;
4361 $user = clone($userobj);
4362 unset($userobj);
4365 if ($needrec) {
4366 $user = get_record('user','id',$user, '', '', '', '', 'id,firstname,lastname,imagealt');
4369 if ($link) {
4370 $url = '/user/view.php?id='. $user->id .'&amp;course='. $courseid ;
4371 if ($target) {
4372 $target='onclick="return openpopup(\''.$url.'\');"';
4374 $output = '<a '.$target.' href="'. $CFG->wwwroot . $url .'">';
4375 } else {
4376 $output = '';
4378 if (empty($size)) {
4379 $file = 'f2';
4380 $size = 35;
4381 } else if ($size === true or $size == 1) {
4382 $file = 'f1';
4383 $size = 100;
4384 } else if ($size >= 50) {
4385 $file = 'f1';
4386 } else {
4387 $file = 'f2';
4389 $class = "userpicture";
4390 if (!empty($HTTPSPAGEREQUIRED)) {
4391 $wwwroot = $CFG->httpswwwroot;
4392 } else {
4393 $wwwroot = $CFG->wwwroot;
4396 if (is_null($picture)) {
4397 $picture = $user->picture;
4400 if ($picture) { // Print custom user picture
4401 if ($CFG->slasharguments) { // Use this method if possible for better caching
4402 $src = $wwwroot .'/user/pix.php/'. $user->id .'/'. $file .'.jpg';
4403 } else {
4404 $src = $wwwroot .'/user/pix.php?file=/'. $user->id .'/'. $file .'.jpg';
4406 } else { // Print default user pictures (use theme version if available)
4407 $class .= " defaultuserpic";
4408 $src = "$CFG->pixpath/u/$file.png";
4410 $imagealt = '';
4411 if ($alttext) {
4412 if (!empty($user->imagealt)) {
4413 $imagealt = $user->imagealt;
4414 } else {
4415 $imagealt = get_string('pictureof','',fullname($user));
4419 $output .= '<img class="'.$class.'" src="'.$src.'" alt="'.s($imagealt).'" />';
4420 if ($link) {
4421 $output .= '</a>';
4424 if ($return) {
4425 return $output;
4426 } else {
4427 echo $output;
4432 * Prints a summary of a user in a nice little box.
4434 * @uses $CFG
4435 * @uses $USER
4436 * @param user $user A {@link $USER} object representing a user
4437 * @param course $course A {@link $COURSE} object representing a course
4439 function print_user($user, $course, $messageselect=false, $return=false) {
4441 global $CFG, $USER;
4443 $output = '';
4445 static $string;
4446 static $datestring;
4447 static $countries;
4449 $context = get_context_instance(CONTEXT_COURSE, $course->id);
4450 if (isset($user->context->id)) {
4451 $usercontext = get_context_instance_by_id($user->context->id);
4454 if (empty($string)) { // Cache all the strings for the rest of the page
4456 $string->email = get_string('email');
4457 $string->city = get_string('city');
4458 $string->lastaccess = get_string('lastaccess');
4459 $string->activity = get_string('activity');
4460 $string->unenrol = get_string('unenrol');
4461 $string->loginas = get_string('loginas');
4462 $string->fullprofile = get_string('fullprofile');
4463 $string->role = get_string('role');
4464 $string->name = get_string('name');
4465 $string->never = get_string('never');
4467 $datestring->day = get_string('day');
4468 $datestring->days = get_string('days');
4469 $datestring->hour = get_string('hour');
4470 $datestring->hours = get_string('hours');
4471 $datestring->min = get_string('min');
4472 $datestring->mins = get_string('mins');
4473 $datestring->sec = get_string('sec');
4474 $datestring->secs = get_string('secs');
4475 $datestring->year = get_string('year');
4476 $datestring->years = get_string('years');
4478 $countries = get_list_of_countries();
4481 /// Get the hidden field list
4482 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
4483 $hiddenfields = array();
4484 } else {
4485 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
4488 $output .= '<table class="userinfobox">';
4489 $output .= '<tr>';
4490 $output .= '<td class="left side">';
4491 $output .= print_user_picture($user, $course->id, $user->picture, true, true);
4492 $output .= '</td>';
4493 $output .= '<td class="content">';
4494 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
4495 $output .= '<div class="info">';
4496 if (!empty($user->role) and ($user->role <> $course->teacher)) {
4497 $output .= $string->role .': '. $user->role .'<br />';
4499 if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguest()) or
4500 has_capability('moodle/course:viewhiddenuserfields', $context)) {
4501 $output .= $string->email .': <a href="mailto:'. $user->email .'">'. $user->email .'</a><br />';
4503 if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
4504 $output .= $string->city .': ';
4505 if ($user->city && !isset($hiddenfields['city'])) {
4506 $output .= $user->city;
4508 if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
4509 if ($user->city && !isset($hiddenfields['city'])) {
4510 $output .= ', ';
4512 $output .= $countries[$user->country];
4514 $output .= '<br />';
4517 if (!isset($hiddenfields['lastaccess'])) {
4518 if ($user->lastaccess) {
4519 $output .= $string->lastaccess .': '. userdate($user->lastaccess);
4520 $output .= '&nbsp; ('. format_time(time() - $user->lastaccess, $datestring) .')';
4521 } else {
4522 $output .= $string->lastaccess .': '. $string->never;
4525 $output .= '</div></td><td class="links">';
4526 //link to blogs
4527 if ($CFG->bloglevel > 0) {
4528 $output .= '<a href="'.$CFG->wwwroot.'/blog/index.php?userid='.$user->id.'">'.get_string('blogs','blog').'</a><br />';
4530 //link to notes
4531 if (has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context)) {
4532 $output .= '<a href="'.$CFG->wwwroot.'/notes/index.php?course=' . $course->id. '&amp;user='.$user->id.'">'.get_string('notes','notes').'</a><br />';
4535 if (has_capability('moodle/user:viewuseractivitiesreport', $context) || (isset($usercontext) && has_capability('moodle/user:viewuseractivitiesreport', $usercontext))) {
4536 $timemidnight = usergetmidnight(time());
4537 $output .= '<a href="'. $CFG->wwwroot .'/course/user.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->activity .'</a><br />';
4539 if (has_capability('moodle/role:assign', $context, NULL)) { // Includes admins
4540 $output .= '<a href="'. $CFG->wwwroot .'/course/unenrol.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->unenrol .'</a><br />';
4542 if ($USER->id != $user->id && empty($USER->realuser) && has_capability('moodle/user:loginas', $context) &&
4543 ! has_capability('moodle/site:doanything', $context, $user->id, false)) {
4544 $output .= '<a href="'. $CFG->wwwroot .'/course/loginas.php?id='. $course->id .'&amp;user='. $user->id .'&amp;sesskey='. sesskey() .'">'. $string->loginas .'</a><br />';
4546 $output .= '<a href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&amp;course='. $course->id .'">'. $string->fullprofile .'...</a>';
4548 if (!empty($messageselect)) {
4549 $output .= '<br /><input type="checkbox" name="user'.$user->id.'" /> ';
4552 $output .= '</td></tr></table>';
4554 if ($return) {
4555 return $output;
4556 } else {
4557 echo $output;
4562 * Print a specified group's avatar.
4564 * @param group $group A single {@link group} object OR array of groups.
4565 * @param int $courseid The course ID.
4566 * @param boolean $large Default small picture, or large.
4567 * @param boolean $return If false print picture, otherwise return the output as string
4568 * @param boolean $link Enclose image in a link to view specified course?
4569 * @return string
4570 * @todo Finish documenting this function
4572 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
4573 global $CFG;
4575 if (is_array($group)) {
4576 $output = '';
4577 foreach($group as $g) {
4578 $output .= print_group_picture($g, $courseid, $large, true, $link);
4580 if ($return) {
4581 return $output;
4582 } else {
4583 echo $output;
4584 return;
4588 $context = get_context_instance(CONTEXT_COURSE, $courseid);
4590 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
4591 return '';
4594 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4595 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
4596 } else {
4597 $output = '';
4599 if ($large) {
4600 $file = 'f1';
4601 $size = 100;
4602 } else {
4603 $file = 'f2';
4604 $size = 35;
4606 if ($group->picture) { // Print custom group picture
4607 if ($CFG->slasharguments) { // Use this method if possible for better caching
4608 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot.'/user/pixgroup.php/'.$group->id.'/'.$file.'.jpg"'.
4609 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
4610 } else {
4611 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot.'/user/pixgroup.php?file=/'.$group->id.'/'.$file.'.jpg"'.
4612 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
4615 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4616 $output .= '</a>';
4619 if ($return) {
4620 return $output;
4621 } else {
4622 echo $output;
4627 * Print a png image.
4629 * @param string $url ?
4630 * @param int $sizex ?
4631 * @param int $sizey ?
4632 * @param boolean $return ?
4633 * @param string $parameters ?
4634 * @todo Finish documenting this function
4636 function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
4637 global $CFG;
4638 static $recentIE;
4640 if (!isset($recentIE)) {
4641 $recentIE = check_browser_version('MSIE', '5.0');
4644 if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
4645 $output .= '<img src="'. $CFG->pixpath .'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
4646 ' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
4647 ' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
4648 "'$url', sizingMethod='scale') ".
4649 ' '. $parameters .' />';
4650 } else {
4651 $output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
4654 if ($return) {
4655 return $output;
4656 } else {
4657 echo $output;
4662 * Print a nicely formatted table.
4664 * @param array $table is an object with several properties.
4665 * <ul>
4666 * <li>$table->head - An array of heading names.
4667 * <li>$table->align - An array of column alignments
4668 * <li>$table->size - An array of column sizes
4669 * <li>$table->wrap - An array of "nowrap"s or nothing
4670 * <li>$table->data[] - An array of arrays containing the data.
4671 * <li>$table->width - A percentage of the page
4672 * <li>$table->tablealign - Align the whole table
4673 * <li>$table->cellpadding - Padding on each cell
4674 * <li>$table->cellspacing - Spacing between cells
4675 * <li>$table->class - class attribute to put on the table
4676 * <li>$table->id - id attribute to put on the table.
4677 * <li>$table->rowclass[] - classes to add to particular rows.
4678 * <li>$table->summary - Description of the contents for screen readers.
4679 * </ul>
4680 * @param bool $return whether to return an output string or echo now
4681 * @return boolean or $string
4682 * @todo Finish documenting this function
4684 function print_table($table, $return=false) {
4685 $output = '';
4687 if (isset($table->align)) {
4688 foreach ($table->align as $key => $aa) {
4689 if ($aa) {
4690 $align[$key] = ' text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
4691 } else {
4692 $align[$key] = '';
4696 if (isset($table->size)) {
4697 foreach ($table->size as $key => $ss) {
4698 if ($ss) {
4699 $size[$key] = ' width:'. $ss .';';
4700 } else {
4701 $size[$key] = '';
4705 if (isset($table->wrap)) {
4706 foreach ($table->wrap as $key => $ww) {
4707 if ($ww) {
4708 $wrap[$key] = ' white-space:nowrap;';
4709 } else {
4710 $wrap[$key] = '';
4715 if (empty($table->width)) {
4716 $table->width = '80%';
4719 if (empty($table->tablealign)) {
4720 $table->tablealign = 'center';
4723 if (!isset($table->cellpadding)) {
4724 $table->cellpadding = '5';
4727 if (!isset($table->cellspacing)) {
4728 $table->cellspacing = '1';
4731 if (empty($table->class)) {
4732 $table->class = 'generaltable';
4735 $tableid = empty($table->id) ? '' : 'id="'.$table->id.'"';
4737 $output .= '<table width="'.$table->width.'" ';
4738 if (!empty($table->summary)) {
4739 $output .= " summary=\"$table->summary\"";
4741 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
4743 $countcols = 0;
4745 if (!empty($table->head)) {
4746 $countcols = count($table->head);
4747 $output .= '<tr>';
4748 $lastkey = end(array_keys($table->head));
4749 foreach ($table->head as $key => $heading) {
4751 if (!isset($size[$key])) {
4752 $size[$key] = '';
4754 if (!isset($align[$key])) {
4755 $align[$key] = '';
4757 if ($key == $lastkey) {
4758 $extraclass = ' lastcol';
4759 } else {
4760 $extraclass = '';
4763 $output .= '<th style="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.$extraclass.'" scope="col">'. $heading .'</th>';
4765 $output .= '</tr>'."\n";
4768 if (!empty($table->data)) {
4769 $oddeven = 1;
4770 $lastrowkey = end(array_keys($table->data));
4771 foreach ($table->data as $key => $row) {
4772 $oddeven = $oddeven ? 0 : 1;
4773 if (!isset($table->rowclass[$key])) {
4774 $table->rowclass[$key] = '';
4776 if ($key == $lastrowkey) {
4777 $table->rowclass[$key] .= ' lastrow';
4779 $output .= '<tr class="r'.$oddeven.' '.$table->rowclass[$key].'">'."\n";
4780 if ($row == 'hr' and $countcols) {
4781 $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
4782 } else { /// it's a normal row of data
4783 $lastkey = end(array_keys($row));
4784 foreach ($row as $key => $item) {
4785 if (!isset($size[$key])) {
4786 $size[$key] = '';
4788 if (!isset($align[$key])) {
4789 $align[$key] = '';
4791 if (!isset($wrap[$key])) {
4792 $wrap[$key] = '';
4794 if ($key == $lastkey) {
4795 $extraclass = ' lastcol';
4796 } else {
4797 $extraclass = '';
4799 $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.$extraclass.'">'. $item .'</td>';
4802 $output .= '</tr>'."\n";
4805 $output .= '</table>'."\n";
4807 if ($return) {
4808 return $output;
4811 echo $output;
4812 return true;
4815 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
4816 static $strftimerecent = null;
4817 $output = '';
4819 if (is_null($viewfullnames)) {
4820 $context = get_context_instance(CONTEXT_SYSTEM);
4821 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
4824 if (is_null($strftimerecent)) {
4825 $strftimerecent = get_string('strftimerecent');
4828 $output .= '<div class="head">';
4829 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
4830 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
4831 $output .= '</div>';
4832 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
4834 if ($return) {
4835 return $output;
4836 } else {
4837 echo $output;
4843 * Prints a basic textarea field.
4845 * @uses $CFG
4846 * @param boolean $usehtmleditor ?
4847 * @param int $rows ?
4848 * @param int $cols ?
4849 * @param null $width <b>Legacy field no longer used!</b> Set to zero to get control over mincols
4850 * @param null $height <b>Legacy field no longer used!</b> Set to zero to get control over minrows
4851 * @param string $name ?
4852 * @param string $value ?
4853 * @param int $courseid ?
4854 * @todo Finish documenting this function
4856 function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $courseid=0, $return=false, $id='') {
4857 /// $width and height are legacy fields and no longer used as pixels like they used to be.
4858 /// However, you can set them to zero to override the mincols and minrows values below.
4860 global $CFG, $COURSE, $HTTPSPAGEREQUIRED;
4861 static $scriptcount = 0; // For loading the htmlarea script only once.
4863 $mincols = 65;
4864 $minrows = 10;
4865 $str = '';
4867 if ($id === '') {
4868 $id = 'edit-'.$name;
4871 if ( empty($CFG->editorsrc) ) { // for backward compatibility.
4872 if (empty($courseid)) {
4873 $courseid = $COURSE->id;
4876 if ($usehtmleditor) {
4877 if (!empty($courseid) and has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE, $courseid))) {
4878 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '&amp;httpsrequired=1';
4879 // needed for course file area browsing in image insert plugin
4880 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4881 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php?id='.$courseid.$httpsrequired.'"></script>'."\n" : '';
4882 } else {
4883 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '?httpsrequired=1';
4884 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4885 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php'.$httpsrequired.'"></script>'."\n" : '';
4888 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4889 $CFG->httpswwwroot .'/lib/editor/htmlarea/lang/en.php"></script>'."\n" : '';
4890 $scriptcount++;
4892 if ($height) { // Usually with legacy calls
4893 if ($rows < $minrows) {
4894 $rows = $minrows;
4897 if ($width) { // Usually with legacy calls
4898 if ($cols < $mincols) {
4899 $cols = $mincols;
4904 $str .= '<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">';
4905 if ($usehtmleditor) {
4906 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
4907 } else {
4908 $str .= s($value);
4910 $str .= '</textarea>'."\n";
4912 if ($usehtmleditor) {
4913 // Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
4914 $str .= '<script type="text/javascript">
4915 //<![CDATA[
4916 document.write(\''.addslashes_js(editorshortcutshelpbutton()).'\');
4917 //]]>
4918 </script>';
4921 if ($return) {
4922 return $str;
4924 echo $str;
4928 * Sets up the HTML editor on textareas in the current page.
4929 * If a field name is provided, then it will only be
4930 * applied to that field - otherwise it will be used
4931 * on every textarea in the page.
4933 * In most cases no arguments need to be supplied
4935 * @param string $name Form element to replace with HTMl editor by name
4937 function use_html_editor($name='', $editorhidebuttons='', $id='') {
4938 global $THEME;
4940 $editor = 'editor_'.md5($name); //name might contain illegal characters
4941 if ($id === '') {
4942 $id = 'edit-'.$name;
4944 echo "\n".'<script type="text/javascript" defer="defer">'."\n";
4945 echo '//<![CDATA['."\n\n"; // Extra \n is to fix odd wiki problem, MDL-8185
4946 echo "$editor = new HTMLArea('$id');\n";
4947 echo "var config = $editor.config;\n";
4949 echo print_editor_config($editorhidebuttons);
4951 if (empty($THEME->htmleditorpostprocess)) {
4952 if (empty($name)) {
4953 echo "\nHTMLArea.replaceAll($editor.config);\n";
4954 } else {
4955 echo "\n$editor.generate();\n";
4957 } else {
4958 if (empty($name)) {
4959 echo "\nvar HTML_name = '';";
4960 } else {
4961 echo "\nvar HTML_name = \"$name;\"";
4963 echo "\nvar HTML_editor = $editor;";
4965 echo '//]]>'."\n";
4966 echo '</script>'."\n";
4969 function print_editor_config($editorhidebuttons='', $return=false) {
4970 global $CFG;
4972 $str = "config.pageStyle = \"body {";
4974 if (!(empty($CFG->editorbackgroundcolor))) {
4975 $str .= " background-color: $CFG->editorbackgroundcolor;";
4978 if (!(empty($CFG->editorfontfamily))) {
4979 $str .= " font-family: $CFG->editorfontfamily;";
4982 if (!(empty($CFG->editorfontsize))) {
4983 $str .= " font-size: $CFG->editorfontsize;";
4986 $str .= " }\";\n";
4987 $str .= "config.killWordOnPaste = ";
4988 $str .= (empty($CFG->editorkillword)) ? "false":"true";
4989 $str .= ';'."\n";
4990 $str .= 'config.fontname = {'."\n";
4992 $fontlist = isset($CFG->editorfontlist) ? explode(';', $CFG->editorfontlist) : array();
4993 $i = 1; // Counter is used to get rid of the last comma.
4995 foreach ($fontlist as $fontline) {
4996 if (!empty($fontline)) {
4997 if ($i > 1) {
4998 $str .= ','."\n";
5000 list($fontkey, $fontvalue) = split(':', $fontline);
5001 $str .= '"'. $fontkey ."\":\t'". $fontvalue ."'";
5003 $i++;
5006 $str .= '};';
5008 if (!empty($editorhidebuttons)) {
5009 $str .= "\nconfig.hideSomeButtons(\" ". $editorhidebuttons ." \");\n";
5010 } else if (!empty($CFG->editorhidebuttons)) {
5011 $str .= "\nconfig.hideSomeButtons(\" ". $CFG->editorhidebuttons ." \");\n";
5014 if (!empty($CFG->editorspelling) && !empty($CFG->aspellpath)) {
5015 $str .= print_speller_code($CFG->htmleditor, true);
5018 if ($return) {
5019 return $str;
5021 echo $str;
5025 * Returns a turn edit on/off button for course in a self contained form.
5026 * Used to be an icon, but it's now a simple form button
5028 * Note that the caller is responsible for capchecks.
5030 * @uses $CFG
5031 * @uses $USER
5032 * @param int $courseid The course to update by id as found in 'course' table
5033 * @return string
5035 function update_course_icon($courseid) {
5036 global $CFG, $USER;
5038 if (!empty($USER->editing)) {
5039 $string = get_string('turneditingoff');
5040 $edit = '0';
5041 } else {
5042 $string = get_string('turneditingon');
5043 $edit = '1';
5046 return '<form '.$CFG->frametarget.' method="get" action="'.$CFG->wwwroot.'/course/view.php">'.
5047 '<div>'.
5048 '<input type="hidden" name="id" value="'.$courseid.'" />'.
5049 '<input type="hidden" name="edit" value="'.$edit.'" />'.
5050 '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
5051 '<input type="submit" value="'.$string.'" />'.
5052 '</div></form>';
5056 * Returns a little popup menu for switching roles
5058 * @uses $CFG
5059 * @uses $USER
5060 * @param int $courseid The course to update by id as found in 'course' table
5061 * @return string
5063 function switchroles_form($courseid) {
5065 global $CFG, $USER;
5068 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
5069 return '';
5072 if (!empty($USER->access['rsw'][$context->path])){ // Just a button to return to normal
5073 $options = array();
5074 $options['id'] = $courseid;
5075 $options['sesskey'] = sesskey();
5076 $options['switchrole'] = 0;
5078 return print_single_button($CFG->wwwroot.'/course/view.php', $options,
5079 get_string('switchrolereturn'), 'post', '_self', true);
5082 if (has_capability('moodle/role:switchroles', $context)) {
5083 if (!$roles = get_assignable_roles_for_switchrole($context)) {
5084 return ''; // Nothing to show!
5086 // unset default user role - it would not work
5087 unset($roles[$CFG->guestroleid]);
5088 return popup_form($CFG->wwwroot.'/course/view.php?id='.$courseid.'&amp;sesskey='.sesskey().'&amp;switchrole=',
5089 $roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
5092 return '';
5097 * Returns a turn edit on/off button for course in a self contained form.
5098 * Used to be an icon, but it's now a simple form button
5100 * @uses $CFG
5101 * @uses $USER
5102 * @param int $courseid The course to update by id as found in 'course' table
5103 * @return string
5105 function update_mymoodle_icon() {
5107 global $CFG, $USER;
5109 if (!empty($USER->editing)) {
5110 $string = get_string('updatemymoodleoff');
5111 $edit = '0';
5112 } else {
5113 $string = get_string('updatemymoodleon');
5114 $edit = '1';
5117 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
5118 "<div>".
5119 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5120 "<input type=\"submit\" value=\"$string\" /></div></form>";
5124 * Returns a turn edit on/off button for tag in a self contained form.
5126 * @uses $CFG
5127 * @uses $USER
5128 * @return string
5130 function update_tag_button($tagid) {
5132 global $CFG, $USER;
5134 if (!empty($USER->editing)) {
5135 $string = get_string('turneditingoff');
5136 $edit = '0';
5137 } else {
5138 $string = get_string('turneditingon');
5139 $edit = '1';
5142 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/tag/index.php\">".
5143 "<div>".
5144 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5145 "<input type=\"hidden\" name=\"id\" value=\"$tagid\" />".
5146 "<input type=\"submit\" value=\"$string\" /></div></form>";
5150 * Prints the editing button on a module "view" page
5152 * @uses $CFG
5153 * @param type description
5154 * @todo Finish documenting this function
5156 function update_module_button($moduleid, $courseid, $string) {
5157 global $CFG, $USER;
5159 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $moduleid))) {
5160 $string = get_string('updatethis', '', $string);
5162 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
5163 "<div>".
5164 "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
5165 "<input type=\"hidden\" name=\"return\" value=\"true\" />".
5166 "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
5167 "<input type=\"submit\" value=\"$string\" /></div></form>";
5168 } else {
5169 return '';
5174 * Prints the editing button on a category page
5176 * @uses $CFG
5177 * @uses $USER
5178 * @param int $categoryid ?
5179 * @return string
5180 * @todo Finish documenting this function
5182 function update_category_button($categoryid) {
5183 global $CFG, $USER;
5185 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_COURSECAT, $categoryid))) {
5186 if (!empty($USER->categoryediting)) {
5187 $string = get_string('turneditingoff');
5188 $edit = 'off';
5189 } else {
5190 $string = get_string('turneditingon');
5191 $edit = 'on';
5194 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/category.php\">".
5195 '<div>'.
5196 "<input type=\"hidden\" name=\"id\" value=\"$categoryid\" />".
5197 "<input type=\"hidden\" name=\"categoryedit\" value=\"$edit\" />".
5198 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5199 "<input type=\"submit\" value=\"$string\" /></div></form>";
5204 * Prints the editing button on categories listing
5206 * @uses $CFG
5207 * @uses $USER
5208 * @return string
5210 function update_categories_button() {
5211 global $CFG, $USER;
5213 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM))) {
5214 if (!empty($USER->categoryediting)) {
5215 $string = get_string('turneditingoff');
5216 $categoryedit = 'off';
5217 } else {
5218 $string = get_string('turneditingon');
5219 $categoryedit = 'on';
5222 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/index.php\">".
5223 '<div>'.
5224 '<input type="hidden" name="categoryedit" value="'. $categoryedit .'" />'.
5225 '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />'.
5226 '<input type="submit" value="'. $string .'" /></div></form>';
5231 * Prints the editing button on search results listing
5232 * For bulk move courses to another category
5235 function update_categories_search_button($search,$page,$perpage) {
5236 global $CFG, $USER;
5238 // not sure if this capability is the best here
5239 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM))) {
5240 if (!empty($USER->categoryediting)) {
5241 $string = get_string("turneditingoff");
5242 $edit = "off";
5243 $perpage = 30;
5244 } else {
5245 $string = get_string("turneditingon");
5246 $edit = "on";
5249 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
5250 '<div>'.
5251 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5252 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5253 "<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
5254 "<input type=\"hidden\" name=\"page\" value=\"$page\" />".
5255 "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
5256 "<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
5261 * Given a course and a (current) coursemodule
5262 * This function returns a small popup menu with all the
5263 * course activity modules in it, as a navigation menu
5264 * The data is taken from the serialised array stored in
5265 * the course record
5267 * @param course $course A {@link $COURSE} object.
5268 * @param course $cm A {@link $COURSE} object.
5269 * @param string $targetwindow ?
5270 * @return string
5271 * @todo Finish documenting this function
5273 function navmenu($course, $cm=NULL, $targetwindow='self') {
5275 global $CFG, $THEME, $USER;
5277 if (empty($THEME->navmenuwidth)) {
5278 $width = 50;
5279 } else {
5280 $width = $THEME->navmenuwidth;
5283 if ($cm) {
5284 $cm = $cm->id;
5287 if ($course->format == 'weeks') {
5288 $strsection = get_string('week');
5289 } else {
5290 $strsection = get_string('topic');
5292 $strjumpto = get_string('jumpto');
5294 $modinfo = get_fast_modinfo($course);
5295 $context = get_context_instance(CONTEXT_COURSE, $course->id);
5297 $section = -1;
5298 $selected = '';
5299 $url = '';
5300 $previousmod = NULL;
5301 $backmod = NULL;
5302 $nextmod = NULL;
5303 $selectmod = NULL;
5304 $logslink = NULL;
5305 $flag = false;
5306 $menu = array();
5307 $menustyle = array();
5309 $sections = get_records('course_sections','course',$course->id,'section','section,visible,summary');
5311 if (!empty($THEME->makenavmenulist)) { /// A hack to produce an XHTML navmenu list for use in themes
5312 $THEME->navmenulist = navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
5315 foreach ($modinfo->cms as $mod) {
5316 if ($mod->modname == 'label') {
5317 continue;
5320 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
5321 break;
5324 if (!$mod->uservisible) { // do not icnlude empty sections at all
5325 continue;
5328 if ($mod->sectionnum > 0 and $section != $mod->sectionnum) {
5329 $thissection = $sections[$mod->sectionnum];
5331 if ($thissection->visible or !$course->hiddensections or
5332 has_capability('moodle/course:viewhiddensections', $context)) {
5333 $thissection->summary = strip_tags(format_string($thissection->summary,true));
5334 if ($course->format == 'weeks' or empty($thissection->summary)) {
5335 $menu[] = '--'.$strsection ." ". $mod->sectionnum;
5336 } else {
5337 if (strlen($thissection->summary) < ($width-3)) {
5338 $menu[] = '--'.$thissection->summary;
5339 } else {
5340 $menu[] = '--'.substr($thissection->summary, 0, $width).'...';
5343 $section = $mod->sectionnum;
5344 } else {
5345 // no activities from this hidden section shown
5346 continue;
5350 $url = $mod->modname.'/view.php?id='. $mod->id;
5351 if ($flag) { // the current mod is the "next" mod
5352 $nextmod = $mod;
5353 $flag = false;
5355 $localname = $mod->name;
5356 if ($cm == $mod->id) {
5357 $selected = $url;
5358 $selectmod = $mod;
5359 $backmod = $previousmod;
5360 $flag = true; // set flag so we know to use next mod for "next"
5361 $localname = $strjumpto;
5362 $strjumpto = '';
5363 } else {
5364 $localname = strip_tags(format_string($localname,true));
5365 $tl=textlib_get_instance();
5366 if ($tl->strlen($localname) > ($width+5)) {
5367 $localname = $tl->substr($localname, 0, $width).'...';
5369 if (!$mod->visible) {
5370 $localname = '('.$localname.')';
5373 $menu[$url] = $localname;
5374 if (empty($THEME->navmenuiconshide)) {
5375 $menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif);"'; // Unfortunately necessary to do this here
5377 $previousmod = $mod;
5379 //Accessibility: added Alt text, replaced &gt; &lt; with 'silent' character and 'accesshide' text.
5381 if ($selectmod and has_capability('moodle/site:viewreports', $context)) {
5382 $logstext = get_string('alllogs');
5383 $logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
5384 $CFG->frametarget.'onclick="this.target=\''.$CFG->framename.'\';"'.' href="'.
5385 $CFG->wwwroot.'/course/report/log/index.php?chooselog=1&amp;user=0&amp;date=0&amp;id='.
5386 $course->id.'&amp;modid='.$selectmod->id.'">'.
5387 '<img class="icon log" src="'.$CFG->pixpath.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
5390 if ($backmod) {
5391 $backtext= get_string('activityprev', 'access');
5392 $backmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$backmod->modname.'/view.php" '.
5393 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
5394 '<input type="hidden" name="id" value="'.$backmod->id.'" />'.
5395 '<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
5396 '</button></fieldset></form></li>';
5398 if ($nextmod) {
5399 $nexttext= get_string('activitynext', 'access');
5400 $nextmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$nextmod->modname.'/view.php" '.
5401 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
5402 '<input type="hidden" name="id" value="'.$nextmod->id.'" />'.
5403 '<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
5404 '</button></fieldset></form></li>';
5407 return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
5408 '<li>'.popup_form($CFG->wwwroot .'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
5409 '', '', true, $targetwindow, '', $menustyle).'</li>'.
5410 $nextmod . '</ul>'."\n".'</div>';
5414 * Given a course
5415 * This function returns a small popup menu with all the
5416 * course activity modules in it, as a navigation menu
5417 * outputs a simple list structure in XHTML
5418 * The data is taken from the serialised array stored in
5419 * the course record
5421 * @param course $course A {@link $COURSE} object.
5422 * @return string
5423 * @todo Finish documenting this function
5425 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
5427 global $CFG;
5429 $section = -1;
5430 $url = '';
5431 $menu = array();
5432 $doneheading = false;
5434 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
5436 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
5437 foreach ($modinfo->cms as $mod) {
5438 if ($mod->modname == 'label') {
5439 continue;
5442 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
5443 break;
5446 if (!$mod->uservisible) { // do not icnlude empty sections at all
5447 continue;
5450 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
5451 $thissection = $sections[$mod->sectionnum];
5453 if ($thissection->visible or !$course->hiddensections or
5454 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
5455 $thissection->summary = strip_tags(format_string($thissection->summary,true));
5456 if (!$doneheading) {
5457 $menu[] = '</ul></li>';
5459 if ($course->format == 'weeks' or empty($thissection->summary)) {
5460 $item = $strsection ." ". $mod->sectionnum;
5461 } else {
5462 if (strlen($thissection->summary) < ($width-3)) {
5463 $item = $thissection->summary;
5464 } else {
5465 $item = substr($thissection->summary, 0, $width).'...';
5468 $menu[] = '<li class="section"><span>'.$item.'</span>';
5469 $menu[] = '<ul>';
5470 $doneheading = true;
5472 $section = $mod->sectionnum;
5473 } else {
5474 // no activities from this hidden section shown
5475 continue;
5479 $url = $mod->modname .'/view.php?id='. $mod->id;
5480 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
5481 if (strlen($mod->name) > ($width+5)) {
5482 $mod->name = substr($mod->name, 0, $width).'...';
5484 if (!$mod->visible) {
5485 $mod->name = '('.$mod->name.')';
5487 $class = 'activity '.$mod->modname;
5488 $class .= ($cmid == $mod->cm) ? ' selected' : '';
5489 $menu[] = '<li class="'.$class.'">'.
5490 '<img src="'.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif" alt="" />'.
5491 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
5494 if ($doneheading) {
5495 $menu[] = '</ul></li>';
5497 $menu[] = '</ul></li></ul>';
5499 return implode("\n", $menu);
5503 * Prints form items with the names $day, $month and $year
5505 * @param string $day fieldname
5506 * @param string $month fieldname
5507 * @param string $year fieldname
5508 * @param int $currenttime A default timestamp in GMT
5509 * @param boolean $return
5511 function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
5513 if (!$currenttime) {
5514 $currenttime = time();
5516 $currentdate = usergetdate($currenttime);
5518 for ($i=1; $i<=31; $i++) {
5519 $days[$i] = $i;
5521 for ($i=1; $i<=12; $i++) {
5522 $months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
5524 for ($i=1970; $i<=2020; $i++) {
5525 $years[$i] = $i;
5527 return choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', $return)
5528 .choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', $return)
5529 .choose_from_menu($years, $year, $currentdate['year'], '', '', '0', $return);
5534 *Prints form items with the names $hour and $minute
5536 * @param string $hour fieldname
5537 * @param string ? $minute fieldname
5538 * @param $currenttime A default timestamp in GMT
5539 * @param int $step minute spacing
5540 * @param boolean $return
5542 function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
5544 if (!$currenttime) {
5545 $currenttime = time();
5547 $currentdate = usergetdate($currenttime);
5548 if ($step != 1) {
5549 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
5551 for ($i=0; $i<=23; $i++) {
5552 $hours[$i] = sprintf("%02d",$i);
5554 for ($i=0; $i<=59; $i+=$step) {
5555 $minutes[$i] = sprintf("%02d",$i);
5558 return choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',$return)
5559 .choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',$return);
5563 * Prints time limit value selector
5565 * @uses $CFG
5566 * @param int $timelimit default
5567 * @param string $unit
5568 * @param string $name
5569 * @param boolean $return
5571 function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
5573 global $CFG;
5575 if ($unit) {
5576 $unit = ' '.$unit;
5579 // Max timelimit is sessiontimeout - 10 minutes.
5580 $maxvalue = ($CFG->sessiontimeout / 60) - 10;
5582 for ($i=1; $i<=$maxvalue; $i++) {
5583 $minutes[$i] = $i.$unit;
5585 return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
5589 * Prints a grade menu (as part of an existing form) with help
5590 * Showing all possible numerical grades and scales
5592 * @uses $CFG
5593 * @param int $courseid ?
5594 * @param string $name ?
5595 * @param string $current ?
5596 * @param boolean $includenograde ?
5597 * @todo Finish documenting this function
5599 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
5601 global $CFG;
5603 $output = '';
5604 $strscale = get_string('scale');
5605 $strscales = get_string('scales');
5607 $scales = get_scales_menu($courseid);
5608 foreach ($scales as $i => $scalename) {
5609 $grades[-$i] = $strscale .': '. $scalename;
5611 if ($includenograde) {
5612 $grades[0] = get_string('nograde');
5614 for ($i=100; $i>=1; $i--) {
5615 $grades[$i] = $i;
5617 $output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
5619 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5620 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5621 $linkobject, 400, 500, $strscales, 'none', true);
5623 if ($return) {
5624 return $output;
5625 } else {
5626 echo $output;
5631 * Prints a scale menu (as part of an existing form) including help button
5632 * Just like {@link print_grade_menu()} but without the numeric grades
5634 * @param int $courseid ?
5635 * @param string $name ?
5636 * @param string $current ?
5637 * @todo Finish documenting this function
5639 function print_scale_menu($courseid, $name, $current, $return=false) {
5641 global $CFG;
5643 $output = '';
5644 $strscales = get_string('scales');
5645 $output .= choose_from_menu(get_scales_menu($courseid), $name, $current, '', '', 0, true);
5647 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5648 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5649 $linkobject, 400, 500, $strscales, 'none', true);
5650 if ($return) {
5651 return $output;
5652 } else {
5653 echo $output;
5658 * Prints a help button about a scale
5660 * @uses $CFG
5661 * @param id $courseid ?
5662 * @param object $scale ?
5663 * @todo Finish documenting this function
5665 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
5667 global $CFG;
5669 $output = '';
5670 $strscales = get_string('scales');
5672 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5673 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true&amp;scaleid='. $scale->id, 'ratingscale',
5674 $linkobject, 400, 500, $scale->name, 'none', true);
5675 if ($return) {
5676 return $output;
5677 } else {
5678 echo $output;
5683 * Print an error page displaying an error message. New method - use this for new code.
5685 * @uses $SESSION
5686 * @uses $CFG
5687 * @param string $errorcode The name of the string from error.php to print
5688 * @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.
5689 * @param object $a Extra words and phrases that might be required in the error string
5691 function print_error ($errorcode, $module='', $link='', $a=NULL) {
5693 global $CFG, $SESSION, $THEME;
5695 if (empty($module) || $module == 'moodle' || $module == 'core') {
5696 $module = 'error';
5697 $modulelink = 'moodle';
5698 } else {
5699 $modulelink = $module;
5702 if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
5703 if ( !empty($SESSION->fromurl) ) {
5704 $link = $SESSION->fromurl;
5705 unset($SESSION->fromurl);
5706 } else {
5707 $link = $CFG->wwwroot .'/';
5711 if (!empty($CFG->errordocroot)) {
5712 $errordocroot = $CFG->errordocroot;
5713 } else if (!empty($CFG->docroot)) {
5714 $errordocroot = $CFG->docroot;
5715 } else {
5716 $errordocroot = 'http://docs.moodle.org';
5719 $message = get_string($errorcode, $module, $a);
5721 if (defined('FULLME') && FULLME == 'cron') {
5722 // Errors in cron should be mtrace'd.
5723 mtrace($message);
5724 die;
5727 $message = clean_text('<p class="errormessage">'.$message.'</p>'.
5728 '<p class="errorcode">'.
5729 '<a href="'.$errordocroot.'/en/error/'.$modulelink.'/'.$errorcode.'">'.
5730 get_string('moreinformation').'</a></p>');
5732 if (! defined('HEADER_PRINTED')) {
5733 //header not yet printed
5734 @header('HTTP/1.0 404 Not Found');
5735 print_header(get_string('error'));
5736 } else {
5737 print_container_end_all(false, $THEME->open_header_containers);
5740 echo '<br />';
5742 print_simple_box($message, '', '', '', '', 'errorbox');
5744 debugging('Stack trace:', DEBUG_DEVELOPER);
5746 // in case we are logging upgrade in admin/index.php stop it
5747 if (function_exists('upgrade_log_finish')) {
5748 upgrade_log_finish();
5751 if (!empty($link)) {
5752 print_continue($link);
5755 print_footer();
5757 for ($i=0;$i<512;$i++) { // Padding to help IE work with 404
5758 echo ' ';
5760 die;
5764 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
5765 * Default errorcode is 1.
5767 * Very useful for perl-like error-handling:
5769 * do_somethting() or mdie("Something went wrong");
5771 * @param string $msg Error message
5772 * @param integer $errorcode Error code to emit
5774 function mdie($msg='', $errorcode=1) {
5775 trigger_error($msg);
5776 exit($errorcode);
5780 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
5781 * Should be used only with htmleditor or textarea.
5782 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
5783 * helpbutton.
5784 * @return string
5786 function editorhelpbutton(){
5787 global $CFG, $SESSION;
5788 $items = func_get_args();
5789 $i = 1;
5790 $urlparams = array();
5791 $titles = array();
5792 foreach ($items as $item){
5793 if (is_array($item)){
5794 $urlparams[] = "keyword$i=".urlencode($item[0]);
5795 $urlparams[] = "title$i=".urlencode($item[1]);
5796 if (isset($item[2])){
5797 $urlparams[] = "module$i=".urlencode($item[2]);
5799 $titles[] = trim($item[1], ". \t");
5800 }elseif (is_string($item)){
5801 $urlparams[] = "button$i=".urlencode($item);
5802 switch ($item){
5803 case 'reading' :
5804 $titles[] = get_string("helpreading");
5805 break;
5806 case 'writing' :
5807 $titles[] = get_string("helpwriting");
5808 break;
5809 case 'questions' :
5810 $titles[] = get_string("helpquestions");
5811 break;
5812 case 'emoticons' :
5813 $titles[] = get_string("helpemoticons");
5814 break;
5815 case 'richtext' :
5816 $titles[] = get_string('helprichtext');
5817 break;
5818 case 'text' :
5819 $titles[] = get_string('helptext');
5820 break;
5821 default :
5822 error('Unknown help topic '.$item);
5825 $i++;
5827 if (count($titles)>1){
5828 //join last two items with an 'and'
5829 $a = new object();
5830 $a->one = $titles[count($titles) - 2];
5831 $a->two = $titles[count($titles) - 1];
5832 $titles[count($titles) - 2] = get_string('and', '', $a);
5833 unset($titles[count($titles) - 1]);
5835 $alttag = join (', ', $titles);
5837 $paramstring = join('&', $urlparams);
5838 $linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath .'/help.gif" />';
5839 return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), 'popup', $linkobject, 400, 500, $alttag, 'none', true);
5843 * Print a help button.
5845 * @uses $CFG
5846 * @param string $page The keyword that defines a help page
5847 * @param string $title The title of links, rollover tips, alt tags etc
5848 * 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
5849 * @param string $module Which module is the page defined in
5850 * @param mixed $image Use a help image for the link? (true/false/"both")
5851 * @param boolean $linktext If true, display the title next to the help icon.
5852 * @param string $text If defined then this text is used in the page, and
5853 * the $page variable is ignored.
5854 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
5855 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
5856 * @return string
5857 * @todo Finish documenting this function
5859 function helpbutton ($page, $title, $module='moodle', $image=true, $linktext=false, $text='', $return=false,
5860 $imagetext='') {
5861 global $CFG, $COURSE;
5863 //warning if ever $text parameter is used
5864 //$text option won't work properly because the text needs to be always cleaned and,
5865 // when cleaned... html tags always break, so it's unusable.
5866 if ( isset($text) && $text!='') {
5867 debugging('Warning: it\'s not recommended to use $text parameter in helpbutton ($page=' . $page . ', $module=' . $module . ') function');
5870 // fix for MDL-7734
5871 if (!empty($COURSE->lang)) {
5872 $forcelang = $COURSE->lang;
5873 } else {
5874 $forcelang = '';
5877 if ($module == '') {
5878 $module = 'moodle';
5881 if ($title == '' && $linktext == '') {
5882 debugging('Error in call to helpbutton function: at least one of $title and $linktext is required');
5885 // Warn users about new window for Accessibility
5886 $tooltip = get_string('helpprefix2', '', trim($title, ". \t")) .' ('.get_string('newwindow').')';
5888 $linkobject = '';
5890 if ($image) {
5891 if ($linktext) {
5892 // MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
5893 $linkobject .= $title.'&nbsp;';
5894 $tooltip = get_string('helpwiththis');
5896 if ($imagetext) {
5897 $linkobject .= $imagetext;
5898 } else {
5899 $linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
5900 $CFG->pixpath .'/help.gif" />';
5902 } else {
5903 $linkobject .= $tooltip;
5906 // fix for MDL-7734
5907 if ($text) {
5908 $url = '/help.php?module='. $module .'&amp;text='. s(urlencode($text).'&amp;forcelang='.$forcelang);
5909 } else {
5910 $url = '/help.php?module='. $module .'&amp;file='. $page .'.html&amp;forcelang='.$forcelang;
5913 $link = '<span class="helplink">'.
5914 link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
5915 '</span>';
5917 if ($return) {
5918 return $link;
5919 } else {
5920 echo $link;
5925 * Print a help button.
5927 * Prints a special help button that is a link to the "live" emoticon popup
5928 * @uses $CFG
5929 * @uses $SESSION
5930 * @param string $form ?
5931 * @param string $field ?
5932 * @todo Finish documenting this function
5934 function emoticonhelpbutton($form, $field, $return = false) {
5936 global $CFG, $SESSION;
5938 $SESSION->inserttextform = $form;
5939 $SESSION->inserttextfield = $field;
5940 $imagetext = '<img src="' . $CFG->pixpath . '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
5941 $help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
5942 if (!$return){
5943 echo $help;
5944 } else {
5945 return $help;
5950 * Print a help button.
5952 * Prints a special help button for html editors (htmlarea in this case)
5953 * @uses $CFG
5955 function editorshortcutshelpbutton() {
5957 global $CFG;
5958 $imagetext = '<img src="' . $CFG->httpswwwroot . '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
5959 get_string('editorshortcutkeys').'" class="iconkbhelp" />';
5961 return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
5965 * Print a message and exit.
5967 * @uses $CFG
5968 * @param string $message ?
5969 * @param string $link ?
5970 * @todo Finish documenting this function
5972 function notice ($message, $link='', $course=NULL) {
5973 global $CFG, $SITE, $THEME, $COURSE;
5975 $message = clean_text($message); // In case nasties are in here
5977 if (defined('FULLME') && FULLME == 'cron') {
5978 // notices in cron should be mtrace'd.
5979 mtrace($message);
5980 die;
5983 if (! defined('HEADER_PRINTED')) {
5984 //header not yet printed
5985 print_header(get_string('notice'));
5986 } else {
5987 print_container_end_all(false, $THEME->open_header_containers);
5990 print_box($message, 'generalbox', 'notice');
5991 print_continue($link);
5993 if (empty($course)) {
5994 print_footer($COURSE);
5995 } else {
5996 print_footer($course);
5998 exit;
6002 * Print a message along with "Yes" and "No" links for the user to continue.
6004 * @param string $message The text to display
6005 * @param string $linkyes The link to take the user to if they choose "Yes"
6006 * @param string $linkno The link to take the user to if they choose "No"
6007 * TODO Document remaining arguments
6009 function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
6011 global $CFG;
6013 $message = clean_text($message);
6014 $linkyes = clean_text($linkyes);
6015 $linkno = clean_text($linkno);
6017 print_box_start('generalbox', 'notice');
6018 echo '<p>'. $message .'</p>';
6019 echo '<div class="buttons">';
6020 print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename);
6021 print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename);
6022 echo '</div>';
6023 print_box_end();
6027 * Provide an definition of error_get_last for PHP before 5.2.0. This simply
6028 * returns NULL, since there is not way to get the right answer.
6030 if (!function_exists('error_get_last')) {
6031 // the eval is needed to prevent PHP 5.2+ from getting a parse error!
6032 eval('
6033 function error_get_last() {
6034 return NULL;
6040 * Redirects the user to another page, after printing a notice
6042 * @param string $url The url to take the user to
6043 * @param string $message The text message to display to the user about the redirect, if any
6044 * @param string $delay How long before refreshing to the new page at $url?
6045 * @todo '&' needs to be encoded into '&amp;' for XHTML compliance,
6046 * however, this is not true for javascript. Therefore we
6047 * first decode all entities in $url (since we cannot rely on)
6048 * the correct input) and then encode for where it's needed
6049 * echo "<script type='text/javascript'>alert('Redirect $url');</script>";
6051 function redirect($url, $message='', $delay=-1) {
6053 global $CFG, $THEME;
6055 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
6056 $url = sid_process_url($url);
6059 $message = clean_text($message);
6061 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
6062 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
6063 $url = str_replace('&amp;', '&', $encodedurl);
6065 /// At developer debug level. Don't redirect if errors have been printed on screen.
6066 /// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
6067 $lasterror = error_get_last();
6068 $error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER));
6069 $errorprinted = debugging('', DEBUG_ALL) && $CFG->debugdisplay && $error;
6070 if ($errorprinted) {
6071 $message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
6074 $performanceinfo = '';
6075 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
6076 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
6077 $perf = get_performance_info();
6078 error_log("PERF: " . $perf['txt']);
6082 /// when no message and header printed yet, try to redirect
6083 if (empty($message) and !defined('HEADER_PRINTED')) {
6085 // Technically, HTTP/1.1 requires Location: header to contain
6086 // the absolute path. (In practice browsers accept relative
6087 // paths - but still, might as well do it properly.)
6088 // This code turns relative into absolute.
6089 if (!preg_match('|^[a-z]+:|', $url)) {
6090 // Get host name http://www.wherever.com
6091 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
6092 if (preg_match('|^/|', $url)) {
6093 // URLs beginning with / are relative to web server root so we just add them in
6094 $url = $hostpart.$url;
6095 } else {
6096 // URLs not beginning with / are relative to path of current script, so add that on.
6097 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
6099 // Replace all ..s
6100 while (true) {
6101 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
6102 if ($newurl == $url) {
6103 break;
6105 $url = $newurl;
6109 $delay = 0;
6110 //try header redirection first
6111 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
6112 @header('Location: '.$url);
6113 //another way for older browsers and already sent headers (eg trailing whitespace in config.php)
6114 echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
6115 echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
6116 die;
6119 if ($delay == -1) {
6120 $delay = 3; // if no delay specified wait 3 seconds
6122 if (! defined('HEADER_PRINTED')) {
6123 // this type of redirect might not be working in some browsers - such as lynx :-(
6124 print_header('', '', '', '', $errorprinted ? '' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
6125 $delay += 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
6126 } else {
6127 print_container_end_all(false, $THEME->open_header_containers);
6129 echo '<div id="redirect">';
6130 echo '<div id="message">' . $message . '</div>';
6131 echo '<div id="continue">( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
6132 echo '</div>';
6134 if (!$errorprinted) {
6136 <script type="text/javascript">
6137 //<![CDATA[
6139 function redirect() {
6140 document.location.replace('<?php echo addslashes_js($url) ?>');
6142 setTimeout("redirect()", <?php echo ($delay * 1000) ?>);
6143 //]]>
6144 </script>
6145 <?php
6148 $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
6149 print_footer('none');
6150 die;
6154 * Print a bold message in an optional color.
6156 * @param string $message The message to print out
6157 * @param string $style Optional style to display message text in
6158 * @param string $align Alignment option
6159 * @param bool $return whether to return an output string or echo now
6161 function notify($message, $style='notifyproblem', $align='center', $return=false) {
6162 if ($style == 'green') {
6163 $style = 'notifysuccess'; // backward compatible with old color system
6166 $message = clean_text($message);
6168 $output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."\n";
6170 if ($return) {
6171 return $output;
6173 echo $output;
6178 * Given an email address, this function will return an obfuscated version of it
6180 * @param string $email The email address to obfuscate
6181 * @return string
6183 function obfuscate_email($email) {
6185 $i = 0;
6186 $length = strlen($email);
6187 $obfuscated = '';
6188 while ($i < $length) {
6189 if (rand(0,2)) {
6190 $obfuscated.='%'.dechex(ord($email{$i}));
6191 } else {
6192 $obfuscated.=$email{$i};
6194 $i++;
6196 return $obfuscated;
6200 * This function takes some text and replaces about half of the characters
6201 * with HTML entity equivalents. Return string is obviously longer.
6203 * @param string $plaintext The text to be obfuscated
6204 * @return string
6206 function obfuscate_text($plaintext) {
6208 $i=0;
6209 $length = strlen($plaintext);
6210 $obfuscated='';
6211 $prev_obfuscated = false;
6212 while ($i < $length) {
6213 $c = ord($plaintext{$i});
6214 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
6215 if ($prev_obfuscated and $numerical ) {
6216 $obfuscated.='&#'.ord($plaintext{$i}).';';
6217 } else if (rand(0,2)) {
6218 $obfuscated.='&#'.ord($plaintext{$i}).';';
6219 $prev_obfuscated = true;
6220 } else {
6221 $obfuscated.=$plaintext{$i};
6222 $prev_obfuscated = false;
6224 $i++;
6226 return $obfuscated;
6230 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
6231 * to generate a fully obfuscated email link, ready to use.
6233 * @param string $email The email address to display
6234 * @param string $label The text to dispalyed as hyperlink to $email
6235 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
6236 * @return string
6238 function obfuscate_mailto($email, $label='', $dimmed=false) {
6240 if (empty($label)) {
6241 $label = $email;
6243 if ($dimmed) {
6244 $title = get_string('emaildisable');
6245 $dimmed = ' class="dimmed"';
6246 } else {
6247 $title = '';
6248 $dimmed = '';
6250 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
6251 obfuscate_text('mailto'), obfuscate_email($email),
6252 obfuscate_text($label));
6256 * Prints a single paging bar to provide access to other pages (usually in a search)
6258 * @param int $totalcount Thetotal number of entries available to be paged through
6259 * @param int $page The page you are currently viewing
6260 * @param int $perpage The number of entries that should be shown per page
6261 * @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.
6262 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
6263 * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
6264 * @param bool $nocurr do not display the current page as a link
6265 * @param bool $return whether to return an output string or echo now
6266 * @return bool or string
6268 function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
6269 $maxdisplay = 18;
6270 $output = '';
6272 if ($totalcount > $perpage) {
6273 $output .= '<div class="paging">';
6274 $output .= get_string('page') .':';
6275 if ($page > 0) {
6276 $pagenum = $page - 1;
6277 if (!is_a($baseurl, 'moodle_url')){
6278 $output .= '&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>)&nbsp;';
6279 } else {
6280 $output .= '&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>)&nbsp;';
6283 if ($perpage > 0) {
6284 $lastpage = ceil($totalcount / $perpage);
6285 } else {
6286 $lastpage = 1;
6288 if ($page > 15) {
6289 $startpage = $page - 10;
6290 if (!is_a($baseurl, 'moodle_url')){
6291 $output .= '&nbsp;<a href="'. $baseurl . $pagevar .'=0">1</a>&nbsp;...';
6292 } else {
6293 $output .= '&nbsp;<a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a>&nbsp;...';
6295 } else {
6296 $startpage = 0;
6298 $currpage = $startpage;
6299 $displaycount = $displaypage = 0;
6300 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
6301 $displaypage = $currpage+1;
6302 if ($page == $currpage && empty($nocurr)) {
6303 $output .= '&nbsp;&nbsp;'. $displaypage;
6304 } else {
6305 if (!is_a($baseurl, 'moodle_url')){
6306 $output .= '&nbsp;&nbsp;<a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
6307 } else {
6308 $output .= '&nbsp;&nbsp;<a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
6312 $displaycount++;
6313 $currpage++;
6315 if ($currpage < $lastpage) {
6316 $lastpageactual = $lastpage - 1;
6317 if (!is_a($baseurl, 'moodle_url')){
6318 $output .= '&nbsp;...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a>&nbsp;';
6319 } else {
6320 $output .= '&nbsp;...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a>&nbsp;';
6323 $pagenum = $page + 1;
6324 if ($pagenum != $displaypage) {
6325 if (!is_a($baseurl, 'moodle_url')){
6326 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
6327 } else {
6328 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
6331 $output .= '</div>';
6334 if ($return) {
6335 return $output;
6338 echo $output;
6339 return true;
6343 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
6344 * will transform it to html entities
6346 * @param string $text Text to search for nolink tag in
6347 * @return string
6349 function rebuildnolinktag($text) {
6351 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
6353 return $text;
6357 * Prints a nice side block with an optional header. The content can either
6358 * be a block of HTML or a list of text with optional icons.
6360 * @param string $heading Block $title embedded in HTML tags, for example <h2>.
6361 * @param string $content ?
6362 * @param array $list ?
6363 * @param array $icons ?
6364 * @param string $footer ?
6365 * @param array $attributes ?
6366 * @param string $title Plain text title, as embedded in the $heading.
6367 * @todo Finish documenting this function. Show example of various attributes, etc.
6369 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
6371 //Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
6372 static $block_id = 0;
6373 $block_id++;
6374 if (empty($heading)) {
6375 $skip_text = get_string('skipblock', 'access').' '.$block_id;
6377 else {
6378 $skip_text = get_string('skipa', 'access', strip_tags($title));
6380 $skip_link = '<a href="#sb-'.$block_id.'" class="skip-block">'.$skip_text.'</a>';
6381 $skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
6383 if (! empty($heading)) {
6384 echo $skip_link;
6386 //ELSE: a single link on a page "Skip block 4" is too confusing - ignore.
6388 print_side_block_start($heading, $attributes);
6390 if ($content) {
6391 echo $content;
6392 if ($footer) {
6393 echo '<div class="footer">'. $footer .'</div>';
6395 } else {
6396 if ($list) {
6397 $row = 0;
6398 //Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
6399 echo "\n<ul class='list'>\n";
6400 foreach ($list as $key => $string) {
6401 echo '<li class="r'. $row .'">';
6402 if ($icons) {
6403 echo '<div class="icon column c0">'. $icons[$key] .'</div>';
6405 echo '<div class="column c1">'. $string .'</div>';
6406 echo "</li>\n";
6407 $row = $row ? 0:1;
6409 echo "</ul>\n";
6411 if ($footer) {
6412 echo '<div class="footer">'. $footer .'</div>';
6417 print_side_block_end($attributes, $title);
6418 echo $skip_dest;
6422 * Starts a nice side block with an optional header.
6424 * @param string $heading ?
6425 * @param array $attributes ?
6426 * @todo Finish documenting this function
6428 function print_side_block_start($heading='', $attributes = array()) {
6430 global $CFG, $THEME;
6432 // If there are no special attributes, give a default CSS class
6433 if (empty($attributes) || !is_array($attributes)) {
6434 $attributes = array('class' => 'sideblock');
6436 } else if(!isset($attributes['class'])) {
6437 $attributes['class'] = 'sideblock';
6439 } else if(!strpos($attributes['class'], 'sideblock')) {
6440 $attributes['class'] .= ' sideblock';
6443 // OK, the class is surely there and in addition to anything
6444 // else, it's tagged as a sideblock
6448 // IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
6450 // If there is a cookie to hide this thing, start it hidden
6451 if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
6452 $attributes['class'] = 'hidden '.$attributes['class'];
6456 $attrtext = '';
6457 foreach ($attributes as $attr => $val) {
6458 $attrtext .= ' '.$attr.'="'.$val.'"';
6461 echo '<div '.$attrtext.'>';
6463 if (!empty($THEME->customcorners)) {
6464 echo '<div class="wrap">'."\n";
6466 if ($heading) {
6467 //Accessibility: H2 more appropriate in moodleblock.class.php: _title_html.
6468 echo '<div class="header">';
6469 if (!empty($THEME->customcorners)) {
6470 echo '<div class="bt"><div>&nbsp;</div></div>';
6471 echo '<div class="i1"><div class="i2">';
6472 echo '<div class="i3">';
6474 echo $heading;
6475 if (!empty($THEME->customcorners)) {
6476 echo '</div></div></div>';
6478 echo '</div>';
6479 } else {
6480 if (!empty($THEME->customcorners)) {
6481 echo '<div class="bt"><div>&nbsp;</div></div>';
6485 if (!empty($THEME->customcorners)) {
6486 echo '<div class="i1"><div class="i2">';
6487 echo '<div class="i3">';
6489 echo '<div class="content">';
6495 * Print table ending tags for a side block box.
6497 function print_side_block_end($attributes = array(), $title='') {
6498 global $CFG, $THEME;
6500 echo '</div>';
6502 if (!empty($THEME->customcorners)) {
6503 echo '</div></div></div><div class="bb"><div>&nbsp;</div></div></div>';
6506 echo '</div>';
6508 $strshow = addslashes_js(get_string('showblocka', 'access', strip_tags($title)));
6509 $strhide = addslashes_js(get_string('hideblocka', 'access', strip_tags($title)));
6511 // IE workaround: if I do it THIS way, it works! WTF?
6512 if (!empty($CFG->allowuserblockhiding) && isset($attributes['id'])) {
6513 echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].
6514 '","'.$strshow.'","'.$strhide."\");\n//]]>\n".'</script>';
6521 * Prints out code needed for spellchecking.
6522 * Original idea by Ludo (Marc Alier).
6524 * Opening CDATA and <script> are output by weblib::use_html_editor()
6525 * @uses $CFG
6526 * @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
6527 * @param boolean $return If false, echos the code instead of returning it
6528 * @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
6530 function print_speller_code ($usehtmleditor=false, $return=false) {
6531 global $CFG;
6532 $str = '';
6534 if(!$usehtmleditor) {
6535 $str .= 'function openSpellChecker() {'."\n";
6536 $str .= "\tvar speller = new spellChecker();\n";
6537 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot ."/lib/speller/spellchecker.html\";\n";
6538 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
6539 $str .= "\tspeller.spellCheckAll();\n";
6540 $str .= '}'."\n";
6541 } else {
6542 $str .= "function spellClickHandler(editor, buttonId) {\n";
6543 $str .= "\teditor._textArea.value = editor.getHTML();\n";
6544 $str .= "\tvar speller = new spellChecker( editor._textArea );\n";
6545 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot ."/lib/speller/spellchecker.html\";\n";
6546 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
6547 $str .= "\tspeller._moogle_edit=1;\n";
6548 $str .= "\tspeller._editor=editor;\n";
6549 $str .= "\tspeller.openChecker();\n";
6550 $str .= '}'."\n";
6553 if ($return) {
6554 return $str;
6556 echo $str;
6560 * Print button for spellchecking when editor is disabled
6562 function print_speller_button () {
6563 echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
6567 function page_id_and_class(&$getid, &$getclass) {
6568 // Create class and id for this page
6569 global $CFG, $ME;
6571 static $class = NULL;
6572 static $id = NULL;
6574 if (empty($CFG->pagepath)) {
6575 $CFG->pagepath = $ME;
6578 if (empty($class) || empty($id)) {
6579 $path = str_replace($CFG->httpswwwroot.'/', '', $CFG->pagepath); //Because the page could be HTTPSPAGEREQUIRED
6580 $path = str_replace('.php', '', $path);
6581 if (substr($path, -1) == '/') {
6582 $path .= 'index';
6584 if (empty($path) || $path == 'index') {
6585 $id = 'site-index';
6586 $class = 'course';
6587 } else if (substr($path, 0, 5) == 'admin') {
6588 $id = str_replace('/', '-', $path);
6589 $class = 'admin';
6590 } else {
6591 $id = str_replace('/', '-', $path);
6592 $class = explode('-', $id);
6593 array_pop($class);
6594 $class = implode('-', $class);
6598 $getid = $id;
6599 $getclass = $class;
6603 * Prints a maintenance message from /maintenance.html
6605 function print_maintenance_message () {
6606 global $CFG, $SITE;
6608 print_header(strip_tags($SITE->fullname), $SITE->fullname, 'home');
6609 print_simple_box_start('center');
6610 print_heading(get_string('sitemaintenance', 'admin'));
6611 @include($CFG->dataroot.'/1/maintenance.html');
6612 print_simple_box_end();
6613 print_footer();
6617 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
6619 function adjust_allowed_tags() {
6621 global $CFG, $ALLOWED_TAGS;
6623 if (!empty($CFG->allowobjectembed)) {
6624 $ALLOWED_TAGS .= '<embed><object>';
6628 /// Some code to print tabs
6630 /// A class for tabs
6631 class tabobject {
6632 var $id;
6633 var $link;
6634 var $text;
6635 var $linkedwhenselected;
6637 /// A constructor just because I like constructors
6638 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
6639 $this->id = $id;
6640 $this->link = $link;
6641 $this->text = $text;
6642 $this->title = $title ? $title : $text;
6643 $this->linkedwhenselected = $linkedwhenselected;
6650 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
6652 * @param array $tabrows An array of rows where each row is an array of tab objects
6653 * @param string $selected The id of the selected tab (whatever row it's on)
6654 * @param array $inactive An array of ids of inactive tabs that are not selectable.
6655 * @param array $activated An array of ids of other tabs that are currently activated
6657 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
6658 global $CFG;
6660 /// $inactive must be an array
6661 if (!is_array($inactive)) {
6662 $inactive = array();
6665 /// $activated must be an array
6666 if (!is_array($activated)) {
6667 $activated = array();
6670 /// Convert the tab rows into a tree that's easier to process
6671 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
6672 return false;
6675 /// Print out the current tree of tabs (this function is recursive)
6677 $output = convert_tree_to_html($tree);
6679 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
6681 /// We're done!
6683 if ($return) {
6684 return $output;
6686 echo $output;
6690 function convert_tree_to_html($tree, $row=0) {
6692 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
6694 $first = true;
6695 $count = count($tree);
6697 foreach ($tree as $tab) {
6698 $count--; // countdown to zero
6700 $liclass = '';
6702 if ($first && ($count == 0)) { // Just one in the row
6703 $liclass = 'first last';
6704 $first = false;
6705 } else if ($first) {
6706 $liclass = 'first';
6707 $first = false;
6708 } else if ($count == 0) {
6709 $liclass = 'last';
6712 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
6713 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
6716 if ($tab->inactive || $tab->active || $tab->selected) {
6717 if ($tab->selected) {
6718 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
6719 } else if ($tab->active) {
6720 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
6724 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
6726 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
6727 // The a tag is used for styling
6728 $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
6729 } else {
6730 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
6733 if (!empty($tab->subtree)) {
6734 $str .= convert_tree_to_html($tab->subtree, $row+1);
6735 } else if ($tab->selected) {
6736 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
6739 $str .= ' </li>'."\n";
6741 $str .= '</ul>'."\n";
6743 return $str;
6747 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
6749 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
6751 $tabrows = array_reverse($tabrows);
6753 $subtree = array();
6755 foreach ($tabrows as $row) {
6756 $tree = array();
6758 foreach ($row as $tab) {
6759 $tab->inactive = in_array((string)$tab->id, $inactive);
6760 $tab->active = in_array((string)$tab->id, $activated);
6761 $tab->selected = (string)$tab->id == $selected;
6763 if ($tab->active || $tab->selected) {
6764 if ($subtree) {
6765 $tab->subtree = $subtree;
6768 $tree[] = $tab;
6770 $subtree = $tree;
6773 return $subtree;
6778 * Returns a string containing a link to the user documentation for the current
6779 * page. Also contains an icon by default. Shown to teachers and admin only.
6781 * @param string $text The text to be displayed for the link
6782 * @param string $iconpath The path to the icon to be displayed
6784 function page_doc_link($text='', $iconpath='') {
6785 global $ME, $COURSE, $CFG;
6787 if (empty($CFG->docroot) or empty($CFG->rolesactive)) {
6788 return '';
6791 if (empty($COURSE->id)) {
6792 $context = get_context_instance(CONTEXT_SYSTEM);
6793 } else {
6794 $context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
6797 if (!has_capability('moodle/site:doclinks', $context)) {
6798 return '';
6801 if (empty($CFG->pagepath)) {
6802 $CFG->pagepath = $ME;
6805 $path = str_replace($CFG->httpswwwroot.'/','', $CFG->pagepath); // Because the page could be HTTPSPAGEREQUIRED
6806 $path = str_replace('.php', '', $path);
6808 if (empty($path)) { // Not for home page
6809 return '';
6811 return doc_link($path, $text, $iconpath);
6815 * Returns a string containing a link to the user documentation.
6816 * Also contains an icon by default. Shown to teachers and admin only.
6818 * @param string $path The page link after doc root and language, no
6819 * leading slash.
6820 * @param string $text The text to be displayed for the link
6821 * @param string $iconpath The path to the icon to be displayed
6823 function doc_link($path='', $text='', $iconpath='') {
6824 global $CFG;
6826 if (empty($CFG->docroot)) {
6827 return '';
6830 $target = '';
6831 if (!empty($CFG->doctonewwindow)) {
6832 $target = ' target="_blank"';
6835 $lang = str_replace('_utf8', '', current_language());
6837 $str = '<a href="' .$CFG->docroot. '/' .$lang. '/' .$path. '"' .$target. '>';
6839 if (empty($iconpath)) {
6840 $iconpath = $CFG->httpswwwroot . '/pix/docs.gif';
6843 // alt left blank intentionally to prevent repetition in screenreaders
6844 $str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
6846 return $str;
6851 * Returns true if the current site debugging settings are equal or above specified level.
6852 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
6853 * routing of notices is controlled by $CFG->debugdisplay
6854 * eg use like this:
6856 * 1) debugging('a normal debug notice');
6857 * 2) debugging('something really picky', DEBUG_ALL);
6858 * 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
6859 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
6861 * In code blocks controlled by debugging() (such as example 4)
6862 * any output should be routed via debugging() itself, or the lower-level
6863 * trigger_error() or error_log(). Using echo or print will break XHTML
6864 * JS and HTTP headers.
6867 * @param string $message a message to print
6868 * @param int $level the level at which this debugging statement should show
6869 * @return bool
6871 function debugging($message='', $level=DEBUG_NORMAL) {
6873 global $CFG;
6875 if (empty($CFG->debug)) {
6876 return false;
6879 if ($CFG->debug >= $level) {
6880 if ($message) {
6881 $callers = debug_backtrace();
6882 $from = '<ul style="text-align: left">';
6883 foreach ($callers as $caller) {
6884 if (!isset($caller['line'])) {
6885 $caller['line'] = '?'; // probably call_user_func()
6887 if (!isset($caller['file'])) {
6888 $caller['file'] = $CFG->dirroot.'/unknownfile'; // probably call_user_func()
6890 $from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
6891 if (isset($caller['function'])) {
6892 $from .= ': call to ';
6893 if (isset($caller['class'])) {
6894 $from .= $caller['class'] . $caller['type'];
6896 $from .= $caller['function'] . '()';
6898 $from .= '</li>';
6900 $from .= '</ul>';
6901 if (!isset($CFG->debugdisplay)) {
6902 $CFG->debugdisplay = ini_get('display_errors');
6904 if ($CFG->debugdisplay) {
6905 if (!defined('DEBUGGING_PRINTED')) {
6906 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
6908 notify($message . $from, 'notifytiny');
6909 } else {
6910 trigger_error($message . $from, E_USER_NOTICE);
6913 return true;
6915 return false;
6919 * Disable debug messages from debugging(), while keeping PHP error reporting level as is.
6921 function disable_debugging() {
6922 global $CFG;
6923 $CFG->debug = $CFG->debug | 0x80000000; // switch the sign bit in integer number ;-)
6928 * Returns string to add a frame attribute, if required
6930 function frametarget() {
6931 global $CFG;
6933 if (empty($CFG->framename) or ($CFG->framename == '_top')) {
6934 return '';
6935 } else {
6936 return ' target="'.$CFG->framename.'" ';
6941 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
6942 * pages that use bits from many different files in very confusing ways (e.g. blocks).
6943 * @usage print_location_comment(__FILE__, __LINE__);
6944 * @param string $file
6945 * @param integer $line
6946 * @param boolean $return Whether to return or print the comment
6947 * @return mixed Void unless true given as third parameter
6949 function print_location_comment($file, $line, $return = false)
6951 if ($return) {
6952 return "<!-- $file at line $line -->\n";
6953 } else {
6954 echo "<!-- $file at line $line -->\n";
6960 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
6961 * provide this function with the language strings for sortasc and sortdesc.
6962 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
6963 * @param string $direction 'up' or 'down'
6964 * @param string $strsort The language string used for the alt attribute of this image
6965 * @param bool $return Whether to print directly or return the html string
6966 * @return string HTML for the image
6968 * TODO See if this isn't already defined somewhere. If not, move this to weblib
6970 function print_arrow($direction='up', $strsort=null, $return=false) {
6971 global $CFG;
6973 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
6974 return null;
6977 $return = null;
6979 switch ($direction) {
6980 case 'up':
6981 $sortdir = 'asc';
6982 break;
6983 case 'down':
6984 $sortdir = 'desc';
6985 break;
6986 case 'move':
6987 $sortdir = 'asc';
6988 break;
6989 default:
6990 $sortdir = null;
6991 break;
6994 // Prepare language string
6995 $strsort = '';
6996 if (empty($strsort) && !empty($sortdir)) {
6997 $strsort = get_string('sort' . $sortdir, 'grades');
7000 $return = ' <img src="'.$CFG->pixpath.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
7002 if ($return) {
7003 return $return;
7004 } else {
7005 echo $return;
7010 * Returns boolean true if the current language is right-to-left (Hebrew, Arabic etc)
7013 function right_to_left() {
7014 static $result;
7016 if (isset($result)) {
7017 return $result;
7019 return $result = (get_string('thisdirection') == 'rtl');
7024 * Returns swapped left<=>right if in RTL environment.
7025 * part of RTL support
7027 * @param string $align align to check
7028 * @return string
7030 function fix_align_rtl($align) {
7031 if (!right_to_left()) {
7032 return $align;
7034 if ($align=='left') { return 'right'; }
7035 if ($align=='right') { return 'left'; }
7036 return $align;
7041 * Returns true if the page is displayed in a popup window.
7042 * Gets the information from the URL parameter inpopup.
7044 * @return boolean
7046 * TODO Use a central function to create the popup calls allover Moodle and
7047 * TODO In the moment only works with resources and probably questions.
7049 function is_in_popup() {
7050 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
7052 return ($inpopup);
7056 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: