"MDL-12304, fix double text"
[moodle-linuxchix.git] / lib / weblib.php
blob425f59b980c52b85c852dc2910e983a6cb816255
1 <?php // $Id$
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.com //
9 // //
10 // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
11 // //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
16 // //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
21 // //
22 // http://www.gnu.org/copyleft/gpl.html //
23 // //
24 ///////////////////////////////////////////////////////////////////////////
26 /**
27 * Library of functions for web output
29 * Library of all general-purpose Moodle PHP functions and constants
30 * that produce HTML output
32 * Other main libraries:
33 * - datalib.php - functions that access the database.
34 * - moodlelib.php - general-purpose Moodle functions.
35 * @author Martin Dougiamas
36 * @version $Id$
37 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
38 * @package moodlecore
41 /// We are going to uses filterlib functions here
42 require_once("$CFG->libdir/filterlib.php");
44 require_once("$CFG->libdir/ajax/ajaxlib.php");
46 /// Constants
48 /// Define text formatting types ... eventually we can add Wiki, BBcode etc
50 /**
51 * Does all sorts of transformations and filtering
53 define('FORMAT_MOODLE', '0'); // Does all sorts of transformations and filtering
55 /**
56 * Plain HTML (with some tags stripped)
58 define('FORMAT_HTML', '1'); // Plain HTML (with some tags stripped)
60 /**
61 * Plain text (even tags are printed in full)
63 define('FORMAT_PLAIN', '2'); // Plain text (even tags are printed in full)
65 /**
66 * Wiki-formatted text
67 * Deprecated: left here just to note that '3' is not used (at the moment)
68 * and to catch any latent wiki-like text (which generates an error)
70 define('FORMAT_WIKI', '3'); // Wiki-formatted text
72 /**
73 * Markdown-formatted text http://daringfireball.net/projects/markdown/
75 define('FORMAT_MARKDOWN', '4'); // Markdown-formatted text http://daringfireball.net/projects/markdown/
77 /**
78 * TRUSTTEXT marker - if present in text, text cleaning should be bypassed
80 define('TRUSTTEXT', '#####TRUSTTEXT#####');
83 /**
84 * Javascript related defines
86 define('REQUIREJS_BEFOREHEADER', 0);
87 define('REQUIREJS_INHEADER', 1);
88 define('REQUIREJS_AFTERHEADER', 2);
90 /**
91 * Allowed tags - string of html tags that can be tested against for safe html tags
92 * @global string $ALLOWED_TAGS
94 global $ALLOWED_TAGS;
95 $ALLOWED_TAGS =
96 '<p><br><b><i><u><font><table><tbody><span><div><tr><td><th><ol><ul><dl><li><dt><dd><h1><h2><h3><h4><h5><h6><hr><img><a><strong><emphasis><em><sup><sub><address><cite><blockquote><pre><strike><param><acronym><nolink><lang><tex><algebra><math><mi><mn><mo><mtext><mspace><ms><mrow><mfrac><msqrt><mroot><mstyle><merror><mpadded><mphantom><mfenced><msub><msup><msubsup><munder><mover><munderover><mmultiscripts><mtable><mtr><mtd><maligngroup><malignmark><maction><cn><ci><apply><reln><fn><interval><inverse><sep><condition><declare><lambda><compose><ident><quotient><exp><factorial><divide><max><min><minus><plus><power><rem><times><root><gcd><and><or><xor><not><implies><forall><exists><abs><conjugate><eq><neq><gt><lt><geq><leq><ln><log><int><diff><partialdiff><lowlimit><uplimit><bvar><degree><set><list><union><intersect><in><notin><subset><prsubset><notsubset><notprsubset><setdiff><sum><product><limit><tendsto><mean><sdev><variance><median><mode><moment><vector><matrix><matrixrow><determinant><transpose><selector><annotation><semantics><annotation-xml><tt><code>';
98 /**
99 * Allowed protocols - array of protocols that are safe to use in links and so on
100 * @global string $ALLOWED_PROTOCOLS
102 $ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms',
103 'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style',
104 'border', 'margin', 'padding', 'background', 'text-decoration'); // CSS as well to get through kses
107 /// Functions
110 * Add quotes to HTML characters
112 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
113 * This function is very similar to {@link p()}
115 * @param string $var the string potentially containing HTML characters
116 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
117 * true should be used to print data from forms and false for data from DB.
118 * @return string
120 function s($var, $strip=false) {
122 if ($var == '0') { // for integer 0, boolean false, string '0'
123 return '0';
126 if ($strip) {
127 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars(stripslashes_safe($var)));
128 } else {
129 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars($var));
134 * Add quotes to HTML characters
136 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
137 * This function is very similar to {@link s()}
139 * @param string $var the string potentially containing HTML characters
140 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
141 * true should be used to print data from forms and false for data from DB.
142 * @return string
144 function p($var, $strip=false) {
145 echo s($var, $strip);
149 * Does proper javascript quoting.
150 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
152 * @since 1.8 - 22/02/2007
153 * @param mixed value
154 * @return mixed quoted result
156 function addslashes_js($var) {
157 if (is_string($var)) {
158 $var = str_replace('\\', '\\\\', $var);
159 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
160 $var = str_replace('</', '<\/', $var); // XHTML compliance
161 } else if (is_array($var)) {
162 $var = array_map('addslashes_js', $var);
163 } else if (is_object($var)) {
164 $a = get_object_vars($var);
165 foreach ($a as $key=>$value) {
166 $a[$key] = addslashes_js($value);
168 $var = (object)$a;
170 return $var;
174 * Remove query string from url
176 * Takes in a URL and returns it without the querystring portion
178 * @param string $url the url which may have a query string attached
179 * @return string
181 function strip_querystring($url) {
183 if ($commapos = strpos($url, '?')) {
184 return substr($url, 0, $commapos);
185 } else {
186 return $url;
191 * Returns the URL of the HTTP_REFERER, less the querystring portion if required
192 * @param boolean $stripquery if true, also removes the query part of the url.
193 * @return string
195 function get_referer($stripquery=true) {
196 if (isset($_SERVER['HTTP_REFERER'])) {
197 if ($stripquery) {
198 return strip_querystring($_SERVER['HTTP_REFERER']);
199 } else {
200 return $_SERVER['HTTP_REFERER'];
202 } else {
203 return '';
209 * Returns the name of the current script, WITH the querystring portion.
210 * this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
211 * return different things depending on a lot of things like your OS, Web
212 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
213 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
215 * @return string
217 function me() {
219 if (!empty($_SERVER['REQUEST_URI'])) {
220 return $_SERVER['REQUEST_URI'];
222 } else if (!empty($_SERVER['PHP_SELF'])) {
223 if (!empty($_SERVER['QUERY_STRING'])) {
224 return $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
226 return $_SERVER['PHP_SELF'];
228 } else if (!empty($_SERVER['SCRIPT_NAME'])) {
229 if (!empty($_SERVER['QUERY_STRING'])) {
230 return $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
232 return $_SERVER['SCRIPT_NAME'];
234 } else if (!empty($_SERVER['URL'])) { // May help IIS (not well tested)
235 if (!empty($_SERVER['QUERY_STRING'])) {
236 return $_SERVER['URL'] .'?'. $_SERVER['QUERY_STRING'];
238 return $_SERVER['URL'];
240 } else {
241 notify('Warning: Could not find any of these web server variables: $REQUEST_URI, $PHP_SELF, $SCRIPT_NAME or $URL');
242 return false;
247 * Like {@link me()} but returns a full URL
248 * @see me()
249 * @return string
251 function qualified_me() {
253 global $CFG;
255 if (!empty($CFG->wwwroot)) {
256 $url = parse_url($CFG->wwwroot);
259 if (!empty($url['host'])) {
260 $hostname = $url['host'];
261 } else if (!empty($_SERVER['SERVER_NAME'])) {
262 $hostname = $_SERVER['SERVER_NAME'];
263 } else if (!empty($_ENV['SERVER_NAME'])) {
264 $hostname = $_ENV['SERVER_NAME'];
265 } else if (!empty($_SERVER['HTTP_HOST'])) {
266 $hostname = $_SERVER['HTTP_HOST'];
267 } else if (!empty($_ENV['HTTP_HOST'])) {
268 $hostname = $_ENV['HTTP_HOST'];
269 } else {
270 notify('Warning: could not find the name of this server!');
271 return false;
274 if (!empty($url['port'])) {
275 $hostname .= ':'.$url['port'];
276 } else if (!empty($_SERVER['SERVER_PORT'])) {
277 if ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
278 $hostname .= ':'.$_SERVER['SERVER_PORT'];
282 // TODO, this does not work in the situation described in MDL-11061, but
283 // I don't know how to fix it. Possibly believe $CFG->wwwroot ahead of what
284 // the server reports.
285 if (isset($_SERVER['HTTPS'])) {
286 $protocol = ($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
287 } else if (isset($_SERVER['SERVER_PORT'])) { # Apache2 does not export $_SERVER['HTTPS']
288 $protocol = ($_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
289 } else {
290 $protocol = 'http://';
293 $url_prefix = $protocol.$hostname;
294 return $url_prefix . me();
299 * Class for creating and manipulating urls.
301 * See short write up here http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url
303 class moodle_url {
304 var $scheme = '';// e.g. http
305 var $host = '';
306 var $port = '';
307 var $user = '';
308 var $pass = '';
309 var $path = '';
310 var $fragment = '';
311 var $params = array(); //associative array of query string params
314 * Pass no arguments to create a url that refers to this page. Use empty string to create empty url.
316 * @param string $url url default null means use this page url with no query string
317 * empty string means empty url.
318 * if you pass any other type of url it will be parsed into it's bits, including query string
319 * @param array $params these params override anything in the query string where params have the same name.
321 function moodle_url($url = null, $params = array()){
322 global $FULLME;
323 if ($url !== ''){
324 if ($url === null){
325 $url = strip_querystring($FULLME);
327 $parts = parse_url($url);
328 if ($parts === FALSE){
329 error('invalidurl');
331 if (isset($parts['query'])){
332 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
334 unset($parts['query']);
335 foreach ($parts as $key => $value){
336 $this->$key = $value;
338 $this->params($params);
342 * Add an array of params to the params for this page. The added params override existing ones if they
343 * have the same name.
345 * @param array $params
347 function params($params){
348 $this->params = $params + $this->params;
352 * Remove all params if no arguments passed. Or else remove param $arg1, $arg2, etc.
354 * @param string $arg1
355 * @param string $arg2
356 * @param string $arg3
358 function remove_params(){
359 if ($thisargs = func_get_args()){
360 foreach ($thisargs as $arg){
361 if (isset($this->params[$arg])){
362 unset($this->params[$arg]);
365 } else { // no args
366 $this->params = array();
371 * Add a param to the params for this page. The added param overrides existing one if they
372 * have the same name.
374 * @param string $paramname name
375 * @param string $param value
377 function param($paramname, $param){
378 $this->params = array($paramname => $param) + $this->params;
382 function get_query_string($overrideparams = array()){
383 $arr = array();
384 $params = $overrideparams + $this->params;
385 foreach ($params as $key => $val){
386 $arr[] = urlencode($key)."=".urlencode($val);
388 return implode($arr, "&amp;");
391 * Outputs params as hidden form elements.
393 * @param array $exclude params to ignore
394 * @param integer $indent indentation
395 * @param array $overrideparams params to add to the output params, these
396 * override existing ones with the same name.
397 * @return string html for form elements.
399 function hidden_params_out($exclude = array(), $indent = 0, $overrideparams=array()){
400 $tabindent = str_repeat("\t", $indent);
401 $str = '';
402 $params = $overrideparams + $this->params;
403 foreach ($params as $key => $val){
404 if (FALSE === array_search($key, $exclude)) {
405 $val = s($val);
406 $str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
409 return $str;
412 * Output url
414 * @param boolean $noquerystring whether to output page params as a query string in the url.
415 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
416 * @return string url
418 function out($noquerystring = false, $overrideparams = array()) {
419 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
420 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
421 $uri .= $this->host ? $this->host : '';
422 $uri .= $this->port ? ':'.$this->port : '';
423 $uri .= $this->path ? $this->path : '';
424 if (!$noquerystring){
425 $uri .= (count($this->params)||count($overrideparams)) ? '?'.$this->get_query_string($overrideparams) : '';
427 $uri .= $this->fragment ? '#'.$this->fragment : '';
428 return $uri;
431 * Output action url with sesskey
433 * @param boolean $noquerystring whether to output page params as a query string in the url.
434 * @return string url
436 function out_action($overrideparams = array()) {
437 $overrideparams = array('sesskey'=> sesskey()) + $overrideparams;
438 return $this->out(false, $overrideparams);
443 * Determine if there is data waiting to be processed from a form
445 * Used on most forms in Moodle to check for data
446 * Returns the data as an object, if it's found.
447 * This object can be used in foreach loops without
448 * casting because it's cast to (array) automatically
450 * Checks that submitted POST data exists and returns it as object.
452 * @param string $url not used anymore
453 * @return mixed false or object
455 function data_submitted($url='') {
457 if (empty($_POST)) {
458 return false;
459 } else {
460 return (object)$_POST;
465 * Moodle replacement for php stripslashes() function,
466 * works also for objects and arrays.
468 * The standard php stripslashes() removes ALL backslashes
469 * even from strings - so C:\temp becomes C:temp - this isn't good.
470 * This function should work as a fairly safe replacement
471 * to be called on quoted AND unquoted strings (to be sure)
473 * @param mixed something to remove unsafe slashes from
474 * @return mixed
476 function stripslashes_safe($mixed) {
477 // there is no need to remove slashes from int, float and bool types
478 if (empty($mixed)) {
479 //nothing to do...
480 } else if (is_string($mixed)) {
481 if (ini_get_bool('magic_quotes_sybase')) { //only unescape single quotes
482 $mixed = str_replace("''", "'", $mixed);
483 } else { //the rest, simple and double quotes and backslashes
484 $mixed = str_replace("\\'", "'", $mixed);
485 $mixed = str_replace('\\"', '"', $mixed);
486 $mixed = str_replace('\\\\', '\\', $mixed);
488 } else if (is_array($mixed)) {
489 foreach ($mixed as $key => $value) {
490 $mixed[$key] = stripslashes_safe($value);
492 } else if (is_object($mixed)) {
493 $vars = get_object_vars($mixed);
494 foreach ($vars as $key => $value) {
495 $mixed->$key = stripslashes_safe($value);
499 return $mixed;
503 * Recursive implementation of stripslashes()
505 * This function will allow you to strip the slashes from a variable.
506 * If the variable is an array or object, slashes will be stripped
507 * from the items (or properties) it contains, even if they are arrays
508 * or objects themselves.
510 * @param mixed the variable to remove slashes from
511 * @return mixed
513 function stripslashes_recursive($var) {
514 if (is_object($var)) {
515 $new_var = new object();
516 $properties = get_object_vars($var);
517 foreach($properties as $property => $value) {
518 $new_var->$property = stripslashes_recursive($value);
521 } else if(is_array($var)) {
522 $new_var = array();
523 foreach($var as $property => $value) {
524 $new_var[$property] = stripslashes_recursive($value);
527 } else if(is_string($var)) {
528 $new_var = stripslashes($var);
530 } else {
531 $new_var = $var;
534 return $new_var;
538 * Recursive implementation of addslashes()
540 * This function will allow you to add the slashes from a variable.
541 * If the variable is an array or object, slashes will be added
542 * to the items (or properties) it contains, even if they are arrays
543 * or objects themselves.
545 * @param mixed the variable to add slashes from
546 * @return mixed
548 function addslashes_recursive($var) {
549 if (is_object($var)) {
550 $new_var = new object();
551 $properties = get_object_vars($var);
552 foreach($properties as $property => $value) {
553 $new_var->$property = addslashes_recursive($value);
556 } else if (is_array($var)) {
557 $new_var = array();
558 foreach($var as $property => $value) {
559 $new_var[$property] = addslashes_recursive($value);
562 } else if (is_string($var)) {
563 $new_var = addslashes($var);
565 } else { // nulls, integers, etc.
566 $new_var = $var;
569 return $new_var;
573 * Given some normal text this function will break up any
574 * long words to a given size by inserting the given character
576 * It's multibyte savvy and doesn't change anything inside html tags.
578 * @param string $string the string to be modified
579 * @param int $maxsize maximum length of the string to be returned
580 * @param string $cutchar the string used to represent word breaks
581 * @return string
583 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
585 /// Loading the textlib singleton instance. We are going to need it.
586 $textlib = textlib_get_instance();
588 /// First of all, save all the tags inside the text to skip them
589 $tags = array();
590 filter_save_tags($string,$tags);
592 /// Process the string adding the cut when necessary
593 $output = '';
594 $length = $textlib->strlen($string);
595 $wordlength = 0;
597 for ($i=0; $i<$length; $i++) {
598 $char = $textlib->substr($string, $i, 1);
599 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
600 $wordlength = 0;
601 } else {
602 $wordlength++;
603 if ($wordlength > $maxsize) {
604 $output .= $cutchar;
605 $wordlength = 0;
608 $output .= $char;
611 /// Finally load the tags back again
612 if (!empty($tags)) {
613 $output = str_replace(array_keys($tags), $tags, $output);
616 return $output;
620 * This does a search and replace, ignoring case
621 * This function is only used for versions of PHP older than version 5
622 * which do not have a native version of this function.
623 * Taken from the PHP manual, by bradhuizenga @ softhome.net
625 * @param string $find the string to search for
626 * @param string $replace the string to replace $find with
627 * @param string $string the string to search through
628 * return string
630 if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
631 function str_ireplace($find, $replace, $string) {
633 if (!is_array($find)) {
634 $find = array($find);
637 if(!is_array($replace)) {
638 if (!is_array($find)) {
639 $replace = array($replace);
640 } else {
641 // this will duplicate the string into an array the size of $find
642 $c = count($find);
643 $rString = $replace;
644 unset($replace);
645 for ($i = 0; $i < $c; $i++) {
646 $replace[$i] = $rString;
651 foreach ($find as $fKey => $fItem) {
652 $between = explode(strtolower($fItem),strtolower($string));
653 $pos = 0;
654 foreach($between as $bKey => $bItem) {
655 $between[$bKey] = substr($string,$pos,strlen($bItem));
656 $pos += strlen($bItem) + strlen($fItem);
658 $string = implode($replace[$fKey],$between);
660 return ($string);
665 * Locate the position of a string in another string
667 * This function is only used for versions of PHP older than version 5
668 * which do not have a native version of this function.
669 * Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
671 * @param string $haystack The string to be searched
672 * @param string $needle The string to search for
673 * @param int $offset The position in $haystack where the search should begin.
675 if (!function_exists('stripos')) { /// Only exists in PHP 5
676 function stripos($haystack, $needle, $offset=0) {
678 return strpos(strtoupper($haystack), strtoupper($needle), $offset);
683 * This function will print a button/link/etc. form element
684 * that will work on both Javascript and non-javascript browsers.
685 * Relies on the Javascript function openpopup in javascript.php
687 * All parameters default to null, only $type and $url are mandatory.
689 * $url must be relative to home page eg /mod/survey/stuff.php
690 * @param string $url Web link relative to home page
691 * @param string $name Name to be assigned to the popup window (this is used by
692 * client-side scripts to "talk" to the popup window)
693 * @param string $linkname Text to be displayed as web link
694 * @param int $height Height to assign to popup window
695 * @param int $width Height to assign to popup window
696 * @param string $title Text to be displayed as popup page title
697 * @param string $options List of additional options for popup window
698 * @param string $return If true, return as a string, otherwise print
699 * @param string $id id added to the element
700 * @param string $class class added to the element
701 * @return string
702 * @uses $CFG
704 function element_to_popup_window ($type=null, $url=null, $name=null, $linkname=null,
705 $height=400, $width=500, $title=null,
706 $options=null, $return=false, $id=null, $class=null) {
708 if (is_null($url)) {
709 debugging('You must give the url to display in the popup. URL is missing - can\'t create popup window.', DEBUG_DEVELOPER);
712 global $CFG;
714 if ($options == 'none') { // 'none' is legacy, should be removed in v2.0
715 $options = null;
718 // add some sane default options for popup windows
719 if (!$options) {
720 $options = 'menubar=0,location=0,scrollbars,resizable';
722 if ($width) {
723 $options .= ',width='. $width;
725 if ($height) {
726 $options .= ',height='. $height;
728 if ($id) {
729 $id = ' id="'.$id.'" ';
731 if ($class) {
732 $class = ' class="'.$class.'" ';
734 if ($name) {
735 $_name = $name;
736 if (($name = preg_replace("/\s/", '_', $name)) != $_name) {
737 debugging('The $name of a popup window shouldn\'t contain spaces - string modified. '. $_name .' changed to '. $name, DEBUG_DEVELOPER);
739 } else {
740 $name = 'popup';
743 // get some default string, using the localized version of legacy defaults
744 if (is_null($linkname) || $linkname === '') {
745 $linkname = get_string('clickhere');
747 if (!$title) {
748 $title = get_string('popupwindowname');
751 $fullscreen = 0; // must be passed to openpopup
752 $element = '';
754 switch ($type) {
755 case 'button' :
756 $element = '<input type="button" name="'. $name .'" title="'. $title .'" value="'. $linkname .'" '. $id . $class .
757 "onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
758 break;
759 case 'link' :
760 // some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
761 if (!(strpos($url,$CFG->wwwroot) === false)) {
762 $url = substr($url, strlen($CFG->wwwroot));
764 $element = '<a title="'. s(strip_tags($title)) .'" href="'. $CFG->wwwroot . $url .'" '.
765 "onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
766 break;
767 default :
768 error('Undefined element - can\'t create popup window.');
769 break;
772 if ($return) {
773 return $element;
774 } else {
775 echo $element;
780 * Creates and displays (or returns) a link to a popup window, using element_to_popup_window function.
782 * @return string html code to display a link to a popup window.
783 * @see element_to_popup_window()
785 function link_to_popup_window ($url, $name=null, $linkname=null,
786 $height=400, $width=500, $title=null,
787 $options=null, $return=false) {
789 return element_to_popup_window('link', $url, $name, $linkname, $height, $width, $title, $options, $return, null, null);
793 * Creates and displays (or returns) a buttons to a popup window, using element_to_popup_window function.
795 * @return string html code to display a button to a popup window.
796 * @see element_to_popup_window()
798 function button_to_popup_window ($url, $name=null, $linkname=null,
799 $height=400, $width=500, $title=null, $options=null, $return=false,
800 $id=null, $class=null) {
802 return element_to_popup_window('button', $url, $name, $linkname, $height, $width, $title, $options, $return, $id, $class);
807 * Prints a simple button to close a window
808 * @param string $name name of the window to close
809 * @param boolean $return whether this function should return a string or output it
810 * @return string if $return is true, nothing otherwise
812 function close_window_button($name='closewindow', $return=false) {
813 global $CFG;
815 $output = '';
817 $output .= '<div class="closewindow">' . "\n";
818 $output .= '<form action="#"><div>';
819 $output .= '<input type="button" onclick="self.close();" value="'.get_string($name).'" />';
820 $output .= '</div></form>';
821 $output .= '</div>' . "\n";
823 if ($return) {
824 return $output;
825 } else {
826 echo $output;
831 * Try and close the current window immediately using Javascript
832 * @param int $delay the delay in seconds before closing the window
834 function close_window($delay=0) {
836 <script type="text/javascript">
837 //<![CDATA[
838 function close_this_window() {
839 self.close();
841 setTimeout("close_this_window()", <?php echo $delay * 1000 ?>);
842 //]]>
843 </script>
844 <noscript><center>
845 <?php print_string('pleaseclose') ?>
846 </center></noscript>
847 <?php
848 die;
853 * Given an array of values, output the HTML for a select element with those options.
854 * Normally, you only need to use the first few parameters.
856 * @param array $options The options to offer. An array of the form
857 * $options[{value}] = {text displayed for that option};
858 * @param string $name the name of this form control, as in &lt;select name="..." ...
859 * @param string $selected the option to select initially, default none.
860 * @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
861 * Set this to '' if you don't want a 'nothing is selected' option.
862 * @param string $script in not '', then this is added to the &lt;select> element as an onchange handler.
863 * @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
864 * @param boolean $return if false (the default) the the output is printed directly, If true, the
865 * generated HTML is returned as a string.
866 * @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
867 * @param int $tabindex if give, sets the tabindex attribute on the &lt;select> element. Default none.
868 * @param string $id value to use for the id attribute of the &lt;select> element. If none is given,
869 * then a suitable one is constructed.
871 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
872 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0, $id='') {
874 if ($nothing == 'choose') {
875 $nothing = get_string('choose') .'...';
878 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
879 if ($disabled) {
880 $attributes .= ' disabled="disabled"';
883 if ($tabindex) {
884 $attributes .= ' tabindex="'.$tabindex.'"';
887 if ($id ==='') {
888 $id = 'menu'.$name;
889 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
890 $id = str_replace('[', '', $id);
891 $id = str_replace(']', '', $id);
894 $output = '<select id="'.$id.'" name="'. $name .'" '. $attributes .'>' . "\n";
895 if ($nothing) {
896 $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
897 if ($nothingvalue === $selected) {
898 $output .= ' selected="selected"';
900 $output .= '>'. $nothing .'</option>' . "\n";
902 if (!empty($options)) {
903 foreach ($options as $value => $label) {
904 $output .= ' <option value="'. s($value) .'"';
905 if ((string)$value == (string)$selected) {
906 $output .= ' selected="selected"';
908 if ($label === '') {
909 $output .= '>'. $value .'</option>' . "\n";
910 } else {
911 $output .= '>'. $label .'</option>' . "\n";
915 $output .= '</select>' . "\n";
917 if ($return) {
918 return $output;
919 } else {
920 echo $output;
925 * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
926 * Other options like choose_from_menu.
927 * @param string $name
928 * @param string $selected
929 * @param string $string (defaults to '')
930 * @param boolean $return whether this function should return a string or output it (defaults to false)
931 * @param boolean $disabled (defaults to false)
932 * @param int $tabindex
934 function choose_from_menu_yesno($name, $selected, $script = '',
935 $return = false, $disabled = false, $tabindex = 0) {
936 return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
937 $selected, '', $script, '0', $return, $disabled, $tabindex);
941 * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
942 * including option headings with the first level.
944 function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
945 $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
947 if ($nothing == 'choose') {
948 $nothing = get_string('choose') .'...';
951 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
952 if ($disabled) {
953 $attributes .= ' disabled="disabled"';
956 if ($tabindex) {
957 $attributes .= ' tabindex="'.$tabindex.'"';
960 $output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
961 if ($nothing) {
962 $output .= ' <option value="'. $nothingvalue .'"'. "\n";
963 if ($nothingvalue === $selected) {
964 $output .= ' selected="selected"';
966 $output .= '>'. $nothing .'</option>' . "\n";
968 if (!empty($options)) {
969 foreach ($options as $section => $values) {
971 $output .= ' <optgroup label="'. s(format_string($section)) .'">'."\n";
972 foreach ($values as $value => $label) {
973 $output .= ' <option value="'. format_string($value) .'"';
974 if ((string)$value == (string)$selected) {
975 $output .= ' selected="selected"';
977 if ($label === '') {
978 $output .= '>'. $value .'</option>' . "\n";
979 } else {
980 $output .= '>'. $label .'</option>' . "\n";
983 $output .= ' </optgroup>'."\n";
986 $output .= '</select>' . "\n";
988 if ($return) {
989 return $output;
990 } else {
991 echo $output;
997 * Given an array of values, creates a group of radio buttons to be part of a form
999 * @param array $options An array of value-label pairs for the radio group (values as keys)
1000 * @param string $name Name of the radiogroup (unique in the form)
1001 * @param string $checked The value that is already checked
1003 function choose_from_radio ($options, $name, $checked='', $return=false) {
1005 static $idcounter = 0;
1007 if (!$name) {
1008 $name = 'unnamed';
1011 $output = '<span class="radiogroup '.$name."\">\n";
1013 if (!empty($options)) {
1014 $currentradio = 0;
1015 foreach ($options as $value => $label) {
1016 $htmlid = 'auto-rb'.sprintf('%04d', ++$idcounter);
1017 $output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
1018 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
1019 if ($value == $checked) {
1020 $output .= ' checked="checked"';
1022 if ($label === '') {
1023 $output .= ' /> <label for="'.$htmlid.'">'. $value .'</label></span>' . "\n";
1024 } else {
1025 $output .= ' /> <label for="'.$htmlid.'">'. $label .'</label></span>' . "\n";
1027 $currentradio = ($currentradio + 1) % 2;
1031 $output .= '</span>' . "\n";
1033 if ($return) {
1034 return $output;
1035 } else {
1036 echo $output;
1040 /** Display an standard html checkbox with an optional label
1042 * @param string $name The name of the checkbox
1043 * @param string $value The valus that the checkbox will pass when checked
1044 * @param boolean $checked The flag to tell the checkbox initial state
1045 * @param string $label The label to be showed near the checkbox
1046 * @param string $alt The info to be inserted in the alt tag
1048 function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
1050 static $idcounter = 0;
1052 if (!$name) {
1053 $name = 'unnamed';
1056 if ($alt) {
1057 $alt = strip_tags($alt);
1058 } else {
1059 $alt = 'checkbox';
1062 if ($checked) {
1063 $strchecked = ' checked="checked"';
1064 } else {
1065 $strchecked = '';
1068 $htmlid = 'auto-cb'.sprintf('%04d', ++$idcounter);
1069 $output = '<span class="checkbox '.$name."\">";
1070 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ? ' onclick="'.$script.'" ' : '').' />';
1071 if(!empty($label)) {
1072 $output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
1074 $output .= '</span>'."\n";
1076 if (empty($return)) {
1077 echo $output;
1078 } else {
1079 return $output;
1084 /** Display an standard html text field with an optional label
1086 * @param string $name The name of the text field
1087 * @param string $value The value of the text field
1088 * @param string $label The label to be showed near the text field
1089 * @param string $alt The info to be inserted in the alt tag
1091 function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
1093 static $idcounter = 0;
1095 if (empty($name)) {
1096 $name = 'unnamed';
1099 if (empty($alt)) {
1100 $alt = 'textfield';
1103 if (!empty($maxlength)) {
1104 $maxlength = ' maxlength="'.$maxlength.'" ';
1107 $htmlid = 'auto-tf'.sprintf('%04d', ++$idcounter);
1108 $output = '<span class="textfield '.$name."\">";
1109 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
1111 $output .= '</span>'."\n";
1113 if (empty($return)) {
1114 echo $output;
1115 } else {
1116 return $output;
1123 * Implements a complete little popup form
1125 * @uses $CFG
1126 * @param string $common The URL up to the point of the variable that changes
1127 * @param array $options Alist of value-label pairs for the popup list
1128 * @param string $formid Id must be unique on the page (originaly $formname)
1129 * @param string $selected The option that is already selected
1130 * @param string $nothing The label for the "no choice" option
1131 * @param string $help The name of a help page if help is required
1132 * @param string $helptext The name of the label for the help button
1133 * @param boolean $return Indicates whether the function should return the text
1134 * as a string or echo it directly to the page being rendered
1135 * @param string $targetwindow The name of the target page to open the linked page in.
1136 * @param string $selectlabel Text to place in a [label] element - preferred for accessibility.
1137 * @param array $optionsextra TODO, an array?
1138 * @return string If $return is true then the entire form is returned as a string.
1139 * @todo Finish documenting this function<br>
1141 function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
1142 $targetwindow='self', $selectlabel='', $optionsextra=NULL) {
1144 global $CFG;
1145 static $go, $choose; /// Locally cached, in case there's lots on a page
1147 if (empty($options)) {
1148 return '';
1151 if (!isset($go)) {
1152 $go = get_string('go');
1155 if ($nothing == 'choose') {
1156 if (!isset($choose)) {
1157 $choose = get_string('choose');
1159 $nothing = $choose.'...';
1162 // changed reference to document.getElementById('id_abc') instead of document.abc
1163 // MDL-7861
1164 $output = '<form action="'.$CFG->wwwroot.'/course/jumpto.php"'.
1165 ' method="get" '.
1166 $CFG->frametarget.
1167 ' id="'.$formid.'"'.
1168 ' class="popupform">';
1169 if ($help) {
1170 $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
1171 } else {
1172 $button = '';
1175 if ($selectlabel) {
1176 $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
1179 //IE and Opera fire the onchange when ever you move into a dropdwown list with the keyboard.
1180 //onfocus will call a function inside dropdown.js. It fixes this IE/Opera behavior.
1181 if (check_browser_version('MSIE') || check_browser_version('Opera')) {
1182 $output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" onfocus="initSelect(\''.$formid.'\','.$targetwindow.')" name="jump">'."\n";
1184 //Other browser
1185 else {
1186 $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";
1189 if ($nothing != '') {
1190 $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
1193 $inoptgroup = false;
1195 foreach ($options as $value => $label) {
1197 if ($label == '--') { /// we are ending previous optgroup
1198 /// Check to see if we already have a valid open optgroup
1199 /// XHTML demands that there be at least 1 option within an optgroup
1200 if ($inoptgroup and (count($optgr) > 1) ) {
1201 $output .= implode('', $optgr);
1202 $output .= ' </optgroup>';
1204 $optgr = array();
1205 $inoptgroup = false;
1206 continue;
1207 } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
1209 /// Check to see if we already have a valid open optgroup
1210 /// XHTML demands that there be at least 1 option within an optgroup
1211 if ($inoptgroup and (count($optgr) > 1) ) {
1212 $output .= implode('', $optgr);
1213 $output .= ' </optgroup>';
1216 unset($optgr);
1217 $optgr = array();
1219 $optgr[] = ' <optgroup label="'. s(format_string(substr($label,2))) .'">'; // Plain labels
1221 $inoptgroup = true; /// everything following will be in an optgroup
1222 continue;
1224 } else {
1225 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()]))
1227 $url=sid_process_url( $common . $value );
1228 } else
1230 $url=$common . $value;
1232 $optstr = ' <option value="' . $url . '"';
1234 if ($value == $selected) {
1235 $optstr .= ' selected="selected"';
1238 if (!empty($optionsextra[$value])) {
1239 $optstr .= ' '.$optionsextra[$value];
1242 if ($label) {
1243 $optstr .= '>'. $label .'</option>' . "\n";
1244 } else {
1245 $optstr .= '>'. $value .'</option>' . "\n";
1248 if ($inoptgroup) {
1249 $optgr[] = $optstr;
1250 } else {
1251 $output .= $optstr;
1257 /// catch the final group if not closed
1258 if ($inoptgroup and count($optgr) > 1) {
1259 $output .= implode('', $optgr);
1260 $output .= ' </optgroup>';
1263 $output .= '</select>';
1264 $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1265 $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
1266 $output .= '<input type="submit" value="'.$go.'" /></div>';
1267 $output .= '<script type="text/javascript">'.
1268 "\n//<![CDATA[\n".
1269 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
1270 "\n//]]>\n".'</script>';
1271 $output .= '</div>';
1272 $output .= '</form>';
1274 if ($return) {
1275 return $output;
1276 } else {
1277 echo $output;
1283 * Prints some red text
1285 * @param string $error The text to be displayed in red
1287 function formerr($error) {
1289 if (!empty($error)) {
1290 echo '<span class="error">'. $error .'</span>';
1295 * Validates an email to make sure it makes sense.
1297 * @param string $address The email address to validate.
1298 * @return boolean
1300 function validate_email($address) {
1302 return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1303 '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1304 '@'.
1305 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1306 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
1307 $address));
1311 * Extracts file argument either from file parameter or PATH_INFO
1313 * @param string $scriptname name of the calling script
1314 * @return string file path (only safe characters)
1316 function get_file_argument($scriptname) {
1317 global $_SERVER;
1319 $relativepath = FALSE;
1321 // first try normal parameter (compatible method == no relative links!)
1322 $relativepath = optional_param('file', FALSE, PARAM_PATH);
1323 if ($relativepath === '/testslasharguments') {
1324 echo 'test -1 : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
1325 die;
1328 // then try extract file from PATH_INFO (slasharguments method)
1329 if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
1330 $path_info = $_SERVER['PATH_INFO'];
1331 // check that PATH_INFO works == must not contain the script name
1332 if (!strpos($path_info, $scriptname)) {
1333 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1334 if ($relativepath === '/testslasharguments') {
1335 echo 'test 1 : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
1336 die;
1341 // now if both fail try the old way
1342 // (for compatibility with misconfigured or older buggy php implementations)
1343 if (!$relativepath) {
1344 $arr = explode($scriptname, me());
1345 if (!empty($arr[1])) {
1346 $path_info = strip_querystring($arr[1]);
1347 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1348 if ($relativepath === '/testslasharguments') {
1349 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
1350 die;
1355 return $relativepath;
1359 * Searches the current environment variables for some slash arguments
1361 * @param string $file ?
1362 * @todo Finish documenting this function
1364 function get_slash_arguments($file='file.php') {
1366 if (!$string = me()) {
1367 return false;
1370 $pathinfo = explode($file, $string);
1372 if (!empty($pathinfo[1])) {
1373 return addslashes($pathinfo[1]);
1374 } else {
1375 return false;
1380 * Extracts arguments from "/foo/bar/something"
1381 * eg http://mysite.com/script.php/foo/bar/something
1383 * @param string $string ?
1384 * @param int $i ?
1385 * @return array|string
1386 * @todo Finish documenting this function
1388 function parse_slash_arguments($string, $i=0) {
1390 if (detect_munged_arguments($string)) {
1391 return false;
1393 $args = explode('/', $string);
1395 if ($i) { // return just the required argument
1396 return $args[$i];
1398 } else { // return the whole array
1399 array_shift($args); // get rid of the empty first one
1400 return $args;
1405 * Just returns an array of text formats suitable for a popup menu
1407 * @uses FORMAT_MOODLE
1408 * @uses FORMAT_HTML
1409 * @uses FORMAT_PLAIN
1410 * @uses FORMAT_MARKDOWN
1411 * @return array
1413 function format_text_menu() {
1415 return array (FORMAT_MOODLE => get_string('formattext'),
1416 FORMAT_HTML => get_string('formathtml'),
1417 FORMAT_PLAIN => get_string('formatplain'),
1418 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1422 * Given text in a variety of format codings, this function returns
1423 * the text as safe HTML.
1425 * This function should mainly be used for long strings like posts,
1426 * answers, glossary items etc. For short strings @see format_string().
1428 * @uses $CFG
1429 * @uses FORMAT_MOODLE
1430 * @uses FORMAT_HTML
1431 * @uses FORMAT_PLAIN
1432 * @uses FORMAT_WIKI
1433 * @uses FORMAT_MARKDOWN
1434 * @param string $text The text to be formatted. This is raw text originally from user input.
1435 * @param int $format Identifier of the text format to be used
1436 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1437 * @param array $options ?
1438 * @param int $courseid ?
1439 * @return string
1440 * @todo Finish documenting this function
1442 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1444 global $CFG, $COURSE;
1446 static $croncache = array();
1448 if ($text === '') {
1449 return ''; // no need to do any filters and cleaning
1452 if (!isset($options->trusttext)) {
1453 $options->trusttext = false;
1456 if (!isset($options->noclean)) {
1457 $options->noclean=false;
1459 if (!isset($options->nocache)) {
1460 $options->nocache=false;
1462 if (!isset($options->smiley)) {
1463 $options->smiley=true;
1465 if (!isset($options->filter)) {
1466 $options->filter=true;
1468 if (!isset($options->para)) {
1469 $options->para=true;
1471 if (!isset($options->newlines)) {
1472 $options->newlines=true;
1475 if (empty($courseid)) {
1476 $courseid = $COURSE->id;
1479 if (!empty($CFG->cachetext) and empty($options->nocache)) {
1480 $time = time() - $CFG->cachetext;
1481 $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);
1483 if (defined('FULLME') and FULLME == 'cron') {
1484 if (isset($croncache[$md5key])) {
1485 return $croncache[$md5key];
1489 if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
1490 if ($oldcacheitem->timemodified >= $time) {
1491 if (defined('FULLME') and FULLME == 'cron') {
1492 if (count($croncache) > 150) {
1493 reset($croncache);
1494 $key = key($croncache);
1495 unset($croncache[$key]);
1497 $croncache[$md5key] = $oldcacheitem->formattedtext;
1499 return $oldcacheitem->formattedtext;
1504 // trusttext overrides the noclean option!
1505 if ($options->trusttext) {
1506 if (trusttext_present($text)) {
1507 $text = trusttext_strip($text);
1508 if (!empty($CFG->enabletrusttext)) {
1509 $options->noclean = true;
1510 } else {
1511 $options->noclean = false;
1513 } else {
1514 $options->noclean = false;
1516 } else if (!debugging('', DEBUG_DEVELOPER)) {
1517 // strip any forgotten trusttext in non-developer mode
1518 // do not forget to disable text cache when debugging trusttext!!
1519 $text = trusttext_strip($text);
1522 $CFG->currenttextiscacheable = true; // Default status - can be changed by any filter
1524 switch ($format) {
1525 case FORMAT_HTML:
1526 if ($options->smiley) {
1527 replace_smilies($text);
1529 if (!$options->noclean) {
1530 $text = clean_text($text, FORMAT_HTML);
1532 if ($options->filter) {
1533 $text = filter_text($text, $courseid);
1535 break;
1537 case FORMAT_PLAIN:
1538 $text = s($text); // cleans dangerous JS
1539 $text = rebuildnolinktag($text);
1540 $text = str_replace(' ', '&nbsp; ', $text);
1541 $text = nl2br($text);
1542 break;
1544 case FORMAT_WIKI:
1545 // this format is deprecated
1546 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1547 this message as all texts should have been converted to Markdown format instead.
1548 Please post a bug report to http://moodle.org/bugs with information about where you
1549 saw this message.</p>'.s($text);
1550 break;
1552 case FORMAT_MARKDOWN:
1553 $text = markdown_to_html($text);
1554 if ($options->smiley) {
1555 replace_smilies($text);
1557 if (!$options->noclean) {
1558 $text = clean_text($text, FORMAT_HTML);
1561 if ($options->filter) {
1562 $text = filter_text($text, $courseid);
1564 break;
1566 default: // FORMAT_MOODLE or anything else
1567 $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
1568 if (!$options->noclean) {
1569 $text = clean_text($text, FORMAT_HTML);
1572 if ($options->filter) {
1573 $text = filter_text($text, $courseid);
1575 break;
1578 if (empty($options->nocache) and !empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
1579 if (defined('FULLME') and FULLME == 'cron') {
1580 // special static cron cache - no need to store it in db if its not already there
1581 if (count($croncache) > 150) {
1582 reset($croncache);
1583 $key = key($croncache);
1584 unset($croncache[$key]);
1586 $croncache[$md5key] = $text;
1587 return $text;
1590 $newcacheitem = new object();
1591 $newcacheitem->md5key = $md5key;
1592 $newcacheitem->formattedtext = addslashes($text);
1593 $newcacheitem->timemodified = time();
1594 if ($oldcacheitem) { // See bug 4677 for discussion
1595 $newcacheitem->id = $oldcacheitem->id;
1596 @update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1597 // It's unlikely that the cron cache cleaner could have
1598 // deleted this entry in the meantime, as it allows
1599 // some extra time to cover these cases.
1600 } else {
1601 @insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1602 // Again, it's possible that another user has caused this
1603 // record to be created already in the time that it took
1604 // to traverse this function. That's OK too, as the
1605 // call above handles duplicate entries, and eventually
1606 // the cron cleaner will delete them.
1610 return $text;
1613 /** Converts the text format from the value to the 'internal'
1614 * name or vice versa. $key can either be the value or the name
1615 * and you get the other back.
1617 * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1618 * @return mixed as above but the other way around!
1620 function text_format_name( $key ) {
1621 $lookup = array();
1622 $lookup[FORMAT_MOODLE] = 'moodle';
1623 $lookup[FORMAT_HTML] = 'html';
1624 $lookup[FORMAT_PLAIN] = 'plain';
1625 $lookup[FORMAT_MARKDOWN] = 'markdown';
1626 $value = "error";
1627 if (!is_numeric($key)) {
1628 $key = strtolower( $key );
1629 $value = array_search( $key, $lookup );
1631 else {
1632 if (isset( $lookup[$key] )) {
1633 $value = $lookup[ $key ];
1636 return $value;
1640 * Resets all data related to filters, called during upgrade or when filter settings change.
1641 * @return void
1643 function reset_text_filters_cache() {
1644 global $CFG;
1646 delete_records('cache_text');
1647 $purifdir = $CFG->dataroot.'/cache/htmlpurifier';
1648 remove_dir($purifdir, true);
1651 /** Given a simple string, this function returns the string
1652 * processed by enabled string filters if $CFG->filterall is enabled
1654 * This function should be used to print short strings (non html) that
1655 * need filter processing e.g. activity titles, post subjects,
1656 * glossary concepts.
1658 * @param string $string The string to be filtered.
1659 * @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
1660 * @param int $courseid Current course as filters can, potentially, use it
1661 * @return string
1663 function format_string ($string, $striplinks=true, $courseid=NULL ) {
1665 global $CFG, $COURSE;
1667 //We'll use a in-memory cache here to speed up repeated strings
1668 static $strcache = false;
1670 if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
1671 $strcache = array();
1674 //init course id
1675 if (empty($courseid)) {
1676 $courseid = $COURSE->id;
1679 //Calculate md5
1680 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
1682 //Fetch from cache if possible
1683 if (isset($strcache[$md5])) {
1684 return $strcache[$md5];
1687 // First replace all ampersands not followed by html entity code
1688 $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1690 if (!empty($CFG->filterall)) {
1691 $string = filter_string($string, $courseid);
1694 // If the site requires it, strip ALL tags from this string
1695 if (!empty($CFG->formatstringstriptags)) {
1696 $string = strip_tags($string);
1698 // Otherwise strip just links if that is required (default)
1699 } else if ($striplinks) { //strip links in string
1700 $string = preg_replace('/(<a[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1703 //Store to cache
1704 $strcache[$md5] = $string;
1706 return $string;
1710 * Given text in a variety of format codings, this function returns
1711 * the text as plain text suitable for plain email.
1713 * @uses FORMAT_MOODLE
1714 * @uses FORMAT_HTML
1715 * @uses FORMAT_PLAIN
1716 * @uses FORMAT_WIKI
1717 * @uses FORMAT_MARKDOWN
1718 * @param string $text The text to be formatted. This is raw text originally from user input.
1719 * @param int $format Identifier of the text format to be used
1720 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1721 * @return string
1723 function format_text_email($text, $format) {
1725 switch ($format) {
1727 case FORMAT_PLAIN:
1728 return $text;
1729 break;
1731 case FORMAT_WIKI:
1732 $text = wiki_to_html($text);
1733 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1734 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
1735 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1736 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1737 break;
1739 case FORMAT_HTML:
1740 return html_to_text($text);
1741 break;
1743 case FORMAT_MOODLE:
1744 case FORMAT_MARKDOWN:
1745 default:
1746 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1747 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1748 break;
1753 * Given some text in HTML format, this function will pass it
1754 * through any filters that have been defined in $CFG->textfilterx
1755 * The variable defines a filepath to a file containing the
1756 * filter function. The file must contain a variable called
1757 * $textfilter_function which contains the name of the function
1758 * with $courseid and $text parameters
1760 * @param string $text The text to be passed through format filters
1761 * @param int $courseid ?
1762 * @return string
1763 * @todo Finish documenting this function
1765 function filter_text($text, $courseid=NULL) {
1766 global $CFG, $COURSE;
1768 if (empty($courseid)) {
1769 $courseid = $COURSE->id; // (copied from format_text)
1772 if (!empty($CFG->textfilters)) {
1773 require_once($CFG->libdir.'/filterlib.php');
1774 $textfilters = explode(',', $CFG->textfilters);
1775 foreach ($textfilters as $textfilter) {
1776 if (is_readable($CFG->dirroot .'/'. $textfilter .'/filter.php')) {
1777 include_once($CFG->dirroot .'/'. $textfilter .'/filter.php');
1778 $functionname = basename($textfilter).'_filter';
1779 if (function_exists($functionname)) {
1780 $text = $functionname($courseid, $text);
1786 /// <nolink> tags removed for XHTML compatibility
1787 $text = str_replace('<nolink>', '', $text);
1788 $text = str_replace('</nolink>', '', $text);
1790 return $text;
1795 * Given a string (short text) in HTML format, this function will pass it
1796 * through any filters that have been defined in $CFG->stringfilters
1797 * The variable defines a filepath to a file containing the
1798 * filter function. The file must contain a variable called
1799 * $textfilter_function which contains the name of the function
1800 * with $courseid and $text parameters
1802 * @param string $string The text to be passed through format filters
1803 * @param int $courseid The id of a course
1804 * @return string
1806 function filter_string($string, $courseid=NULL) {
1807 global $CFG, $COURSE;
1809 if (empty($CFG->textfilters)) { // All filters are disabled anyway so quit
1810 return $string;
1813 if (empty($courseid)) {
1814 $courseid = $COURSE->id;
1817 require_once($CFG->libdir.'/filterlib.php');
1819 if (isset($CFG->stringfilters)) { // We have a predefined list to use, great!
1820 if (empty($CFG->stringfilters)) { // but it's blank, so finish now
1821 return $string;
1823 $stringfilters = explode(',', $CFG->stringfilters); // ..use the list we have
1825 } else { // Otherwise try to derive a list from textfilters
1826 if (strpos($CFG->textfilters, 'filter/multilang') !== false) { // Multilang is here
1827 $stringfilters = array('filter/multilang'); // Let's use just that
1828 $CFG->stringfilters = 'filter/multilang'; // Save it for next time through
1829 } else {
1830 $CFG->stringfilters = ''; // Save the result and return
1831 return $string;
1836 foreach ($stringfilters as $stringfilter) {
1837 if (is_readable($CFG->dirroot .'/'. $stringfilter .'/filter.php')) {
1838 include_once($CFG->dirroot .'/'. $stringfilter .'/filter.php');
1839 $functionname = basename($stringfilter).'_filter';
1840 if (function_exists($functionname)) {
1841 $string = $functionname($courseid, $string);
1846 /// <nolink> tags removed for XHTML compatibility
1847 $string = str_replace('<nolink>', '', $string);
1848 $string = str_replace('</nolink>', '', $string);
1850 return $string;
1854 * Is the text marked as trusted?
1856 * @param string $text text to be searched for TRUSTTEXT marker
1857 * @return boolean
1859 function trusttext_present($text) {
1860 if (strpos($text, TRUSTTEXT) !== FALSE) {
1861 return true;
1862 } else {
1863 return false;
1868 * This funtion MUST be called before the cleaning or any other
1869 * function that modifies the data! We do not know the origin of trusttext
1870 * in database, if it gets there in tweaked form we must not convert it
1871 * to supported form!!!
1873 * Please be carefull not to use stripslashes on data from database
1874 * or twice stripslashes when processing data recieved from user.
1876 * @param string $text text that may contain TRUSTTEXT marker
1877 * @return text without any TRUSTTEXT marker
1879 function trusttext_strip($text) {
1880 global $CFG;
1882 while (true) { //removing nested TRUSTTEXT
1883 $orig = $text;
1884 $text = str_replace(TRUSTTEXT, '', $text);
1885 if (strcmp($orig, $text) === 0) {
1886 return $text;
1892 * Mark text as trusted, such text may contain any HTML tags because the
1893 * normal text cleaning will be bypassed.
1894 * Please make sure that the text comes from trusted user before storing
1895 * it into database!
1897 function trusttext_mark($text) {
1898 global $CFG;
1899 if (!empty($CFG->enabletrusttext) and (strpos($text, TRUSTTEXT) === FALSE)) {
1900 return TRUSTTEXT.$text;
1901 } else {
1902 return $text;
1905 function trusttext_after_edit(&$text, $context) {
1906 if (has_capability('moodle/site:trustcontent', $context)) {
1907 $text = trusttext_strip($text);
1908 $text = trusttext_mark($text);
1909 } else {
1910 $text = trusttext_strip($text);
1914 function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
1915 global $CFG;
1917 $options = new object();
1918 $options->smiley = false;
1919 $options->filter = false;
1920 if (!empty($CFG->enabletrusttext)
1921 and has_capability('moodle/site:trustcontent', $context)
1922 and trusttext_present($text)) {
1923 $options->noclean = true;
1924 } else {
1925 $options->noclean = false;
1927 $text = trusttext_strip($text);
1928 if ($usehtmleditor) {
1929 $text = format_text($text, $format, $options);
1930 $format = FORMAT_HTML;
1931 } else if (!$options->noclean){
1932 $text = clean_text($text, $format);
1937 * Given raw text (eg typed in by a user), this function cleans it up
1938 * and removes any nasty tags that could mess up Moodle pages.
1940 * @uses FORMAT_MOODLE
1941 * @uses FORMAT_PLAIN
1942 * @uses ALLOWED_TAGS
1943 * @param string $text The text to be cleaned
1944 * @param int $format Identifier of the text format to be used
1945 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1946 * @return string The cleaned up text
1948 function clean_text($text, $format=FORMAT_MOODLE) {
1950 global $ALLOWED_TAGS, $CFG;
1952 if (empty($text) or is_numeric($text)) {
1953 return (string)$text;
1956 switch ($format) {
1957 case FORMAT_PLAIN:
1958 case FORMAT_MARKDOWN:
1959 return $text;
1961 default:
1963 if (!empty($CFG->enablehtmlpurifier)) {
1964 $text = purify_html($text);
1965 } else {
1966 /// Fix non standard entity notations
1967 $text = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $text);
1968 $text = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $text);
1970 /// Remove tags that are not allowed
1971 $text = strip_tags($text, $ALLOWED_TAGS);
1973 /// Clean up embedded scripts and , using kses
1974 $text = cleanAttributes($text);
1976 /// Again remove tags that are not allowed
1977 $text = strip_tags($text, $ALLOWED_TAGS);
1981 /// Remove potential script events - some extra protection for undiscovered bugs in our code
1982 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
1983 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
1985 return $text;
1990 * KSES replacement cleaning function - uses HTML Purifier.
1992 function purify_html($text) {
1993 global $CFG;
1995 // this can not be done only once because we sometimes need to reset the cache
1996 $cachedir = $CFG->dataroot.'/cache/htmlpurifier/';
1997 $status = check_dir_exists($cachedir, true, true);
1999 static $purifier = false;
2000 if ($purifier === false) {
2001 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.auto.php';
2002 $config = HTMLPurifier_Config::createDefault();
2003 $config->set('Core', 'AcceptFullDocuments', false);
2004 $config->set('Core', 'Encoding', 'UTF-8');
2005 $config->set('HTML', 'Doctype', 'XHTML 1.0 Transitional');
2006 $config->set('Cache', 'SerializerPath', $cachedir);
2007 $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));
2008 $purifier = new HTMLPurifier($config);
2010 return $purifier->purify($text);
2014 * This function takes a string and examines it for HTML tags.
2015 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
2016 * which checks for attributes and filters them for malicious content
2017 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2019 * @param string $str The string to be examined for html tags
2020 * @return string
2022 function cleanAttributes($str){
2023 $result = preg_replace_callback(
2024 '%(<[^>]*(>|$)|>)%m', #search for html tags
2025 "cleanAttributes2",
2026 $str
2028 return $result;
2032 * This function takes a string with an html tag and strips out any unallowed
2033 * protocols e.g. javascript:
2034 * It calls ancillary functions in kses which are prefixed by kses
2035 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2037 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
2038 * element the html to be cleared
2039 * @return string
2041 function cleanAttributes2($htmlArray){
2043 global $CFG, $ALLOWED_PROTOCOLS;
2044 require_once($CFG->libdir .'/kses.php');
2046 $htmlTag = $htmlArray[1];
2047 if (substr($htmlTag, 0, 1) != '<') {
2048 return '&gt;'; //a single character ">" detected
2050 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
2051 return ''; // It's seriously malformed
2053 $slash = trim($matches[1]); //trailing xhtml slash
2054 $elem = $matches[2]; //the element name
2055 $attrlist = $matches[3]; // the list of attributes as a string
2057 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
2059 $attStr = '';
2060 foreach ($attrArray as $arreach) {
2061 $arreach['name'] = strtolower($arreach['name']);
2062 if ($arreach['name'] == 'style') {
2063 $value = $arreach['value'];
2064 while (true) {
2065 $prevvalue = $value;
2066 $value = kses_no_null($value);
2067 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
2068 $value = kses_decode_entities($value);
2069 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
2070 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
2071 if ($value === $prevvalue) {
2072 $arreach['value'] = $value;
2073 break;
2076 $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']);
2077 $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']);
2078 $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
2079 } else if ($arreach['name'] == 'href') {
2080 //Adobe Acrobat Reader XSS protection
2081 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd))[^a-z0-9_\.\-].*$/i', '$1', $arreach['value']);
2083 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
2086 $xhtml_slash = '';
2087 if (preg_match('%/\s*$%', $attrlist)) {
2088 $xhtml_slash = ' /';
2090 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
2094 * Replaces all known smileys in the text with image equivalents
2096 * @uses $CFG
2097 * @param string $text Passed by reference. The string to search for smily strings.
2098 * @return string
2100 function replace_smilies(&$text) {
2102 global $CFG;
2104 if (empty($CFG->emoticons)) { /// No emoticons defined, nothing to process here
2105 return;
2108 $lang = current_language();
2109 $emoticonstring = $CFG->emoticons;
2110 static $e = array();
2111 static $img = array();
2112 static $emoticons = null;
2114 if (is_null($emoticons)) {
2115 $emoticons = array();
2116 if ($emoticonstring) {
2117 $items = explode('{;}', $CFG->emoticons);
2118 foreach ($items as $item) {
2119 $item = explode('{:}', $item);
2120 $emoticons[$item[0]] = $item[1];
2126 if (empty($img[$lang])) { /// After the first time this is not run again
2127 $e[$lang] = array();
2128 $img[$lang] = array();
2129 foreach ($emoticons as $emoticon => $image){
2130 $alttext = get_string($image, 'pix');
2131 $e[$lang][] = $emoticon;
2132 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath .'/s/'. $image .'.gif" />';
2136 // Exclude from transformations all the code inside <script> tags
2137 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
2138 // Based on code from glossary fiter by Williams Castillo.
2139 // - Eloy
2141 // Detect all the <script> zones to take out
2142 $excludes = array();
2143 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
2145 // Take out all the <script> zones from text
2146 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
2147 $excludes['<+'.$key.'+>'] = $value;
2149 if ($excludes) {
2150 $text = str_replace($excludes,array_keys($excludes),$text);
2153 /// this is the meat of the code - this is run every time
2154 $text = str_replace($e[$lang], $img[$lang], $text);
2156 // Recover all the <script> zones to text
2157 if ($excludes) {
2158 $text = str_replace(array_keys($excludes),$excludes,$text);
2163 * Given plain text, makes it into HTML as nicely as possible.
2164 * May contain HTML tags already
2166 * @uses $CFG
2167 * @param string $text The string to convert.
2168 * @param boolean $smiley Convert any smiley characters to smiley images?
2169 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
2170 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2171 * @return string
2174 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
2177 global $CFG;
2179 /// Remove any whitespace that may be between HTML tags
2180 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
2182 /// Remove any returns that precede or follow HTML tags
2183 $text = eregi_replace("([\n\r])<", " <", $text);
2184 $text = eregi_replace(">([\n\r])", "> ", $text);
2186 convert_urls_into_links($text);
2188 /// Make returns into HTML newlines.
2189 if ($newlines) {
2190 $text = nl2br($text);
2193 /// Turn smileys into images.
2194 if ($smiley) {
2195 replace_smilies($text);
2198 /// Wrap the whole thing in a paragraph tag if required
2199 if ($para) {
2200 return '<p>'.$text.'</p>';
2201 } else {
2202 return $text;
2207 * Given Markdown formatted text, make it into XHTML using external function
2209 * @uses $CFG
2210 * @param string $text The markdown formatted text to be converted.
2211 * @return string Converted text
2213 function markdown_to_html($text) {
2214 global $CFG;
2216 require_once($CFG->libdir .'/markdown.php');
2218 return Markdown($text);
2222 * Given HTML text, make it into plain text using external function
2224 * @uses $CFG
2225 * @param string $html The text to be converted.
2226 * @return string
2228 function html_to_text($html) {
2230 global $CFG;
2232 require_once($CFG->libdir .'/html2text.php');
2234 $result = html2text($html);
2236 // html2text does not fix numerical entities so handle those here.
2237 $tl=textlib_get_instance();
2238 $result = $tl->entities_to_utf8($result,false);
2240 return $result;
2244 * Given some text this function converts any URLs it finds into HTML links
2246 * @param string $text Passed in by reference. The string to be searched for urls.
2248 function convert_urls_into_links(&$text) {
2249 /// Make lone URLs into links. eg http://moodle.com/
2250 $text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
2251 "\\1<a href=\"\\2://\\3\\4\" target=\"_blank\">\\2://\\3\\4</a>", $text);
2253 /// eg www.moodle.com
2254 $text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
2255 "\\1<a href=\"http://www.\\2\\3\" target=\"_blank\">www.\\2\\3</a>", $text);
2259 * This function will highlight search words in a given string
2260 * It cares about HTML and will not ruin links. It's best to use
2261 * this function after performing any conversions to HTML.
2262 * Function found here: http://forums.devshed.com/t67822/scdaa2d1c3d4bacb4671d075ad41f0854.html
2264 * @param string $needle The string to search for
2265 * @param string $haystack The string to search for $needle in
2266 * @param int $case whether to do case-sensitive or insensitive matching.
2267 * @return string
2268 * @todo Finish documenting this function
2270 function highlight($needle, $haystack, $case=0,
2271 $left_string='<span class="highlight">', $right_string='</span>') {
2273 if (empty($needle) or empty($haystack)) {
2274 return $haystack;
2277 //$list_of_words = eregi_replace("[^-a-zA-Z0-9&.']", " ", $needle); // bug 3101
2278 $list_of_words = $needle;
2279 $list_array = explode(' ', $list_of_words);
2280 for ($i=0; $i<sizeof($list_array); $i++) {
2281 if (strlen($list_array[$i]) == 1) {
2282 $list_array[$i] = '';
2285 $list_of_words = implode(' ', $list_array);
2286 $list_of_words_cp = $list_of_words;
2287 $final = array();
2288 preg_match_all('/<(.+?)>/is',$haystack,$list_of_words);
2290 foreach (array_unique($list_of_words[0]) as $key=>$value) {
2291 $final['<|'.$key.'|>'] = $value;
2294 $haystack = str_replace($final,array_keys($final),$haystack);
2295 $list_of_words_cp = eregi_replace(' +', '|', $list_of_words_cp);
2297 if ($list_of_words_cp{0}=='|') {
2298 $list_of_words_cp{0} = '';
2300 if ($list_of_words_cp{strlen($list_of_words_cp)-1}=='|') {
2301 $list_of_words_cp{strlen($list_of_words_cp)-1}='';
2304 $list_of_words_cp = trim($list_of_words_cp);
2306 if ($list_of_words_cp) {
2308 $list_of_words_cp = "(". $list_of_words_cp .")";
2310 if (!$case){
2311 $haystack = eregi_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2312 } else {
2313 $haystack = ereg_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2316 $haystack = str_replace(array_keys($final),$final,$haystack);
2318 return $haystack;
2322 * This function will highlight instances of $needle in $haystack
2323 * It's faster that the above function and doesn't care about
2324 * HTML or anything.
2326 * @param string $needle The string to search for
2327 * @param string $haystack The string to search for $needle in
2328 * @return string
2330 function highlightfast($needle, $haystack) {
2332 if (empty($needle) or empty($haystack)) {
2333 return $haystack;
2336 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
2338 if (count($parts) === 1) {
2339 return $haystack;
2342 $pos = 0;
2344 foreach ($parts as $key => $part) {
2345 $parts[$key] = substr($haystack, $pos, strlen($part));
2346 $pos += strlen($part);
2348 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2349 $pos += strlen($needle);
2352 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2356 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2357 * Internationalisation, for print_header and backup/restorelib.
2358 * @param $dir Default false.
2359 * @return string Attributes.
2361 function get_html_lang($dir = false) {
2362 $direction = '';
2363 if ($dir) {
2364 if (get_string('thisdirection') == 'rtl') {
2365 $direction = ' dir="rtl"';
2366 } else {
2367 $direction = ' dir="ltr"';
2370 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2371 $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
2372 @header('Content-Language: '.$language);
2373 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2377 * Return the markup for the destination of the 'Skip to main content' links.
2378 * Accessibility improvement for keyboard-only users.
2379 * Used in course formats, /index.php and /course/index.php
2380 * @return string HTML element.
2382 function skip_main_destination() {
2383 return '<span id="maincontent"></span>';
2387 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
2390 * Print a standard header
2392 * @uses $USER
2393 * @uses $CFG
2394 * @uses $SESSION
2395 * @param string $title Appears at the top of the window
2396 * @param string $heading Appears at the top of the page
2397 * @param array $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
2398 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2399 * @param string $meta Meta tags to be added to the header
2400 * @param boolean $cache Should this page be cacheable?
2401 * @param string $button HTML code for a button (usually for module editing)
2402 * @param string $menu HTML code for a popup menu
2403 * @param boolean $usexml use XML for this page
2404 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2405 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2407 function print_header ($title='', $heading='', $navigation='', $focus='',
2408 $meta='', $cache=true, $button='&nbsp;', $menu='',
2409 $usexml=false, $bodytags='', $return=false) {
2411 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
2413 if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
2414 debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
2415 . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.", DEBUG_DEVELOPER);
2418 $heading = format_string($heading); // Fix for MDL-8582
2420 /// This makes sure that the header is never repeated twice on a page
2421 if (defined('HEADER_PRINTED')) {
2422 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().');
2423 return;
2425 define('HEADER_PRINTED', 'true');
2428 /// Add the required stylesheets
2429 $stylesheetshtml = '';
2430 foreach ($CFG->stylesheets as $stylesheet) {
2431 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2433 $meta = $stylesheetshtml.$meta;
2436 /// Add the meta page from the themes if any were requested
2438 $metapage = '';
2440 if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
2441 ob_start();
2442 include_once($CFG->dirroot.'/theme/standard/meta.php');
2443 $metapage .= ob_get_contents();
2444 ob_end_clean();
2447 if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
2448 if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
2449 ob_start();
2450 include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
2451 $metapage .= ob_get_contents();
2452 ob_end_clean();
2456 if (!isset($THEME->metainclude) || $THEME->metainclude) {
2457 if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
2458 ob_start();
2459 include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
2460 $metapage .= ob_get_contents();
2461 ob_end_clean();
2465 $meta = $meta."\n".$metapage;
2467 $meta .= "\n".require_js('',1);
2469 /// Set up some navigation variables
2471 if (is_newnav($navigation)){
2472 $home = false;
2473 } else {
2474 if ($navigation == 'home') {
2475 $home = true;
2476 $navigation = '';
2477 } else {
2478 $home = false;
2482 /// This is another ugly hack to make navigation elements available to print_footer later
2483 $THEME->title = $title;
2484 $THEME->heading = $heading;
2485 $THEME->navigation = $navigation;
2486 $THEME->button = $button;
2487 $THEME->menu = $menu;
2488 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2490 if ($button == '') {
2491 $button = '&nbsp;';
2494 if (!$menu and $navigation) {
2495 if (empty($CFG->loginhttps)) {
2496 $wwwroot = $CFG->wwwroot;
2497 } else {
2498 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
2500 $menu = user_login_string($COURSE);
2503 if (isset($SESSION->justloggedin)) {
2504 unset($SESSION->justloggedin);
2505 if (!empty($CFG->displayloginfailures)) {
2506 if (!empty($USER->username) and $USER->username != 'guest') {
2507 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
2508 $menu .= '&nbsp;<font size="1">';
2509 if (empty($count->accounts)) {
2510 $menu .= get_string('failedloginattempts', '', $count);
2511 } else {
2512 $menu .= get_string('failedloginattemptsall', '', $count);
2514 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_SYSTEM))) {
2515 $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
2516 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
2518 $menu .= '</font>';
2525 $meta = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' .
2526 "\n" . $meta . "\n";
2527 if (!$usexml) {
2528 @header('Content-Type: text/html; charset=utf-8');
2530 @header('Content-Script-Type: text/javascript');
2531 @header('Content-Style-Type: text/css');
2533 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2534 $direction = get_html_lang($dir=true);
2536 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2537 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2538 @header('Pragma: no-cache');
2539 @header('Expires: ');
2540 } else { // Do everything we can to always prevent clients and proxies caching
2541 @header('Cache-Control: no-store, no-cache, must-revalidate');
2542 @header('Cache-Control: post-check=0, pre-check=0', false);
2543 @header('Pragma: no-cache');
2544 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2545 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2547 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2548 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
2550 @header('Accept-Ranges: none');
2552 $currentlanguage = current_language();
2554 if (empty($usexml)) {
2555 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2556 } else {
2557 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2558 if(!$mathplayer) {
2559 header('Content-Type: application/xhtml+xml');
2561 echo '<?xml version="1.0" ?>'."\n";
2562 if (!empty($CFG->xml_stylesheets)) {
2563 $stylesheets = explode(';', $CFG->xml_stylesheets);
2564 foreach ($stylesheets as $stylesheet) {
2565 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
2568 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
2569 if (!empty($CFG->xml_doctype_extra)) {
2570 echo ' plus '. $CFG->xml_doctype_extra;
2572 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
2573 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2574 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
2575 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2576 $direction";
2577 if($mathplayer) {
2578 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
2579 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2580 $meta .= '</object>'."\n";
2581 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2585 // Clean up the title
2587 $title = format_string($title); // fix for MDL-8582
2588 $title = str_replace('"', '&quot;', $title);
2590 // Create class and id for this page
2592 page_id_and_class($pageid, $pageclass);
2594 $pageclass .= ' course-'.$COURSE->id;
2596 if (!isloggedin()) {
2597 $pageclass .= ' notloggedin';
2600 if (!empty($USER->editing)) {
2601 $pageclass .= ' editing';
2604 if (!empty($CFG->blocksdrag)) {
2605 $pageclass .= ' drag';
2608 $pageclass .= ' dir-'.get_string('thisdirection');
2610 $pageclass .= ' lang-'.$currentlanguage;
2612 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
2614 ob_start();
2615 include($CFG->header);
2616 $output = ob_get_contents();
2617 ob_end_clean();
2619 // container debugging info
2620 $THEME->open_header_containers = open_containers();
2622 // Skip to main content, see skip_main_destination().
2623 if ($pageid=='course-view' or $pageid=='site-index' or $pageid=='course-index') {
2624 $skiplink = '<a class="skip" href="#maincontent">'.get_string('tocontent', 'access').'</a>';
2625 if (! preg_match('/(.*<div[^>]+id="page"[^>]*>)(.*)/s', $output, $matches)) {
2626 preg_match('/(.*<body.*?>)(.*)/s', $output, $matches);
2628 $output = $matches[1]."\n". $skiplink .$matches[2];
2631 $output = force_strict_header($output);
2633 if (!empty($CFG->messaging)) {
2634 $output .= message_popup_window();
2637 // Add in any extra JavaScript libraries that occurred during the header
2638 $output .= require_js('', 2);
2640 if ($return) {
2641 return $output;
2642 } else {
2643 echo $output;
2648 * Used to include JavaScript libraries.
2650 * When the $lib parameter is given, the function will ensure that the
2651 * named library is loaded onto the page - either in the HTML <head>,
2652 * just after the header, or at an arbitrary later point in the page,
2653 * depending on where this function is called.
2655 * Libraries will not be included more than once, so this works like
2656 * require_once in PHP.
2658 * There are two special-case calls to this function which are both used only
2659 * by weblib print_header:
2660 * $extracthtml = 1: this is used before printing the header.
2661 * It returns the script tag code that should go inside the <head>.
2662 * $extracthtml = 2: this is used after printing the header and handles any
2663 * require_js calls that occurred within the header itself.
2665 * @param mixed $lib - string or array of strings
2666 * string(s) should be the shortname for the library or the
2667 * full path to the library file.
2668 * @param int $extracthtml Do not set this parameter usually (leave 0), only
2669 * weblib should set this to 1 or 2 in print_header function.
2670 * @return mixed No return value, except when using $extracthtml it returns the html code.
2672 function require_js($lib,$extracthtml=0) {
2673 global $CFG;
2674 static $loadlibs = array();
2676 static $state = REQUIREJS_BEFOREHEADER;
2677 static $latecode = '';
2679 if (!empty($lib)) {
2680 // Add the lib to the list of libs to be loaded, if it isn't already
2681 // in the list.
2682 if (is_array($lib)) {
2683 foreach($lib as $singlelib) {
2684 require_js($singlelib);
2686 } else {
2687 $libpath = ajax_get_lib($lib);
2688 if (array_search($libpath, $loadlibs) === false) {
2689 $loadlibs[] = $libpath;
2691 // For state other than 0 we need to take action as well as just
2692 // adding it to loadlibs
2693 if($state != REQUIREJS_BEFOREHEADER) {
2694 // Get the script statement for this library
2695 $scriptstatement=get_require_js_code(array($libpath));
2697 if($state == REQUIREJS_AFTERHEADER) {
2698 // After the header, print it immediately
2699 print $scriptstatement;
2700 } else {
2701 // Haven't finished the header yet. Add it after the
2702 // header
2703 $latecode .= $scriptstatement;
2708 } else if($extracthtml==1) {
2709 if($state !== REQUIREJS_BEFOREHEADER) {
2710 debugging('Incorrect state in require_js (expected BEFOREHEADER): be careful not to call with empty $lib (except in print_header)');
2711 } else {
2712 $state = REQUIREJS_INHEADER;
2715 return get_require_js_code($loadlibs);
2716 } else if($extracthtml==2) {
2717 if($state !== REQUIREJS_INHEADER) {
2718 debugging('Incorrect state in require_js (expected INHEADER): be careful not to call with empty $lib (except in print_header)');
2719 return '';
2720 } else {
2721 $state = REQUIREJS_AFTERHEADER;
2722 return $latecode;
2724 } else {
2725 debugging('Unexpected value for $extracthtml');
2730 * Should not be called directly - use require_js. This function obtains the code
2731 * (script tags) needed to include JavaScript libraries.
2732 * @param array $loadlibs Array of library files to include
2733 * @return string HTML code to include them
2735 function get_require_js_code($loadlibs) {
2736 global $CFG;
2737 // Return the html needed to load the JavaScript files defined in
2738 // our list of libs to be loaded.
2739 $output = '';
2740 foreach ($loadlibs as $loadlib) {
2741 $output .= '<script type="text/javascript" ';
2742 $output .= " src=\"$loadlib\"></script>\n";
2743 if ($loadlib == $CFG->wwwroot.'/lib/yui/logger/logger-min.js') {
2744 // Special case, we need the CSS too.
2745 $output .= '<link type="text/css" rel="stylesheet" ';
2746 $output .= " href=\"{$CFG->wwwroot}/lib/yui/logger/assets/logger.css\" />\n";
2749 return $output;
2754 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2755 * and substitute the XHTML strict document type.
2756 * Note, requires the 'xmlns' fix in function print_header above.
2757 * See: http://tracker.moodle.org/browse/MDL-7883
2758 * TODO:
2760 function force_strict_header($output) {
2761 global $CFG;
2762 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2763 $xsl = '/lib/xhtml.xsl';
2765 if (!headers_sent() && !empty($CFG->xmlstrictheaders)) { // With xml strict headers, the browser will barf
2766 $ctype = 'Content-Type: ';
2767 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2769 if (isset($_SERVER['HTTP_ACCEPT'])
2770 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2771 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2772 // Firefox et al.
2773 $ctype .= 'application/xhtml+xml';
2774 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2776 } else if (file_exists($CFG->dirroot.$xsl)
2777 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2778 // XSL hack for IE 5+ on Windows.
2779 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2780 $www_xsl = $CFG->wwwroot .$xsl;
2781 $ctype .= 'application/xml';
2782 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2783 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2785 } else {
2786 //ELSE: Mac/IE, old/non-XML browsers.
2787 $ctype .= 'text/html';
2788 $prolog = '';
2790 @header($ctype.'; charset=utf-8');
2791 $output = $prolog . $output;
2793 // Test parser error-handling.
2794 if (isset($_GET['error'])) {
2795 $output .= "__ TEST: XML well-formed error < __\n";
2799 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
2801 return $output;
2807 * This version of print_header is simpler because the course name does not have to be
2808 * provided explicitly in the strings. It can be used on the site page as in courses
2809 * Eventually all print_header could be replaced by print_header_simple
2811 * @param string $title Appears at the top of the window
2812 * @param string $heading Appears at the top of the page
2813 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2814 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2815 * @param string $meta Meta tags to be added to the header
2816 * @param boolean $cache Should this page be cacheable?
2817 * @param string $button HTML code for a button (usually for module editing)
2818 * @param string $menu HTML code for a popup menu
2819 * @param boolean $usexml use XML for this page
2820 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2821 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2823 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
2824 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
2826 global $COURSE, $CFG;
2828 // if we have no navigation specified, build it
2829 if( empty($navigation) ){
2830 $navigation = build_navigation('');
2833 // If old style nav prepend course short name otherwise leave $navigation object alone
2834 if (!is_newnav($navigation)) {
2835 if ($COURSE->id != SITEID) {
2836 $shortname = '<a href="'.$CFG->wwwroot.'/course/view.php?id='. $COURSE->id .'">'. $COURSE->shortname .'</a> ->';
2837 $navigation = $shortname.' '.$navigation;
2841 $output = print_header($COURSE->shortname .': '. $title, $COURSE->fullname .' '. $heading, $navigation, $focus, $meta,
2842 $cache, $button, $menu, $usexml, $bodytags, true);
2844 if ($return) {
2845 return $output;
2846 } else {
2847 echo $output;
2853 * Can provide a course object to make the footer contain a link to
2854 * to the course home page, otherwise the link will go to the site home
2855 * @uses $USER
2856 * @param mixed $course course object, used for course link button or
2857 * 'none' means no user link, only docs link
2858 * 'empty' means nothing printed in footer
2859 * 'home' special frontpage footer
2860 * @param object $usercourse course used in user link
2861 * @param boolean $return output as string
2862 * @return mixed string or void
2864 function print_footer($course=NULL, $usercourse=NULL, $return=false) {
2865 global $USER, $CFG, $THEME, $COURSE;
2867 if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
2868 admin_externalpage_print_footer();
2869 return;
2872 /// Course links or special footer
2873 if ($course) {
2874 if ($course === 'empty') {
2875 // special hack - sometimes we do not want even the docs link in footer
2876 $output = '';
2877 if (!empty($THEME->open_header_containers)) {
2878 for ($i=0; $i<$THEME->open_header_containers; $i++) {
2879 $output .= print_container_end_all(); // containers opened from header
2881 } else {
2882 //1.8 theme compatibility
2883 $output .= "\n</div>"; // content div
2885 $output .= "\n</div>\n</body>\n</html>"; // close page div started in header
2886 if ($return) {
2887 return $output;
2888 } else {
2889 echo $output;
2890 return;
2893 } else if ($course === 'none') { // Don't print any links etc
2894 $homelink = '';
2895 $loggedinas = '';
2896 $home = false;
2898 } else if ($course === 'home') { // special case for site home page - please do not remove
2899 $course = get_site();
2900 $homelink = '<div class="sitelink">'.
2901 '<a title="Moodle '. $CFG->release .'" href="http://moodle.org/">'.
2902 '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
2903 $home = true;
2905 } else {
2906 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
2907 '/course/view.php?id='.$course->id.'">'.format_string($course->shortname).'</a></div>';
2908 $home = false;
2911 } else {
2912 $course = get_site(); // Set course as site course by default
2913 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
2914 $home = false;
2917 /// Set up some other navigation links (passed from print_header by ugly hack)
2918 $menu = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
2919 $title = isset($THEME->title) ? $THEME->title : '';
2920 $button = isset($THEME->button) ? $THEME->button : '';
2921 $heading = isset($THEME->heading) ? $THEME->heading : '';
2922 $navigation = isset($THEME->navigation) ? $THEME->navigation : '';
2923 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2926 /// Set the user link if necessary
2927 if (!$usercourse and is_object($course)) {
2928 $usercourse = $course;
2931 if (!isset($loggedinas)) {
2932 $loggedinas = user_login_string($usercourse, $USER);
2935 if ($loggedinas == $menu) {
2936 $menu = '';
2939 /// there should be exactly the same number of open containers as after the header
2940 if ($THEME->open_header_containers != open_containers()) {
2941 debugging('Unexpected number of open containers: '.open_containers().', expecting '.$THEME->open_header_containers, DEBUG_DEVELOPER);
2944 /// Provide some performance info if required
2945 $performanceinfo = '';
2946 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2947 $perf = get_performance_info();
2948 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
2949 error_log("PERF: " . $perf['txt']);
2951 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
2952 $performanceinfo = $perf['html'];
2956 /// Include the actual footer file
2958 ob_start();
2959 include($CFG->footer);
2960 $output = ob_get_contents();
2961 ob_end_clean();
2963 if ($return) {
2964 return $output;
2965 } else {
2966 echo $output;
2971 * Returns the name of the current theme
2973 * @uses $CFG
2974 * @uses $USER
2975 * @uses $SESSION
2976 * @uses $COURSE
2977 * @uses $FULLME
2978 * @return string
2980 function current_theme() {
2981 global $CFG, $USER, $SESSION, $COURSE, $FULLME;
2983 if (empty($CFG->themeorder)) {
2984 $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
2985 } else {
2986 $themeorder = $CFG->themeorder;
2989 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id) {
2990 require_once($CFG->dirroot.'/mnet/peer.php');
2991 $mnet_peer = new mnet_peer();
2992 $mnet_peer->set_id($USER->mnethostid);
2995 $theme = '';
2996 foreach ($themeorder as $themetype) {
2998 if (!empty($theme)) continue;
3000 switch ($themetype) {
3001 case 'page': // Page theme is for special page-only themes set by code
3002 if (!empty($CFG->pagetheme)) {
3003 $theme = $CFG->pagetheme;
3005 break;
3006 case 'course':
3007 if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) {
3008 $theme = $COURSE->theme;
3010 break;
3011 case 'category':
3012 if (!empty($CFG->allowcategorythemes)) {
3013 /// Nasty hack to check if we're in a category page
3014 if (stripos($FULLME, 'course/category.php') !== false) {
3015 global $id;
3016 if (!empty($id)) {
3017 $theme = current_category_theme($id);
3019 /// Otherwise check if we're in a course that has a category theme set
3020 } else if (!empty($COURSE->category)) {
3021 $theme = current_category_theme($COURSE->category);
3024 break;
3025 case 'session':
3026 if (!empty($SESSION->theme)) {
3027 $theme = $SESSION->theme;
3029 break;
3030 case 'user':
3031 if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) {
3032 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
3033 $theme = $mnet_peer->theme;
3034 } else {
3035 $theme = $USER->theme;
3038 break;
3039 case 'site':
3040 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
3041 $theme = $mnet_peer->theme;
3042 } else {
3043 $theme = $CFG->theme;
3045 break;
3046 default:
3047 /// do nothing
3051 /// A final check in case 'site' was not included in $CFG->themeorder
3052 if (empty($theme)) {
3053 $theme = $CFG->theme;
3056 return $theme;
3060 * Retrieves the category theme if one exists, otherwise checks the parent categories.
3061 * Recursive function.
3063 * @uses $COURSE
3064 * @param integer $categoryid id of the category to check
3065 * @return string theme name
3067 function current_category_theme($categoryid=0) {
3068 global $COURSE;
3070 /// Use the COURSE global if the categoryid not set
3071 if (empty($categoryid)) {
3072 if (!empty($COURSE->category)) {
3073 $categoryid = $COURSE->category;
3074 } else {
3075 return false;
3079 /// Retrieve the current category
3080 if ($category = get_record('course_categories', 'id', $categoryid)) {
3082 /// Return the category theme if it exists
3083 if (!empty($category->theme)) {
3084 return $category->theme;
3086 /// Otherwise try the parent category if one exists
3087 } else if (!empty($category->parent)) {
3088 return current_category_theme($category->parent);
3091 /// Return false if we can't find the category record
3092 } else {
3093 return false;
3098 * This function is called by stylesheets to set up the header
3099 * approriately as well as the current path
3101 * @uses $CFG
3102 * @param int $lastmodified ?
3103 * @param int $lifetime ?
3104 * @param string $thename ?
3106 function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
3108 global $CFG, $THEME;
3110 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
3111 $lastmodified = time();
3113 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
3114 header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
3115 header('Cache-Control: max-age='. $lifetime);
3116 header('Pragma: ');
3117 header('Content-type: text/css'); // Correct MIME type
3119 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
3121 if (empty($themename)) {
3122 $themename = current_theme(); // So we have something. Normally not needed.
3123 } else {
3124 $themename = clean_param($themename, PARAM_SAFEDIR);
3127 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
3128 unset($THEME);
3129 include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
3132 /// If this is the standard theme calling us, then find out what sheets we need
3134 if ($themename == 'standard') {
3135 if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
3136 $THEME->sheets = $DEFAULT_SHEET_LIST;
3137 } else if (empty($THEME->standardsheets)) { // We can stop right now!
3138 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3139 exit;
3140 } else { // Use the provided subset only
3141 $THEME->sheets = $THEME->standardsheets;
3144 /// If we are a parent theme, then check for parent definitions
3146 } else if (!empty($THEME->parent) && $themename == $THEME->parent) {
3147 if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have
3148 $THEME->sheets = $DEFAULT_SHEET_LIST;
3149 } else if (empty($THEME->parentsheets)) { // We can stop right now!
3150 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3151 exit;
3152 } else { // Use the provided subset only
3153 $THEME->sheets = $THEME->parentsheets;
3157 /// Work out the last modified date for this theme
3159 foreach ($THEME->sheets as $sheet) {
3160 if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
3161 $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
3162 if ($sheetmodified > $lastmodified) {
3163 $lastmodified = $sheetmodified;
3169 /// Get a list of all the files we want to include
3170 $files = array();
3172 foreach ($THEME->sheets as $sheet) {
3173 $files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
3176 if ($themename == 'standard') { // Add any standard styles included in any modules
3177 if (!empty($THEME->modsheets)) { // Search for styles.php within activity modules
3178 if ($mods = get_list_of_plugins('mod')) {
3179 foreach ($mods as $mod) {
3180 if (file_exists($CFG->dirroot.'/mod/'.$mod.'/styles.php')) {
3181 $files[] = array($CFG->dirroot, '/mod/'.$mod.'/styles.php');
3187 if (!empty($THEME->blocksheets)) { // Search for styles.php within block modules
3188 if ($mods = get_list_of_plugins('blocks')) {
3189 foreach ($mods as $mod) {
3190 if (file_exists($CFG->dirroot.'/blocks/'.$mod.'/styles.php')) {
3191 $files[] = array($CFG->dirroot, '/blocks/'.$mod.'/styles.php');
3197 if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
3198 if ($mods = get_list_of_plugins('format','',$CFG->dirroot.'/course')) {
3199 foreach ($mods as $mod) {
3200 if (file_exists($CFG->dirroot.'/course/format/'.$mod.'/styles.php')) {
3201 $files[] = array($CFG->dirroot, '/course/format/'.$mod.'/styles.php');
3207 if (!isset($THEME->gradereportsheets) || $THEME->gradereportsheets) { // Search for styles.php in grade reports
3208 if ($reports = get_list_of_plugins('grade/report')) {
3209 foreach ($reports as $report) {
3210 if (file_exists($CFG->dirroot.'/grade/report/'.$report.'/styles.php')) {
3211 $files[] = array($CFG->dirroot, '/grade/report/'.$report.'/styles.php');
3217 if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
3218 if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
3219 $files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
3224 if ($files) {
3225 /// Produce a list of all the files first
3226 echo '/**************************************'."\n";
3227 echo ' * THEME NAME: '.$themename."\n *\n";
3228 echo ' * Files included in this sheet:'."\n *\n";
3229 foreach ($files as $file) {
3230 echo ' * '.$file[1]."\n";
3232 echo ' **************************************/'."\n\n";
3235 /// check if csscobstants is set
3236 if (!empty($THEME->cssconstants)) {
3237 require_once("$CFG->libdir/cssconstants.php");
3238 /// Actually collect all the files in order.
3239 $css = '';
3240 foreach ($files as $file) {
3241 $css .= '/***** '.$file[1].' start *****/'."\n\n";
3242 $css .= file_get_contents($file[0].'/'.$file[1]);
3243 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
3245 /// replace css_constants with their values
3246 echo replace_cssconstants($css);
3247 } else {
3248 /// Actually output all the files in order.
3249 if (empty($CFG->CSSEdit) && empty($THEME->CSSEdit)) {
3250 foreach ($files as $file) {
3251 echo '/***** '.$file[1].' start *****/'."\n\n";
3252 @include_once($file[0].'/'.$file[1]);
3253 echo '/***** '.$file[1].' end *****/'."\n\n";
3255 } else {
3256 foreach ($files as $file) {
3257 echo '/* @group '.$file[1].' */'."\n\n";
3258 if (strstr($file[1], '.css') !== FALSE) {
3259 echo '@import url("'.$CFG->themewww.'/'.$file[1].'");'."\n\n";
3260 } else {
3261 @include_once($file[0].'/'.$file[1]);
3263 echo '/* @end */'."\n\n";
3269 return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
3273 function theme_setup($theme = '', $params=NULL) {
3274 /// Sets up global variables related to themes
3276 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
3278 /// Do not mess with THEME if header already printed - this would break all the extra stuff in global $THEME from print_header()!!
3279 if (defined('HEADER_PRINTED')) {
3280 return;
3283 if (empty($theme)) {
3284 $theme = current_theme();
3287 /// If the theme doesn't exist for some reason then revert to standardwhite
3288 if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
3289 $CFG->theme = $theme = 'standardwhite';
3292 /// Load up the theme config
3293 $THEME = NULL; // Just to be sure
3294 include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
3296 /// Put together the parameters
3297 if (!$params) {
3298 $params = array();
3301 if ($theme != $CFG->theme) {
3302 $params[] = 'forceconfig='.$theme;
3305 /// Force language too if required
3306 if (!empty($THEME->langsheets)) {
3307 $params[] = 'lang='.current_language();
3311 /// Convert params to string
3312 if ($params) {
3313 $paramstring = '?'.implode('&', $params);
3314 } else {
3315 $paramstring = '';
3318 /// Set up image paths
3319 if(isset($CFG->smartpix) && $CFG->smartpix==1) {
3320 if($CFG->slasharguments) { // Use this method if possible for better caching
3321 $extra='';
3322 } else {
3323 $extra='?file=';
3326 $CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
3327 $CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
3328 } else if (empty($THEME->custompix)) { // Could be set in the above file
3329 $CFG->pixpath = $CFG->wwwroot .'/pix';
3330 $CFG->modpixpath = $CFG->wwwroot .'/mod';
3331 } else {
3332 $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
3333 $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
3336 /// Header and footer paths
3337 $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
3338 $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
3340 /// Define stylesheet loading order
3341 $CFG->stylesheets = array();
3342 if ($theme != 'standard') { /// The standard sheet is always loaded first
3343 $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
3345 if (!empty($THEME->parent)) { /// Parent stylesheets are loaded next
3346 $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
3348 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
3350 /// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
3351 if (!empty($HTTPSPAGEREQUIRED)) {
3352 $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
3353 $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
3354 $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
3355 foreach ($CFG->stylesheets as $key => $stylesheet) {
3356 $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
3360 // RTL support - only for RTL languages, add RTL CSS
3361 if (get_string('thisdirection') == 'rtl') {
3362 $CFG->stylesheets[] = $CFG->themewww.'/standard/rtl.css'.$paramstring;
3363 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/rtl.css'.$paramstring;
3369 * Returns text to be displayed to the user which reflects their login status
3371 * @uses $CFG
3372 * @uses $USER
3373 * @param course $course {@link $COURSE} object containing course information
3374 * @param user $user {@link $USER} object containing user information
3375 * @return string
3377 function user_login_string($course=NULL, $user=NULL) {
3378 global $USER, $CFG, $SITE;
3380 if (empty($user) and !empty($USER->id)) {
3381 $user = $USER;
3384 if (empty($course)) {
3385 $course = $SITE;
3388 if (!empty($user->realuser)) {
3389 if ($realuser = get_record('user', 'id', $user->realuser)) {
3390 $fullname = fullname($realuser, true);
3391 $realuserinfo = " [<a $CFG->frametarget
3392 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=1&amp;sesskey=".sesskey()."\">$fullname</a>] ";
3394 } else {
3395 $realuserinfo = '';
3398 if (empty($CFG->loginhttps)) {
3399 $wwwroot = $CFG->wwwroot;
3400 } else {
3401 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
3404 if (empty($course->id)) {
3405 // $course->id is not defined during installation
3406 return '';
3407 } else if (!empty($user->id)) {
3408 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3410 $fullname = fullname($user, true);
3411 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a>";
3412 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid)) {
3413 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
3415 if (isset($user->username) && $user->username == 'guest') {
3416 $loggedinas = $realuserinfo.get_string('loggedinasguest').
3417 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3418 } else if (!empty($user->access['rsw'][$context->path])) {
3419 $rolename = '';
3420 if ($role = get_record('role', 'id', $user->access['rsw'][$context->path])) {
3421 $rolename = ': '.format_string($role->name);
3423 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
3424 " (<a $CFG->frametarget
3425 href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
3426 } else {
3427 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
3428 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
3430 } else {
3431 $loggedinas = get_string('loggedinnot', 'moodle').
3432 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3434 return '<div class="logininfo">'.$loggedinas.'</div>';
3438 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
3439 * If not it applies sensible defaults.
3441 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
3442 * search forum block, etc. Important: these are 'silent' in a screen-reader
3443 * (unlike &gt; &raquo;), and must be accompanied by text.
3444 * @uses $THEME
3446 function check_theme_arrows() {
3447 global $THEME;
3449 if (!isset($THEME->rarrow) and !isset($THEME->larrow)) {
3450 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
3451 // Also OK in Win 9x/2K/IE 5.x
3452 $THEME->rarrow = '&#x25BA;';
3453 $THEME->larrow = '&#x25C4;';
3454 $uagent = $_SERVER['HTTP_USER_AGENT'];
3455 if (false !== strpos($uagent, 'Opera')
3456 || false !== strpos($uagent, 'Mac')) {
3457 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
3458 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
3459 $THEME->rarrow = '&#x25B6;';
3460 $THEME->larrow = '&#x25C0;';
3462 elseif (false !== strpos($uagent, 'Konqueror')) {
3463 $THEME->rarrow = '&rarr;';
3464 $THEME->larrow = '&larr;';
3466 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
3467 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
3468 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
3469 // To be safe, non-Unicode browsers!
3470 $THEME->rarrow = '&gt;';
3471 $THEME->larrow = '&lt;';
3474 /// RTL support - in RTL languages, swap r and l arrows
3475 if (right_to_left()) {
3476 $t = $THEME->rarrow;
3477 $THEME->rarrow = $THEME->larrow;
3478 $THEME->larrow = $t;
3485 * Return the right arrow with text ('next'), and optionally embedded in a link.
3486 * See function above, check_theme_arrows.
3487 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3488 * @param string $url An optional link to use in a surrounding HTML anchor.
3489 * @param bool $accesshide True if text should be hidden (for screen readers only).
3490 * @param string $addclass Additional class names for the link, or the arrow character.
3491 * @return string HTML string.
3493 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
3494 global $THEME;
3495 check_theme_arrows();
3496 $arrowclass = 'arrow ';
3497 if (! $url) {
3498 $arrowclass .= $addclass;
3500 $arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow.'</span>';
3501 $htmltext = '';
3502 if ($text) {
3503 $htmltext = $text.'&nbsp;';
3504 if ($accesshide) {
3505 $htmltext = get_accesshide($htmltext);
3508 if ($url) {
3509 $class = '';
3510 if ($addclass) {
3511 $class =" class=\"$addclass\"";
3513 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
3515 return $htmltext.$arrow;
3519 * Return the left arrow with text ('previous'), and optionally embedded in a link.
3520 * See function above, check_theme_arrows.
3521 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3522 * @param string $url An optional link to use in a surrounding HTML anchor.
3523 * @param bool $accesshide True if text should be hidden (for screen readers only).
3524 * @param string $addclass Additional class names for the link, or the arrow character.
3525 * @return string HTML string.
3527 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
3528 global $THEME;
3529 check_theme_arrows();
3530 $arrowclass = 'arrow ';
3531 if (! $url) {
3532 $arrowclass .= $addclass;
3534 $arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow.'</span>';
3535 $htmltext = '';
3536 if ($text) {
3537 $htmltext = '&nbsp;'.$text;
3538 if ($accesshide) {
3539 $htmltext = get_accesshide($htmltext);
3542 if ($url) {
3543 $class = '';
3544 if ($addclass) {
3545 $class =" class=\"$addclass\"";
3547 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
3549 return $arrow.$htmltext;
3553 * Return a HTML element with the class "accesshide", for accessibility.
3554 * Please use cautiously - where possible, text should be visible!
3555 * @param string $text Plain text.
3556 * @param string $elem Lowercase element name, default "span".
3557 * @param string $class Additional classes for the element.
3558 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
3559 * @return string HTML string.
3561 function get_accesshide($text, $elem='span', $class='', $attrs='') {
3562 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
3566 * Return the breadcrumb trail navigation separator.
3567 * @return string HTML string.
3569 function get_separator() {
3570 //Accessibility: the 'hidden' slash is preferred for screen readers.
3571 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
3575 * Prints breadcrumb trail of links, called in theme/-/header.html
3577 * @uses $CFG
3578 * @param mixed $navigation The breadcrumb navigation string to be printed
3579 * @param string $separator The breadcrumb trail separator. The default 0 leads to the use
3580 * of $THEME->rarrow, themes could use '&rarr;', '/', or '' for a style-sheet solution.
3581 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
3583 function print_navigation ($navigation, $separator=0, $return=false) {
3584 global $CFG, $THEME;
3585 $output = '';
3587 if (0 === $separator) {
3588 $separator = get_separator();
3590 else {
3591 $separator = '<span class="sep">'. $separator .'</span>';
3594 if ($navigation) {
3596 if (is_newnav($navigation)) {
3597 if ($return) {
3598 return($navigation['navlinks']);
3599 } else {
3600 echo $navigation['navlinks'];
3601 return;
3603 } else {
3604 debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER);
3607 if (!is_array($navigation)) {
3608 $ar = explode('->', $navigation);
3609 $navigation = array();
3611 foreach ($ar as $a) {
3612 if (strpos($a, '</a>') === false) {
3613 $navigation[] = array('title' => $a, 'url' => '');
3614 } else {
3615 if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
3616 $navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
3622 if (! $site = get_site()) {
3623 $site = new object();
3624 $site->shortname = get_string('home');
3627 //Accessibility: breadcrumb links now in a list, &raquo; replaced with a 'silent' character.
3628 $output .= get_accesshide(get_string('youarehere','access'), 'h2')."<ul>\n";
3630 $output .= '<li class="first">'."\n".'<a '.$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3631 .$CFG->wwwroot.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))
3632 && !empty($USER->id) && !empty($CFG->mymoodleredirect) && !isguest())
3633 ? '/my' : '') .'/">'. format_string($site->shortname) ."</a>\n</li>\n";
3636 foreach ($navigation as $navitem) {
3637 $title = trim(strip_tags(format_string($navitem['title'], false)));
3638 $url = $navitem['url'];
3640 if (empty($url)) {
3641 $output .= '<li class="first">'."$separator $title</li>\n";
3642 } else {
3643 $output .= '<li class="first">'."$separator\n<a ".$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3644 .$url.'">'."$title</a>\n</li>\n";
3648 $output .= "</ul>\n";
3651 if ($return) {
3652 return $output;
3653 } else {
3654 echo $output;
3659 * This function will build the navigation string to be used by print_header
3660 * and others.
3662 * It automatically generates the site and course level (if appropriate) links.
3664 * If you pass in a $cm object, the method will also generate the activity (e.g. 'Forums')
3665 * and activityinstances (e.g. 'General Developer Forum') navigation levels.
3667 * If you want to add any further navigation links after the ones this function generates,
3668 * the pass an array of extra link arrays like this:
3669 * array(
3670 * array('name' => $linktext1, 'link' => $url1, 'type' => $linktype1),
3671 * array('name' => $linktext2, 'link' => $url2, 'type' => $linktype2)
3673 * The normal case is to just add one further link, for example 'Editing forum' after
3674 * 'General Developer Forum', with no link.
3675 * To do that, you need to pass
3676 * array(array('name' => $linktext, 'link' => '', 'type' => 'title'))
3677 * However, becuase this is a very common case, you can use a shortcut syntax, and just
3678 * pass the string 'Editing forum', instead of an array as $extranavlinks.
3680 * At the moment, the link types only have limited significance. Type 'activity' is
3681 * recognised in order to implement the $CFG->hideactivitytypenavlink feature. Types
3682 * that are known to appear are 'home', 'course', 'activity', 'activityinstance' and 'title'.
3683 * This really needs to be documented better. In the mean time, try to be consistent, it will
3684 * enable people to customise the navigation more in future.
3686 * When passing a $cm object, the fields used are $cm->modname, $cm->name and $cm->course.
3687 * If you get the $cm object using the function get_coursemodule_from_instance or
3688 * get_coursemodule_from_id (as recommended) then this will be done for you automatically.
3689 * If you don't have $cm->modname or $cm->name, this fuction will attempt to find them using
3690 * the $cm->module and $cm->instance fields, but this takes extra database queries, so a
3691 * warning is printed in developer debug mode.
3693 * @uses $CFG
3694 * @uses $THEME
3696 * @param mixed $extranavlinks - Normally an array of arrays, keys: name, link, type. If you
3697 * only want one extra item with no link, you can pass a string instead. If you don't want
3698 * any extra links, pass an empty string.
3699 * @param mixed $cm - optionally the $cm object, if you want this function to generate the
3700 * activity and activityinstance levels of navigation too.
3702 * @return $navigation as an object so it can be differentiated from old style
3703 * navigation strings.
3705 function build_navigation($extranavlinks, $cm = null) {
3706 global $CFG, $COURSE;
3708 if (is_string($extranavlinks)) {
3709 if ($extranavlinks == '') {
3710 $extranavlinks = array();
3711 } else {
3712 $extranavlinks = array(array('name' => $extranavlinks, 'link' => '', 'type' => 'title'));
3716 $navlinks = array();
3718 //Site name
3719 if ($site = get_site()) {
3720 $navlinks[] = array(
3721 'name' => format_string($site->shortname),
3722 'link' => "$CFG->wwwroot/",
3723 'type' => 'home');
3726 // Course name, if appropriate.
3727 if (isset($COURSE) && $COURSE->id != SITEID) {
3728 $navlinks[] = array(
3729 'name' => format_string($COURSE->shortname),
3730 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",
3731 'type' => 'course');
3734 // Activity type and instance, if appropriate.
3735 if (is_object($cm)) {
3736 if (!isset($cm->modname)) {
3737 debugging('The field $cm->modname should be set if you call build_navigation with '.
3738 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3739 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
3740 if (!$cm->modname = get_field('modules', 'name', 'id', $cm->module)) {
3741 error('Cannot get the module type in build navigation.');
3744 if (!isset($cm->name)) {
3745 debugging('The field $cm->name should be set if you call build_navigation with '.
3746 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3747 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
3748 if (!$cm->name = get_field($cm->modname, 'name', 'id', $cm->instance)) {
3749 error('Cannot get the module name in build navigation.');
3752 $navlinks[] = array(
3753 'name' => get_string('modulenameplural', $cm->modname),
3754 'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/index.php?id=' . $cm->course,
3755 'type' => 'activity');
3756 $navlinks[] = array(
3757 'name' => format_string($cm->name),
3758 'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/view.php?id=' . $cm->id,
3759 'type' => 'activityinstance');
3762 //Merge in extra navigation links
3763 $navlinks = array_merge($navlinks, $extranavlinks);
3765 // Work out whether we should be showing the activity (e.g. Forums) link.
3766 // Note: build_navigation() is called from many places --
3767 // install & upgrade for example -- where we cannot count on the
3768 // roles infrastructure to be defined. Hence the $CFG->rolesactive check.
3769 if (!isset($CFG->hideactivitytypenavlink)) {
3770 $CFG->hideactivitytypenavlink = 0;
3772 if ($CFG->hideactivitytypenavlink == 2) {
3773 $hideactivitylink = true;
3774 } else if ($CFG->hideactivitytypenavlink == 1 && $CFG->rolesactive &&
3775 !empty($COURSE->id) && $COURSE->id != SITEID) {
3776 if (!isset($COURSE->context)) {
3777 $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
3779 $hideactivitylink = !has_capability('moodle/course:manageactivities', $COURSE->context);
3780 } else {
3781 $hideactivitylink = false;
3784 //Construct an unordered list from $navlinks
3785 //Accessibility: heading hidden from visual browsers by default.
3786 $navigation = get_accesshide(get_string('youarehere','access'), 'h2')." <ul>\n";
3787 $lastindex = count($navlinks) - 1;
3788 $i = -1; // Used to count the times, so we know when we get to the last item.
3789 $first = true;
3790 foreach ($navlinks as $navlink) {
3791 $i++;
3792 $last = ($i == $lastindex);
3793 if (!is_array($navlink)) {
3794 continue;
3796 if ($navlink['type'] == 'activity' && !$last && $hideactivitylink) {
3797 continue;
3799 $navigation .= '<li class="first">';
3800 if (!$first) {
3801 $navigation .= get_separator();
3803 if ((!empty($navlink['link'])) && !$last) {
3804 $navigation .= "<a onclick=\"this.target='$CFG->framename'\" href=\"{$navlink['link']}\">";
3806 $navigation .= "{$navlink['name']}";
3807 if ((!empty($navlink['link'])) && !$last) {
3808 $navigation .= "</a>";
3811 $navigation .= "</li>";
3812 $first = false;
3814 $navigation .= "</ul>";
3816 return(array('newnav' => true, 'navlinks' => $navigation));
3821 * Prints a string in a specified size (retained for backward compatibility)
3823 * @param string $text The text to be displayed
3824 * @param int $size The size to set the font for text display.
3826 function print_headline($text, $size=2, $return=false) {
3827 $output = print_heading($text, '', $size, true);
3828 if ($return) {
3829 return $output;
3830 } else {
3831 echo $output;
3836 * Prints text in a format for use in headings.
3838 * @param string $text The text to be displayed
3839 * @param string $align The alignment of the printed paragraph of text
3840 * @param int $size The size to set the font for text display.
3842 function print_heading($text, $align='', $size=2, $class='main', $return=false) {
3843 if ($align) {
3844 $align = ' style="text-align:'.$align.';"';
3846 if ($class) {
3847 $class = ' class="'.$class.'"';
3849 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
3851 if ($return) {
3852 return $output;
3853 } else {
3854 echo $output;
3859 * Centered heading with attached help button (same title text)
3860 * and optional icon attached
3862 * @param string $text The text to be displayed
3863 * @param string $helppage The help page to link to
3864 * @param string $module The module whose help should be linked to
3865 * @param string $icon Image to display if needed
3867 function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
3868 $output = '';
3869 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
3870 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
3871 $output .= '</h2>';
3873 if ($return) {
3874 return $output;
3875 } else {
3876 echo $output;
3881 function print_heading_block($heading, $class='', $return=false) {
3882 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
3883 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
3885 if ($return) {
3886 return $output;
3887 } else {
3888 echo $output;
3894 * Print a link to continue on to another page.
3896 * @uses $CFG
3897 * @param string $link The url to create a link to.
3899 function print_continue($link, $return=false) {
3901 global $CFG;
3903 // in case we are logging upgrade in admin/index.php stop it
3904 if (function_exists('upgrade_log_finish')) {
3905 upgrade_log_finish();
3908 $output = '';
3910 if ($link == '') {
3911 if (!empty($_SERVER['HTTP_REFERER'])) {
3912 $link = $_SERVER['HTTP_REFERER'];
3913 $link = str_replace('&', '&amp;', $link); // make it valid XHTML
3914 } else {
3915 $link = $CFG->wwwroot .'/';
3919 $options = array();
3920 $linkparts = parse_url(str_replace('&amp;', '&', $link));
3921 if (isset($linkparts['query'])) {
3922 parse_str($linkparts['query'], $options);
3925 $output .= '<div class="continuebutton">';
3927 $output .= print_single_button($link, $options, get_string('continue'), 'get', $CFG->framename, true);
3928 $output .= '</div>'."\n";
3930 if ($return) {
3931 return $output;
3932 } else {
3933 echo $output;
3939 * Print a message in a standard themed box.
3940 * Replaces print_simple_box (see deprecatedlib.php)
3942 * @param string $message, the content of the box
3943 * @param string $classes, space-separated class names.
3944 * @param string $idbase
3945 * @param boolean $return, return as string or just print it
3946 * @return mixed string or void
3948 function print_box($message, $classes='generalbox', $ids='', $return=false) {
3950 $output = print_box_start($classes, $ids, true);
3951 $output .= stripslashes_safe($message);
3952 $output .= print_box_end(true);
3954 if ($return) {
3955 return $output;
3956 } else {
3957 echo $output;
3962 * Starts a box using divs
3963 * Replaces print_simple_box_start (see deprecatedlib.php)
3965 * @param string $classes, space-separated class names.
3966 * @param string $idbase
3967 * @param boolean $return, return as string or just print it
3968 * @return mixed string or void
3970 function print_box_start($classes='generalbox', $ids='', $return=false) {
3971 global $THEME;
3973 if (strpos($classes, 'clearfix') !== false) {
3974 $clearfix = true;
3975 $classes = trim(str_replace('clearfix', '', $classes));
3976 } else {
3977 $clearfix = false;
3980 if (!empty($THEME->customcorners)) {
3981 $classes .= ' ccbox box';
3982 } else {
3983 $classes .= ' box';
3986 return print_container_start($clearfix, $classes, $ids, $return);
3990 * Simple function to end a box (see above)
3991 * Replaces print_simple_box_end (see deprecatedlib.php)
3993 * @param boolean $return, return as string or just print it
3995 function print_box_end($return=false) {
3996 return print_container_end($return);
4000 * Print a message in a standard themed container.
4002 * @param string $message, the content of the container
4003 * @param boolean $clearfix clear both sides
4004 * @param string $classes, space-separated class names.
4005 * @param string $idbase
4006 * @param boolean $return, return as string or just print it
4007 * @return string or void
4009 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
4011 $output = print_container_start($clearfix, $classes, $idbase, true);
4012 $output .= stripslashes_safe($message);
4013 $output .= print_container_end(true);
4015 if ($return) {
4016 return $output;
4017 } else {
4018 echo $output;
4023 * Starts a container using divs
4025 * @param boolean $clearfix clear both sides
4026 * @param string $classes, space-separated class names.
4027 * @param string $idbase
4028 * @param boolean $return, return as string or just print it
4029 * @return mixed string or void
4031 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
4032 global $THEME;
4034 if (!isset($THEME->open_containers)) {
4035 $THEME->open_containers = array();
4037 $THEME->open_containers[] = $idbase;
4040 if (!empty($THEME->customcorners)) {
4041 $output = _print_custom_corners_start($clearfix, $classes, $idbase);
4042 } else {
4043 if ($idbase) {
4044 $id = ' id="'.$idbase.'"';
4045 } else {
4046 $id = '';
4048 if ($clearfix) {
4049 $clearfix = ' clearfix';
4050 } else {
4051 $clearfix = '';
4053 if ($classes or $clearfix) {
4054 $class = ' class="'.$classes.$clearfix.'"';
4055 } else {
4056 $class = '';
4058 $output = '<div'.$id.$class.'>';
4061 if ($return) {
4062 return $output;
4063 } else {
4064 echo $output;
4069 * Simple function to end a container (see above)
4070 * @param boolean $return, return as string or just print it
4071 * @return mixed string or void
4073 function print_container_end($return=false) {
4074 global $THEME;
4076 if (empty($THEME->open_containers)) {
4077 debugging('Incorrect request to end container - no more open containers.', DEBUG_DEVELOPER);
4078 $idbase = '';
4079 } else {
4080 $idbase = array_pop($THEME->open_containers);
4083 if (!empty($THEME->customcorners)) {
4084 $output = _print_custom_corners_end($idbase);
4085 } else {
4086 $output = '</div>';
4089 if ($return) {
4090 return $output;
4091 } else {
4092 echo $output;
4097 * Returns number of currently open containers
4098 * @return int number of open containers
4100 function open_containers() {
4101 global $THEME;
4103 if (!isset($THEME->open_containers)) {
4104 $THEME->open_containers = array();
4107 return count($THEME->open_containers);
4111 * Force closing of open containers
4112 * @param boolean $return, return as string or just print it
4113 * @param int $keep number of containers to be kept open - usually theme or page containers
4114 * @return mixed string or void
4116 function print_container_end_all($return=false, $keep=0) {
4117 $output = '';
4118 while (open_containers() > $keep) {
4119 $output .= print_container_end($return);
4122 if ($return) {
4123 return $output;
4124 } else {
4125 echo $output;
4130 * Internal function - do not use directly!
4131 * Starting part of the surrounding divs for custom corners
4133 * @param boolean $clearfix, add CLASS "clearfix" to the inner div against collapsing
4134 * @param string $classes
4135 * @param mixed $idbase, optionally, define one idbase to be added to all the elements in the corners
4136 * @return string
4138 function _print_custom_corners_start($clearfix=false, $classes='', $idbase='') {
4139 /// Analise if we want ids for the custom corner elements
4140 $id = '';
4141 $idbt = '';
4142 $idi1 = '';
4143 $idi2 = '';
4144 $idi3 = '';
4146 if ($idbase) {
4147 $id = 'id="'.$idbase.'" ';
4148 $idbt = 'id="'.$idbase.'-bt" ';
4149 $idi1 = 'id="'.$idbase.'-i1" ';
4150 $idi2 = 'id="'.$idbase.'-i2" ';
4151 $idi3 = 'id="'.$idbase.'-i3" ';
4154 /// Calculate current level
4155 $level = open_containers();
4157 /// Output begins
4158 $output = '<div '.$id.'class="wrap wraplevel'.$level.' '.$classes.'">'."\n";
4159 $output .= '<div '.$idbt.'class="bt"><div>&nbsp;</div></div>';
4160 $output .= "\n";
4161 $output .= '<div '.$idi1.'class="i1"><div '.$idi2.'class="i2">';
4162 $output .= (!empty($clearfix)) ? '<div '.$idi3.'class="i3 clearfix">' : '<div '.$idi3.'class="i3">';
4164 return $output;
4169 * Internal function - do not use directly!
4170 * Ending part of the surrounding divs for custom corners
4171 * @param string $idbase
4172 * @return string
4174 function _print_custom_corners_end($idbase) {
4175 /// Analise if we want ids for the custom corner elements
4176 $idbb = '';
4178 if ($idbase) {
4179 $idbb = 'id="' . $idbase . '-bb" ';
4182 /// Output begins
4183 $output = '</div></div></div>';
4184 $output .= "\n";
4185 $output .= '<div '.$idbb.'class="bb"><div>&nbsp;</div></div>'."\n";
4186 $output .= '</div>';
4188 return $output;
4193 * Print a self contained form with a single submit button.
4195 * @param string $link used as the action attribute on the form, so the URL that will be hit if the button is clicked.
4196 * @param array $options these become hidden form fields, so these options get passed to the script at $link.
4197 * @param string $label the caption that appears on the button.
4198 * @param string $method HTTP method used on the request of the button is clicked. 'get' or 'post'.
4199 * @param string $target no longer used.
4200 * @param boolean $return if false, output the form directly, otherwise return the HTML as a string.
4201 * @param string $tooltip a tooltip to add to the button as a title attribute.
4202 * @param boolean $disabled if true, the button will be disabled.
4203 * @param string $jsconfirmmessage if not empty then display a confirm dialogue with this string as the question.
4204 * @return string / nothing depending on the $return paramter.
4206 function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='', $disabled = false, $jsconfirmmessage='') {
4207 $output = '';
4208 $link = str_replace('"', '&quot;', $link); //basic XSS protection
4209 $output .= '<div class="singlebutton">';
4210 // taking target out, will need to add later target="'.$target.'"
4211 $output .= '<form action="'. $link .'" method="'. $method .'">';
4212 $output .= '<div>';
4213 if ($options) {
4214 foreach ($options as $name => $value) {
4215 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
4218 if ($tooltip) {
4219 $tooltip = 'title="' . s($tooltip) . '"';
4220 } else {
4221 $tooltip = '';
4223 if ($disabled) {
4224 $disabled = 'disabled="disabled"';
4225 } else {
4226 $disabled = '';
4228 if ($jsconfirmmessage){
4229 $jsconfirmmessage = addslashes_js($jsconfirmmessage);
4230 $jsconfirmmessage = 'onclick="return confirm(\''. $jsconfirmmessage .'\');" ';
4232 $output .= '<input type="submit" value="'. s($label) ."\" $tooltip $disabled $jsconfirmmessage/></div></form></div>";
4234 if ($return) {
4235 return $output;
4236 } else {
4237 echo $output;
4243 * Print a spacer image with the option of including a line break.
4245 * @param int $height ?
4246 * @param int $width ?
4247 * @param boolean $br ?
4248 * @todo Finish documenting this function
4250 function print_spacer($height=1, $width=1, $br=true, $return=false) {
4251 global $CFG;
4252 $output = '';
4254 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot .'/pix/spacer.gif" alt="" />';
4255 if ($br) {
4256 $output .= '<br />'."\n";
4259 if ($return) {
4260 return $output;
4261 } else {
4262 echo $output;
4267 * Given the path to a picture file in a course, or a URL,
4268 * this function includes the picture in the page.
4270 * @param string $path ?
4271 * @param int $courseid ?
4272 * @param int $height ?
4273 * @param int $width ?
4274 * @param string $link ?
4275 * @todo Finish documenting this function
4277 function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
4278 global $CFG;
4279 $output = '';
4281 if ($height) {
4282 $height = 'height="'. $height .'"';
4284 if ($width) {
4285 $width = 'width="'. $width .'"';
4287 if ($link) {
4288 $output .= '<a href="'. $link .'">';
4290 if (substr(strtolower($path), 0, 7) == 'http://') {
4291 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
4293 } else if ($courseid) {
4294 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
4295 if ($CFG->slasharguments) { // Use this method if possible for better caching
4296 $output .= $CFG->wwwroot .'/file.php/'. $courseid .'/'. $path;
4297 } else {
4298 $output .= $CFG->wwwroot .'/file.php?file=/'. $courseid .'/'. $path;
4300 $output .= '" />';
4301 } else {
4302 $output .= 'Error: must pass URL or course';
4304 if ($link) {
4305 $output .= '</a>';
4308 if ($return) {
4309 return $output;
4310 } else {
4311 echo $output;
4316 * Print the specified user's avatar.
4318 * If you pass a $user object that has id, picture, imagealt, firstname, lastname
4319 * you save a DB query.
4321 * @param int $user takes a userid, or a userobj
4322 * @param int $courseid ?
4323 * @param boolean $picture Print the user picture?
4324 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
4325 * @param boolean $return If false print picture to current page, otherwise return the output as string
4326 * @param boolean $link Enclose printed image in a link to view specified course?
4327 * @param string $target link target attribute
4328 * @param boolean $alttext use username or userspecified text in image alt attribute
4329 * return string
4330 * @todo Finish documenting this function
4332 function print_user_picture($user, $courseid, $picture=NULL, $size=0, $return=false, $link=true, $target='', $alttext=true) {
4333 global $CFG, $HTTPSPAGEREQUIRED;
4335 $needrec = false;
4336 // only touch the DB if we are missing data...
4337 if (is_object($user)) {
4338 // Note - both picture and imagealt _can_ be empty
4339 // what we are trying to see here is if they have been fetched
4340 // from the DB. We should use isset() _except_ that some installs
4341 // have those fields as nullable, and isset() will return false
4342 // on null. The only safe thing is to ask array_key_exists()
4343 // which works on objects. property_exists() isn't quite
4344 // what we want here...
4345 if (! (array_key_exists('picture', $user)
4346 && ($alttext && array_key_exists('imagealt', $user)
4347 || (isset($user->firstname) && isset($user->lastname)))) ) {
4348 $needrec = true;
4349 $user = $user->id;
4351 } else {
4352 if ($alttext) {
4353 // we need firstname, lastname, imagealt, can't escape...
4354 $needrec = true;
4355 } else {
4356 $userobj = new StdClass; // fake it to save DB traffic
4357 $userobj->id = $user;
4358 $userobj->picture = $picture;
4359 $user = clone($userobj);
4360 unset($userobj);
4363 if ($needrec) {
4364 $user = get_record('user','id',$user, '', '', '', '', 'id,firstname,lastname,imagealt');
4367 if ($link) {
4368 $url = '/user/view.php?id='. $user->id .'&amp;course='. $courseid ;
4369 if ($target) {
4370 $target='onclick="return openpopup(\''.$url.'\');"';
4372 $output = '<a '.$target.' href="'. $CFG->wwwroot . $url .'">';
4373 } else {
4374 $output = '';
4376 if (empty($size)) {
4377 $file = 'f2';
4378 $size = 35;
4379 } else if ($size === true or $size == 1) {
4380 $file = 'f1';
4381 $size = 100;
4382 } else if ($size >= 50) {
4383 $file = 'f1';
4384 } else {
4385 $file = 'f2';
4387 $class = "userpicture";
4388 if (!empty($HTTPSPAGEREQUIRED)) {
4389 $wwwroot = $CFG->httpswwwroot;
4390 } else {
4391 $wwwroot = $CFG->wwwroot;
4394 if (is_null($picture)) {
4395 $picture = $user->picture;
4398 if ($picture) { // Print custom user picture
4399 if ($CFG->slasharguments) { // Use this method if possible for better caching
4400 $src = $wwwroot .'/user/pix.php/'. $user->id .'/'. $file .'.jpg';
4401 } else {
4402 $src = $wwwroot .'/user/pix.php?file=/'. $user->id .'/'. $file .'.jpg';
4404 } else { // Print default user pictures (use theme version if available)
4405 $class .= " defaultuserpic";
4406 $src = "$CFG->pixpath/u/$file.png";
4408 $imagealt = '';
4409 if ($alttext) {
4410 if (!empty($user->imagealt)) {
4411 $imagealt = $user->imagealt;
4412 } else {
4413 $imagealt = get_string('pictureof','',fullname($user));
4417 $output .= '<img class="'.$class.'" src="'.$src.'" alt="'.s($imagealt).'" />';
4418 if ($link) {
4419 $output .= '</a>';
4422 if ($return) {
4423 return $output;
4424 } else {
4425 echo $output;
4430 * Prints a summary of a user in a nice little box.
4432 * @uses $CFG
4433 * @uses $USER
4434 * @param user $user A {@link $USER} object representing a user
4435 * @param course $course A {@link $COURSE} object representing a course
4437 function print_user($user, $course, $messageselect=false, $return=false) {
4439 global $CFG, $USER;
4441 $output = '';
4443 static $string;
4444 static $datestring;
4445 static $countries;
4447 $context = get_context_instance(CONTEXT_COURSE, $course->id);
4448 if (isset($user->context->id)) {
4449 $usercontext = get_context_instance_by_id($user->context->id);
4452 if (empty($string)) { // Cache all the strings for the rest of the page
4454 $string->email = get_string('email');
4455 $string->city = get_string('city');
4456 $string->lastaccess = get_string('lastaccess');
4457 $string->activity = get_string('activity');
4458 $string->unenrol = get_string('unenrol');
4459 $string->loginas = get_string('loginas');
4460 $string->fullprofile = get_string('fullprofile');
4461 $string->role = get_string('role');
4462 $string->name = get_string('name');
4463 $string->never = get_string('never');
4465 $datestring->day = get_string('day');
4466 $datestring->days = get_string('days');
4467 $datestring->hour = get_string('hour');
4468 $datestring->hours = get_string('hours');
4469 $datestring->min = get_string('min');
4470 $datestring->mins = get_string('mins');
4471 $datestring->sec = get_string('sec');
4472 $datestring->secs = get_string('secs');
4473 $datestring->year = get_string('year');
4474 $datestring->years = get_string('years');
4476 $countries = get_list_of_countries();
4479 /// Get the hidden field list
4480 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
4481 $hiddenfields = array();
4482 } else {
4483 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
4486 $output .= '<table class="userinfobox">';
4487 $output .= '<tr>';
4488 $output .= '<td class="left side">';
4489 $output .= print_user_picture($user, $course->id, $user->picture, true, true);
4490 $output .= '</td>';
4491 $output .= '<td class="content">';
4492 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
4493 $output .= '<div class="info">';
4494 if (!empty($user->role) and ($user->role <> $course->teacher)) {
4495 $output .= $string->role .': '. $user->role .'<br />';
4497 if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguest()) or
4498 has_capability('moodle/course:viewhiddenuserfields', $context)) {
4499 $output .= $string->email .': <a href="mailto:'. $user->email .'">'. $user->email .'</a><br />';
4501 if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
4502 $output .= $string->city .': ';
4503 if ($user->city && !isset($hiddenfields['city'])) {
4504 $output .= $user->city;
4506 if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
4507 if ($user->city && !isset($hiddenfields['city'])) {
4508 $output .= ', ';
4510 $output .= $countries[$user->country];
4512 $output .= '<br />';
4515 if (!isset($hiddenfields['lastaccess'])) {
4516 if ($user->lastaccess) {
4517 $output .= $string->lastaccess .': '. userdate($user->lastaccess);
4518 $output .= '&nbsp; ('. format_time(time() - $user->lastaccess, $datestring) .')';
4519 } else {
4520 $output .= $string->lastaccess .': '. $string->never;
4523 $output .= '</div></td><td class="links">';
4524 //link to blogs
4525 if ($CFG->bloglevel > 0) {
4526 $output .= '<a href="'.$CFG->wwwroot.'/blog/index.php?userid='.$user->id.'">'.get_string('blogs','blog').'</a><br />';
4528 //link to notes
4529 if (has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context)) {
4530 $output .= '<a href="'.$CFG->wwwroot.'/notes/index.php?course=' . $course->id. '&amp;user='.$user->id.'">'.get_string('notes','notes').'</a><br />';
4533 if (has_capability('moodle/user:viewuseractivitiesreport', $context) || (isset($usercontext) && has_capability('moodle/user:viewuseractivitiesreport', $usercontext))) {
4534 $timemidnight = usergetmidnight(time());
4535 $output .= '<a href="'. $CFG->wwwroot .'/course/user.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->activity .'</a><br />';
4537 if (has_capability('moodle/role:assign', $context, NULL)) { // Includes admins
4538 $output .= '<a href="'. $CFG->wwwroot .'/course/unenrol.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->unenrol .'</a><br />';
4540 if ($USER->id != $user->id && empty($USER->realuser) && has_capability('moodle/user:loginas', $context) &&
4541 ! has_capability('moodle/site:doanything', $context, $user->id, false)) {
4542 $output .= '<a href="'. $CFG->wwwroot .'/course/loginas.php?id='. $course->id .'&amp;user='. $user->id .'&amp;sesskey='. sesskey() .'">'. $string->loginas .'</a><br />';
4544 $output .= '<a href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&amp;course='. $course->id .'">'. $string->fullprofile .'...</a>';
4546 if (!empty($messageselect)) {
4547 $output .= '<br /><input type="checkbox" name="user'.$user->id.'" /> ';
4550 $output .= '</td></tr></table>';
4552 if ($return) {
4553 return $output;
4554 } else {
4555 echo $output;
4560 * Print a specified group's avatar.
4562 * @param group $group A single {@link group} object OR array of groups.
4563 * @param int $courseid The course ID.
4564 * @param boolean $large Default small picture, or large.
4565 * @param boolean $return If false print picture, otherwise return the output as string
4566 * @param boolean $link Enclose image in a link to view specified course?
4567 * @return string
4568 * @todo Finish documenting this function
4570 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
4571 global $CFG;
4573 if (is_array($group)) {
4574 $output = '';
4575 foreach($group as $g) {
4576 $output .= print_group_picture($g, $courseid, $large, true, $link);
4578 if ($return) {
4579 return $output;
4580 } else {
4581 echo $output;
4582 return;
4586 $context = get_context_instance(CONTEXT_COURSE, $courseid);
4588 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
4589 return '';
4592 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4593 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
4594 } else {
4595 $output = '';
4597 if ($large) {
4598 $file = 'f1';
4599 $size = 100;
4600 } else {
4601 $file = 'f2';
4602 $size = 35;
4604 if ($group->picture) { // Print custom group picture
4605 if ($CFG->slasharguments) { // Use this method if possible for better caching
4606 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot.'/user/pixgroup.php/'.$group->id.'/'.$file.'.jpg"'.
4607 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
4608 } else {
4609 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot.'/user/pixgroup.php?file=/'.$group->id.'/'.$file.'.jpg"'.
4610 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
4613 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4614 $output .= '</a>';
4617 if ($return) {
4618 return $output;
4619 } else {
4620 echo $output;
4625 * Print a png image.
4627 * @param string $url ?
4628 * @param int $sizex ?
4629 * @param int $sizey ?
4630 * @param boolean $return ?
4631 * @param string $parameters ?
4632 * @todo Finish documenting this function
4634 function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
4635 global $CFG;
4636 static $recentIE;
4638 if (!isset($recentIE)) {
4639 $recentIE = check_browser_version('MSIE', '5.0');
4642 if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
4643 $output .= '<img src="'. $CFG->pixpath .'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
4644 ' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
4645 ' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
4646 "'$url', sizingMethod='scale') ".
4647 ' '. $parameters .' />';
4648 } else {
4649 $output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
4652 if ($return) {
4653 return $output;
4654 } else {
4655 echo $output;
4660 * Print a nicely formatted table.
4662 * @param array $table is an object with several properties.
4663 * <ul>
4664 * <li>$table->head - An array of heading names.
4665 * <li>$table->align - An array of column alignments
4666 * <li>$table->size - An array of column sizes
4667 * <li>$table->wrap - An array of "nowrap"s or nothing
4668 * <li>$table->data[] - An array of arrays containing the data.
4669 * <li>$table->width - A percentage of the page
4670 * <li>$table->tablealign - Align the whole table
4671 * <li>$table->cellpadding - Padding on each cell
4672 * <li>$table->cellspacing - Spacing between cells
4673 * <li>$table->class - class attribute to put on the table
4674 * <li>$table->id - id attribute to put on the table.
4675 * <li>$table->rowclass[] - classes to add to particular rows.
4676 * <li>$table->summary - Description of the contents for screen readers.
4677 * </ul>
4678 * @param bool $return whether to return an output string or echo now
4679 * @return boolean or $string
4680 * @todo Finish documenting this function
4682 function print_table($table, $return=false) {
4683 $output = '';
4685 if (isset($table->align)) {
4686 foreach ($table->align as $key => $aa) {
4687 if ($aa) {
4688 $align[$key] = ' text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
4689 } else {
4690 $align[$key] = '';
4694 if (isset($table->size)) {
4695 foreach ($table->size as $key => $ss) {
4696 if ($ss) {
4697 $size[$key] = ' width:'. $ss .';';
4698 } else {
4699 $size[$key] = '';
4703 if (isset($table->wrap)) {
4704 foreach ($table->wrap as $key => $ww) {
4705 if ($ww) {
4706 $wrap[$key] = ' white-space:nowrap;';
4707 } else {
4708 $wrap[$key] = '';
4713 if (empty($table->width)) {
4714 $table->width = '80%';
4717 if (empty($table->tablealign)) {
4718 $table->tablealign = 'center';
4721 if (!isset($table->cellpadding)) {
4722 $table->cellpadding = '5';
4725 if (!isset($table->cellspacing)) {
4726 $table->cellspacing = '1';
4729 if (empty($table->class)) {
4730 $table->class = 'generaltable';
4733 $tableid = empty($table->id) ? '' : 'id="'.$table->id.'"';
4735 $output .= '<table width="'.$table->width.'" ';
4736 if (!empty($table->summary)) {
4737 $output .= " summary=\"$table->summary\"";
4739 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
4741 $countcols = 0;
4743 if (!empty($table->head)) {
4744 $countcols = count($table->head);
4745 $output .= '<tr>';
4746 foreach ($table->head as $key => $heading) {
4748 if (!isset($size[$key])) {
4749 $size[$key] = '';
4751 if (!isset($align[$key])) {
4752 $align[$key] = '';
4755 $output .= '<th style="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.'" scope="col">'. $heading .'</th>';
4757 $output .= '</tr>'."\n";
4760 if (!empty($table->data)) {
4761 $oddeven = 1;
4762 foreach ($table->data as $key => $row) {
4763 $oddeven = $oddeven ? 0 : 1;
4764 if (!isset($table->rowclass[$key])) {
4765 $table->rowclass[$key] = '';
4767 $output .= '<tr class="r'.$oddeven.' '.$table->rowclass[$key].'">'."\n";
4768 if ($row == 'hr' and $countcols) {
4769 $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
4770 } else { /// it's a normal row of data
4771 foreach ($row as $key => $item) {
4772 if (!isset($size[$key])) {
4773 $size[$key] = '';
4775 if (!isset($align[$key])) {
4776 $align[$key] = '';
4778 if (!isset($wrap[$key])) {
4779 $wrap[$key] = '';
4781 $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.'">'. $item .'</td>';
4784 $output .= '</tr>'."\n";
4787 $output .= '</table>'."\n";
4789 if ($return) {
4790 return $output;
4793 echo $output;
4794 return true;
4797 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
4798 static $strftimerecent = null;
4799 $output = '';
4801 if (is_null($viewfullnames)) {
4802 $context = get_context_instance(CONTEXT_SYSTEM);
4803 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
4806 if (is_null($strftimerecent)) {
4807 $strftimerecent = get_string('strftimerecent');
4810 $output .= '<div class="head">';
4811 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
4812 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
4813 $output .= '</div>';
4814 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
4816 if ($return) {
4817 return $output;
4818 } else {
4819 echo $output;
4825 * Prints a basic textarea field.
4827 * @uses $CFG
4828 * @param boolean $usehtmleditor ?
4829 * @param int $rows ?
4830 * @param int $cols ?
4831 * @param null $width <b>Legacy field no longer used!</b> Set to zero to get control over mincols
4832 * @param null $height <b>Legacy field no longer used!</b> Set to zero to get control over minrows
4833 * @param string $name ?
4834 * @param string $value ?
4835 * @param int $courseid ?
4836 * @todo Finish documenting this function
4838 function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $courseid=0, $return=false, $id='') {
4839 /// $width and height are legacy fields and no longer used as pixels like they used to be.
4840 /// However, you can set them to zero to override the mincols and minrows values below.
4842 global $CFG, $COURSE, $HTTPSPAGEREQUIRED;
4843 static $scriptcount = 0; // For loading the htmlarea script only once.
4845 $mincols = 65;
4846 $minrows = 10;
4847 $str = '';
4849 if ($id === '') {
4850 $id = 'edit-'.$name;
4853 if ( empty($CFG->editorsrc) ) { // for backward compatibility.
4854 if (empty($courseid)) {
4855 $courseid = $COURSE->id;
4858 if ($usehtmleditor) {
4859 if (!empty($courseid) and has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE, $courseid))) {
4860 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '&amp;httpsrequired=1';
4861 // needed for course file area browsing in image insert plugin
4862 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4863 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php?id='.$courseid.$httpsrequired.'"></script>'."\n" : '';
4864 } else {
4865 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '?httpsrequired=1';
4866 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4867 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php'.$httpsrequired.'"></script>'."\n" : '';
4870 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4871 $CFG->httpswwwroot .'/lib/editor/htmlarea/lang/en.php"></script>'."\n" : '';
4872 $scriptcount++;
4874 if ($height) { // Usually with legacy calls
4875 if ($rows < $minrows) {
4876 $rows = $minrows;
4879 if ($width) { // Usually with legacy calls
4880 if ($cols < $mincols) {
4881 $cols = $mincols;
4886 $str .= '<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">';
4887 if ($usehtmleditor) {
4888 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
4889 } else {
4890 $str .= s($value);
4892 $str .= '</textarea>'."\n";
4894 if ($usehtmleditor) {
4895 // Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
4896 $str .= '<script type="text/javascript">
4897 //<![CDATA[
4898 document.write(\''.addslashes_js(editorshortcutshelpbutton()).'\');
4899 //]]>
4900 </script>';
4903 if ($return) {
4904 return $str;
4906 echo $str;
4910 * Sets up the HTML editor on textareas in the current page.
4911 * If a field name is provided, then it will only be
4912 * applied to that field - otherwise it will be used
4913 * on every textarea in the page.
4915 * In most cases no arguments need to be supplied
4917 * @param string $name Form element to replace with HTMl editor by name
4919 function use_html_editor($name='', $editorhidebuttons='', $id='') {
4920 global $THEME;
4922 $editor = 'editor_'.md5($name); //name might contain illegal characters
4923 if ($id === '') {
4924 $id = 'edit-'.$name;
4926 echo "\n".'<script type="text/javascript" defer="defer">'."\n";
4927 echo '//<![CDATA['."\n\n"; // Extra \n is to fix odd wiki problem, MDL-8185
4928 echo "$editor = new HTMLArea('$id');\n";
4929 echo "var config = $editor.config;\n";
4931 echo print_editor_config($editorhidebuttons);
4933 if (empty($THEME->htmleditorpostprocess)) {
4934 if (empty($name)) {
4935 echo "\nHTMLArea.replaceAll($editor.config);\n";
4936 } else {
4937 echo "\n$editor.generate();\n";
4939 } else {
4940 if (empty($name)) {
4941 echo "\nvar HTML_name = '';";
4942 } else {
4943 echo "\nvar HTML_name = \"$name;\"";
4945 echo "\nvar HTML_editor = $editor;";
4947 echo '//]]>'."\n";
4948 echo '</script>'."\n";
4951 function print_editor_config($editorhidebuttons='', $return=false) {
4952 global $CFG;
4954 $str = "config.pageStyle = \"body {";
4956 if (!(empty($CFG->editorbackgroundcolor))) {
4957 $str .= " background-color: $CFG->editorbackgroundcolor;";
4960 if (!(empty($CFG->editorfontfamily))) {
4961 $str .= " font-family: $CFG->editorfontfamily;";
4964 if (!(empty($CFG->editorfontsize))) {
4965 $str .= " font-size: $CFG->editorfontsize;";
4968 $str .= " }\";\n";
4969 $str .= "config.killWordOnPaste = ";
4970 $str .= (empty($CFG->editorkillword)) ? "false":"true";
4971 $str .= ';'."\n";
4972 $str .= 'config.fontname = {'."\n";
4974 $fontlist = isset($CFG->editorfontlist) ? explode(';', $CFG->editorfontlist) : array();
4975 $i = 1; // Counter is used to get rid of the last comma.
4977 foreach ($fontlist as $fontline) {
4978 if (!empty($fontline)) {
4979 if ($i > 1) {
4980 $str .= ','."\n";
4982 list($fontkey, $fontvalue) = split(':', $fontline);
4983 $str .= '"'. $fontkey ."\":\t'". $fontvalue ."'";
4985 $i++;
4988 $str .= '};';
4990 if (!empty($editorhidebuttons)) {
4991 $str .= "\nconfig.hideSomeButtons(\" ". $editorhidebuttons ." \");\n";
4992 } else if (!empty($CFG->editorhidebuttons)) {
4993 $str .= "\nconfig.hideSomeButtons(\" ". $CFG->editorhidebuttons ." \");\n";
4996 if (!empty($CFG->editorspelling) && !empty($CFG->aspellpath)) {
4997 $str .= print_speller_code($CFG->htmleditor, true);
5000 if ($return) {
5001 return $str;
5003 echo $str;
5007 * Returns a turn edit on/off button for course in a self contained form.
5008 * Used to be an icon, but it's now a simple form button
5010 * Note that the caller is responsible for capchecks.
5012 * @uses $CFG
5013 * @uses $USER
5014 * @param int $courseid The course to update by id as found in 'course' table
5015 * @return string
5017 function update_course_icon($courseid) {
5018 global $CFG, $USER;
5020 if (!empty($USER->editing)) {
5021 $string = get_string('turneditingoff');
5022 $edit = '0';
5023 } else {
5024 $string = get_string('turneditingon');
5025 $edit = '1';
5028 return '<form '.$CFG->frametarget.' method="get" action="'.$CFG->wwwroot.'/course/view.php">'.
5029 '<div>'.
5030 '<input type="hidden" name="id" value="'.$courseid.'" />'.
5031 '<input type="hidden" name="edit" value="'.$edit.'" />'.
5032 '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
5033 '<input type="submit" value="'.$string.'" />'.
5034 '</div></form>';
5038 * Returns a little popup menu for switching roles
5040 * @uses $CFG
5041 * @uses $USER
5042 * @param int $courseid The course to update by id as found in 'course' table
5043 * @return string
5045 function switchroles_form($courseid) {
5047 global $CFG, $USER;
5050 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
5051 return '';
5054 if (!empty($USER->access['rsw'][$context->path])){ // Just a button to return to normal
5055 $options = array();
5056 $options['id'] = $courseid;
5057 $options['sesskey'] = sesskey();
5058 $options['switchrole'] = 0;
5060 return print_single_button($CFG->wwwroot.'/course/view.php', $options,
5061 get_string('switchrolereturn'), 'post', '_self', true);
5064 if (has_capability('moodle/role:switchroles', $context)) {
5065 if (!$roles = get_assignable_roles_for_switchrole($context)) {
5066 return ''; // Nothing to show!
5068 // unset default user role - it would not work
5069 unset($roles[$CFG->guestroleid]);
5070 return popup_form($CFG->wwwroot.'/course/view.php?id='.$courseid.'&amp;sesskey='.sesskey().'&amp;switchrole=',
5071 $roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
5074 return '';
5079 * Returns a turn edit on/off button for course in a self contained form.
5080 * Used to be an icon, but it's now a simple form button
5082 * @uses $CFG
5083 * @uses $USER
5084 * @param int $courseid The course to update by id as found in 'course' table
5085 * @return string
5087 function update_mymoodle_icon() {
5089 global $CFG, $USER;
5091 if (!empty($USER->editing)) {
5092 $string = get_string('updatemymoodleoff');
5093 $edit = '0';
5094 } else {
5095 $string = get_string('updatemymoodleon');
5096 $edit = '1';
5099 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
5100 "<div>".
5101 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5102 "<input type=\"submit\" value=\"$string\" /></div></form>";
5106 * Returns a turn edit on/off button for tag in a self contained form.
5108 * @uses $CFG
5109 * @uses $USER
5110 * @return string
5112 function update_tag_button($tagid) {
5114 global $CFG, $USER;
5116 if (!empty($USER->editing)) {
5117 $string = get_string('turneditingoff');
5118 $edit = '0';
5119 } else {
5120 $string = get_string('turneditingon');
5121 $edit = '1';
5124 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/tag/index.php\">".
5125 "<div>".
5126 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5127 "<input type=\"hidden\" name=\"id\" value=\"$tagid\" />".
5128 "<input type=\"submit\" value=\"$string\" /></div></form>";
5132 * Prints the editing button on a module "view" page
5134 * @uses $CFG
5135 * @param type description
5136 * @todo Finish documenting this function
5138 function update_module_button($moduleid, $courseid, $string) {
5139 global $CFG, $USER;
5141 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $moduleid))) {
5142 $string = get_string('updatethis', '', $string);
5144 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
5145 "<div>".
5146 "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
5147 "<input type=\"hidden\" name=\"return\" value=\"true\" />".
5148 "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
5149 "<input type=\"submit\" value=\"$string\" /></div></form>";
5150 } else {
5151 return '';
5156 * Prints the editing button on a category page
5158 * @uses $CFG
5159 * @uses $USER
5160 * @param int $categoryid ?
5161 * @return string
5162 * @todo Finish documenting this function
5164 function update_category_button($categoryid) {
5165 global $CFG, $USER;
5167 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_COURSECAT, $categoryid))) {
5168 if (!empty($USER->categoryediting)) {
5169 $string = get_string('turneditingoff');
5170 $edit = 'off';
5171 } else {
5172 $string = get_string('turneditingon');
5173 $edit = 'on';
5176 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/category.php\">".
5177 '<div>'.
5178 "<input type=\"hidden\" name=\"id\" value=\"$categoryid\" />".
5179 "<input type=\"hidden\" name=\"categoryedit\" value=\"$edit\" />".
5180 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5181 "<input type=\"submit\" value=\"$string\" /></div></form>";
5186 * Prints the editing button on categories listing
5188 * @uses $CFG
5189 * @uses $USER
5190 * @return string
5192 function update_categories_button() {
5193 global $CFG, $USER;
5195 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM))) {
5196 if (!empty($USER->categoryediting)) {
5197 $string = get_string('turneditingoff');
5198 $categoryedit = 'off';
5199 } else {
5200 $string = get_string('turneditingon');
5201 $categoryedit = 'on';
5204 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/index.php\">".
5205 '<div>'.
5206 '<input type="hidden" name="categoryedit" value="'. $categoryedit .'" />'.
5207 '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />'.
5208 '<input type="submit" value="'. $string .'" /></div></form>';
5213 * Prints the editing button on search results listing
5214 * For bulk move courses to another category
5217 function update_categories_search_button($search,$page,$perpage) {
5218 global $CFG, $USER;
5220 // not sure if this capability is the best here
5221 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM))) {
5222 if (!empty($USER->categoryediting)) {
5223 $string = get_string("turneditingoff");
5224 $edit = "off";
5225 $perpage = 30;
5226 } else {
5227 $string = get_string("turneditingon");
5228 $edit = "on";
5231 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
5232 '<div>'.
5233 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5234 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5235 "<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
5236 "<input type=\"hidden\" name=\"page\" value=\"$page\" />".
5237 "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
5238 "<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
5243 * Given a course and a (current) coursemodule
5244 * This function returns a small popup menu with all the
5245 * course activity modules in it, as a navigation menu
5246 * The data is taken from the serialised array stored in
5247 * the course record
5249 * @param course $course A {@link $COURSE} object.
5250 * @param course $cm A {@link $COURSE} object.
5251 * @param string $targetwindow ?
5252 * @return string
5253 * @todo Finish documenting this function
5255 function navmenu($course, $cm=NULL, $targetwindow='self') {
5257 global $CFG, $THEME, $USER;
5259 if (empty($THEME->navmenuwidth)) {
5260 $width = 50;
5261 } else {
5262 $width = $THEME->navmenuwidth;
5265 if ($cm) {
5266 $cm = $cm->id;
5269 if ($course->format == 'weeks') {
5270 $strsection = get_string('week');
5271 } else {
5272 $strsection = get_string('topic');
5274 $strjumpto = get_string('jumpto');
5276 $modinfo = get_fast_modinfo($course);
5277 $context = get_context_instance(CONTEXT_COURSE, $course->id);
5279 $section = -1;
5280 $selected = '';
5281 $url = '';
5282 $previousmod = NULL;
5283 $backmod = NULL;
5284 $nextmod = NULL;
5285 $selectmod = NULL;
5286 $logslink = NULL;
5287 $flag = false;
5288 $menu = array();
5289 $menustyle = array();
5291 $sections = get_records('course_sections','course',$course->id,'section','section,visible,summary');
5293 if (!empty($THEME->makenavmenulist)) { /// A hack to produce an XHTML navmenu list for use in themes
5294 $THEME->navmenulist = navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
5297 foreach ($modinfo->cms as $mod) {
5298 if ($mod->modname == 'label') {
5299 continue;
5302 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
5303 break;
5306 if (!$mod->uservisible) { // do not icnlude empty sections at all
5307 continue;
5310 if ($mod->sectionnum > 0 and $section != $mod->sectionnum) {
5311 $thissection = $sections[$mod->sectionnum];
5313 if ($thissection->visible or !$course->hiddensections or
5314 has_capability('moodle/course:viewhiddensections', $context)) {
5315 $thissection->summary = strip_tags(format_string($thissection->summary,true));
5316 if ($course->format == 'weeks' or empty($thissection->summary)) {
5317 $menu[] = '--'.$strsection ." ". $mod->sectionnum;
5318 } else {
5319 if (strlen($thissection->summary) < ($width-3)) {
5320 $menu[] = '--'.$thissection->summary;
5321 } else {
5322 $menu[] = '--'.substr($thissection->summary, 0, $width).'...';
5325 $section = $mod->sectionnum;
5326 } else {
5327 // no activities from this hidden section shown
5328 continue;
5332 $url = $mod->modname.'/view.php?id='. $mod->id;
5333 if ($flag) { // the current mod is the "next" mod
5334 $nextmod = $mod;
5335 $flag = false;
5337 $localname = $mod->name;
5338 if ($cm == $mod->id) {
5339 $selected = $url;
5340 $selectmod = $mod;
5341 $backmod = $previousmod;
5342 $flag = true; // set flag so we know to use next mod for "next"
5343 $localname = $strjumpto;
5344 $strjumpto = '';
5345 } else {
5346 $localname = strip_tags(format_string($localname,true));
5347 $tl=textlib_get_instance();
5348 if ($tl->strlen($localname) > ($width+5)) {
5349 $localname = $tl->substr($localname, 0, $width).'...';
5351 if (!$mod->visible) {
5352 $localname = '('.$localname.')';
5355 $menu[$url] = $localname;
5356 if (empty($THEME->navmenuiconshide)) {
5357 $menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif);"'; // Unfortunately necessary to do this here
5359 $previousmod = $mod;
5361 //Accessibility: added Alt text, replaced &gt; &lt; with 'silent' character and 'accesshide' text.
5363 if ($selectmod and has_capability('moodle/site:viewreports', $context)) {
5364 $logstext = get_string('alllogs');
5365 $logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
5366 $CFG->frametarget.'onclick="this.target=\''.$CFG->framename.'\';"'.' href="'.
5367 $CFG->wwwroot.'/course/report/log/index.php?chooselog=1&amp;user=0&amp;date=0&amp;id='.
5368 $course->id.'&amp;modid='.$selectmod->id.'">'.
5369 '<img class="icon log" src="'.$CFG->pixpath.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
5372 if ($backmod) {
5373 $backtext= get_string('activityprev', 'access');
5374 $backmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$backmod->modname.'/view.php" '.
5375 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
5376 '<input type="hidden" name="id" value="'.$backmod->id.'" />'.
5377 '<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
5378 '</button></fieldset></form></li>';
5380 if ($nextmod) {
5381 $nexttext= get_string('activitynext', 'access');
5382 $nextmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$nextmod->modname.'/view.php" '.
5383 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
5384 '<input type="hidden" name="id" value="'.$nextmod->id.'" />'.
5385 '<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
5386 '</button></fieldset></form></li>';
5389 return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
5390 '<li>'.popup_form($CFG->wwwroot .'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
5391 '', '', true, $targetwindow, '', $menustyle).'</li>'.
5392 $nextmod . '</ul>'."\n".'</div>';
5396 * Given a course
5397 * This function returns a small popup menu with all the
5398 * course activity modules in it, as a navigation menu
5399 * outputs a simple list structure in XHTML
5400 * The data is taken from the serialised array stored in
5401 * the course record
5403 * @param course $course A {@link $COURSE} object.
5404 * @return string
5405 * @todo Finish documenting this function
5407 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
5409 global $CFG;
5411 $section = -1;
5412 $url = '';
5413 $menu = array();
5414 $doneheading = false;
5416 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
5418 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
5419 foreach ($modinfo->cms as $mod) {
5420 if ($mod->modname == 'label') {
5421 continue;
5424 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
5425 break;
5428 if (!$mod->uservisible) { // do not icnlude empty sections at all
5429 continue;
5432 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
5433 $thissection = $sections[$mod->sectionnum];
5435 if ($thissection->visible or !$course->hiddensections or
5436 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
5437 $thissection->summary = strip_tags(format_string($thissection->summary,true));
5438 if (!$doneheading) {
5439 $menu[] = '</ul></li>';
5441 if ($course->format == 'weeks' or empty($thissection->summary)) {
5442 $item = $strsection ." ". $mod->sectionnum;
5443 } else {
5444 if (strlen($thissection->summary) < ($width-3)) {
5445 $item = $thissection->summary;
5446 } else {
5447 $item = substr($thissection->summary, 0, $width).'...';
5450 $menu[] = '<li class="section"><span>'.$item.'</span>';
5451 $menu[] = '<ul>';
5452 $doneheading = true;
5454 $section = $mod->sectionnum;
5455 } else {
5456 // no activities from this hidden section shown
5457 continue;
5461 $url = $mod->modname .'/view.php?id='. $mod->id;
5462 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
5463 if (strlen($mod->name) > ($width+5)) {
5464 $mod->name = substr($mod->name, 0, $width).'...';
5466 if (!$mod->visible) {
5467 $mod->name = '('.$mod->name.')';
5469 $class = 'activity '.$mod->modname;
5470 $class .= ($cmid == $mod->cm) ? ' selected' : '';
5471 $menu[] = '<li class="'.$class.'">'.
5472 '<img src="'.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif" alt="" />'.
5473 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
5476 if ($doneheading) {
5477 $menu[] = '</ul></li>';
5479 $menu[] = '</ul></li></ul>';
5481 return implode("\n", $menu);
5485 * Prints form items with the names $day, $month and $year
5487 * @param string $day fieldname
5488 * @param string $month fieldname
5489 * @param string $year fieldname
5490 * @param int $currenttime A default timestamp in GMT
5491 * @param boolean $return
5493 function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
5495 if (!$currenttime) {
5496 $currenttime = time();
5498 $currentdate = usergetdate($currenttime);
5500 for ($i=1; $i<=31; $i++) {
5501 $days[$i] = $i;
5503 for ($i=1; $i<=12; $i++) {
5504 $months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
5506 for ($i=1970; $i<=2020; $i++) {
5507 $years[$i] = $i;
5509 return choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', $return)
5510 .choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', $return)
5511 .choose_from_menu($years, $year, $currentdate['year'], '', '', '0', $return);
5516 *Prints form items with the names $hour and $minute
5518 * @param string $hour fieldname
5519 * @param string ? $minute fieldname
5520 * @param $currenttime A default timestamp in GMT
5521 * @param int $step minute spacing
5522 * @param boolean $return
5524 function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
5526 if (!$currenttime) {
5527 $currenttime = time();
5529 $currentdate = usergetdate($currenttime);
5530 if ($step != 1) {
5531 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
5533 for ($i=0; $i<=23; $i++) {
5534 $hours[$i] = sprintf("%02d",$i);
5536 for ($i=0; $i<=59; $i+=$step) {
5537 $minutes[$i] = sprintf("%02d",$i);
5540 return choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',$return)
5541 .choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',$return);
5545 * Prints time limit value selector
5547 * @uses $CFG
5548 * @param int $timelimit default
5549 * @param string $unit
5550 * @param string $name
5551 * @param boolean $return
5553 function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
5555 global $CFG;
5557 if ($unit) {
5558 $unit = ' '.$unit;
5561 // Max timelimit is sessiontimeout - 10 minutes.
5562 $maxvalue = ($CFG->sessiontimeout / 60) - 10;
5564 for ($i=1; $i<=$maxvalue; $i++) {
5565 $minutes[$i] = $i.$unit;
5567 return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
5571 * Prints a grade menu (as part of an existing form) with help
5572 * Showing all possible numerical grades and scales
5574 * @uses $CFG
5575 * @param int $courseid ?
5576 * @param string $name ?
5577 * @param string $current ?
5578 * @param boolean $includenograde ?
5579 * @todo Finish documenting this function
5581 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
5583 global $CFG;
5585 $output = '';
5586 $strscale = get_string('scale');
5587 $strscales = get_string('scales');
5589 $scales = get_scales_menu($courseid);
5590 foreach ($scales as $i => $scalename) {
5591 $grades[-$i] = $strscale .': '. $scalename;
5593 if ($includenograde) {
5594 $grades[0] = get_string('nograde');
5596 for ($i=100; $i>=1; $i--) {
5597 $grades[$i] = $i;
5599 $output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
5601 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5602 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5603 $linkobject, 400, 500, $strscales, 'none', true);
5605 if ($return) {
5606 return $output;
5607 } else {
5608 echo $output;
5613 * Prints a scale menu (as part of an existing form) including help button
5614 * Just like {@link print_grade_menu()} but without the numeric grades
5616 * @param int $courseid ?
5617 * @param string $name ?
5618 * @param string $current ?
5619 * @todo Finish documenting this function
5621 function print_scale_menu($courseid, $name, $current, $return=false) {
5623 global $CFG;
5625 $output = '';
5626 $strscales = get_string('scales');
5627 $output .= choose_from_menu(get_scales_menu($courseid), $name, $current, '', '', 0, true);
5629 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5630 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5631 $linkobject, 400, 500, $strscales, 'none', true);
5632 if ($return) {
5633 return $output;
5634 } else {
5635 echo $output;
5640 * Prints a help button about a scale
5642 * @uses $CFG
5643 * @param id $courseid ?
5644 * @param object $scale ?
5645 * @todo Finish documenting this function
5647 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
5649 global $CFG;
5651 $output = '';
5652 $strscales = get_string('scales');
5654 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5655 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true&amp;scaleid='. $scale->id, 'ratingscale',
5656 $linkobject, 400, 500, $scale->name, 'none', true);
5657 if ($return) {
5658 return $output;
5659 } else {
5660 echo $output;
5665 * Print an error page displaying an error message. New method - use this for new code.
5667 * @uses $SESSION
5668 * @uses $CFG
5669 * @param string $errorcode The name of the string from error.php to print
5670 * @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.
5671 * @param object $a Extra words and phrases that might be required in the error string
5673 function print_error ($errorcode, $module='', $link='', $a=NULL) {
5675 global $CFG, $SESSION, $THEME;
5677 if (empty($module) || $module == 'moodle' || $module == 'core') {
5678 $module = 'error';
5679 $modulelink = 'moodle';
5680 } else {
5681 $modulelink = $module;
5684 if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
5685 if ( !empty($SESSION->fromurl) ) {
5686 $link = $SESSION->fromurl;
5687 unset($SESSION->fromurl);
5688 } else {
5689 $link = $CFG->wwwroot .'/';
5693 if (!empty($CFG->errordocroot)) {
5694 $errordocroot = $CFG->errordocroot;
5695 } else if (!empty($CFG->docroot)) {
5696 $errordocroot = $CFG->docroot;
5697 } else {
5698 $errordocroot = 'http://docs.moodle.org';
5701 $message = get_string($errorcode, $module, $a);
5703 if (defined('FULLME') && FULLME == 'cron') {
5704 // Errors in cron should be mtrace'd.
5705 mtrace($message);
5706 die;
5709 $message = clean_text('<p class="errormessage">'.$message.'</p>'.
5710 '<p class="errorcode">'.
5711 '<a href="'.$errordocroot.'/en/error/'.$modulelink.'/'.$errorcode.'">'.
5712 get_string('moreinformation').'</a></p>');
5714 if (! defined('HEADER_PRINTED')) {
5715 //header not yet printed
5716 @header('HTTP/1.0 404 Not Found');
5717 print_header(get_string('error'));
5718 } else {
5719 print_container_end_all(false, $THEME->open_header_containers);
5722 echo '<br />';
5724 print_simple_box($message, '', '', '', '', 'errorbox');
5726 debugging('Stack trace:', DEBUG_DEVELOPER);
5728 // in case we are logging upgrade in admin/index.php stop it
5729 if (function_exists('upgrade_log_finish')) {
5730 upgrade_log_finish();
5733 if (!empty($link)) {
5734 print_continue($link);
5737 print_footer();
5739 for ($i=0;$i<512;$i++) { // Padding to help IE work with 404
5740 echo ' ';
5742 die;
5746 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
5747 * Default errorcode is 1.
5749 * Very useful for perl-like error-handling:
5751 * do_somethting() or mdie("Something went wrong");
5753 * @param string $msg Error message
5754 * @param integer $errorcode Error code to emit
5756 function mdie($msg='', $errorcode=1) {
5757 trigger_error($msg);
5758 exit($errorcode);
5762 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
5763 * Should be used only with htmleditor or textarea.
5764 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
5765 * helpbutton.
5766 * @return string
5768 function editorhelpbutton(){
5769 global $CFG, $SESSION;
5770 $items = func_get_args();
5771 $i = 1;
5772 $urlparams = array();
5773 $titles = array();
5774 foreach ($items as $item){
5775 if (is_array($item)){
5776 $urlparams[] = "keyword$i=".urlencode($item[0]);
5777 $urlparams[] = "title$i=".urlencode($item[1]);
5778 if (isset($item[2])){
5779 $urlparams[] = "module$i=".urlencode($item[2]);
5781 $titles[] = trim($item[1], ". \t");
5782 }elseif (is_string($item)){
5783 $urlparams[] = "button$i=".urlencode($item);
5784 switch ($item){
5785 case 'reading' :
5786 $titles[] = get_string("helpreading");
5787 break;
5788 case 'writing' :
5789 $titles[] = get_string("helpwriting");
5790 break;
5791 case 'questions' :
5792 $titles[] = get_string("helpquestions");
5793 break;
5794 case 'emoticons' :
5795 $titles[] = get_string("helpemoticons");
5796 break;
5797 case 'richtext' :
5798 $titles[] = get_string('helprichtext');
5799 break;
5800 case 'text' :
5801 $titles[] = get_string('helptext');
5802 break;
5803 default :
5804 error('Unknown help topic '.$item);
5807 $i++;
5809 if (count($titles)>1){
5810 //join last two items with an 'and'
5811 $a = new object();
5812 $a->one = $titles[count($titles) - 2];
5813 $a->two = $titles[count($titles) - 1];
5814 $titles[count($titles) - 2] = get_string('and', '', $a);
5815 unset($titles[count($titles) - 1]);
5817 $alttag = join (', ', $titles);
5819 $paramstring = join('&', $urlparams);
5820 $linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath .'/help.gif" />';
5821 return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), 'popup', $linkobject, 400, 500, $alttag, 'none', true);
5825 * Print a help button.
5827 * @uses $CFG
5828 * @param string $page The keyword that defines a help page
5829 * @param string $title The title of links, rollover tips, alt tags etc
5830 * 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
5831 * @param string $module Which module is the page defined in
5832 * @param mixed $image Use a help image for the link? (true/false/"both")
5833 * @param boolean $linktext If true, display the title next to the help icon.
5834 * @param string $text If defined then this text is used in the page, and
5835 * the $page variable is ignored.
5836 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
5837 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
5838 * @return string
5839 * @todo Finish documenting this function
5841 function helpbutton ($page, $title, $module='moodle', $image=true, $linktext=false, $text='', $return=false,
5842 $imagetext='') {
5843 global $CFG, $COURSE;
5845 // fix for MDL-7734
5846 if (!empty($COURSE->lang)) {
5847 $forcelang = $COURSE->lang;
5848 } else {
5849 $forcelang = '';
5852 if ($module == '') {
5853 $module = 'moodle';
5856 if ($title == '' && $linktext == '') {
5857 debugging('Error in call to helpbutton function: at least one of $title and $linktext is required');
5860 // Warn users about new window for Accessibility
5861 $tooltip = get_string('helpprefix2', '', trim($title, ". \t")) .' ('.get_string('newwindow').')';
5863 $linkobject = '';
5865 if ($image) {
5866 if ($linktext) {
5867 // MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
5868 $linkobject .= $title.'&nbsp;';
5869 $tooltip = get_string('helpwiththis');
5871 if ($imagetext) {
5872 $linkobject .= $imagetext;
5873 } else {
5874 $linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
5875 $CFG->pixpath .'/help.gif" />';
5877 } else {
5878 $linkobject .= $tooltip;
5881 // fix for MDL-7734
5882 if ($text) {
5883 $url = '/help.php?module='. $module .'&amp;text='. s(urlencode($text).'&amp;forcelang='.$forcelang);
5884 } else {
5885 $url = '/help.php?module='. $module .'&amp;file='. $page .'.html&amp;forcelang='.$forcelang;
5888 $link = '<span class="helplink">'.
5889 link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
5890 '</span>';
5892 if ($return) {
5893 return $link;
5894 } else {
5895 echo $link;
5900 * Print a help button.
5902 * Prints a special help button that is a link to the "live" emoticon popup
5903 * @uses $CFG
5904 * @uses $SESSION
5905 * @param string $form ?
5906 * @param string $field ?
5907 * @todo Finish documenting this function
5909 function emoticonhelpbutton($form, $field, $return = false) {
5911 global $CFG, $SESSION;
5913 $SESSION->inserttextform = $form;
5914 $SESSION->inserttextfield = $field;
5915 $imagetext = '<img src="' . $CFG->pixpath . '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
5916 $help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
5917 if (!$return){
5918 echo $help;
5919 } else {
5920 return $help;
5925 * Print a help button.
5927 * Prints a special help button for html editors (htmlarea in this case)
5928 * @uses $CFG
5930 function editorshortcutshelpbutton() {
5932 global $CFG;
5933 $imagetext = '<img src="' . $CFG->httpswwwroot . '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
5934 get_string('editorshortcutkeys').'" class="iconkbhelp" />';
5936 return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
5940 * Print a message and exit.
5942 * @uses $CFG
5943 * @param string $message ?
5944 * @param string $link ?
5945 * @todo Finish documenting this function
5947 function notice ($message, $link='', $course=NULL) {
5948 global $CFG, $SITE, $THEME, $COURSE;
5950 $message = clean_text($message); // In case nasties are in here
5952 if (defined('FULLME') && FULLME == 'cron') {
5953 // notices in cron should be mtrace'd.
5954 mtrace($message);
5955 die;
5958 if (! defined('HEADER_PRINTED')) {
5959 //header not yet printed
5960 print_header(get_string('notice'));
5961 } else {
5962 print_container_end_all(false, $THEME->open_header_containers);
5965 print_box($message, 'generalbox', 'notice');
5966 print_continue($link);
5968 if (empty($course)) {
5969 print_footer($COURSE);
5970 } else {
5971 print_footer($course);
5973 exit;
5977 * Print a message along with "Yes" and "No" links for the user to continue.
5979 * @param string $message The text to display
5980 * @param string $linkyes The link to take the user to if they choose "Yes"
5981 * @param string $linkno The link to take the user to if they choose "No"
5982 * TODO Document remaining arguments
5984 function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
5986 global $CFG;
5988 $message = clean_text($message);
5989 $linkyes = clean_text($linkyes);
5990 $linkno = clean_text($linkno);
5992 print_box_start('generalbox', 'notice');
5993 echo '<p>'. $message .'</p>';
5994 echo '<div class="buttons">';
5995 print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename);
5996 print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename);
5997 echo '</div>';
5998 print_box_end();
6002 * Provide an definition of error_get_last for PHP before 5.2.0. This simply
6003 * returns NULL, since there is not way to get the right answer.
6005 if (!function_exists('error_get_last')) {
6006 // the eval is needed to prevent PHP 5.2+ from getting a parse error!
6007 eval('
6008 function error_get_last() {
6009 return NULL;
6015 * Redirects the user to another page, after printing a notice
6017 * @param string $url The url to take the user to
6018 * @param string $message The text message to display to the user about the redirect, if any
6019 * @param string $delay How long before refreshing to the new page at $url?
6020 * @todo '&' needs to be encoded into '&amp;' for XHTML compliance,
6021 * however, this is not true for javascript. Therefore we
6022 * first decode all entities in $url (since we cannot rely on)
6023 * the correct input) and then encode for where it's needed
6024 * echo "<script type='text/javascript'>alert('Redirect $url');</script>";
6026 function redirect($url, $message='', $delay=-1) {
6028 global $CFG, $THEME;
6030 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
6031 $url = sid_process_url($url);
6034 $message = clean_text($message);
6036 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
6037 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
6038 $url = str_replace('&amp;', '&', $encodedurl);
6040 /// At developer debug level. Don't redirect if errors have been printed on screen.
6041 /// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
6042 $lasterror = error_get_last();
6043 $error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER));
6044 $errorprinted = debugging('', DEBUG_ALL) && $CFG->debugdisplay && $error;
6045 if ($errorprinted) {
6046 $message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
6049 $performanceinfo = '';
6050 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
6051 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
6052 $perf = get_performance_info();
6053 error_log("PERF: " . $perf['txt']);
6057 /// when no message and header printed yet, try to redirect
6058 if (empty($message) and !defined('HEADER_PRINTED')) {
6060 // Technically, HTTP/1.1 requires Location: header to contain
6061 // the absolute path. (In practice browsers accept relative
6062 // paths - but still, might as well do it properly.)
6063 // This code turns relative into absolute.
6064 if (!preg_match('|^[a-z]+:|', $url)) {
6065 // Get host name http://www.wherever.com
6066 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
6067 if (preg_match('|^/|', $url)) {
6068 // URLs beginning with / are relative to web server root so we just add them in
6069 $url = $hostpart.$url;
6070 } else {
6071 // URLs not beginning with / are relative to path of current script, so add that on.
6072 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
6074 // Replace all ..s
6075 while (true) {
6076 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
6077 if ($newurl == $url) {
6078 break;
6080 $url = $newurl;
6084 $delay = 0;
6085 //try header redirection first
6086 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
6087 @header('Location: '.$url);
6088 //another way for older browsers and already sent headers (eg trailing whitespace in config.php)
6089 echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
6090 echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
6091 die;
6094 if ($delay == -1) {
6095 $delay = 3; // if no delay specified wait 3 seconds
6097 if (! defined('HEADER_PRINTED')) {
6098 // this type of redirect might not be working in some browsers - such as lynx :-(
6099 print_header('', '', '', '', $errorprinted ? '' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
6100 $delay += 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
6101 } else {
6102 print_container_end_all(false, $THEME->open_header_containers);
6104 echo '<div id="redirect">';
6105 echo '<div id="message">' . $message . '</div>';
6106 echo '<div id="continue">( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
6107 echo '</div>';
6109 if (!$errorprinted) {
6111 <script type="text/javascript">
6112 //<![CDATA[
6114 function redirect() {
6115 document.location.replace('<?php echo addslashes_js($url) ?>');
6117 setTimeout("redirect()", <?php echo ($delay * 1000) ?>);
6118 //]]>
6119 </script>
6120 <?php
6123 $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
6124 print_footer('none');
6125 die;
6129 * Print a bold message in an optional color.
6131 * @param string $message The message to print out
6132 * @param string $style Optional style to display message text in
6133 * @param string $align Alignment option
6134 * @param bool $return whether to return an output string or echo now
6136 function notify($message, $style='notifyproblem', $align='center', $return=false) {
6137 if ($style == 'green') {
6138 $style = 'notifysuccess'; // backward compatible with old color system
6141 $message = clean_text($message);
6143 $output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."\n";
6145 if ($return) {
6146 return $output;
6148 echo $output;
6153 * Given an email address, this function will return an obfuscated version of it
6155 * @param string $email The email address to obfuscate
6156 * @return string
6158 function obfuscate_email($email) {
6160 $i = 0;
6161 $length = strlen($email);
6162 $obfuscated = '';
6163 while ($i < $length) {
6164 if (rand(0,2)) {
6165 $obfuscated.='%'.dechex(ord($email{$i}));
6166 } else {
6167 $obfuscated.=$email{$i};
6169 $i++;
6171 return $obfuscated;
6175 * This function takes some text and replaces about half of the characters
6176 * with HTML entity equivalents. Return string is obviously longer.
6178 * @param string $plaintext The text to be obfuscated
6179 * @return string
6181 function obfuscate_text($plaintext) {
6183 $i=0;
6184 $length = strlen($plaintext);
6185 $obfuscated='';
6186 $prev_obfuscated = false;
6187 while ($i < $length) {
6188 $c = ord($plaintext{$i});
6189 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
6190 if ($prev_obfuscated and $numerical ) {
6191 $obfuscated.='&#'.ord($plaintext{$i}).';';
6192 } else if (rand(0,2)) {
6193 $obfuscated.='&#'.ord($plaintext{$i}).';';
6194 $prev_obfuscated = true;
6195 } else {
6196 $obfuscated.=$plaintext{$i};
6197 $prev_obfuscated = false;
6199 $i++;
6201 return $obfuscated;
6205 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
6206 * to generate a fully obfuscated email link, ready to use.
6208 * @param string $email The email address to display
6209 * @param string $label The text to dispalyed as hyperlink to $email
6210 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
6211 * @return string
6213 function obfuscate_mailto($email, $label='', $dimmed=false) {
6215 if (empty($label)) {
6216 $label = $email;
6218 if ($dimmed) {
6219 $title = get_string('emaildisable');
6220 $dimmed = ' class="dimmed"';
6221 } else {
6222 $title = '';
6223 $dimmed = '';
6225 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
6226 obfuscate_text('mailto'), obfuscate_email($email),
6227 obfuscate_text($label));
6231 * Prints a single paging bar to provide access to other pages (usually in a search)
6233 * @param int $totalcount Thetotal number of entries available to be paged through
6234 * @param int $page The page you are currently viewing
6235 * @param int $perpage The number of entries that should be shown per page
6236 * @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.
6237 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
6238 * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
6239 * @param bool $nocurr do not display the current page as a link
6240 * @param bool $return whether to return an output string or echo now
6241 * @return bool or string
6243 function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
6244 $maxdisplay = 18;
6245 $output = '';
6247 if ($totalcount > $perpage) {
6248 $output .= '<div class="paging">';
6249 $output .= get_string('page') .':';
6250 if ($page > 0) {
6251 $pagenum = $page - 1;
6252 if (!is_a($baseurl, 'moodle_url')){
6253 $output .= '&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>)&nbsp;';
6254 } else {
6255 $output .= '&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>)&nbsp;';
6258 if ($perpage > 0) {
6259 $lastpage = ceil($totalcount / $perpage);
6260 } else {
6261 $lastpage = 1;
6263 if ($page > 15) {
6264 $startpage = $page - 10;
6265 if (!is_a($baseurl, 'moodle_url')){
6266 $output .= '&nbsp;<a href="'. $baseurl . $pagevar .'=0">1</a>&nbsp;...';
6267 } else {
6268 $output .= '&nbsp;<a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a>&nbsp;...';
6270 } else {
6271 $startpage = 0;
6273 $currpage = $startpage;
6274 $displaycount = $displaypage = 0;
6275 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
6276 $displaypage = $currpage+1;
6277 if ($page == $currpage && empty($nocurr)) {
6278 $output .= '&nbsp;&nbsp;'. $displaypage;
6279 } else {
6280 if (!is_a($baseurl, 'moodle_url')){
6281 $output .= '&nbsp;&nbsp;<a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
6282 } else {
6283 $output .= '&nbsp;&nbsp;<a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
6287 $displaycount++;
6288 $currpage++;
6290 if ($currpage < $lastpage) {
6291 $lastpageactual = $lastpage - 1;
6292 if (!is_a($baseurl, 'moodle_url')){
6293 $output .= '&nbsp;...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a>&nbsp;';
6294 } else {
6295 $output .= '&nbsp;...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a>&nbsp;';
6298 $pagenum = $page + 1;
6299 if ($pagenum != $displaypage) {
6300 if (!is_a($baseurl, 'moodle_url')){
6301 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
6302 } else {
6303 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
6306 $output .= '</div>';
6309 if ($return) {
6310 return $output;
6313 echo $output;
6314 return true;
6318 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
6319 * will transform it to html entities
6321 * @param string $text Text to search for nolink tag in
6322 * @return string
6324 function rebuildnolinktag($text) {
6326 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
6328 return $text;
6332 * Prints a nice side block with an optional header. The content can either
6333 * be a block of HTML or a list of text with optional icons.
6335 * @param string $heading Block $title embedded in HTML tags, for example <h2>.
6336 * @param string $content ?
6337 * @param array $list ?
6338 * @param array $icons ?
6339 * @param string $footer ?
6340 * @param array $attributes ?
6341 * @param string $title Plain text title, as embedded in the $heading.
6342 * @todo Finish documenting this function. Show example of various attributes, etc.
6344 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
6346 //Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
6347 static $block_id = 0;
6348 $block_id++;
6349 if (empty($heading)) {
6350 $skip_text = get_string('skipblock', 'access').' '.$block_id;
6352 else {
6353 $skip_text = get_string('skipa', 'access', strip_tags($title));
6355 $skip_link = '<a href="#sb-'.$block_id.'" class="skip-block">'.$skip_text.'</a>';
6356 $skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
6358 if (! empty($heading)) {
6359 echo $skip_link;
6361 //ELSE: a single link on a page "Skip block 4" is too confusing - ignore.
6363 print_side_block_start($heading, $attributes);
6365 if ($content) {
6366 echo $content;
6367 if ($footer) {
6368 echo '<div class="footer">'. $footer .'</div>';
6370 } else {
6371 if ($list) {
6372 $row = 0;
6373 //Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
6374 echo "\n<ul class='list'>\n";
6375 foreach ($list as $key => $string) {
6376 echo '<li class="r'. $row .'">';
6377 if ($icons) {
6378 echo '<div class="icon column c0">'. $icons[$key] .'</div>';
6380 echo '<div class="column c1">'. $string .'</div>';
6381 echo "</li>\n";
6382 $row = $row ? 0:1;
6384 echo "</ul>\n";
6386 if ($footer) {
6387 echo '<div class="footer">'. $footer .'</div>';
6392 print_side_block_end($attributes, $title);
6393 echo $skip_dest;
6397 * Starts a nice side block with an optional header.
6399 * @param string $heading ?
6400 * @param array $attributes ?
6401 * @todo Finish documenting this function
6403 function print_side_block_start($heading='', $attributes = array()) {
6405 global $CFG, $THEME;
6407 // If there are no special attributes, give a default CSS class
6408 if (empty($attributes) || !is_array($attributes)) {
6409 $attributes = array('class' => 'sideblock');
6411 } else if(!isset($attributes['class'])) {
6412 $attributes['class'] = 'sideblock';
6414 } else if(!strpos($attributes['class'], 'sideblock')) {
6415 $attributes['class'] .= ' sideblock';
6418 // OK, the class is surely there and in addition to anything
6419 // else, it's tagged as a sideblock
6423 // IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
6425 // If there is a cookie to hide this thing, start it hidden
6426 if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
6427 $attributes['class'] = 'hidden '.$attributes['class'];
6431 $attrtext = '';
6432 foreach ($attributes as $attr => $val) {
6433 $attrtext .= ' '.$attr.'="'.$val.'"';
6436 echo '<div '.$attrtext.'>';
6438 if (!empty($THEME->customcorners)) {
6439 echo '<div class="wrap">'."\n";
6441 if ($heading) {
6442 //Accessibility: H2 more appropriate in moodleblock.class.php: _title_html.
6443 echo '<div class="header">';
6444 if (!empty($THEME->customcorners)) {
6445 echo '<div class="bt"><div>&nbsp;</div></div>';
6446 echo '<div class="i1"><div class="i2">';
6447 echo '<div class="i3">';
6449 echo $heading;
6450 if (!empty($THEME->customcorners)) {
6451 echo '</div></div></div>';
6453 echo '</div>';
6454 } else {
6455 if (!empty($THEME->customcorners)) {
6456 echo '<div class="bt"><div>&nbsp;</div></div>';
6460 if (!empty($THEME->customcorners)) {
6461 echo '<div class="i1"><div class="i2">';
6462 echo '<div class="i3">';
6464 echo '<div class="content">';
6470 * Print table ending tags for a side block box.
6472 function print_side_block_end($attributes = array(), $title='') {
6473 global $CFG, $THEME;
6475 echo '</div>';
6477 if (!empty($THEME->customcorners)) {
6478 echo '</div></div></div><div class="bb"><div>&nbsp;</div></div></div>';
6481 echo '</div>';
6483 $strshow = addslashes_js(get_string('showblocka', 'access', strip_tags($title)));
6484 $strhide = addslashes_js(get_string('hideblocka', 'access', strip_tags($title)));
6486 // IE workaround: if I do it THIS way, it works! WTF?
6487 if (!empty($CFG->allowuserblockhiding) && isset($attributes['id'])) {
6488 echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].
6489 '","'.$strshow.'","'.$strhide."\");\n//]]>\n".'</script>';
6496 * Prints out code needed for spellchecking.
6497 * Original idea by Ludo (Marc Alier).
6499 * Opening CDATA and <script> are output by weblib::use_html_editor()
6500 * @uses $CFG
6501 * @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
6502 * @param boolean $return If false, echos the code instead of returning it
6503 * @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
6505 function print_speller_code ($usehtmleditor=false, $return=false) {
6506 global $CFG;
6507 $str = '';
6509 if(!$usehtmleditor) {
6510 $str .= 'function openSpellChecker() {'."\n";
6511 $str .= "\tvar speller = new spellChecker();\n";
6512 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot ."/lib/speller/spellchecker.html\";\n";
6513 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
6514 $str .= "\tspeller.spellCheckAll();\n";
6515 $str .= '}'."\n";
6516 } else {
6517 $str .= "function spellClickHandler(editor, buttonId) {\n";
6518 $str .= "\teditor._textArea.value = editor.getHTML();\n";
6519 $str .= "\tvar speller = new spellChecker( editor._textArea );\n";
6520 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot ."/lib/speller/spellchecker.html\";\n";
6521 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
6522 $str .= "\tspeller._moogle_edit=1;\n";
6523 $str .= "\tspeller._editor=editor;\n";
6524 $str .= "\tspeller.openChecker();\n";
6525 $str .= '}'."\n";
6528 if ($return) {
6529 return $str;
6531 echo $str;
6535 * Print button for spellchecking when editor is disabled
6537 function print_speller_button () {
6538 echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
6542 function page_id_and_class(&$getid, &$getclass) {
6543 // Create class and id for this page
6544 global $CFG, $ME;
6546 static $class = NULL;
6547 static $id = NULL;
6549 if (empty($CFG->pagepath)) {
6550 $CFG->pagepath = $ME;
6553 if (empty($class) || empty($id)) {
6554 $path = str_replace($CFG->httpswwwroot.'/', '', $CFG->pagepath); //Because the page could be HTTPSPAGEREQUIRED
6555 $path = str_replace('.php', '', $path);
6556 if (substr($path, -1) == '/') {
6557 $path .= 'index';
6559 if (empty($path) || $path == 'index') {
6560 $id = 'site-index';
6561 $class = 'course';
6562 } else if (substr($path, 0, 5) == 'admin') {
6563 $id = str_replace('/', '-', $path);
6564 $class = 'admin';
6565 } else {
6566 $id = str_replace('/', '-', $path);
6567 $class = explode('-', $id);
6568 array_pop($class);
6569 $class = implode('-', $class);
6573 $getid = $id;
6574 $getclass = $class;
6578 * Prints a maintenance message from /maintenance.html
6580 function print_maintenance_message () {
6581 global $CFG, $SITE;
6583 print_header(strip_tags($SITE->fullname), $SITE->fullname, 'home');
6584 print_simple_box_start('center');
6585 print_heading(get_string('sitemaintenance', 'admin'));
6586 @include($CFG->dataroot.'/1/maintenance.html');
6587 print_simple_box_end();
6588 print_footer();
6592 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
6594 function adjust_allowed_tags() {
6596 global $CFG, $ALLOWED_TAGS;
6598 if (!empty($CFG->allowobjectembed)) {
6599 $ALLOWED_TAGS .= '<embed><object>';
6603 /// Some code to print tabs
6605 /// A class for tabs
6606 class tabobject {
6607 var $id;
6608 var $link;
6609 var $text;
6610 var $linkedwhenselected;
6612 /// A constructor just because I like constructors
6613 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
6614 $this->id = $id;
6615 $this->link = $link;
6616 $this->text = $text;
6617 $this->title = $title ? $title : $text;
6618 $this->linkedwhenselected = $linkedwhenselected;
6625 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
6627 * @param array $tabrows An array of rows where each row is an array of tab objects
6628 * @param string $selected The id of the selected tab (whatever row it's on)
6629 * @param array $inactive An array of ids of inactive tabs that are not selectable.
6630 * @param array $activated An array of ids of other tabs that are currently activated
6632 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
6633 global $CFG;
6635 /// $inactive must be an array
6636 if (!is_array($inactive)) {
6637 $inactive = array();
6640 /// $activated must be an array
6641 if (!is_array($activated)) {
6642 $activated = array();
6645 /// Convert the tab rows into a tree that's easier to process
6646 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
6647 return false;
6650 /// Print out the current tree of tabs (this function is recursive)
6652 $output = convert_tree_to_html($tree);
6654 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
6656 /// We're done!
6658 if ($return) {
6659 return $output;
6661 echo $output;
6665 function convert_tree_to_html($tree, $row=0) {
6667 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
6669 $first = true;
6670 $count = count($tree);
6672 foreach ($tree as $tab) {
6673 $count--; // countdown to zero
6675 $liclass = '';
6677 if ($first && ($count == 0)) { // Just one in the row
6678 $liclass = 'first last';
6679 $first = false;
6680 } else if ($first) {
6681 $liclass = 'first';
6682 $first = false;
6683 } else if ($count == 0) {
6684 $liclass = 'last';
6687 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
6688 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
6691 if ($tab->inactive || $tab->active || $tab->selected) {
6692 if ($tab->selected) {
6693 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
6694 } else if ($tab->active) {
6695 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
6699 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
6701 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
6702 // The a tag is used for styling
6703 $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
6704 } else {
6705 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
6708 if (!empty($tab->subtree)) {
6709 $str .= convert_tree_to_html($tab->subtree, $row+1);
6710 } else if ($tab->selected) {
6711 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
6714 $str .= ' </li>'."\n";
6716 $str .= '</ul>'."\n";
6718 return $str;
6722 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
6724 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
6726 $tabrows = array_reverse($tabrows);
6728 $subtree = array();
6730 foreach ($tabrows as $row) {
6731 $tree = array();
6733 foreach ($row as $tab) {
6734 $tab->inactive = in_array((string)$tab->id, $inactive);
6735 $tab->active = in_array((string)$tab->id, $activated);
6736 $tab->selected = (string)$tab->id == $selected;
6738 if ($tab->active || $tab->selected) {
6739 if ($subtree) {
6740 $tab->subtree = $subtree;
6743 $tree[] = $tab;
6745 $subtree = $tree;
6748 return $subtree;
6753 * Returns a string containing a link to the user documentation for the current
6754 * page. Also contains an icon by default. Shown to teachers and admin only.
6756 * @param string $text The text to be displayed for the link
6757 * @param string $iconpath The path to the icon to be displayed
6759 function page_doc_link($text='', $iconpath='') {
6760 global $ME, $COURSE, $CFG;
6762 if (empty($CFG->docroot) or empty($CFG->rolesactive)) {
6763 return '';
6766 if (empty($COURSE->id)) {
6767 $context = get_context_instance(CONTEXT_SYSTEM);
6768 } else {
6769 $context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
6772 if (!has_capability('moodle/site:doclinks', $context)) {
6773 return '';
6776 if (empty($CFG->pagepath)) {
6777 $CFG->pagepath = $ME;
6780 $path = str_replace($CFG->httpswwwroot.'/','', $CFG->pagepath); // Because the page could be HTTPSPAGEREQUIRED
6781 $path = str_replace('.php', '', $path);
6783 if (empty($path)) { // Not for home page
6784 return '';
6786 return doc_link($path, $text, $iconpath);
6790 * Returns a string containing a link to the user documentation.
6791 * Also contains an icon by default. Shown to teachers and admin only.
6793 * @param string $path The page link after doc root and language, no
6794 * leading slash.
6795 * @param string $text The text to be displayed for the link
6796 * @param string $iconpath The path to the icon to be displayed
6798 function doc_link($path='', $text='', $iconpath='') {
6799 global $CFG;
6801 if (empty($CFG->docroot)) {
6802 return '';
6805 $target = '';
6806 if (!empty($CFG->doctonewwindow)) {
6807 $target = ' target="_blank"';
6810 $lang = str_replace('_utf8', '', current_language());
6812 $str = '<a href="' .$CFG->docroot. '/' .$lang. '/' .$path. '"' .$target. '>';
6814 if (empty($iconpath)) {
6815 $iconpath = $CFG->httpswwwroot . '/pix/docs.gif';
6818 // alt left blank intentionally to prevent repetition in screenreaders
6819 $str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
6821 return $str;
6826 * Returns true if the current site debugging settings are equal or above specified level.
6827 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
6828 * routing of notices is controlled by $CFG->debugdisplay
6829 * eg use like this:
6831 * 1) debugging('a normal debug notice');
6832 * 2) debugging('something really picky', DEBUG_ALL);
6833 * 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
6834 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
6836 * In code blocks controlled by debugging() (such as example 4)
6837 * any output should be routed via debugging() itself, or the lower-level
6838 * trigger_error() or error_log(). Using echo or print will break XHTML
6839 * JS and HTTP headers.
6842 * @param string $message a message to print
6843 * @param int $level the level at which this debugging statement should show
6844 * @return bool
6846 function debugging($message='', $level=DEBUG_NORMAL) {
6848 global $CFG;
6850 if (empty($CFG->debug)) {
6851 return false;
6854 if ($CFG->debug >= $level) {
6855 if ($message) {
6856 $callers = debug_backtrace();
6857 $from = '<ul style="text-align: left">';
6858 foreach ($callers as $caller) {
6859 if (!isset($caller['line'])) {
6860 $caller['line'] = '?'; // probably call_user_func()
6862 if (!isset($caller['file'])) {
6863 $caller['file'] = $CFG->dirroot.'/unknownfile'; // probably call_user_func()
6865 $from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
6866 if (isset($caller['function'])) {
6867 $from .= ': call to ';
6868 if (isset($caller['class'])) {
6869 $from .= $caller['class'] . $caller['type'];
6871 $from .= $caller['function'] . '()';
6873 $from .= '</li>';
6875 $from .= '</ul>';
6876 if (!isset($CFG->debugdisplay)) {
6877 $CFG->debugdisplay = ini_get('display_errors');
6879 if ($CFG->debugdisplay) {
6880 if (!defined('DEBUGGING_PRINTED')) {
6881 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
6883 notify($message . $from, 'notifytiny');
6884 } else {
6885 trigger_error($message . $from, E_USER_NOTICE);
6888 return true;
6890 return false;
6894 * Disable debug messages from debugging(), while keeping PHP error reporting level as is.
6896 function disable_debugging() {
6897 global $CFG;
6898 $CFG->debug = $CFG->debug | 0x80000000; // switch the sign bit in integer number ;-)
6903 * Returns string to add a frame attribute, if required
6905 function frametarget() {
6906 global $CFG;
6908 if (empty($CFG->framename) or ($CFG->framename == '_top')) {
6909 return '';
6910 } else {
6911 return ' target="'.$CFG->framename.'" ';
6916 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
6917 * pages that use bits from many different files in very confusing ways (e.g. blocks).
6918 * @usage print_location_comment(__FILE__, __LINE__);
6919 * @param string $file
6920 * @param integer $line
6921 * @param boolean $return Whether to return or print the comment
6922 * @return mixed Void unless true given as third parameter
6924 function print_location_comment($file, $line, $return = false)
6926 if ($return) {
6927 return "<!-- $file at line $line -->\n";
6928 } else {
6929 echo "<!-- $file at line $line -->\n";
6935 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
6936 * provide this function with the language strings for sortasc and sortdesc.
6937 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
6938 * @param string $direction 'up' or 'down'
6939 * @param string $strsort The language string used for the alt attribute of this image
6940 * @param bool $return Whether to print directly or return the html string
6941 * @return string HTML for the image
6943 * TODO See if this isn't already defined somewhere. If not, move this to weblib
6945 function print_arrow($direction='up', $strsort=null, $return=false) {
6946 global $CFG;
6948 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
6949 return null;
6952 $return = null;
6954 switch ($direction) {
6955 case 'up':
6956 $sortdir = 'asc';
6957 break;
6958 case 'down':
6959 $sortdir = 'desc';
6960 break;
6961 case 'move':
6962 $sortdir = 'asc';
6963 break;
6964 default:
6965 $sortdir = null;
6966 break;
6969 // Prepare language string
6970 $strsort = '';
6971 if (empty($strsort) && !empty($sortdir)) {
6972 $strsort = get_string('sort' . $sortdir, 'grades');
6975 $return = ' <img src="'.$CFG->pixpath.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
6977 if ($return) {
6978 return $return;
6979 } else {
6980 echo $return;
6985 * Returns boolean true if the current language is right-to-left (Hebrew, Arabic etc)
6988 function right_to_left() {
6989 static $result;
6991 if (isset($result)) {
6992 return $result;
6994 return $result = (get_string('thisdirection') == 'rtl');
6999 * Returns swapped left<=>right if in RTL environment.
7000 * part of RTL support
7002 * @param string $align align to check
7003 * @return string
7005 function fix_align_rtl($align) {
7006 if (!right_to_left()) {
7007 return $align;
7009 if ($align=='left') { return 'right'; }
7010 if ($align=='right') { return 'left'; }
7011 return $align;
7016 * Returns true if the page is displayed in a popup window.
7017 * Gets the information from the URL parameter inpopup.
7019 * @return boolean
7021 * TODO Use a central function to create the popup calls allover Moodle and
7022 * TODO In the moment only works with resources and probably questions.
7024 function is_in_popup() {
7025 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
7027 return ($inpopup);
7031 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: