MDL-14832
[moodle-linuxchix.git] / lib / weblib.php
blobb9f2acf06af2b27abc91c51e0c9441e7f18d874c
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 * @return string html for form elements.
397 function hidden_params_out($exclude = array(), $indent = 0){
398 $tabindent = str_repeat("\t", $indent);
399 $str = '';
400 foreach ($this->params as $key => $val){
401 if (FALSE === array_search($key, $exclude)) {
402 $val = s($val);
403 $str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
406 return $str;
409 * Output url
411 * @param boolean $noquerystring whether to output page params as a query string in the url.
412 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
413 * @return string url
415 function out($noquerystring = false, $overrideparams = array()) {
416 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
417 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
418 $uri .= $this->host ? $this->host : '';
419 $uri .= $this->port ? ':'.$this->port : '';
420 $uri .= $this->path ? $this->path : '';
421 if (!$noquerystring){
422 $uri .= (count($this->params)||count($overrideparams)) ? '?'.$this->get_query_string($overrideparams) : '';
424 $uri .= $this->fragment ? '#'.$this->fragment : '';
425 return $uri;
428 * Output action url with sesskey
430 * @param boolean $noquerystring whether to output page params as a query string in the url.
431 * @return string url
433 function out_action($overrideparams = array()) {
434 $overrideparams = array('sesskey'=> sesskey()) + $overrideparams;
435 return $this->out(false, $overrideparams);
440 * Determine if there is data waiting to be processed from a form
442 * Used on most forms in Moodle to check for data
443 * Returns the data as an object, if it's found.
444 * This object can be used in foreach loops without
445 * casting because it's cast to (array) automatically
447 * Checks that submitted POST data exists and returns it as object.
449 * @param string $url not used anymore
450 * @return mixed false or object
452 function data_submitted($url='') {
454 if (empty($_POST)) {
455 return false;
456 } else {
457 return (object)$_POST;
462 * Moodle replacement for php stripslashes() function,
463 * works also for objects and arrays.
465 * The standard php stripslashes() removes ALL backslashes
466 * even from strings - so C:\temp becomes C:temp - this isn't good.
467 * This function should work as a fairly safe replacement
468 * to be called on quoted AND unquoted strings (to be sure)
470 * @param mixed something to remove unsafe slashes from
471 * @return mixed
473 function stripslashes_safe($mixed) {
474 // there is no need to remove slashes from int, float and bool types
475 if (empty($mixed)) {
476 //nothing to do...
477 } else if (is_string($mixed)) {
478 if (ini_get_bool('magic_quotes_sybase')) { //only unescape single quotes
479 $mixed = str_replace("''", "'", $mixed);
480 } else { //the rest, simple and double quotes and backslashes
481 $mixed = str_replace("\\'", "'", $mixed);
482 $mixed = str_replace('\\"', '"', $mixed);
483 $mixed = str_replace('\\\\', '\\', $mixed);
485 } else if (is_array($mixed)) {
486 foreach ($mixed as $key => $value) {
487 $mixed[$key] = stripslashes_safe($value);
489 } else if (is_object($mixed)) {
490 $vars = get_object_vars($mixed);
491 foreach ($vars as $key => $value) {
492 $mixed->$key = stripslashes_safe($value);
496 return $mixed;
500 * Recursive implementation of stripslashes()
502 * This function will allow you to strip the slashes from a variable.
503 * If the variable is an array or object, slashes will be stripped
504 * from the items (or properties) it contains, even if they are arrays
505 * or objects themselves.
507 * @param mixed the variable to remove slashes from
508 * @return mixed
510 function stripslashes_recursive($var) {
511 if (is_object($var)) {
512 $new_var = new object();
513 $properties = get_object_vars($var);
514 foreach($properties as $property => $value) {
515 $new_var->$property = stripslashes_recursive($value);
518 } else if(is_array($var)) {
519 $new_var = array();
520 foreach($var as $property => $value) {
521 $new_var[$property] = stripslashes_recursive($value);
524 } else if(is_string($var)) {
525 $new_var = stripslashes($var);
527 } else {
528 $new_var = $var;
531 return $new_var;
535 * Recursive implementation of addslashes()
537 * This function will allow you to add the slashes from a variable.
538 * If the variable is an array or object, slashes will be added
539 * to the items (or properties) it contains, even if they are arrays
540 * or objects themselves.
542 * @param mixed the variable to add slashes from
543 * @return mixed
545 function addslashes_recursive($var) {
546 if (is_object($var)) {
547 $new_var = new object();
548 $properties = get_object_vars($var);
549 foreach($properties as $property => $value) {
550 $new_var->$property = addslashes_recursive($value);
553 } else if (is_array($var)) {
554 $new_var = array();
555 foreach($var as $property => $value) {
556 $new_var[$property] = addslashes_recursive($value);
559 } else if (is_string($var)) {
560 $new_var = addslashes($var);
562 } else { // nulls, integers, etc.
563 $new_var = $var;
566 return $new_var;
570 * Given some normal text this function will break up any
571 * long words to a given size by inserting the given character
573 * It's multibyte savvy and doesn't change anything inside html tags.
575 * @param string $string the string to be modified
576 * @param int $maxsize maximum length of the string to be returned
577 * @param string $cutchar the string used to represent word breaks
578 * @return string
580 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
582 /// Loading the textlib singleton instance. We are going to need it.
583 $textlib = textlib_get_instance();
585 /// First of all, save all the tags inside the text to skip them
586 $tags = array();
587 filter_save_tags($string,$tags);
589 /// Process the string adding the cut when necessary
590 $output = '';
591 $length = $textlib->strlen($string);
592 $wordlength = 0;
594 for ($i=0; $i<$length; $i++) {
595 $char = $textlib->substr($string, $i, 1);
596 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
597 $wordlength = 0;
598 } else {
599 $wordlength++;
600 if ($wordlength > $maxsize) {
601 $output .= $cutchar;
602 $wordlength = 0;
605 $output .= $char;
608 /// Finally load the tags back again
609 if (!empty($tags)) {
610 $output = str_replace(array_keys($tags), $tags, $output);
613 return $output;
617 * This does a search and replace, ignoring case
618 * This function is only used for versions of PHP older than version 5
619 * which do not have a native version of this function.
620 * Taken from the PHP manual, by bradhuizenga @ softhome.net
622 * @param string $find the string to search for
623 * @param string $replace the string to replace $find with
624 * @param string $string the string to search through
625 * return string
627 if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
628 function str_ireplace($find, $replace, $string) {
630 if (!is_array($find)) {
631 $find = array($find);
634 if(!is_array($replace)) {
635 if (!is_array($find)) {
636 $replace = array($replace);
637 } else {
638 // this will duplicate the string into an array the size of $find
639 $c = count($find);
640 $rString = $replace;
641 unset($replace);
642 for ($i = 0; $i < $c; $i++) {
643 $replace[$i] = $rString;
648 foreach ($find as $fKey => $fItem) {
649 $between = explode(strtolower($fItem),strtolower($string));
650 $pos = 0;
651 foreach($between as $bKey => $bItem) {
652 $between[$bKey] = substr($string,$pos,strlen($bItem));
653 $pos += strlen($bItem) + strlen($fItem);
655 $string = implode($replace[$fKey],$between);
657 return ($string);
662 * Locate the position of a string in another string
664 * This function is only used for versions of PHP older than version 5
665 * which do not have a native version of this function.
666 * Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
668 * @param string $haystack The string to be searched
669 * @param string $needle The string to search for
670 * @param int $offset The position in $haystack where the search should begin.
672 if (!function_exists('stripos')) { /// Only exists in PHP 5
673 function stripos($haystack, $needle, $offset=0) {
675 return strpos(strtoupper($haystack), strtoupper($needle), $offset);
680 * This function will print a button/link/etc. form element
681 * that will work on both Javascript and non-javascript browsers.
682 * Relies on the Javascript function openpopup in javascript.php
684 * All parameters default to null, only $type and $url are mandatory.
686 * $url must be relative to home page eg /mod/survey/stuff.php
687 * @param string $url Web link relative to home page
688 * @param string $name Name to be assigned to the popup window (this is used by
689 * client-side scripts to "talk" to the popup window)
690 * @param string $linkname Text to be displayed as web link
691 * @param int $height Height to assign to popup window
692 * @param int $width Height to assign to popup window
693 * @param string $title Text to be displayed as popup page title
694 * @param string $options List of additional options for popup window
695 * @param string $return If true, return as a string, otherwise print
696 * @param string $id id added to the element
697 * @param string $class class added to the element
698 * @return string
699 * @uses $CFG
701 function element_to_popup_window ($type=null, $url=null, $name=null, $linkname=null,
702 $height=400, $width=500, $title=null,
703 $options=null, $return=false, $id=null, $class=null) {
705 if (is_null($url)) {
706 debugging('You must give the url to display in the popup. URL is missing - can\'t create popup window.', DEBUG_DEVELOPER);
709 global $CFG;
711 if ($options == 'none') { // 'none' is legacy, should be removed in v2.0
712 $options = null;
715 // add some sane default options for popup windows
716 if (!$options) {
717 $options = 'menubar=0,location=0,scrollbars,resizable';
719 if ($width) {
720 $options .= ',width='. $width;
722 if ($height) {
723 $options .= ',height='. $height;
725 if ($id) {
726 $id = ' id="'.$id.'" ';
728 if ($class) {
729 $class = ' class="'.$class.'" ';
731 if ($name) {
732 $_name = $name;
733 if (($name = preg_replace("/\s/", '_', $name)) != $_name) {
734 debugging('The $name of a popup window shouldn\'t contain spaces - string modified. '. $_name .' changed to '. $name, DEBUG_DEVELOPER);
736 } else {
737 $name = 'popup';
740 // get some default string, using the localized version of legacy defaults
741 if (is_null($linkname) || $linkname === '') {
742 $linkname = get_string('clickhere');
744 if (!$title) {
745 $title = get_string('popupwindowname');
748 $fullscreen = 0; // must be passed to openpopup
749 $element = '';
751 switch ($type) {
752 case 'button' :
753 $element = '<input type="button" name="'. $name .'" title="'. $title .'" value="'. $linkname .'" '. $id . $class .
754 "onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
755 break;
756 case 'link' :
757 // some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
758 if (!(strpos($url,$CFG->wwwroot) === false)) {
759 $url = substr($url, strlen($CFG->wwwroot));
761 $element = '<a title="'. s(strip_tags($title)) .'" href="'. $CFG->wwwroot . $url .'" '.
762 "onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
763 break;
764 default :
765 error('Undefined element - can\'t create popup window.');
766 break;
769 if ($return) {
770 return $element;
771 } else {
772 echo $element;
777 * Creates and displays (or returns) a link to a popup window, using element_to_popup_window function.
779 * @return string html code to display a link to a popup window.
780 * @see element_to_popup_window()
782 function link_to_popup_window ($url, $name=null, $linkname=null,
783 $height=400, $width=500, $title=null,
784 $options=null, $return=false) {
786 return element_to_popup_window('link', $url, $name, $linkname, $height, $width, $title, $options, $return, null, null);
790 * Creates and displays (or returns) a buttons to a popup window, using element_to_popup_window function.
792 * @return string html code to display a button to a popup window.
793 * @see element_to_popup_window()
795 function button_to_popup_window ($url, $name=null, $linkname=null,
796 $height=400, $width=500, $title=null, $options=null, $return=false,
797 $id=null, $class=null) {
799 return element_to_popup_window('button', $url, $name, $linkname, $height, $width, $title, $options, $return, $id, $class);
804 * Prints a simple button to close a window
805 * @param string $name name of the window to close
806 * @param boolean $return whether this function should return a string or output it
807 * @return string if $return is true, nothing otherwise
809 function close_window_button($name='closewindow', $return=false) {
810 global $CFG;
812 $output = '';
814 $output .= '<div class="closewindow">' . "\n";
815 $output .= '<form action="#"><div>';
816 $output .= '<input type="button" onclick="self.close();" value="'.get_string($name).'" />';
817 $output .= '</div></form>';
818 $output .= '</div>' . "\n";
820 if ($return) {
821 return $output;
822 } else {
823 echo $output;
828 * Try and close the current window immediately using Javascript
829 * @param int $delay the delay in seconds before closing the window
831 function close_window($delay=0) {
833 <script type="text/javascript">
834 //<![CDATA[
835 function close_this_window() {
836 self.close();
838 setTimeout("close_this_window()", <?php echo $delay * 1000 ?>);
839 //]]>
840 </script>
841 <noscript><center>
842 <?php print_string('pleaseclose') ?>
843 </center></noscript>
844 <?php
845 die;
850 * Given an array of values, output the HTML for a select element with those options.
851 * Normally, you only need to use the first few parameters.
853 * @param array $options The options to offer. An array of the form
854 * $options[{value}] = {text displayed for that option};
855 * @param string $name the name of this form control, as in &lt;select name="..." ...
856 * @param string $selected the option to select initially, default none.
857 * @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
858 * Set this to '' if you don't want a 'nothing is selected' option.
859 * @param string $script in not '', then this is added to the &lt;select> element as an onchange handler.
860 * @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
861 * @param boolean $return if false (the default) the the output is printed directly, If true, the
862 * generated HTML is returned as a string.
863 * @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
864 * @param int $tabindex if give, sets the tabindex attribute on the &lt;select> element. Default none.
865 * @param string $id value to use for the id attribute of the &lt;select> element. If none is given,
866 * then a suitable one is constructed.
868 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
869 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0, $id='') {
871 if ($nothing == 'choose') {
872 $nothing = get_string('choose') .'...';
875 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
876 if ($disabled) {
877 $attributes .= ' disabled="disabled"';
880 if ($tabindex) {
881 $attributes .= ' tabindex="'.$tabindex.'"';
884 if ($id ==='') {
885 $id = 'menu'.$name;
886 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
887 $id = str_replace('[', '', $id);
888 $id = str_replace(']', '', $id);
891 $output = '<select id="'.$id.'" name="'. $name .'" '. $attributes .'>' . "\n";
892 if ($nothing) {
893 $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
894 if ($nothingvalue === $selected) {
895 $output .= ' selected="selected"';
897 $output .= '>'. $nothing .'</option>' . "\n";
899 if (!empty($options)) {
900 foreach ($options as $value => $label) {
901 $output .= ' <option value="'. s($value) .'"';
902 if ((string)$value == (string)$selected) {
903 $output .= ' selected="selected"';
905 if ($label === '') {
906 $output .= '>'. $value .'</option>' . "\n";
907 } else {
908 $output .= '>'. $label .'</option>' . "\n";
912 $output .= '</select>' . "\n";
914 if ($return) {
915 return $output;
916 } else {
917 echo $output;
922 * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
923 * Other options like choose_from_menu.
924 * @param string $name
925 * @param string $selected
926 * @param string $string (defaults to '')
927 * @param boolean $return whether this function should return a string or output it (defaults to false)
928 * @param boolean $disabled (defaults to false)
929 * @param int $tabindex
931 function choose_from_menu_yesno($name, $selected, $script = '',
932 $return = false, $disabled = false, $tabindex = 0) {
933 return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
934 $selected, '', $script, '0', $return, $disabled, $tabindex);
938 * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
939 * including option headings with the first level.
941 function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
942 $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
944 if ($nothing == 'choose') {
945 $nothing = get_string('choose') .'...';
948 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
949 if ($disabled) {
950 $attributes .= ' disabled="disabled"';
953 if ($tabindex) {
954 $attributes .= ' tabindex="'.$tabindex.'"';
957 $output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
958 if ($nothing) {
959 $output .= ' <option value="'. $nothingvalue .'"'. "\n";
960 if ($nothingvalue === $selected) {
961 $output .= ' selected="selected"';
963 $output .= '>'. $nothing .'</option>' . "\n";
965 if (!empty($options)) {
966 foreach ($options as $section => $values) {
968 $output .= ' <optgroup label="'. s(format_string($section)) .'">'."\n";
969 foreach ($values as $value => $label) {
970 $output .= ' <option value="'. format_string($value) .'"';
971 if ((string)$value == (string)$selected) {
972 $output .= ' selected="selected"';
974 if ($label === '') {
975 $output .= '>'. $value .'</option>' . "\n";
976 } else {
977 $output .= '>'. $label .'</option>' . "\n";
980 $output .= ' </optgroup>'."\n";
983 $output .= '</select>' . "\n";
985 if ($return) {
986 return $output;
987 } else {
988 echo $output;
994 * Given an array of values, creates a group of radio buttons to be part of a form
996 * @param array $options An array of value-label pairs for the radio group (values as keys)
997 * @param string $name Name of the radiogroup (unique in the form)
998 * @param string $checked The value that is already checked
1000 function choose_from_radio ($options, $name, $checked='', $return=false) {
1002 static $idcounter = 0;
1004 if (!$name) {
1005 $name = 'unnamed';
1008 $output = '<span class="radiogroup '.$name."\">\n";
1010 if (!empty($options)) {
1011 $currentradio = 0;
1012 foreach ($options as $value => $label) {
1013 $htmlid = 'auto-rb'.sprintf('%04d', ++$idcounter);
1014 $output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
1015 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
1016 if ($value == $checked) {
1017 $output .= ' checked="checked"';
1019 if ($label === '') {
1020 $output .= ' /> <label for="'.$htmlid.'">'. $value .'</label></span>' . "\n";
1021 } else {
1022 $output .= ' /> <label for="'.$htmlid.'">'. $label .'</label></span>' . "\n";
1024 $currentradio = ($currentradio + 1) % 2;
1028 $output .= '</span>' . "\n";
1030 if ($return) {
1031 return $output;
1032 } else {
1033 echo $output;
1037 /** Display an standard html checkbox with an optional label
1039 * @param string $name The name of the checkbox
1040 * @param string $value The valus that the checkbox will pass when checked
1041 * @param boolean $checked The flag to tell the checkbox initial state
1042 * @param string $label The label to be showed near the checkbox
1043 * @param string $alt The info to be inserted in the alt tag
1045 function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
1047 static $idcounter = 0;
1049 if (!$name) {
1050 $name = 'unnamed';
1053 if ($alt) {
1054 $alt = strip_tags($alt);
1055 } else {
1056 $alt = 'checkbox';
1059 if ($checked) {
1060 $strchecked = ' checked="checked"';
1061 } else {
1062 $strchecked = '';
1065 $htmlid = 'auto-cb'.sprintf('%04d', ++$idcounter);
1066 $output = '<span class="checkbox '.$name."\">";
1067 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ? ' onclick="'.$script.'" ' : '').' />';
1068 if(!empty($label)) {
1069 $output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
1071 $output .= '</span>'."\n";
1073 if (empty($return)) {
1074 echo $output;
1075 } else {
1076 return $output;
1081 /** Display an standard html text field with an optional label
1083 * @param string $name The name of the text field
1084 * @param string $value The value of the text field
1085 * @param string $label The label to be showed near the text field
1086 * @param string $alt The info to be inserted in the alt tag
1088 function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
1090 static $idcounter = 0;
1092 if (empty($name)) {
1093 $name = 'unnamed';
1096 if (empty($alt)) {
1097 $alt = 'textfield';
1100 if (!empty($maxlength)) {
1101 $maxlength = ' maxlength="'.$maxlength.'" ';
1104 $htmlid = 'auto-tf'.sprintf('%04d', ++$idcounter);
1105 $output = '<span class="textfield '.$name."\">";
1106 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
1108 $output .= '</span>'."\n";
1110 if (empty($return)) {
1111 echo $output;
1112 } else {
1113 return $output;
1120 * Implements a complete little popup form
1122 * @uses $CFG
1123 * @param string $common The URL up to the point of the variable that changes
1124 * @param array $options Alist of value-label pairs for the popup list
1125 * @param string $formid Id must be unique on the page (originaly $formname)
1126 * @param string $selected The option that is already selected
1127 * @param string $nothing The label for the "no choice" option
1128 * @param string $help The name of a help page if help is required
1129 * @param string $helptext The name of the label for the help button
1130 * @param boolean $return Indicates whether the function should return the text
1131 * as a string or echo it directly to the page being rendered
1132 * @param string $targetwindow The name of the target page to open the linked page in.
1133 * @param string $selectlabel Text to place in a [label] element - preferred for accessibility.
1134 * @param array $optionsextra TODO, an array?
1135 * @return string If $return is true then the entire form is returned as a string.
1136 * @todo Finish documenting this function<br>
1138 function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
1139 $targetwindow='self', $selectlabel='', $optionsextra=NULL) {
1141 global $CFG;
1142 static $go, $choose; /// Locally cached, in case there's lots on a page
1144 if (empty($options)) {
1145 return '';
1148 if (!isset($go)) {
1149 $go = get_string('go');
1152 if ($nothing == 'choose') {
1153 if (!isset($choose)) {
1154 $choose = get_string('choose');
1156 $nothing = $choose.'...';
1159 // changed reference to document.getElementById('id_abc') instead of document.abc
1160 // MDL-7861
1161 $output = '<form action="'.$CFG->wwwroot.'/course/jumpto.php"'.
1162 ' method="get" '.
1163 $CFG->frametarget.
1164 ' id="'.$formid.'"'.
1165 ' class="popupform">';
1166 if ($help) {
1167 $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
1168 } else {
1169 $button = '';
1172 if ($selectlabel) {
1173 $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
1176 //IE and Opera fire the onchange when ever you move into a dropdwown list with the keyboard.
1177 //onfocus will call a function inside dropdown.js. It fixes this IE/Opera behavior.
1178 if (check_browser_version('MSIE') || check_browser_version('Opera')) {
1179 $output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" onfocus="initSelect(\''.$formid.'\','.$targetwindow.')" name="jump">'."\n";
1181 //Other browser
1182 else {
1183 $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";
1186 if ($nothing != '') {
1187 $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
1190 $inoptgroup = false;
1192 foreach ($options as $value => $label) {
1194 if ($label == '--') { /// we are ending previous optgroup
1195 /// Check to see if we already have a valid open optgroup
1196 /// XHTML demands that there be at least 1 option within an optgroup
1197 if ($inoptgroup and (count($optgr) > 1) ) {
1198 $output .= implode('', $optgr);
1199 $output .= ' </optgroup>';
1201 $optgr = array();
1202 $inoptgroup = false;
1203 continue;
1204 } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
1206 /// Check to see if we already have a valid open optgroup
1207 /// XHTML demands that there be at least 1 option within an optgroup
1208 if ($inoptgroup and (count($optgr) > 1) ) {
1209 $output .= implode('', $optgr);
1210 $output .= ' </optgroup>';
1213 unset($optgr);
1214 $optgr = array();
1216 $optgr[] = ' <optgroup label="'. s(format_string(substr($label,2))) .'">'; // Plain labels
1218 $inoptgroup = true; /// everything following will be in an optgroup
1219 continue;
1221 } else {
1222 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()]))
1224 $url=sid_process_url( $common . $value );
1225 } else
1227 $url=$common . $value;
1229 $optstr = ' <option value="' . $url . '"';
1231 if ($value == $selected) {
1232 $optstr .= ' selected="selected"';
1235 if (!empty($optionsextra[$value])) {
1236 $optstr .= ' '.$optionsextra[$value];
1239 if ($label) {
1240 $optstr .= '>'. $label .'</option>' . "\n";
1241 } else {
1242 $optstr .= '>'. $value .'</option>' . "\n";
1245 if ($inoptgroup) {
1246 $optgr[] = $optstr;
1247 } else {
1248 $output .= $optstr;
1254 /// catch the final group if not closed
1255 if ($inoptgroup and count($optgr) > 1) {
1256 $output .= implode('', $optgr);
1257 $output .= ' </optgroup>';
1260 $output .= '</select>';
1261 $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1262 $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
1263 $output .= '<input type="submit" value="'.$go.'" /></div>';
1264 $output .= '<script type="text/javascript">'.
1265 "\n//<![CDATA[\n".
1266 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
1267 "\n//]]>\n".'</script>';
1268 $output .= '</div>';
1269 $output .= '</form>';
1271 if ($return) {
1272 return $output;
1273 } else {
1274 echo $output;
1280 * Prints some red text
1282 * @param string $error The text to be displayed in red
1284 function formerr($error) {
1286 if (!empty($error)) {
1287 echo '<span class="error">'. $error .'</span>';
1292 * Validates an email to make sure it makes sense.
1294 * @param string $address The email address to validate.
1295 * @return boolean
1297 function validate_email($address) {
1299 return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1300 '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1301 '@'.
1302 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1303 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
1304 $address));
1308 * Extracts file argument either from file parameter or PATH_INFO
1310 * @param string $scriptname name of the calling script
1311 * @return string file path (only safe characters)
1313 function get_file_argument($scriptname) {
1314 global $_SERVER;
1316 $relativepath = FALSE;
1318 // first try normal parameter (compatible method == no relative links!)
1319 $relativepath = optional_param('file', FALSE, PARAM_PATH);
1320 if ($relativepath === '/testslasharguments') {
1321 echo 'test -1 : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
1322 die;
1325 // then try extract file from PATH_INFO (slasharguments method)
1326 if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
1327 $path_info = $_SERVER['PATH_INFO'];
1328 // check that PATH_INFO works == must not contain the script name
1329 if (!strpos($path_info, $scriptname)) {
1330 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1331 if ($relativepath === '/testslasharguments') {
1332 echo 'test 1 : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
1333 die;
1338 // now if both fail try the old way
1339 // (for compatibility with misconfigured or older buggy php implementations)
1340 if (!$relativepath) {
1341 $arr = explode($scriptname, me());
1342 if (!empty($arr[1])) {
1343 $path_info = strip_querystring($arr[1]);
1344 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1345 if ($relativepath === '/testslasharguments') {
1346 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
1347 die;
1352 return $relativepath;
1356 * Searches the current environment variables for some slash arguments
1358 * @param string $file ?
1359 * @todo Finish documenting this function
1361 function get_slash_arguments($file='file.php') {
1363 if (!$string = me()) {
1364 return false;
1367 $pathinfo = explode($file, $string);
1369 if (!empty($pathinfo[1])) {
1370 return addslashes($pathinfo[1]);
1371 } else {
1372 return false;
1377 * Extracts arguments from "/foo/bar/something"
1378 * eg http://mysite.com/script.php/foo/bar/something
1380 * @param string $string ?
1381 * @param int $i ?
1382 * @return array|string
1383 * @todo Finish documenting this function
1385 function parse_slash_arguments($string, $i=0) {
1387 if (detect_munged_arguments($string)) {
1388 return false;
1390 $args = explode('/', $string);
1392 if ($i) { // return just the required argument
1393 return $args[$i];
1395 } else { // return the whole array
1396 array_shift($args); // get rid of the empty first one
1397 return $args;
1402 * Just returns an array of text formats suitable for a popup menu
1404 * @uses FORMAT_MOODLE
1405 * @uses FORMAT_HTML
1406 * @uses FORMAT_PLAIN
1407 * @uses FORMAT_MARKDOWN
1408 * @return array
1410 function format_text_menu() {
1412 return array (FORMAT_MOODLE => get_string('formattext'),
1413 FORMAT_HTML => get_string('formathtml'),
1414 FORMAT_PLAIN => get_string('formatplain'),
1415 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1419 * Given text in a variety of format codings, this function returns
1420 * the text as safe HTML.
1422 * This function should mainly be used for long strings like posts,
1423 * answers, glossary items etc. For short strings @see format_string().
1425 * @uses $CFG
1426 * @uses FORMAT_MOODLE
1427 * @uses FORMAT_HTML
1428 * @uses FORMAT_PLAIN
1429 * @uses FORMAT_WIKI
1430 * @uses FORMAT_MARKDOWN
1431 * @param string $text The text to be formatted. This is raw text originally from user input.
1432 * @param int $format Identifier of the text format to be used
1433 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1434 * @param array $options ?
1435 * @param int $courseid ?
1436 * @return string
1437 * @todo Finish documenting this function
1439 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1441 global $CFG, $COURSE;
1443 static $croncache = array();
1445 if ($text === '') {
1446 return ''; // no need to do any filters and cleaning
1449 if (!isset($options->trusttext)) {
1450 $options->trusttext = false;
1453 if (!isset($options->noclean)) {
1454 $options->noclean=false;
1456 if (!isset($options->nocache)) {
1457 $options->nocache=false;
1459 if (!isset($options->smiley)) {
1460 $options->smiley=true;
1462 if (!isset($options->filter)) {
1463 $options->filter=true;
1465 if (!isset($options->para)) {
1466 $options->para=true;
1468 if (!isset($options->newlines)) {
1469 $options->newlines=true;
1472 if (empty($courseid)) {
1473 $courseid = $COURSE->id;
1476 if (!empty($CFG->cachetext) and empty($options->nocache)) {
1477 $time = time() - $CFG->cachetext;
1478 $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);
1480 if (defined('FULLME') and FULLME == 'cron') {
1481 if (isset($croncache[$md5key])) {
1482 return $croncache[$md5key];
1486 if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
1487 if ($oldcacheitem->timemodified >= $time) {
1488 if (defined('FULLME') and FULLME == 'cron') {
1489 if (count($croncache) > 150) {
1490 reset($croncache);
1491 $key = key($croncache);
1492 unset($croncache[$key]);
1494 $croncache[$md5key] = $oldcacheitem->formattedtext;
1496 return $oldcacheitem->formattedtext;
1501 // trusttext overrides the noclean option!
1502 if ($options->trusttext) {
1503 if (trusttext_present($text)) {
1504 $text = trusttext_strip($text);
1505 if (!empty($CFG->enabletrusttext)) {
1506 $options->noclean = true;
1507 } else {
1508 $options->noclean = false;
1510 } else {
1511 $options->noclean = false;
1513 } else if (!debugging('', DEBUG_DEVELOPER)) {
1514 // strip any forgotten trusttext in non-developer mode
1515 // do not forget to disable text cache when debugging trusttext!!
1516 $text = trusttext_strip($text);
1519 $CFG->currenttextiscacheable = true; // Default status - can be changed by any filter
1521 switch ($format) {
1522 case FORMAT_HTML:
1523 if ($options->smiley) {
1524 replace_smilies($text);
1526 if (!$options->noclean) {
1527 $text = clean_text($text, FORMAT_HTML);
1529 if ($options->filter) {
1530 $text = filter_text($text, $courseid);
1532 break;
1534 case FORMAT_PLAIN:
1535 $text = s($text); // cleans dangerous JS
1536 $text = rebuildnolinktag($text);
1537 $text = str_replace(' ', '&nbsp; ', $text);
1538 $text = nl2br($text);
1539 break;
1541 case FORMAT_WIKI:
1542 // this format is deprecated
1543 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1544 this message as all texts should have been converted to Markdown format instead.
1545 Please post a bug report to http://moodle.org/bugs with information about where you
1546 saw this message.</p>'.s($text);
1547 break;
1549 case FORMAT_MARKDOWN:
1550 $text = markdown_to_html($text);
1551 if ($options->smiley) {
1552 replace_smilies($text);
1554 if (!$options->noclean) {
1555 $text = clean_text($text, FORMAT_HTML);
1558 if ($options->filter) {
1559 $text = filter_text($text, $courseid);
1561 break;
1563 default: // FORMAT_MOODLE or anything else
1564 $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
1565 if (!$options->noclean) {
1566 $text = clean_text($text, FORMAT_HTML);
1569 if ($options->filter) {
1570 $text = filter_text($text, $courseid);
1572 break;
1575 if (empty($options->nocache) and !empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
1576 if (defined('FULLME') and FULLME == 'cron') {
1577 // special static cron cache - no need to store it in db if its not already there
1578 if (count($croncache) > 150) {
1579 reset($croncache);
1580 $key = key($croncache);
1581 unset($croncache[$key]);
1583 $croncache[$md5key] = $text;
1584 return $text;
1587 $newcacheitem = new object();
1588 $newcacheitem->md5key = $md5key;
1589 $newcacheitem->formattedtext = addslashes($text);
1590 $newcacheitem->timemodified = time();
1591 if ($oldcacheitem) { // See bug 4677 for discussion
1592 $newcacheitem->id = $oldcacheitem->id;
1593 @update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1594 // It's unlikely that the cron cache cleaner could have
1595 // deleted this entry in the meantime, as it allows
1596 // some extra time to cover these cases.
1597 } else {
1598 @insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1599 // Again, it's possible that another user has caused this
1600 // record to be created already in the time that it took
1601 // to traverse this function. That's OK too, as the
1602 // call above handles duplicate entries, and eventually
1603 // the cron cleaner will delete them.
1607 return $text;
1610 /** Converts the text format from the value to the 'internal'
1611 * name or vice versa. $key can either be the value or the name
1612 * and you get the other back.
1614 * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1615 * @return mixed as above but the other way around!
1617 function text_format_name( $key ) {
1618 $lookup = array();
1619 $lookup[FORMAT_MOODLE] = 'moodle';
1620 $lookup[FORMAT_HTML] = 'html';
1621 $lookup[FORMAT_PLAIN] = 'plain';
1622 $lookup[FORMAT_MARKDOWN] = 'markdown';
1623 $value = "error";
1624 if (!is_numeric($key)) {
1625 $key = strtolower( $key );
1626 $value = array_search( $key, $lookup );
1628 else {
1629 if (isset( $lookup[$key] )) {
1630 $value = $lookup[ $key ];
1633 return $value;
1637 * Resets all data related to filters, called during upgrade or when filter settings change.
1638 * @return void
1640 function reset_text_filters_cache() {
1641 global $CFG;
1643 delete_records('cache_text');
1644 $purifdir = $CFG->dataroot.'/cache/htmlpurifier';
1645 remove_dir($purifdir, true);
1648 /** Given a simple string, this function returns the string
1649 * processed by enabled string filters if $CFG->filterall is enabled
1651 * This function should be used to print short strings (non html) that
1652 * need filter processing e.g. activity titles, post subjects,
1653 * glossary concepts.
1655 * @param string $string The string to be filtered.
1656 * @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
1657 * @param int $courseid Current course as filters can, potentially, use it
1658 * @return string
1660 function format_string ($string, $striplinks=true, $courseid=NULL ) {
1662 global $CFG, $COURSE;
1664 //We'll use a in-memory cache here to speed up repeated strings
1665 static $strcache = false;
1667 if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
1668 $strcache = array();
1671 //init course id
1672 if (empty($courseid)) {
1673 $courseid = $COURSE->id;
1676 //Calculate md5
1677 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
1679 //Fetch from cache if possible
1680 if (isset($strcache[$md5])) {
1681 return $strcache[$md5];
1684 // First replace all ampersands not followed by html entity code
1685 $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1687 if (!empty($CFG->filterall)) {
1688 $string = filter_string($string, $courseid);
1691 // If the site requires it, strip ALL tags from this string
1692 if (!empty($CFG->formatstringstriptags)) {
1693 $string = strip_tags($string);
1695 // Otherwise strip just links if that is required (default)
1696 } else if ($striplinks) { //strip links in string
1697 $string = preg_replace('/(<a[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1700 //Store to cache
1701 $strcache[$md5] = $string;
1703 return $string;
1707 * Given text in a variety of format codings, this function returns
1708 * the text as plain text suitable for plain email.
1710 * @uses FORMAT_MOODLE
1711 * @uses FORMAT_HTML
1712 * @uses FORMAT_PLAIN
1713 * @uses FORMAT_WIKI
1714 * @uses FORMAT_MARKDOWN
1715 * @param string $text The text to be formatted. This is raw text originally from user input.
1716 * @param int $format Identifier of the text format to be used
1717 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1718 * @return string
1720 function format_text_email($text, $format) {
1722 switch ($format) {
1724 case FORMAT_PLAIN:
1725 return $text;
1726 break;
1728 case FORMAT_WIKI:
1729 $text = wiki_to_html($text);
1730 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1731 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
1732 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1733 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1734 break;
1736 case FORMAT_HTML:
1737 return html_to_text($text);
1738 break;
1740 case FORMAT_MOODLE:
1741 case FORMAT_MARKDOWN:
1742 default:
1743 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1744 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1745 break;
1750 * Given some text in HTML format, this function will pass it
1751 * through any filters that have been defined in $CFG->textfilterx
1752 * The variable defines a filepath to a file containing the
1753 * filter function. The file must contain a variable called
1754 * $textfilter_function which contains the name of the function
1755 * with $courseid and $text parameters
1757 * @param string $text The text to be passed through format filters
1758 * @param int $courseid ?
1759 * @return string
1760 * @todo Finish documenting this function
1762 function filter_text($text, $courseid=NULL) {
1763 global $CFG, $COURSE;
1765 if (empty($courseid)) {
1766 $courseid = $COURSE->id; // (copied from format_text)
1769 if (!empty($CFG->textfilters)) {
1770 require_once($CFG->libdir.'/filterlib.php');
1771 $textfilters = explode(',', $CFG->textfilters);
1772 foreach ($textfilters as $textfilter) {
1773 if (is_readable($CFG->dirroot .'/'. $textfilter .'/filter.php')) {
1774 include_once($CFG->dirroot .'/'. $textfilter .'/filter.php');
1775 $functionname = basename($textfilter).'_filter';
1776 if (function_exists($functionname)) {
1777 $text = $functionname($courseid, $text);
1783 /// <nolink> tags removed for XHTML compatibility
1784 $text = str_replace('<nolink>', '', $text);
1785 $text = str_replace('</nolink>', '', $text);
1787 return $text;
1792 * Given a string (short text) in HTML format, this function will pass it
1793 * through any filters that have been defined in $CFG->stringfilters
1794 * The variable defines a filepath to a file containing the
1795 * filter function. The file must contain a variable called
1796 * $textfilter_function which contains the name of the function
1797 * with $courseid and $text parameters
1799 * @param string $string The text to be passed through format filters
1800 * @param int $courseid The id of a course
1801 * @return string
1803 function filter_string($string, $courseid=NULL) {
1804 global $CFG, $COURSE;
1806 if (empty($CFG->textfilters)) { // All filters are disabled anyway so quit
1807 return $string;
1810 if (empty($courseid)) {
1811 $courseid = $COURSE->id;
1814 require_once($CFG->libdir.'/filterlib.php');
1816 if (isset($CFG->stringfilters)) { // We have a predefined list to use, great!
1817 if (empty($CFG->stringfilters)) { // but it's blank, so finish now
1818 return $string;
1820 $stringfilters = explode(',', $CFG->stringfilters); // ..use the list we have
1822 } else { // Otherwise try to derive a list from textfilters
1823 if (strpos($CFG->textfilters, 'filter/multilang') !== false) { // Multilang is here
1824 $stringfilters = array('filter/multilang'); // Let's use just that
1825 $CFG->stringfilters = 'filter/multilang'; // Save it for next time through
1826 } else {
1827 $CFG->stringfilters = ''; // Save the result and return
1828 return $string;
1833 foreach ($stringfilters as $stringfilter) {
1834 if (is_readable($CFG->dirroot .'/'. $stringfilter .'/filter.php')) {
1835 include_once($CFG->dirroot .'/'. $stringfilter .'/filter.php');
1836 $functionname = basename($stringfilter).'_filter';
1837 if (function_exists($functionname)) {
1838 $string = $functionname($courseid, $string);
1843 /// <nolink> tags removed for XHTML compatibility
1844 $string = str_replace('<nolink>', '', $string);
1845 $string = str_replace('</nolink>', '', $string);
1847 return $string;
1851 * Is the text marked as trusted?
1853 * @param string $text text to be searched for TRUSTTEXT marker
1854 * @return boolean
1856 function trusttext_present($text) {
1857 if (strpos($text, TRUSTTEXT) !== FALSE) {
1858 return true;
1859 } else {
1860 return false;
1865 * This funtion MUST be called before the cleaning or any other
1866 * function that modifies the data! We do not know the origin of trusttext
1867 * in database, if it gets there in tweaked form we must not convert it
1868 * to supported form!!!
1870 * Please be carefull not to use stripslashes on data from database
1871 * or twice stripslashes when processing data recieved from user.
1873 * @param string $text text that may contain TRUSTTEXT marker
1874 * @return text without any TRUSTTEXT marker
1876 function trusttext_strip($text) {
1877 global $CFG;
1879 while (true) { //removing nested TRUSTTEXT
1880 $orig = $text;
1881 $text = str_replace(TRUSTTEXT, '', $text);
1882 if (strcmp($orig, $text) === 0) {
1883 return $text;
1889 * Mark text as trusted, such text may contain any HTML tags because the
1890 * normal text cleaning will be bypassed.
1891 * Please make sure that the text comes from trusted user before storing
1892 * it into database!
1894 function trusttext_mark($text) {
1895 global $CFG;
1896 if (!empty($CFG->enabletrusttext) and (strpos($text, TRUSTTEXT) === FALSE)) {
1897 return TRUSTTEXT.$text;
1898 } else {
1899 return $text;
1902 function trusttext_after_edit(&$text, $context) {
1903 if (has_capability('moodle/site:trustcontent', $context)) {
1904 $text = trusttext_strip($text);
1905 $text = trusttext_mark($text);
1906 } else {
1907 $text = trusttext_strip($text);
1911 function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
1912 global $CFG;
1914 $options = new object();
1915 $options->smiley = false;
1916 $options->filter = false;
1917 if (!empty($CFG->enabletrusttext)
1918 and has_capability('moodle/site:trustcontent', $context)
1919 and trusttext_present($text)) {
1920 $options->noclean = true;
1921 } else {
1922 $options->noclean = false;
1924 $text = trusttext_strip($text);
1925 if ($usehtmleditor) {
1926 $text = format_text($text, $format, $options);
1927 $format = FORMAT_HTML;
1928 } else if (!$options->noclean){
1929 $text = clean_text($text, $format);
1934 * Given raw text (eg typed in by a user), this function cleans it up
1935 * and removes any nasty tags that could mess up Moodle pages.
1937 * @uses FORMAT_MOODLE
1938 * @uses FORMAT_PLAIN
1939 * @uses ALLOWED_TAGS
1940 * @param string $text The text to be cleaned
1941 * @param int $format Identifier of the text format to be used
1942 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1943 * @return string The cleaned up text
1945 function clean_text($text, $format=FORMAT_MOODLE) {
1947 global $ALLOWED_TAGS, $CFG;
1949 if (empty($text) or is_numeric($text)) {
1950 return (string)$text;
1953 switch ($format) {
1954 case FORMAT_PLAIN:
1955 case FORMAT_MARKDOWN:
1956 return $text;
1958 default:
1960 if (!empty($CFG->enablehtmlpurifier)) {
1961 $text = purify_html($text);
1962 } else {
1963 /// Fix non standard entity notations
1964 $text = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $text);
1965 $text = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $text);
1967 /// Remove tags that are not allowed
1968 $text = strip_tags($text, $ALLOWED_TAGS);
1970 /// Clean up embedded scripts and , using kses
1971 $text = cleanAttributes($text);
1973 /// Again remove tags that are not allowed
1974 $text = strip_tags($text, $ALLOWED_TAGS);
1978 /// Remove potential script events - some extra protection for undiscovered bugs in our code
1979 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
1980 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
1982 return $text;
1987 * KSES replacement cleaning function - uses HTML Purifier.
1989 function purify_html($text) {
1990 global $CFG;
1992 // this can not be done only once because we sometimes need to reset the cache
1993 $cachedir = $CFG->dataroot.'/cache/htmlpurifier/';
1994 $status = check_dir_exists($cachedir, true, true);
1996 static $purifier = false;
1997 if ($purifier === false) {
1998 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.auto.php';
1999 $config = HTMLPurifier_Config::createDefault();
2000 $config->set('Core', 'AcceptFullDocuments', false);
2001 $config->set('Core', 'Encoding', 'UTF-8');
2002 $config->set('HTML', 'Doctype', 'XHTML 1.0 Transitional');
2003 $config->set('Cache', 'SerializerPath', $cachedir);
2004 $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));
2005 $purifier = new HTMLPurifier($config);
2007 return $purifier->purify($text);
2011 * This function takes a string and examines it for HTML tags.
2012 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
2013 * which checks for attributes and filters them for malicious content
2014 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2016 * @param string $str The string to be examined for html tags
2017 * @return string
2019 function cleanAttributes($str){
2020 $result = preg_replace_callback(
2021 '%(<[^>]*(>|$)|>)%m', #search for html tags
2022 "cleanAttributes2",
2023 $str
2025 return $result;
2029 * This function takes a string with an html tag and strips out any unallowed
2030 * protocols e.g. javascript:
2031 * It calls ancillary functions in kses which are prefixed by kses
2032 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2034 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
2035 * element the html to be cleared
2036 * @return string
2038 function cleanAttributes2($htmlArray){
2040 global $CFG, $ALLOWED_PROTOCOLS;
2041 require_once($CFG->libdir .'/kses.php');
2043 $htmlTag = $htmlArray[1];
2044 if (substr($htmlTag, 0, 1) != '<') {
2045 return '&gt;'; //a single character ">" detected
2047 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
2048 return ''; // It's seriously malformed
2050 $slash = trim($matches[1]); //trailing xhtml slash
2051 $elem = $matches[2]; //the element name
2052 $attrlist = $matches[3]; // the list of attributes as a string
2054 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
2056 $attStr = '';
2057 foreach ($attrArray as $arreach) {
2058 $arreach['name'] = strtolower($arreach['name']);
2059 if ($arreach['name'] == 'style') {
2060 $value = $arreach['value'];
2061 while (true) {
2062 $prevvalue = $value;
2063 $value = kses_no_null($value);
2064 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
2065 $value = kses_decode_entities($value);
2066 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
2067 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
2068 if ($value === $prevvalue) {
2069 $arreach['value'] = $value;
2070 break;
2073 $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']);
2074 $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']);
2075 $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
2076 } else if ($arreach['name'] == 'href') {
2077 //Adobe Acrobat Reader XSS protection
2078 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd))[^a-z0-9_\.\-].*$/i', '$1', $arreach['value']);
2080 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
2083 $xhtml_slash = '';
2084 if (preg_match('%/\s*$%', $attrlist)) {
2085 $xhtml_slash = ' /';
2087 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
2091 * Replaces all known smileys in the text with image equivalents
2093 * @uses $CFG
2094 * @param string $text Passed by reference. The string to search for smily strings.
2095 * @return string
2097 function replace_smilies(&$text) {
2099 global $CFG;
2101 if (empty($CFG->emoticons)) { /// No emoticons defined, nothing to process here
2102 return;
2105 $lang = current_language();
2106 $emoticonstring = $CFG->emoticons;
2107 static $e = array();
2108 static $img = array();
2109 static $emoticons = null;
2111 if (is_null($emoticons)) {
2112 $emoticons = array();
2113 if ($emoticonstring) {
2114 $items = explode('{;}', $CFG->emoticons);
2115 foreach ($items as $item) {
2116 $item = explode('{:}', $item);
2117 $emoticons[$item[0]] = $item[1];
2123 if (empty($img[$lang])) { /// After the first time this is not run again
2124 $e[$lang] = array();
2125 $img[$lang] = array();
2126 foreach ($emoticons as $emoticon => $image){
2127 $alttext = get_string($image, 'pix');
2128 $e[$lang][] = $emoticon;
2129 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath .'/s/'. $image .'.gif" />';
2133 // Exclude from transformations all the code inside <script> tags
2134 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
2135 // Based on code from glossary fiter by Williams Castillo.
2136 // - Eloy
2138 // Detect all the <script> zones to take out
2139 $excludes = array();
2140 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
2142 // Take out all the <script> zones from text
2143 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
2144 $excludes['<+'.$key.'+>'] = $value;
2146 if ($excludes) {
2147 $text = str_replace($excludes,array_keys($excludes),$text);
2150 /// this is the meat of the code - this is run every time
2151 $text = str_replace($e[$lang], $img[$lang], $text);
2153 // Recover all the <script> zones to text
2154 if ($excludes) {
2155 $text = str_replace(array_keys($excludes),$excludes,$text);
2160 * Given plain text, makes it into HTML as nicely as possible.
2161 * May contain HTML tags already
2163 * @uses $CFG
2164 * @param string $text The string to convert.
2165 * @param boolean $smiley Convert any smiley characters to smiley images?
2166 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
2167 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2168 * @return string
2171 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
2174 global $CFG;
2176 /// Remove any whitespace that may be between HTML tags
2177 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
2179 /// Remove any returns that precede or follow HTML tags
2180 $text = eregi_replace("([\n\r])<", " <", $text);
2181 $text = eregi_replace(">([\n\r])", "> ", $text);
2183 convert_urls_into_links($text);
2185 /// Make returns into HTML newlines.
2186 if ($newlines) {
2187 $text = nl2br($text);
2190 /// Turn smileys into images.
2191 if ($smiley) {
2192 replace_smilies($text);
2195 /// Wrap the whole thing in a paragraph tag if required
2196 if ($para) {
2197 return '<p>'.$text.'</p>';
2198 } else {
2199 return $text;
2204 * Given Markdown formatted text, make it into XHTML using external function
2206 * @uses $CFG
2207 * @param string $text The markdown formatted text to be converted.
2208 * @return string Converted text
2210 function markdown_to_html($text) {
2211 global $CFG;
2213 require_once($CFG->libdir .'/markdown.php');
2215 return Markdown($text);
2219 * Given HTML text, make it into plain text using external function
2221 * @uses $CFG
2222 * @param string $html The text to be converted.
2223 * @return string
2225 function html_to_text($html) {
2227 global $CFG;
2229 require_once($CFG->libdir .'/html2text.php');
2231 return html2text($html);
2235 * Given some text this function converts any URLs it finds into HTML links
2237 * @param string $text Passed in by reference. The string to be searched for urls.
2239 function convert_urls_into_links(&$text) {
2240 /// Make lone URLs into links. eg http://moodle.com/
2241 $text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
2242 "\\1<a href=\"\\2://\\3\\4\" target=\"_blank\">\\2://\\3\\4</a>", $text);
2244 /// eg www.moodle.com
2245 $text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
2246 "\\1<a href=\"http://www.\\2\\3\" target=\"_blank\">www.\\2\\3</a>", $text);
2250 * This function will highlight search words in a given string
2251 * It cares about HTML and will not ruin links. It's best to use
2252 * this function after performing any conversions to HTML.
2253 * Function found here: http://forums.devshed.com/t67822/scdaa2d1c3d4bacb4671d075ad41f0854.html
2255 * @param string $needle The string to search for
2256 * @param string $haystack The string to search for $needle in
2257 * @param int $case whether to do case-sensitive or insensitive matching.
2258 * @return string
2259 * @todo Finish documenting this function
2261 function highlight($needle, $haystack, $case=0,
2262 $left_string='<span class="highlight">', $right_string='</span>') {
2264 if (empty($needle) or empty($haystack)) {
2265 return $haystack;
2268 //$list_of_words = eregi_replace("[^-a-zA-Z0-9&.']", " ", $needle); // bug 3101
2269 $list_of_words = $needle;
2270 $list_array = explode(' ', $list_of_words);
2271 for ($i=0; $i<sizeof($list_array); $i++) {
2272 if (strlen($list_array[$i]) == 1) {
2273 $list_array[$i] = '';
2276 $list_of_words = implode(' ', $list_array);
2277 $list_of_words_cp = $list_of_words;
2278 $final = array();
2279 preg_match_all('/<(.+?)>/is',$haystack,$list_of_words);
2281 foreach (array_unique($list_of_words[0]) as $key=>$value) {
2282 $final['<|'.$key.'|>'] = $value;
2285 $haystack = str_replace($final,array_keys($final),$haystack);
2286 $list_of_words_cp = eregi_replace(' +', '|', $list_of_words_cp);
2288 if ($list_of_words_cp{0}=='|') {
2289 $list_of_words_cp{0} = '';
2291 if ($list_of_words_cp{strlen($list_of_words_cp)-1}=='|') {
2292 $list_of_words_cp{strlen($list_of_words_cp)-1}='';
2295 $list_of_words_cp = trim($list_of_words_cp);
2297 if ($list_of_words_cp) {
2299 $list_of_words_cp = "(". $list_of_words_cp .")";
2301 if (!$case){
2302 $haystack = eregi_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2303 } else {
2304 $haystack = ereg_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2307 $haystack = str_replace(array_keys($final),$final,$haystack);
2309 return $haystack;
2313 * This function will highlight instances of $needle in $haystack
2314 * It's faster that the above function and doesn't care about
2315 * HTML or anything.
2317 * @param string $needle The string to search for
2318 * @param string $haystack The string to search for $needle in
2319 * @return string
2321 function highlightfast($needle, $haystack) {
2323 if (empty($needle) or empty($haystack)) {
2324 return $haystack;
2327 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
2329 if (count($parts) === 1) {
2330 return $haystack;
2333 $pos = 0;
2335 foreach ($parts as $key => $part) {
2336 $parts[$key] = substr($haystack, $pos, strlen($part));
2337 $pos += strlen($part);
2339 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2340 $pos += strlen($needle);
2343 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2347 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2348 * Internationalisation, for print_header and backup/restorelib.
2349 * @param $dir Default false.
2350 * @return string Attributes.
2352 function get_html_lang($dir = false) {
2353 $direction = '';
2354 if ($dir) {
2355 if (get_string('thisdirection') == 'rtl') {
2356 $direction = ' dir="rtl"';
2357 } else {
2358 $direction = ' dir="ltr"';
2361 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2362 $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
2363 @header('Content-Language: '.$language);
2364 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2368 * Return the markup for the destination of the 'Skip to main content' links.
2369 * Accessibility improvement for keyboard-only users.
2370 * Used in course formats, /index.php and /course/index.php
2371 * @return string HTML element.
2373 function skip_main_destination() {
2374 return '<span id="maincontent"></span>';
2378 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
2381 * Print a standard header
2383 * @uses $USER
2384 * @uses $CFG
2385 * @uses $SESSION
2386 * @param string $title Appears at the top of the window
2387 * @param string $heading Appears at the top of the page
2388 * @param array $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
2389 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2390 * @param string $meta Meta tags to be added to the header
2391 * @param boolean $cache Should this page be cacheable?
2392 * @param string $button HTML code for a button (usually for module editing)
2393 * @param string $menu HTML code for a popup menu
2394 * @param boolean $usexml use XML for this page
2395 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2396 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2398 function print_header ($title='', $heading='', $navigation='', $focus='',
2399 $meta='', $cache=true, $button='&nbsp;', $menu='',
2400 $usexml=false, $bodytags='', $return=false) {
2402 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
2404 if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
2405 debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
2406 . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.", DEBUG_DEVELOPER);
2409 $heading = format_string($heading); // Fix for MDL-8582
2411 /// This makes sure that the header is never repeated twice on a page
2412 if (defined('HEADER_PRINTED')) {
2413 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().');
2414 return;
2416 define('HEADER_PRINTED', 'true');
2419 /// Add the required stylesheets
2420 $stylesheetshtml = '';
2421 foreach ($CFG->stylesheets as $stylesheet) {
2422 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2424 $meta = $stylesheetshtml.$meta;
2427 /// Add the meta page from the themes if any were requested
2429 $metapage = '';
2431 if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
2432 ob_start();
2433 include_once($CFG->dirroot.'/theme/standard/meta.php');
2434 $metapage .= ob_get_contents();
2435 ob_end_clean();
2438 if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
2439 if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
2440 ob_start();
2441 include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
2442 $metapage .= ob_get_contents();
2443 ob_end_clean();
2447 if (!isset($THEME->metainclude) || $THEME->metainclude) {
2448 if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
2449 ob_start();
2450 include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
2451 $metapage .= ob_get_contents();
2452 ob_end_clean();
2456 $meta = $meta."\n".$metapage;
2458 $meta .= "\n".require_js('',1);
2460 /// Set up some navigation variables
2462 if (is_newnav($navigation)){
2463 $home = false;
2464 } else {
2465 if ($navigation == 'home') {
2466 $home = true;
2467 $navigation = '';
2468 } else {
2469 $home = false;
2473 /// This is another ugly hack to make navigation elements available to print_footer later
2474 $THEME->title = $title;
2475 $THEME->heading = $heading;
2476 $THEME->navigation = $navigation;
2477 $THEME->button = $button;
2478 $THEME->menu = $menu;
2479 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2481 if ($button == '') {
2482 $button = '&nbsp;';
2485 if (!$menu and $navigation) {
2486 if (empty($CFG->loginhttps)) {
2487 $wwwroot = $CFG->wwwroot;
2488 } else {
2489 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
2491 $menu = user_login_string($COURSE);
2494 if (isset($SESSION->justloggedin)) {
2495 unset($SESSION->justloggedin);
2496 if (!empty($CFG->displayloginfailures)) {
2497 if (!empty($USER->username) and $USER->username != 'guest') {
2498 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
2499 $menu .= '&nbsp;<font size="1">';
2500 if (empty($count->accounts)) {
2501 $menu .= get_string('failedloginattempts', '', $count);
2502 } else {
2503 $menu .= get_string('failedloginattemptsall', '', $count);
2505 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_SYSTEM))) {
2506 $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
2507 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
2509 $menu .= '</font>';
2516 $meta = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' .
2517 "\n" . $meta . "\n";
2518 if (!$usexml) {
2519 @header('Content-Type: text/html; charset=utf-8');
2521 @header('Content-Script-Type: text/javascript');
2522 @header('Content-Style-Type: text/css');
2524 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2525 $direction = get_html_lang($dir=true);
2527 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2528 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2529 @header('Pragma: no-cache');
2530 @header('Expires: ');
2531 } else { // Do everything we can to always prevent clients and proxies caching
2532 @header('Cache-Control: no-store, no-cache, must-revalidate');
2533 @header('Cache-Control: post-check=0, pre-check=0', false);
2534 @header('Pragma: no-cache');
2535 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2536 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2538 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2539 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
2541 @header('Accept-Ranges: none');
2543 $currentlanguage = current_language();
2545 if (empty($usexml)) {
2546 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2547 } else {
2548 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2549 if(!$mathplayer) {
2550 header('Content-Type: application/xhtml+xml');
2552 echo '<?xml version="1.0" ?>'."\n";
2553 if (!empty($CFG->xml_stylesheets)) {
2554 $stylesheets = explode(';', $CFG->xml_stylesheets);
2555 foreach ($stylesheets as $stylesheet) {
2556 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
2559 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
2560 if (!empty($CFG->xml_doctype_extra)) {
2561 echo ' plus '. $CFG->xml_doctype_extra;
2563 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
2564 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2565 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
2566 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2567 $direction";
2568 if($mathplayer) {
2569 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
2570 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2571 $meta .= '</object>'."\n";
2572 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2576 // Clean up the title
2578 $title = format_string($title); // fix for MDL-8582
2579 $title = str_replace('"', '&quot;', $title);
2581 // Create class and id for this page
2583 page_id_and_class($pageid, $pageclass);
2585 $pageclass .= ' course-'.$COURSE->id;
2587 if (!isloggedin()) {
2588 $pageclass .= ' notloggedin';
2591 if (!empty($USER->editing)) {
2592 $pageclass .= ' editing';
2595 if (!empty($CFG->blocksdrag)) {
2596 $pageclass .= ' drag';
2599 $pageclass .= ' dir-'.get_string('thisdirection');
2601 $pageclass .= ' lang-'.$currentlanguage;
2603 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
2605 ob_start();
2606 include($CFG->header);
2607 $output = ob_get_contents();
2608 ob_end_clean();
2610 // container debugging info
2611 $THEME->open_header_containers = open_containers();
2613 // Skip to main content, see skip_main_destination().
2614 if ($pageid=='course-view' or $pageid=='site-index' or $pageid=='course-index') {
2615 $skiplink = '<a class="skip" href="#maincontent">'.get_string('tocontent', 'access').'</a>';
2616 if (! preg_match('/(.*<div[^>]+id="page"[^>]*>)(.*)/s', $output, $matches)) {
2617 preg_match('/(.*<body.*?>)(.*)/s', $output, $matches);
2619 $output = $matches[1]."\n". $skiplink .$matches[2];
2622 $output = force_strict_header($output);
2624 if (!empty($CFG->messaging)) {
2625 $output .= message_popup_window();
2628 // Add in any extra JavaScript libraries that occurred during the header
2629 $output .= require_js('', 2);
2631 if ($return) {
2632 return $output;
2633 } else {
2634 echo $output;
2639 * Used to include JavaScript libraries.
2641 * When the $lib parameter is given, the function will ensure that the
2642 * named library is loaded onto the page - either in the HTML <head>,
2643 * just after the header, or at an arbitrary later point in the page,
2644 * depending on where this function is called.
2646 * Libraries will not be included more than once, so this works like
2647 * require_once in PHP.
2649 * There are two special-case calls to this function which are both used only
2650 * by weblib print_header:
2651 * $extracthtml = 1: this is used before printing the header.
2652 * It returns the script tag code that should go inside the <head>.
2653 * $extracthtml = 2: this is used after printing the header and handles any
2654 * require_js calls that occurred within the header itself.
2656 * @param mixed $lib - string or array of strings
2657 * string(s) should be the shortname for the library or the
2658 * full path to the library file.
2659 * @param int $extracthtml Do not set this parameter usually (leave 0), only
2660 * weblib should set this to 1 or 2 in print_header function.
2661 * @return mixed No return value, except when using $extracthtml it returns the html code.
2663 function require_js($lib,$extracthtml=0) {
2664 global $CFG;
2665 static $loadlibs = array();
2667 static $state = REQUIREJS_BEFOREHEADER;
2668 static $latecode = '';
2670 if (!empty($lib)) {
2671 // Add the lib to the list of libs to be loaded, if it isn't already
2672 // in the list.
2673 if (is_array($lib)) {
2674 foreach($lib as $singlelib) {
2675 require_js($singlelib);
2677 } else {
2678 $libpath = ajax_get_lib($lib);
2679 if (array_search($libpath, $loadlibs) === false) {
2680 $loadlibs[] = $libpath;
2682 // For state other than 0 we need to take action as well as just
2683 // adding it to loadlibs
2684 if($state != REQUIREJS_BEFOREHEADER) {
2685 // Get the script statement for this library
2686 $scriptstatement=get_require_js_code(array($libpath));
2688 if($state == REQUIREJS_AFTERHEADER) {
2689 // After the header, print it immediately
2690 print $scriptstatement;
2691 } else {
2692 // Haven't finished the header yet. Add it after the
2693 // header
2694 $latecode .= $scriptstatement;
2699 } else if($extracthtml==1) {
2700 if($state !== REQUIREJS_BEFOREHEADER) {
2701 debugging('Incorrect state in require_js (expected BEFOREHEADER): be careful not to call with empty $lib (except in print_header)');
2702 } else {
2703 $state = REQUIREJS_INHEADER;
2706 return get_require_js_code($loadlibs);
2707 } else if($extracthtml==2) {
2708 if($state !== REQUIREJS_INHEADER) {
2709 debugging('Incorrect state in require_js (expected INHEADER): be careful not to call with empty $lib (except in print_header)');
2710 return '';
2711 } else {
2712 $state = REQUIREJS_AFTERHEADER;
2713 return $latecode;
2715 } else {
2716 debugging('Unexpected value for $extracthtml');
2721 * Should not be called directly - use require_js. This function obtains the code
2722 * (script tags) needed to include JavaScript libraries.
2723 * @param array $loadlibs Array of library files to include
2724 * @return string HTML code to include them
2726 function get_require_js_code($loadlibs) {
2727 global $CFG;
2728 // Return the html needed to load the JavaScript files defined in
2729 // our list of libs to be loaded.
2730 $output = '';
2731 foreach ($loadlibs as $loadlib) {
2732 $output .= '<script type="text/javascript" ';
2733 $output .= " src=\"$loadlib\"></script>\n";
2734 if ($loadlib == $CFG->wwwroot.'/lib/yui/logger/logger-min.js') {
2735 // Special case, we need the CSS too.
2736 $output .= '<link type="text/css" rel="stylesheet" ';
2737 $output .= " href=\"{$CFG->wwwroot}/lib/yui/logger/assets/logger.css\" />\n";
2740 return $output;
2745 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2746 * and substitute the XHTML strict document type.
2747 * Note, requires the 'xmlns' fix in function print_header above.
2748 * See: http://tracker.moodle.org/browse/MDL-7883
2749 * TODO:
2751 function force_strict_header($output) {
2752 global $CFG;
2753 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2754 $xsl = '/lib/xhtml.xsl';
2756 if (!headers_sent() && !empty($CFG->xmlstrictheaders)) { // With xml strict headers, the browser will barf
2757 $ctype = 'Content-Type: ';
2758 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2760 if (isset($_SERVER['HTTP_ACCEPT'])
2761 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2762 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2763 // Firefox et al.
2764 $ctype .= 'application/xhtml+xml';
2765 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2767 } else if (file_exists($CFG->dirroot.$xsl)
2768 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2769 // XSL hack for IE 5+ on Windows.
2770 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2771 $www_xsl = $CFG->wwwroot .$xsl;
2772 $ctype .= 'application/xml';
2773 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2774 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2776 } else {
2777 //ELSE: Mac/IE, old/non-XML browsers.
2778 $ctype .= 'text/html';
2779 $prolog = '';
2781 @header($ctype.'; charset=utf-8');
2782 $output = $prolog . $output;
2784 // Test parser error-handling.
2785 if (isset($_GET['error'])) {
2786 $output .= "__ TEST: XML well-formed error < __\n";
2790 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
2792 return $output;
2798 * This version of print_header is simpler because the course name does not have to be
2799 * provided explicitly in the strings. It can be used on the site page as in courses
2800 * Eventually all print_header could be replaced by print_header_simple
2802 * @param string $title Appears at the top of the window
2803 * @param string $heading Appears at the top of the page
2804 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2805 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2806 * @param string $meta Meta tags to be added to the header
2807 * @param boolean $cache Should this page be cacheable?
2808 * @param string $button HTML code for a button (usually for module editing)
2809 * @param string $menu HTML code for a popup menu
2810 * @param boolean $usexml use XML for this page
2811 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2812 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2814 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
2815 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
2817 global $COURSE, $CFG;
2819 // if we have no navigation specified, build it
2820 if( empty($navigation) ){
2821 $navigation = build_navigation('');
2824 // If old style nav prepend course short name otherwise leave $navigation object alone
2825 if (!is_newnav($navigation)) {
2826 if ($COURSE->id != SITEID) {
2827 $shortname = '<a href="'.$CFG->wwwroot.'/course/view.php?id='. $COURSE->id .'">'. $COURSE->shortname .'</a> ->';
2828 $navigation = $shortname.' '.$navigation;
2832 $output = print_header($COURSE->shortname .': '. $title, $COURSE->fullname .' '. $heading, $navigation, $focus, $meta,
2833 $cache, $button, $menu, $usexml, $bodytags, true);
2835 if ($return) {
2836 return $output;
2837 } else {
2838 echo $output;
2844 * Can provide a course object to make the footer contain a link to
2845 * to the course home page, otherwise the link will go to the site home
2846 * @uses $USER
2847 * @param mixed $course course object, used for course link button or
2848 * 'none' means no user link, only docs link
2849 * 'empty' means nothing printed in footer
2850 * 'home' special frontpage footer
2851 * @param object $usercourse course used in user link
2852 * @param boolean $return output as string
2853 * @return mixed string or void
2855 function print_footer($course=NULL, $usercourse=NULL, $return=false) {
2856 global $USER, $CFG, $THEME, $COURSE;
2858 if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
2859 admin_externalpage_print_footer();
2860 return;
2863 /// Course links or special footer
2864 if ($course) {
2865 if ($course === 'empty') {
2866 // special hack - sometimes we do not want even the docs link in footer
2867 $output = '';
2868 if (!empty($THEME->open_header_containers)) {
2869 for ($i=0; $i<$THEME->open_header_containers; $i++) {
2870 $output .= print_container_end_all(); // containers opened from header
2872 } else {
2873 //1.8 theme compatibility
2874 $output .= "\n</div>"; // content div
2876 $output .= "\n</div>\n</body>\n</html>"; // close page div started in header
2877 if ($return) {
2878 return $output;
2879 } else {
2880 echo $output;
2881 return;
2884 } else if ($course === 'none') { // Don't print any links etc
2885 $homelink = '';
2886 $loggedinas = '';
2887 $home = false;
2889 } else if ($course === 'home') { // special case for site home page - please do not remove
2890 $course = get_site();
2891 $homelink = '<div class="sitelink">'.
2892 '<a title="Moodle '. $CFG->release .'" href="http://moodle.org/">'.
2893 '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
2894 $home = true;
2896 } else {
2897 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
2898 '/course/view.php?id='.$course->id.'">'.format_string($course->shortname).'</a></div>';
2899 $home = false;
2902 } else {
2903 $course = get_site(); // Set course as site course by default
2904 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
2905 $home = false;
2908 /// Set up some other navigation links (passed from print_header by ugly hack)
2909 $menu = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
2910 $title = isset($THEME->title) ? $THEME->title : '';
2911 $button = isset($THEME->button) ? $THEME->button : '';
2912 $heading = isset($THEME->heading) ? $THEME->heading : '';
2913 $navigation = isset($THEME->navigation) ? $THEME->navigation : '';
2914 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2917 /// Set the user link if necessary
2918 if (!$usercourse and is_object($course)) {
2919 $usercourse = $course;
2922 if (!isset($loggedinas)) {
2923 $loggedinas = user_login_string($usercourse, $USER);
2926 if ($loggedinas == $menu) {
2927 $menu = '';
2930 /// there should be exactly the same number of open containers as after the header
2931 if ($THEME->open_header_containers != open_containers()) {
2932 debugging('Unexpected number of open containers: '.open_containers().', expecting '.$THEME->open_header_containers, DEBUG_DEVELOPER);
2935 /// Provide some performance info if required
2936 $performanceinfo = '';
2937 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2938 $perf = get_performance_info();
2939 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
2940 error_log("PERF: " . $perf['txt']);
2942 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
2943 $performanceinfo = $perf['html'];
2947 /// Include the actual footer file
2949 ob_start();
2950 include($CFG->footer);
2951 $output = ob_get_contents();
2952 ob_end_clean();
2954 if ($return) {
2955 return $output;
2956 } else {
2957 echo $output;
2962 * Returns the name of the current theme
2964 * @uses $CFG
2965 * @uses $USER
2966 * @uses $SESSION
2967 * @uses $COURSE
2968 * @uses $FULLME
2969 * @return string
2971 function current_theme() {
2972 global $CFG, $USER, $SESSION, $COURSE, $FULLME;
2974 if (empty($CFG->themeorder)) {
2975 $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
2976 } else {
2977 $themeorder = $CFG->themeorder;
2980 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id) {
2981 require_once($CFG->dirroot.'/mnet/peer.php');
2982 $mnet_peer = new mnet_peer();
2983 $mnet_peer->set_id($USER->mnethostid);
2986 $theme = '';
2987 foreach ($themeorder as $themetype) {
2989 if (!empty($theme)) continue;
2991 switch ($themetype) {
2992 case 'page': // Page theme is for special page-only themes set by code
2993 if (!empty($CFG->pagetheme)) {
2994 $theme = $CFG->pagetheme;
2996 break;
2997 case 'course':
2998 if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) {
2999 $theme = $COURSE->theme;
3001 break;
3002 case 'category':
3003 if (!empty($CFG->allowcategorythemes)) {
3004 /// Nasty hack to check if we're in a category page
3005 if (stripos($FULLME, 'course/category.php') !== false) {
3006 global $id;
3007 if (!empty($id)) {
3008 $theme = current_category_theme($id);
3010 /// Otherwise check if we're in a course that has a category theme set
3011 } else if (!empty($COURSE->category)) {
3012 $theme = current_category_theme($COURSE->category);
3015 break;
3016 case 'session':
3017 if (!empty($SESSION->theme)) {
3018 $theme = $SESSION->theme;
3020 break;
3021 case 'user':
3022 if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) {
3023 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
3024 $theme = $mnet_peer->theme;
3025 } else {
3026 $theme = $USER->theme;
3029 break;
3030 case 'site':
3031 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
3032 $theme = $mnet_peer->theme;
3033 } else {
3034 $theme = $CFG->theme;
3036 break;
3037 default:
3038 /// do nothing
3042 /// A final check in case 'site' was not included in $CFG->themeorder
3043 if (empty($theme)) {
3044 $theme = $CFG->theme;
3047 return $theme;
3051 * Retrieves the category theme if one exists, otherwise checks the parent categories.
3052 * Recursive function.
3054 * @uses $COURSE
3055 * @param integer $categoryid id of the category to check
3056 * @return string theme name
3058 function current_category_theme($categoryid=0) {
3059 global $COURSE;
3061 /// Use the COURSE global if the categoryid not set
3062 if (empty($categoryid)) {
3063 if (!empty($COURSE->category)) {
3064 $categoryid = $COURSE->category;
3065 } else {
3066 return false;
3070 /// Retrieve the current category
3071 if ($category = get_record('course_categories', 'id', $categoryid)) {
3073 /// Return the category theme if it exists
3074 if (!empty($category->theme)) {
3075 return $category->theme;
3077 /// Otherwise try the parent category if one exists
3078 } else if (!empty($category->parent)) {
3079 return current_category_theme($category->parent);
3082 /// Return false if we can't find the category record
3083 } else {
3084 return false;
3089 * This function is called by stylesheets to set up the header
3090 * approriately as well as the current path
3092 * @uses $CFG
3093 * @param int $lastmodified ?
3094 * @param int $lifetime ?
3095 * @param string $thename ?
3097 function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
3099 global $CFG, $THEME;
3101 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
3102 $lastmodified = time();
3104 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
3105 header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
3106 header('Cache-Control: max-age='. $lifetime);
3107 header('Pragma: ');
3108 header('Content-type: text/css'); // Correct MIME type
3110 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
3112 if (empty($themename)) {
3113 $themename = current_theme(); // So we have something. Normally not needed.
3114 } else {
3115 $themename = clean_param($themename, PARAM_SAFEDIR);
3118 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
3119 unset($THEME);
3120 include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
3123 /// If this is the standard theme calling us, then find out what sheets we need
3125 if ($themename == 'standard') {
3126 if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
3127 $THEME->sheets = $DEFAULT_SHEET_LIST;
3128 } else if (empty($THEME->standardsheets)) { // We can stop right now!
3129 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3130 exit;
3131 } else { // Use the provided subset only
3132 $THEME->sheets = $THEME->standardsheets;
3135 /// If we are a parent theme, then check for parent definitions
3137 } else if (!empty($THEME->parent) && $themename == $THEME->parent) {
3138 if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have
3139 $THEME->sheets = $DEFAULT_SHEET_LIST;
3140 } else if (empty($THEME->parentsheets)) { // We can stop right now!
3141 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3142 exit;
3143 } else { // Use the provided subset only
3144 $THEME->sheets = $THEME->parentsheets;
3148 /// Work out the last modified date for this theme
3150 foreach ($THEME->sheets as $sheet) {
3151 if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
3152 $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
3153 if ($sheetmodified > $lastmodified) {
3154 $lastmodified = $sheetmodified;
3160 /// Get a list of all the files we want to include
3161 $files = array();
3163 foreach ($THEME->sheets as $sheet) {
3164 $files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
3167 if ($themename == 'standard') { // Add any standard styles included in any modules
3168 if (!empty($THEME->modsheets)) { // Search for styles.php within activity modules
3169 if ($mods = get_list_of_plugins('mod')) {
3170 foreach ($mods as $mod) {
3171 if (file_exists($CFG->dirroot.'/mod/'.$mod.'/styles.php')) {
3172 $files[] = array($CFG->dirroot, '/mod/'.$mod.'/styles.php');
3178 if (!empty($THEME->blocksheets)) { // Search for styles.php within block modules
3179 if ($mods = get_list_of_plugins('blocks')) {
3180 foreach ($mods as $mod) {
3181 if (file_exists($CFG->dirroot.'/blocks/'.$mod.'/styles.php')) {
3182 $files[] = array($CFG->dirroot, '/blocks/'.$mod.'/styles.php');
3188 if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
3189 if ($mods = get_list_of_plugins('format','',$CFG->dirroot.'/course')) {
3190 foreach ($mods as $mod) {
3191 if (file_exists($CFG->dirroot.'/course/format/'.$mod.'/styles.php')) {
3192 $files[] = array($CFG->dirroot, '/course/format/'.$mod.'/styles.php');
3198 if (!isset($THEME->gradereportsheets) || $THEME->gradereportsheets) { // Search for styles.php in grade reports
3199 if ($reports = get_list_of_plugins('grade/report')) {
3200 foreach ($reports as $report) {
3201 if (file_exists($CFG->dirroot.'/grade/report/'.$report.'/styles.php')) {
3202 $files[] = array($CFG->dirroot, '/grade/report/'.$report.'/styles.php');
3208 if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
3209 if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
3210 $files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
3215 if ($files) {
3216 /// Produce a list of all the files first
3217 echo '/**************************************'."\n";
3218 echo ' * THEME NAME: '.$themename."\n *\n";
3219 echo ' * Files included in this sheet:'."\n *\n";
3220 foreach ($files as $file) {
3221 echo ' * '.$file[1]."\n";
3223 echo ' **************************************/'."\n\n";
3226 /// check if csscobstants is set
3227 if (!empty($THEME->cssconstants)) {
3228 require_once("$CFG->libdir/cssconstants.php");
3229 /// Actually collect all the files in order.
3230 $css = '';
3231 foreach ($files as $file) {
3232 $css .= '/***** '.$file[1].' start *****/'."\n\n";
3233 $css .= file_get_contents($file[0].'/'.$file[1]);
3234 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
3236 /// replace css_constants with their values
3237 echo replace_cssconstants($css);
3238 } else {
3239 /// Actually output all the files in order.
3240 if (empty($CFG->CSSEdit) && empty($THEME->CSSEdit)) {
3241 foreach ($files as $file) {
3242 echo '/***** '.$file[1].' start *****/'."\n\n";
3243 @include_once($file[0].'/'.$file[1]);
3244 echo '/***** '.$file[1].' end *****/'."\n\n";
3246 } else {
3247 foreach ($files as $file) {
3248 echo '/* @group '.$file[1].' */'."\n\n";
3249 if (strstr($file[1], '.css') !== FALSE) {
3250 echo '@import url("'.$CFG->themewww.'/'.$file[1].'");'."\n\n";
3251 } else {
3252 @include_once($file[0].'/'.$file[1]);
3254 echo '/* @end */'."\n\n";
3260 return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
3264 function theme_setup($theme = '', $params=NULL) {
3265 /// Sets up global variables related to themes
3267 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
3269 /// Do not mess with THEME if header already printed - this would break all the extra stuff in global $THEME from print_header()!!
3270 if (defined('HEADER_PRINTED')) {
3271 return;
3274 if (empty($theme)) {
3275 $theme = current_theme();
3278 /// If the theme doesn't exist for some reason then revert to standardwhite
3279 if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
3280 $CFG->theme = $theme = 'standardwhite';
3283 /// Load up the theme config
3284 $THEME = NULL; // Just to be sure
3285 include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
3287 /// Put together the parameters
3288 if (!$params) {
3289 $params = array();
3292 if ($theme != $CFG->theme) {
3293 $params[] = 'forceconfig='.$theme;
3296 /// Force language too if required
3297 if (!empty($THEME->langsheets)) {
3298 $params[] = 'lang='.current_language();
3302 /// Convert params to string
3303 if ($params) {
3304 $paramstring = '?'.implode('&', $params);
3305 } else {
3306 $paramstring = '';
3309 /// Set up image paths
3310 if(isset($CFG->smartpix) && $CFG->smartpix==1) {
3311 if($CFG->slasharguments) { // Use this method if possible for better caching
3312 $extra='';
3313 } else {
3314 $extra='?file=';
3317 $CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
3318 $CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
3319 } else if (empty($THEME->custompix)) { // Could be set in the above file
3320 $CFG->pixpath = $CFG->wwwroot .'/pix';
3321 $CFG->modpixpath = $CFG->wwwroot .'/mod';
3322 } else {
3323 $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
3324 $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
3327 /// Header and footer paths
3328 $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
3329 $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
3331 /// Define stylesheet loading order
3332 $CFG->stylesheets = array();
3333 if ($theme != 'standard') { /// The standard sheet is always loaded first
3334 $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
3336 if (!empty($THEME->parent)) { /// Parent stylesheets are loaded next
3337 $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
3339 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
3341 /// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
3342 if (!empty($HTTPSPAGEREQUIRED)) {
3343 $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
3344 $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
3345 $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
3346 foreach ($CFG->stylesheets as $key => $stylesheet) {
3347 $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
3351 // RTL support - only for RTL languages, add RTL CSS
3352 if (get_string('thisdirection') == 'rtl') {
3353 $CFG->stylesheets[] = $CFG->themewww.'/standard/rtl.css'.$paramstring;
3354 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/rtl.css'.$paramstring;
3360 * Returns text to be displayed to the user which reflects their login status
3362 * @uses $CFG
3363 * @uses $USER
3364 * @param course $course {@link $COURSE} object containing course information
3365 * @param user $user {@link $USER} object containing user information
3366 * @return string
3368 function user_login_string($course=NULL, $user=NULL) {
3369 global $USER, $CFG, $SITE;
3371 if (empty($user) and !empty($USER->id)) {
3372 $user = $USER;
3375 if (empty($course)) {
3376 $course = $SITE;
3379 if (!empty($user->realuser)) {
3380 if ($realuser = get_record('user', 'id', $user->realuser)) {
3381 $fullname = fullname($realuser, true);
3382 $realuserinfo = " [<a $CFG->frametarget
3383 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=1&amp;sesskey=".sesskey()."\">$fullname</a>] ";
3385 } else {
3386 $realuserinfo = '';
3389 if (empty($CFG->loginhttps)) {
3390 $wwwroot = $CFG->wwwroot;
3391 } else {
3392 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
3395 if (empty($course->id)) {
3396 // $course->id is not defined during installation
3397 return '';
3398 } else if (!empty($user->id)) {
3399 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3401 $fullname = fullname($user, true);
3402 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a>";
3403 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid)) {
3404 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
3406 if (isset($user->username) && $user->username == 'guest') {
3407 $loggedinas = $realuserinfo.get_string('loggedinasguest').
3408 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3409 } else if (!empty($user->access['rsw'][$context->path])) {
3410 $rolename = '';
3411 if ($role = get_record('role', 'id', $user->access['rsw'][$context->path])) {
3412 $rolename = ': '.format_string($role->name);
3414 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
3415 " (<a $CFG->frametarget
3416 href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
3417 } else {
3418 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
3419 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
3421 } else {
3422 $loggedinas = get_string('loggedinnot', 'moodle').
3423 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3425 return '<div class="logininfo">'.$loggedinas.'</div>';
3429 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
3430 * If not it applies sensible defaults.
3432 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
3433 * search forum block, etc. Important: these are 'silent' in a screen-reader
3434 * (unlike &gt; &raquo;), and must be accompanied by text.
3435 * @uses $THEME
3437 function check_theme_arrows() {
3438 global $THEME;
3440 if (!isset($THEME->rarrow) and !isset($THEME->larrow)) {
3441 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
3442 // Also OK in Win 9x/2K/IE 5.x
3443 $THEME->rarrow = '&#x25BA;';
3444 $THEME->larrow = '&#x25C4;';
3445 $uagent = $_SERVER['HTTP_USER_AGENT'];
3446 if (false !== strpos($uagent, 'Opera')
3447 || false !== strpos($uagent, 'Mac')) {
3448 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
3449 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
3450 $THEME->rarrow = '&#x25B6;';
3451 $THEME->larrow = '&#x25C0;';
3453 elseif (false !== strpos($uagent, 'Konqueror')) {
3454 $THEME->rarrow = '&rarr;';
3455 $THEME->larrow = '&larr;';
3457 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
3458 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
3459 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
3460 // To be safe, non-Unicode browsers!
3461 $THEME->rarrow = '&gt;';
3462 $THEME->larrow = '&lt;';
3465 /// RTL support - in RTL languages, swap r and l arrows
3466 if (right_to_left()) {
3467 $t = $THEME->rarrow;
3468 $THEME->rarrow = $THEME->larrow;
3469 $THEME->larrow = $t;
3476 * Return the right arrow with text ('next'), and optionally embedded in a link.
3477 * See function above, check_theme_arrows.
3478 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3479 * @param string $url An optional link to use in a surrounding HTML anchor.
3480 * @param bool $accesshide True if text should be hidden (for screen readers only).
3481 * @param string $addclass Additional class names for the link, or the arrow character.
3482 * @return string HTML string.
3484 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
3485 global $THEME;
3486 check_theme_arrows();
3487 $arrowclass = 'arrow ';
3488 if (! $url) {
3489 $arrowclass .= $addclass;
3491 $arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow.'</span>';
3492 $htmltext = '';
3493 if ($text) {
3494 $htmltext = $text.'&nbsp;';
3495 if ($accesshide) {
3496 $htmltext = get_accesshide($htmltext);
3499 if ($url) {
3500 $class = '';
3501 if ($addclass) {
3502 $class =" class=\"$addclass\"";
3504 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
3506 return $htmltext.$arrow;
3510 * Return the left arrow with text ('previous'), and optionally embedded in a link.
3511 * See function above, check_theme_arrows.
3512 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3513 * @param string $url An optional link to use in a surrounding HTML anchor.
3514 * @param bool $accesshide True if text should be hidden (for screen readers only).
3515 * @param string $addclass Additional class names for the link, or the arrow character.
3516 * @return string HTML string.
3518 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
3519 global $THEME;
3520 check_theme_arrows();
3521 $arrowclass = 'arrow ';
3522 if (! $url) {
3523 $arrowclass .= $addclass;
3525 $arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow.'</span>';
3526 $htmltext = '';
3527 if ($text) {
3528 $htmltext = '&nbsp;'.$text;
3529 if ($accesshide) {
3530 $htmltext = get_accesshide($htmltext);
3533 if ($url) {
3534 $class = '';
3535 if ($addclass) {
3536 $class =" class=\"$addclass\"";
3538 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
3540 return $arrow.$htmltext;
3544 * Return a HTML element with the class "accesshide", for accessibility.
3545 * Please use cautiously - where possible, text should be visible!
3546 * @param string $text Plain text.
3547 * @param string $elem Lowercase element name, default "span".
3548 * @param string $class Additional classes for the element.
3549 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
3550 * @return string HTML string.
3552 function get_accesshide($text, $elem='span', $class='', $attrs='') {
3553 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
3557 * Return the breadcrumb trail navigation separator.
3558 * @return string HTML string.
3560 function get_separator() {
3561 //Accessibility: the 'hidden' slash is preferred for screen readers.
3562 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
3566 * Prints breadcrumb trail of links, called in theme/-/header.html
3568 * @uses $CFG
3569 * @param mixed $navigation The breadcrumb navigation string to be printed
3570 * @param string $separator The breadcrumb trail separator. The default 0 leads to the use
3571 * of $THEME->rarrow, themes could use '&rarr;', '/', or '' for a style-sheet solution.
3572 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
3574 function print_navigation ($navigation, $separator=0, $return=false) {
3575 global $CFG, $THEME;
3576 $output = '';
3578 if (0 === $separator) {
3579 $separator = get_separator();
3581 else {
3582 $separator = '<span class="sep">'. $separator .'</span>';
3585 if ($navigation) {
3587 if (is_newnav($navigation)) {
3588 if ($return) {
3589 return($navigation['navlinks']);
3590 } else {
3591 echo $navigation['navlinks'];
3592 return;
3594 } else {
3595 debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER);
3598 if (!is_array($navigation)) {
3599 $ar = explode('->', $navigation);
3600 $navigation = array();
3602 foreach ($ar as $a) {
3603 if (strpos($a, '</a>') === false) {
3604 $navigation[] = array('title' => $a, 'url' => '');
3605 } else {
3606 if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
3607 $navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
3613 if (! $site = get_site()) {
3614 $site = new object();
3615 $site->shortname = get_string('home');
3618 //Accessibility: breadcrumb links now in a list, &raquo; replaced with a 'silent' character.
3619 $output .= get_accesshide(get_string('youarehere','access'), 'h2')."<ul>\n";
3621 $output .= '<li class="first">'."\n".'<a '.$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3622 .$CFG->wwwroot.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))
3623 && !empty($USER->id) && !empty($CFG->mymoodleredirect) && !isguest())
3624 ? '/my' : '') .'/">'. format_string($site->shortname) ."</a>\n</li>\n";
3627 foreach ($navigation as $navitem) {
3628 $title = trim(strip_tags(format_string($navitem['title'], false)));
3629 $url = $navitem['url'];
3631 if (empty($url)) {
3632 $output .= '<li class="first">'."$separator $title</li>\n";
3633 } else {
3634 $output .= '<li class="first">'."$separator\n<a ".$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3635 .$url.'">'."$title</a>\n</li>\n";
3639 $output .= "</ul>\n";
3642 if ($return) {
3643 return $output;
3644 } else {
3645 echo $output;
3650 * This function will build the navigation string to be used by print_header
3651 * and others.
3653 * It automatically generates the site and course level (if appropriate) links.
3655 * If you pass in a $cm object, the method will also generate the activity (e.g. 'Forums')
3656 * and activityinstances (e.g. 'General Developer Forum') navigation levels.
3658 * If you want to add any further navigation links after the ones this function generates,
3659 * the pass an array of extra link arrays like this:
3660 * array(
3661 * array('name' => $linktext1, 'link' => $url1, 'type' => $linktype1),
3662 * array('name' => $linktext2, 'link' => $url2, 'type' => $linktype2)
3664 * The normal case is to just add one further link, for example 'Editing forum' after
3665 * 'General Developer Forum', with no link.
3666 * To do that, you need to pass
3667 * array(array('name' => $linktext, 'link' => '', 'type' => 'title'))
3668 * However, becuase this is a very common case, you can use a shortcut syntax, and just
3669 * pass the string 'Editing forum', instead of an array as $extranavlinks.
3671 * At the moment, the link types only have limited significance. Type 'activity' is
3672 * recognised in order to implement the $CFG->hideactivitytypenavlink feature. Types
3673 * that are known to appear are 'home', 'course', 'activity', 'activityinstance' and 'title'.
3674 * This really needs to be documented better. In the mean time, try to be consistent, it will
3675 * enable people to customise the navigation more in future.
3677 * When passing a $cm object, the fields used are $cm->modname, $cm->name and $cm->course.
3678 * If you get the $cm object using the function get_coursemodule_from_instance or
3679 * get_coursemodule_from_id (as recommended) then this will be done for you automatically.
3680 * If you don't have $cm->modname or $cm->name, this fuction will attempt to find them using
3681 * the $cm->module and $cm->instance fields, but this takes extra database queries, so a
3682 * warning is printed in developer debug mode.
3684 * @uses $CFG
3685 * @uses $THEME
3687 * @param mixed $extranavlinks - Normally an array of arrays, keys: name, link, type. If you
3688 * only want one extra item with no link, you can pass a string instead. If you don't want
3689 * any extra links, pass an empty string.
3690 * @param mixed $cm - optionally the $cm object, if you want this function to generate the
3691 * activity and activityinstance levels of navigation too.
3693 * @return $navigation as an object so it can be differentiated from old style
3694 * navigation strings.
3696 function build_navigation($extranavlinks, $cm = null) {
3697 global $CFG, $COURSE;
3699 if (is_string($extranavlinks)) {
3700 if ($extranavlinks == '') {
3701 $extranavlinks = array();
3702 } else {
3703 $extranavlinks = array(array('name' => $extranavlinks, 'link' => '', 'type' => 'title'));
3707 $navlinks = array();
3709 //Site name
3710 if ($site = get_site()) {
3711 $navlinks[] = array(
3712 'name' => format_string($site->shortname),
3713 'link' => "$CFG->wwwroot/",
3714 'type' => 'home');
3717 // Course name, if appropriate.
3718 if (isset($COURSE) && $COURSE->id != SITEID) {
3719 $navlinks[] = array(
3720 'name' => format_string($COURSE->shortname),
3721 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",
3722 'type' => 'course');
3725 // Activity type and instance, if appropriate.
3726 if (is_object($cm)) {
3727 if (!isset($cm->modname)) {
3728 debugging('The field $cm->modname should be set if you call build_navigation with '.
3729 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3730 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
3731 if (!$cm->modname = get_field('modules', 'name', 'id', $cm->module)) {
3732 error('Cannot get the module type in build navigation.');
3735 if (!isset($cm->name)) {
3736 debugging('The field $cm->name should be set if you call build_navigation with '.
3737 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3738 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
3739 if (!$cm->name = get_field($cm->modname, 'name', 'id', $cm->instance)) {
3740 error('Cannot get the module name in build navigation.');
3743 $navlinks[] = array(
3744 'name' => get_string('modulenameplural', $cm->modname),
3745 'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/index.php?id=' . $cm->course,
3746 'type' => 'activity');
3747 $navlinks[] = array(
3748 'name' => format_string($cm->name),
3749 'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/view.php?id=' . $cm->id,
3750 'type' => 'activityinstance');
3753 //Merge in extra navigation links
3754 $navlinks = array_merge($navlinks, $extranavlinks);
3756 // Work out whether we should be showing the activity (e.g. Forums) link.
3757 // Note: build_navigation() is called from many places --
3758 // install & upgrade for example -- where we cannot count on the
3759 // roles infrastructure to be defined. Hence the $CFG->rolesactive check.
3760 if (!isset($CFG->hideactivitytypenavlink)) {
3761 $CFG->hideactivitytypenavlink = 0;
3763 if ($CFG->hideactivitytypenavlink == 2) {
3764 $hideactivitylink = true;
3765 } else if ($CFG->hideactivitytypenavlink == 1 && $CFG->rolesactive &&
3766 !empty($COURSE->id) && $COURSE->id != SITEID) {
3767 if (!isset($COURSE->context)) {
3768 $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
3770 $hideactivitylink = !has_capability('moodle/course:manageactivities', $COURSE->context);
3771 } else {
3772 $hideactivitylink = false;
3775 //Construct an unordered list from $navlinks
3776 //Accessibility: heading hidden from visual browsers by default.
3777 $navigation = get_accesshide(get_string('youarehere','access'), 'h2')." <ul>\n";
3778 $lastindex = count($navlinks) - 1;
3779 $i = -1; // Used to count the times, so we know when we get to the last item.
3780 $first = true;
3781 foreach ($navlinks as $navlink) {
3782 $i++;
3783 $last = ($i == $lastindex);
3784 if (!is_array($navlink)) {
3785 continue;
3787 if ($navlink['type'] == 'activity' && !$last && $hideactivitylink) {
3788 continue;
3790 $navigation .= '<li class="first">';
3791 if (!$first) {
3792 $navigation .= get_separator();
3794 if ((!empty($navlink['link'])) && !$last) {
3795 $navigation .= "<a onclick=\"this.target='$CFG->framename'\" href=\"{$navlink['link']}\">";
3797 $navigation .= "{$navlink['name']}";
3798 if ((!empty($navlink['link'])) && !$last) {
3799 $navigation .= "</a>";
3802 $navigation .= "</li>";
3803 $first = false;
3805 $navigation .= "</ul>";
3807 return(array('newnav' => true, 'navlinks' => $navigation));
3812 * Prints a string in a specified size (retained for backward compatibility)
3814 * @param string $text The text to be displayed
3815 * @param int $size The size to set the font for text display.
3817 function print_headline($text, $size=2, $return=false) {
3818 $output = print_heading($text, '', $size, true);
3819 if ($return) {
3820 return $output;
3821 } else {
3822 echo $output;
3827 * Prints text in a format for use in headings.
3829 * @param string $text The text to be displayed
3830 * @param string $align The alignment of the printed paragraph of text
3831 * @param int $size The size to set the font for text display.
3833 function print_heading($text, $align='', $size=2, $class='main', $return=false) {
3834 if ($align) {
3835 $align = ' style="text-align:'.$align.';"';
3837 if ($class) {
3838 $class = ' class="'.$class.'"';
3840 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
3842 if ($return) {
3843 return $output;
3844 } else {
3845 echo $output;
3850 * Centered heading with attached help button (same title text)
3851 * and optional icon attached
3853 * @param string $text The text to be displayed
3854 * @param string $helppage The help page to link to
3855 * @param string $module The module whose help should be linked to
3856 * @param string $icon Image to display if needed
3858 function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
3859 $output = '';
3860 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
3861 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
3862 $output .= '</h2>';
3864 if ($return) {
3865 return $output;
3866 } else {
3867 echo $output;
3872 function print_heading_block($heading, $class='', $return=false) {
3873 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
3874 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
3876 if ($return) {
3877 return $output;
3878 } else {
3879 echo $output;
3885 * Print a link to continue on to another page.
3887 * @uses $CFG
3888 * @param string $link The url to create a link to.
3890 function print_continue($link, $return=false) {
3892 global $CFG;
3894 // in case we are logging upgrade in admin/index.php stop it
3895 if (function_exists('upgrade_log_finish')) {
3896 upgrade_log_finish();
3899 $output = '';
3901 if ($link == '') {
3902 if (!empty($_SERVER['HTTP_REFERER'])) {
3903 $link = $_SERVER['HTTP_REFERER'];
3904 $link = str_replace('&', '&amp;', $link); // make it valid XHTML
3905 } else {
3906 $link = $CFG->wwwroot .'/';
3910 $options = array();
3911 $linkparts = parse_url(str_replace('&amp;', '&', $link));
3912 if (isset($linkparts['query'])) {
3913 parse_str($linkparts['query'], $options);
3916 $output .= '<div class="continuebutton">';
3918 $output .= print_single_button($link, $options, get_string('continue'), 'get', $CFG->framename, true);
3919 $output .= '</div>'."\n";
3921 if ($return) {
3922 return $output;
3923 } else {
3924 echo $output;
3930 * Print a message in a standard themed box.
3931 * Replaces print_simple_box (see deprecatedlib.php)
3933 * @param string $message, the content of the box
3934 * @param string $classes, space-separated class names.
3935 * @param string $idbase
3936 * @param boolean $return, return as string or just print it
3937 * @return mixed string or void
3939 function print_box($message, $classes='generalbox', $ids='', $return=false) {
3941 $output = print_box_start($classes, $ids, true);
3942 $output .= stripslashes_safe($message);
3943 $output .= print_box_end(true);
3945 if ($return) {
3946 return $output;
3947 } else {
3948 echo $output;
3953 * Starts a box using divs
3954 * Replaces print_simple_box_start (see deprecatedlib.php)
3956 * @param string $classes, space-separated class names.
3957 * @param string $idbase
3958 * @param boolean $return, return as string or just print it
3959 * @return mixed string or void
3961 function print_box_start($classes='generalbox', $ids='', $return=false) {
3962 global $THEME;
3964 if (strpos($classes, 'clearfix') !== false) {
3965 $clearfix = true;
3966 $classes = trim(str_replace('clearfix', '', $classes));
3967 } else {
3968 $clearfix = false;
3971 if (!empty($THEME->customcorners)) {
3972 $classes .= ' ccbox box';
3973 } else {
3974 $classes .= ' box';
3977 return print_container_start($clearfix, $classes, $ids, $return);
3981 * Simple function to end a box (see above)
3982 * Replaces print_simple_box_end (see deprecatedlib.php)
3984 * @param boolean $return, return as string or just print it
3986 function print_box_end($return=false) {
3987 return print_container_end($return);
3991 * Print a message in a standard themed container.
3993 * @param string $message, the content of the container
3994 * @param boolean $clearfix clear both sides
3995 * @param string $classes, space-separated class names.
3996 * @param string $idbase
3997 * @param boolean $return, return as string or just print it
3998 * @return string or void
4000 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
4002 $output = print_container_start($clearfix, $classes, $idbase, true);
4003 $output .= stripslashes_safe($message);
4004 $output .= print_container_end(true);
4006 if ($return) {
4007 return $output;
4008 } else {
4009 echo $output;
4014 * Starts a container using divs
4016 * @param boolean $clearfix clear both sides
4017 * @param string $classes, space-separated class names.
4018 * @param string $idbase
4019 * @param boolean $return, return as string or just print it
4020 * @return mixed string or void
4022 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
4023 global $THEME;
4025 if (!isset($THEME->open_containers)) {
4026 $THEME->open_containers = array();
4028 $THEME->open_containers[] = $idbase;
4031 if (!empty($THEME->customcorners)) {
4032 $output = _print_custom_corners_start($clearfix, $classes, $idbase);
4033 } else {
4034 if ($idbase) {
4035 $id = ' id="'.$idbase.'"';
4036 } else {
4037 $id = '';
4039 if ($clearfix) {
4040 $clearfix = ' clearfix';
4041 } else {
4042 $clearfix = '';
4044 if ($classes or $clearfix) {
4045 $class = ' class="'.$classes.$clearfix.'"';
4046 } else {
4047 $class = '';
4049 $output = '<div'.$id.$class.'>';
4052 if ($return) {
4053 return $output;
4054 } else {
4055 echo $output;
4060 * Simple function to end a container (see above)
4061 * @param boolean $return, return as string or just print it
4062 * @return mixed string or void
4064 function print_container_end($return=false) {
4065 global $THEME;
4067 if (empty($THEME->open_containers)) {
4068 debugging('Incorrect request to end container - no more open containers.', DEBUG_DEVELOPER);
4069 $idbase = '';
4070 } else {
4071 $idbase = array_pop($THEME->open_containers);
4074 if (!empty($THEME->customcorners)) {
4075 $output = _print_custom_corners_end($idbase);
4076 } else {
4077 $output = '</div>';
4080 if ($return) {
4081 return $output;
4082 } else {
4083 echo $output;
4088 * Returns number of currently open containers
4089 * @return int number of open containers
4091 function open_containers() {
4092 global $THEME;
4094 if (!isset($THEME->open_containers)) {
4095 $THEME->open_containers = array();
4098 return count($THEME->open_containers);
4102 * Force closing of open containers
4103 * @param boolean $return, return as string or just print it
4104 * @param int $keep number of containers to be kept open - usually theme or page containers
4105 * @return mixed string or void
4107 function print_container_end_all($return=false, $keep=0) {
4108 $output = '';
4109 while (open_containers() > $keep) {
4110 $output .= print_container_end($return);
4113 if ($return) {
4114 return $output;
4115 } else {
4116 echo $output;
4121 * Internal function - do not use directly!
4122 * Starting part of the surrounding divs for custom corners
4124 * @param boolean $clearfix, add CLASS "clearfix" to the inner div against collapsing
4125 * @param string $classes
4126 * @param mixed $idbase, optionally, define one idbase to be added to all the elements in the corners
4127 * @return string
4129 function _print_custom_corners_start($clearfix=false, $classes='', $idbase='') {
4130 /// Analise if we want ids for the custom corner elements
4131 $id = '';
4132 $idbt = '';
4133 $idi1 = '';
4134 $idi2 = '';
4135 $idi3 = '';
4137 if ($idbase) {
4138 $id = 'id="'.$idbase.'" ';
4139 $idbt = 'id="'.$idbase.'-bt" ';
4140 $idi1 = 'id="'.$idbase.'-i1" ';
4141 $idi2 = 'id="'.$idbase.'-i2" ';
4142 $idi3 = 'id="'.$idbase.'-i3" ';
4145 /// Calculate current level
4146 $level = open_containers();
4148 /// Output begins
4149 $output = '<div '.$id.'class="wrap wraplevel'.$level.' '.$classes.'">'."\n";
4150 $output .= '<div '.$idbt.'class="bt"><div>&nbsp;</div></div>';
4151 $output .= "\n";
4152 $output .= '<div '.$idi1.'class="i1"><div '.$idi2.'class="i2">';
4153 $output .= (!empty($clearfix)) ? '<div '.$idi3.'class="i3 clearfix">' : '<div '.$idi3.'class="i3">';
4155 return $output;
4160 * Internal function - do not use directly!
4161 * Ending part of the surrounding divs for custom corners
4162 * @param string $idbase
4163 * @return string
4165 function _print_custom_corners_end($idbase) {
4166 /// Analise if we want ids for the custom corner elements
4167 $idbb = '';
4169 if ($idbase) {
4170 $idbb = 'id="' . $idbase . '-bb" ';
4173 /// Output begins
4174 $output = '</div></div></div>';
4175 $output .= "\n";
4176 $output .= '<div '.$idbb.'class="bb"><div>&nbsp;</div></div>'."\n";
4177 $output .= '</div>';
4179 return $output;
4184 * Print a self contained form with a single submit button.
4186 * @param string $link used as the action attribute on the form, so the URL that will be hit if the button is clicked.
4187 * @param array $options these become hidden form fields, so these options get passed to the script at $link.
4188 * @param string $label the caption that appears on the button.
4189 * @param string $method HTTP method used on the request of the button is clicked. 'get' or 'post'.
4190 * @param string $target no longer used.
4191 * @param boolean $return if false, output the form directly, otherwise return the HTML as a string.
4192 * @param string $tooltip a tooltip to add to the button as a title attribute.
4193 * @param boolean $disabled if true, the button will be disabled.
4194 * @param string $jsconfirmmessage if not empty then display a confirm dialogue with this string as the question.
4195 * @return string / nothing depending on the $return paramter.
4197 function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='', $disabled = false, $jsconfirmmessage='') {
4198 $output = '';
4199 $link = str_replace('"', '&quot;', $link); //basic XSS protection
4200 $output .= '<div class="singlebutton">';
4201 // taking target out, will need to add later target="'.$target.'"
4202 $output .= '<form action="'. $link .'" method="'. $method .'">';
4203 $output .= '<div>';
4204 if ($options) {
4205 foreach ($options as $name => $value) {
4206 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
4209 if ($tooltip) {
4210 $tooltip = 'title="' . s($tooltip) . '"';
4211 } else {
4212 $tooltip = '';
4214 if ($disabled) {
4215 $disabled = 'disabled="disabled"';
4216 } else {
4217 $disabled = '';
4219 if ($jsconfirmmessage){
4220 $jsconfirmmessage = addslashes_js($jsconfirmmessage);
4221 $jsconfirmmessage = 'onclick="return confirm(\''. $jsconfirmmessage .'\');" ';
4223 $output .= '<input type="submit" value="'. s($label) ."\" $tooltip $disabled $jsconfirmmessage/></div></form></div>";
4225 if ($return) {
4226 return $output;
4227 } else {
4228 echo $output;
4234 * Print a spacer image with the option of including a line break.
4236 * @param int $height ?
4237 * @param int $width ?
4238 * @param boolean $br ?
4239 * @todo Finish documenting this function
4241 function print_spacer($height=1, $width=1, $br=true, $return=false) {
4242 global $CFG;
4243 $output = '';
4245 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot .'/pix/spacer.gif" alt="" />';
4246 if ($br) {
4247 $output .= '<br />'."\n";
4250 if ($return) {
4251 return $output;
4252 } else {
4253 echo $output;
4258 * Given the path to a picture file in a course, or a URL,
4259 * this function includes the picture in the page.
4261 * @param string $path ?
4262 * @param int $courseid ?
4263 * @param int $height ?
4264 * @param int $width ?
4265 * @param string $link ?
4266 * @todo Finish documenting this function
4268 function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
4269 global $CFG;
4270 $output = '';
4272 if ($height) {
4273 $height = 'height="'. $height .'"';
4275 if ($width) {
4276 $width = 'width="'. $width .'"';
4278 if ($link) {
4279 $output .= '<a href="'. $link .'">';
4281 if (substr(strtolower($path), 0, 7) == 'http://') {
4282 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
4284 } else if ($courseid) {
4285 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
4286 if ($CFG->slasharguments) { // Use this method if possible for better caching
4287 $output .= $CFG->wwwroot .'/file.php/'. $courseid .'/'. $path;
4288 } else {
4289 $output .= $CFG->wwwroot .'/file.php?file=/'. $courseid .'/'. $path;
4291 $output .= '" />';
4292 } else {
4293 $output .= 'Error: must pass URL or course';
4295 if ($link) {
4296 $output .= '</a>';
4299 if ($return) {
4300 return $output;
4301 } else {
4302 echo $output;
4307 * Print the specified user's avatar.
4309 * If you pass a $user object that has id, picture, imagealt, firstname, lastname
4310 * you save a DB query.
4312 * @param int $user takes a userid, or a userobj
4313 * @param int $courseid ?
4314 * @param boolean $picture Print the user picture?
4315 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
4316 * @param boolean $return If false print picture to current page, otherwise return the output as string
4317 * @param boolean $link Enclose printed image in a link to view specified course?
4318 * @param string $target link target attribute
4319 * @param boolean $alttext use username or userspecified text in image alt attribute
4320 * return string
4321 * @todo Finish documenting this function
4323 function print_user_picture($user, $courseid, $picture=NULL, $size=0, $return=false, $link=true, $target='', $alttext=true) {
4324 global $CFG, $HTTPSPAGEREQUIRED;
4326 $needrec = false;
4327 // only touch the DB if we are missing data...
4328 if (is_object($user)) {
4329 // Note - both picture and imagealt _can_ be empty
4330 // what we are trying to see here is if they have been fetched
4331 // from the DB. We should use isset() _except_ that some installs
4332 // have those fields as nullable, and isset() will return false
4333 // on null. The only safe thing is to ask array_key_exists()
4334 // which works on objects. property_exists() isn't quite
4335 // what we want here...
4336 if (! (array_key_exists('picture', $user)
4337 && ($alttext && array_key_exists('imagealt', $user)
4338 || (isset($user->firstname) && isset($user->lastname)))) ) {
4339 $needrec = true;
4340 $user = $user->id;
4342 } else {
4343 if ($alttext) {
4344 // we need firstname, lastname, imagealt, can't escape...
4345 $needrec = true;
4346 } else {
4347 $userobj = new StdClass; // fake it to save DB traffic
4348 $userobj->id = $user;
4349 $userobj->picture = $picture;
4350 $user = clone($userobj);
4351 unset($userobj);
4354 if ($needrec) {
4355 $user = get_record('user','id',$user, '', '', '', '', 'id,firstname,lastname,imagealt');
4358 if ($link) {
4359 $url = '/user/view.php?id='. $user->id .'&amp;course='. $courseid ;
4360 if ($target) {
4361 $target='onclick="return openpopup(\''.$url.'\');"';
4363 $output = '<a '.$target.' href="'. $CFG->wwwroot . $url .'">';
4364 } else {
4365 $output = '';
4367 if (empty($size)) {
4368 $file = 'f2';
4369 $size = 35;
4370 } else if ($size === true or $size == 1) {
4371 $file = 'f1';
4372 $size = 100;
4373 } else if ($size >= 50) {
4374 $file = 'f1';
4375 } else {
4376 $file = 'f2';
4378 $class = "userpicture";
4379 if (!empty($HTTPSPAGEREQUIRED)) {
4380 $wwwroot = $CFG->httpswwwroot;
4381 } else {
4382 $wwwroot = $CFG->wwwroot;
4385 if (is_null($picture)) {
4386 $picture = $user->picture;
4389 if ($picture) { // Print custom user picture
4390 if ($CFG->slasharguments) { // Use this method if possible for better caching
4391 $src = $wwwroot .'/user/pix.php/'. $user->id .'/'. $file .'.jpg';
4392 } else {
4393 $src = $wwwroot .'/user/pix.php?file=/'. $user->id .'/'. $file .'.jpg';
4395 } else { // Print default user pictures (use theme version if available)
4396 $class .= " defaultuserpic";
4397 $src = "$CFG->pixpath/u/$file.png";
4399 $imagealt = '';
4400 if ($alttext) {
4401 if (!empty($user->imagealt)) {
4402 $imagealt = $user->imagealt;
4403 } else {
4404 $imagealt = get_string('pictureof','',fullname($user));
4408 $output .= '<img class="'.$class.'" src="'.$src.'" alt="'.s($imagealt).'" />';
4409 if ($link) {
4410 $output .= '</a>';
4413 if ($return) {
4414 return $output;
4415 } else {
4416 echo $output;
4421 * Prints a summary of a user in a nice little box.
4423 * @uses $CFG
4424 * @uses $USER
4425 * @param user $user A {@link $USER} object representing a user
4426 * @param course $course A {@link $COURSE} object representing a course
4428 function print_user($user, $course, $messageselect=false, $return=false) {
4430 global $CFG, $USER;
4432 $output = '';
4434 static $string;
4435 static $datestring;
4436 static $countries;
4438 $context = get_context_instance(CONTEXT_COURSE, $course->id);
4439 if (isset($user->context->id)) {
4440 $usercontext = get_context_instance_by_id($user->context->id);
4443 if (empty($string)) { // Cache all the strings for the rest of the page
4445 $string->email = get_string('email');
4446 $string->city = get_string('city');
4447 $string->lastaccess = get_string('lastaccess');
4448 $string->activity = get_string('activity');
4449 $string->unenrol = get_string('unenrol');
4450 $string->loginas = get_string('loginas');
4451 $string->fullprofile = get_string('fullprofile');
4452 $string->role = get_string('role');
4453 $string->name = get_string('name');
4454 $string->never = get_string('never');
4456 $datestring->day = get_string('day');
4457 $datestring->days = get_string('days');
4458 $datestring->hour = get_string('hour');
4459 $datestring->hours = get_string('hours');
4460 $datestring->min = get_string('min');
4461 $datestring->mins = get_string('mins');
4462 $datestring->sec = get_string('sec');
4463 $datestring->secs = get_string('secs');
4464 $datestring->year = get_string('year');
4465 $datestring->years = get_string('years');
4467 $countries = get_list_of_countries();
4470 /// Get the hidden field list
4471 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
4472 $hiddenfields = array();
4473 } else {
4474 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
4477 $output .= '<table class="userinfobox">';
4478 $output .= '<tr>';
4479 $output .= '<td class="left side">';
4480 $output .= print_user_picture($user, $course->id, $user->picture, true, true);
4481 $output .= '</td>';
4482 $output .= '<td class="content">';
4483 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
4484 $output .= '<div class="info">';
4485 if (!empty($user->role) and ($user->role <> $course->teacher)) {
4486 $output .= $string->role .': '. $user->role .'<br />';
4488 if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguest()) or
4489 has_capability('moodle/course:viewhiddenuserfields', $context)) {
4490 $output .= $string->email .': <a href="mailto:'. $user->email .'">'. $user->email .'</a><br />';
4492 if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
4493 $output .= $string->city .': ';
4494 if ($user->city && !isset($hiddenfields['city'])) {
4495 $output .= $user->city;
4497 if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
4498 if ($user->city && !isset($hiddenfields['city'])) {
4499 $output .= ', ';
4501 $output .= $countries[$user->country];
4503 $output .= '<br />';
4506 if (!isset($hiddenfields['lastaccess'])) {
4507 if ($user->lastaccess) {
4508 $output .= $string->lastaccess .': '. userdate($user->lastaccess);
4509 $output .= '&nbsp; ('. format_time(time() - $user->lastaccess, $datestring) .')';
4510 } else {
4511 $output .= $string->lastaccess .': '. $string->never;
4514 $output .= '</div></td><td class="links">';
4515 //link to blogs
4516 if ($CFG->bloglevel > 0) {
4517 $output .= '<a href="'.$CFG->wwwroot.'/blog/index.php?userid='.$user->id.'">'.get_string('blogs','blog').'</a><br />';
4519 //link to notes
4520 if (has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context)) {
4521 $output .= '<a href="'.$CFG->wwwroot.'/notes/index.php?course=' . $course->id. '&amp;user='.$user->id.'">'.get_string('notes','notes').'</a><br />';
4524 if (has_capability('moodle/user:viewuseractivitiesreport', $context) || (isset($usercontext) && has_capability('moodle/user:viewuseractivitiesreport', $usercontext))) {
4525 $timemidnight = usergetmidnight(time());
4526 $output .= '<a href="'. $CFG->wwwroot .'/course/user.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->activity .'</a><br />';
4528 if (has_capability('moodle/role:assign', $context, NULL)) { // Includes admins
4529 $output .= '<a href="'. $CFG->wwwroot .'/course/unenrol.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->unenrol .'</a><br />';
4531 if ($USER->id != $user->id && empty($USER->realuser) && has_capability('moodle/user:loginas', $context) &&
4532 ! has_capability('moodle/site:doanything', $context, $user->id, false)) {
4533 $output .= '<a href="'. $CFG->wwwroot .'/course/loginas.php?id='. $course->id .'&amp;user='. $user->id .'&amp;sesskey='. sesskey() .'">'. $string->loginas .'</a><br />';
4535 $output .= '<a href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&amp;course='. $course->id .'">'. $string->fullprofile .'...</a>';
4537 if (!empty($messageselect)) {
4538 $output .= '<br /><input type="checkbox" name="user'.$user->id.'" /> ';
4541 $output .= '</td></tr></table>';
4543 if ($return) {
4544 return $output;
4545 } else {
4546 echo $output;
4551 * Print a specified group's avatar.
4553 * @param group $group A single {@link group} object OR array of groups.
4554 * @param int $courseid The course ID.
4555 * @param boolean $large Default small picture, or large.
4556 * @param boolean $return If false print picture, otherwise return the output as string
4557 * @param boolean $link Enclose image in a link to view specified course?
4558 * @return string
4559 * @todo Finish documenting this function
4561 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
4562 global $CFG;
4564 if (is_array($group)) {
4565 $output = '';
4566 foreach($group as $g) {
4567 $output .= print_group_picture($g, $courseid, $large, true, $link);
4569 if ($return) {
4570 return $output;
4571 } else {
4572 echo $output;
4573 return;
4577 $context = get_context_instance(CONTEXT_COURSE, $courseid);
4579 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
4580 return '';
4583 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4584 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
4585 } else {
4586 $output = '';
4588 if ($large) {
4589 $file = 'f1';
4590 $size = 100;
4591 } else {
4592 $file = 'f2';
4593 $size = 35;
4595 if ($group->picture) { // Print custom group picture
4596 if ($CFG->slasharguments) { // Use this method if possible for better caching
4597 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot.'/user/pixgroup.php/'.$group->id.'/'.$file.'.jpg"'.
4598 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
4599 } else {
4600 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot.'/user/pixgroup.php?file=/'.$group->id.'/'.$file.'.jpg"'.
4601 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
4604 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4605 $output .= '</a>';
4608 if ($return) {
4609 return $output;
4610 } else {
4611 echo $output;
4616 * Print a png image.
4618 * @param string $url ?
4619 * @param int $sizex ?
4620 * @param int $sizey ?
4621 * @param boolean $return ?
4622 * @param string $parameters ?
4623 * @todo Finish documenting this function
4625 function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
4626 global $CFG;
4627 static $recentIE;
4629 if (!isset($recentIE)) {
4630 $recentIE = check_browser_version('MSIE', '5.0');
4633 if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
4634 $output .= '<img src="'. $CFG->pixpath .'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
4635 ' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
4636 ' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
4637 "'$url', sizingMethod='scale') ".
4638 ' '. $parameters .' />';
4639 } else {
4640 $output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
4643 if ($return) {
4644 return $output;
4645 } else {
4646 echo $output;
4651 * Print a nicely formatted table.
4653 * @param array $table is an object with several properties.
4654 * <ul>
4655 * <li>$table->head - An array of heading names.
4656 * <li>$table->align - An array of column alignments
4657 * <li>$table->size - An array of column sizes
4658 * <li>$table->wrap - An array of "nowrap"s or nothing
4659 * <li>$table->data[] - An array of arrays containing the data.
4660 * <li>$table->width - A percentage of the page
4661 * <li>$table->tablealign - Align the whole table
4662 * <li>$table->cellpadding - Padding on each cell
4663 * <li>$table->cellspacing - Spacing between cells
4664 * <li>$table->class - class attribute to put on the table
4665 * <li>$table->id - id attribute to put on the table.
4666 * <li>$table->rowclass[] - classes to add to particular rows.
4667 * <li>$table->summary - Description of the contents for screen readers.
4668 * </ul>
4669 * @param bool $return whether to return an output string or echo now
4670 * @return boolean or $string
4671 * @todo Finish documenting this function
4673 function print_table($table, $return=false) {
4674 $output = '';
4676 if (isset($table->align)) {
4677 foreach ($table->align as $key => $aa) {
4678 if ($aa) {
4679 $align[$key] = ' text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
4680 } else {
4681 $align[$key] = '';
4685 if (isset($table->size)) {
4686 foreach ($table->size as $key => $ss) {
4687 if ($ss) {
4688 $size[$key] = ' width:'. $ss .';';
4689 } else {
4690 $size[$key] = '';
4694 if (isset($table->wrap)) {
4695 foreach ($table->wrap as $key => $ww) {
4696 if ($ww) {
4697 $wrap[$key] = ' white-space:nowrap;';
4698 } else {
4699 $wrap[$key] = '';
4704 if (empty($table->width)) {
4705 $table->width = '80%';
4708 if (empty($table->tablealign)) {
4709 $table->tablealign = 'center';
4712 if (!isset($table->cellpadding)) {
4713 $table->cellpadding = '5';
4716 if (!isset($table->cellspacing)) {
4717 $table->cellspacing = '1';
4720 if (empty($table->class)) {
4721 $table->class = 'generaltable';
4724 $tableid = empty($table->id) ? '' : 'id="'.$table->id.'"';
4726 $output .= '<table width="'.$table->width.'" ';
4727 if (!empty($table->summary)) {
4728 $output .= " summary=\"$table->summary\"";
4730 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
4732 $countcols = 0;
4734 if (!empty($table->head)) {
4735 $countcols = count($table->head);
4736 $output .= '<tr>';
4737 foreach ($table->head as $key => $heading) {
4739 if (!isset($size[$key])) {
4740 $size[$key] = '';
4742 if (!isset($align[$key])) {
4743 $align[$key] = '';
4746 $output .= '<th style="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.'" scope="col">'. $heading .'</th>';
4748 $output .= '</tr>'."\n";
4751 if (!empty($table->data)) {
4752 $oddeven = 1;
4753 foreach ($table->data as $key => $row) {
4754 $oddeven = $oddeven ? 0 : 1;
4755 if (!isset($table->rowclass[$key])) {
4756 $table->rowclass[$key] = '';
4758 $output .= '<tr class="r'.$oddeven.' '.$table->rowclass[$key].'">'."\n";
4759 if ($row == 'hr' and $countcols) {
4760 $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
4761 } else { /// it's a normal row of data
4762 foreach ($row as $key => $item) {
4763 if (!isset($size[$key])) {
4764 $size[$key] = '';
4766 if (!isset($align[$key])) {
4767 $align[$key] = '';
4769 if (!isset($wrap[$key])) {
4770 $wrap[$key] = '';
4772 $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.'">'. $item .'</td>';
4775 $output .= '</tr>'."\n";
4778 $output .= '</table>'."\n";
4780 if ($return) {
4781 return $output;
4784 echo $output;
4785 return true;
4788 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
4789 static $strftimerecent = null;
4790 $output = '';
4792 if (is_null($viewfullnames)) {
4793 $context = get_context_instance(CONTEXT_SYSTEM);
4794 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
4797 if (is_null($strftimerecent)) {
4798 $strftimerecent = get_string('strftimerecent');
4801 $output .= '<div class="head">';
4802 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
4803 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
4804 $output .= '</div>';
4805 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
4807 if ($return) {
4808 return $output;
4809 } else {
4810 echo $output;
4816 * Prints a basic textarea field.
4818 * @uses $CFG
4819 * @param boolean $usehtmleditor ?
4820 * @param int $rows ?
4821 * @param int $cols ?
4822 * @param null $width <b>Legacy field no longer used!</b> Set to zero to get control over mincols
4823 * @param null $height <b>Legacy field no longer used!</b> Set to zero to get control over minrows
4824 * @param string $name ?
4825 * @param string $value ?
4826 * @param int $courseid ?
4827 * @todo Finish documenting this function
4829 function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $courseid=0, $return=false, $id='') {
4830 /// $width and height are legacy fields and no longer used as pixels like they used to be.
4831 /// However, you can set them to zero to override the mincols and minrows values below.
4833 global $CFG, $COURSE, $HTTPSPAGEREQUIRED;
4834 static $scriptcount = 0; // For loading the htmlarea script only once.
4836 $mincols = 65;
4837 $minrows = 10;
4838 $str = '';
4840 if ($id === '') {
4841 $id = 'edit-'.$name;
4844 if ( empty($CFG->editorsrc) ) { // for backward compatibility.
4845 if (empty($courseid)) {
4846 $courseid = $COURSE->id;
4849 if ($usehtmleditor) {
4850 if (!empty($courseid) and has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE, $courseid))) {
4851 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '&amp;httpsrequired=1';
4852 // needed for course file area browsing in image insert plugin
4853 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4854 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php?id='.$courseid.$httpsrequired.'"></script>'."\n" : '';
4855 } else {
4856 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '?httpsrequired=1';
4857 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4858 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php'.$httpsrequired.'"></script>'."\n" : '';
4861 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4862 $CFG->httpswwwroot .'/lib/editor/htmlarea/lang/en.php"></script>'."\n" : '';
4863 $scriptcount++;
4865 if ($height) { // Usually with legacy calls
4866 if ($rows < $minrows) {
4867 $rows = $minrows;
4870 if ($width) { // Usually with legacy calls
4871 if ($cols < $mincols) {
4872 $cols = $mincols;
4877 $str .= '<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">';
4878 if ($usehtmleditor) {
4879 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
4880 } else {
4881 $str .= s($value);
4883 $str .= '</textarea>'."\n";
4885 if ($usehtmleditor) {
4886 // Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
4887 $str .= '<script type="text/javascript">
4888 //<![CDATA[
4889 document.write(\''.addslashes_js(editorshortcutshelpbutton()).'\');
4890 //]]>
4891 </script>';
4894 if ($return) {
4895 return $str;
4897 echo $str;
4901 * Sets up the HTML editor on textareas in the current page.
4902 * If a field name is provided, then it will only be
4903 * applied to that field - otherwise it will be used
4904 * on every textarea in the page.
4906 * In most cases no arguments need to be supplied
4908 * @param string $name Form element to replace with HTMl editor by name
4910 function use_html_editor($name='', $editorhidebuttons='', $id='') {
4911 global $THEME;
4913 $editor = 'editor_'.md5($name); //name might contain illegal characters
4914 if ($id === '') {
4915 $id = 'edit-'.$name;
4917 echo "\n".'<script type="text/javascript" defer="defer">'."\n";
4918 echo '//<![CDATA['."\n\n"; // Extra \n is to fix odd wiki problem, MDL-8185
4919 echo "$editor = new HTMLArea('$id');\n";
4920 echo "var config = $editor.config;\n";
4922 echo print_editor_config($editorhidebuttons);
4924 if (empty($THEME->htmleditorpostprocess)) {
4925 if (empty($name)) {
4926 echo "\nHTMLArea.replaceAll($editor.config);\n";
4927 } else {
4928 echo "\n$editor.generate();\n";
4930 } else {
4931 if (empty($name)) {
4932 echo "\nvar HTML_name = '';";
4933 } else {
4934 echo "\nvar HTML_name = \"$name;\"";
4936 echo "\nvar HTML_editor = $editor;";
4938 echo '//]]>'."\n";
4939 echo '</script>'."\n";
4942 function print_editor_config($editorhidebuttons='', $return=false) {
4943 global $CFG;
4945 $str = "config.pageStyle = \"body {";
4947 if (!(empty($CFG->editorbackgroundcolor))) {
4948 $str .= " background-color: $CFG->editorbackgroundcolor;";
4951 if (!(empty($CFG->editorfontfamily))) {
4952 $str .= " font-family: $CFG->editorfontfamily;";
4955 if (!(empty($CFG->editorfontsize))) {
4956 $str .= " font-size: $CFG->editorfontsize;";
4959 $str .= " }\";\n";
4960 $str .= "config.killWordOnPaste = ";
4961 $str .= (empty($CFG->editorkillword)) ? "false":"true";
4962 $str .= ';'."\n";
4963 $str .= 'config.fontname = {'."\n";
4965 $fontlist = isset($CFG->editorfontlist) ? explode(';', $CFG->editorfontlist) : array();
4966 $i = 1; // Counter is used to get rid of the last comma.
4968 foreach ($fontlist as $fontline) {
4969 if (!empty($fontline)) {
4970 if ($i > 1) {
4971 $str .= ','."\n";
4973 list($fontkey, $fontvalue) = split(':', $fontline);
4974 $str .= '"'. $fontkey ."\":\t'". $fontvalue ."'";
4976 $i++;
4979 $str .= '};';
4981 if (!empty($editorhidebuttons)) {
4982 $str .= "\nconfig.hideSomeButtons(\" ". $editorhidebuttons ." \");\n";
4983 } else if (!empty($CFG->editorhidebuttons)) {
4984 $str .= "\nconfig.hideSomeButtons(\" ". $CFG->editorhidebuttons ." \");\n";
4987 if (!empty($CFG->editorspelling) && !empty($CFG->aspellpath)) {
4988 $str .= print_speller_code($CFG->htmleditor, true);
4991 if ($return) {
4992 return $str;
4994 echo $str;
4998 * Returns a turn edit on/off button for course in a self contained form.
4999 * Used to be an icon, but it's now a simple form button
5001 * Note that the caller is responsible for capchecks.
5003 * @uses $CFG
5004 * @uses $USER
5005 * @param int $courseid The course to update by id as found in 'course' table
5006 * @return string
5008 function update_course_icon($courseid) {
5009 global $CFG, $USER;
5011 if (!empty($USER->editing)) {
5012 $string = get_string('turneditingoff');
5013 $edit = '0';
5014 } else {
5015 $string = get_string('turneditingon');
5016 $edit = '1';
5019 return '<form '.$CFG->frametarget.' method="get" action="'.$CFG->wwwroot.'/course/view.php">'.
5020 '<div>'.
5021 '<input type="hidden" name="id" value="'.$courseid.'" />'.
5022 '<input type="hidden" name="edit" value="'.$edit.'" />'.
5023 '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
5024 '<input type="submit" value="'.$string.'" />'.
5025 '</div></form>';
5029 * Returns a little popup menu for switching roles
5031 * @uses $CFG
5032 * @uses $USER
5033 * @param int $courseid The course to update by id as found in 'course' table
5034 * @return string
5036 function switchroles_form($courseid) {
5038 global $CFG, $USER;
5041 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
5042 return '';
5045 if (!empty($USER->access['rsw'][$context->path])){ // Just a button to return to normal
5046 $options = array();
5047 $options['id'] = $courseid;
5048 $options['sesskey'] = sesskey();
5049 $options['switchrole'] = 0;
5051 return print_single_button($CFG->wwwroot.'/course/view.php', $options,
5052 get_string('switchrolereturn'), 'post', '_self', true);
5055 if (has_capability('moodle/role:switchroles', $context)) {
5056 if (!$roles = get_assignable_roles_for_switchrole($context)) {
5057 return ''; // Nothing to show!
5059 // unset default user role - it would not work
5060 unset($roles[$CFG->guestroleid]);
5061 return popup_form($CFG->wwwroot.'/course/view.php?id='.$courseid.'&amp;sesskey='.sesskey().'&amp;switchrole=',
5062 $roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
5065 return '';
5070 * Returns a turn edit on/off button for course in a self contained form.
5071 * Used to be an icon, but it's now a simple form button
5073 * @uses $CFG
5074 * @uses $USER
5075 * @param int $courseid The course to update by id as found in 'course' table
5076 * @return string
5078 function update_mymoodle_icon() {
5080 global $CFG, $USER;
5082 if (!empty($USER->editing)) {
5083 $string = get_string('updatemymoodleoff');
5084 $edit = '0';
5085 } else {
5086 $string = get_string('updatemymoodleon');
5087 $edit = '1';
5090 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
5091 "<div>".
5092 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5093 "<input type=\"submit\" value=\"$string\" /></div></form>";
5097 * Returns a turn edit on/off button for tag in a self contained form.
5099 * @uses $CFG
5100 * @uses $USER
5101 * @return string
5103 function update_tag_button($tagid) {
5105 global $CFG, $USER;
5107 if (!empty($USER->editing)) {
5108 $string = get_string('turneditingoff');
5109 $edit = '0';
5110 } else {
5111 $string = get_string('turneditingon');
5112 $edit = '1';
5115 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/tag/index.php\">".
5116 "<div>".
5117 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5118 "<input type=\"hidden\" name=\"id\" value=\"$tagid\" />".
5119 "<input type=\"submit\" value=\"$string\" /></div></form>";
5123 * Prints the editing button on a module "view" page
5125 * @uses $CFG
5126 * @param type description
5127 * @todo Finish documenting this function
5129 function update_module_button($moduleid, $courseid, $string) {
5130 global $CFG, $USER;
5132 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $moduleid))) {
5133 $string = get_string('updatethis', '', $string);
5135 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
5136 "<div>".
5137 "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
5138 "<input type=\"hidden\" name=\"return\" value=\"true\" />".
5139 "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
5140 "<input type=\"submit\" value=\"$string\" /></div></form>";
5141 } else {
5142 return '';
5147 * Prints the editing button on a category page
5149 * @uses $CFG
5150 * @uses $USER
5151 * @param int $categoryid ?
5152 * @return string
5153 * @todo Finish documenting this function
5155 function update_category_button($categoryid) {
5156 global $CFG, $USER;
5158 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_COURSECAT, $categoryid))) {
5159 if (!empty($USER->categoryediting)) {
5160 $string = get_string('turneditingoff');
5161 $edit = 'off';
5162 } else {
5163 $string = get_string('turneditingon');
5164 $edit = 'on';
5167 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/category.php\">".
5168 '<div>'.
5169 "<input type=\"hidden\" name=\"id\" value=\"$categoryid\" />".
5170 "<input type=\"hidden\" name=\"categoryedit\" value=\"$edit\" />".
5171 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5172 "<input type=\"submit\" value=\"$string\" /></div></form>";
5177 * Prints the editing button on categories listing
5179 * @uses $CFG
5180 * @uses $USER
5181 * @return string
5183 function update_categories_button() {
5184 global $CFG, $USER;
5186 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM))) {
5187 if (!empty($USER->categoryediting)) {
5188 $string = get_string('turneditingoff');
5189 $categoryedit = 'off';
5190 } else {
5191 $string = get_string('turneditingon');
5192 $categoryedit = 'on';
5195 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/index.php\">".
5196 '<div>'.
5197 '<input type="hidden" name="categoryedit" value="'. $categoryedit .'" />'.
5198 '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />'.
5199 '<input type="submit" value="'. $string .'" /></div></form>';
5204 * Prints the editing button on search results listing
5205 * For bulk move courses to another category
5208 function update_categories_search_button($search,$page,$perpage) {
5209 global $CFG, $USER;
5211 // not sure if this capability is the best here
5212 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM))) {
5213 if (!empty($USER->categoryediting)) {
5214 $string = get_string("turneditingoff");
5215 $edit = "off";
5216 $perpage = 30;
5217 } else {
5218 $string = get_string("turneditingon");
5219 $edit = "on";
5222 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
5223 '<div>'.
5224 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5225 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5226 "<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
5227 "<input type=\"hidden\" name=\"page\" value=\"$page\" />".
5228 "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
5229 "<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
5234 * Given a course and a (current) coursemodule
5235 * This function returns a small popup menu with all the
5236 * course activity modules in it, as a navigation menu
5237 * The data is taken from the serialised array stored in
5238 * the course record
5240 * @param course $course A {@link $COURSE} object.
5241 * @param course $cm A {@link $COURSE} object.
5242 * @param string $targetwindow ?
5243 * @return string
5244 * @todo Finish documenting this function
5246 function navmenu($course, $cm=NULL, $targetwindow='self') {
5248 global $CFG, $THEME, $USER;
5250 if (empty($THEME->navmenuwidth)) {
5251 $width = 50;
5252 } else {
5253 $width = $THEME->navmenuwidth;
5256 if ($cm) {
5257 $cm = $cm->id;
5260 if ($course->format == 'weeks') {
5261 $strsection = get_string('week');
5262 } else {
5263 $strsection = get_string('topic');
5265 $strjumpto = get_string('jumpto');
5267 $modinfo = get_fast_modinfo($course);
5268 $context = get_context_instance(CONTEXT_COURSE, $course->id);
5270 $section = -1;
5271 $selected = '';
5272 $url = '';
5273 $previousmod = NULL;
5274 $backmod = NULL;
5275 $nextmod = NULL;
5276 $selectmod = NULL;
5277 $logslink = NULL;
5278 $flag = false;
5279 $menu = array();
5280 $menustyle = array();
5282 $sections = get_records('course_sections','course',$course->id,'section','section,visible,summary');
5284 if (!empty($THEME->makenavmenulist)) { /// A hack to produce an XHTML navmenu list for use in themes
5285 $THEME->navmenulist = navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
5288 foreach ($modinfo->cms as $mod) {
5289 if ($mod->modname == 'label') {
5290 continue;
5293 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
5294 break;
5297 if (!$mod->uservisible) { // do not icnlude empty sections at all
5298 continue;
5301 if ($mod->sectionnum > 0 and $section != $mod->sectionnum) {
5302 $thissection = $sections[$mod->sectionnum];
5304 if ($thissection->visible or !$course->hiddensections or
5305 has_capability('moodle/course:viewhiddensections', $context)) {
5306 $thissection->summary = strip_tags(format_string($thissection->summary,true));
5307 if ($course->format == 'weeks' or empty($thissection->summary)) {
5308 $menu[] = '--'.$strsection ." ". $mod->sectionnum;
5309 } else {
5310 if (strlen($thissection->summary) < ($width-3)) {
5311 $menu[] = '--'.$thissection->summary;
5312 } else {
5313 $menu[] = '--'.substr($thissection->summary, 0, $width).'...';
5316 $section = $mod->sectionnum;
5317 } else {
5318 // no activities from this hidden section shown
5319 continue;
5323 $url = $mod->modname.'/view.php?id='. $mod->id;
5324 if ($flag) { // the current mod is the "next" mod
5325 $nextmod = $mod;
5326 $flag = false;
5328 $localname = $mod->name;
5329 if ($cm == $mod->id) {
5330 $selected = $url;
5331 $selectmod = $mod;
5332 $backmod = $previousmod;
5333 $flag = true; // set flag so we know to use next mod for "next"
5334 $localname = $strjumpto;
5335 $strjumpto = '';
5336 } else {
5337 $localname = strip_tags(format_string($localname,true));
5338 $tl=textlib_get_instance();
5339 if ($tl->strlen($localname) > ($width+5)) {
5340 $localname = $tl->substr($localname, 0, $width).'...';
5342 if (!$mod->visible) {
5343 $localname = '('.$localname.')';
5346 $menu[$url] = $localname;
5347 if (empty($THEME->navmenuiconshide)) {
5348 $menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif);"'; // Unfortunately necessary to do this here
5350 $previousmod = $mod;
5352 //Accessibility: added Alt text, replaced &gt; &lt; with 'silent' character and 'accesshide' text.
5354 if ($selectmod and has_capability('moodle/site:viewreports', $context)) {
5355 $logstext = get_string('alllogs');
5356 $logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
5357 $CFG->frametarget.'onclick="this.target=\''.$CFG->framename.'\';"'.' href="'.
5358 $CFG->wwwroot.'/course/report/log/index.php?chooselog=1&amp;user=0&amp;date=0&amp;id='.
5359 $course->id.'&amp;modid='.$selectmod->id.'">'.
5360 '<img class="icon log" src="'.$CFG->pixpath.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
5363 if ($backmod) {
5364 $backtext= get_string('activityprev', 'access');
5365 $backmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$backmod->modname.'/view.php" '.
5366 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
5367 '<input type="hidden" name="id" value="'.$backmod->id.'" />'.
5368 '<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
5369 '</button></fieldset></form></li>';
5371 if ($nextmod) {
5372 $nexttext= get_string('activitynext', 'access');
5373 $nextmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$nextmod->modname.'/view.php" '.
5374 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
5375 '<input type="hidden" name="id" value="'.$nextmod->id.'" />'.
5376 '<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
5377 '</button></fieldset></form></li>';
5380 return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
5381 '<li>'.popup_form($CFG->wwwroot .'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
5382 '', '', true, $targetwindow, '', $menustyle).'</li>'.
5383 $nextmod . '</ul>'."\n".'</div>';
5387 * Given a course
5388 * This function returns a small popup menu with all the
5389 * course activity modules in it, as a navigation menu
5390 * outputs a simple list structure in XHTML
5391 * The data is taken from the serialised array stored in
5392 * the course record
5394 * @param course $course A {@link $COURSE} object.
5395 * @return string
5396 * @todo Finish documenting this function
5398 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
5400 global $CFG;
5402 $section = -1;
5403 $url = '';
5404 $menu = array();
5405 $doneheading = false;
5407 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
5409 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
5410 foreach ($modinfo->cms as $mod) {
5411 if ($mod->modname == 'label') {
5412 continue;
5415 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
5416 break;
5419 if (!$mod->uservisible) { // do not icnlude empty sections at all
5420 continue;
5423 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
5424 $thissection = $sections[$mod->sectionnum];
5426 if ($thissection->visible or !$course->hiddensections or
5427 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
5428 $thissection->summary = strip_tags(format_string($thissection->summary,true));
5429 if (!$doneheading) {
5430 $menu[] = '</ul></li>';
5432 if ($course->format == 'weeks' or empty($thissection->summary)) {
5433 $item = $strsection ." ". $mod->sectionnum;
5434 } else {
5435 if (strlen($thissection->summary) < ($width-3)) {
5436 $item = $thissection->summary;
5437 } else {
5438 $item = substr($thissection->summary, 0, $width).'...';
5441 $menu[] = '<li class="section"><span>'.$item.'</span>';
5442 $menu[] = '<ul>';
5443 $doneheading = true;
5445 $section = $mod->sectionnum;
5446 } else {
5447 // no activities from this hidden section shown
5448 continue;
5452 $url = $mod->modname .'/view.php?id='. $mod->id;
5453 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
5454 if (strlen($mod->name) > ($width+5)) {
5455 $mod->name = substr($mod->name, 0, $width).'...';
5457 if (!$mod->visible) {
5458 $mod->name = '('.$mod->name.')';
5460 $class = 'activity '.$mod->modname;
5461 $class .= ($cmid == $mod->cm) ? ' selected' : '';
5462 $menu[] = '<li class="'.$class.'">'.
5463 '<img src="'.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif" alt="" />'.
5464 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
5467 if ($doneheading) {
5468 $menu[] = '</ul></li>';
5470 $menu[] = '</ul></li></ul>';
5472 return implode("\n", $menu);
5476 * Prints form items with the names $day, $month and $year
5478 * @param string $day fieldname
5479 * @param string $month fieldname
5480 * @param string $year fieldname
5481 * @param int $currenttime A default timestamp in GMT
5482 * @param boolean $return
5484 function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
5486 if (!$currenttime) {
5487 $currenttime = time();
5489 $currentdate = usergetdate($currenttime);
5491 for ($i=1; $i<=31; $i++) {
5492 $days[$i] = $i;
5494 for ($i=1; $i<=12; $i++) {
5495 $months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
5497 for ($i=1970; $i<=2020; $i++) {
5498 $years[$i] = $i;
5500 return choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', $return)
5501 .choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', $return)
5502 .choose_from_menu($years, $year, $currentdate['year'], '', '', '0', $return);
5507 *Prints form items with the names $hour and $minute
5509 * @param string $hour fieldname
5510 * @param string ? $minute fieldname
5511 * @param $currenttime A default timestamp in GMT
5512 * @param int $step minute spacing
5513 * @param boolean $return
5515 function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
5517 if (!$currenttime) {
5518 $currenttime = time();
5520 $currentdate = usergetdate($currenttime);
5521 if ($step != 1) {
5522 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
5524 for ($i=0; $i<=23; $i++) {
5525 $hours[$i] = sprintf("%02d",$i);
5527 for ($i=0; $i<=59; $i+=$step) {
5528 $minutes[$i] = sprintf("%02d",$i);
5531 return choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',$return)
5532 .choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',$return);
5536 * Prints time limit value selector
5538 * @uses $CFG
5539 * @param int $timelimit default
5540 * @param string $unit
5541 * @param string $name
5542 * @param boolean $return
5544 function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
5546 global $CFG;
5548 if ($unit) {
5549 $unit = ' '.$unit;
5552 // Max timelimit is sessiontimeout - 10 minutes.
5553 $maxvalue = ($CFG->sessiontimeout / 60) - 10;
5555 for ($i=1; $i<=$maxvalue; $i++) {
5556 $minutes[$i] = $i.$unit;
5558 return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
5562 * Prints a grade menu (as part of an existing form) with help
5563 * Showing all possible numerical grades and scales
5565 * @uses $CFG
5566 * @param int $courseid ?
5567 * @param string $name ?
5568 * @param string $current ?
5569 * @param boolean $includenograde ?
5570 * @todo Finish documenting this function
5572 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
5574 global $CFG;
5576 $output = '';
5577 $strscale = get_string('scale');
5578 $strscales = get_string('scales');
5580 $scales = get_scales_menu($courseid);
5581 foreach ($scales as $i => $scalename) {
5582 $grades[-$i] = $strscale .': '. $scalename;
5584 if ($includenograde) {
5585 $grades[0] = get_string('nograde');
5587 for ($i=100; $i>=1; $i--) {
5588 $grades[$i] = $i;
5590 $output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
5592 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5593 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5594 $linkobject, 400, 500, $strscales, 'none', true);
5596 if ($return) {
5597 return $output;
5598 } else {
5599 echo $output;
5604 * Prints a scale menu (as part of an existing form) including help button
5605 * Just like {@link print_grade_menu()} but without the numeric grades
5607 * @param int $courseid ?
5608 * @param string $name ?
5609 * @param string $current ?
5610 * @todo Finish documenting this function
5612 function print_scale_menu($courseid, $name, $current, $return=false) {
5614 global $CFG;
5616 $output = '';
5617 $strscales = get_string('scales');
5618 $output .= choose_from_menu(get_scales_menu($courseid), $name, $current, '', '', 0, true);
5620 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5621 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5622 $linkobject, 400, 500, $strscales, 'none', true);
5623 if ($return) {
5624 return $output;
5625 } else {
5626 echo $output;
5631 * Prints a help button about a scale
5633 * @uses $CFG
5634 * @param id $courseid ?
5635 * @param object $scale ?
5636 * @todo Finish documenting this function
5638 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
5640 global $CFG;
5642 $output = '';
5643 $strscales = get_string('scales');
5645 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5646 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true&amp;scaleid='. $scale->id, 'ratingscale',
5647 $linkobject, 400, 500, $scale->name, 'none', true);
5648 if ($return) {
5649 return $output;
5650 } else {
5651 echo $output;
5656 * Print an error page displaying an error message. New method - use this for new code.
5658 * @uses $SESSION
5659 * @uses $CFG
5660 * @param string $errorcode The name of the string from error.php to print
5661 * @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.
5662 * @param object $a Extra words and phrases that might be required in the error string
5664 function print_error ($errorcode, $module='', $link='', $a=NULL) {
5666 global $CFG, $SESSION, $THEME;
5668 if (empty($module) || $module == 'moodle' || $module == 'core') {
5669 $module = 'error';
5670 $modulelink = 'moodle';
5671 } else {
5672 $modulelink = $module;
5675 if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
5676 if ( !empty($SESSION->fromurl) ) {
5677 $link = $SESSION->fromurl;
5678 unset($SESSION->fromurl);
5679 } else {
5680 $link = $CFG->wwwroot .'/';
5684 if (!empty($CFG->errordocroot)) {
5685 $errordocroot = $CFG->errordocroot;
5686 } else if (!empty($CFG->docroot)) {
5687 $errordocroot = $CFG->docroot;
5688 } else {
5689 $errordocroot = 'http://docs.moodle.org';
5692 $message = get_string($errorcode, $module, $a);
5694 if (defined('FULLME') && FULLME == 'cron') {
5695 // Errors in cron should be mtrace'd.
5696 mtrace($message);
5697 die;
5700 $message = clean_text('<p class="errormessage">'.$message.'</p>'.
5701 '<p class="errorcode">'.
5702 '<a href="'.$errordocroot.'/en/error/'.$modulelink.'/'.$errorcode.'">'.
5703 get_string('moreinformation').'</a></p>');
5705 if (! defined('HEADER_PRINTED')) {
5706 //header not yet printed
5707 @header('HTTP/1.0 404 Not Found');
5708 print_header(get_string('error'));
5709 } else {
5710 print_container_end_all(false, $THEME->open_header_containers);
5713 echo '<br />';
5715 print_simple_box($message, '', '', '', '', 'errorbox');
5717 debugging('Stack trace:', DEBUG_DEVELOPER);
5719 // in case we are logging upgrade in admin/index.php stop it
5720 if (function_exists('upgrade_log_finish')) {
5721 upgrade_log_finish();
5724 if (!empty($link)) {
5725 print_continue($link);
5728 print_footer();
5730 for ($i=0;$i<512;$i++) { // Padding to help IE work with 404
5731 echo ' ';
5733 die;
5737 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
5738 * Default errorcode is 1.
5740 * Very useful for perl-like error-handling:
5742 * do_somethting() or mdie("Something went wrong");
5744 * @param string $msg Error message
5745 * @param integer $errorcode Error code to emit
5747 function mdie($msg='', $errorcode=1) {
5748 trigger_error($msg);
5749 exit($errorcode);
5753 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
5754 * Should be used only with htmleditor or textarea.
5755 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
5756 * helpbutton.
5757 * @return string
5759 function editorhelpbutton(){
5760 global $CFG, $SESSION;
5761 $items = func_get_args();
5762 $i = 1;
5763 $urlparams = array();
5764 $titles = array();
5765 foreach ($items as $item){
5766 if (is_array($item)){
5767 $urlparams[] = "keyword$i=".urlencode($item[0]);
5768 $urlparams[] = "title$i=".urlencode($item[1]);
5769 if (isset($item[2])){
5770 $urlparams[] = "module$i=".urlencode($item[2]);
5772 $titles[] = trim($item[1], ". \t");
5773 }elseif (is_string($item)){
5774 $urlparams[] = "button$i=".urlencode($item);
5775 switch ($item){
5776 case 'reading' :
5777 $titles[] = get_string("helpreading");
5778 break;
5779 case 'writing' :
5780 $titles[] = get_string("helpwriting");
5781 break;
5782 case 'questions' :
5783 $titles[] = get_string("helpquestions");
5784 break;
5785 case 'emoticons' :
5786 $titles[] = get_string("helpemoticons");
5787 break;
5788 case 'richtext' :
5789 $titles[] = get_string('helprichtext');
5790 break;
5791 case 'text' :
5792 $titles[] = get_string('helptext');
5793 break;
5794 default :
5795 error('Unknown help topic '.$item);
5798 $i++;
5800 if (count($titles)>1){
5801 //join last two items with an 'and'
5802 $a = new object();
5803 $a->one = $titles[count($titles) - 2];
5804 $a->two = $titles[count($titles) - 1];
5805 $titles[count($titles) - 2] = get_string('and', '', $a);
5806 unset($titles[count($titles) - 1]);
5808 $alttag = join (', ', $titles);
5810 $paramstring = join('&', $urlparams);
5811 $linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath .'/help.gif" />';
5812 return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), 'popup', $linkobject, 400, 500, $alttag, 'none', true);
5816 * Print a help button.
5818 * @uses $CFG
5819 * @param string $page The keyword that defines a help page
5820 * @param string $title The title of links, rollover tips, alt tags etc
5821 * 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
5822 * @param string $module Which module is the page defined in
5823 * @param mixed $image Use a help image for the link? (true/false/"both")
5824 * @param boolean $linktext If true, display the title next to the help icon.
5825 * @param string $text If defined then this text is used in the page, and
5826 * the $page variable is ignored.
5827 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
5828 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
5829 * @return string
5830 * @todo Finish documenting this function
5832 function helpbutton ($page, $title, $module='moodle', $image=true, $linktext=false, $text='', $return=false,
5833 $imagetext='') {
5834 global $CFG, $COURSE;
5836 // fix for MDL-7734
5837 if (!empty($COURSE->lang)) {
5838 $forcelang = $COURSE->lang;
5839 } else {
5840 $forcelang = '';
5843 if ($module == '') {
5844 $module = 'moodle';
5847 if ($title == '' && $linktext == '') {
5848 debugging('Error in call to helpbutton function: at least one of $title and $linktext is required');
5851 // Warn users about new window for Accessibility
5852 $tooltip = get_string('helpprefix2', '', trim($title, ". \t")) .' ('.get_string('newwindow').')';
5854 $linkobject = '';
5856 if ($image) {
5857 if ($linktext) {
5858 // MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
5859 $linkobject .= $title.'&nbsp;';
5860 $tooltip = get_string('helpwiththis');
5862 if ($imagetext) {
5863 $linkobject .= $imagetext;
5864 } else {
5865 $linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
5866 $CFG->pixpath .'/help.gif" />';
5868 } else {
5869 $linkobject .= $tooltip;
5872 // fix for MDL-7734
5873 if ($text) {
5874 $url = '/help.php?module='. $module .'&amp;text='. s(urlencode($text).'&amp;forcelang='.$forcelang);
5875 } else {
5876 $url = '/help.php?module='. $module .'&amp;file='. $page .'.html&amp;forcelang='.$forcelang;
5879 $link = '<span class="helplink">'.
5880 link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
5881 '</span>';
5883 if ($return) {
5884 return $link;
5885 } else {
5886 echo $link;
5891 * Print a help button.
5893 * Prints a special help button that is a link to the "live" emoticon popup
5894 * @uses $CFG
5895 * @uses $SESSION
5896 * @param string $form ?
5897 * @param string $field ?
5898 * @todo Finish documenting this function
5900 function emoticonhelpbutton($form, $field, $return = false) {
5902 global $CFG, $SESSION;
5904 $SESSION->inserttextform = $form;
5905 $SESSION->inserttextfield = $field;
5906 $imagetext = '<img src="' . $CFG->pixpath . '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
5907 $help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
5908 if (!$return){
5909 echo $help;
5910 } else {
5911 return $help;
5916 * Print a help button.
5918 * Prints a special help button for html editors (htmlarea in this case)
5919 * @uses $CFG
5921 function editorshortcutshelpbutton() {
5923 global $CFG;
5924 $imagetext = '<img src="' . $CFG->httpswwwroot . '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
5925 get_string('editorshortcutkeys').'" class="iconkbhelp" />';
5927 return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
5931 * Print a message and exit.
5933 * @uses $CFG
5934 * @param string $message ?
5935 * @param string $link ?
5936 * @todo Finish documenting this function
5938 function notice ($message, $link='', $course=NULL) {
5939 global $CFG, $SITE, $THEME, $COURSE;
5941 $message = clean_text($message); // In case nasties are in here
5943 if (defined('FULLME') && FULLME == 'cron') {
5944 // notices in cron should be mtrace'd.
5945 mtrace($message);
5946 die;
5949 if (! defined('HEADER_PRINTED')) {
5950 //header not yet printed
5951 print_header(get_string('notice'));
5952 } else {
5953 print_container_end_all(false, $THEME->open_header_containers);
5956 print_box($message, 'generalbox', 'notice');
5957 print_continue($link);
5959 if (empty($course)) {
5960 print_footer($COURSE);
5961 } else {
5962 print_footer($course);
5964 exit;
5968 * Print a message along with "Yes" and "No" links for the user to continue.
5970 * @param string $message The text to display
5971 * @param string $linkyes The link to take the user to if they choose "Yes"
5972 * @param string $linkno The link to take the user to if they choose "No"
5973 * TODO Document remaining arguments
5975 function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
5977 global $CFG;
5979 $message = clean_text($message);
5980 $linkyes = clean_text($linkyes);
5981 $linkno = clean_text($linkno);
5983 print_box_start('generalbox', 'notice');
5984 echo '<p>'. $message .'</p>';
5985 echo '<div class="buttons">';
5986 print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename);
5987 print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename);
5988 echo '</div>';
5989 print_box_end();
5993 * Provide an definition of error_get_last for PHP before 5.2.0. This simply
5994 * returns NULL, since there is not way to get the right answer.
5996 if (!function_exists('error_get_last')) {
5997 // the eval is needed to prevent PHP 5.2+ from getting a parse error!
5998 eval('
5999 function error_get_last() {
6000 return NULL;
6006 * Redirects the user to another page, after printing a notice
6008 * @param string $url The url to take the user to
6009 * @param string $message The text message to display to the user about the redirect, if any
6010 * @param string $delay How long before refreshing to the new page at $url?
6011 * @todo '&' needs to be encoded into '&amp;' for XHTML compliance,
6012 * however, this is not true for javascript. Therefore we
6013 * first decode all entities in $url (since we cannot rely on)
6014 * the correct input) and then encode for where it's needed
6015 * echo "<script type='text/javascript'>alert('Redirect $url');</script>";
6017 function redirect($url, $message='', $delay=-1) {
6019 global $CFG, $THEME;
6021 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
6022 $url = sid_process_url($url);
6025 $message = clean_text($message);
6027 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
6028 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
6029 $url = str_replace('&amp;', '&', $encodedurl);
6031 /// At developer debug level. Don't redirect if errors have been printed on screen.
6032 /// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
6033 $lasterror = error_get_last();
6034 $error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER));
6035 $errorprinted = debugging('', DEBUG_ALL) && $CFG->debugdisplay && $error;
6036 if ($errorprinted) {
6037 $message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
6040 $performanceinfo = '';
6041 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
6042 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
6043 $perf = get_performance_info();
6044 error_log("PERF: " . $perf['txt']);
6048 /// when no message and header printed yet, try to redirect
6049 if (empty($message) and !defined('HEADER_PRINTED')) {
6051 // Technically, HTTP/1.1 requires Location: header to contain
6052 // the absolute path. (In practice browsers accept relative
6053 // paths - but still, might as well do it properly.)
6054 // This code turns relative into absolute.
6055 if (!preg_match('|^[a-z]+:|', $url)) {
6056 // Get host name http://www.wherever.com
6057 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
6058 if (preg_match('|^/|', $url)) {
6059 // URLs beginning with / are relative to web server root so we just add them in
6060 $url = $hostpart.$url;
6061 } else {
6062 // URLs not beginning with / are relative to path of current script, so add that on.
6063 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
6065 // Replace all ..s
6066 while (true) {
6067 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
6068 if ($newurl == $url) {
6069 break;
6071 $url = $newurl;
6075 $delay = 0;
6076 //try header redirection first
6077 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
6078 @header('Location: '.$url);
6079 //another way for older browsers and already sent headers (eg trailing whitespace in config.php)
6080 echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
6081 echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
6082 die;
6085 if ($delay == -1) {
6086 $delay = 3; // if no delay specified wait 3 seconds
6088 if (! defined('HEADER_PRINTED')) {
6089 // this type of redirect might not be working in some browsers - such as lynx :-(
6090 print_header('', '', '', '', $errorprinted ? '' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
6091 $delay += 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
6092 } else {
6093 print_container_end_all(false, $THEME->open_header_containers);
6095 echo '<div id="redirect">';
6096 echo '<div id="message">' . $message . '</div>';
6097 echo '<div id="continue">( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
6098 echo '</div>';
6100 if (!$errorprinted) {
6102 <script type="text/javascript">
6103 //<![CDATA[
6105 function redirect() {
6106 document.location.replace('<?php echo addslashes_js($url) ?>');
6108 setTimeout("redirect()", <?php echo ($delay * 1000) ?>);
6109 //]]>
6110 </script>
6111 <?php
6114 $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
6115 print_footer('none');
6116 die;
6120 * Print a bold message in an optional color.
6122 * @param string $message The message to print out
6123 * @param string $style Optional style to display message text in
6124 * @param string $align Alignment option
6125 * @param bool $return whether to return an output string or echo now
6127 function notify($message, $style='notifyproblem', $align='center', $return=false) {
6128 if ($style == 'green') {
6129 $style = 'notifysuccess'; // backward compatible with old color system
6132 $message = clean_text($message);
6134 $output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."\n";
6136 if ($return) {
6137 return $output;
6139 echo $output;
6144 * Given an email address, this function will return an obfuscated version of it
6146 * @param string $email The email address to obfuscate
6147 * @return string
6149 function obfuscate_email($email) {
6151 $i = 0;
6152 $length = strlen($email);
6153 $obfuscated = '';
6154 while ($i < $length) {
6155 if (rand(0,2)) {
6156 $obfuscated.='%'.dechex(ord($email{$i}));
6157 } else {
6158 $obfuscated.=$email{$i};
6160 $i++;
6162 return $obfuscated;
6166 * This function takes some text and replaces about half of the characters
6167 * with HTML entity equivalents. Return string is obviously longer.
6169 * @param string $plaintext The text to be obfuscated
6170 * @return string
6172 function obfuscate_text($plaintext) {
6174 $i=0;
6175 $length = strlen($plaintext);
6176 $obfuscated='';
6177 $prev_obfuscated = false;
6178 while ($i < $length) {
6179 $c = ord($plaintext{$i});
6180 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
6181 if ($prev_obfuscated and $numerical ) {
6182 $obfuscated.='&#'.ord($plaintext{$i}).';';
6183 } else if (rand(0,2)) {
6184 $obfuscated.='&#'.ord($plaintext{$i}).';';
6185 $prev_obfuscated = true;
6186 } else {
6187 $obfuscated.=$plaintext{$i};
6188 $prev_obfuscated = false;
6190 $i++;
6192 return $obfuscated;
6196 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
6197 * to generate a fully obfuscated email link, ready to use.
6199 * @param string $email The email address to display
6200 * @param string $label The text to dispalyed as hyperlink to $email
6201 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
6202 * @return string
6204 function obfuscate_mailto($email, $label='', $dimmed=false) {
6206 if (empty($label)) {
6207 $label = $email;
6209 if ($dimmed) {
6210 $title = get_string('emaildisable');
6211 $dimmed = ' class="dimmed"';
6212 } else {
6213 $title = '';
6214 $dimmed = '';
6216 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
6217 obfuscate_text('mailto'), obfuscate_email($email),
6218 obfuscate_text($label));
6222 * Prints a single paging bar to provide access to other pages (usually in a search)
6224 * @param int $totalcount Thetotal number of entries available to be paged through
6225 * @param int $page The page you are currently viewing
6226 * @param int $perpage The number of entries that should be shown per page
6227 * @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.
6228 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
6229 * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
6230 * @param bool $nocurr do not display the current page as a link
6231 * @param bool $return whether to return an output string or echo now
6232 * @return bool or string
6234 function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
6235 $maxdisplay = 18;
6236 $output = '';
6238 if ($totalcount > $perpage) {
6239 $output .= '<div class="paging">';
6240 $output .= get_string('page') .':';
6241 if ($page > 0) {
6242 $pagenum = $page - 1;
6243 if (!is_a($baseurl, 'moodle_url')){
6244 $output .= '&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>)&nbsp;';
6245 } else {
6246 $output .= '&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>)&nbsp;';
6249 if ($perpage > 0) {
6250 $lastpage = ceil($totalcount / $perpage);
6251 } else {
6252 $lastpage = 1;
6254 if ($page > 15) {
6255 $startpage = $page - 10;
6256 if (!is_a($baseurl, 'moodle_url')){
6257 $output .= '&nbsp;<a href="'. $baseurl . $pagevar .'=0">1</a>&nbsp;...';
6258 } else {
6259 $output .= '&nbsp;<a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a>&nbsp;...';
6261 } else {
6262 $startpage = 0;
6264 $currpage = $startpage;
6265 $displaycount = $displaypage = 0;
6266 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
6267 $displaypage = $currpage+1;
6268 if ($page == $currpage && empty($nocurr)) {
6269 $output .= '&nbsp;&nbsp;'. $displaypage;
6270 } else {
6271 if (!is_a($baseurl, 'moodle_url')){
6272 $output .= '&nbsp;&nbsp;<a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
6273 } else {
6274 $output .= '&nbsp;&nbsp;<a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
6278 $displaycount++;
6279 $currpage++;
6281 if ($currpage < $lastpage) {
6282 $lastpageactual = $lastpage - 1;
6283 if (!is_a($baseurl, 'moodle_url')){
6284 $output .= '&nbsp;...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a>&nbsp;';
6285 } else {
6286 $output .= '&nbsp;...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a>&nbsp;';
6289 $pagenum = $page + 1;
6290 if ($pagenum != $displaypage) {
6291 if (!is_a($baseurl, 'moodle_url')){
6292 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
6293 } else {
6294 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
6297 $output .= '</div>';
6300 if ($return) {
6301 return $output;
6304 echo $output;
6305 return true;
6309 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
6310 * will transform it to html entities
6312 * @param string $text Text to search for nolink tag in
6313 * @return string
6315 function rebuildnolinktag($text) {
6317 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
6319 return $text;
6323 * Prints a nice side block with an optional header. The content can either
6324 * be a block of HTML or a list of text with optional icons.
6326 * @param string $heading Block $title embedded in HTML tags, for example <h2>.
6327 * @param string $content ?
6328 * @param array $list ?
6329 * @param array $icons ?
6330 * @param string $footer ?
6331 * @param array $attributes ?
6332 * @param string $title Plain text title, as embedded in the $heading.
6333 * @todo Finish documenting this function. Show example of various attributes, etc.
6335 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
6337 //Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
6338 static $block_id = 0;
6339 $block_id++;
6340 if (empty($heading)) {
6341 $skip_text = get_string('skipblock', 'access').' '.$block_id;
6343 else {
6344 $skip_text = get_string('skipa', 'access', strip_tags($title));
6346 $skip_link = '<a href="#sb-'.$block_id.'" class="skip-block">'.$skip_text.'</a>';
6347 $skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
6349 if (! empty($heading)) {
6350 echo $skip_link;
6352 //ELSE: a single link on a page "Skip block 4" is too confusing - ignore.
6354 print_side_block_start($heading, $attributes);
6356 if ($content) {
6357 echo $content;
6358 if ($footer) {
6359 echo '<div class="footer">'. $footer .'</div>';
6361 } else {
6362 if ($list) {
6363 $row = 0;
6364 //Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
6365 echo "\n<ul class='list'>\n";
6366 foreach ($list as $key => $string) {
6367 echo '<li class="r'. $row .'">';
6368 if ($icons) {
6369 echo '<div class="icon column c0">'. $icons[$key] .'</div>';
6371 echo '<div class="column c1">'. $string .'</div>';
6372 echo "</li>\n";
6373 $row = $row ? 0:1;
6375 echo "</ul>\n";
6377 if ($footer) {
6378 echo '<div class="footer">'. $footer .'</div>';
6383 print_side_block_end($attributes, $title);
6384 echo $skip_dest;
6388 * Starts a nice side block with an optional header.
6390 * @param string $heading ?
6391 * @param array $attributes ?
6392 * @todo Finish documenting this function
6394 function print_side_block_start($heading='', $attributes = array()) {
6396 global $CFG, $THEME;
6398 // If there are no special attributes, give a default CSS class
6399 if (empty($attributes) || !is_array($attributes)) {
6400 $attributes = array('class' => 'sideblock');
6402 } else if(!isset($attributes['class'])) {
6403 $attributes['class'] = 'sideblock';
6405 } else if(!strpos($attributes['class'], 'sideblock')) {
6406 $attributes['class'] .= ' sideblock';
6409 // OK, the class is surely there and in addition to anything
6410 // else, it's tagged as a sideblock
6414 // IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
6416 // If there is a cookie to hide this thing, start it hidden
6417 if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
6418 $attributes['class'] = 'hidden '.$attributes['class'];
6422 $attrtext = '';
6423 foreach ($attributes as $attr => $val) {
6424 $attrtext .= ' '.$attr.'="'.$val.'"';
6427 echo '<div '.$attrtext.'>';
6429 if (!empty($THEME->customcorners)) {
6430 echo '<div class="wrap">'."\n";
6432 if ($heading) {
6433 //Accessibility: H2 more appropriate in moodleblock.class.php: _title_html.
6434 echo '<div class="header">';
6435 if (!empty($THEME->customcorners)) {
6436 echo '<div class="bt"><div>&nbsp;</div></div>';
6437 echo '<div class="i1"><div class="i2">';
6438 echo '<div class="i3">';
6440 echo $heading;
6441 if (!empty($THEME->customcorners)) {
6442 echo '</div></div></div>';
6444 echo '</div>';
6445 } else {
6446 if (!empty($THEME->customcorners)) {
6447 echo '<div class="bt"><div>&nbsp;</div></div>';
6451 if (!empty($THEME->customcorners)) {
6452 echo '<div class="i1"><div class="i2">';
6453 echo '<div class="i3">';
6455 echo '<div class="content">';
6461 * Print table ending tags for a side block box.
6463 function print_side_block_end($attributes = array(), $title='') {
6464 global $CFG, $THEME;
6466 echo '</div>';
6468 if (!empty($THEME->customcorners)) {
6469 echo '</div></div></div><div class="bb"><div>&nbsp;</div></div></div>';
6472 echo '</div>';
6474 $strshow = addslashes_js(get_string('showblocka', 'access', strip_tags($title)));
6475 $strhide = addslashes_js(get_string('hideblocka', 'access', strip_tags($title)));
6477 // IE workaround: if I do it THIS way, it works! WTF?
6478 if (!empty($CFG->allowuserblockhiding) && isset($attributes['id'])) {
6479 echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].
6480 '","'.$strshow.'","'.$strhide."\");\n//]]>\n".'</script>';
6487 * Prints out code needed for spellchecking.
6488 * Original idea by Ludo (Marc Alier).
6490 * Opening CDATA and <script> are output by weblib::use_html_editor()
6491 * @uses $CFG
6492 * @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
6493 * @param boolean $return If false, echos the code instead of returning it
6494 * @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
6496 function print_speller_code ($usehtmleditor=false, $return=false) {
6497 global $CFG;
6498 $str = '';
6500 if(!$usehtmleditor) {
6501 $str .= 'function openSpellChecker() {'."\n";
6502 $str .= "\tvar speller = new spellChecker();\n";
6503 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot ."/lib/speller/spellchecker.html\";\n";
6504 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
6505 $str .= "\tspeller.spellCheckAll();\n";
6506 $str .= '}'."\n";
6507 } else {
6508 $str .= "function spellClickHandler(editor, buttonId) {\n";
6509 $str .= "\teditor._textArea.value = editor.getHTML();\n";
6510 $str .= "\tvar speller = new spellChecker( editor._textArea );\n";
6511 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot ."/lib/speller/spellchecker.html\";\n";
6512 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
6513 $str .= "\tspeller._moogle_edit=1;\n";
6514 $str .= "\tspeller._editor=editor;\n";
6515 $str .= "\tspeller.openChecker();\n";
6516 $str .= '}'."\n";
6519 if ($return) {
6520 return $str;
6522 echo $str;
6526 * Print button for spellchecking when editor is disabled
6528 function print_speller_button () {
6529 echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
6533 function page_id_and_class(&$getid, &$getclass) {
6534 // Create class and id for this page
6535 global $CFG, $ME;
6537 static $class = NULL;
6538 static $id = NULL;
6540 if (empty($CFG->pagepath)) {
6541 $CFG->pagepath = $ME;
6544 if (empty($class) || empty($id)) {
6545 $path = str_replace($CFG->httpswwwroot.'/', '', $CFG->pagepath); //Because the page could be HTTPSPAGEREQUIRED
6546 $path = str_replace('.php', '', $path);
6547 if (substr($path, -1) == '/') {
6548 $path .= 'index';
6550 if (empty($path) || $path == 'index') {
6551 $id = 'site-index';
6552 $class = 'course';
6553 } else if (substr($path, 0, 5) == 'admin') {
6554 $id = str_replace('/', '-', $path);
6555 $class = 'admin';
6556 } else {
6557 $id = str_replace('/', '-', $path);
6558 $class = explode('-', $id);
6559 array_pop($class);
6560 $class = implode('-', $class);
6564 $getid = $id;
6565 $getclass = $class;
6569 * Prints a maintenance message from /maintenance.html
6571 function print_maintenance_message () {
6572 global $CFG, $SITE;
6574 print_header(strip_tags($SITE->fullname), $SITE->fullname, 'home');
6575 print_simple_box_start('center');
6576 print_heading(get_string('sitemaintenance', 'admin'));
6577 @include($CFG->dataroot.'/1/maintenance.html');
6578 print_simple_box_end();
6579 print_footer();
6583 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
6585 function adjust_allowed_tags() {
6587 global $CFG, $ALLOWED_TAGS;
6589 if (!empty($CFG->allowobjectembed)) {
6590 $ALLOWED_TAGS .= '<embed><object>';
6594 /// Some code to print tabs
6596 /// A class for tabs
6597 class tabobject {
6598 var $id;
6599 var $link;
6600 var $text;
6601 var $linkedwhenselected;
6603 /// A constructor just because I like constructors
6604 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
6605 $this->id = $id;
6606 $this->link = $link;
6607 $this->text = $text;
6608 $this->title = $title ? $title : $text;
6609 $this->linkedwhenselected = $linkedwhenselected;
6616 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
6618 * @param array $tabrows An array of rows where each row is an array of tab objects
6619 * @param string $selected The id of the selected tab (whatever row it's on)
6620 * @param array $inactive An array of ids of inactive tabs that are not selectable.
6621 * @param array $activated An array of ids of other tabs that are currently activated
6623 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
6624 global $CFG;
6626 /// $inactive must be an array
6627 if (!is_array($inactive)) {
6628 $inactive = array();
6631 /// $activated must be an array
6632 if (!is_array($activated)) {
6633 $activated = array();
6636 /// Convert the tab rows into a tree that's easier to process
6637 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
6638 return false;
6641 /// Print out the current tree of tabs (this function is recursive)
6643 $output = convert_tree_to_html($tree);
6645 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
6647 /// We're done!
6649 if ($return) {
6650 return $output;
6652 echo $output;
6656 function convert_tree_to_html($tree, $row=0) {
6658 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
6660 $first = true;
6661 $count = count($tree);
6663 foreach ($tree as $tab) {
6664 $count--; // countdown to zero
6666 $liclass = '';
6668 if ($first && ($count == 0)) { // Just one in the row
6669 $liclass = 'first last';
6670 $first = false;
6671 } else if ($first) {
6672 $liclass = 'first';
6673 $first = false;
6674 } else if ($count == 0) {
6675 $liclass = 'last';
6678 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
6679 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
6682 if ($tab->inactive || $tab->active || $tab->selected) {
6683 if ($tab->selected) {
6684 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
6685 } else if ($tab->active) {
6686 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
6690 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
6692 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
6693 // The a tag is used for styling
6694 $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
6695 } else {
6696 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
6699 if (!empty($tab->subtree)) {
6700 $str .= convert_tree_to_html($tab->subtree, $row+1);
6701 } else if ($tab->selected) {
6702 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
6705 $str .= ' </li>'."\n";
6707 $str .= '</ul>'."\n";
6709 return $str;
6713 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
6715 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
6717 $tabrows = array_reverse($tabrows);
6719 $subtree = array();
6721 foreach ($tabrows as $row) {
6722 $tree = array();
6724 foreach ($row as $tab) {
6725 $tab->inactive = in_array((string)$tab->id, $inactive);
6726 $tab->active = in_array((string)$tab->id, $activated);
6727 $tab->selected = (string)$tab->id == $selected;
6729 if ($tab->active || $tab->selected) {
6730 if ($subtree) {
6731 $tab->subtree = $subtree;
6734 $tree[] = $tab;
6736 $subtree = $tree;
6739 return $subtree;
6744 * Returns a string containing a link to the user documentation for the current
6745 * page. Also contains an icon by default. Shown to teachers and admin only.
6747 * @param string $text The text to be displayed for the link
6748 * @param string $iconpath The path to the icon to be displayed
6750 function page_doc_link($text='', $iconpath='') {
6751 global $ME, $COURSE, $CFG;
6753 if (empty($CFG->docroot) or empty($CFG->rolesactive)) {
6754 return '';
6757 if (empty($COURSE->id)) {
6758 $context = get_context_instance(CONTEXT_SYSTEM);
6759 } else {
6760 $context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
6763 if (!has_capability('moodle/site:doclinks', $context)) {
6764 return '';
6767 if (empty($CFG->pagepath)) {
6768 $CFG->pagepath = $ME;
6771 $path = str_replace($CFG->httpswwwroot.'/','', $CFG->pagepath); // Because the page could be HTTPSPAGEREQUIRED
6772 $path = str_replace('.php', '', $path);
6774 if (empty($path)) { // Not for home page
6775 return '';
6777 return doc_link($path, $text, $iconpath);
6781 * Returns a string containing a link to the user documentation.
6782 * Also contains an icon by default. Shown to teachers and admin only.
6784 * @param string $path The page link after doc root and language, no
6785 * leading slash.
6786 * @param string $text The text to be displayed for the link
6787 * @param string $iconpath The path to the icon to be displayed
6789 function doc_link($path='', $text='', $iconpath='') {
6790 global $CFG;
6792 if (empty($CFG->docroot)) {
6793 return '';
6796 $target = '';
6797 if (!empty($CFG->doctonewwindow)) {
6798 $target = ' target="_blank"';
6801 $lang = str_replace('_utf8', '', current_language());
6803 $str = '<a href="' .$CFG->docroot. '/' .$lang. '/' .$path. '"' .$target. '>';
6805 if (empty($iconpath)) {
6806 $iconpath = $CFG->httpswwwroot . '/pix/docs.gif';
6809 // alt left blank intentionally to prevent repetition in screenreaders
6810 $str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
6812 return $str;
6817 * Returns true if the current site debugging settings are equal or above specified level.
6818 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
6819 * routing of notices is controlled by $CFG->debugdisplay
6820 * eg use like this:
6822 * 1) debugging('a normal debug notice');
6823 * 2) debugging('something really picky', DEBUG_ALL);
6824 * 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
6825 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
6827 * In code blocks controlled by debugging() (such as example 4)
6828 * any output should be routed via debugging() itself, or the lower-level
6829 * trigger_error() or error_log(). Using echo or print will break XHTML
6830 * JS and HTTP headers.
6833 * @param string $message a message to print
6834 * @param int $level the level at which this debugging statement should show
6835 * @return bool
6837 function debugging($message='', $level=DEBUG_NORMAL) {
6839 global $CFG;
6841 if (empty($CFG->debug)) {
6842 return false;
6845 if ($CFG->debug >= $level) {
6846 if ($message) {
6847 $callers = debug_backtrace();
6848 $from = '<ul style="text-align: left">';
6849 foreach ($callers as $caller) {
6850 if (!isset($caller['line'])) {
6851 $caller['line'] = '?'; // probably call_user_func()
6853 if (!isset($caller['file'])) {
6854 $caller['file'] = $CFG->dirroot.'/unknownfile'; // probably call_user_func()
6856 $from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
6857 if (isset($caller['function'])) {
6858 $from .= ': call to ';
6859 if (isset($caller['class'])) {
6860 $from .= $caller['class'] . $caller['type'];
6862 $from .= $caller['function'] . '()';
6864 $from .= '</li>';
6866 $from .= '</ul>';
6867 if (!isset($CFG->debugdisplay)) {
6868 $CFG->debugdisplay = ini_get('display_errors');
6870 if ($CFG->debugdisplay) {
6871 if (!defined('DEBUGGING_PRINTED')) {
6872 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
6874 notify($message . $from, 'notifytiny');
6875 } else {
6876 trigger_error($message . $from, E_USER_NOTICE);
6879 return true;
6881 return false;
6885 * Disable debug messages from debugging(), while keeping PHP error reporting level as is.
6887 function disable_debugging() {
6888 global $CFG;
6889 $CFG->debug = $CFG->debug | 0x80000000; // switch the sign bit in integer number ;-)
6894 * Returns string to add a frame attribute, if required
6896 function frametarget() {
6897 global $CFG;
6899 if (empty($CFG->framename) or ($CFG->framename == '_top')) {
6900 return '';
6901 } else {
6902 return ' target="'.$CFG->framename.'" ';
6907 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
6908 * pages that use bits from many different files in very confusing ways (e.g. blocks).
6909 * @usage print_location_comment(__FILE__, __LINE__);
6910 * @param string $file
6911 * @param integer $line
6912 * @param boolean $return Whether to return or print the comment
6913 * @return mixed Void unless true given as third parameter
6915 function print_location_comment($file, $line, $return = false)
6917 if ($return) {
6918 return "<!-- $file at line $line -->\n";
6919 } else {
6920 echo "<!-- $file at line $line -->\n";
6926 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
6927 * provide this function with the language strings for sortasc and sortdesc.
6928 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
6929 * @param string $direction 'up' or 'down'
6930 * @param string $strsort The language string used for the alt attribute of this image
6931 * @param bool $return Whether to print directly or return the html string
6932 * @return string HTML for the image
6934 * TODO See if this isn't already defined somewhere. If not, move this to weblib
6936 function print_arrow($direction='up', $strsort=null, $return=false) {
6937 global $CFG;
6939 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
6940 return null;
6943 $return = null;
6945 switch ($direction) {
6946 case 'up':
6947 $sortdir = 'asc';
6948 break;
6949 case 'down':
6950 $sortdir = 'desc';
6951 break;
6952 case 'move':
6953 $sortdir = 'asc';
6954 break;
6955 default:
6956 $sortdir = null;
6957 break;
6960 // Prepare language string
6961 $strsort = '';
6962 if (empty($strsort) && !empty($sortdir)) {
6963 $strsort = get_string('sort' . $sortdir, 'grades');
6966 $return = ' <img src="'.$CFG->pixpath.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
6968 if ($return) {
6969 return $return;
6970 } else {
6971 echo $return;
6976 * Returns boolean true if the current language is right-to-left (Hebrew, Arabic etc)
6979 function right_to_left() {
6980 static $result;
6982 if (isset($result)) {
6983 return $result;
6985 return $result = (get_string('thisdirection') == 'rtl');
6990 * Returns swapped left<=>right if in RTL environment.
6991 * part of RTL support
6993 * @param string $align align to check
6994 * @return string
6996 function fix_align_rtl($align) {
6997 if (!right_to_left()) {
6998 return $align;
7000 if ($align=='left') { return 'right'; }
7001 if ($align=='right') { return 'left'; }
7002 return $align;
7007 * Returns true if the page is displayed in a popup window.
7008 * Gets the information from the URL parameter inpopup.
7010 * @return boolean
7012 * TODO Use a central function to create the popup calls allover Moodle and
7013 * TODO In the moment only works with resources and probably questions.
7015 function is_in_popup() {
7016 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
7018 return ($inpopup);
7022 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: