glossary->id for block is now properly recoded by restore. MDL-4934 ; merged from...
[moodle-linuxchix.git] / lib / weblib.php
blob0c692df94204d6ee53cf201b88958b8c996bbd34
1 <?php // $Id$
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.com //
9 // //
10 // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
11 // //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
16 // //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
21 // //
22 // http://www.gnu.org/copyleft/gpl.html //
23 // //
24 ///////////////////////////////////////////////////////////////////////////
26 /**
27 * Library of functions for web output
29 * Library of all general-purpose Moodle PHP functions and constants
30 * that produce HTML output
32 * Other main libraries:
33 * - datalib.php - functions that access the database.
34 * - moodlelib.php - general-purpose Moodle functions.
35 * @author Martin Dougiamas
36 * @version $Id$
37 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
38 * @package moodlecore
41 /// We are going to uses filterlib functions here
42 require_once("$CFG->libdir/filterlib.php");
44 require_once("$CFG->libdir/ajax/ajaxlib.php");
46 /// Constants
48 /// Define text formatting types ... eventually we can add Wiki, BBcode etc
50 /**
51 * Does all sorts of transformations and filtering
53 define('FORMAT_MOODLE', '0'); // Does all sorts of transformations and filtering
55 /**
56 * Plain HTML (with some tags stripped)
58 define('FORMAT_HTML', '1'); // Plain HTML (with some tags stripped)
60 /**
61 * Plain text (even tags are printed in full)
63 define('FORMAT_PLAIN', '2'); // Plain text (even tags are printed in full)
65 /**
66 * Wiki-formatted text
67 * Deprecated: left here just to note that '3' is not used (at the moment)
68 * and to catch any latent wiki-like text (which generates an error)
70 define('FORMAT_WIKI', '3'); // Wiki-formatted text
72 /**
73 * Markdown-formatted text http://daringfireball.net/projects/markdown/
75 define('FORMAT_MARKDOWN', '4'); // Markdown-formatted text http://daringfireball.net/projects/markdown/
77 /**
78 * TRUSTTEXT marker - if present in text, text cleaning should be bypassed
80 define('TRUSTTEXT', '#####TRUSTTEXT#####');
83 /**
84 * Javascript related defines
86 define('REQUIREJS_BEFOREHEADER', 0);
87 define('REQUIREJS_INHEADER', 1);
88 define('REQUIREJS_AFTERHEADER', 2);
90 /**
91 * Allowed tags - string of html tags that can be tested against for safe html tags
92 * @global string $ALLOWED_TAGS
94 global $ALLOWED_TAGS;
95 $ALLOWED_TAGS =
96 '<p><br><b><i><u><font><table><tbody><span><div><tr><td><th><ol><ul><dl><li><dt><dd><h1><h2><h3><h4><h5><h6><hr><img><a><strong><emphasis><em><sup><sub><address><cite><blockquote><pre><strike><param><acronym><nolink><lang><tex><algebra><math><mi><mn><mo><mtext><mspace><ms><mrow><mfrac><msqrt><mroot><mstyle><merror><mpadded><mphantom><mfenced><msub><msup><msubsup><munder><mover><munderover><mmultiscripts><mtable><mtr><mtd><maligngroup><malignmark><maction><cn><ci><apply><reln><fn><interval><inverse><sep><condition><declare><lambda><compose><ident><quotient><exp><factorial><divide><max><min><minus><plus><power><rem><times><root><gcd><and><or><xor><not><implies><forall><exists><abs><conjugate><eq><neq><gt><lt><geq><leq><ln><log><int><diff><partialdiff><lowlimit><uplimit><bvar><degree><set><list><union><intersect><in><notin><subset><prsubset><notsubset><notprsubset><setdiff><sum><product><limit><tendsto><mean><sdev><variance><median><mode><moment><vector><matrix><matrixrow><determinant><transpose><selector><annotation><semantics><annotation-xml><tt><code>';
98 /**
99 * Allowed protocols - array of protocols that are safe to use in links and so on
100 * @global string $ALLOWED_PROTOCOLS
102 $ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms',
103 'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style',
104 'border', 'margin', 'padding', 'background', 'text-decoration'); // CSS as well to get through kses
107 /// Functions
110 * Add quotes to HTML characters
112 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
113 * This function is very similar to {@link p()}
115 * @param string $var the string potentially containing HTML characters
116 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
117 * true should be used to print data from forms and false for data from DB.
118 * @return string
120 function s($var, $strip=false) {
122 if ($var == '0') { // for integer 0, boolean false, string '0'
123 return '0';
126 if ($strip) {
127 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars(stripslashes_safe($var)));
128 } else {
129 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars($var));
134 * Add quotes to HTML characters
136 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
137 * This function is very similar to {@link s()}
139 * @param string $var the string potentially containing HTML characters
140 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
141 * true should be used to print data from forms and false for data from DB.
142 * @return string
144 function p($var, $strip=false) {
145 echo s($var, $strip);
149 * Does proper javascript quoting.
150 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
152 * @since 1.8 - 22/02/2007
153 * @param mixed value
154 * @return mixed quoted result
156 function addslashes_js($var) {
157 if (is_string($var)) {
158 $var = str_replace('\\', '\\\\', $var);
159 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
160 $var = str_replace('</', '<\/', $var); // XHTML compliance
161 } else if (is_array($var)) {
162 $var = array_map('addslashes_js', $var);
163 } else if (is_object($var)) {
164 $a = get_object_vars($var);
165 foreach ($a as $key=>$value) {
166 $a[$key] = addslashes_js($value);
168 $var = (object)$a;
170 return $var;
174 * Remove query string from url
176 * Takes in a URL and returns it without the querystring portion
178 * @param string $url the url which may have a query string attached
179 * @return string
181 function strip_querystring($url) {
183 if ($commapos = strpos($url, '?')) {
184 return substr($url, 0, $commapos);
185 } else {
186 return $url;
191 * Returns the URL of the HTTP_REFERER, less the querystring portion if required
192 * @param boolean $stripquery if true, also removes the query part of the url.
193 * @return string
195 function get_referer($stripquery=true) {
196 if (isset($_SERVER['HTTP_REFERER'])) {
197 if ($stripquery) {
198 return strip_querystring($_SERVER['HTTP_REFERER']);
199 } else {
200 return $_SERVER['HTTP_REFERER'];
202 } else {
203 return '';
209 * Returns the name of the current script, WITH the querystring portion.
210 * this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
211 * return different things depending on a lot of things like your OS, Web
212 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
213 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
215 * @return string
217 function me() {
219 if (!empty($_SERVER['REQUEST_URI'])) {
220 return $_SERVER['REQUEST_URI'];
222 } else if (!empty($_SERVER['PHP_SELF'])) {
223 if (!empty($_SERVER['QUERY_STRING'])) {
224 return $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
226 return $_SERVER['PHP_SELF'];
228 } else if (!empty($_SERVER['SCRIPT_NAME'])) {
229 if (!empty($_SERVER['QUERY_STRING'])) {
230 return $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
232 return $_SERVER['SCRIPT_NAME'];
234 } else if (!empty($_SERVER['URL'])) { // May help IIS (not well tested)
235 if (!empty($_SERVER['QUERY_STRING'])) {
236 return $_SERVER['URL'] .'?'. $_SERVER['QUERY_STRING'];
238 return $_SERVER['URL'];
240 } else {
241 notify('Warning: Could not find any of these web server variables: $REQUEST_URI, $PHP_SELF, $SCRIPT_NAME or $URL');
242 return false;
247 * Like {@link me()} but returns a full URL
248 * @see me()
249 * @return string
251 function qualified_me() {
253 global $CFG;
255 if (!empty($CFG->wwwroot)) {
256 $url = parse_url($CFG->wwwroot);
259 if (!empty($url['host'])) {
260 $hostname = $url['host'];
261 } else if (!empty($_SERVER['SERVER_NAME'])) {
262 $hostname = $_SERVER['SERVER_NAME'];
263 } else if (!empty($_ENV['SERVER_NAME'])) {
264 $hostname = $_ENV['SERVER_NAME'];
265 } else if (!empty($_SERVER['HTTP_HOST'])) {
266 $hostname = $_SERVER['HTTP_HOST'];
267 } else if (!empty($_ENV['HTTP_HOST'])) {
268 $hostname = $_ENV['HTTP_HOST'];
269 } else {
270 notify('Warning: could not find the name of this server!');
271 return false;
274 if (!empty($url['port'])) {
275 $hostname .= ':'.$url['port'];
276 } else if (!empty($_SERVER['SERVER_PORT'])) {
277 if ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
278 $hostname .= ':'.$_SERVER['SERVER_PORT'];
282 // TODO, this does not work in the situation described in MDL-11061, but
283 // I don't know how to fix it. Possibly believe $CFG->wwwroot ahead of what
284 // the server reports.
285 if (isset($_SERVER['HTTPS'])) {
286 $protocol = ($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
287 } else if (isset($_SERVER['SERVER_PORT'])) { # Apache2 does not export $_SERVER['HTTPS']
288 $protocol = ($_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
289 } else {
290 $protocol = 'http://';
293 $url_prefix = $protocol.$hostname;
294 return $url_prefix . me();
299 * Class for creating and manipulating urls.
301 * See short write up here http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url
303 class moodle_url {
304 var $scheme = '';// e.g. http
305 var $host = '';
306 var $port = '';
307 var $user = '';
308 var $pass = '';
309 var $path = '';
310 var $fragment = '';
311 var $params = array(); //associative array of query string params
314 * Pass no arguments to create a url that refers to this page. Use empty string to create empty url.
316 * @param string $url url default null means use this page url with no query string
317 * empty string means empty url.
318 * if you pass any other type of url it will be parsed into it's bits, including query string
319 * @param array $params these params override anything in the query string where params have the same name.
321 function moodle_url($url = null, $params = array()){
322 global $FULLME;
323 if ($url !== ''){
324 if ($url === null){
325 $url = strip_querystring($FULLME);
327 $parts = parse_url($url);
328 if ($parts === FALSE){
329 error('invalidurl');
331 if (isset($parts['query'])){
332 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
334 unset($parts['query']);
335 foreach ($parts as $key => $value){
336 $this->$key = $value;
338 $this->params($params);
342 * Add an array of params to the params for this page. The added params override existing ones if they
343 * have the same name.
345 * @param array $params
347 function params($params){
348 $this->params = $params + $this->params;
352 * Remove all params if no arguments passed. Or else remove param $arg1, $arg2, etc.
354 * @param string $arg1
355 * @param string $arg2
356 * @param string $arg3
358 function remove_params(){
359 if ($thisargs = func_get_args()){
360 foreach ($thisargs as $arg){
361 if (isset($this->params->$arg)){
362 unset($this->params->$arg);
365 } else { // no args
366 $this->params = array();
371 * Add a param to the params for this page. The added param overrides existing one if they
372 * have the same name.
374 * @param string $paramname name
375 * @param string $param value
377 function param($paramname, $param){
378 $this->params = array($paramname => $param) + $this->params;
382 function get_query_string($overrideparams = array()){
383 $arr = array();
384 $params = $overrideparams + $this->params;
385 foreach ($params as $key => $val){
386 $arr[] = urlencode($key)."=".urlencode($val);
388 return implode($arr, "&amp;");
391 * Outputs params as hidden form elements.
393 * @param array $exclude params to ignore
394 * @param integer $indent indentation
395 * @return string html for form elements.
397 function hidden_params_out($exclude = array(), $indent = 0){
398 $tabindent = str_repeat("\t", $indent);
399 $str = '';
400 foreach ($this->params as $key => $val){
401 if (FALSE === array_search($key, $exclude)) {
402 $val = s($val);
403 $str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
406 return $str;
409 * Output url
411 * @param boolean $noquerystring whether to output page params as a query string in the url.
412 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
413 * @return string url
415 function out($noquerystring = false, $overrideparams = array()) {
416 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
417 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
418 $uri .= $this->host ? $this->host : '';
419 $uri .= $this->port ? ':'.$this->port : '';
420 $uri .= $this->path ? $this->path : '';
421 if (!$noquerystring){
422 $uri .= (count($this->params)||count($overrideparams)) ? '?'.$this->get_query_string($overrideparams) : '';
424 $uri .= $this->fragment ? '#'.$this->fragment : '';
425 return $uri;
428 * Output action url with sesskey
430 * @param boolean $noquerystring whether to output page params as a query string in the url.
431 * @return string url
433 function out_action($overrideparams = array()) {
434 $overrideparams = array('sesskey'=> sesskey()) + $overrideparams;
435 return $this->out(false, $overrideparams);
440 * Determine if there is data waiting to be processed from a form
442 * Used on most forms in Moodle to check for data
443 * Returns the data as an object, if it's found.
444 * This object can be used in foreach loops without
445 * casting because it's cast to (array) automatically
447 * Checks that submitted POST data exists and returns it as object.
449 * @param string $url not used anymore
450 * @return mixed false or object
452 function data_submitted($url='') {
454 if (empty($_POST)) {
455 return false;
456 } else {
457 return (object)$_POST;
462 * Moodle replacement for php stripslashes() function,
463 * works also for objects and arrays.
465 * The standard php stripslashes() removes ALL backslashes
466 * even from strings - so C:\temp becomes C:temp - this isn't good.
467 * This function should work as a fairly safe replacement
468 * to be called on quoted AND unquoted strings (to be sure)
470 * @param mixed something to remove unsafe slashes from
471 * @return mixed
473 function stripslashes_safe($mixed) {
474 // there is no need to remove slashes from int, float and bool types
475 if (empty($mixed)) {
476 //nothing to do...
477 } else if (is_string($mixed)) {
478 if (ini_get_bool('magic_quotes_sybase')) { //only unescape single quotes
479 $mixed = str_replace("''", "'", $mixed);
480 } else { //the rest, simple and double quotes and backslashes
481 $mixed = str_replace("\\'", "'", $mixed);
482 $mixed = str_replace('\\"', '"', $mixed);
483 $mixed = str_replace('\\\\', '\\', $mixed);
485 } else if (is_array($mixed)) {
486 foreach ($mixed as $key => $value) {
487 $mixed[$key] = stripslashes_safe($value);
489 } else if (is_object($mixed)) {
490 $vars = get_object_vars($mixed);
491 foreach ($vars as $key => $value) {
492 $mixed->$key = stripslashes_safe($value);
496 return $mixed;
500 * Recursive implementation of stripslashes()
502 * This function will allow you to strip the slashes from a variable.
503 * If the variable is an array or object, slashes will be stripped
504 * from the items (or properties) it contains, even if they are arrays
505 * or objects themselves.
507 * @param mixed the variable to remove slashes from
508 * @return mixed
510 function stripslashes_recursive($var) {
511 if (is_object($var)) {
512 $new_var = new object();
513 $properties = get_object_vars($var);
514 foreach($properties as $property => $value) {
515 $new_var->$property = stripslashes_recursive($value);
518 } else if(is_array($var)) {
519 $new_var = array();
520 foreach($var as $property => $value) {
521 $new_var[$property] = stripslashes_recursive($value);
524 } else if(is_string($var)) {
525 $new_var = stripslashes($var);
527 } else {
528 $new_var = $var;
531 return $new_var;
535 * Recursive implementation of addslashes()
537 * This function will allow you to add the slashes from a variable.
538 * If the variable is an array or object, slashes will be added
539 * to the items (or properties) it contains, even if they are arrays
540 * or objects themselves.
542 * @param mixed the variable to add slashes from
543 * @return mixed
545 function addslashes_recursive($var) {
546 if (is_object($var)) {
547 $new_var = new object();
548 $properties = get_object_vars($var);
549 foreach($properties as $property => $value) {
550 $new_var->$property = addslashes_recursive($value);
553 } else if (is_array($var)) {
554 $new_var = array();
555 foreach($var as $property => $value) {
556 $new_var[$property] = addslashes_recursive($value);
559 } else if (is_string($var)) {
560 $new_var = addslashes($var);
562 } else { // nulls, integers, etc.
563 $new_var = $var;
566 return $new_var;
570 * Given some normal text this function will break up any
571 * long words to a given size by inserting the given character
573 * It's multibyte savvy and doesn't change anything inside html tags.
575 * @param string $string the string to be modified
576 * @param int $maxsize maximum length of the string to be returned
577 * @param string $cutchar the string used to represent word breaks
578 * @return string
580 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
582 /// Loading the textlib singleton instance. We are going to need it.
583 $textlib = textlib_get_instance();
585 /// First of all, save all the tags inside the text to skip them
586 $tags = array();
587 filter_save_tags($string,$tags);
589 /// Process the string adding the cut when necessary
590 $output = '';
591 $length = $textlib->strlen($string);
592 $wordlength = 0;
594 for ($i=0; $i<$length; $i++) {
595 $char = $textlib->substr($string, $i, 1);
596 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
597 $wordlength = 0;
598 } else {
599 $wordlength++;
600 if ($wordlength > $maxsize) {
601 $output .= $cutchar;
602 $wordlength = 0;
605 $output .= $char;
608 /// Finally load the tags back again
609 if (!empty($tags)) {
610 $output = str_replace(array_keys($tags), $tags, $output);
613 return $output;
617 * This does a search and replace, ignoring case
618 * This function is only used for versions of PHP older than version 5
619 * which do not have a native version of this function.
620 * Taken from the PHP manual, by bradhuizenga @ softhome.net
622 * @param string $find the string to search for
623 * @param string $replace the string to replace $find with
624 * @param string $string the string to search through
625 * return string
627 if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
628 function str_ireplace($find, $replace, $string) {
630 if (!is_array($find)) {
631 $find = array($find);
634 if(!is_array($replace)) {
635 if (!is_array($find)) {
636 $replace = array($replace);
637 } else {
638 // this will duplicate the string into an array the size of $find
639 $c = count($find);
640 $rString = $replace;
641 unset($replace);
642 for ($i = 0; $i < $c; $i++) {
643 $replace[$i] = $rString;
648 foreach ($find as $fKey => $fItem) {
649 $between = explode(strtolower($fItem),strtolower($string));
650 $pos = 0;
651 foreach($between as $bKey => $bItem) {
652 $between[$bKey] = substr($string,$pos,strlen($bItem));
653 $pos += strlen($bItem) + strlen($fItem);
655 $string = implode($replace[$fKey],$between);
657 return ($string);
662 * Locate the position of a string in another string
664 * This function is only used for versions of PHP older than version 5
665 * which do not have a native version of this function.
666 * Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
668 * @param string $haystack The string to be searched
669 * @param string $needle The string to search for
670 * @param int $offset The position in $haystack where the search should begin.
672 if (!function_exists('stripos')) { /// Only exists in PHP 5
673 function stripos($haystack, $needle, $offset=0) {
675 return strpos(strtoupper($haystack), strtoupper($needle), $offset);
680 * This function will print a button/link/etc. form element
681 * that will work on both Javascript and non-javascript browsers.
682 * Relies on the Javascript function openpopup in javascript.php
684 * All parameters default to null, only $type and $url are mandatory.
686 * $url must be relative to home page eg /mod/survey/stuff.php
687 * @param string $url Web link relative to home page
688 * @param string $name Name to be assigned to the popup window (this is used by
689 * client-side scripts to "talk" to the popup window)
690 * @param string $linkname Text to be displayed as web link
691 * @param int $height Height to assign to popup window
692 * @param int $width Height to assign to popup window
693 * @param string $title Text to be displayed as popup page title
694 * @param string $options List of additional options for popup window
695 * @param string $return If true, return as a string, otherwise print
696 * @param string $id id added to the element
697 * @param string $class class added to the element
698 * @return string
699 * @uses $CFG
701 function element_to_popup_window ($type=null, $url=null, $name=null, $linkname=null,
702 $height=400, $width=500, $title=null,
703 $options=null, $return=false, $id=null, $class=null) {
705 if (is_null($url)) {
706 error('There must be an url to the popup. Can\'t create popup window.');
709 global $CFG;
711 if ($options == 'none') { // 'none' is legacy, should be removed in v2.0
712 $options = null;
715 // add some sane default options for popup windows
716 if (!$options) {
717 $options = 'menubar=0,location=0,scrollbars,resizable';
719 if ($width) {
720 $options .= ',width='. $width;
722 if ($height) {
723 $options .= ',height='. $height;
725 if ($id) {
726 $id = ' id="'.$id.'" ';
728 if ($class) {
729 $class = ' class="'.$class.'" ';
731 if (!$name) {
732 $name = 'popup';
735 // get some default string, using the localized version of legacy defaults
736 if (!$linkname) {
737 $linkname = get_string('clickhere');
739 if (!$title) {
740 $title = get_string('popupwindowname');
743 $fullscreen = 0; // must be passed to openpopup
744 $element = '';
746 switch ($type) {
747 case 'button' :
748 $element = '<input type="button" name="'. $name .'" title="'. $title .'" value="'. $linkname .'" '. $id . $class .
749 "onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
750 break;
751 case 'link' :
752 // some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
753 if (!(strpos($url,$CFG->wwwroot) === false)) {
754 $url = substr($url, strlen($CFG->wwwroot));
756 $element = '<a title="'. s(strip_tags($title)) .'" href="'. $CFG->wwwroot . $url .'" '.
757 "onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
758 break;
759 default :
760 error('Undefined element - can\'t create popup window.');
761 break;
764 if ($return) {
765 return $element;
766 } else {
767 echo $element;
772 * Creates and displays (or returns) a link to a popup window, using element_to_popup_window function.
774 * @return string html code to display a link to a popup window.
775 * @see element_to_popup_window()
777 function link_to_popup_window ($url, $name=null, $linkname=null,
778 $height=400, $width=500, $title=null,
779 $options=null, $return=false) {
781 return element_to_popup_window('link', $url, $name, $linkname, $height, $width, $title, $options, $return, null, null);
785 * Creates and displays (or returns) a buttons to a popup window, using element_to_popup_window function.
787 * @return string html code to display a button to a popup window.
788 * @see element_to_popup_window()
790 function button_to_popup_window ($url, $name=null, $linkname=null,
791 $height=400, $width=500, $title=null, $options=null, $return=false,
792 $id=null, $class=null) {
794 return element_to_popup_window('button', $url, $name, $linkname, $height, $width, $title, $options, $return, $id, $class);
799 * Prints a simple button to close a window
800 * @param string $name name of the window to close
801 * @param boolean $return whether this function should return a string or output it
802 * @return string if $return is true, nothing otherwise
804 function close_window_button($name='closewindow', $return=false) {
805 global $CFG;
807 $output = '';
809 $output .= '<div class="closewindow">' . "\n";
810 $output .= '<form action="'.$CFG->wwwroot.'"><div>'; // We don't use this
811 $output .= '<input type="button" onclick="self.close();" value="'.get_string($name).'" />';
812 $output .= '</div></form>';
813 $output .= '</div>' . "\n";
815 if ($return) {
816 return $output;
817 } else {
818 echo $output;
823 * Try and close the current window immediately using Javascript
824 * @param int $delay the delay in seconds before closing the window
826 function close_window($delay=0) {
828 <script type="text/javascript">
829 //<![CDATA[
830 function close_this_window() {
831 self.close();
833 setTimeout("close_this_window()", <?php echo $delay * 1000 ?>);
834 //]]>
835 </script>
836 <noscript><center>
837 <?php print_string('pleaseclose') ?>
838 </center></noscript>
839 <?php
840 die;
845 * Given an array of values, output the HTML for a select element with those options.
846 * Normally, you only need to use the first few parameters.
848 * @param array $options The options to offer. An array of the form
849 * $options[{value}] = {text displayed for that option};
850 * @param string $name the name of this form control, as in &lt;select name="..." ...
851 * @param string $selected the option to select initially, default none.
852 * @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
853 * Set this to '' if you don't want a 'nothing is selected' option.
854 * @param string $script in not '', then this is added to the &lt;select> element as an onchange handler.
855 * @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
856 * @param boolean $return if false (the default) the the output is printed directly, If true, the
857 * generated HTML is returned as a string.
858 * @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
859 * @param int $tabindex if give, sets the tabindex attribute on the &lt;select> element. Default none.
860 * @param string $id value to use for the id attribute of the &lt;select> element. If none is given,
861 * then a suitable one is constructed.
863 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
864 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0, $id='') {
866 if ($nothing == 'choose') {
867 $nothing = get_string('choose') .'...';
870 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
871 if ($disabled) {
872 $attributes .= ' disabled="disabled"';
875 if ($tabindex) {
876 $attributes .= ' tabindex="'.$tabindex.'"';
879 if ($id ==='') {
880 $id = 'menu'.$name;
881 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
882 $id = str_replace('[', '', $id);
883 $id = str_replace(']', '', $id);
886 $output = '<select id="'.$id.'" name="'. $name .'" '. $attributes .'>' . "\n";
887 if ($nothing) {
888 $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
889 if ($nothingvalue === $selected) {
890 $output .= ' selected="selected"';
892 $output .= '>'. $nothing .'</option>' . "\n";
894 if (!empty($options)) {
895 foreach ($options as $value => $label) {
896 $output .= ' <option value="'. s($value) .'"';
897 if ((string)$value == (string)$selected) {
898 $output .= ' selected="selected"';
900 if ($label === '') {
901 $output .= '>'. $value .'</option>' . "\n";
902 } else {
903 $output .= '>'. $label .'</option>' . "\n";
907 $output .= '</select>' . "\n";
909 if ($return) {
910 return $output;
911 } else {
912 echo $output;
917 * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
918 * Other options like choose_from_menu.
919 * @param string $name
920 * @param string $selected
921 * @param string $string (defaults to '')
922 * @param boolean $return whether this function should return a string or output it (defaults to false)
923 * @param boolean $disabled (defaults to false)
924 * @param int $tabindex
926 function choose_from_menu_yesno($name, $selected, $script = '',
927 $return = false, $disabled = false, $tabindex = 0) {
928 return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
929 $selected, '', $script, '0', $return, $disabled, $tabindex);
933 * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
934 * including option headings with the first level.
936 function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
937 $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
939 if ($nothing == 'choose') {
940 $nothing = get_string('choose') .'...';
943 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
944 if ($disabled) {
945 $attributes .= ' disabled="disabled"';
948 if ($tabindex) {
949 $attributes .= ' tabindex="'.$tabindex.'"';
952 $output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
953 if ($nothing) {
954 $output .= ' <option value="'. $nothingvalue .'"'. "\n";
955 if ($nothingvalue === $selected) {
956 $output .= ' selected="selected"';
958 $output .= '>'. $nothing .'</option>' . "\n";
960 if (!empty($options)) {
961 foreach ($options as $section => $values) {
963 $output .= ' <optgroup label="'. s(format_string($section)) .'">'."\n";
964 foreach ($values as $value => $label) {
965 $output .= ' <option value="'. format_string($value) .'"';
966 if ((string)$value == (string)$selected) {
967 $output .= ' selected="selected"';
969 if ($label === '') {
970 $output .= '>'. $value .'</option>' . "\n";
971 } else {
972 $output .= '>'. $label .'</option>' . "\n";
975 $output .= ' </optgroup>'."\n";
978 $output .= '</select>' . "\n";
980 if ($return) {
981 return $output;
982 } else {
983 echo $output;
989 * Given an array of values, creates a group of radio buttons to be part of a form
991 * @param array $options An array of value-label pairs for the radio group (values as keys)
992 * @param string $name Name of the radiogroup (unique in the form)
993 * @param string $checked The value that is already checked
995 function choose_from_radio ($options, $name, $checked='', $return=false) {
997 static $idcounter = 0;
999 if (!$name) {
1000 $name = 'unnamed';
1003 $output = '<span class="radiogroup '.$name."\">\n";
1005 if (!empty($options)) {
1006 $currentradio = 0;
1007 foreach ($options as $value => $label) {
1008 $htmlid = 'auto-rb'.sprintf('%04d', ++$idcounter);
1009 $output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
1010 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
1011 if ($value == $checked) {
1012 $output .= ' checked="checked"';
1014 if ($label === '') {
1015 $output .= ' /> <label for="'.$htmlid.'">'. $value .'</label></span>' . "\n";
1016 } else {
1017 $output .= ' /> <label for="'.$htmlid.'">'. $label .'</label></span>' . "\n";
1019 $currentradio = ($currentradio + 1) % 2;
1023 $output .= '</span>' . "\n";
1025 if ($return) {
1026 return $output;
1027 } else {
1028 echo $output;
1032 /** Display an standard html checkbox with an optional label
1034 * @param string $name The name of the checkbox
1035 * @param string $value The valus that the checkbox will pass when checked
1036 * @param boolean $checked The flag to tell the checkbox initial state
1037 * @param string $label The label to be showed near the checkbox
1038 * @param string $alt The info to be inserted in the alt tag
1040 function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
1042 static $idcounter = 0;
1044 if (!$name) {
1045 $name = 'unnamed';
1048 if ($alt) {
1049 $alt = strip_tags($alt);
1050 } else {
1051 $alt = 'checkbox';
1054 if ($checked) {
1055 $strchecked = ' checked="checked"';
1056 } else {
1057 $strchecked = '';
1060 $htmlid = 'auto-cb'.sprintf('%04d', ++$idcounter);
1061 $output = '<span class="checkbox '.$name."\">";
1062 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ? ' onclick="'.$script.'" ' : '').' />';
1063 if(!empty($label)) {
1064 $output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
1066 $output .= '</span>'."\n";
1068 if (empty($return)) {
1069 echo $output;
1070 } else {
1071 return $output;
1076 /** Display an standard html text field with an optional label
1078 * @param string $name The name of the text field
1079 * @param string $value The value of the text field
1080 * @param string $label The label to be showed near the text field
1081 * @param string $alt The info to be inserted in the alt tag
1083 function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
1085 static $idcounter = 0;
1087 if (empty($name)) {
1088 $name = 'unnamed';
1091 if (empty($alt)) {
1092 $alt = 'textfield';
1095 if (!empty($maxlength)) {
1096 $maxlength = ' maxlength="'.$maxlength.'" ';
1099 $htmlid = 'auto-tf'.sprintf('%04d', ++$idcounter);
1100 $output = '<span class="textfield '.$name."\">";
1101 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
1103 $output .= '</span>'."\n";
1105 if (empty($return)) {
1106 echo $output;
1107 } else {
1108 return $output;
1115 * Implements a complete little popup form
1117 * @uses $CFG
1118 * @param string $common The URL up to the point of the variable that changes
1119 * @param array $options Alist of value-label pairs for the popup list
1120 * @param string $formid Id must be unique on the page (originaly $formname)
1121 * @param string $selected The option that is already selected
1122 * @param string $nothing The label for the "no choice" option
1123 * @param string $help The name of a help page if help is required
1124 * @param string $helptext The name of the label for the help button
1125 * @param boolean $return Indicates whether the function should return the text
1126 * as a string or echo it directly to the page being rendered
1127 * @param string $targetwindow The name of the target page to open the linked page in.
1128 * @param string $selectlabel Text to place in a [label] element - preferred for accessibility.
1129 * @param array $optionsextra TODO, an array?
1130 * @return string If $return is true then the entire form is returned as a string.
1131 * @todo Finish documenting this function<br>
1133 function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
1134 $targetwindow='self', $selectlabel='', $optionsextra=NULL) {
1136 global $CFG;
1137 static $go, $choose; /// Locally cached, in case there's lots on a page
1139 if (empty($options)) {
1140 return '';
1143 if (!isset($go)) {
1144 $go = get_string('go');
1147 if ($nothing == 'choose') {
1148 if (!isset($choose)) {
1149 $choose = get_string('choose');
1151 $nothing = $choose.'...';
1154 // changed reference to document.getElementById('id_abc') instead of document.abc
1155 // MDL-7861
1156 $output = '<form action="'.$CFG->wwwroot.'/course/jumpto.php"'.
1157 ' method="get" '.
1158 $CFG->frametarget.
1159 ' id="'.$formid.'"'.
1160 ' class="popupform">';
1161 if ($help) {
1162 $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
1163 } else {
1164 $button = '';
1167 if ($selectlabel) {
1168 $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
1171 $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";
1173 if ($nothing != '') {
1174 $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
1177 $inoptgroup = false;
1179 foreach ($options as $value => $label) {
1181 if ($label == '--') { /// we are ending previous optgroup
1182 /// Check to see if we already have a valid open optgroup
1183 /// XHTML demands that there be at least 1 option within an optgroup
1184 if ($inoptgroup and (count($optgr) > 1) ) {
1185 $output .= implode('', $optgr);
1186 $output .= ' </optgroup>';
1188 $optgr = array();
1189 $inoptgroup = false;
1190 continue;
1191 } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
1193 /// Check to see if we already have a valid open optgroup
1194 /// XHTML demands that there be at least 1 option within an optgroup
1195 if ($inoptgroup and (count($optgr) > 1) ) {
1196 $output .= implode('', $optgr);
1197 $output .= ' </optgroup>';
1200 unset($optgr);
1201 $optgr = array();
1203 $optgr[] = ' <optgroup label="'. s(format_string(substr($label,2))) .'">'; // Plain labels
1205 $inoptgroup = true; /// everything following will be in an optgroup
1206 continue;
1208 } else {
1209 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()]))
1211 $url=sid_process_url( $common . $value );
1212 } else
1214 $url=$common . $value;
1216 $optstr = ' <option value="' . $url . '"';
1218 if ($value == $selected) {
1219 $optstr .= ' selected="selected"';
1222 if (!empty($optionsextra[$value])) {
1223 $optstr .= ' '.$optionsextra[$value];
1226 if ($label) {
1227 $optstr .= '>'. $label .'</option>' . "\n";
1228 } else {
1229 $optstr .= '>'. $value .'</option>' . "\n";
1232 if ($inoptgroup) {
1233 $optgr[] = $optstr;
1234 } else {
1235 $output .= $optstr;
1241 /// catch the final group if not closed
1242 if ($inoptgroup and count($optgr) > 1) {
1243 $output .= implode('', $optgr);
1244 $output .= ' </optgroup>';
1247 $output .= '</select>';
1248 $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1249 $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
1250 $output .= '<input type="submit" value="'.$go.'" /></div>';
1251 $output .= '<script type="text/javascript">'.
1252 "\n//<![CDATA[\n".
1253 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
1254 "\n//]]>\n".'</script>';
1255 $output .= '</div>';
1256 $output .= '</form>';
1258 if ($return) {
1259 return $output;
1260 } else {
1261 echo $output;
1267 * Prints some red text
1269 * @param string $error The text to be displayed in red
1271 function formerr($error) {
1273 if (!empty($error)) {
1274 echo '<span class="error">'. $error .'</span>';
1279 * Validates an email to make sure it makes sense.
1281 * @param string $address The email address to validate.
1282 * @return boolean
1284 function validate_email($address) {
1286 return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1287 '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1288 '@'.
1289 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1290 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
1291 $address));
1295 * Extracts file argument either from file parameter or PATH_INFO
1297 * @param string $scriptname name of the calling script
1298 * @return string file path (only safe characters)
1300 function get_file_argument($scriptname) {
1301 global $_SERVER;
1303 $relativepath = FALSE;
1305 // first try normal parameter (compatible method == no relative links!)
1306 $relativepath = optional_param('file', FALSE, PARAM_PATH);
1307 if ($relativepath === '/testslasharguments') {
1308 echo 'test -1 : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
1309 die;
1312 // then try extract file from PATH_INFO (slasharguments method)
1313 if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
1314 $path_info = $_SERVER['PATH_INFO'];
1315 // check that PATH_INFO works == must not contain the script name
1316 if (!strpos($path_info, $scriptname)) {
1317 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1318 if ($relativepath === '/testslasharguments') {
1319 echo 'test 1 : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
1320 die;
1325 // now if both fail try the old way
1326 // (for compatibility with misconfigured or older buggy php implementations)
1327 if (!$relativepath) {
1328 $arr = explode($scriptname, me());
1329 if (!empty($arr[1])) {
1330 $path_info = strip_querystring($arr[1]);
1331 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1332 if ($relativepath === '/testslasharguments') {
1333 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
1334 die;
1339 return $relativepath;
1343 * Searches the current environment variables for some slash arguments
1345 * @param string $file ?
1346 * @todo Finish documenting this function
1348 function get_slash_arguments($file='file.php') {
1350 if (!$string = me()) {
1351 return false;
1354 $pathinfo = explode($file, $string);
1356 if (!empty($pathinfo[1])) {
1357 return addslashes($pathinfo[1]);
1358 } else {
1359 return false;
1364 * Extracts arguments from "/foo/bar/something"
1365 * eg http://mysite.com/script.php/foo/bar/something
1367 * @param string $string ?
1368 * @param int $i ?
1369 * @return array|string
1370 * @todo Finish documenting this function
1372 function parse_slash_arguments($string, $i=0) {
1374 if (detect_munged_arguments($string)) {
1375 return false;
1377 $args = explode('/', $string);
1379 if ($i) { // return just the required argument
1380 return $args[$i];
1382 } else { // return the whole array
1383 array_shift($args); // get rid of the empty first one
1384 return $args;
1389 * Just returns an array of text formats suitable for a popup menu
1391 * @uses FORMAT_MOODLE
1392 * @uses FORMAT_HTML
1393 * @uses FORMAT_PLAIN
1394 * @uses FORMAT_MARKDOWN
1395 * @return array
1397 function format_text_menu() {
1399 return array (FORMAT_MOODLE => get_string('formattext'),
1400 FORMAT_HTML => get_string('formathtml'),
1401 FORMAT_PLAIN => get_string('formatplain'),
1402 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1406 * Given text in a variety of format codings, this function returns
1407 * the text as safe HTML.
1409 * This function should mainly be used for long strings like posts,
1410 * answers, glossary items etc. For short strings @see format_string().
1412 * @uses $CFG
1413 * @uses FORMAT_MOODLE
1414 * @uses FORMAT_HTML
1415 * @uses FORMAT_PLAIN
1416 * @uses FORMAT_WIKI
1417 * @uses FORMAT_MARKDOWN
1418 * @param string $text The text to be formatted. This is raw text originally from user input.
1419 * @param int $format Identifier of the text format to be used
1420 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1421 * @param array $options ?
1422 * @param int $courseid ?
1423 * @return string
1424 * @todo Finish documenting this function
1426 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1428 global $CFG, $COURSE;
1430 static $croncache = array();
1432 if ($text === '') {
1433 return ''; // no need to do any filters and cleaning
1436 if (!isset($options->trusttext)) {
1437 $options->trusttext = false;
1440 if (!isset($options->noclean)) {
1441 $options->noclean=false;
1443 if (!isset($options->nocache)) {
1444 $options->nocache=false;
1446 if (!isset($options->smiley)) {
1447 $options->smiley=true;
1449 if (!isset($options->filter)) {
1450 $options->filter=true;
1452 if (!isset($options->para)) {
1453 $options->para=true;
1455 if (!isset($options->newlines)) {
1456 $options->newlines=true;
1459 if (empty($courseid)) {
1460 $courseid = $COURSE->id;
1463 if (!empty($CFG->cachetext) and empty($options->nocache)) {
1464 $time = time() - $CFG->cachetext;
1465 $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);
1467 if (defined('FULLME') and FULLME == 'cron') {
1468 if (isset($croncache[$md5key])) {
1469 return $croncache[$md5key];
1473 if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
1474 if ($oldcacheitem->timemodified >= $time) {
1475 if (defined('FULLME') and FULLME == 'cron') {
1476 if (count($croncache) > 150) {
1477 reset($croncache);
1478 $key = key($croncache);
1479 unset($croncache[$key]);
1481 $croncache[$md5key] = $oldcacheitem->formattedtext;
1483 return $oldcacheitem->formattedtext;
1488 // trusttext overrides the noclean option!
1489 if ($options->trusttext) {
1490 if (trusttext_present($text)) {
1491 $text = trusttext_strip($text);
1492 if (!empty($CFG->enabletrusttext)) {
1493 $options->noclean = true;
1494 } else {
1495 $options->noclean = false;
1497 } else {
1498 $options->noclean = false;
1500 } else if (!debugging('', DEBUG_DEVELOPER)) {
1501 // strip any forgotten trusttext in non-developer mode
1502 // do not forget to disable text cache when debugging trusttext!!
1503 $text = trusttext_strip($text);
1506 $CFG->currenttextiscacheable = true; // Default status - can be changed by any filter
1508 switch ($format) {
1509 case FORMAT_HTML:
1510 if ($options->smiley) {
1511 replace_smilies($text);
1513 if (!$options->noclean) {
1514 $text = clean_text($text, FORMAT_HTML);
1516 if ($options->filter) {
1517 $text = filter_text($text, $courseid);
1519 break;
1521 case FORMAT_PLAIN:
1522 $text = s($text); // cleans dangerous JS
1523 $text = rebuildnolinktag($text);
1524 $text = str_replace(' ', '&nbsp; ', $text);
1525 $text = nl2br($text);
1526 break;
1528 case FORMAT_WIKI:
1529 // this format is deprecated
1530 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1531 this message as all texts should have been converted to Markdown format instead.
1532 Please post a bug report to http://moodle.org/bugs with information about where you
1533 saw this message.</p>'.s($text);
1534 break;
1536 case FORMAT_MARKDOWN:
1537 $text = markdown_to_html($text);
1538 if ($options->smiley) {
1539 replace_smilies($text);
1541 if (!$options->noclean) {
1542 $text = clean_text($text, FORMAT_HTML);
1545 if ($options->filter) {
1546 $text = filter_text($text, $courseid);
1548 break;
1550 default: // FORMAT_MOODLE or anything else
1551 $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
1552 if (!$options->noclean) {
1553 $text = clean_text($text, FORMAT_HTML);
1556 if ($options->filter) {
1557 $text = filter_text($text, $courseid);
1559 break;
1562 if (empty($options->nocache) and !empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
1563 if (defined('FULLME') and FULLME == 'cron') {
1564 // special static cron cache - no need to store it in db if its not already there
1565 if (count($croncache) > 150) {
1566 reset($croncache);
1567 $key = key($croncache);
1568 unset($croncache[$key]);
1570 $croncache[$md5key] = $text;
1571 return $text;
1574 $newcacheitem = new object();
1575 $newcacheitem->md5key = $md5key;
1576 $newcacheitem->formattedtext = addslashes($text);
1577 $newcacheitem->timemodified = time();
1578 if ($oldcacheitem) { // See bug 4677 for discussion
1579 $newcacheitem->id = $oldcacheitem->id;
1580 @update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1581 // It's unlikely that the cron cache cleaner could have
1582 // deleted this entry in the meantime, as it allows
1583 // some extra time to cover these cases.
1584 } else {
1585 @insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1586 // Again, it's possible that another user has caused this
1587 // record to be created already in the time that it took
1588 // to traverse this function. That's OK too, as the
1589 // call above handles duplicate entries, and eventually
1590 // the cron cleaner will delete them.
1594 return $text;
1597 /** Converts the text format from the value to the 'internal'
1598 * name or vice versa. $key can either be the value or the name
1599 * and you get the other back.
1601 * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1602 * @return mixed as above but the other way around!
1604 function text_format_name( $key ) {
1605 $lookup = array();
1606 $lookup[FORMAT_MOODLE] = 'moodle';
1607 $lookup[FORMAT_HTML] = 'html';
1608 $lookup[FORMAT_PLAIN] = 'plain';
1609 $lookup[FORMAT_MARKDOWN] = 'markdown';
1610 $value = "error";
1611 if (!is_numeric($key)) {
1612 $key = strtolower( $key );
1613 $value = array_search( $key, $lookup );
1615 else {
1616 if (isset( $lookup[$key] )) {
1617 $value = $lookup[ $key ];
1620 return $value;
1624 * Resets all data related to filters, called during upgrade or when filter settings change.
1625 * @return void
1627 function reset_text_filters_cache() {
1628 global $CFG;
1630 delete_records('cache_text');
1631 $purifdir = $CFG->dataroot.'/cache/htmlpurifier';
1632 remove_dir($purifdir, true);
1635 /** Given a simple string, this function returns the string
1636 * processed by enabled string filters if $CFG->filterall is enabled
1638 * This function should be used to print short strings (non html) that
1639 * need filter processing e.g. activity titles, post subjects,
1640 * glossary concepts.
1642 * @param string $string The string to be filtered.
1643 * @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
1644 * @param int $courseid Current course as filters can, potentially, use it
1645 * @return string
1647 function format_string ($string, $striplinks=true, $courseid=NULL ) {
1649 global $CFG, $COURSE;
1651 //We'll use a in-memory cache here to speed up repeated strings
1652 static $strcache = false;
1654 if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
1655 $strcache = array();
1658 //init course id
1659 if (empty($courseid)) {
1660 $courseid = $COURSE->id;
1663 //Calculate md5
1664 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
1666 //Fetch from cache if possible
1667 if (isset($strcache[$md5])) {
1668 return $strcache[$md5];
1671 // First replace all ampersands not followed by html entity code
1672 $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1674 if (!empty($CFG->filterall)) {
1675 $string = filter_string($string, $courseid);
1678 // If the site requires it, strip ALL tags from this string
1679 if (!empty($CFG->formatstringstriptags)) {
1680 $string = strip_tags($string);
1682 // Otherwise strip just links if that is required (default)
1683 } else if ($striplinks) { //strip links in string
1684 $string = preg_replace('/(<a[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1687 //Store to cache
1688 $strcache[$md5] = $string;
1690 return $string;
1694 * Given text in a variety of format codings, this function returns
1695 * the text as plain text suitable for plain email.
1697 * @uses FORMAT_MOODLE
1698 * @uses FORMAT_HTML
1699 * @uses FORMAT_PLAIN
1700 * @uses FORMAT_WIKI
1701 * @uses FORMAT_MARKDOWN
1702 * @param string $text The text to be formatted. This is raw text originally from user input.
1703 * @param int $format Identifier of the text format to be used
1704 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1705 * @return string
1707 function format_text_email($text, $format) {
1709 switch ($format) {
1711 case FORMAT_PLAIN:
1712 return $text;
1713 break;
1715 case FORMAT_WIKI:
1716 $text = wiki_to_html($text);
1717 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1718 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
1719 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1720 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1721 break;
1723 case FORMAT_HTML:
1724 return html_to_text($text);
1725 break;
1727 case FORMAT_MOODLE:
1728 case FORMAT_MARKDOWN:
1729 default:
1730 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1731 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1732 break;
1737 * Given some text in HTML format, this function will pass it
1738 * through any filters that have been defined in $CFG->textfilterx
1739 * The variable defines a filepath to a file containing the
1740 * filter function. The file must contain a variable called
1741 * $textfilter_function which contains the name of the function
1742 * with $courseid and $text parameters
1744 * @param string $text The text to be passed through format filters
1745 * @param int $courseid ?
1746 * @return string
1747 * @todo Finish documenting this function
1749 function filter_text($text, $courseid=NULL) {
1750 global $CFG, $COURSE;
1752 if (empty($courseid)) {
1753 $courseid = $COURSE->id; // (copied from format_text)
1756 if (!empty($CFG->textfilters)) {
1757 require_once($CFG->libdir.'/filterlib.php');
1758 $textfilters = explode(',', $CFG->textfilters);
1759 foreach ($textfilters as $textfilter) {
1760 if (is_readable($CFG->dirroot .'/'. $textfilter .'/filter.php')) {
1761 include_once($CFG->dirroot .'/'. $textfilter .'/filter.php');
1762 $functionname = basename($textfilter).'_filter';
1763 if (function_exists($functionname)) {
1764 $text = $functionname($courseid, $text);
1770 /// <nolink> tags removed for XHTML compatibility
1771 $text = str_replace('<nolink>', '', $text);
1772 $text = str_replace('</nolink>', '', $text);
1774 return $text;
1779 * Given a string (short text) in HTML format, this function will pass it
1780 * through any filters that have been defined in $CFG->stringfilters
1781 * The variable defines a filepath to a file containing the
1782 * filter function. The file must contain a variable called
1783 * $textfilter_function which contains the name of the function
1784 * with $courseid and $text parameters
1786 * @param string $string The text to be passed through format filters
1787 * @param int $courseid The id of a course
1788 * @return string
1790 function filter_string($string, $courseid=NULL) {
1791 global $CFG, $COURSE;
1793 if (empty($CFG->textfilters)) { // All filters are disabled anyway so quit
1794 return $string;
1797 if (empty($courseid)) {
1798 $courseid = $COURSE->id;
1801 require_once($CFG->libdir.'/filterlib.php');
1803 if (isset($CFG->stringfilters)) { // We have a predefined list to use, great!
1804 if (empty($CFG->stringfilters)) { // but it's blank, so finish now
1805 return $string;
1807 $stringfilters = explode(',', $CFG->stringfilters); // ..use the list we have
1809 } else { // Otherwise try to derive a list from textfilters
1810 if (strpos($CFG->textfilters, 'filter/multilang') !== false) { // Multilang is here
1811 $stringfilters = array('filter/multilang'); // Let's use just that
1812 $CFG->stringfilters = 'filter/multilang'; // Save it for next time through
1813 } else {
1814 $CFG->stringfilters = ''; // Save the result and return
1815 return $string;
1820 foreach ($stringfilters as $stringfilter) {
1821 if (is_readable($CFG->dirroot .'/'. $stringfilter .'/filter.php')) {
1822 include_once($CFG->dirroot .'/'. $stringfilter .'/filter.php');
1823 $functionname = basename($stringfilter).'_filter';
1824 if (function_exists($functionname)) {
1825 $string = $functionname($courseid, $string);
1830 /// <nolink> tags removed for XHTML compatibility
1831 $string = str_replace('<nolink>', '', $string);
1832 $string = str_replace('</nolink>', '', $string);
1834 return $string;
1838 * Is the text marked as trusted?
1840 * @param string $text text to be searched for TRUSTTEXT marker
1841 * @return boolean
1843 function trusttext_present($text) {
1844 if (strpos($text, TRUSTTEXT) !== FALSE) {
1845 return true;
1846 } else {
1847 return false;
1852 * This funtion MUST be called before the cleaning or any other
1853 * function that modifies the data! We do not know the origin of trusttext
1854 * in database, if it gets there in tweaked form we must not convert it
1855 * to supported form!!!
1857 * Please be carefull not to use stripslashes on data from database
1858 * or twice stripslashes when processing data recieved from user.
1860 * @param string $text text that may contain TRUSTTEXT marker
1861 * @return text without any TRUSTTEXT marker
1863 function trusttext_strip($text) {
1864 global $CFG;
1866 while (true) { //removing nested TRUSTTEXT
1867 $orig = $text;
1868 $text = str_replace(TRUSTTEXT, '', $text);
1869 if (strcmp($orig, $text) === 0) {
1870 return $text;
1876 * Mark text as trusted, such text may contain any HTML tags because the
1877 * normal text cleaning will be bypassed.
1878 * Please make sure that the text comes from trusted user before storing
1879 * it into database!
1881 function trusttext_mark($text) {
1882 global $CFG;
1883 if (!empty($CFG->enabletrusttext) and (strpos($text, TRUSTTEXT) === FALSE)) {
1884 return TRUSTTEXT.$text;
1885 } else {
1886 return $text;
1889 function trusttext_after_edit(&$text, $context) {
1890 if (has_capability('moodle/site:trustcontent', $context)) {
1891 $text = trusttext_strip($text);
1892 $text = trusttext_mark($text);
1893 } else {
1894 $text = trusttext_strip($text);
1898 function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
1899 global $CFG;
1901 $options = new object();
1902 $options->smiley = false;
1903 $options->filter = false;
1904 if (!empty($CFG->enabletrusttext)
1905 and has_capability('moodle/site:trustcontent', $context)
1906 and trusttext_present($text)) {
1907 $options->noclean = true;
1908 } else {
1909 $options->noclean = false;
1911 $text = trusttext_strip($text);
1912 if ($usehtmleditor) {
1913 $text = format_text($text, $format, $options);
1914 $format = FORMAT_HTML;
1915 } else if (!$options->noclean){
1916 $text = clean_text($text, $format);
1921 * Given raw text (eg typed in by a user), this function cleans it up
1922 * and removes any nasty tags that could mess up Moodle pages.
1924 * @uses FORMAT_MOODLE
1925 * @uses FORMAT_PLAIN
1926 * @uses ALLOWED_TAGS
1927 * @param string $text The text to be cleaned
1928 * @param int $format Identifier of the text format to be used
1929 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1930 * @return string The cleaned up text
1932 function clean_text($text, $format=FORMAT_MOODLE) {
1934 global $ALLOWED_TAGS, $CFG;
1936 if (empty($text) or is_numeric($text)) {
1937 return (string)$text;
1940 switch ($format) {
1941 case FORMAT_PLAIN:
1942 case FORMAT_MARKDOWN:
1943 return $text;
1945 default:
1947 if (!empty($CFG->enablehtmlpurifier)) {
1948 $text = purify_html($text);
1949 } else {
1950 /// Fix non standard entity notations
1951 $text = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $text);
1952 $text = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $text);
1954 /// Remove tags that are not allowed
1955 $text = strip_tags($text, $ALLOWED_TAGS);
1957 /// Clean up embedded scripts and , using kses
1958 $text = cleanAttributes($text);
1960 /// Again remove tags that are not allowed
1961 $text = strip_tags($text, $ALLOWED_TAGS);
1965 /// Remove potential script events - some extra protection for undiscovered bugs in our code
1966 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
1967 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
1969 return $text;
1974 * KSES replacement cleaning function - uses HTML Purifier.
1976 function purify_html($text) {
1977 global $CFG;
1979 // this can not be done only once because we sometimes need to reset the cache
1980 $cachedir = $CFG->dataroot.'/cache/htmlpurifier/';
1981 $status = check_dir_exists($cachedir, true, true);
1983 static $purifier = false;
1984 if ($purifier === false) {
1985 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.auto.php';
1986 $config = HTMLPurifier_Config::createDefault();
1987 $config->set('Core', 'AcceptFullDocuments', false);
1988 $config->set('Core', 'Encoding', 'UTF-8');
1989 $config->set('HTML', 'Doctype', 'XHTML 1.0 Transitional');
1990 $config->set('Cache', 'SerializerPath', $cachedir);
1991 $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));
1992 $purifier = new HTMLPurifier($config);
1994 return $purifier->purify($text);
1998 * This function takes a string and examines it for HTML tags.
1999 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
2000 * which checks for attributes and filters them for malicious content
2001 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2003 * @param string $str The string to be examined for html tags
2004 * @return string
2006 function cleanAttributes($str){
2007 $result = preg_replace_callback(
2008 '%(<[^>]*(>|$)|>)%m', #search for html tags
2009 "cleanAttributes2",
2010 $str
2012 return $result;
2016 * This function takes a string with an html tag and strips out any unallowed
2017 * protocols e.g. javascript:
2018 * It calls ancillary functions in kses which are prefixed by kses
2019 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2021 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
2022 * element the html to be cleared
2023 * @return string
2025 function cleanAttributes2($htmlArray){
2027 global $CFG, $ALLOWED_PROTOCOLS;
2028 require_once($CFG->libdir .'/kses.php');
2030 $htmlTag = $htmlArray[1];
2031 if (substr($htmlTag, 0, 1) != '<') {
2032 return '&gt;'; //a single character ">" detected
2034 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
2035 return ''; // It's seriously malformed
2037 $slash = trim($matches[1]); //trailing xhtml slash
2038 $elem = $matches[2]; //the element name
2039 $attrlist = $matches[3]; // the list of attributes as a string
2041 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
2043 $attStr = '';
2044 foreach ($attrArray as $arreach) {
2045 $arreach['name'] = strtolower($arreach['name']);
2046 if ($arreach['name'] == 'style') {
2047 $value = $arreach['value'];
2048 while (true) {
2049 $prevvalue = $value;
2050 $value = kses_no_null($value);
2051 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
2052 $value = kses_decode_entities($value);
2053 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
2054 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
2055 if ($value === $prevvalue) {
2056 $arreach['value'] = $value;
2057 break;
2060 $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']);
2061 $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']);
2062 $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
2063 } else if ($arreach['name'] == 'href') {
2064 //Adobe Acrobat Reader XSS protection
2065 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd))[^a-z0-9_\.\-].*$/i', '$1', $arreach['value']);
2067 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
2070 $xhtml_slash = '';
2071 if (preg_match('%/\s*$%', $attrlist)) {
2072 $xhtml_slash = ' /';
2074 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
2078 * Replaces all known smileys in the text with image equivalents
2080 * @uses $CFG
2081 * @param string $text Passed by reference. The string to search for smily strings.
2082 * @return string
2084 function replace_smilies(&$text) {
2086 global $CFG;
2087 $lang = current_language();
2088 $emoticonstring = $CFG->emoticons;
2089 static $e = array();
2090 static $img = array();
2091 static $emoticons = null;
2093 if (is_null($emoticons)) {
2094 $emoticons = array();
2095 if ($emoticonstring) {
2096 $items = explode('{;}', $CFG->emoticons);
2097 foreach ($items as $item) {
2098 $item = explode('{:}', $item);
2099 $emoticons[$item[0]] = $item[1];
2105 if (empty($img[$lang])) { /// After the first time this is not run again
2106 $e[$lang] = array();
2107 $img[$lang] = array();
2108 foreach ($emoticons as $emoticon => $image){
2109 $alttext = get_string($image, 'pix');
2110 $e[$lang][] = $emoticon;
2111 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath .'/s/'. $image .'.gif" />';
2115 // Exclude from transformations all the code inside <script> tags
2116 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
2117 // Based on code from glossary fiter by Williams Castillo.
2118 // - Eloy
2120 // Detect all the <script> zones to take out
2121 $excludes = array();
2122 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
2124 // Take out all the <script> zones from text
2125 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
2126 $excludes['<+'.$key.'+>'] = $value;
2128 if ($excludes) {
2129 $text = str_replace($excludes,array_keys($excludes),$text);
2132 /// this is the meat of the code - this is run every time
2133 $text = str_replace($e[$lang], $img[$lang], $text);
2135 // Recover all the <script> zones to text
2136 if ($excludes) {
2137 $text = str_replace(array_keys($excludes),$excludes,$text);
2142 * Given plain text, makes it into HTML as nicely as possible.
2143 * May contain HTML tags already
2145 * @uses $CFG
2146 * @param string $text The string to convert.
2147 * @param boolean $smiley Convert any smiley characters to smiley images?
2148 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
2149 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2150 * @return string
2153 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
2156 global $CFG;
2158 /// Remove any whitespace that may be between HTML tags
2159 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
2161 /// Remove any returns that precede or follow HTML tags
2162 $text = eregi_replace("([\n\r])<", " <", $text);
2163 $text = eregi_replace(">([\n\r])", "> ", $text);
2165 convert_urls_into_links($text);
2167 /// Make returns into HTML newlines.
2168 if ($newlines) {
2169 $text = nl2br($text);
2172 /// Turn smileys into images.
2173 if ($smiley) {
2174 replace_smilies($text);
2177 /// Wrap the whole thing in a paragraph tag if required
2178 if ($para) {
2179 return '<p>'.$text.'</p>';
2180 } else {
2181 return $text;
2186 * Given Markdown formatted text, make it into XHTML using external function
2188 * @uses $CFG
2189 * @param string $text The markdown formatted text to be converted.
2190 * @return string Converted text
2192 function markdown_to_html($text) {
2193 global $CFG;
2195 require_once($CFG->libdir .'/markdown.php');
2197 return Markdown($text);
2201 * Given HTML text, make it into plain text using external function
2203 * @uses $CFG
2204 * @param string $html The text to be converted.
2205 * @return string
2207 function html_to_text($html) {
2209 global $CFG;
2211 require_once($CFG->libdir .'/html2text.php');
2213 return html2text($html);
2217 * Given some text this function converts any URLs it finds into HTML links
2219 * @param string $text Passed in by reference. The string to be searched for urls.
2221 function convert_urls_into_links(&$text) {
2222 /// Make lone URLs into links. eg http://moodle.com/
2223 $text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
2224 "\\1<a href=\"\\2://\\3\\4\" target=\"_blank\">\\2://\\3\\4</a>", $text);
2226 /// eg www.moodle.com
2227 $text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
2228 "\\1<a href=\"http://www.\\2\\3\" target=\"_blank\">www.\\2\\3</a>", $text);
2232 * This function will highlight search words in a given string
2233 * It cares about HTML and will not ruin links. It's best to use
2234 * this function after performing any conversions to HTML.
2235 * Function found here: http://forums.devshed.com/t67822/scdaa2d1c3d4bacb4671d075ad41f0854.html
2237 * @param string $needle The string to search for
2238 * @param string $haystack The string to search for $needle in
2239 * @param int $case whether to do case-sensitive or insensitive matching.
2240 * @return string
2241 * @todo Finish documenting this function
2243 function highlight($needle, $haystack, $case=0,
2244 $left_string='<span class="highlight">', $right_string='</span>') {
2246 if (empty($needle) or empty($haystack)) {
2247 return $haystack;
2250 //$list_of_words = eregi_replace("[^-a-zA-Z0-9&.']", " ", $needle); // bug 3101
2251 $list_of_words = $needle;
2252 $list_array = explode(' ', $list_of_words);
2253 for ($i=0; $i<sizeof($list_array); $i++) {
2254 if (strlen($list_array[$i]) == 1) {
2255 $list_array[$i] = '';
2258 $list_of_words = implode(' ', $list_array);
2259 $list_of_words_cp = $list_of_words;
2260 $final = array();
2261 preg_match_all('/<(.+?)>/is',$haystack,$list_of_words);
2263 foreach (array_unique($list_of_words[0]) as $key=>$value) {
2264 $final['<|'.$key.'|>'] = $value;
2267 $haystack = str_replace($final,array_keys($final),$haystack);
2268 $list_of_words_cp = eregi_replace(' +', '|', $list_of_words_cp);
2270 if ($list_of_words_cp{0}=='|') {
2271 $list_of_words_cp{0} = '';
2273 if ($list_of_words_cp{strlen($list_of_words_cp)-1}=='|') {
2274 $list_of_words_cp{strlen($list_of_words_cp)-1}='';
2277 $list_of_words_cp = trim($list_of_words_cp);
2279 if ($list_of_words_cp) {
2281 $list_of_words_cp = "(". $list_of_words_cp .")";
2283 if (!$case){
2284 $haystack = eregi_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2285 } else {
2286 $haystack = ereg_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2289 $haystack = str_replace(array_keys($final),$final,$haystack);
2291 return $haystack;
2295 * This function will highlight instances of $needle in $haystack
2296 * It's faster that the above function and doesn't care about
2297 * HTML or anything.
2299 * @param string $needle The string to search for
2300 * @param string $haystack The string to search for $needle in
2301 * @return string
2303 function highlightfast($needle, $haystack) {
2305 if (empty($needle) or empty($haystack)) {
2306 return $haystack;
2309 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
2311 if (count($parts) === 1) {
2312 return $haystack;
2315 $pos = 0;
2317 foreach ($parts as $key => $part) {
2318 $parts[$key] = substr($haystack, $pos, strlen($part));
2319 $pos += strlen($part);
2321 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2322 $pos += strlen($needle);
2325 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2329 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2330 * Internationalisation, for print_header and backup/restorelib.
2331 * @param $dir Default false.
2332 * @return string Attributes.
2334 function get_html_lang($dir = false) {
2335 $direction = '';
2336 if ($dir) {
2337 if (get_string('thisdirection') == 'rtl') {
2338 $direction = ' dir="rtl"';
2339 } else {
2340 $direction = ' dir="ltr"';
2343 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2344 $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
2345 @header('Content-Language: '.$language);
2346 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2350 * Return the markup for the destination of the 'Skip to main content' links.
2351 * Accessibility improvement for keyboard-only users.
2352 * Used in course formats, /index.php and /course/index.php
2353 * @return string HTML element.
2355 function skip_main_destination() {
2356 return '<span id="maincontent"></span>';
2360 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
2363 * Print a standard header
2365 * @uses $USER
2366 * @uses $CFG
2367 * @uses $SESSION
2368 * @param string $title Appears at the top of the window
2369 * @param string $heading Appears at the top of the page
2370 * @param array $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
2371 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2372 * @param string $meta Meta tags to be added to the header
2373 * @param boolean $cache Should this page be cacheable?
2374 * @param string $button HTML code for a button (usually for module editing)
2375 * @param string $menu HTML code for a popup menu
2376 * @param boolean $usexml use XML for this page
2377 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2378 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2380 function print_header ($title='', $heading='', $navigation='', $focus='',
2381 $meta='', $cache=true, $button='&nbsp;', $menu='',
2382 $usexml=false, $bodytags='', $return=false) {
2384 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
2386 if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
2387 debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
2388 . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.", DEBUG_DEVELOPER);
2391 $heading = format_string($heading); // Fix for MDL-8582
2393 /// This makes sure that the header is never repeated twice on a page
2394 if (defined('HEADER_PRINTED')) {
2395 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().');
2396 return;
2398 define('HEADER_PRINTED', 'true');
2401 /// Add the required stylesheets
2402 $stylesheetshtml = '';
2403 foreach ($CFG->stylesheets as $stylesheet) {
2404 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2406 $meta = $stylesheetshtml.$meta;
2409 /// Add the meta page from the themes if any were requested
2411 $metapage = '';
2413 if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
2414 ob_start();
2415 include_once($CFG->dirroot.'/theme/standard/meta.php');
2416 $metapage .= ob_get_contents();
2417 ob_end_clean();
2420 if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
2421 if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
2422 ob_start();
2423 include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
2424 $metapage .= ob_get_contents();
2425 ob_end_clean();
2429 if (!isset($THEME->metainclude) || $THEME->metainclude) {
2430 if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
2431 ob_start();
2432 include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
2433 $metapage .= ob_get_contents();
2434 ob_end_clean();
2438 $meta = $meta."\n".$metapage;
2440 $meta .= "\n".require_js('',1);
2442 /// Set up some navigation variables
2444 if (is_newnav($navigation)){
2445 $home = false;
2446 } else {
2447 if ($navigation == 'home') {
2448 $home = true;
2449 $navigation = '';
2450 } else {
2451 $home = false;
2455 /// This is another ugly hack to make navigation elements available to print_footer later
2456 $THEME->title = $title;
2457 $THEME->heading = $heading;
2458 $THEME->navigation = $navigation;
2459 $THEME->button = $button;
2460 $THEME->menu = $menu;
2461 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2463 if ($button == '') {
2464 $button = '&nbsp;';
2467 if (!$menu and $navigation) {
2468 if (empty($CFG->loginhttps)) {
2469 $wwwroot = $CFG->wwwroot;
2470 } else {
2471 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
2473 $menu = user_login_string($COURSE);
2476 if (isset($SESSION->justloggedin)) {
2477 unset($SESSION->justloggedin);
2478 if (!empty($CFG->displayloginfailures)) {
2479 if (!empty($USER->username) and $USER->username != 'guest') {
2480 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
2481 $menu .= '&nbsp;<font size="1">';
2482 if (empty($count->accounts)) {
2483 $menu .= get_string('failedloginattempts', '', $count);
2484 } else {
2485 $menu .= get_string('failedloginattemptsall', '', $count);
2487 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
2488 $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
2489 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
2491 $menu .= '</font>';
2498 $meta = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' .
2499 "\n" . $meta . "\n";
2500 if (!$usexml) {
2501 @header('Content-Type: text/html; charset=utf-8');
2503 @header('Content-Script-Type: text/javascript');
2504 @header('Content-Style-Type: text/css');
2506 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2507 $direction = get_html_lang($dir=true);
2509 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2510 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2511 @header('Pragma: no-cache');
2512 @header('Expires: ');
2513 } else { // Do everything we can to always prevent clients and proxies caching
2514 @header('Cache-Control: no-store, no-cache, must-revalidate');
2515 @header('Cache-Control: post-check=0, pre-check=0', false);
2516 @header('Pragma: no-cache');
2517 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2518 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2520 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2521 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
2523 @header('Accept-Ranges: none');
2525 $currentlanguage = current_language();
2527 if (empty($usexml)) {
2528 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2529 } else {
2530 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2531 if(!$mathplayer) {
2532 header('Content-Type: application/xhtml+xml');
2534 echo '<?xml version="1.0" ?>'."\n";
2535 if (!empty($CFG->xml_stylesheets)) {
2536 $stylesheets = explode(';', $CFG->xml_stylesheets);
2537 foreach ($stylesheets as $stylesheet) {
2538 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
2541 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
2542 if (!empty($CFG->xml_doctype_extra)) {
2543 echo ' plus '. $CFG->xml_doctype_extra;
2545 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
2546 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2547 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
2548 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2549 $direction";
2550 if($mathplayer) {
2551 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
2552 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2553 $meta .= '</object>'."\n";
2554 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2558 // Clean up the title
2560 $title = format_string($title); // fix for MDL-8582
2561 $title = str_replace('"', '&quot;', $title);
2563 // Create class and id for this page
2565 page_id_and_class($pageid, $pageclass);
2567 $pageclass .= ' course-'.$COURSE->id;
2569 if (!isloggedin()) {
2570 $pageclass .= ' notloggedin';
2573 if (!empty($USER->editing)) {
2574 $pageclass .= ' editing';
2577 if (!empty($CFG->blocksdrag)) {
2578 $pageclass .= ' drag';
2581 $pageclass .= ' dir-'.get_string('thisdirection');
2583 $pageclass .= ' lang-'.$currentlanguage;
2585 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
2587 ob_start();
2588 include($CFG->header);
2589 $output = ob_get_contents();
2590 ob_end_clean();
2592 // container debugging info
2593 $THEME->open_header_containers = open_containers();
2595 // Skip to main content, see skip_main_destination().
2596 if ($pageid=='course-view' or $pageid=='site-index' or $pageid=='course-index') {
2597 $skiplink = '<a class="skip" href="#maincontent">'.get_string('tocontent', 'access').'</a>';
2598 if (! preg_match('/(.*<div[^>]+id="page"[^>]*>)(.*)/s', $output, $matches)) {
2599 preg_match('/(.*<body.*?>)(.*)/s', $output, $matches);
2601 $output = $matches[1]."\n". $skiplink .$matches[2];
2604 $output = force_strict_header($output);
2606 if (!empty($CFG->messaging)) {
2607 $output .= message_popup_window();
2610 // Add in any extra JavaScript libraries that occurred during the header
2611 $output .= require_js('', 2);
2613 if ($return) {
2614 return $output;
2615 } else {
2616 echo $output;
2621 * Used to include JavaScript libraries.
2623 * When the $lib parameter is given, the function will ensure that the
2624 * named library is loaded onto the page - either in the HTML <head>,
2625 * just after the header, or at an arbitrary later point in the page,
2626 * depending on where this function is called.
2628 * Libraries will not be included more than once, so this works like
2629 * require_once in PHP.
2631 * There are two special-case calls to this function which are both used only
2632 * by weblib print_header:
2633 * $extracthtml = 1: this is used before printing the header.
2634 * It returns the script tag code that should go inside the <head>.
2635 * $extracthtml = 2: this is used after printing the header and handles any
2636 * require_js calls that occurred within the header itself.
2638 * @param mixed $lib - string or array of strings
2639 * string(s) should be the shortname for the library or the
2640 * full path to the library file.
2641 * @param int $extracthtml Do not set this parameter usually (leave 0), only
2642 * weblib should set this to 1 or 2 in print_header function.
2643 * @return mixed No return value, except when using $extracthtml it returns the html code.
2645 function require_js($lib,$extracthtml=0) {
2646 global $CFG;
2647 static $loadlibs = array();
2649 static $state = REQUIREJS_BEFOREHEADER;
2650 static $latecode = '';
2652 if (!empty($lib)) {
2653 // Add the lib to the list of libs to be loaded, if it isn't already
2654 // in the list.
2655 if (is_array($lib)) {
2656 foreach($lib as $singlelib) {
2657 require_js($singlelib);
2659 } else {
2660 $libpath = ajax_get_lib($lib);
2661 if (array_search($libpath, $loadlibs) === false) {
2662 $loadlibs[] = $libpath;
2664 // For state other than 0 we need to take action as well as just
2665 // adding it to loadlibs
2666 if($state != REQUIREJS_BEFOREHEADER) {
2667 // Get the script statement for this library
2668 $scriptstatement=get_require_js_code(array($libpath));
2670 if($state == REQUIREJS_AFTERHEADER) {
2671 // After the header, print it immediately
2672 print $scriptstatement;
2673 } else {
2674 // Haven't finished the header yet. Add it after the
2675 // header
2676 $latecode .= $scriptstatement;
2681 } else if($extracthtml==1) {
2682 if($state !== REQUIREJS_BEFOREHEADER) {
2683 debugging('Incorrect state in require_js (expected BEFOREHEADER): be careful not to call with empty $lib (except in print_header)');
2684 } else {
2685 $state = REQUIREJS_INHEADER;
2688 return get_require_js_code($loadlibs);
2689 } else if($extracthtml==2) {
2690 if($state !== REQUIREJS_INHEADER) {
2691 debugging('Incorrect state in require_js (expected INHEADER): be careful not to call with empty $lib (except in print_header)');
2692 return '';
2693 } else {
2694 $state = REQUIREJS_AFTERHEADER;
2695 return $latecode;
2697 } else {
2698 debugging('Unexpected value for $extracthtml');
2703 * Should not be called directly - use require_js. This function obtains the code
2704 * (script tags) needed to include JavaScript libraries.
2705 * @param array $loadlibs Array of library files to include
2706 * @return string HTML code to include them
2708 function get_require_js_code($loadlibs) {
2709 global $CFG;
2710 // Return the html needed to load the JavaScript files defined in
2711 // our list of libs to be loaded.
2712 $output = '';
2713 foreach ($loadlibs as $loadlib) {
2714 $output .= '<script type="text/javascript" ';
2715 $output .= " src=\"$loadlib\"></script>\n";
2716 if ($loadlib == $CFG->wwwroot.'/lib/yui/logger/logger-min.js') {
2717 // Special case, we need the CSS too.
2718 $output .= '<link type="text/css" rel="stylesheet" ';
2719 $output .= " href=\"{$CFG->wwwroot}/lib/yui/logger/assets/logger.css\" />\n";
2722 return $output;
2727 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2728 * and substitute the XHTML strict document type.
2729 * Note, requires the 'xmlns' fix in function print_header above.
2730 * See: http://tracker.moodle.org/browse/MDL-7883
2731 * TODO:
2733 function force_strict_header($output) {
2734 global $CFG;
2735 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2736 $xsl = '/lib/xhtml.xsl';
2738 if (!headers_sent() && !empty($CFG->xmlstrictheaders)) { // With xml strict headers, the browser will barf
2739 $ctype = 'Content-Type: ';
2740 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2742 if (isset($_SERVER['HTTP_ACCEPT'])
2743 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2744 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2745 // Firefox et al.
2746 $ctype .= 'application/xhtml+xml';
2747 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2749 } else if (file_exists($CFG->dirroot.$xsl)
2750 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2751 // XSL hack for IE 5+ on Windows.
2752 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2753 $www_xsl = $CFG->wwwroot .$xsl;
2754 $ctype .= 'application/xml';
2755 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2756 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2758 } else {
2759 //ELSE: Mac/IE, old/non-XML browsers.
2760 $ctype .= 'text/html';
2761 $prolog = '';
2763 @header($ctype.'; charset=utf-8');
2764 $output = $prolog . $output;
2766 // Test parser error-handling.
2767 if (isset($_GET['error'])) {
2768 $output .= "__ TEST: XML well-formed error < __\n";
2772 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
2774 return $output;
2780 * This version of print_header is simpler because the course name does not have to be
2781 * provided explicitly in the strings. It can be used on the site page as in courses
2782 * Eventually all print_header could be replaced by print_header_simple
2784 * @param string $title Appears at the top of the window
2785 * @param string $heading Appears at the top of the page
2786 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2787 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2788 * @param string $meta Meta tags to be added to the header
2789 * @param boolean $cache Should this page be cacheable?
2790 * @param string $button HTML code for a button (usually for module editing)
2791 * @param string $menu HTML code for a popup menu
2792 * @param boolean $usexml use XML for this page
2793 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2794 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2796 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
2797 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
2799 global $COURSE, $CFG;
2801 // if we have no navigation specified, build it
2802 if( empty($navigation) ){
2803 $navigation = build_navigation('');
2806 // If old style nav prepend course short name otherwise leave $navigation object alone
2807 if (!is_newnav($navigation)) {
2808 if ($COURSE->id != SITEID) {
2809 $shortname = '<a href="'.$CFG->wwwroot.'/course/view.php?id='. $COURSE->id .'">'. $COURSE->shortname .'</a> ->';
2810 $navigation = $shortname.' '.$navigation;
2814 $output = print_header($COURSE->shortname .': '. $title, $COURSE->fullname .' '. $heading, $navigation, $focus, $meta,
2815 $cache, $button, $menu, $usexml, $bodytags, true);
2817 if ($return) {
2818 return $output;
2819 } else {
2820 echo $output;
2826 * Can provide a course object to make the footer contain a link to
2827 * to the course home page, otherwise the link will go to the site home
2828 * @uses $USER
2829 * @param mixed $course course object, used for course link button or
2830 * 'none' means no user link, only docs link
2831 * 'empty' means nothing printed in footer
2832 * 'home' special frontpage footer
2833 * @param object $usercourse course used in user link
2834 * @param boolean $return output as string
2835 * @return mixed string or void
2837 function print_footer($course=NULL, $usercourse=NULL, $return=false) {
2838 global $USER, $CFG, $THEME, $COURSE;
2840 if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
2841 admin_externalpage_print_footer();
2842 return;
2845 /// Course links or special footer
2846 if ($course) {
2847 if ($course === 'empty') {
2848 // special hack - sometimes we do not want even the docs link in footer
2849 $output = '';
2850 if (!empty($THEME->open_header_containers)) {
2851 for ($i=0; $i<$THEME->open_header_containers; $i++) {
2852 $output .= print_container_end_all(); // containers opened from header
2854 } else {
2855 //1.8 theme compatibility
2856 $output .= "\n</div>"; // content div
2858 $output .= "\n</div>\n</body>\n</html>"; // close page div started in header
2859 if ($return) {
2860 return $output;
2861 } else {
2862 echo $output;
2863 return;
2866 } else if ($course === 'none') { // Don't print any links etc
2867 $homelink = '';
2868 $loggedinas = '';
2869 $home = false;
2871 } else if ($course === 'home') { // special case for site home page - please do not remove
2872 $course = get_site();
2873 $homelink = '<div class="sitelink">'.
2874 '<a title="Moodle '. $CFG->release .'" href="http://moodle.org/">'.
2875 '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
2876 $home = true;
2878 } else {
2879 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
2880 '/course/view.php?id='.$course->id.'">'.format_string($course->shortname).'</a></div>';
2881 $home = false;
2884 } else {
2885 $course = get_site(); // Set course as site course by default
2886 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
2887 $home = false;
2890 /// Set up some other navigation links (passed from print_header by ugly hack)
2891 $menu = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
2892 $title = isset($THEME->title) ? $THEME->title : '';
2893 $button = isset($THEME->button) ? $THEME->button : '';
2894 $heading = isset($THEME->heading) ? $THEME->heading : '';
2895 $navigation = isset($THEME->navigation) ? $THEME->navigation : '';
2896 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2899 /// Set the user link if necessary
2900 if (!$usercourse and is_object($course)) {
2901 $usercourse = $course;
2904 if (!isset($loggedinas)) {
2905 $loggedinas = user_login_string($usercourse, $USER);
2908 if ($loggedinas == $menu) {
2909 $menu = '';
2912 /// there should be exactly the same number of open containers as after the header
2913 if ($THEME->open_header_containers != open_containers()) {
2914 debugging('Unexpected number of open containers: '.open_containers().', expecting '.$THEME->open_header_containers, DEBUG_DEVELOPER);
2917 /// Provide some performance info if required
2918 $performanceinfo = '';
2919 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2920 $perf = get_performance_info();
2921 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
2922 error_log("PERF: " . $perf['txt']);
2924 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
2925 $performanceinfo = $perf['html'];
2929 /// Include the actual footer file
2931 ob_start();
2932 include($CFG->footer);
2933 $output = ob_get_contents();
2934 ob_end_clean();
2936 if ($return) {
2937 return $output;
2938 } else {
2939 echo $output;
2944 * Returns the name of the current theme
2946 * @uses $CFG
2947 * @uses $USER
2948 * @uses $SESSION
2949 * @uses $COURSE
2950 * @uses $FULLME
2951 * @return string
2953 function current_theme() {
2954 global $CFG, $USER, $SESSION, $COURSE, $FULLME;
2956 if (empty($CFG->themeorder)) {
2957 $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
2958 } else {
2959 $themeorder = $CFG->themeorder;
2962 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id) {
2963 require_once($CFG->dirroot.'/mnet/peer.php');
2964 $mnet_peer = new mnet_peer();
2965 $mnet_peer->set_id($USER->mnethostid);
2968 $theme = '';
2969 foreach ($themeorder as $themetype) {
2971 if (!empty($theme)) continue;
2973 switch ($themetype) {
2974 case 'page': // Page theme is for special page-only themes set by code
2975 if (!empty($CFG->pagetheme)) {
2976 $theme = $CFG->pagetheme;
2978 break;
2979 case 'course':
2980 if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) {
2981 $theme = $COURSE->theme;
2983 break;
2984 case 'category':
2985 if (!empty($CFG->allowcategorythemes)) {
2986 /// Nasty hack to check if we're in a category page
2987 if (stripos($FULLME, 'course/category.php') !== false) {
2988 global $id;
2989 if (!empty($id)) {
2990 $theme = current_category_theme($id);
2992 /// Otherwise check if we're in a course that has a category theme set
2993 } else if (!empty($COURSE->category)) {
2994 $theme = current_category_theme($COURSE->category);
2997 break;
2998 case 'session':
2999 if (!empty($SESSION->theme)) {
3000 $theme = $SESSION->theme;
3002 break;
3003 case 'user':
3004 if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) {
3005 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
3006 $theme = $mnet_peer->theme;
3007 } else {
3008 $theme = $USER->theme;
3011 break;
3012 case 'site':
3013 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
3014 $theme = $mnet_peer->theme;
3015 } else {
3016 $theme = $CFG->theme;
3018 break;
3019 default:
3020 /// do nothing
3024 /// A final check in case 'site' was not included in $CFG->themeorder
3025 if (empty($theme)) {
3026 $theme = $CFG->theme;
3029 return $theme;
3033 * Retrieves the category theme if one exists, otherwise checks the parent categories.
3034 * Recursive function.
3036 * @uses $COURSE
3037 * @param integer $categoryid id of the category to check
3038 * @return string theme name
3040 function current_category_theme($categoryid=0) {
3041 global $COURSE;
3043 /// Use the COURSE global if the categoryid not set
3044 if (empty($categoryid)) {
3045 if (!empty($COURSE->category)) {
3046 $categoryid = $COURSE->category;
3047 } else {
3048 return false;
3052 /// Retrieve the current category
3053 if ($category = get_record('course_categories', 'id', $categoryid)) {
3055 /// Return the category theme if it exists
3056 if (!empty($category->theme)) {
3057 return $category->theme;
3059 /// Otherwise try the parent category if one exists
3060 } else if (!empty($category->parent)) {
3061 return current_category_theme($category->parent);
3064 /// Return false if we can't find the category record
3065 } else {
3066 return false;
3071 * This function is called by stylesheets to set up the header
3072 * approriately as well as the current path
3074 * @uses $CFG
3075 * @param int $lastmodified ?
3076 * @param int $lifetime ?
3077 * @param string $thename ?
3079 function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
3081 global $CFG, $THEME;
3083 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
3084 $lastmodified = time();
3086 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
3087 header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
3088 header('Cache-Control: max-age='. $lifetime);
3089 header('Pragma: ');
3090 header('Content-type: text/css'); // Correct MIME type
3092 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
3094 if (empty($themename)) {
3095 $themename = current_theme(); // So we have something. Normally not needed.
3096 } else {
3097 $themename = clean_param($themename, PARAM_SAFEDIR);
3100 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
3101 unset($THEME);
3102 include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
3105 /// If this is the standard theme calling us, then find out what sheets we need
3107 if ($themename == 'standard') {
3108 if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
3109 $THEME->sheets = $DEFAULT_SHEET_LIST;
3110 } else if (empty($THEME->standardsheets)) { // We can stop right now!
3111 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3112 exit;
3113 } else { // Use the provided subset only
3114 $THEME->sheets = $THEME->standardsheets;
3117 /// If we are a parent theme, then check for parent definitions
3119 } else if (!empty($THEME->parent) && $themename == $THEME->parent) {
3120 if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have
3121 $THEME->sheets = $DEFAULT_SHEET_LIST;
3122 } else if (empty($THEME->parentsheets)) { // We can stop right now!
3123 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3124 exit;
3125 } else { // Use the provided subset only
3126 $THEME->sheets = $THEME->parentsheets;
3130 /// Work out the last modified date for this theme
3132 foreach ($THEME->sheets as $sheet) {
3133 if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
3134 $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
3135 if ($sheetmodified > $lastmodified) {
3136 $lastmodified = $sheetmodified;
3142 /// Get a list of all the files we want to include
3143 $files = array();
3145 foreach ($THEME->sheets as $sheet) {
3146 $files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
3149 if ($themename == 'standard') { // Add any standard styles included in any modules
3150 if (!empty($THEME->modsheets)) { // Search for styles.php within activity modules
3151 if ($mods = get_list_of_plugins('mod')) {
3152 foreach ($mods as $mod) {
3153 if (file_exists($CFG->dirroot.'/mod/'.$mod.'/styles.php')) {
3154 $files[] = array($CFG->dirroot, '/mod/'.$mod.'/styles.php');
3160 if (!empty($THEME->blocksheets)) { // Search for styles.php within block modules
3161 if ($mods = get_list_of_plugins('blocks')) {
3162 foreach ($mods as $mod) {
3163 if (file_exists($CFG->dirroot.'/blocks/'.$mod.'/styles.php')) {
3164 $files[] = array($CFG->dirroot, '/blocks/'.$mod.'/styles.php');
3170 if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
3171 if ($mods = get_list_of_plugins('format','',$CFG->dirroot.'/course')) {
3172 foreach ($mods as $mod) {
3173 if (file_exists($CFG->dirroot.'/course/format/'.$mod.'/styles.php')) {
3174 $files[] = array($CFG->dirroot, '/course/format/'.$mod.'/styles.php');
3180 if (!isset($THEME->gradereportsheets) || $THEME->gradereportsheets) { // Search for styles.php in grade reports
3181 if ($reports = get_list_of_plugins('grade/report')) {
3182 foreach ($reports as $report) {
3183 if (file_exists($CFG->dirroot.'/grade/report/'.$report.'/styles.php')) {
3184 $files[] = array($CFG->dirroot, '/grade/report/'.$report.'/styles.php');
3190 if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
3191 if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
3192 $files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
3197 if ($files) {
3198 /// Produce a list of all the files first
3199 echo '/**************************************'."\n";
3200 echo ' * THEME NAME: '.$themename."\n *\n";
3201 echo ' * Files included in this sheet:'."\n *\n";
3202 foreach ($files as $file) {
3203 echo ' * '.$file[1]."\n";
3205 echo ' **************************************/'."\n\n";
3208 /// check if csscobstants is set
3209 if (!empty($THEME->cssconstants)) {
3210 require_once("$CFG->libdir/cssconstants.php");
3211 /// Actually collect all the files in order.
3212 $css = '';
3213 foreach ($files as $file) {
3214 $css .= '/***** '.$file[1].' start *****/'."\n\n";
3215 $css .= file_get_contents($file[0].'/'.$file[1]);
3216 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
3218 /// replace css_constants with their values
3219 echo replace_cssconstants($css);
3220 } else {
3221 /// Actually output all the files in order.
3222 if (empty($CFG->CSSEdit) && empty($THEME->CSSEdit)) {
3223 foreach ($files as $file) {
3224 echo '/***** '.$file[1].' start *****/'."\n\n";
3225 @include_once($file[0].'/'.$file[1]);
3226 echo '/***** '.$file[1].' end *****/'."\n\n";
3228 } else {
3229 foreach ($files as $file) {
3230 echo '/* @group '.$file[1].' */'."\n\n";
3231 if (strstr($file[1], '.css') !== FALSE) {
3232 echo '@import url("'.$CFG->themewww.'/'.$file[1].'");'."\n\n";
3233 } else {
3234 @include_once($file[0].'/'.$file[1]);
3236 echo '/* @end */'."\n\n";
3242 return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
3246 function theme_setup($theme = '', $params=NULL) {
3247 /// Sets up global variables related to themes
3249 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
3251 /// Do not mess with THEME if header already printed - this would break all the extra stuff in global $THEME from print_header()!!
3252 if (defined('HEADER_PRINTED')) {
3253 return;
3256 if (empty($theme)) {
3257 $theme = current_theme();
3260 /// If the theme doesn't exist for some reason then revert to standardwhite
3261 if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
3262 $CFG->theme = $theme = 'standardwhite';
3265 /// Load up the theme config
3266 $THEME = NULL; // Just to be sure
3267 include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
3269 /// Put together the parameters
3270 if (!$params) {
3271 $params = array();
3274 if ($theme != $CFG->theme) {
3275 $params[] = 'forceconfig='.$theme;
3278 /// Force language too if required
3279 if (!empty($THEME->langsheets)) {
3280 $params[] = 'lang='.current_language();
3284 /// Convert params to string
3285 if ($params) {
3286 $paramstring = '?'.implode('&', $params);
3287 } else {
3288 $paramstring = '';
3291 /// Set up image paths
3292 if(isset($CFG->smartpix) && $CFG->smartpix==1) {
3293 if($CFG->slasharguments) { // Use this method if possible for better caching
3294 $extra='';
3295 } else {
3296 $extra='?file=';
3299 $CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
3300 $CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
3301 } else if (empty($THEME->custompix)) { // Could be set in the above file
3302 $CFG->pixpath = $CFG->wwwroot .'/pix';
3303 $CFG->modpixpath = $CFG->wwwroot .'/mod';
3304 } else {
3305 $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
3306 $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
3309 /// Header and footer paths
3310 $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
3311 $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
3313 /// Define stylesheet loading order
3314 $CFG->stylesheets = array();
3315 if ($theme != 'standard') { /// The standard sheet is always loaded first
3316 $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
3318 if (!empty($THEME->parent)) { /// Parent stylesheets are loaded next
3319 $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
3321 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
3323 /// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
3324 if (!empty($HTTPSPAGEREQUIRED)) {
3325 $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
3326 $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
3327 $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
3328 foreach ($CFG->stylesheets as $key => $stylesheet) {
3329 $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
3333 // RTL support - only for RTL languages, add RTL CSS
3334 if (get_string('thisdirection') == 'rtl') {
3335 $CFG->stylesheets[] = $CFG->themewww.'/standard/rtl.css'.$paramstring;
3336 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/rtl.css'.$paramstring;
3342 * Returns text to be displayed to the user which reflects their login status
3344 * @uses $CFG
3345 * @uses $USER
3346 * @param course $course {@link $COURSE} object containing course information
3347 * @param user $user {@link $USER} object containing user information
3348 * @return string
3350 function user_login_string($course=NULL, $user=NULL) {
3351 global $USER, $CFG, $SITE;
3353 if (empty($user) and !empty($USER->id)) {
3354 $user = $USER;
3357 if (empty($course)) {
3358 $course = $SITE;
3361 if (!empty($user->realuser)) {
3362 if ($realuser = get_record('user', 'id', $user->realuser)) {
3363 $fullname = fullname($realuser, true);
3364 $realuserinfo = " [<a $CFG->frametarget
3365 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=1&amp;sesskey=".sesskey()."\">$fullname</a>] ";
3367 } else {
3368 $realuserinfo = '';
3371 if (empty($CFG->loginhttps)) {
3372 $wwwroot = $CFG->wwwroot;
3373 } else {
3374 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
3377 if (empty($course->id)) {
3378 // $course->id is not defined during installation
3379 return '';
3380 } else if (!empty($user->id)) {
3381 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3383 $fullname = fullname($user, true);
3384 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a>";
3385 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid)) {
3386 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
3388 if (isset($user->username) && $user->username == 'guest') {
3389 $loggedinas = $realuserinfo.get_string('loggedinasguest').
3390 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3391 } else if (!empty($user->access['rsw'][$context->path])) {
3392 $rolename = '';
3393 if ($role = get_record('role', 'id', $user->access['rsw'][$context->path])) {
3394 $rolename = ': '.format_string($role->name);
3396 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
3397 " (<a $CFG->frametarget
3398 href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
3399 } else {
3400 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
3401 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
3403 } else {
3404 $loggedinas = get_string('loggedinnot', 'moodle').
3405 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3407 return '<div class="logininfo">'.$loggedinas.'</div>';
3411 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
3412 * If not it applies sensible defaults.
3414 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
3415 * search forum block, etc. Important: these are 'silent' in a screen-reader
3416 * (unlike &gt; &raquo;), and must be accompanied by text.
3417 * @uses $THEME
3419 function check_theme_arrows() {
3420 global $THEME;
3422 if (!isset($THEME->rarrow) and !isset($THEME->larrow)) {
3423 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
3424 // Also OK in Win 9x/2K/IE 5.x
3425 $THEME->rarrow = '&#x25BA;';
3426 $THEME->larrow = '&#x25C4;';
3427 $uagent = $_SERVER['HTTP_USER_AGENT'];
3428 if (false !== strpos($uagent, 'Opera')
3429 || false !== strpos($uagent, 'Mac')) {
3430 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
3431 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
3432 $THEME->rarrow = '&#x25B6;';
3433 $THEME->larrow = '&#x25C0;';
3435 elseif (false !== strpos($uagent, 'Konqueror')) {
3436 $THEME->rarrow = '&rarr;';
3437 $THEME->larrow = '&larr;';
3439 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
3440 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
3441 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
3442 // To be safe, non-Unicode browsers!
3443 $THEME->rarrow = '&gt;';
3444 $THEME->larrow = '&lt;';
3447 /// RTL support - in RTL languages, swap r and l arrows
3448 if (right_to_left()) {
3449 $t = $THEME->rarrow;
3450 $THEME->rarrow = $THEME->larrow;
3451 $THEME->larrow = $t;
3458 * Return the right arrow with text ('next'), and optionally embedded in a link.
3459 * See function above, check_theme_arrows.
3460 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3461 * @param string $url An optional link to use in a surrounding HTML anchor.
3462 * @param bool $accesshide True if text should be hidden (for screen readers only).
3463 * @param string $addclass Additional class names for the link, or the arrow character.
3464 * @return string HTML string.
3466 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
3467 global $THEME;
3468 check_theme_arrows();
3469 $arrowclass = 'arrow ';
3470 if (! $url) {
3471 $arrowclass .= $addclass;
3473 $arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow.'</span>';
3474 $htmltext = '';
3475 if ($text) {
3476 $htmltext = $text.'&nbsp;';
3477 if ($accesshide) {
3478 $htmltext = get_accesshide($htmltext);
3481 if ($url) {
3482 $class = '';
3483 if ($addclass) {
3484 $class =" class=\"$addclass\"";
3486 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
3488 return $htmltext.$arrow;
3492 * Return the left arrow with text ('previous'), and optionally embedded in a link.
3493 * See function above, check_theme_arrows.
3494 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3495 * @param string $url An optional link to use in a surrounding HTML anchor.
3496 * @param bool $accesshide True if text should be hidden (for screen readers only).
3497 * @param string $addclass Additional class names for the link, or the arrow character.
3498 * @return string HTML string.
3500 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
3501 global $THEME;
3502 check_theme_arrows();
3503 $arrowclass = 'arrow ';
3504 if (! $url) {
3505 $arrowclass .= $addclass;
3507 $arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow.'</span>';
3508 $htmltext = '';
3509 if ($text) {
3510 $htmltext = '&nbsp;'.$text;
3511 if ($accesshide) {
3512 $htmltext = get_accesshide($htmltext);
3515 if ($url) {
3516 $class = '';
3517 if ($addclass) {
3518 $class =" class=\"$addclass\"";
3520 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
3522 return $arrow.$htmltext;
3526 * Return a HTML element with the class "accesshide", for accessibility.
3527 * Please use cautiously - where possible, text should be visible!
3528 * @param string $text Plain text.
3529 * @param string $elem Lowercase element name, default "span".
3530 * @param string $class Additional classes for the element.
3531 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
3532 * @return string HTML string.
3534 function get_accesshide($text, $elem='span', $class='', $attrs='') {
3535 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
3539 * Return the breadcrumb trail navigation separator.
3540 * @return string HTML string.
3542 function get_separator() {
3543 //Accessibility: the 'hidden' slash is preferred for screen readers.
3544 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
3548 * Prints breadcrumb trail of links, called in theme/-/header.html
3550 * @uses $CFG
3551 * @param mixed $navigation The breadcrumb navigation string to be printed
3552 * @param string $separator The breadcrumb trail separator. The default 0 leads to the use
3553 * of $THEME->rarrow, themes could use '&rarr;', '/', or '' for a style-sheet solution.
3554 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
3556 function print_navigation ($navigation, $separator=0, $return=false) {
3557 global $CFG, $THEME;
3558 $output = '';
3560 if (0 === $separator) {
3561 $separator = get_separator();
3563 else {
3564 $separator = '<span class="sep">'. $separator .'</span>';
3567 if ($navigation) {
3569 if (is_newnav($navigation)) {
3570 if ($return) {
3571 return($navigation['navlinks']);
3572 } else {
3573 echo $navigation['navlinks'];
3574 return;
3576 } else {
3577 debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER);
3580 if (!is_array($navigation)) {
3581 $ar = explode('->', $navigation);
3582 $navigation = array();
3584 foreach ($ar as $a) {
3585 if (strpos($a, '</a>') === false) {
3586 $navigation[] = array('title' => $a, 'url' => '');
3587 } else {
3588 if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
3589 $navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
3595 if (! $site = get_site()) {
3596 $site = new object();
3597 $site->shortname = get_string('home');
3600 //Accessibility: breadcrumb links now in a list, &raquo; replaced with a 'silent' character.
3601 $output .= get_accesshide(get_string('youarehere','access'), 'h2')."<ul>\n";
3603 $output .= '<li class="first">'."\n".'<a '.$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3604 .$CFG->wwwroot.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))
3605 && !empty($USER->id) && !empty($CFG->mymoodleredirect) && !isguest())
3606 ? '/my' : '') .'/">'. format_string($site->shortname) ."</a>\n</li>\n";
3609 foreach ($navigation as $navitem) {
3610 $title = trim(strip_tags(format_string($navitem['title'], false)));
3611 $url = $navitem['url'];
3613 if (empty($url)) {
3614 $output .= '<li class="first">'."$separator $title</li>\n";
3615 } else {
3616 $output .= '<li class="first">'."$separator\n<a ".$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3617 .$url.'">'."$title</a>\n</li>\n";
3621 $output .= "</ul>\n";
3624 if ($return) {
3625 return $output;
3626 } else {
3627 echo $output;
3632 * This function will build the navigation string to be used by print_header
3633 * and others.
3635 * It automatically generates the site and course level (if appropriate) links.
3637 * If you pass in a $cm object, the method will also generate the activity (e.g. 'Forums')
3638 * and activityinstances (e.g. 'General Developer Forum') navigation levels.
3640 * If you want to add any further navigation links after the ones this function generates,
3641 * the pass an array of extra link arrays like this:
3642 * array(
3643 * array('name' => $linktext1, 'link' => $url1, 'type' => $linktype1),
3644 * array('name' => $linktext2, 'link' => $url2, 'type' => $linktype2)
3646 * The normal case is to just add one further link, for example 'Editing forum' after
3647 * 'General Developer Forum', with no link.
3648 * To do that, you need to pass
3649 * array(array('name' => $linktext, 'link' => '', 'type' => 'title'))
3650 * However, becuase this is a very common case, you can use a shortcut syntax, and just
3651 * pass the string 'Editing forum', instead of an array as $extranavlinks.
3653 * At the moment, the link types only have limited significance. Type 'activity' is
3654 * recognised in order to implement the $CFG->hideactivitytypenavlink feature. Types
3655 * that are known to appear are 'home', 'course', 'activity', 'activityinstance' and 'title'.
3656 * This really needs to be documented better. In the mean time, try to be consistent, it will
3657 * enable people to customise the navigation more in future.
3659 * When passing a $cm object, the fields used are $cm->modname, $cm->name and $cm->course.
3660 * If you get the $cm object using the function get_coursemodule_from_instance or
3661 * get_coursemodule_from_id (as recommended) then this will be done for you automatically.
3662 * If you don't have $cm->modname or $cm->name, this fuction will attempt to find them using
3663 * the $cm->module and $cm->instance fields, but this takes extra database queries, so a
3664 * warning is printed in developer debug mode.
3666 * @uses $CFG
3667 * @uses $THEME
3669 * @param mixed $extranavlinks - Normally an array of arrays, keys: name, link, type. If you
3670 * only want one extra item with no link, you can pass a string instead. If you don't want
3671 * any extra links, pass an empty string.
3672 * @param mixed $cm - optionally the $cm object, if you want this function to generate the
3673 * activity and activityinstance levels of navigation too.
3675 * @return $navigation as an object so it can be differentiated from old style
3676 * navigation strings.
3678 function build_navigation($extranavlinks, $cm = null) {
3679 global $CFG, $COURSE;
3681 if (is_string($extranavlinks)) {
3682 if ($extranavlinks == '') {
3683 $extranavlinks = array();
3684 } else {
3685 $extranavlinks = array(array('name' => $extranavlinks, 'link' => '', 'type' => 'title'));
3689 $navlinks = array();
3691 //Site name
3692 if ($site = get_site()) {
3693 $navlinks[] = array(
3694 'name' => format_string($site->shortname),
3695 'link' => "$CFG->wwwroot/",
3696 'type' => 'home');
3699 // Course name, if appropriate.
3700 if (isset($COURSE) && $COURSE->id != SITEID) {
3701 $navlinks[] = array(
3702 'name' => format_string($COURSE->shortname),
3703 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",
3704 'type' => 'course');
3707 // Activity type and instance, if appropriate.
3708 if (is_object($cm)) {
3709 if (!isset($cm->modname)) {
3710 debugging('The field $cm->modname should be set if you call build_navigation with '.
3711 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3712 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
3713 if (!$cm->modname = get_field('modules', 'name', 'id', $cm->module)) {
3714 error('Cannot get the module type in build navigation.');
3717 if (!isset($cm->name)) {
3718 debugging('The field $cm->name should be set if you call build_navigation with '.
3719 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3720 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
3721 if (!$cm->name = get_field($cm->modname, 'name', 'id', $cm->instance)) {
3722 error('Cannot get the module name in build navigation.');
3725 $navlinks[] = array(
3726 'name' => get_string('modulenameplural', $cm->modname),
3727 'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/index.php?id=' . $cm->course,
3728 'type' => 'activity');
3729 $navlinks[] = array(
3730 'name' => format_string($cm->name),
3731 'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/view.php?id=' . $cm->id,
3732 'type' => 'activityinstance');
3735 //Merge in extra navigation links
3736 $navlinks = array_merge($navlinks, $extranavlinks);
3738 // Work out whether we should be showing the activity (e.g. Forums) link.
3739 // Note: build_navigation() is called from many places --
3740 // install & upgrade for example -- where we cannot count on the
3741 // roles infrastructure to be defined. Hence the $CFG->rolesactive check.
3742 if (!isset($CFG->hideactivitytypenavlink)) {
3743 $CFG->hideactivitytypenavlink = 0;
3745 if ($CFG->hideactivitytypenavlink == 2) {
3746 $hideactivitylink = true;
3747 } else if ($CFG->hideactivitytypenavlink == 1 && $CFG->rolesactive &&
3748 !empty($COURSE->id) && $COURSE->id != SITEID) {
3749 if (!isset($COURSE->context)) {
3750 $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
3752 $hideactivitylink = !has_capability('moodle/course:manageactivities', $COURSE->context);
3753 } else {
3754 $hideactivitylink = false;
3757 //Construct an unordered list from $navlinks
3758 //Accessibility: heading hidden from visual browsers by default.
3759 $navigation = get_accesshide(get_string('youarehere','access'), 'h2')." <ul>\n";
3760 $lastindex = count($navlinks) - 1;
3761 $i = -1; // Used to count the times, so we know when we get to the last item.
3762 $first = true;
3763 foreach ($navlinks as $navlink) {
3764 $i++;
3765 $last = ($i == $lastindex);
3766 if (!is_array($navlink)) {
3767 continue;
3769 if ($navlink['type'] == 'activity' && !$last && $hideactivitylink) {
3770 continue;
3772 $navigation .= '<li class="first">';
3773 if (!$first) {
3774 $navigation .= get_separator();
3776 if ((!empty($navlink['link'])) && !$last) {
3777 $navigation .= "<a onclick=\"this.target='$CFG->framename'\" href=\"{$navlink['link']}\">";
3779 $navigation .= "{$navlink['name']}";
3780 if ((!empty($navlink['link'])) && !$last) {
3781 $navigation .= "</a>";
3784 $navigation .= "</li>";
3785 $first = false;
3787 $navigation .= "</ul>";
3789 return(array('newnav' => true, 'navlinks' => $navigation));
3794 * Prints a string in a specified size (retained for backward compatibility)
3796 * @param string $text The text to be displayed
3797 * @param int $size The size to set the font for text display.
3799 function print_headline($text, $size=2, $return=false) {
3800 $output = print_heading($text, '', $size, true);
3801 if ($return) {
3802 return $output;
3803 } else {
3804 echo $output;
3809 * Prints text in a format for use in headings.
3811 * @param string $text The text to be displayed
3812 * @param string $align The alignment of the printed paragraph of text
3813 * @param int $size The size to set the font for text display.
3815 function print_heading($text, $align='', $size=2, $class='main', $return=false) {
3816 if ($align) {
3817 $align = ' style="text-align:'.$align.';"';
3819 if ($class) {
3820 $class = ' class="'.$class.'"';
3822 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
3824 if ($return) {
3825 return $output;
3826 } else {
3827 echo $output;
3832 * Centered heading with attached help button (same title text)
3833 * and optional icon attached
3835 * @param string $text The text to be displayed
3836 * @param string $helppage The help page to link to
3837 * @param string $module The module whose help should be linked to
3838 * @param string $icon Image to display if needed
3840 function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
3841 $output = '';
3842 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
3843 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
3844 $output .= '</h2>';
3846 if ($return) {
3847 return $output;
3848 } else {
3849 echo $output;
3854 function print_heading_block($heading, $class='', $return=false) {
3855 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
3856 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
3858 if ($return) {
3859 return $output;
3860 } else {
3861 echo $output;
3867 * Print a link to continue on to another page.
3869 * @uses $CFG
3870 * @param string $link The url to create a link to.
3872 function print_continue($link, $return=false) {
3874 global $CFG;
3876 // in case we are logging upgrade in admin/index.php stop it
3877 if (function_exists('upgrade_log_finish')) {
3878 upgrade_log_finish();
3881 $output = '';
3883 if ($link == '') {
3884 if (!empty($_SERVER['HTTP_REFERER'])) {
3885 $link = $_SERVER['HTTP_REFERER'];
3886 $link = str_replace('&', '&amp;', $link); // make it valid XHTML
3887 } else {
3888 $link = $CFG->wwwroot .'/';
3892 $options = array();
3893 $linkparts = parse_url(str_replace('&amp;', '&', $link));
3894 if (isset($linkparts['query'])) {
3895 parse_str($linkparts['query'], $options);
3898 $output .= '<div class="continuebutton">';
3900 $output .= print_single_button($link, $options, get_string('continue'), 'get', $CFG->framename, true);
3901 $output .= '</div>'."\n";
3903 if ($return) {
3904 return $output;
3905 } else {
3906 echo $output;
3912 * Print a message in a standard themed box.
3913 * Replaces print_simple_box (see deprecatedlib.php)
3915 * @param string $message, the content of the box
3916 * @param string $classes, space-separated class names.
3917 * @param string $idbase
3918 * @param boolean $return, return as string or just print it
3919 * @return mixed string or void
3921 function print_box($message, $classes='generalbox', $ids='', $return=false) {
3923 $output = print_box_start($classes, $ids, true);
3924 $output .= stripslashes_safe($message);
3925 $output .= print_box_end(true);
3927 if ($return) {
3928 return $output;
3929 } else {
3930 echo $output;
3935 * Starts a box using divs
3936 * Replaces print_simple_box_start (see deprecatedlib.php)
3938 * @param string $classes, space-separated class names.
3939 * @param string $idbase
3940 * @param boolean $return, return as string or just print it
3941 * @return mixed string or void
3943 function print_box_start($classes='generalbox', $ids='', $return=false) {
3944 global $THEME;
3946 if (strpos($classes, 'clearfix') !== false) {
3947 $clearfix = true;
3948 $classes = trim(str_replace('clearfix', '', $classes));
3949 } else {
3950 $clearfix = false;
3953 if (!empty($THEME->customcorners)) {
3954 $classes .= ' ccbox box';
3955 } else {
3956 $classes .= ' box';
3959 return print_container_start($clearfix, $classes, $ids, $return);
3963 * Simple function to end a box (see above)
3964 * Replaces print_simple_box_end (see deprecatedlib.php)
3966 * @param boolean $return, return as string or just print it
3968 function print_box_end($return=false) {
3969 return print_container_end($return);
3973 * Print a message in a standard themed container.
3975 * @param string $message, the content of the container
3976 * @param boolean $clearfix clear both sides
3977 * @param string $classes, space-separated class names.
3978 * @param string $idbase
3979 * @param boolean $return, return as string or just print it
3980 * @return string or void
3982 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
3984 $output = print_container_start($clearfix, $classes, $idbase, true);
3985 $output .= stripslashes_safe($message);
3986 $output .= print_container_end(true);
3988 if ($return) {
3989 return $output;
3990 } else {
3991 echo $output;
3996 * Starts a container using divs
3998 * @param boolean $clearfix clear both sides
3999 * @param string $classes, space-separated class names.
4000 * @param string $idbase
4001 * @param boolean $return, return as string or just print it
4002 * @return mixed string or void
4004 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
4005 global $THEME;
4007 if (!isset($THEME->open_containers)) {
4008 $THEME->open_containers = array();
4010 $THEME->open_containers[] = $idbase;
4013 if (!empty($THEME->customcorners)) {
4014 $output = _print_custom_corners_start($clearfix, $classes, $idbase);
4015 } else {
4016 if ($idbase) {
4017 $id = ' id="'.$idbase.'"';
4018 } else {
4019 $id = '';
4021 if ($clearfix) {
4022 $clearfix = ' clearfix';
4023 } else {
4024 $clearfix = '';
4026 if ($classes or $clearfix) {
4027 $class = ' class="'.$classes.$clearfix.'"';
4028 } else {
4029 $class = '';
4031 $output = '<div'.$id.$class.'>';
4034 if ($return) {
4035 return $output;
4036 } else {
4037 echo $output;
4042 * Simple function to end a container (see above)
4043 * @param boolean $return, return as string or just print it
4044 * @return mixed string or void
4046 function print_container_end($return=false) {
4047 global $THEME;
4049 if (empty($THEME->open_containers)) {
4050 debugging('Incorrect request to end container - no more open containers.', DEBUG_DEVELOPER);
4051 $idbase = '';
4052 } else {
4053 $idbase = array_pop($THEME->open_containers);
4056 if (!empty($THEME->customcorners)) {
4057 $output = _print_custom_corners_end($idbase);
4058 } else {
4059 $output = '</div>';
4062 if ($return) {
4063 return $output;
4064 } else {
4065 echo $output;
4070 * Returns number of currently open containers
4071 * @return int number of open containers
4073 function open_containers() {
4074 global $THEME;
4076 if (!isset($THEME->open_containers)) {
4077 $THEME->open_containers = array();
4080 return count($THEME->open_containers);
4084 * Force closing of open containers
4085 * @param boolean $return, return as string or just print it
4086 * @param int $keep number of containers to be kept open - usually theme or page containers
4087 * @return mixed string or void
4089 function print_container_end_all($return=false, $keep=0) {
4090 $output = '';
4091 while (open_containers() > $keep) {
4092 $output .= print_container_end($return);
4095 if ($return) {
4096 return $output;
4097 } else {
4098 echo $output;
4103 * Internal function - do not use directly!
4104 * Starting part of the surrounding divs for custom corners
4106 * @param boolean $clearfix, add CLASS "clearfix" to the inner div against collapsing
4107 * @param string $classes
4108 * @param mixed $idbase, optionally, define one idbase to be added to all the elements in the corners
4109 * @return string
4111 function _print_custom_corners_start($clearfix=false, $classes='', $idbase='') {
4112 /// Analise if we want ids for the custom corner elements
4113 $id = '';
4114 $idbt = '';
4115 $idi1 = '';
4116 $idi2 = '';
4117 $idi3 = '';
4119 if ($idbase) {
4120 $id = 'id="'.$idbase.'" ';
4121 $idbt = 'id="'.$idbase.'-bt" ';
4122 $idi1 = 'id="'.$idbase.'-i1" ';
4123 $idi2 = 'id="'.$idbase.'-i2" ';
4124 $idi3 = 'id="'.$idbase.'-i3" ';
4127 /// Calculate current level
4128 $level = open_containers();
4130 /// Output begins
4131 $output = '<div '.$id.'class="wrap wraplevel'.$level.' '.$classes.'">'."\n";
4132 $output .= '<div '.$idbt.'class="bt"><div>&nbsp;</div></div>';
4133 $output .= "\n";
4134 $output .= '<div '.$idi1.'class="i1"><div '.$idi2.'class="i2">';
4135 $output .= (!empty($clearfix)) ? '<div '.$idi3.'class="i3 clearfix">' : '<div '.$idi3.'class="i3">';
4137 return $output;
4142 * Internal function - do not use directly!
4143 * Ending part of the surrounding divs for custom corners
4144 * @param string $idbase
4145 * @return string
4147 function _print_custom_corners_end($idbase) {
4148 /// Analise if we want ids for the custom corner elements
4149 $idbb = '';
4151 if ($idbase) {
4152 $idbb = 'id="' . $idbase . '-bb" ';
4155 /// Output begins
4156 $output = '</div></div></div>';
4157 $output .= "\n";
4158 $output .= '<div '.$idbb.'class="bb"><div>&nbsp;</div></div>'."\n";
4159 $output .= '</div>';
4161 return $output;
4166 * Print a self contained form with a single submit button.
4168 * @param string $link used as the action attribute on the form, so the URL that will be hit if the button is clicked.
4169 * @param array $options these become hidden form fields, so these options get passed to the script at $link.
4170 * @param string $label the caption that appears on the button.
4171 * @param string $method HTTP method used on the request of the button is clicked. 'get' or 'post'.
4172 * @param string $target no longer used.
4173 * @param boolean $return if false, output the form directly, otherwise return the HTML as a string.
4174 * @param string $tooltip a tooltip to add to the button as a title attribute.
4175 * @param boolean $disabled if true, the button will be disabled.
4176 * @param string $jsconfirmmessage if not empty then display a confirm dialogue with this string as the question.
4177 * @return string / nothing depending on the $return paramter.
4179 function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='', $disabled = false, $jsconfirmmessage='') {
4180 $output = '';
4181 $link = str_replace('"', '&quot;', $link); //basic XSS protection
4182 $output .= '<div class="singlebutton">';
4183 // taking target out, will need to add later target="'.$target.'"
4184 $output .= '<form action="'. $link .'" method="'. $method .'">';
4185 $output .= '<div>';
4186 if ($options) {
4187 foreach ($options as $name => $value) {
4188 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
4191 if ($tooltip) {
4192 $tooltip = 'title="' . s($tooltip) . '"';
4193 } else {
4194 $tooltip = '';
4196 if ($disabled) {
4197 $disabled = 'disabled="disabled"';
4198 } else {
4199 $disabled = '';
4201 if ($jsconfirmmessage){
4202 $jsconfirmmessage = addslashes_js($jsconfirmmessage);
4203 $jsconfirmmessage = 'onclick="return confirm(\''. $jsconfirmmessage .'\');" ';
4205 $output .= '<input type="submit" value="'. s($label) ."\" $tooltip $disabled $jsconfirmmessage/></div></form></div>";
4207 if ($return) {
4208 return $output;
4209 } else {
4210 echo $output;
4216 * Print a spacer image with the option of including a line break.
4218 * @param int $height ?
4219 * @param int $width ?
4220 * @param boolean $br ?
4221 * @todo Finish documenting this function
4223 function print_spacer($height=1, $width=1, $br=true, $return=false) {
4224 global $CFG;
4225 $output = '';
4227 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot .'/pix/spacer.gif" alt="" />';
4228 if ($br) {
4229 $output .= '<br />'."\n";
4232 if ($return) {
4233 return $output;
4234 } else {
4235 echo $output;
4240 * Given the path to a picture file in a course, or a URL,
4241 * this function includes the picture in the page.
4243 * @param string $path ?
4244 * @param int $courseid ?
4245 * @param int $height ?
4246 * @param int $width ?
4247 * @param string $link ?
4248 * @todo Finish documenting this function
4250 function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
4251 global $CFG;
4252 $output = '';
4254 if ($height) {
4255 $height = 'height="'. $height .'"';
4257 if ($width) {
4258 $width = 'width="'. $width .'"';
4260 if ($link) {
4261 $output .= '<a href="'. $link .'">';
4263 if (substr(strtolower($path), 0, 7) == 'http://') {
4264 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
4266 } else if ($courseid) {
4267 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
4268 if ($CFG->slasharguments) { // Use this method if possible for better caching
4269 $output .= $CFG->wwwroot .'/file.php/'. $courseid .'/'. $path;
4270 } else {
4271 $output .= $CFG->wwwroot .'/file.php?file=/'. $courseid .'/'. $path;
4273 $output .= '" />';
4274 } else {
4275 $output .= 'Error: must pass URL or course';
4277 if ($link) {
4278 $output .= '</a>';
4281 if ($return) {
4282 return $output;
4283 } else {
4284 echo $output;
4289 * Print the specified user's avatar.
4291 * If you pass a $user object that has id, picture, imagealt, firstname, lastname
4292 * you save a DB query.
4294 * @param int $user takes a userid, or a userobj
4295 * @param int $courseid ?
4296 * @param boolean $picture Print the user picture?
4297 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
4298 * @param boolean $return If false print picture to current page, otherwise return the output as string
4299 * @param boolean $link Enclose printed image in a link to view specified course?
4300 * @param string $target link target attribute
4301 * @param boolean $alttext use username or userspecified text in image alt attribute
4302 * return string
4303 * @todo Finish documenting this function
4305 function print_user_picture($user, $courseid, $picture=NULL, $size=0, $return=false, $link=true, $target='', $alttext=true) {
4306 global $CFG, $HTTPSPAGEREQUIRED;
4308 $needrec = false;
4309 // only touch the DB if we are missing data...
4310 if (is_object($user)) {
4311 // Note - both picture and imagealt _can_ be empty
4312 // what we are trying to see here is if they have been fetched
4313 // from the DB. We should use isset() _except_ that some installs
4314 // have those fields as nullable, and isset() will return false
4315 // on null. The only safe thing is to ask array_key_exists()
4316 // which works on objects. property_exists() isn't quite
4317 // what we want here...
4318 if (! (array_key_exists('picture', $user)
4319 && ($alttext && array_key_exists('imagealt', $user)
4320 || (isset($user->firstname) && isset($user->lastname)))) ) {
4321 $needrec = true;
4322 $user = $user->id;
4324 } else {
4325 if ($alttext) {
4326 // we need firstname, lastname, imagealt, can't escape...
4327 $needrec = true;
4328 } else {
4329 $userobj = new StdClass; // fake it to save DB traffic
4330 $userobj->id = $user;
4331 $userobj->picture = $picture;
4332 $user = clone($userobj);
4333 unset($userobj);
4336 if ($needrec) {
4337 $user = get_record('user','id',$user, '', '', '', '', 'id,firstname,lastname,imagealt');
4340 if ($link) {
4341 if ($target) {
4342 $target=' target="_blank"';
4344 $output = '<a '.$target.' href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&amp;course='. $courseid .'">';
4345 } else {
4346 $output = '';
4348 if (empty($size)) {
4349 $file = 'f2';
4350 $size = 35;
4351 } else if ($size === true or $size == 1) {
4352 $file = 'f1';
4353 $size = 100;
4354 } else if ($size >= 50) {
4355 $file = 'f1';
4356 } else {
4357 $file = 'f2';
4359 $class = "userpicture";
4360 if (!empty($HTTPSPAGEREQUIRED)) {
4361 $wwwroot = $CFG->httpswwwroot;
4362 } else {
4363 $wwwroot = $CFG->wwwroot;
4366 if (is_null($picture)) {
4367 $picture = $user->picture;
4370 if ($picture) { // Print custom user picture
4371 if ($CFG->slasharguments) { // Use this method if possible for better caching
4372 $src = $wwwroot .'/user/pix.php/'. $user->id .'/'. $file .'.jpg';
4373 } else {
4374 $src = $wwwroot .'/user/pix.php?file=/'. $user->id .'/'. $file .'.jpg';
4376 } else { // Print default user pictures (use theme version if available)
4377 $class .= " defaultuserpic";
4378 $src = "$CFG->pixpath/u/$file.png";
4380 $imagealt = '';
4381 if ($alttext) {
4382 if (!empty($user->imagealt)) {
4383 $imagealt = $user->imagealt;
4384 } else {
4385 $imagealt = get_string('pictureof','',fullname($user));
4389 $output .= '<img class="'.$class.'" src="'.$src.'" alt="'.s($imagealt).'" />';
4390 if ($link) {
4391 $output .= '</a>';
4394 if ($return) {
4395 return $output;
4396 } else {
4397 echo $output;
4402 * Prints a summary of a user in a nice little box.
4404 * @uses $CFG
4405 * @uses $USER
4406 * @param user $user A {@link $USER} object representing a user
4407 * @param course $course A {@link $COURSE} object representing a course
4409 function print_user($user, $course, $messageselect=false, $return=false) {
4411 global $CFG, $USER;
4413 $output = '';
4415 static $string;
4416 static $datestring;
4417 static $countries;
4419 $context = get_context_instance(CONTEXT_COURSE, $course->id);
4420 if (isset($user->context->id)) {
4421 $usercontext = get_context_instance_by_id($user->context->id);
4424 if (empty($string)) { // Cache all the strings for the rest of the page
4426 $string->email = get_string('email');
4427 $string->city = get_string('city');
4428 $string->lastaccess = get_string('lastaccess');
4429 $string->activity = get_string('activity');
4430 $string->unenrol = get_string('unenrol');
4431 $string->loginas = get_string('loginas');
4432 $string->fullprofile = get_string('fullprofile');
4433 $string->role = get_string('role');
4434 $string->name = get_string('name');
4435 $string->never = get_string('never');
4437 $datestring->day = get_string('day');
4438 $datestring->days = get_string('days');
4439 $datestring->hour = get_string('hour');
4440 $datestring->hours = get_string('hours');
4441 $datestring->min = get_string('min');
4442 $datestring->mins = get_string('mins');
4443 $datestring->sec = get_string('sec');
4444 $datestring->secs = get_string('secs');
4445 $datestring->year = get_string('year');
4446 $datestring->years = get_string('years');
4448 $countries = get_list_of_countries();
4451 /// Get the hidden field list
4452 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
4453 $hiddenfields = array();
4454 } else {
4455 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
4458 $output .= '<table class="userinfobox">';
4459 $output .= '<tr>';
4460 $output .= '<td class="left side">';
4461 $output .= print_user_picture($user, $course->id, $user->picture, true, true);
4462 $output .= '</td>';
4463 $output .= '<td class="content">';
4464 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
4465 $output .= '<div class="info">';
4466 if (!empty($user->role) and ($user->role <> $course->teacher)) {
4467 $output .= $string->role .': '. $user->role .'<br />';
4469 if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguest()) or
4470 has_capability('moodle/course:viewhiddenuserfields', $context)) {
4471 $output .= $string->email .': <a href="mailto:'. $user->email .'">'. $user->email .'</a><br />';
4473 if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
4474 $output .= $string->city .': ';
4475 if ($user->city && !isset($hiddenfields['city'])) {
4476 $output .= $user->city;
4478 if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
4479 if ($user->city && !isset($hiddenfields['city'])) {
4480 $output .= ', ';
4482 $output .= $countries[$user->country];
4484 $output .= '<br />';
4487 if (!isset($hiddenfields['lastaccess'])) {
4488 if ($user->lastaccess) {
4489 $output .= $string->lastaccess .': '. userdate($user->lastaccess);
4490 $output .= '&nbsp; ('. format_time(time() - $user->lastaccess, $datestring) .')';
4491 } else {
4492 $output .= $string->lastaccess .': '. $string->never;
4495 $output .= '</div></td><td class="links">';
4496 //link to blogs
4497 if ($CFG->bloglevel > 0) {
4498 $output .= '<a href="'.$CFG->wwwroot.'/blog/index.php?userid='.$user->id.'">'.get_string('blogs','blog').'</a><br />';
4500 //link to notes
4501 if (has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context)) {
4502 $output .= '<a href="'.$CFG->wwwroot.'/notes/index.php?course=' . $course->id. '&amp;user='.$user->id.'">'.get_string('notes','notes').'</a><br />';
4505 if (has_capability('moodle/user:viewuseractivitiesreport', $context) || (isset($usercontext) && has_capability('moodle/user:viewuseractivitiesreport', $usercontext))) {
4506 $timemidnight = usergetmidnight(time());
4507 $output .= '<a href="'. $CFG->wwwroot .'/course/user.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->activity .'</a><br />';
4509 if (has_capability('moodle/role:assign', $context, NULL)) { // Includes admins
4510 $output .= '<a href="'. $CFG->wwwroot .'/course/unenrol.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->unenrol .'</a><br />';
4512 if ($USER->id != $user->id && empty($USER->realuser) && has_capability('moodle/user:loginas', $context) &&
4513 ! has_capability('moodle/site:doanything', $context, $user->id, false)) {
4514 $output .= '<a href="'. $CFG->wwwroot .'/course/loginas.php?id='. $course->id .'&amp;user='. $user->id .'&amp;sesskey='. sesskey() .'">'. $string->loginas .'</a><br />';
4516 $output .= '<a href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&amp;course='. $course->id .'">'. $string->fullprofile .'...</a>';
4518 if (!empty($messageselect)) {
4519 $output .= '<br /><input type="checkbox" name="user'.$user->id.'" /> ';
4522 $output .= '</td></tr></table>';
4524 if ($return) {
4525 return $output;
4526 } else {
4527 echo $output;
4532 * Print a specified group's avatar.
4534 * @param group $group A single {@link group} object OR array of groups.
4535 * @param int $courseid The course ID.
4536 * @param boolean $large Default small picture, or large.
4537 * @param boolean $return If false print picture, otherwise return the output as string
4538 * @param boolean $link Enclose image in a link to view specified course?
4539 * @return string
4540 * @todo Finish documenting this function
4542 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
4543 global $CFG;
4545 if (is_array($group)) {
4546 $output = '';
4547 foreach($group as $g) {
4548 $output .= print_group_picture($g, $courseid, $large, true, $link);
4550 if ($return) {
4551 return $output;
4552 } else {
4553 echo $output;
4554 return;
4558 $context = get_context_instance(CONTEXT_COURSE, $courseid);
4560 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
4561 return '';
4564 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4565 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
4566 } else {
4567 $output = '';
4569 if ($large) {
4570 $file = 'f1';
4571 $size = 100;
4572 } else {
4573 $file = 'f2';
4574 $size = 35;
4576 if ($group->picture) { // Print custom group picture
4577 if ($CFG->slasharguments) { // Use this method if possible for better caching
4578 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot.'/user/pixgroup.php/'.$group->id.'/'.$file.'.jpg"'.
4579 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
4580 } else {
4581 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot.'/user/pixgroup.php?file=/'.$group->id.'/'.$file.'.jpg"'.
4582 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
4585 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4586 $output .= '</a>';
4589 if ($return) {
4590 return $output;
4591 } else {
4592 echo $output;
4597 * Print a png image.
4599 * @param string $url ?
4600 * @param int $sizex ?
4601 * @param int $sizey ?
4602 * @param boolean $return ?
4603 * @param string $parameters ?
4604 * @todo Finish documenting this function
4606 function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
4607 global $CFG;
4608 static $recentIE;
4610 if (!isset($recentIE)) {
4611 $recentIE = check_browser_version('MSIE', '5.0');
4614 if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
4615 $output .= '<img src="'. $CFG->pixpath .'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
4616 ' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
4617 ' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
4618 "'$url', sizingMethod='scale') ".
4619 ' '. $parameters .' />';
4620 } else {
4621 $output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
4624 if ($return) {
4625 return $output;
4626 } else {
4627 echo $output;
4632 * Print a nicely formatted table.
4634 * @param array $table is an object with several properties.
4635 * <ul>
4636 * <li>$table->head - An array of heading names.
4637 * <li>$table->align - An array of column alignments
4638 * <li>$table->size - An array of column sizes
4639 * <li>$table->wrap - An array of "nowrap"s or nothing
4640 * <li>$table->data[] - An array of arrays containing the data.
4641 * <li>$table->width - A percentage of the page
4642 * <li>$table->tablealign - Align the whole table
4643 * <li>$table->cellpadding - Padding on each cell
4644 * <li>$table->cellspacing - Spacing between cells
4645 * <li>$table->class - class attribute to put on the table
4646 * <li>$table->id - id attribute to put on the table.
4647 * <li>$table->rowclass[] - classes to add to particular rows.
4648 * <li>$table->summary - Description of the contents for screen readers.
4649 * </ul>
4650 * @param bool $return whether to return an output string or echo now
4651 * @return boolean or $string
4652 * @todo Finish documenting this function
4654 function print_table($table, $return=false) {
4655 $output = '';
4657 if (isset($table->align)) {
4658 foreach ($table->align as $key => $aa) {
4659 if ($aa) {
4660 $align[$key] = ' text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
4661 } else {
4662 $align[$key] = '';
4666 if (isset($table->size)) {
4667 foreach ($table->size as $key => $ss) {
4668 if ($ss) {
4669 $size[$key] = ' width:'. $ss .';';
4670 } else {
4671 $size[$key] = '';
4675 if (isset($table->wrap)) {
4676 foreach ($table->wrap as $key => $ww) {
4677 if ($ww) {
4678 $wrap[$key] = ' white-space:nowrap;';
4679 } else {
4680 $wrap[$key] = '';
4685 if (empty($table->width)) {
4686 $table->width = '80%';
4689 if (empty($table->tablealign)) {
4690 $table->tablealign = 'center';
4693 if (!isset($table->cellpadding)) {
4694 $table->cellpadding = '5';
4697 if (!isset($table->cellspacing)) {
4698 $table->cellspacing = '1';
4701 if (empty($table->class)) {
4702 $table->class = 'generaltable';
4705 $tableid = empty($table->id) ? '' : 'id="'.$table->id.'"';
4707 $output .= '<table width="'.$table->width.'" ';
4708 if (!empty($table->summary)) {
4709 $output .= " summary=\"$table->summary\"";
4711 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
4713 $countcols = 0;
4715 if (!empty($table->head)) {
4716 $countcols = count($table->head);
4717 $output .= '<tr>';
4718 foreach ($table->head as $key => $heading) {
4720 if (!isset($size[$key])) {
4721 $size[$key] = '';
4723 if (!isset($align[$key])) {
4724 $align[$key] = '';
4727 $output .= '<th style="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.'" scope="col">'. $heading .'</th>';
4729 $output .= '</tr>'."\n";
4732 if (!empty($table->data)) {
4733 $oddeven = 1;
4734 foreach ($table->data as $key => $row) {
4735 $oddeven = $oddeven ? 0 : 1;
4736 if (!isset($table->rowclass[$key])) {
4737 $table->rowclass[$key] = '';
4739 $output .= '<tr class="r'.$oddeven.' '.$table->rowclass[$key].'">'."\n";
4740 if ($row == 'hr' and $countcols) {
4741 $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
4742 } else { /// it's a normal row of data
4743 foreach ($row as $key => $item) {
4744 if (!isset($size[$key])) {
4745 $size[$key] = '';
4747 if (!isset($align[$key])) {
4748 $align[$key] = '';
4750 if (!isset($wrap[$key])) {
4751 $wrap[$key] = '';
4753 $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.'">'. $item .'</td>';
4756 $output .= '</tr>'."\n";
4759 $output .= '</table>'."\n";
4761 if ($return) {
4762 return $output;
4765 echo $output;
4766 return true;
4769 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
4770 static $strftimerecent = null;
4771 $output = '';
4773 if (is_null($viewfullnames)) {
4774 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
4775 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
4778 if (is_null($strftimerecent)) {
4779 $strftimerecent = get_string('strftimerecent');
4782 $output .= '<div class="head">';
4783 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
4784 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
4785 $output .= '</div>';
4786 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
4788 if ($return) {
4789 return $output;
4790 } else {
4791 echo $output;
4797 * Prints a basic textarea field.
4799 * @uses $CFG
4800 * @param boolean $usehtmleditor ?
4801 * @param int $rows ?
4802 * @param int $cols ?
4803 * @param null $width <b>Legacy field no longer used!</b> Set to zero to get control over mincols
4804 * @param null $height <b>Legacy field no longer used!</b> Set to zero to get control over minrows
4805 * @param string $name ?
4806 * @param string $value ?
4807 * @param int $courseid ?
4808 * @todo Finish documenting this function
4810 function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $courseid=0, $return=false, $id='') {
4811 /// $width and height are legacy fields and no longer used as pixels like they used to be.
4812 /// However, you can set them to zero to override the mincols and minrows values below.
4814 global $CFG, $COURSE, $HTTPSPAGEREQUIRED;
4815 static $scriptcount = 0; // For loading the htmlarea script only once.
4817 $mincols = 65;
4818 $minrows = 10;
4819 $str = '';
4821 if ($id === '') {
4822 $id = 'edit-'.$name;
4825 if ( empty($CFG->editorsrc) ) { // for backward compatibility.
4826 if (empty($courseid)) {
4827 $courseid = $COURSE->id;
4830 if ($usehtmleditor) {
4831 if (!empty($courseid) and has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE, $courseid))) {
4832 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '&amp;httpsrequired=1';
4833 // needed for course file area browsing in image insert plugin
4834 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4835 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php?id='.$courseid.$httpsrequired.'"></script>'."\n" : '';
4836 } else {
4837 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '?httpsrequired=1';
4838 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4839 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php'.$httpsrequired.'"></script>'."\n" : '';
4842 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4843 $CFG->httpswwwroot .'/lib/editor/htmlarea/lang/en.php"></script>'."\n" : '';
4844 $scriptcount++;
4846 if ($height) { // Usually with legacy calls
4847 if ($rows < $minrows) {
4848 $rows = $minrows;
4851 if ($width) { // Usually with legacy calls
4852 if ($cols < $mincols) {
4853 $cols = $mincols;
4858 $str .= '<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">';
4859 if ($usehtmleditor) {
4860 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
4861 } else {
4862 $str .= s($value);
4864 $str .= '</textarea>'."\n";
4866 if ($usehtmleditor) {
4867 // Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
4868 $str .= '<script type="text/javascript">
4869 //<![CDATA[
4870 document.write(\''.addslashes_js(editorshortcutshelpbutton()).'\');
4871 //]]>
4872 </script>';
4875 if ($return) {
4876 return $str;
4878 echo $str;
4882 * Sets up the HTML editor on textareas in the current page.
4883 * If a field name is provided, then it will only be
4884 * applied to that field - otherwise it will be used
4885 * on every textarea in the page.
4887 * In most cases no arguments need to be supplied
4889 * @param string $name Form element to replace with HTMl editor by name
4891 function use_html_editor($name='', $editorhidebuttons='', $id='') {
4892 global $THEME;
4894 $editor = 'editor_'.md5($name); //name might contain illegal characters
4895 if ($id === '') {
4896 $id = 'edit-'.$name;
4898 echo "\n".'<script type="text/javascript" defer="defer">'."\n";
4899 echo '//<![CDATA['."\n\n"; // Extra \n is to fix odd wiki problem, MDL-8185
4900 echo "$editor = new HTMLArea('$id');\n";
4901 echo "var config = $editor.config;\n";
4903 echo print_editor_config($editorhidebuttons);
4905 if (empty($THEME->htmleditorpostprocess)) {
4906 if (empty($name)) {
4907 echo "\nHTMLArea.replaceAll($editor.config);\n";
4908 } else {
4909 echo "\n$editor.generate();\n";
4911 } else {
4912 if (empty($name)) {
4913 echo "\nvar HTML_name = '';";
4914 } else {
4915 echo "\nvar HTML_name = \"$name;\"";
4917 echo "\nvar HTML_editor = $editor;";
4919 echo '//]]>'."\n";
4920 echo '</script>'."\n";
4923 function print_editor_config($editorhidebuttons='', $return=false) {
4924 global $CFG;
4926 $str = "config.pageStyle = \"body {";
4928 if (!(empty($CFG->editorbackgroundcolor))) {
4929 $str .= " background-color: $CFG->editorbackgroundcolor;";
4932 if (!(empty($CFG->editorfontfamily))) {
4933 $str .= " font-family: $CFG->editorfontfamily;";
4936 if (!(empty($CFG->editorfontsize))) {
4937 $str .= " font-size: $CFG->editorfontsize;";
4940 $str .= " }\";\n";
4941 $str .= "config.killWordOnPaste = ";
4942 $str .= (empty($CFG->editorkillword)) ? "false":"true";
4943 $str .= ';'."\n";
4944 $str .= 'config.fontname = {'."\n";
4946 $fontlist = isset($CFG->editorfontlist) ? explode(';', $CFG->editorfontlist) : array();
4947 $i = 1; // Counter is used to get rid of the last comma.
4949 foreach ($fontlist as $fontline) {
4950 if (!empty($fontline)) {
4951 if ($i > 1) {
4952 $str .= ','."\n";
4954 list($fontkey, $fontvalue) = split(':', $fontline);
4955 $str .= '"'. $fontkey ."\":\t'". $fontvalue ."'";
4957 $i++;
4960 $str .= '};';
4962 if (!empty($editorhidebuttons)) {
4963 $str .= "\nconfig.hideSomeButtons(\" ". $editorhidebuttons ." \");\n";
4964 } else if (!empty($CFG->editorhidebuttons)) {
4965 $str .= "\nconfig.hideSomeButtons(\" ". $CFG->editorhidebuttons ." \");\n";
4968 if (!empty($CFG->editorspelling) && !empty($CFG->aspellpath)) {
4969 $str .= print_speller_code($CFG->htmleditor, true);
4972 if ($return) {
4973 return $str;
4975 echo $str;
4979 * Returns a turn edit on/off button for course in a self contained form.
4980 * Used to be an icon, but it's now a simple form button
4982 * Note that the caller is responsible for capchecks.
4984 * @uses $CFG
4985 * @uses $USER
4986 * @param int $courseid The course to update by id as found in 'course' table
4987 * @return string
4989 function update_course_icon($courseid) {
4990 global $CFG, $USER;
4992 if (!empty($USER->editing)) {
4993 $string = get_string('turneditingoff');
4994 $edit = '0';
4995 } else {
4996 $string = get_string('turneditingon');
4997 $edit = '1';
5000 return '<form '.$CFG->frametarget.' method="get" action="'.$CFG->wwwroot.'/course/view.php">'.
5001 '<div>'.
5002 '<input type="hidden" name="id" value="'.$courseid.'" />'.
5003 '<input type="hidden" name="edit" value="'.$edit.'" />'.
5004 '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
5005 '<input type="submit" value="'.$string.'" />'.
5006 '</div></form>';
5010 * Returns a little popup menu for switching roles
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 switchroles_form($courseid) {
5019 global $CFG, $USER;
5022 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
5023 return '';
5026 if (!empty($USER->access['rsw'][$context->path])){ // Just a button to return to normal
5027 $options = array();
5028 $options['id'] = $courseid;
5029 $options['sesskey'] = sesskey();
5030 $options['switchrole'] = 0;
5032 return print_single_button($CFG->wwwroot.'/course/view.php', $options,
5033 get_string('switchrolereturn'), 'post', '_self', true);
5036 if (has_capability('moodle/role:switchroles', $context)) {
5037 if (!$roles = get_assignable_roles_for_switchrole($context)) {
5038 return ''; // Nothing to show!
5040 // unset default user role - it would not work
5041 unset($roles[$CFG->guestroleid]);
5042 return popup_form($CFG->wwwroot.'/course/view.php?id='.$courseid.'&amp;sesskey='.sesskey().'&amp;switchrole=',
5043 $roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
5046 return '';
5051 * Returns a turn edit on/off button for course in a self contained form.
5052 * Used to be an icon, but it's now a simple form button
5054 * @uses $CFG
5055 * @uses $USER
5056 * @param int $courseid The course to update by id as found in 'course' table
5057 * @return string
5059 function update_mymoodle_icon() {
5061 global $CFG, $USER;
5063 if (!empty($USER->editing)) {
5064 $string = get_string('updatemymoodleoff');
5065 $edit = '0';
5066 } else {
5067 $string = get_string('updatemymoodleon');
5068 $edit = '1';
5071 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
5072 "<div>".
5073 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5074 "<input type=\"submit\" value=\"$string\" /></div></form>";
5078 * Returns a turn edit on/off button for tag in a self contained form.
5080 * @uses $CFG
5081 * @uses $USER
5082 * @return string
5084 function update_tag_button($tagid) {
5086 global $CFG, $USER;
5088 if (!empty($USER->editing)) {
5089 $string = get_string('turneditingoff');
5090 $edit = '0';
5091 } else {
5092 $string = get_string('turneditingon');
5093 $edit = '1';
5096 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/tag/index.php\">".
5097 "<div>".
5098 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5099 "<input type=\"hidden\" name=\"id\" value=\"$tagid\" />".
5100 "<input type=\"submit\" value=\"$string\" /></div></form>";
5104 * Prints the editing button on a module "view" page
5106 * @uses $CFG
5107 * @param type description
5108 * @todo Finish documenting this function
5110 function update_module_button($moduleid, $courseid, $string) {
5111 global $CFG, $USER;
5113 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $moduleid))) {
5114 $string = get_string('updatethis', '', $string);
5116 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
5117 "<div>".
5118 "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
5119 "<input type=\"hidden\" name=\"return\" value=\"true\" />".
5120 "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
5121 "<input type=\"submit\" value=\"$string\" /></div></form>";
5122 } else {
5123 return '';
5128 * Prints the editing button on a category page
5130 * @uses $CFG
5131 * @uses $USER
5132 * @param int $categoryid ?
5133 * @return string
5134 * @todo Finish documenting this function
5136 function update_category_button($categoryid) {
5137 global $CFG, $USER;
5139 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_COURSECAT, $categoryid))) {
5140 if (!empty($USER->categoryediting)) {
5141 $string = get_string('turneditingoff');
5142 $edit = 'off';
5143 } else {
5144 $string = get_string('turneditingon');
5145 $edit = 'on';
5148 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/category.php\">".
5149 '<div>'.
5150 "<input type=\"hidden\" name=\"id\" value=\"$categoryid\" />".
5151 "<input type=\"hidden\" name=\"categoryedit\" value=\"$edit\" />".
5152 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5153 "<input type=\"submit\" value=\"$string\" /></div></form>";
5158 * Prints the editing button on categories listing
5160 * @uses $CFG
5161 * @uses $USER
5162 * @return string
5164 function update_categories_button() {
5165 global $CFG, $USER;
5167 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
5168 if (!empty($USER->categoryediting)) {
5169 $string = get_string('turneditingoff');
5170 $categoryedit = 'off';
5171 } else {
5172 $string = get_string('turneditingon');
5173 $categoryedit = 'on';
5176 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/index.php\">".
5177 '<div>'.
5178 '<input type="hidden" name="categoryedit" value="'. $categoryedit .'" />'.
5179 '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />'.
5180 '<input type="submit" value="'. $string .'" /></div></form>';
5185 * Prints the editing button on search results listing
5186 * For bulk move courses to another category
5189 function update_categories_search_button($search,$page,$perpage) {
5190 global $CFG, $USER;
5192 // not sure if this capability is the best here
5193 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
5194 if (!empty($USER->categoryediting)) {
5195 $string = get_string("turneditingoff");
5196 $edit = "off";
5197 $perpage = 30;
5198 } else {
5199 $string = get_string("turneditingon");
5200 $edit = "on";
5203 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
5204 '<div>'.
5205 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5206 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5207 "<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
5208 "<input type=\"hidden\" name=\"page\" value=\"$page\" />".
5209 "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
5210 "<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
5215 * Given a course and a (current) coursemodule
5216 * This function returns a small popup menu with all the
5217 * course activity modules in it, as a navigation menu
5218 * The data is taken from the serialised array stored in
5219 * the course record
5221 * @param course $course A {@link $COURSE} object.
5222 * @param course $cm A {@link $COURSE} object.
5223 * @param string $targetwindow ?
5224 * @return string
5225 * @todo Finish documenting this function
5227 function navmenu($course, $cm=NULL, $targetwindow='self') {
5229 global $CFG, $THEME, $USER;
5231 if (empty($THEME->navmenuwidth)) {
5232 $width = 50;
5233 } else {
5234 $width = $THEME->navmenuwidth;
5237 if ($cm) {
5238 $cm = $cm->id;
5241 if ($course->format == 'weeks') {
5242 $strsection = get_string('week');
5243 } else {
5244 $strsection = get_string('topic');
5246 $strjumpto = get_string('jumpto');
5248 $modinfo = get_fast_modinfo($course);
5249 $context = get_context_instance(CONTEXT_COURSE, $course->id);
5251 $section = -1;
5252 $selected = '';
5253 $url = '';
5254 $previousmod = NULL;
5255 $backmod = NULL;
5256 $nextmod = NULL;
5257 $selectmod = NULL;
5258 $logslink = NULL;
5259 $flag = false;
5260 $menu = array();
5261 $menustyle = array();
5263 $sections = get_records('course_sections','course',$course->id,'section','section,visible,summary');
5265 if (!empty($THEME->makenavmenulist)) { /// A hack to produce an XHTML navmenu list for use in themes
5266 $THEME->navmenulist = navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
5269 foreach ($modinfo->cms as $mod) {
5270 if ($mod->modname == 'label') {
5271 continue;
5274 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
5275 break;
5278 if (!$mod->uservisible) { // do not icnlude empty sections at all
5279 continue;
5282 if ($mod->sectionnum > 0 and $section != $mod->sectionnum) {
5283 $thissection = $sections[$mod->sectionnum];
5285 if ($thissection->visible or !$course->hiddensections or
5286 has_capability('moodle/course:viewhiddensections', $context)) {
5287 $thissection->summary = strip_tags(format_string($thissection->summary,true));
5288 if ($course->format == 'weeks' or empty($thissection->summary)) {
5289 $menu[] = '--'.$strsection ." ". $mod->sectionnum;
5290 } else {
5291 if (strlen($thissection->summary) < ($width-3)) {
5292 $menu[] = '--'.$thissection->summary;
5293 } else {
5294 $menu[] = '--'.substr($thissection->summary, 0, $width).'...';
5297 $section = $mod->sectionnum;
5298 } else {
5299 // no activities from this hidden section shown
5300 continue;
5304 $url = $mod->modname.'/view.php?id='. $mod->id;
5305 if ($flag) { // the current mod is the "next" mod
5306 $nextmod = $mod;
5307 $flag = false;
5309 $localname = $mod->name;
5310 if ($cm == $mod->id) {
5311 $selected = $url;
5312 $selectmod = $mod;
5313 $backmod = $previousmod;
5314 $flag = true; // set flag so we know to use next mod for "next"
5315 $localname = $strjumpto;
5316 $strjumpto = '';
5317 } else {
5318 $localname = strip_tags(format_string($localname,true));
5319 $tl=textlib_get_instance();
5320 if ($tl->strlen($localname) > ($width+5)) {
5321 $localname = $tl->substr($localname, 0, $width).'...';
5323 if (!$mod->visible) {
5324 $localname = '('.$localname.')';
5327 $menu[$url] = $localname;
5328 if (empty($THEME->navmenuiconshide)) {
5329 $menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif);"'; // Unfortunately necessary to do this here
5331 $previousmod = $mod;
5333 //Accessibility: added Alt text, replaced &gt; &lt; with 'silent' character and 'accesshide' text.
5335 if ($selectmod and has_capability('moodle/site:viewreports', $context)) {
5336 $logstext = get_string('alllogs');
5337 $logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
5338 $CFG->frametarget.'onclick="this.target=\''.$CFG->framename.'\';"'.' href="'.
5339 $CFG->wwwroot.'/course/report/log/index.php?chooselog=1&amp;user=0&amp;date=0&amp;id='.
5340 $course->id.'&amp;modid='.$selectmod->id.'">'.
5341 '<img class="icon log" src="'.$CFG->pixpath.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
5344 if ($backmod) {
5345 $backtext= get_string('activityprev', 'access');
5346 $backmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$backmod->modname.'/view.php" '.
5347 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
5348 '<input type="hidden" name="id" value="'.$backmod->id.'" />'.
5349 '<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
5350 '</button></fieldset></form></li>';
5352 if ($nextmod) {
5353 $nexttext= get_string('activitynext', 'access');
5354 $nextmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$nextmod->modname.'/view.php" '.
5355 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
5356 '<input type="hidden" name="id" value="'.$nextmod->id.'" />'.
5357 '<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
5358 '</button></fieldset></form></li>';
5361 return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
5362 '<li>'.popup_form($CFG->wwwroot .'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
5363 '', '', true, $targetwindow, '', $menustyle).'</li>'.
5364 $nextmod . '</ul>'."\n".'</div>';
5368 * Given a course
5369 * This function returns a small popup menu with all the
5370 * course activity modules in it, as a navigation menu
5371 * outputs a simple list structure in XHTML
5372 * The data is taken from the serialised array stored in
5373 * the course record
5375 * @param course $course A {@link $COURSE} object.
5376 * @return string
5377 * @todo Finish documenting this function
5379 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
5381 global $CFG;
5383 $section = -1;
5384 $url = '';
5385 $menu = array();
5386 $doneheading = false;
5388 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
5390 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
5391 foreach ($modinfo->cms as $mod) {
5392 if ($mod->modname == 'label') {
5393 continue;
5396 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
5397 break;
5400 if (!$mod->uservisible) { // do not icnlude empty sections at all
5401 continue;
5404 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
5405 $thissection = $sections[$mod->sectionnum];
5407 if ($thissection->visible or !$course->hiddensections or
5408 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
5409 $thissection->summary = strip_tags(format_string($thissection->summary,true));
5410 if (!$doneheading) {
5411 $menu[] = '</ul></li>';
5413 if ($course->format == 'weeks' or empty($thissection->summary)) {
5414 $item = $strsection ." ". $mod->sectionnum;
5415 } else {
5416 if (strlen($thissection->summary) < ($width-3)) {
5417 $item = $thissection->summary;
5418 } else {
5419 $item = substr($thissection->summary, 0, $width).'...';
5422 $menu[] = '<li class="section"><span>'.$item.'</span>';
5423 $menu[] = '<ul>';
5424 $doneheading = true;
5426 $section = $mod->sectionnum;
5427 } else {
5428 // no activities from this hidden section shown
5429 continue;
5433 $url = $mod->modname .'/view.php?id='. $mod->id;
5434 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
5435 if (strlen($mod->name) > ($width+5)) {
5436 $mod->name = substr($mod->name, 0, $width).'...';
5438 if (!$mod->visible) {
5439 $mod->name = '('.$mod->name.')';
5441 $class = 'activity '.$mod->modname;
5442 $class .= ($cmid == $mod->cm) ? ' selected' : '';
5443 $menu[] = '<li class="'.$class.'">'.
5444 '<img src="'.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif" alt="" />'.
5445 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
5448 if ($doneheading) {
5449 $menu[] = '</ul></li>';
5451 $menu[] = '</ul></li></ul>';
5453 return implode("\n", $menu);
5457 * Prints form items with the names $day, $month and $year
5459 * @param string $day fieldname
5460 * @param string $month fieldname
5461 * @param string $year fieldname
5462 * @param int $currenttime A default timestamp in GMT
5463 * @param boolean $return
5465 function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
5467 if (!$currenttime) {
5468 $currenttime = time();
5470 $currentdate = usergetdate($currenttime);
5472 for ($i=1; $i<=31; $i++) {
5473 $days[$i] = $i;
5475 for ($i=1; $i<=12; $i++) {
5476 $months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
5478 for ($i=1970; $i<=2020; $i++) {
5479 $years[$i] = $i;
5481 return choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', $return)
5482 .choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', $return)
5483 .choose_from_menu($years, $year, $currentdate['year'], '', '', '0', $return);
5488 *Prints form items with the names $hour and $minute
5490 * @param string $hour fieldname
5491 * @param string ? $minute fieldname
5492 * @param $currenttime A default timestamp in GMT
5493 * @param int $step minute spacing
5494 * @param boolean $return
5496 function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
5498 if (!$currenttime) {
5499 $currenttime = time();
5501 $currentdate = usergetdate($currenttime);
5502 if ($step != 1) {
5503 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
5505 for ($i=0; $i<=23; $i++) {
5506 $hours[$i] = sprintf("%02d",$i);
5508 for ($i=0; $i<=59; $i+=$step) {
5509 $minutes[$i] = sprintf("%02d",$i);
5512 return choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',$return)
5513 .choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',$return);
5517 * Prints time limit value selector
5519 * @uses $CFG
5520 * @param int $timelimit default
5521 * @param string $unit
5522 * @param string $name
5523 * @param boolean $return
5525 function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
5527 global $CFG;
5529 if ($unit) {
5530 $unit = ' '.$unit;
5533 // Max timelimit is sessiontimeout - 10 minutes.
5534 $maxvalue = ($CFG->sessiontimeout / 60) - 10;
5536 for ($i=1; $i<=$maxvalue; $i++) {
5537 $minutes[$i] = $i.$unit;
5539 return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
5543 * Prints a grade menu (as part of an existing form) with help
5544 * Showing all possible numerical grades and scales
5546 * @uses $CFG
5547 * @param int $courseid ?
5548 * @param string $name ?
5549 * @param string $current ?
5550 * @param boolean $includenograde ?
5551 * @todo Finish documenting this function
5553 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
5555 global $CFG;
5557 $output = '';
5558 $strscale = get_string('scale');
5559 $strscales = get_string('scales');
5561 $scales = get_scales_menu($courseid);
5562 foreach ($scales as $i => $scalename) {
5563 $grades[-$i] = $strscale .': '. $scalename;
5565 if ($includenograde) {
5566 $grades[0] = get_string('nograde');
5568 for ($i=100; $i>=1; $i--) {
5569 $grades[$i] = $i;
5571 $output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
5573 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5574 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5575 $linkobject, 400, 500, $strscales, 'none', true);
5577 if ($return) {
5578 return $output;
5579 } else {
5580 echo $output;
5585 * Prints a scale menu (as part of an existing form) including help button
5586 * Just like {@link print_grade_menu()} but without the numeric grades
5588 * @param int $courseid ?
5589 * @param string $name ?
5590 * @param string $current ?
5591 * @todo Finish documenting this function
5593 function print_scale_menu($courseid, $name, $current, $return=false) {
5595 global $CFG;
5597 $output = '';
5598 $strscales = get_string('scales');
5599 $output .= choose_from_menu(get_scales_menu($courseid), $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);
5604 if ($return) {
5605 return $output;
5606 } else {
5607 echo $output;
5612 * Prints a help button about a scale
5614 * @uses $CFG
5615 * @param id $courseid ?
5616 * @param object $scale ?
5617 * @todo Finish documenting this function
5619 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
5621 global $CFG;
5623 $output = '';
5624 $strscales = get_string('scales');
5626 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5627 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true&amp;scaleid='. $scale->id, 'ratingscale',
5628 $linkobject, 400, 500, $scale->name, 'none', true);
5629 if ($return) {
5630 return $output;
5631 } else {
5632 echo $output;
5637 * Print an error page displaying an error message. New method - use this for new code.
5639 * @uses $SESSION
5640 * @uses $CFG
5641 * @param string $errorcode The name of the string from error.php to print
5642 * @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.
5643 * @param object $a Extra words and phrases that might be required in the error string
5645 function print_error ($errorcode, $module='', $link='', $a=NULL) {
5647 global $CFG, $SESSION, $THEME;
5649 if (empty($module) || $module == 'moodle' || $module == 'core') {
5650 $module = 'error';
5651 $modulelink = 'moodle';
5652 } else {
5653 $modulelink = $module;
5656 if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
5657 if ( !empty($SESSION->fromurl) ) {
5658 $link = $SESSION->fromurl;
5659 unset($SESSION->fromurl);
5660 } else {
5661 $link = $CFG->wwwroot .'/';
5665 if (!empty($CFG->errordocroot)) {
5666 $errordocroot = $CFG->errordocroot;
5667 } else if (!empty($CFG->docroot)) {
5668 $errordocroot = $CFG->docroot;
5669 } else {
5670 $errordocroot = 'http://docs.moodle.org';
5673 $message = get_string($errorcode, $module, $a);
5675 if (defined('FULLME') && FULLME == 'cron') {
5676 // Errors in cron should be mtrace'd.
5677 mtrace($message);
5678 die;
5681 $message = clean_text('<p class="errormessage">'.$message.'</p>'.
5682 '<p class="errorcode">'.
5683 '<a href="'.$errordocroot.'/en/error/'.$modulelink.'/'.$errorcode.'">'.
5684 get_string('moreinformation').'</a></p>');
5686 if (! defined('HEADER_PRINTED')) {
5687 //header not yet printed
5688 @header('HTTP/1.0 404 Not Found');
5689 print_header(get_string('error'));
5690 } else {
5691 print_container_end_all(false, $THEME->open_header_containers);
5694 echo '<br />';
5696 print_simple_box($message, '', '', '', '', 'errorbox');
5698 debugging('Stack trace:', DEBUG_DEVELOPER);
5700 // in case we are logging upgrade in admin/index.php stop it
5701 if (function_exists('upgrade_log_finish')) {
5702 upgrade_log_finish();
5705 if (!empty($link)) {
5706 print_continue($link);
5709 print_footer();
5711 for ($i=0;$i<512;$i++) { // Padding to help IE work with 404
5712 echo ' ';
5714 die;
5718 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
5719 * Default errorcode is 1.
5721 * Very useful for perl-like error-handling:
5723 * do_somethting() or mdie("Something went wrong");
5725 * @param string $msg Error message
5726 * @param integer $errorcode Error code to emit
5728 function mdie($msg='', $errorcode=1) {
5729 trigger_error($msg);
5730 exit($errorcode);
5734 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
5735 * Should be used only with htmleditor or textarea.
5736 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
5737 * helpbutton.
5738 * @return string
5740 function editorhelpbutton(){
5741 global $CFG, $SESSION;
5742 $items = func_get_args();
5743 $i = 1;
5744 $urlparams = array();
5745 $titles = array();
5746 foreach ($items as $item){
5747 if (is_array($item)){
5748 $urlparams[] = "keyword$i=".urlencode($item[0]);
5749 $urlparams[] = "title$i=".urlencode($item[1]);
5750 if (isset($item[2])){
5751 $urlparams[] = "module$i=".urlencode($item[2]);
5753 $titles[] = trim($item[1], ". \t");
5754 }elseif (is_string($item)){
5755 $urlparams[] = "button$i=".urlencode($item);
5756 switch ($item){
5757 case 'reading' :
5758 $titles[] = get_string("helpreading");
5759 break;
5760 case 'writing' :
5761 $titles[] = get_string("helpwriting");
5762 break;
5763 case 'questions' :
5764 $titles[] = get_string("helpquestions");
5765 break;
5766 case 'emoticons' :
5767 $titles[] = get_string("helpemoticons");
5768 break;
5769 case 'richtext' :
5770 $titles[] = get_string('helprichtext');
5771 break;
5772 case 'text' :
5773 $titles[] = get_string('helptext');
5774 break;
5775 default :
5776 error('Unknown help topic '.$item);
5779 $i++;
5781 if (count($titles)>1){
5782 //join last two items with an 'and'
5783 $a = new object();
5784 $a->one = $titles[count($titles) - 2];
5785 $a->two = $titles[count($titles) - 1];
5786 $titles[count($titles) - 2] = get_string('and', '', $a);
5787 unset($titles[count($titles) - 1]);
5789 $alttag = join (', ', $titles);
5791 $paramstring = join('&', $urlparams);
5792 $linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath .'/help.gif" />';
5793 return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), $alttag, $linkobject, 400, 500, $alttag, 'none', true);
5797 * Print a help button.
5799 * @uses $CFG
5800 * @param string $page The keyword that defines a help page
5801 * @param string $title The title of links, rollover tips, alt tags etc
5802 * 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
5803 * @param string $module Which module is the page defined in
5804 * @param mixed $image Use a help image for the link? (true/false/"both")
5805 * @param boolean $linktext If true, display the title next to the help icon.
5806 * @param string $text If defined then this text is used in the page, and
5807 * the $page variable is ignored.
5808 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
5809 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
5810 * @return string
5811 * @todo Finish documenting this function
5813 function helpbutton ($page, $title, $module='moodle', $image=true, $linktext=false, $text='', $return=false,
5814 $imagetext='') {
5815 global $CFG, $COURSE;
5817 // fix for MDL-7734
5818 if (!empty($COURSE->lang)) {
5819 $forcelang = $COURSE->lang;
5820 } else {
5821 $forcelang = '';
5824 if ($module == '') {
5825 $module = 'moodle';
5828 if ($title == '' && $linktext == '') {
5829 debugging('Error in call to helpbutton function: at least one of $title and $linktext is required');
5832 // Warn users about new window for Accessibility
5833 $tooltip = get_string('helpprefix2', '', trim($title, ". \t")) .' ('.get_string('newwindow').')';
5835 $linkobject = '';
5837 if ($image) {
5838 if ($linktext) {
5839 // MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
5840 $linkobject .= $title.'&nbsp;';
5841 $tooltip = get_string('helpwiththis');
5843 if ($imagetext) {
5844 $linkobject .= $imagetext;
5845 } else {
5846 $linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
5847 $CFG->pixpath .'/help.gif" />';
5849 } else {
5850 $linkobject .= $tooltip;
5853 // fix for MDL-7734
5854 if ($text) {
5855 $url = '/help.php?module='. $module .'&amp;text='. s(urlencode($text).'&amp;forcelang='.$forcelang);
5856 } else {
5857 $url = '/help.php?module='. $module .'&amp;file='. $page .'.html&amp;forcelang='.$forcelang;
5860 $link = '<span class="helplink">'.
5861 link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
5862 '</span>';
5864 if ($return) {
5865 return $link;
5866 } else {
5867 echo $link;
5872 * Print a help button.
5874 * Prints a special help button that is a link to the "live" emoticon popup
5875 * @uses $CFG
5876 * @uses $SESSION
5877 * @param string $form ?
5878 * @param string $field ?
5879 * @todo Finish documenting this function
5881 function emoticonhelpbutton($form, $field, $return = false) {
5883 global $CFG, $SESSION;
5885 $SESSION->inserttextform = $form;
5886 $SESSION->inserttextfield = $field;
5887 $imagetext = '<img src="' . $CFG->pixpath . '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
5888 $help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
5889 if (!$return){
5890 echo $help;
5891 } else {
5892 return $help;
5897 * Print a help button.
5899 * Prints a special help button for html editors (htmlarea in this case)
5900 * @uses $CFG
5902 function editorshortcutshelpbutton() {
5904 global $CFG;
5905 $imagetext = '<img src="' . $CFG->httpswwwroot . '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
5906 get_string('editorshortcutkeys').'" class="iconkbhelp" />';
5908 return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
5912 * Print a message and exit.
5914 * @uses $CFG
5915 * @param string $message ?
5916 * @param string $link ?
5917 * @todo Finish documenting this function
5919 function notice ($message, $link='', $course=NULL) {
5920 global $CFG, $SITE, $THEME, $COURSE;
5922 $message = clean_text($message); // In case nasties are in here
5924 if (defined('FULLME') && FULLME == 'cron') {
5925 // notices in cron should be mtrace'd.
5926 mtrace($message);
5927 die;
5930 if (! defined('HEADER_PRINTED')) {
5931 //header not yet printed
5932 print_header(get_string('notice'));
5933 } else {
5934 print_container_end_all(false, $THEME->open_header_containers);
5937 print_box($message, 'generalbox', 'notice');
5938 print_continue($link);
5940 if (empty($course)) {
5941 print_footer($COURSE);
5942 } else {
5943 print_footer($course);
5945 exit;
5949 * Print a message along with "Yes" and "No" links for the user to continue.
5951 * @param string $message The text to display
5952 * @param string $linkyes The link to take the user to if they choose "Yes"
5953 * @param string $linkno The link to take the user to if they choose "No"
5954 * TODO Document remaining arguments
5956 function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
5958 global $CFG;
5960 $message = clean_text($message);
5961 $linkyes = clean_text($linkyes);
5962 $linkno = clean_text($linkno);
5964 print_box_start('generalbox', 'notice');
5965 echo '<p>'. $message .'</p>';
5966 echo '<div class="buttons">';
5967 print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename);
5968 print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename);
5969 echo '</div>';
5970 print_box_end();
5974 * Provide an definition of error_get_last for PHP before 5.2.0. This simply
5975 * returns NULL, since there is not way to get the right answer.
5977 if (!function_exists('error_get_last')) {
5978 // the eval is needed to prevent PHP 5.2+ from getting a parse error!
5979 eval('
5980 function error_get_last() {
5981 return NULL;
5987 * Redirects the user to another page, after printing a notice
5989 * @param string $url The url to take the user to
5990 * @param string $message The text message to display to the user about the redirect, if any
5991 * @param string $delay How long before refreshing to the new page at $url?
5992 * @todo '&' needs to be encoded into '&amp;' for XHTML compliance,
5993 * however, this is not true for javascript. Therefore we
5994 * first decode all entities in $url (since we cannot rely on)
5995 * the correct input) and then encode for where it's needed
5996 * echo "<script type='text/javascript'>alert('Redirect $url');</script>";
5998 function redirect($url, $message='', $delay=-1) {
6000 global $CFG, $THEME;
6002 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
6003 $url = sid_process_url($url);
6006 $message = clean_text($message);
6008 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
6009 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
6010 $url = str_replace('&amp;', '&', $encodedurl);
6012 /// At developer debug level. Don't redirect if errors have been printed on screen.
6013 /// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
6014 $lasterror = error_get_last();
6015 $error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER));
6016 $errorprinted = debugging('', DEBUG_ALL) && $CFG->debugdisplay && $error;
6017 if ($errorprinted) {
6018 $message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
6021 $performanceinfo = '';
6022 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
6023 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
6024 $perf = get_performance_info();
6025 error_log("PERF: " . $perf['txt']);
6029 /// when no message and header printed yet, try to redirect
6030 if (empty($message) and !defined('HEADER_PRINTED')) {
6032 // Technically, HTTP/1.1 requires Location: header to contain
6033 // the absolute path. (In practice browsers accept relative
6034 // paths - but still, might as well do it properly.)
6035 // This code turns relative into absolute.
6036 if (!preg_match('|^[a-z]+:|', $url)) {
6037 // Get host name http://www.wherever.com
6038 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
6039 if (preg_match('|^/|', $url)) {
6040 // URLs beginning with / are relative to web server root so we just add them in
6041 $url = $hostpart.$url;
6042 } else {
6043 // URLs not beginning with / are relative to path of current script, so add that on.
6044 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
6046 // Replace all ..s
6047 while (true) {
6048 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
6049 if ($newurl == $url) {
6050 break;
6052 $url = $newurl;
6056 $delay = 0;
6057 //try header redirection first
6058 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
6059 @header('Location: '.$url);
6060 //another way for older browsers and already sent headers (eg trailing whitespace in config.php)
6061 echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
6062 echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
6063 die;
6066 if ($delay == -1) {
6067 $delay = 3; // if no delay specified wait 3 seconds
6069 if (! defined('HEADER_PRINTED')) {
6070 // this type of redirect might not be working in some browsers - such as lynx :-(
6071 print_header('', '', '', '', $errorprinted ? '' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
6072 $delay += 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
6073 } else {
6074 print_container_end_all(false, $THEME->open_header_containers);
6076 echo '<div id="redirect">';
6077 echo '<div id="message">' . $message . '</div>';
6078 echo '<div id="continue">( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
6079 echo '</div>';
6081 if (!$errorprinted) {
6083 <script type="text/javascript">
6084 //<![CDATA[
6086 function redirect() {
6087 document.location.replace('<?php echo addslashes_js($url) ?>');
6089 setTimeout("redirect()", <?php echo ($delay * 1000) ?>);
6090 //]]>
6091 </script>
6092 <?php
6095 $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
6096 print_footer('none');
6097 die;
6101 * Print a bold message in an optional color.
6103 * @param string $message The message to print out
6104 * @param string $style Optional style to display message text in
6105 * @param string $align Alignment option
6106 * @param bool $return whether to return an output string or echo now
6108 function notify($message, $style='notifyproblem', $align='center', $return=false) {
6109 if ($style == 'green') {
6110 $style = 'notifysuccess'; // backward compatible with old color system
6113 $message = clean_text($message);
6115 $output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."\n";
6117 if ($return) {
6118 return $output;
6120 echo $output;
6125 * Given an email address, this function will return an obfuscated version of it
6127 * @param string $email The email address to obfuscate
6128 * @return string
6130 function obfuscate_email($email) {
6132 $i = 0;
6133 $length = strlen($email);
6134 $obfuscated = '';
6135 while ($i < $length) {
6136 if (rand(0,2)) {
6137 $obfuscated.='%'.dechex(ord($email{$i}));
6138 } else {
6139 $obfuscated.=$email{$i};
6141 $i++;
6143 return $obfuscated;
6147 * This function takes some text and replaces about half of the characters
6148 * with HTML entity equivalents. Return string is obviously longer.
6150 * @param string $plaintext The text to be obfuscated
6151 * @return string
6153 function obfuscate_text($plaintext) {
6155 $i=0;
6156 $length = strlen($plaintext);
6157 $obfuscated='';
6158 $prev_obfuscated = false;
6159 while ($i < $length) {
6160 $c = ord($plaintext{$i});
6161 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
6162 if ($prev_obfuscated and $numerical ) {
6163 $obfuscated.='&#'.ord($plaintext{$i}).';';
6164 } else if (rand(0,2)) {
6165 $obfuscated.='&#'.ord($plaintext{$i}).';';
6166 $prev_obfuscated = true;
6167 } else {
6168 $obfuscated.=$plaintext{$i};
6169 $prev_obfuscated = false;
6171 $i++;
6173 return $obfuscated;
6177 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
6178 * to generate a fully obfuscated email link, ready to use.
6180 * @param string $email The email address to display
6181 * @param string $label The text to dispalyed as hyperlink to $email
6182 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
6183 * @return string
6185 function obfuscate_mailto($email, $label='', $dimmed=false) {
6187 if (empty($label)) {
6188 $label = $email;
6190 if ($dimmed) {
6191 $title = get_string('emaildisable');
6192 $dimmed = ' class="dimmed"';
6193 } else {
6194 $title = '';
6195 $dimmed = '';
6197 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
6198 obfuscate_text('mailto'), obfuscate_email($email),
6199 obfuscate_text($label));
6203 * Prints a single paging bar to provide access to other pages (usually in a search)
6205 * @param int $totalcount Thetotal number of entries available to be paged through
6206 * @param int $page The page you are currently viewing
6207 * @param int $perpage The number of entries that should be shown per page
6208 * @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.
6209 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
6210 * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
6211 * @param bool $nocurr do not display the current page as a link
6212 * @param bool $return whether to return an output string or echo now
6213 * @return bool or string
6215 function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
6216 $maxdisplay = 18;
6217 $output = '';
6219 if ($totalcount > $perpage) {
6220 $output .= '<div class="paging">';
6221 $output .= get_string('page') .':';
6222 if ($page > 0) {
6223 $pagenum = $page - 1;
6224 if (!is_a($baseurl, 'moodle_url')){
6225 $output .= '&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>)&nbsp;';
6226 } else {
6227 $output .= '&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>)&nbsp;';
6230 if ($perpage > 0) {
6231 $lastpage = ceil($totalcount / $perpage);
6232 } else {
6233 $lastpage = 1;
6235 if ($page > 15) {
6236 $startpage = $page - 10;
6237 if (!is_a($baseurl, 'moodle_url')){
6238 $output .= '&nbsp;<a href="'. $baseurl . $pagevar .'=0">1</a>&nbsp;...';
6239 } else {
6240 $output .= '&nbsp;<a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a>&nbsp;...';
6242 } else {
6243 $startpage = 0;
6245 $currpage = $startpage;
6246 $displaycount = $displaypage = 0;
6247 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
6248 $displaypage = $currpage+1;
6249 if ($page == $currpage && empty($nocurr)) {
6250 $output .= '&nbsp;&nbsp;'. $displaypage;
6251 } else {
6252 if (!is_a($baseurl, 'moodle_url')){
6253 $output .= '&nbsp;&nbsp;<a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
6254 } else {
6255 $output .= '&nbsp;&nbsp;<a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
6259 $displaycount++;
6260 $currpage++;
6262 if ($currpage < $lastpage) {
6263 $lastpageactual = $lastpage - 1;
6264 if (!is_a($baseurl, 'moodle_url')){
6265 $output .= '&nbsp;...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a>&nbsp;';
6266 } else {
6267 $output .= '&nbsp;...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a>&nbsp;';
6270 $pagenum = $page + 1;
6271 if ($pagenum != $displaypage) {
6272 if (!is_a($baseurl, 'moodle_url')){
6273 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
6274 } else {
6275 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
6278 $output .= '</div>';
6281 if ($return) {
6282 return $output;
6285 echo $output;
6286 return true;
6290 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
6291 * will transform it to html entities
6293 * @param string $text Text to search for nolink tag in
6294 * @return string
6296 function rebuildnolinktag($text) {
6298 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
6300 return $text;
6304 * Prints a nice side block with an optional header. The content can either
6305 * be a block of HTML or a list of text with optional icons.
6307 * @param string $heading Block $title embedded in HTML tags, for example <h2>.
6308 * @param string $content ?
6309 * @param array $list ?
6310 * @param array $icons ?
6311 * @param string $footer ?
6312 * @param array $attributes ?
6313 * @param string $title Plain text title, as embedded in the $heading.
6314 * @todo Finish documenting this function. Show example of various attributes, etc.
6316 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
6318 //Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
6319 static $block_id = 0;
6320 $block_id++;
6321 if (empty($heading)) {
6322 $skip_text = get_string('skipblock', 'access').' '.$block_id;
6324 else {
6325 $skip_text = get_string('skipa', 'access', strip_tags($title));
6327 $skip_link = '<a href="#sb-'.$block_id.'" class="skip-block">'.$skip_text.'</a>';
6328 $skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
6330 if (! empty($heading)) {
6331 echo $skip_link;
6333 //ELSE: a single link on a page "Skip block 4" is too confusing - ignore.
6335 print_side_block_start($heading, $attributes);
6337 if ($content) {
6338 echo $content;
6339 if ($footer) {
6340 echo '<div class="footer">'. $footer .'</div>';
6342 } else {
6343 if ($list) {
6344 $row = 0;
6345 //Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
6346 echo "\n<ul class='list'>\n";
6347 foreach ($list as $key => $string) {
6348 echo '<li class="r'. $row .'">';
6349 if ($icons) {
6350 echo '<div class="icon column c0">'. $icons[$key] .'</div>';
6352 echo '<div class="column c1">'. $string .'</div>';
6353 echo "</li>\n";
6354 $row = $row ? 0:1;
6356 echo "</ul>\n";
6358 if ($footer) {
6359 echo '<div class="footer">'. $footer .'</div>';
6364 print_side_block_end($attributes, $title);
6365 echo $skip_dest;
6369 * Starts a nice side block with an optional header.
6371 * @param string $heading ?
6372 * @param array $attributes ?
6373 * @todo Finish documenting this function
6375 function print_side_block_start($heading='', $attributes = array()) {
6377 global $CFG, $THEME;
6379 // If there are no special attributes, give a default CSS class
6380 if (empty($attributes) || !is_array($attributes)) {
6381 $attributes = array('class' => 'sideblock');
6383 } else if(!isset($attributes['class'])) {
6384 $attributes['class'] = 'sideblock';
6386 } else if(!strpos($attributes['class'], 'sideblock')) {
6387 $attributes['class'] .= ' sideblock';
6390 // OK, the class is surely there and in addition to anything
6391 // else, it's tagged as a sideblock
6395 // IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
6397 // If there is a cookie to hide this thing, start it hidden
6398 if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
6399 $attributes['class'] = 'hidden '.$attributes['class'];
6403 $attrtext = '';
6404 foreach ($attributes as $attr => $val) {
6405 $attrtext .= ' '.$attr.'="'.$val.'"';
6408 echo '<div '.$attrtext.'>';
6410 if (!empty($THEME->customcorners)) {
6411 echo '<div class="wrap">'."\n";
6413 if ($heading) {
6414 //Accessibility: H2 more appropriate in moodleblock.class.php: _title_html.
6415 echo '<div class="header">';
6416 if (!empty($THEME->customcorners)) {
6417 echo '<div class="bt"><div>&nbsp;</div></div>';
6418 echo '<div class="i1"><div class="i2">';
6419 echo '<div class="i3">';
6421 echo $heading;
6422 if (!empty($THEME->customcorners)) {
6423 echo '</div></div></div>';
6425 echo '</div>';
6426 } else {
6427 if (!empty($THEME->customcorners)) {
6428 echo '<div class="bt"><div>&nbsp;</div></div>';
6432 if (!empty($THEME->customcorners)) {
6433 echo '<div class="i1"><div class="i2">';
6434 echo '<div class="i3">';
6436 echo '<div class="content">';
6442 * Print table ending tags for a side block box.
6444 function print_side_block_end($attributes = array(), $title='') {
6445 global $CFG, $THEME;
6447 echo '</div>';
6449 if (!empty($THEME->customcorners)) {
6450 echo '</div></div></div><div class="bb"><div>&nbsp;</div></div></div>';
6453 echo '</div>';
6455 $strshow = addslashes_js(get_string('showblocka', 'access', strip_tags($title)));
6456 $strhide = addslashes_js(get_string('hideblocka', 'access', strip_tags($title)));
6458 // IE workaround: if I do it THIS way, it works! WTF?
6459 if (!empty($CFG->allowuserblockhiding) && isset($attributes['id'])) {
6460 echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].
6461 '","'.$strshow.'","'.$strhide."\");\n//]]>\n".'</script>';
6468 * Prints out code needed for spellchecking.
6469 * Original idea by Ludo (Marc Alier).
6471 * Opening CDATA and <script> are output by weblib::use_html_editor()
6472 * @uses $CFG
6473 * @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
6474 * @param boolean $return If false, echos the code instead of returning it
6475 * @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
6477 function print_speller_code ($usehtmleditor=false, $return=false) {
6478 global $CFG;
6479 $str = '';
6481 if(!$usehtmleditor) {
6482 $str .= 'function openSpellChecker() {'."\n";
6483 $str .= "\tvar speller = new spellChecker();\n";
6484 $str .= "\tspeller.popUpUrl = \"" . $CFG->wwwroot ."/lib/speller/spellchecker.html\";\n";
6485 $str .= "\tspeller.spellCheckScript = \"". $CFG->wwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
6486 $str .= "\tspeller.spellCheckAll();\n";
6487 $str .= '}'."\n";
6488 } else {
6489 $str .= "function spellClickHandler(editor, buttonId) {\n";
6490 $str .= "\teditor._textArea.value = editor.getHTML();\n";
6491 $str .= "\tvar speller = new spellChecker( editor._textArea );\n";
6492 $str .= "\tspeller.popUpUrl = \"" . $CFG->wwwroot ."/lib/speller/spellchecker.html\";\n";
6493 $str .= "\tspeller.spellCheckScript = \"". $CFG->wwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
6494 $str .= "\tspeller._moogle_edit=1;\n";
6495 $str .= "\tspeller._editor=editor;\n";
6496 $str .= "\tspeller.openChecker();\n";
6497 $str .= '}'."\n";
6500 if ($return) {
6501 return $str;
6503 echo $str;
6507 * Print button for spellchecking when editor is disabled
6509 function print_speller_button () {
6510 echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
6514 function page_id_and_class(&$getid, &$getclass) {
6515 // Create class and id for this page
6516 global $CFG, $ME;
6518 static $class = NULL;
6519 static $id = NULL;
6521 if (empty($CFG->pagepath)) {
6522 $CFG->pagepath = $ME;
6525 if (empty($class) || empty($id)) {
6526 $path = str_replace($CFG->httpswwwroot.'/', '', $CFG->pagepath); //Because the page could be HTTPSPAGEREQUIRED
6527 $path = str_replace('.php', '', $path);
6528 if (substr($path, -1) == '/') {
6529 $path .= 'index';
6531 if (empty($path) || $path == 'index') {
6532 $id = 'site-index';
6533 $class = 'course';
6534 } else if (substr($path, 0, 5) == 'admin') {
6535 $id = str_replace('/', '-', $path);
6536 $class = 'admin';
6537 } else {
6538 $id = str_replace('/', '-', $path);
6539 $class = explode('-', $id);
6540 array_pop($class);
6541 $class = implode('-', $class);
6545 $getid = $id;
6546 $getclass = $class;
6550 * Prints a maintenance message from /maintenance.html
6552 function print_maintenance_message () {
6553 global $CFG, $SITE;
6555 print_header(strip_tags($SITE->fullname), $SITE->fullname, 'home');
6556 print_simple_box_start('center');
6557 print_heading(get_string('sitemaintenance', 'admin'));
6558 @include($CFG->dataroot.'/1/maintenance.html');
6559 print_simple_box_end();
6560 print_footer();
6564 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
6566 function adjust_allowed_tags() {
6568 global $CFG, $ALLOWED_TAGS;
6570 if (!empty($CFG->allowobjectembed)) {
6571 $ALLOWED_TAGS .= '<embed><object>';
6575 /// Some code to print tabs
6577 /// A class for tabs
6578 class tabobject {
6579 var $id;
6580 var $link;
6581 var $text;
6582 var $linkedwhenselected;
6584 /// A constructor just because I like constructors
6585 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
6586 $this->id = $id;
6587 $this->link = $link;
6588 $this->text = $text;
6589 $this->title = $title ? $title : $text;
6590 $this->linkedwhenselected = $linkedwhenselected;
6597 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
6599 * @param array $tabrows An array of rows where each row is an array of tab objects
6600 * @param string $selected The id of the selected tab (whatever row it's on)
6601 * @param array $inactive An array of ids of inactive tabs that are not selectable.
6602 * @param array $activated An array of ids of other tabs that are currently activated
6604 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
6605 global $CFG;
6607 /// $inactive must be an array
6608 if (!is_array($inactive)) {
6609 $inactive = array();
6612 /// $activated must be an array
6613 if (!is_array($activated)) {
6614 $activated = array();
6617 /// Convert the tab rows into a tree that's easier to process
6618 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
6619 return false;
6622 /// Print out the current tree of tabs (this function is recursive)
6624 $output = convert_tree_to_html($tree);
6626 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
6628 /// We're done!
6630 if ($return) {
6631 return $output;
6633 echo $output;
6637 function convert_tree_to_html($tree, $row=0) {
6639 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
6641 $first = true;
6642 $count = count($tree);
6644 foreach ($tree as $tab) {
6645 $count--; // countdown to zero
6647 $liclass = '';
6649 if ($first && ($count == 0)) { // Just one in the row
6650 $liclass = 'first last';
6651 $first = false;
6652 } else if ($first) {
6653 $liclass = 'first';
6654 $first = false;
6655 } else if ($count == 0) {
6656 $liclass = 'last';
6659 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
6660 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
6663 if ($tab->inactive || $tab->active || $tab->selected) {
6664 if ($tab->selected) {
6665 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
6666 } else if ($tab->active) {
6667 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
6671 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
6673 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
6674 // The a tag is used for styling
6675 $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
6676 } else {
6677 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
6680 if (!empty($tab->subtree)) {
6681 $str .= convert_tree_to_html($tab->subtree, $row+1);
6682 } else if ($tab->selected) {
6683 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
6686 $str .= ' </li>'."\n";
6688 $str .= '</ul>'."\n";
6690 return $str;
6694 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
6696 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
6698 $tabrows = array_reverse($tabrows);
6700 $subtree = array();
6702 foreach ($tabrows as $row) {
6703 $tree = array();
6705 foreach ($row as $tab) {
6706 $tab->inactive = in_array((string)$tab->id, $inactive);
6707 $tab->active = in_array((string)$tab->id, $activated);
6708 $tab->selected = (string)$tab->id == $selected;
6710 if ($tab->active || $tab->selected) {
6711 if ($subtree) {
6712 $tab->subtree = $subtree;
6715 $tree[] = $tab;
6717 $subtree = $tree;
6720 return $subtree;
6725 * Returns a string containing a link to the user documentation for the current
6726 * page. Also contains an icon by default. Shown to teachers and admin only.
6728 * @param string $text The text to be displayed for the link
6729 * @param string $iconpath The path to the icon to be displayed
6731 function page_doc_link($text='', $iconpath='') {
6732 global $ME, $COURSE, $CFG;
6734 if (empty($CFG->docroot) or empty($CFG->rolesactive)) {
6735 return '';
6738 if (empty($COURSE->id)) {
6739 $context = get_context_instance(CONTEXT_SYSTEM);
6740 } else {
6741 $context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
6744 if (!has_capability('moodle/site:doclinks', $context)) {
6745 return '';
6748 if (empty($CFG->pagepath)) {
6749 $CFG->pagepath = $ME;
6752 $path = str_replace($CFG->httpswwwroot.'/','', $CFG->pagepath); // Because the page could be HTTPSPAGEREQUIRED
6753 $path = str_replace('.php', '', $path);
6755 if (empty($path)) { // Not for home page
6756 return '';
6758 return doc_link($path, $text, $iconpath);
6762 * Returns a string containing a link to the user documentation.
6763 * Also contains an icon by default. Shown to teachers and admin only.
6765 * @param string $path The page link after doc root and language, no
6766 * leading slash.
6767 * @param string $text The text to be displayed for the link
6768 * @param string $iconpath The path to the icon to be displayed
6770 function doc_link($path='', $text='', $iconpath='') {
6771 global $CFG;
6773 if (empty($CFG->docroot)) {
6774 return '';
6777 $target = '';
6778 if (!empty($CFG->doctonewwindow)) {
6779 $target = ' target="_blank"';
6782 $lang = str_replace('_utf8', '', current_language());
6784 $str = '<a href="' .$CFG->docroot. '/' .$lang. '/' .$path. '"' .$target. '>';
6786 if (empty($iconpath)) {
6787 $iconpath = $CFG->httpswwwroot . '/pix/docs.gif';
6790 // alt left blank intentionally to prevent repetition in screenreaders
6791 $str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
6793 return $str;
6798 * Returns true if the current site debugging settings are equal or above specified level.
6799 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
6800 * routing of notices is controlled by $CFG->debugdisplay
6801 * eg use like this:
6803 * 1) debugging('a normal debug notice');
6804 * 2) debugging('something really picky', DEBUG_ALL);
6805 * 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
6806 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
6808 * In code blocks controlled by debugging() (such as example 4)
6809 * any output should be routed via debugging() itself, or the lower-level
6810 * trigger_error() or error_log(). Using echo or print will break XHTML
6811 * JS and HTTP headers.
6814 * @param string $message a message to print
6815 * @param int $level the level at which this debugging statement should show
6816 * @return bool
6818 function debugging($message='', $level=DEBUG_NORMAL) {
6820 global $CFG;
6822 if (empty($CFG->debug)) {
6823 return false;
6826 if ($CFG->debug >= $level) {
6827 if ($message) {
6828 $callers = debug_backtrace();
6829 $from = '<ul style="text-align: left">';
6830 foreach ($callers as $caller) {
6831 if (!isset($caller['line'])) {
6832 $caller['line'] = '?'; // probably call_user_func()
6834 if (!isset($caller['file'])) {
6835 $caller['file'] = $CFG->dirroot.'/unknownfile'; // probably call_user_func()
6837 $from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
6838 if (isset($caller['function'])) {
6839 $from .= ': call to ';
6840 if (isset($caller['class'])) {
6841 $from .= $caller['class'] . $caller['type'];
6843 $from .= $caller['function'] . '()';
6845 $from .= '</li>';
6847 $from .= '</ul>';
6848 if (!isset($CFG->debugdisplay)) {
6849 $CFG->debugdisplay = ini_get('display_errors');
6851 if ($CFG->debugdisplay) {
6852 if (!defined('DEBUGGING_PRINTED')) {
6853 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
6855 notify($message . $from, 'notifytiny');
6856 } else {
6857 trigger_error($message . $from, E_USER_NOTICE);
6860 return true;
6862 return false;
6866 * Disable debug messages from debugging(), while keeping PHP error reporting level as is.
6868 function disable_debugging() {
6869 global $CFG;
6870 $CFG->debug = $CFG->debug | 0x80000000; // switch the sign bit in integer number ;-)
6875 * Returns string to add a frame attribute, if required
6877 function frametarget() {
6878 global $CFG;
6880 if (empty($CFG->framename) or ($CFG->framename == '_top')) {
6881 return '';
6882 } else {
6883 return ' target="'.$CFG->framename.'" ';
6888 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
6889 * pages that use bits from many different files in very confusing ways (e.g. blocks).
6890 * @usage print_location_comment(__FILE__, __LINE__);
6891 * @param string $file
6892 * @param integer $line
6893 * @param boolean $return Whether to return or print the comment
6894 * @return mixed Void unless true given as third parameter
6896 function print_location_comment($file, $line, $return = false)
6898 if ($return) {
6899 return "<!-- $file at line $line -->\n";
6900 } else {
6901 echo "<!-- $file at line $line -->\n";
6907 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
6908 * provide this function with the language strings for sortasc and sortdesc.
6909 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
6910 * @param string $direction 'up' or 'down'
6911 * @param string $strsort The language string used for the alt attribute of this image
6912 * @param bool $return Whether to print directly or return the html string
6913 * @return string HTML for the image
6915 * TODO See if this isn't already defined somewhere. If not, move this to weblib
6917 function print_arrow($direction='up', $strsort=null, $return=false) {
6918 global $CFG;
6920 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
6921 return null;
6924 $return = null;
6926 switch ($direction) {
6927 case 'up':
6928 $sortdir = 'asc';
6929 break;
6930 case 'down':
6931 $sortdir = 'desc';
6932 break;
6933 case 'move':
6934 $sortdir = 'asc';
6935 break;
6936 default:
6937 $sortdir = null;
6938 break;
6941 // Prepare language string
6942 $strsort = '';
6943 if (empty($strsort) && !empty($sortdir)) {
6944 $strsort = get_string('sort' . $sortdir, 'grades');
6947 $return = ' <img src="'.$CFG->pixpath.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
6949 if ($return) {
6950 return $return;
6951 } else {
6952 echo $return;
6957 * Returns boolean true if the current language is right-to-left (Hebrew, Arabic etc)
6960 function right_to_left() {
6961 static $result;
6963 if (isset($result)) {
6964 return $result;
6966 return $result = (get_string('thisdirection') == 'rtl');
6971 * Returns swapped left<=>right if in RTL environment.
6972 * part of RTL support
6974 * @param string $align align to check
6975 * @return string
6977 function fix_align_rtl($align) {
6978 if (!right_to_left()) {
6979 return $align;
6981 if ($align=='left') { return 'right'; }
6982 if ($align=='right') { return 'left'; }
6983 return $align;
6988 * Returns true if the page is displayed in a popup window.
6989 * Gets the information from the URL parameter inpopup.
6991 * @return boolean
6993 * TODO Use a central function to create the popup calls allover Moodle and
6994 * TODO In the moment only works with resources and probably questions.
6996 function is_in_popup() {
6997 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
6999 return ($inpopup);
7003 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: