MDL-26502 check browser - fix for Symbian (backported)
[moodle.git] / lib / weblib.php
blobdfd570402fe040e009163c397300960428f4f063
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><thead><tfoot><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', 'font-family',
104 'border', 'border-bottom', 'border-left', 'border-top', 'border-right', 'margin', 'margin-bottom', 'margin-left', 'margin-top', 'margin-right',
105 'padding', 'padding-bottom', 'padding-left', 'padding-top', 'padding-right', 'vertical-align',
106 'background', 'background-color', 'text-decoration'); // CSS as well to get through kses
109 /// Functions
112 * Add quotes to HTML characters
114 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
115 * This function is very similar to {@link p()}
117 * @param string $var the string potentially containing HTML characters
118 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
119 * true should be used to print data from forms and false for data from DB.
120 * @return string
122 function s($var, $strip=false) {
124 if ($var === '0' or $var === false or $var === 0) {
125 return '0';
128 if ($strip) {
129 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars(stripslashes_safe($var)));
130 } else {
131 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars($var));
136 * Add quotes to HTML characters
138 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
139 * This function is very similar to {@link s()}
141 * @param string $var the string potentially containing HTML characters
142 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
143 * true should be used to print data from forms and false for data from DB.
144 * @return string
146 function p($var, $strip=false) {
147 echo s($var, $strip);
151 * Does proper javascript quoting.
152 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
154 * @since 1.8 - 22/02/2007
155 * @param mixed value
156 * @return mixed quoted result
158 function addslashes_js($var) {
159 if (is_string($var)) {
160 $var = str_replace('\\', '\\\\', $var);
161 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
162 $var = str_replace('</', '<\/', $var); // XHTML compliance
163 } else if (is_array($var)) {
164 $var = array_map('addslashes_js', $var);
165 } else if (is_object($var)) {
166 $a = get_object_vars($var);
167 foreach ($a as $key=>$value) {
168 $a[$key] = addslashes_js($value);
170 $var = (object)$a;
172 return $var;
176 * Remove query string from url
178 * Takes in a URL and returns it without the querystring portion
180 * @param string $url the url which may have a query string attached
181 * @return string
183 function strip_querystring($url) {
185 if ($commapos = strpos($url, '?')) {
186 return substr($url, 0, $commapos);
187 } else {
188 return $url;
193 * Returns the URL of the HTTP_REFERER, less the querystring portion if required
194 * @param boolean $stripquery if true, also removes the query part of the url.
195 * @return string
197 function get_referer($stripquery=true) {
198 if (isset($_SERVER['HTTP_REFERER'])) {
199 if ($stripquery) {
200 return strip_querystring($_SERVER['HTTP_REFERER']);
201 } else {
202 return $_SERVER['HTTP_REFERER'];
204 } else {
205 return '';
211 * Returns the name of the current script, WITH the querystring portion.
212 * this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
213 * return different things depending on a lot of things like your OS, Web
214 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
215 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
217 * @return string
219 function me() {
221 if (!empty($_SERVER['REQUEST_URI'])) {
222 return $_SERVER['REQUEST_URI'];
224 } else if (!empty($_SERVER['PHP_SELF'])) {
225 if (!empty($_SERVER['QUERY_STRING'])) {
226 return $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
228 return $_SERVER['PHP_SELF'];
230 } else if (!empty($_SERVER['SCRIPT_NAME'])) {
231 if (!empty($_SERVER['QUERY_STRING'])) {
232 return $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
234 return $_SERVER['SCRIPT_NAME'];
236 } else if (!empty($_SERVER['URL'])) { // May help IIS (not well tested)
237 if (!empty($_SERVER['QUERY_STRING'])) {
238 return $_SERVER['URL'] .'?'. $_SERVER['QUERY_STRING'];
240 return $_SERVER['URL'];
242 } else {
243 notify('Warning: Could not find any of these web server variables: $REQUEST_URI, $PHP_SELF, $SCRIPT_NAME or $URL');
244 return false;
249 * Like {@link me()} but returns a full URL
250 * @see me()
251 * @return string
253 function qualified_me() {
255 global $CFG;
257 if (!empty($CFG->wwwroot)) {
258 $url = parse_url($CFG->wwwroot);
261 if (!empty($url['host'])) {
262 $hostname = $url['host'];
263 } else if (!empty($_SERVER['SERVER_NAME'])) {
264 $hostname = $_SERVER['SERVER_NAME'];
265 } else if (!empty($_ENV['SERVER_NAME'])) {
266 $hostname = $_ENV['SERVER_NAME'];
267 } else if (!empty($_SERVER['HTTP_HOST'])) {
268 $hostname = $_SERVER['HTTP_HOST'];
269 } else if (!empty($_ENV['HTTP_HOST'])) {
270 $hostname = $_ENV['HTTP_HOST'];
271 } else {
272 notify('Warning: could not find the name of this server!');
273 return false;
276 if (!empty($url['port'])) {
277 $hostname .= ':'.$url['port'];
278 } else if (!empty($_SERVER['SERVER_PORT'])) {
279 if ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
280 $hostname .= ':'.$_SERVER['SERVER_PORT'];
284 // TODO, this does not work in the situation described in MDL-11061, but
285 // I don't know how to fix it. Possibly believe $CFG->wwwroot ahead of what
286 // the server reports.
287 if (isset($_SERVER['HTTPS'])) {
288 $protocol = ($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
289 } else if (isset($_SERVER['SERVER_PORT'])) { # Apache2 does not export $_SERVER['HTTPS']
290 $protocol = ($_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
291 } else {
292 $protocol = 'http://';
295 $url_prefix = $protocol.$hostname;
296 return $url_prefix . me();
301 * Class for creating and manipulating urls.
303 * See short write up here http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url
305 class moodle_url {
306 var $scheme = '';// e.g. http
307 var $host = '';
308 var $port = '';
309 var $user = '';
310 var $pass = '';
311 var $path = '';
312 var $fragment = '';
313 var $params = array(); //associative array of query string params
316 * Pass no arguments to create a url that refers to this page. Use empty string to create empty url.
318 * @param string $url url default null means use this page url with no query string
319 * empty string means empty url.
320 * if you pass any other type of url it will be parsed into it's bits, including query string
321 * @param array $params these params override anything in the query string where params have the same name.
323 function moodle_url($url = null, $params = array()){
324 global $FULLME;
325 if ($url !== ''){
326 if ($url === null){
327 $url = strip_querystring($FULLME);
329 $parts = parse_url($url);
330 if ($parts === FALSE){
331 error('invalidurl');
333 if (isset($parts['query'])){
334 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
336 unset($parts['query']);
337 foreach ($parts as $key => $value){
338 $this->$key = $value;
340 $this->params($params);
345 * Add an array of params to the params for this page.
347 * The added params override existing ones if they have the same name.
349 * @param array $params Defaults to null. If null then return value of param 'name'.
350 * @return array Array of Params for url.
352 function params($params = null) {
353 if (!is_null($params)) {
354 return $this->params = $params + $this->params;
355 } else {
356 return $this->params;
361 * Remove all params if no arguments passed. Or else remove param $arg1, $arg2, etc.
363 * @param string $arg1
364 * @param string $arg2
365 * @param string $arg3
367 function remove_params(){
368 if ($thisargs = func_get_args()){
369 foreach ($thisargs as $arg){
370 if (isset($this->params[$arg])){
371 unset($this->params[$arg]);
374 } else { // no args
375 $this->params = array();
380 * Add a param to the params for this page. The added param overrides existing one if they
381 * have the same name.
383 * @param string $paramname name
384 * @param string $param value
386 function param($paramname, $param){
387 $this->params = array($paramname => $param) + $this->params;
391 function get_query_string($overrideparams = array()){
392 $arr = array();
393 $params = $overrideparams + $this->params;
394 foreach ($params as $key => $val){
395 $arr[] = urlencode($key)."=".urlencode($val);
397 return implode($arr, "&amp;");
400 * Outputs params as hidden form elements.
402 * @param array $exclude params to ignore
403 * @param integer $indent indentation
404 * @param array $overrideparams params to add to the output params, these
405 * override existing ones with the same name.
406 * @return string html for form elements.
408 function hidden_params_out($exclude = array(), $indent = 0, $overrideparams=array()){
409 $tabindent = str_repeat("\t", $indent);
410 $str = '';
411 $params = $overrideparams + $this->params;
412 foreach ($params as $key => $val){
413 if (FALSE === array_search($key, $exclude)) {
414 $val = s($val);
415 $str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
418 return $str;
421 * Output url
423 * @param boolean $noquerystring whether to output page params as a query string in the url.
424 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
425 * @return string url
427 function out($noquerystring = false, $overrideparams = array()) {
428 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
429 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
430 $uri .= $this->host ? $this->host : '';
431 $uri .= $this->port ? ':'.$this->port : '';
432 $uri .= $this->path ? $this->path : '';
433 if (!$noquerystring){
434 $uri .= (count($this->params)||count($overrideparams)) ? '?'.$this->get_query_string($overrideparams) : '';
436 $uri .= $this->fragment ? '#'.$this->fragment : '';
437 return $uri;
440 * Output action url with sesskey
442 * @param boolean $noquerystring whether to output page params as a query string in the url.
443 * @return string url
445 function out_action($overrideparams = array()) {
446 $overrideparams = array('sesskey'=> sesskey()) + $overrideparams;
447 return $this->out(false, $overrideparams);
452 * Determine if there is data waiting to be processed from a form
454 * Used on most forms in Moodle to check for data
455 * Returns the data as an object, if it's found.
456 * This object can be used in foreach loops without
457 * casting because it's cast to (array) automatically
459 * Checks that submitted POST data exists and returns it as object.
461 * @param string $url not used anymore
462 * @return mixed false or object
464 function data_submitted($url='') {
466 if (empty($_POST)) {
467 return false;
468 } else {
469 return (object)$_POST;
474 * Moodle replacement for php stripslashes() function,
475 * works also for objects and arrays.
477 * The standard php stripslashes() removes ALL backslashes
478 * even from strings - so C:\temp becomes C:temp - this isn't good.
479 * This function should work as a fairly safe replacement
480 * to be called on quoted AND unquoted strings (to be sure)
482 * @param mixed something to remove unsafe slashes from
483 * @return mixed
485 function stripslashes_safe($mixed) {
486 // there is no need to remove slashes from int, float and bool types
487 if (empty($mixed)) {
488 //nothing to do...
489 } else if (is_string($mixed)) {
490 if (ini_get_bool('magic_quotes_sybase')) { //only unescape single quotes
491 $mixed = str_replace("''", "'", $mixed);
492 } else { //the rest, simple and double quotes and backslashes
493 $mixed = str_replace("\\'", "'", $mixed);
494 $mixed = str_replace('\\"', '"', $mixed);
495 $mixed = str_replace('\\\\', '\\', $mixed);
497 } else if (is_array($mixed)) {
498 foreach ($mixed as $key => $value) {
499 $mixed[$key] = stripslashes_safe($value);
501 } else if (is_object($mixed)) {
502 $vars = get_object_vars($mixed);
503 foreach ($vars as $key => $value) {
504 $mixed->$key = stripslashes_safe($value);
508 return $mixed;
512 * Recursive implementation of stripslashes()
514 * This function will allow you to strip the slashes from a variable.
515 * If the variable is an array or object, slashes will be stripped
516 * from the items (or properties) it contains, even if they are arrays
517 * or objects themselves.
519 * @param mixed the variable to remove slashes from
520 * @return mixed
522 function stripslashes_recursive($var) {
523 if (is_object($var)) {
524 $new_var = new object();
525 $properties = get_object_vars($var);
526 foreach($properties as $property => $value) {
527 $new_var->$property = stripslashes_recursive($value);
530 } else if(is_array($var)) {
531 $new_var = array();
532 foreach($var as $property => $value) {
533 $new_var[$property] = stripslashes_recursive($value);
536 } else if(is_string($var)) {
537 $new_var = stripslashes($var);
539 } else {
540 $new_var = $var;
543 return $new_var;
547 * Recursive implementation of addslashes()
549 * This function will allow you to add the slashes from a variable.
550 * If the variable is an array or object, slashes will be added
551 * to the items (or properties) it contains, even if they are arrays
552 * or objects themselves.
554 * @param mixed the variable to add slashes from
555 * @return mixed
557 function addslashes_recursive($var) {
558 if (is_object($var)) {
559 $new_var = new object();
560 $properties = get_object_vars($var);
561 foreach($properties as $property => $value) {
562 $new_var->$property = addslashes_recursive($value);
565 } else if (is_array($var)) {
566 $new_var = array();
567 foreach($var as $property => $value) {
568 $new_var[$property] = addslashes_recursive($value);
571 } else if (is_string($var)) {
572 $new_var = addslashes($var);
574 } else { // nulls, integers, etc.
575 $new_var = $var;
578 return $new_var;
582 * Given some normal text this function will break up any
583 * long words to a given size by inserting the given character
585 * It's multibyte savvy and doesn't change anything inside html tags.
587 * @param string $string the string to be modified
588 * @param int $maxsize maximum length of the string to be returned
589 * @param string $cutchar the string used to represent word breaks
590 * @return string
592 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
594 /// Loading the textlib singleton instance. We are going to need it.
595 $textlib = textlib_get_instance();
597 /// First of all, save all the tags inside the text to skip them
598 $tags = array();
599 filter_save_tags($string,$tags);
601 /// Process the string adding the cut when necessary
602 $output = '';
603 $length = $textlib->strlen($string);
604 $wordlength = 0;
606 for ($i=0; $i<$length; $i++) {
607 $char = $textlib->substr($string, $i, 1);
608 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
609 $wordlength = 0;
610 } else {
611 $wordlength++;
612 if ($wordlength > $maxsize) {
613 $output .= $cutchar;
614 $wordlength = 0;
617 $output .= $char;
620 /// Finally load the tags back again
621 if (!empty($tags)) {
622 $output = str_replace(array_keys($tags), $tags, $output);
625 return $output;
629 * This does a search and replace, ignoring case
630 * This function is only used for versions of PHP older than version 5
631 * which do not have a native version of this function.
632 * Taken from the PHP manual, by bradhuizenga @ softhome.net
634 * @param string $find the string to search for
635 * @param string $replace the string to replace $find with
636 * @param string $string the string to search through
637 * return string
639 if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
640 function str_ireplace($find, $replace, $string) {
642 if (!is_array($find)) {
643 $find = array($find);
646 if(!is_array($replace)) {
647 if (!is_array($find)) {
648 $replace = array($replace);
649 } else {
650 // this will duplicate the string into an array the size of $find
651 $c = count($find);
652 $rString = $replace;
653 unset($replace);
654 for ($i = 0; $i < $c; $i++) {
655 $replace[$i] = $rString;
660 foreach ($find as $fKey => $fItem) {
661 $between = explode(strtolower($fItem),strtolower($string));
662 $pos = 0;
663 foreach($between as $bKey => $bItem) {
664 $between[$bKey] = substr($string,$pos,strlen($bItem));
665 $pos += strlen($bItem) + strlen($fItem);
667 $string = implode($replace[$fKey],$between);
669 return ($string);
674 * Locate the position of a string in another string
676 * This function is only used for versions of PHP older than version 5
677 * which do not have a native version of this function.
678 * Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
680 * @param string $haystack The string to be searched
681 * @param string $needle The string to search for
682 * @param int $offset The position in $haystack where the search should begin.
684 if (!function_exists('stripos')) { /// Only exists in PHP 5
685 function stripos($haystack, $needle, $offset=0) {
687 return strpos(strtoupper($haystack), strtoupper($needle), $offset);
692 * This function will print a button/link/etc. form element
693 * that will work on both Javascript and non-javascript browsers.
694 * Relies on the Javascript function openpopup in javascript.php
696 * All parameters default to null, only $type and $url are mandatory.
698 * $url must be relative to home page eg /mod/survey/stuff.php
699 * @param string $url Web link relative to home page
700 * @param string $name Name to be assigned to the popup window (this is used by
701 * client-side scripts to "talk" to the popup window)
702 * @param string $linkname Text to be displayed as web link
703 * @param int $height Height to assign to popup window
704 * @param int $width Height to assign to popup window
705 * @param string $title Text to be displayed as popup page title
706 * @param string $options List of additional options for popup window
707 * @param string $return If true, return as a string, otherwise print
708 * @param string $id id added to the element
709 * @param string $class class added to the element
710 * @return string
711 * @uses $CFG
713 function element_to_popup_window ($type=null, $url=null, $name=null, $linkname=null,
714 $height=400, $width=500, $title=null,
715 $options=null, $return=false, $id=null, $class=null) {
717 if (is_null($url)) {
718 debugging('You must give the url to display in the popup. URL is missing - can\'t create popup window.', DEBUG_DEVELOPER);
721 global $CFG;
723 if ($options == 'none') { // 'none' is legacy, should be removed in v2.0
724 $options = null;
727 // add some sane default options for popup windows
728 if (!$options) {
729 $options = 'menubar=0,location=0,scrollbars,resizable';
731 if ($width) {
732 $options .= ',width='. $width;
734 if ($height) {
735 $options .= ',height='. $height;
737 if ($id) {
738 $id = ' id="'.$id.'" ';
740 if ($class) {
741 $class = ' class="'.$class.'" ';
743 if ($name) {
744 $_name = $name;
745 if (($name = preg_replace("/\s/", '_', $name)) != $_name) {
746 debugging('The $name of a popup window shouldn\'t contain spaces - string modified. '. $_name .' changed to '. $name, DEBUG_DEVELOPER);
748 } else {
749 $name = 'popup';
752 // get some default string, using the localized version of legacy defaults
753 if (is_null($linkname) || $linkname === '') {
754 $linkname = get_string('clickhere');
756 if (!$title) {
757 $title = get_string('popupwindowname');
760 $fullscreen = 0; // must be passed to openpopup
761 $element = '';
763 switch ($type) {
764 case 'button' :
765 $element = '<input type="button" name="'. $name .'" title="'. $title .'" value="'. $linkname .'" '. $id . $class .
766 "onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
767 break;
768 case 'link' :
769 // some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
770 if (!(strpos($url,$CFG->wwwroot) === false)) {
771 $url = substr($url, strlen($CFG->wwwroot));
773 $element = '<a title="'. s(strip_tags($title)) .'" href="'. $CFG->wwwroot . $url .'" '.
774 "$CFG->frametarget onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
775 break;
776 default :
777 error('Undefined element - can\'t create popup window.');
778 break;
781 if ($return) {
782 return $element;
783 } else {
784 echo $element;
789 * Creates and displays (or returns) a link to a popup window, using element_to_popup_window function.
791 * @return string html code to display a link to a popup window.
792 * @see element_to_popup_window()
794 function link_to_popup_window ($url, $name=null, $linkname=null,
795 $height=400, $width=500, $title=null,
796 $options=null, $return=false) {
798 return element_to_popup_window('link', $url, $name, $linkname, $height, $width, $title, $options, $return, null, null);
802 * Creates and displays (or returns) a buttons to a popup window, using element_to_popup_window function.
804 * @return string html code to display a button to a popup window.
805 * @see element_to_popup_window()
807 function button_to_popup_window ($url, $name=null, $linkname=null,
808 $height=400, $width=500, $title=null, $options=null, $return=false,
809 $id=null, $class=null) {
811 return element_to_popup_window('button', $url, $name, $linkname, $height, $width, $title, $options, $return, $id, $class);
816 * Prints a simple button to close a window
817 * @param string $name name of the window to close
818 * @param boolean $return whether this function should return a string or output it
819 * @return string if $return is true, nothing otherwise
821 function close_window_button($name='closewindow', $return=false) {
822 global $CFG;
824 $output = '';
826 $output .= '<div class="closewindow">' . "\n";
827 $output .= '<form action="#"><div>';
828 $output .= '<input type="button" onclick="self.close();" value="'.get_string($name).'" />';
829 $output .= '</div></form>';
830 $output .= '</div>' . "\n";
832 if ($return) {
833 return $output;
834 } else {
835 echo $output;
840 * Try and close the current window immediately using Javascript
841 * @param int $delay the delay in seconds before closing the window
843 function close_window($delay=0) {
845 <script type="text/javascript">
846 //<![CDATA[
847 function close_this_window() {
848 self.close();
850 setTimeout("close_this_window()", <?php echo $delay * 1000 ?>);
851 //]]>
852 </script>
853 <noscript><center>
854 <?php print_string('pleaseclose') ?>
855 </center></noscript>
856 <?php
857 die;
861 * Given an array of values, output the HTML for a select element with those options.
862 * Normally, you only need to use the first few parameters.
864 * @param array $options The options to offer. An array of the form
865 * $options[{value}] = {text displayed for that option};
866 * @param string $name the name of this form control, as in &lt;select name="..." ...
867 * @param string $selected the option to select initially, default none.
868 * @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
869 * Set this to '' if you don't want a 'nothing is selected' option.
870 * @param string $script in not '', then this is added to the &lt;select> element as an onchange handler.
871 * @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
872 * @param boolean $return if false (the default) the the output is printed directly, If true, the
873 * generated HTML is returned as a string.
874 * @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
875 * @param int $tabindex if give, sets the tabindex attribute on the &lt;select> element. Default none.
876 * @param string $id value to use for the id attribute of the &lt;select> element. If none is given,
877 * then a suitable one is constructed.
878 * @param mixed $listbox if false, display as a dropdown menu. If true, display as a list box.
879 * By default, the list box will have a number of rows equal to min(10, count($options)), but if
880 * $listbox is an integer, that number is used for size instead.
881 * @param boolean $multiple if true, enable multiple selections, else only 1 item can be selected. Used
882 * when $listbox display is enabled
883 * @param string $class value to use for the class attribute of the &lt;select> element. If none is given,
884 * then a suitable one is constructed.
886 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
887 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0,
888 $id='', $listbox=false, $multiple=false, $class='') {
890 if ($nothing == 'choose') {
891 $nothing = get_string('choose') .'...';
894 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
895 if ($disabled) {
896 $attributes .= ' disabled="disabled"';
899 if ($tabindex) {
900 $attributes .= ' tabindex="'.$tabindex.'"';
903 if ($id ==='') {
904 $id = 'menu'.$name;
905 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
906 $id = str_replace('[', '', $id);
907 $id = str_replace(']', '', $id);
910 if ($class ==='') {
911 $class = 'menu'.$name;
912 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
913 $class = str_replace('[', '', $class);
914 $class = str_replace(']', '', $class);
916 $class = 'select ' . $class; /// Add 'select' selector always
918 if ($listbox) {
919 if (is_integer($listbox)) {
920 $size = $listbox;
921 } else {
922 $numchoices = count($options);
923 if ($nothing) {
924 $numchoices += 1;
926 $size = min(10, $numchoices);
928 $attributes .= ' size="' . $size . '"';
929 if ($multiple) {
930 $attributes .= ' multiple="multiple"';
934 $output = '<select id="'. $id .'" class="'. $class .'" name="'. $name .'" '. $attributes .'>' . "\n";
935 if ($nothing) {
936 $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
937 if ($nothingvalue === $selected) {
938 $output .= ' selected="selected"';
940 $output .= '>'. $nothing .'</option>' . "\n";
943 if (!empty($options)) {
944 foreach ($options as $value => $label) {
945 $output .= ' <option value="'. s($value) .'"';
946 if ((string)$value == (string)$selected ||
947 (is_array($selected) && in_array($value, $selected))) {
948 $output .= ' selected="selected"';
950 if ($label === '') {
951 $output .= '>'. $value .'</option>' . "\n";
952 } else {
953 $output .= '>'. $label .'</option>' . "\n";
957 $output .= '</select>' . "\n";
959 if ($return) {
960 return $output;
961 } else {
962 echo $output;
967 * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
968 * Other options like choose_from_menu.
969 * @param string $name
970 * @param string $selected
971 * @param string $string (defaults to '')
972 * @param boolean $return whether this function should return a string or output it (defaults to false)
973 * @param boolean $disabled (defaults to false)
974 * @param int $tabindex
976 function choose_from_menu_yesno($name, $selected, $script = '',
977 $return = false, $disabled = false, $tabindex = 0) {
978 return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
979 $selected, '', $script, '0', $return, $disabled, $tabindex);
983 * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
984 * including option headings with the first level.
986 function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
987 $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
989 if ($nothing == 'choose') {
990 $nothing = get_string('choose') .'...';
993 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
994 if ($disabled) {
995 $attributes .= ' disabled="disabled"';
998 if ($tabindex) {
999 $attributes .= ' tabindex="'.$tabindex.'"';
1002 $output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
1003 if ($nothing) {
1004 $output .= ' <option value="'. $nothingvalue .'"'. "\n";
1005 if ($nothingvalue === $selected) {
1006 $output .= ' selected="selected"';
1008 $output .= '>'. $nothing .'</option>' . "\n";
1010 if (!empty($options)) {
1011 foreach ($options as $section => $values) {
1012 $output .= ' <optgroup label="'. s(strip_tags(format_string($section))) .'">'."\n";
1013 foreach ($values as $value => $label) {
1014 $output .= ' <option value="'. format_string($value) .'"';
1015 if ((string)$value == (string)$selected) {
1016 $output .= ' selected="selected"';
1018 if ($label === '') {
1019 $output .= '>'. $value .'</option>' . "\n";
1020 } else {
1021 $output .= '>'. $label .'</option>' . "\n";
1024 $output .= ' </optgroup>'."\n";
1027 $output .= '</select>' . "\n";
1029 if ($return) {
1030 return $output;
1031 } else {
1032 echo $output;
1038 * Given an array of values, creates a group of radio buttons to be part of a form
1040 * @param array $options An array of value-label pairs for the radio group (values as keys)
1041 * @param string $name Name of the radiogroup (unique in the form)
1042 * @param string $checked The value that is already checked
1044 function choose_from_radio ($options, $name, $checked='', $return=false) {
1046 static $idcounter = 0;
1048 if (!$name) {
1049 $name = 'unnamed';
1052 $output = '<span class="radiogroup '.$name."\">\n";
1054 if (!empty($options)) {
1055 $currentradio = 0;
1056 foreach ($options as $value => $label) {
1057 $htmlid = 'auto-rb'.sprintf('%04d', ++$idcounter);
1058 $output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
1059 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
1060 if ($value == $checked) {
1061 $output .= ' checked="checked"';
1063 if ($label === '') {
1064 $output .= ' /> <label for="'.$htmlid.'">'. $value .'</label></span>' . "\n";
1065 } else {
1066 $output .= ' /> <label for="'.$htmlid.'">'. $label .'</label></span>' . "\n";
1068 $currentradio = ($currentradio + 1) % 2;
1072 $output .= '</span>' . "\n";
1074 if ($return) {
1075 return $output;
1076 } else {
1077 echo $output;
1081 /** Display an standard html checkbox with an optional label
1083 * @param string $name The name of the checkbox
1084 * @param string $value The valus that the checkbox will pass when checked
1085 * @param boolean $checked The flag to tell the checkbox initial state
1086 * @param string $label The label to be showed near the checkbox
1087 * @param string $alt The info to be inserted in the alt tag
1089 function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
1091 static $idcounter = 0;
1093 if (!$name) {
1094 $name = 'unnamed';
1097 if ($alt) {
1098 $alt = strip_tags($alt);
1099 } else {
1100 $alt = 'checkbox';
1103 if ($checked) {
1104 $strchecked = ' checked="checked"';
1105 } else {
1106 $strchecked = '';
1109 $htmlid = 'auto-cb'.sprintf('%04d', ++$idcounter);
1110 $output = '<span class="checkbox '.$name."\">";
1111 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ? ' onclick="'.$script.'" ' : '').' />';
1112 if(!empty($label)) {
1113 $output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
1115 $output .= '</span>'."\n";
1117 if (empty($return)) {
1118 echo $output;
1119 } else {
1120 return $output;
1125 /** Display an standard html text field with an optional label
1127 * @param string $name The name of the text field
1128 * @param string $value The value of the text field
1129 * @param string $label The label to be showed near the text field
1130 * @param string $alt The info to be inserted in the alt tag
1132 function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
1134 static $idcounter = 0;
1136 if (empty($name)) {
1137 $name = 'unnamed';
1140 if (empty($alt)) {
1141 $alt = 'textfield';
1144 if (!empty($maxlength)) {
1145 $maxlength = ' maxlength="'.$maxlength.'" ';
1148 $htmlid = 'auto-tf'.sprintf('%04d', ++$idcounter);
1149 $output = '<span class="textfield '.$name."\">";
1150 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
1152 $output .= '</span>'."\n";
1154 if (empty($return)) {
1155 echo $output;
1156 } else {
1157 return $output;
1164 * Implements a complete little popup form
1166 * @uses $CFG
1167 * @param string $common The URL up to the point of the variable that changes
1168 * @param array $options Alist of value-label pairs for the popup list
1169 * @param string $formid Id must be unique on the page (originaly $formname)
1170 * @param string $selected The option that is already selected
1171 * @param string $nothing The label for the "no choice" option
1172 * @param string $help The name of a help page if help is required
1173 * @param string $helptext The name of the label for the help button
1174 * @param boolean $return Indicates whether the function should return the text
1175 * as a string or echo it directly to the page being rendered
1176 * @param string $targetwindow The name of the target page to open the linked page in.
1177 * @param string $selectlabel Text to place in a [label] element - preferred for accessibility.
1178 * @param array $optionsextra TODO, an array?
1179 * @param mixed $gobutton If set, this turns off the JavaScript and uses a 'go'
1180 * button instead (as is always included for JS-disabled users). Set to true
1181 * for a literal 'Go' button, or to a string to change the name of the button.
1182 * @return string If $return is true then the entire form is returned as a string.
1183 * @todo Finish documenting this function<br>
1185 function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
1186 $targetwindow='self', $selectlabel='', $optionsextra=NULL, $gobutton=NULL) {
1188 global $CFG;
1189 static $go, $choose; /// Locally cached, in case there's lots on a page
1191 if (empty($options)) {
1192 return '';
1195 if (!isset($go)) {
1196 $go = get_string('go');
1199 if ($nothing == 'choose') {
1200 if (!isset($choose)) {
1201 $choose = get_string('choose');
1203 $nothing = $choose.'...';
1206 // changed reference to document.getElementById('id_abc') instead of document.abc
1207 // MDL-7861
1208 $output = '<form action="'.$CFG->wwwroot.'/course/jumpto.php"'.
1209 ' method="get" '.
1210 $CFG->frametarget.
1211 ' id="'.$formid.'"'.
1212 ' class="popupform">';
1213 if ($help) {
1214 $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
1215 } else {
1216 $button = '';
1219 if ($selectlabel) {
1220 $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
1223 if ($gobutton) {
1224 // Using the no-JavaScript version
1225 $javascript = '';
1226 } else if (check_browser_version('MSIE') || (check_browser_version('Opera') && !check_browser_operating_system("Linux"))) {
1227 //IE and Opera fire the onchange when ever you move into a dropdown list with the keyboard.
1228 //onfocus will call a function inside dropdown.js. It fixes this IE/Opera behavior.
1229 //Note: There is a bug on Opera+Linux with the javascript code (first mouse selection is inactive),
1230 //so we do not fix the Opera behavior on Linux
1231 $javascript = ' onfocus="initSelect(\''.$formid.'\','.$targetwindow.')"';
1232 } else {
1233 //Other browser
1234 $javascript = ' onchange="'.$targetwindow.
1235 '.location=document.getElementById(\''.$formid.
1236 '\').jump.options[document.getElementById(\''.
1237 $formid.'\').jump.selectedIndex].value;"';
1240 $output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" name="jump"'.$javascript.'>'."\n";
1242 if ($nothing != '') {
1243 $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
1246 $inoptgroup = false;
1248 foreach ($options as $value => $label) {
1250 if ($label == '--') { /// we are ending previous optgroup
1251 /// Check to see if we already have a valid open optgroup
1252 /// XHTML demands that there be at least 1 option within an optgroup
1253 if ($inoptgroup and (count($optgr) > 1) ) {
1254 $output .= implode('', $optgr);
1255 $output .= ' </optgroup>';
1257 $optgr = array();
1258 $inoptgroup = false;
1259 continue;
1260 } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
1262 /// Check to see if we already have a valid open optgroup
1263 /// XHTML demands that there be at least 1 option within an optgroup
1264 if ($inoptgroup and (count($optgr) > 1) ) {
1265 $output .= implode('', $optgr);
1266 $output .= ' </optgroup>';
1269 unset($optgr);
1270 $optgr = array();
1272 $optgr[] = ' <optgroup label="'. s(format_string(substr($label,2))) .'">'; // Plain labels
1274 $inoptgroup = true; /// everything following will be in an optgroup
1275 continue;
1277 } else {
1278 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()]))
1280 $url=sid_process_url( $common . $value );
1281 } else
1283 $url=$common . $value;
1285 $optstr = ' <option value="' . $url . '"';
1287 if ($value == $selected) {
1288 $optstr .= ' selected="selected"';
1291 if (!empty($optionsextra[$value])) {
1292 $optstr .= ' '.$optionsextra[$value];
1295 if ($label) {
1296 $optstr .= '>'. $label .'</option>' . "\n";
1297 } else {
1298 $optstr .= '>'. $value .'</option>' . "\n";
1301 if ($inoptgroup) {
1302 $optgr[] = $optstr;
1303 } else {
1304 $output .= $optstr;
1310 /// catch the final group if not closed
1311 if ($inoptgroup and count($optgr) > 1) {
1312 $output .= implode('', $optgr);
1313 $output .= ' </optgroup>';
1316 $output .= '</select>';
1317 $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1318 if ($gobutton) {
1319 $output .= '<input type="submit" value="'.
1320 ($gobutton===true ? $go : $gobutton).'" />';
1321 } else {
1322 $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
1323 $output .= '<input type="submit" value="'.$go.'" /></div>';
1324 $output .= '<script type="text/javascript">'.
1325 "\n//<![CDATA[\n".
1326 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
1327 "\n//]]>\n".'</script>';
1329 $output .= '</div></form>';
1331 if ($return) {
1332 return $output;
1333 } else {
1334 echo $output;
1340 * Prints some red text
1342 * @param string $error The text to be displayed in red
1344 function formerr($error) {
1346 if (!empty($error)) {
1347 echo '<span class="error">'. $error .'</span>';
1352 * Validates an email to make sure it makes sense.
1354 * @param string $address The email address to validate.
1355 * @return boolean
1357 function validate_email($address) {
1359 return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1360 '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1361 '@'.
1362 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1363 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
1364 $address));
1368 * Extracts file argument either from file parameter or PATH_INFO
1370 * @param string $scriptname name of the calling script
1371 * @return string file path (only safe characters)
1373 function get_file_argument($scriptname) {
1374 global $_SERVER;
1376 $relativepath = FALSE;
1378 // first try normal parameter (compatible method == no relative links!)
1379 $relativepath = optional_param('file', FALSE, PARAM_PATH);
1380 if ($relativepath === '/testslasharguments') {
1381 echo 'test -1 : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
1382 die;
1385 // then try extract file from PATH_INFO (slasharguments method)
1386 if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
1387 $path_info = $_SERVER['PATH_INFO'];
1388 // check that PATH_INFO works == must not contain the script name
1389 if (!strpos($path_info, $scriptname)) {
1390 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1391 if ($relativepath === '/testslasharguments') {
1392 echo 'test 1 : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
1393 die;
1398 // now if both fail try the old way
1399 // (for compatibility with misconfigured or older buggy php implementations)
1400 if (!$relativepath) {
1401 $arr = explode($scriptname, me());
1402 if (!empty($arr[1])) {
1403 $path_info = strip_querystring($arr[1]);
1404 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1405 if ($relativepath === '/testslasharguments') {
1406 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
1407 die;
1412 return $relativepath;
1416 * Searches the current environment variables for some slash arguments
1418 * @param string $file ?
1419 * @todo Finish documenting this function
1421 function get_slash_arguments($file='file.php') {
1423 if (!$string = me()) {
1424 return false;
1427 $pathinfo = explode($file, $string);
1429 if (!empty($pathinfo[1])) {
1430 return addslashes($pathinfo[1]);
1431 } else {
1432 return false;
1437 * Extracts arguments from "/foo/bar/something"
1438 * eg http://mysite.com/script.php/foo/bar/something
1440 * @param string $string ?
1441 * @param int $i ?
1442 * @return array|string
1443 * @todo Finish documenting this function
1445 function parse_slash_arguments($string, $i=0) {
1447 if (detect_munged_arguments($string)) {
1448 return false;
1450 $args = explode('/', $string);
1452 if ($i) { // return just the required argument
1453 return $args[$i];
1455 } else { // return the whole array
1456 array_shift($args); // get rid of the empty first one
1457 return $args;
1462 * Just returns an array of text formats suitable for a popup menu
1464 * @uses FORMAT_MOODLE
1465 * @uses FORMAT_HTML
1466 * @uses FORMAT_PLAIN
1467 * @uses FORMAT_MARKDOWN
1468 * @return array
1470 function format_text_menu() {
1472 return array (FORMAT_MOODLE => get_string('formattext'),
1473 FORMAT_HTML => get_string('formathtml'),
1474 FORMAT_PLAIN => get_string('formatplain'),
1475 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1479 * Given text in a variety of format codings, this function returns
1480 * the text as safe HTML.
1482 * This function should mainly be used for long strings like posts,
1483 * answers, glossary items etc. For short strings @see format_string().
1485 * @uses $CFG
1486 * @uses FORMAT_MOODLE
1487 * @uses FORMAT_HTML
1488 * @uses FORMAT_PLAIN
1489 * @uses FORMAT_WIKI
1490 * @uses FORMAT_MARKDOWN
1491 * @param string $text The text to be formatted. This is raw text originally from user input.
1492 * @param int $format Identifier of the text format to be used
1493 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1494 * @param array $options ?
1495 * @param int $courseid ?
1496 * @return string
1497 * @todo Finish documenting this function
1499 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1501 global $CFG, $COURSE;
1503 static $croncache = array();
1505 if ($text === '') {
1506 return ''; // no need to do any filters and cleaning
1509 if (!isset($options->trusttext)) {
1510 $options->trusttext = false;
1513 if (!isset($options->noclean)) {
1514 $options->noclean=false;
1516 if (!isset($options->nocache)) {
1517 $options->nocache=false;
1519 if (!isset($options->smiley)) {
1520 $options->smiley=true;
1522 if (!isset($options->filter)) {
1523 $options->filter=true;
1525 if (!isset($options->para)) {
1526 $options->para=true;
1528 if (!isset($options->newlines)) {
1529 $options->newlines=true;
1532 if (empty($courseid)) {
1533 $courseid = $COURSE->id;
1536 if (!empty($CFG->cachetext) and empty($options->nocache)) {
1537 $time = time() - $CFG->cachetext;
1538 $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);
1540 if (defined('FULLME') and FULLME == 'cron') {
1541 if (isset($croncache[$md5key])) {
1542 return $croncache[$md5key];
1546 if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
1547 if ($oldcacheitem->timemodified >= $time) {
1548 if (defined('FULLME') and FULLME == 'cron') {
1549 if (count($croncache) > 150) {
1550 reset($croncache);
1551 $key = key($croncache);
1552 unset($croncache[$key]);
1554 $croncache[$md5key] = $oldcacheitem->formattedtext;
1556 return $oldcacheitem->formattedtext;
1561 // trusttext overrides the noclean option!
1562 if ($options->trusttext) {
1563 if (trusttext_present($text)) {
1564 $text = trusttext_strip($text);
1565 if (!empty($CFG->enabletrusttext)) {
1566 $options->noclean = true;
1567 } else {
1568 $options->noclean = false;
1570 } else {
1571 $options->noclean = false;
1573 } else if (!debugging('', DEBUG_DEVELOPER)) {
1574 // strip any forgotten trusttext in non-developer mode
1575 // do not forget to disable text cache when debugging trusttext!!
1576 $text = trusttext_strip($text);
1579 $CFG->currenttextiscacheable = true; // Default status - can be changed by any filter
1581 switch ($format) {
1582 case FORMAT_HTML:
1583 if ($options->smiley) {
1584 replace_smilies($text);
1586 if (!$options->noclean) {
1587 $text = clean_text($text, FORMAT_HTML);
1589 if ($options->filter) {
1590 $text = filter_text($text, $courseid);
1592 break;
1594 case FORMAT_PLAIN:
1595 $text = s($text); // cleans dangerous JS
1596 $text = rebuildnolinktag($text);
1597 $text = str_replace(' ', '&nbsp; ', $text);
1598 $text = nl2br($text);
1599 break;
1601 case FORMAT_WIKI:
1602 // this format is deprecated
1603 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1604 this message as all texts should have been converted to Markdown format instead.
1605 Please post a bug report to http://moodle.org/bugs with information about where you
1606 saw this message.</p>'.s($text);
1607 break;
1609 case FORMAT_MARKDOWN:
1610 $text = markdown_to_html($text);
1611 if ($options->smiley) {
1612 replace_smilies($text);
1614 if (!$options->noclean) {
1615 $text = clean_text($text, FORMAT_HTML);
1618 if ($options->filter) {
1619 $text = filter_text($text, $courseid);
1621 break;
1623 default: // FORMAT_MOODLE or anything else
1624 $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
1625 if (!$options->noclean) {
1626 $text = clean_text($text, FORMAT_HTML);
1629 if ($options->filter) {
1630 $text = filter_text($text, $courseid);
1632 break;
1635 if (empty($options->nocache) and !empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
1636 if (defined('FULLME') and FULLME == 'cron') {
1637 // special static cron cache - no need to store it in db if its not already there
1638 if (count($croncache) > 150) {
1639 reset($croncache);
1640 $key = key($croncache);
1641 unset($croncache[$key]);
1643 $croncache[$md5key] = $text;
1644 return $text;
1647 $newcacheitem = new object();
1648 $newcacheitem->md5key = $md5key;
1649 $newcacheitem->formattedtext = addslashes($text);
1650 $newcacheitem->timemodified = time();
1651 if ($oldcacheitem) { // See bug 4677 for discussion
1652 $newcacheitem->id = $oldcacheitem->id;
1653 @update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1654 // It's unlikely that the cron cache cleaner could have
1655 // deleted this entry in the meantime, as it allows
1656 // some extra time to cover these cases.
1657 } else {
1658 @insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1659 // Again, it's possible that another user has caused this
1660 // record to be created already in the time that it took
1661 // to traverse this function. That's OK too, as the
1662 // call above handles duplicate entries, and eventually
1663 // the cron cleaner will delete them.
1667 return $text;
1670 /** Converts the text format from the value to the 'internal'
1671 * name or vice versa. $key can either be the value or the name
1672 * and you get the other back.
1674 * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1675 * @return mixed as above but the other way around!
1677 function text_format_name( $key ) {
1678 $lookup = array();
1679 $lookup[FORMAT_MOODLE] = 'moodle';
1680 $lookup[FORMAT_HTML] = 'html';
1681 $lookup[FORMAT_PLAIN] = 'plain';
1682 $lookup[FORMAT_MARKDOWN] = 'markdown';
1683 $value = "error";
1684 if (!is_numeric($key)) {
1685 $key = strtolower( $key );
1686 $value = array_search( $key, $lookup );
1688 else {
1689 if (isset( $lookup[$key] )) {
1690 $value = $lookup[ $key ];
1693 return $value;
1697 * Resets all data related to filters, called during upgrade or when filter settings change.
1698 * @return void
1700 function reset_text_filters_cache() {
1701 global $CFG;
1703 delete_records('cache_text');
1704 $purifdir = $CFG->dataroot.'/cache/htmlpurifier';
1705 remove_dir($purifdir, true);
1708 /** Given a simple string, this function returns the string
1709 * processed by enabled string filters if $CFG->filterall is enabled
1711 * This function should be used to print short strings (non html) that
1712 * need filter processing e.g. activity titles, post subjects,
1713 * glossary concepts.
1715 * @param string $string The string to be filtered.
1716 * @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
1717 * @param int $courseid Current course as filters can, potentially, use it
1718 * @return string
1720 function format_string ($string, $striplinks=true, $courseid=NULL ) {
1722 global $CFG, $COURSE;
1724 //We'll use a in-memory cache here to speed up repeated strings
1725 static $strcache = false;
1727 if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
1728 $strcache = array();
1731 //init course id
1732 if (empty($courseid)) {
1733 $courseid = $COURSE->id;
1736 //Calculate md5
1737 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
1739 //Fetch from cache if possible
1740 if (isset($strcache[$md5])) {
1741 return $strcache[$md5];
1744 // First replace all ampersands not followed by html entity code
1745 $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1747 if (!empty($CFG->filterall)) {
1748 $string = filter_string($string, $courseid);
1751 // If the site requires it, strip ALL tags from this string
1752 if (!empty($CFG->formatstringstriptags)) {
1753 $string = strip_tags($string);
1755 } else {
1756 // Otherwise strip just links if that is required (default)
1757 if ($striplinks) { //strip links in string
1758 $string = preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1760 $string = clean_text($string);
1763 //Store to cache
1764 $strcache[$md5] = $string;
1766 return $string;
1770 * Given text in a variety of format codings, this function returns
1771 * the text as plain text suitable for plain email.
1773 * @uses FORMAT_MOODLE
1774 * @uses FORMAT_HTML
1775 * @uses FORMAT_PLAIN
1776 * @uses FORMAT_WIKI
1777 * @uses FORMAT_MARKDOWN
1778 * @param string $text The text to be formatted. This is raw text originally from user input.
1779 * @param int $format Identifier of the text format to be used
1780 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1781 * @return string
1783 function format_text_email($text, $format) {
1785 switch ($format) {
1787 case FORMAT_PLAIN:
1788 return $text;
1789 break;
1791 case FORMAT_WIKI:
1792 // there should not be any of these any more!
1793 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1794 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
1795 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1796 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1797 break;
1799 case FORMAT_HTML:
1800 return html_to_text($text);
1801 break;
1803 case FORMAT_MOODLE:
1804 case FORMAT_MARKDOWN:
1805 default:
1806 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1807 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1808 break;
1813 * Given some text in HTML format, this function will pass it
1814 * through any filters that have been defined in $CFG->textfilterx
1815 * The variable defines a filepath to a file containing the
1816 * filter function. The file must contain a variable called
1817 * $textfilter_function which contains the name of the function
1818 * with $courseid and $text parameters
1820 * @param string $text The text to be passed through format filters
1821 * @param int $courseid ?
1822 * @return string
1823 * @todo Finish documenting this function
1825 function filter_text($text, $courseid=NULL) {
1826 global $CFG, $COURSE;
1828 if (empty($courseid)) {
1829 $courseid = $COURSE->id; // (copied from format_text)
1832 if (!empty($CFG->textfilters)) {
1833 require_once($CFG->libdir.'/filterlib.php');
1834 $textfilters = explode(',', $CFG->textfilters);
1835 foreach ($textfilters as $textfilter) {
1836 if (is_readable($CFG->dirroot .'/'. $textfilter .'/filter.php')) {
1837 include_once($CFG->dirroot .'/'. $textfilter .'/filter.php');
1838 $functionname = basename($textfilter).'_filter';
1839 if (function_exists($functionname)) {
1840 $text = $functionname($courseid, $text);
1846 /// <nolink> tags removed for XHTML compatibility
1847 $text = str_replace('<nolink>', '', $text);
1848 $text = str_replace('</nolink>', '', $text);
1850 return $text;
1855 * Given a string (short text) in HTML format, this function will pass it
1856 * through any filters that have been defined in $CFG->stringfilters
1857 * The variable defines a filepath to a file containing the
1858 * filter function. The file must contain a variable called
1859 * $textfilter_function which contains the name of the function
1860 * with $courseid and $text parameters
1862 * @param string $string The text to be passed through format filters
1863 * @param int $courseid The id of a course
1864 * @return string
1866 function filter_string($string, $courseid=NULL) {
1867 global $CFG, $COURSE;
1869 if (empty($CFG->textfilters)) { // All filters are disabled anyway so quit
1870 return $string;
1873 if (empty($courseid)) {
1874 $courseid = $COURSE->id;
1877 require_once($CFG->libdir.'/filterlib.php');
1879 if (isset($CFG->stringfilters)) { // We have a predefined list to use, great!
1880 if (empty($CFG->stringfilters)) { // but it's blank, so finish now
1881 return $string;
1883 $stringfilters = explode(',', $CFG->stringfilters); // ..use the list we have
1885 } else { // Otherwise try to derive a list from textfilters
1886 if (strpos($CFG->textfilters, 'filter/multilang') !== false) { // Multilang is here
1887 $stringfilters = array('filter/multilang'); // Let's use just that
1888 $CFG->stringfilters = 'filter/multilang'; // Save it for next time through
1889 } else {
1890 $CFG->stringfilters = ''; // Save the result and return
1891 return $string;
1896 foreach ($stringfilters as $stringfilter) {
1897 if (is_readable($CFG->dirroot .'/'. $stringfilter .'/filter.php')) {
1898 include_once($CFG->dirroot .'/'. $stringfilter .'/filter.php');
1899 $functionname = basename($stringfilter).'_filter';
1900 if (function_exists($functionname)) {
1901 $string = $functionname($courseid, $string);
1906 /// <nolink> tags removed for XHTML compatibility
1907 $string = str_replace('<nolink>', '', $string);
1908 $string = str_replace('</nolink>', '', $string);
1910 return $string;
1914 * Is the text marked as trusted?
1916 * @param string $text text to be searched for TRUSTTEXT marker
1917 * @return boolean
1919 function trusttext_present($text) {
1920 if (strpos($text, TRUSTTEXT) !== FALSE) {
1921 return true;
1922 } else {
1923 return false;
1928 * This funtion MUST be called before the cleaning or any other
1929 * function that modifies the data! We do not know the origin of trusttext
1930 * in database, if it gets there in tweaked form we must not convert it
1931 * to supported form!!!
1933 * Please be carefull not to use stripslashes on data from database
1934 * or twice stripslashes when processing data recieved from user.
1936 * @param string $text text that may contain TRUSTTEXT marker
1937 * @return text without any TRUSTTEXT marker
1939 function trusttext_strip($text) {
1940 global $CFG;
1942 while (true) { //removing nested TRUSTTEXT
1943 $orig = $text;
1944 $text = str_replace(TRUSTTEXT, '', $text);
1945 if (strcmp($orig, $text) === 0) {
1946 return $text;
1952 * Mark text as trusted, such text may contain any HTML tags because the
1953 * normal text cleaning will be bypassed.
1954 * Please make sure that the text comes from trusted user before storing
1955 * it into database!
1957 function trusttext_mark($text) {
1958 global $CFG;
1959 if (!empty($CFG->enabletrusttext) and (strpos($text, TRUSTTEXT) === FALSE)) {
1960 return TRUSTTEXT.$text;
1961 } else {
1962 return $text;
1965 function trusttext_after_edit(&$text, $context) {
1966 if (has_capability('moodle/site:trustcontent', $context)) {
1967 $text = trusttext_strip($text);
1968 $text = trusttext_mark($text);
1969 } else {
1970 $text = trusttext_strip($text);
1974 function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
1975 global $CFG;
1977 $options = new object();
1978 $options->smiley = false;
1979 $options->filter = false;
1980 if (!empty($CFG->enabletrusttext)
1981 and has_capability('moodle/site:trustcontent', $context)
1982 and trusttext_present($text)) {
1983 $options->noclean = true;
1984 } else {
1985 $options->noclean = false;
1987 $text = trusttext_strip($text);
1988 if ($usehtmleditor) {
1989 $text = format_text($text, $format, $options);
1990 $format = FORMAT_HTML;
1991 } else if (!$options->noclean){
1992 $text = clean_text($text, $format);
1997 * Given raw text (eg typed in by a user), this function cleans it up
1998 * and removes any nasty tags that could mess up Moodle pages.
2000 * @uses FORMAT_MOODLE
2001 * @uses FORMAT_PLAIN
2002 * @uses ALLOWED_TAGS
2003 * @param string $text The text to be cleaned
2004 * @param int $format Identifier of the text format to be used
2005 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
2006 * @return string The cleaned up text
2008 function clean_text($text, $format=FORMAT_MOODLE) {
2010 global $ALLOWED_TAGS, $CFG;
2012 if (empty($text) or is_numeric($text)) {
2013 return (string)$text;
2016 switch ($format) {
2017 case FORMAT_PLAIN:
2018 return $text;
2020 default:
2022 if (!empty($CFG->enablehtmlpurifier)) {
2023 //this is PHP5 only, the lib/setup.php contains a disabler for PHP4
2024 $text = purify_html($text);
2025 } else {
2026 /// Fix non standard entity notations
2027 $text = preg_replace('/&#0*([0-9]+);?/', "&#\\1;", $text);
2028 $text = preg_replace('/&#x0*([0-9a-fA-F]+);?/', "&#x\\1;", $text);
2029 $text = preg_replace('[\x00-\x08\x0b-\x0c\x0e-\x1f]', '', $text);
2031 /// Remove tags that are not allowed
2032 $text = strip_tags($text, $ALLOWED_TAGS);
2034 /// Clean up embedded scripts and , using kses
2035 $text = cleanAttributes($text);
2037 /// Again remove tags that are not allowed
2038 $text = strip_tags($text, $ALLOWED_TAGS);
2042 /// Remove potential script events - some extra protection for undiscovered bugs in our code
2043 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
2044 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
2046 return $text;
2051 * KSES replacement cleaning function - uses HTML Purifier.
2053 * @global object
2054 * @param string $text The (X)HTML string to purify
2056 function purify_html($text) {
2057 global $CFG;
2059 // this can not be done only once because we sometimes need to reset the cache
2060 $cachedir = $CFG->dataroot.'/cache/htmlpurifier';
2061 check_dir_exists($cachedir);
2063 static $purifier = false;
2064 if ($purifier === false) {
2065 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
2066 $config = HTMLPurifier_Config::createDefault();
2068 $config->set('HTML.DefinitionID', 'moodlehtml');
2069 $config->set('HTML.DefinitionRev', 1);
2070 $config->set('Cache.SerializerPath', $cachedir);
2071 //$config->set('Cache.SerializerPermission', $CFG->directorypermissions); // it would be nice to get this upstream
2072 $config->set('Core.NormalizeNewlines', false);
2073 $config->set('Core.ConvertDocumentToFragment', true);
2074 $config->set('Core.Encoding', 'UTF-8');
2075 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
2076 $config->set('URI.AllowedSchemes', array('http'=>true, 'https'=>true, 'ftp'=>true, 'irc'=>true, 'nntp'=>true, 'news'=>true, 'rtsp'=>true, 'teamspeak'=>true, 'gopher'=>true, 'mms'=>true));
2077 $config->set('Attr.AllowedFrameTargets', array('_blank'));
2079 if (!empty($CFG->allowobjectembed)) {
2080 $config->set('HTML.SafeObject', true);
2081 $config->set('Output.FlashCompat', true);
2082 $config->set('HTML.SafeEmbed', true);
2085 $def = $config->getHTMLDefinition(true);
2086 $def->addElement('nolink', 'Block', 'Flow', array()); // skip our filters inside
2087 $def->addElement('tex', 'Inline', 'Inline', array()); // tex syntax, equivalent to $$xx$$
2088 $def->addElement('algebra', 'Inline', 'Inline', array()); // algebra syntax, equivalent to @@xx@@
2089 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // old anf future style multilang - only our hacked lang attribute
2090 $def->addAttribute('span', 'xxxlang', 'CDATA'); // current problematic multilang
2092 $purifier = new HTMLPurifier($config);
2095 $multilang = (strpos($text, 'class="multilang"') !== false);
2097 if ($multilang) {
2098 $text = preg_replace('/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/', '<span xxxlang="${2}">', $text);
2100 $text = $purifier->purify($text);
2101 if ($multilang) {
2102 $text = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $text);
2105 return $text;
2109 * This function takes a string and examines it for HTML tags.
2110 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
2111 * which checks for attributes and filters them for malicious content
2112 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2114 * @param string $str The string to be examined for html tags
2115 * @return string
2117 function cleanAttributes($str){
2118 $result = preg_replace_callback(
2119 '%(<[^>]*(>|$)|>)%m', #search for html tags
2120 "cleanAttributes2",
2121 $str
2123 return $result;
2127 * This function takes a string with an html tag and strips out any unallowed
2128 * protocols e.g. javascript:
2129 * It calls ancillary functions in kses which are prefixed by kses
2130 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2132 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
2133 * element the html to be cleared
2134 * @return string
2136 function cleanAttributes2($htmlArray){
2138 global $CFG, $ALLOWED_PROTOCOLS;
2139 require_once($CFG->libdir .'/kses.php');
2141 $htmlTag = $htmlArray[1];
2142 if (substr($htmlTag, 0, 1) != '<') {
2143 return '&gt;'; //a single character ">" detected
2145 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
2146 return ''; // It's seriously malformed
2148 $slash = trim($matches[1]); //trailing xhtml slash
2149 $elem = $matches[2]; //the element name
2150 $attrlist = $matches[3]; // the list of attributes as a string
2152 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
2154 $attStr = '';
2155 foreach ($attrArray as $arreach) {
2156 $arreach['name'] = strtolower($arreach['name']);
2157 if ($arreach['name'] == 'style') {
2158 $value = $arreach['value'];
2159 while (true) {
2160 $prevvalue = $value;
2161 $value = kses_no_null($value);
2162 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
2163 $value = kses_decode_entities($value);
2164 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
2165 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
2166 if ($value === $prevvalue) {
2167 $arreach['value'] = $value;
2168 break;
2171 $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']);
2172 $arreach['value'] = preg_replace("/v\s*b\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xvbscript", $arreach['value']);
2173 $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']);
2174 $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
2175 } else if ($arreach['name'] == 'href') {
2176 //Adobe Acrobat Reader XSS protection
2177 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd)[^#]*)#.*$/i', '$1', $arreach['value']);
2179 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
2182 $xhtml_slash = '';
2183 if (preg_match('%/\s*$%', $attrlist)) {
2184 $xhtml_slash = ' /';
2186 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
2190 * Replaces all known smileys in the text with image equivalents
2192 * @uses $CFG
2193 * @param string $text Passed by reference. The string to search for smily strings.
2194 * @return string
2196 function replace_smilies(&$text) {
2198 global $CFG;
2200 if (empty($CFG->emoticons)) { /// No emoticons defined, nothing to process here
2201 return;
2204 $lang = current_language();
2205 $emoticonstring = $CFG->emoticons;
2206 static $e = array();
2207 static $img = array();
2208 static $emoticons = null;
2210 if (is_null($emoticons)) {
2211 $emoticons = array();
2212 if ($emoticonstring) {
2213 $items = explode('{;}', $CFG->emoticons);
2214 foreach ($items as $item) {
2215 $item = explode('{:}', $item);
2216 $emoticons[$item[0]] = $item[1];
2222 if (empty($img[$lang])) { /// After the first time this is not run again
2223 $e[$lang] = array();
2224 $img[$lang] = array();
2225 foreach ($emoticons as $emoticon => $image){
2226 $alttext = get_string($image, 'pix');
2227 $alttext = preg_replace('/^\[\[(.*)\]\]$/', '$1', $alttext); /// Clean alttext in case there isn't lang string for it.
2228 $e[$lang][] = $emoticon;
2229 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath .'/s/'. $image .'.gif" />';
2233 // Exclude from transformations all the code inside <script> tags
2234 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
2235 // Based on code from glossary fiter by Williams Castillo.
2236 // - Eloy
2238 // Detect all the <script> zones to take out
2239 $excludes = array();
2240 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
2242 // Take out all the <script> zones from text
2243 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
2244 $excludes['<+'.$key.'+>'] = $value;
2246 if ($excludes) {
2247 $text = str_replace($excludes,array_keys($excludes),$text);
2250 /// this is the meat of the code - this is run every time
2251 $text = str_replace($e[$lang], $img[$lang], $text);
2253 // Recover all the <script> zones to text
2254 if ($excludes) {
2255 $text = str_replace(array_keys($excludes),$excludes,$text);
2260 * Given plain text, makes it into HTML as nicely as possible.
2261 * May contain HTML tags already
2263 * @uses $CFG
2264 * @param string $text The string to convert.
2265 * @param boolean $smiley Convert any smiley characters to smiley images?
2266 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
2267 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2268 * @return string
2271 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
2274 global $CFG;
2276 /// Remove any whitespace that may be between HTML tags
2277 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
2279 /// Remove any returns that precede or follow HTML tags
2280 $text = eregi_replace("([\n\r])<", " <", $text);
2281 $text = eregi_replace(">([\n\r])", "> ", $text);
2283 convert_urls_into_links($text);
2285 /// Make returns into HTML newlines.
2286 if ($newlines) {
2287 $text = nl2br($text);
2290 /// Turn smileys into images.
2291 if ($smiley) {
2292 replace_smilies($text);
2295 /// Wrap the whole thing in a paragraph tag if required
2296 if ($para) {
2297 return '<p>'.$text.'</p>';
2298 } else {
2299 return $text;
2304 * Given Markdown formatted text, make it into XHTML using external function
2306 * @uses $CFG
2307 * @param string $text The markdown formatted text to be converted.
2308 * @return string Converted text
2310 function markdown_to_html($text) {
2311 global $CFG;
2313 require_once($CFG->libdir .'/markdown.php');
2315 return Markdown($text);
2319 * Given HTML text, make it into plain text using external function
2321 * @param string $html The text to be converted.
2322 * @param integer $width Width to wrap the text at. (optional, default 75 which
2323 * is a good value for email. 0 means do not limit line length.)
2324 * @return string plain text equivalent of the HTML.
2326 function html_to_text($html, $width = 75) {
2328 global $CFG;
2330 require_once($CFG->libdir .'/html2text.php');
2332 $h2t = new html2text($html, false, true, $width);
2333 $result = $h2t->get_text();
2335 return $result;
2339 * Given some text this function converts any URLs it finds into HTML links
2341 * @param string $text Passed in by reference. The string to be searched for urls.
2343 function convert_urls_into_links(&$text) {
2344 //I've added img tags to this list of tags to ignore.
2345 //See MDL-21168 for more info. A better way to ignore tags whether or not
2346 //they are escaped partially or completely would be desirable. For example:
2347 //<a href="blah">
2348 //&lt;a href="blah"&gt;
2349 //&lt;a href="blah">
2350 $filterignoretagsopen = array('<a\s[^>]+?>');
2351 $filterignoretagsclose = array('</a>');
2352 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
2354 // Check if we support unicode modifiers in regular expressions. Cache it.
2355 // TODO: this check should be a environment requirement in Moodle 2.0, as far as unicode
2356 // chars are going to arrive to URLs officially really soon (2010?)
2357 // Original RFC regex from: http://www.bytemycode.com/snippets/snippet/796/
2358 // Various ideas from: http://alanstorm.com/url_regex_explained
2359 // Unicode check, negative assertion and other bits from Moodle.
2360 static $unicoderegexp;
2361 if (!isset($unicoderegexp)) {
2362 $unicoderegexp = @preg_match('/\pL/u', 'a'); // This will fail silenty, returning false,
2365 $unicoderegexp = false;//force non use of unicode modifiers. MDL-21296
2366 if ($unicoderegexp) { //We can use unicode modifiers
2367 $text = preg_replace('#(?<!=["\'])(((http(s?))://)(((([\pLl0-9]([\pLl0-9]|-)*[\pLl0-9]|[\pLl0-9])\.)+([\pLl]([\pLl0-9]|-)*[\pLl0-9]|[\pLl]))|(([0-9]{1,3}\.){3}[0-9]{1,3}))(:[\pL0-9]*)?(/([\pLl0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-fA-F0-9]{2})*)*(\?([\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,\.;])#iu',
2368 '<a href="\\1" target="_blank">\\1</a>', $text);
2369 $text = preg_replace('#(?<!=["\']|//)((www\.([\pLl0-9]([\pLl0-9]|-)*[\pLl0-9]|[\pLl0-9])\.)+([\pLl]([\pLl0-9]|-)*[\pLl0-9]|[\pLl])(:[\pL0-9]*)?(/([\pLl0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-fA-F0-9]{2})*)*(\?([\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,\.;])#iu',
2370 '<a href="http://\\1" target="_blank">\\1</a>', $text);
2371 } else { //We cannot use unicode modifiers
2372 $text = preg_replace('#(?<!=["\'])(((http(s?))://)(((([a-z0-9]([a-z0-9]|-)*[a-z0-9]|[a-z0-9])\.)+([a-z]([a-z0-9]|-)*[a-z0-9]|[a-z]))|(([0-9]{1,3}\.){3}[0-9]{1,3}))(:[a-zA-Z0-9]*)?(/([a-z0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-f0-9]{2})*)*(\?([a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,\.;])#i',
2373 '<a href="\\1" target="_blank">\\1</a>', $text);
2374 $text = preg_replace('#(?<!=["\']|//)((www\.([a-z0-9]([a-z0-9]|-)*[a-z0-9]|[a-z0-9])\.)+([a-z]([a-z0-9]|-)*[a-z0-9]|[a-z])(:[a-zA-Z0-9]*)?(/([a-z0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-f0-9]{2})*)*(\?([a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,\.;])#i',
2375 '<a href="http://\\1" target="_blank">\\1</a>', $text);
2378 if (!empty($ignoretags)) {
2379 $ignoretags = array_reverse($ignoretags); /// Reversed so "progressive" str_replace() will solve some nesting problems.
2380 $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
2385 * This function will highlight search words in a given string
2386 * It cares about HTML and will not ruin links. It's best to use
2387 * this function after performing any conversions to HTML.
2389 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
2390 * @param string $haystack The string (HTML) within which to highlight the search terms.
2391 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
2392 * @param string $prefix the string to put before each search term found.
2393 * @param string $suffix the string to put after each search term found.
2394 * @return string The highlighted HTML.
2396 function highlight($needle, $haystack, $matchcase = false,
2397 $prefix = '<span class="highlight">', $suffix = '</span>') {
2399 /// Quick bail-out in trivial cases.
2400 if (empty($needle) or empty($haystack)) {
2401 return $haystack;
2404 /// Break up the search term into words, discard any -words and build a regexp.
2405 $words = preg_split('/ +/', trim($needle));
2406 foreach ($words as $index => $word) {
2407 if (strpos($word, '-') === 0) {
2408 unset($words[$index]);
2409 } else if (strpos($word, '+') === 0) {
2410 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
2411 } else {
2412 $words[$index] = preg_quote($word, '/');
2415 $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
2416 if (!$matchcase) {
2417 $regexp .= 'i';
2420 /// Another chance to bail-out if $search was only -words
2421 if (empty($words)) {
2422 return $haystack;
2425 /// Find all the HTML tags in the input, and store them in a placeholders array.
2426 $placeholders = array();
2427 $matches = array();
2428 preg_match_all('/<[^>]*>/', $haystack, $matches);
2429 foreach (array_unique($matches[0]) as $key => $htmltag) {
2430 $placeholders['<|' . $key . '|>'] = $htmltag;
2433 /// In $hastack, replace each HTML tag with the corresponding placeholder.
2434 $haystack = str_replace($placeholders, array_keys($placeholders), $haystack);
2436 /// In the resulting string, Do the highlighting.
2437 $haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack);
2439 /// Turn the placeholders back into HTML tags.
2440 $haystack = str_replace(array_keys($placeholders), $placeholders, $haystack);
2442 return $haystack;
2446 * This function will highlight instances of $needle in $haystack
2447 * It's faster that the above function and doesn't care about
2448 * HTML or anything.
2450 * @param string $needle The string to search for
2451 * @param string $haystack The string to search for $needle in
2452 * @return string
2454 function highlightfast($needle, $haystack) {
2456 if (empty($needle) or empty($haystack)) {
2457 return $haystack;
2460 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
2462 if (count($parts) === 1) {
2463 return $haystack;
2466 $pos = 0;
2468 foreach ($parts as $key => $part) {
2469 $parts[$key] = substr($haystack, $pos, strlen($part));
2470 $pos += strlen($part);
2472 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2473 $pos += strlen($needle);
2476 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2480 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2481 * Internationalisation, for print_header and backup/restorelib.
2482 * @param $dir Default false.
2483 * @return string Attributes.
2485 function get_html_lang($dir = false) {
2486 $direction = '';
2487 if ($dir) {
2488 if (get_string('thisdirection') == 'rtl') {
2489 $direction = ' dir="rtl"';
2490 } else {
2491 $direction = ' dir="ltr"';
2494 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2495 $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
2496 @header('Content-Language: '.$language);
2497 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2501 * Return the markup for the destination of the 'Skip to main content' links.
2502 * Accessibility improvement for keyboard-only users.
2503 * Used in course formats, /index.php and /course/index.php
2504 * @return string HTML element.
2506 function skip_main_destination() {
2507 return '<span id="maincontent"></span>';
2511 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
2514 * Print a standard header
2516 * @uses $USER
2517 * @uses $CFG
2518 * @uses $SESSION
2519 * @param string $title Appears at the top of the window
2520 * @param string $heading Appears at the top of the page
2521 * @param array $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
2522 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2523 * @param string $meta Meta tags to be added to the header
2524 * @param boolean $cache Should this page be cacheable?
2525 * @param string $button HTML code for a button (usually for module editing)
2526 * @param string $menu HTML code for a popup menu
2527 * @param boolean $usexml use XML for this page
2528 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2529 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2531 function print_header ($title='', $heading='', $navigation='', $focus='',
2532 $meta='', $cache=true, $button='&nbsp;', $menu='',
2533 $usexml=false, $bodytags='', $return=false) {
2535 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
2537 if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
2538 debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
2539 . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.", DEBUG_DEVELOPER);
2542 $heading = format_string($heading); // Fix for MDL-8582
2544 /// This makes sure that the header is never repeated twice on a page
2545 if (defined('HEADER_PRINTED')) {
2546 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().');
2547 return;
2549 define('HEADER_PRINTED', 'true');
2551 /// Perform a browser environment check for the flash version. Should only run once per login session.
2552 if (isloggedin() && !empty($CFG->excludeoldflashclients) && empty($SESSION->flashversion)) {
2553 // Unfortunately we can't use require_js here and keep it all clean in 1.9 ...
2554 // require_js(array('yui_yahoo', 'yui_event', 'yui_connection', $CFG->httpswwwroot."/lib/swfobject/swfobject.js"));
2555 $meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot.'/lib/yui/yahoo/yahoo-min.js"></script>';
2556 $meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot.'/lib/yui/event/event-min.js"></script>';
2557 $meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot.'/lib/yui/connection/connection-min.js"></script>';
2558 $meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot.'/lib/swfobject/swfobject.js"></script>';
2559 $meta .=
2560 "<script type=\"text/javascript\">\n".
2561 "//<![CDATA[\n".
2562 " var flashversion = swfobject.getFlashPlayerVersion();\n".
2563 " YAHOO.util.Connect.asyncRequest('GET','".$CFG->httpswwwroot."/login/environment.php?sesskey=".sesskey()."&flashversion='+flashversion.major+'.'+flashversion.minor+'.'+flashversion.release);\n".
2564 "//]]>\n".
2565 "</script>";
2569 /// Add the required stylesheets
2570 $stylesheetshtml = '';
2571 foreach ($CFG->stylesheets as $stylesheet) {
2572 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2574 $meta = $stylesheetshtml.$meta;
2577 /// Add the meta page from the themes if any were requested
2579 $metapage = '';
2581 if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
2582 ob_start();
2583 include_once($CFG->dirroot.'/theme/standard/meta.php');
2584 $metapage .= ob_get_contents();
2585 ob_end_clean();
2588 if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
2589 if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
2590 ob_start();
2591 include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
2592 $metapage .= ob_get_contents();
2593 ob_end_clean();
2597 if (!isset($THEME->metainclude) || $THEME->metainclude) {
2598 if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
2599 ob_start();
2600 include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
2601 $metapage .= ob_get_contents();
2602 ob_end_clean();
2606 $meta = $meta."\n".$metapage;
2608 $meta .= "\n".require_js('',1);
2610 /// Set up some navigation variables
2612 if (is_newnav($navigation)){
2613 $home = false;
2614 } else {
2615 if ($navigation == 'home') {
2616 $home = true;
2617 $navigation = '';
2618 } else {
2619 $home = false;
2623 /// This is another ugly hack to make navigation elements available to print_footer later
2624 $THEME->title = $title;
2625 $THEME->heading = $heading;
2626 $THEME->navigation = $navigation;
2627 $THEME->button = $button;
2628 $THEME->menu = $menu;
2629 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2631 if ($button == '') {
2632 $button = '&nbsp;';
2635 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
2636 $button = '<a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/maintenance.php">'.get_string('maintenancemode', 'admin').'</a> '.$button;
2637 if(!empty($title)) {
2638 $title .= ' - ';
2640 $title .= get_string('maintenancemode', 'admin');
2643 if (!$menu and $navigation) {
2644 if (empty($CFG->loginhttps)) {
2645 $wwwroot = $CFG->wwwroot;
2646 } else {
2648 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
2650 $menu = user_login_string($COURSE);
2653 if (isset($SESSION->justloggedin)) {
2654 unset($SESSION->justloggedin);
2655 if (!empty($CFG->displayloginfailures)) {
2656 if (!empty($USER->username) and $USER->username != 'guest') {
2657 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
2658 $menu .= '&nbsp;<font size="1">';
2659 if (empty($count->accounts)) {
2660 $menu .= get_string('failedloginattempts', '', $count);
2661 } else {
2662 $menu .= get_string('failedloginattemptsall', '', $count);
2664 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM))) {
2665 $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
2666 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
2668 $menu .= '</font>';
2675 $meta = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' .
2676 "\n" . $meta . "\n";
2677 if (!$usexml) {
2678 @header('Content-Type: text/html; charset=utf-8');
2680 @header('Content-Script-Type: text/javascript');
2681 @header('Content-Style-Type: text/css');
2683 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2684 $direction = get_html_lang($dir=true);
2686 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2687 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2688 @header('Pragma: no-cache');
2689 @header('Expires: ');
2690 } else { // Do everything we can to always prevent clients and proxies caching
2691 @header('Cache-Control: no-store, no-cache, must-revalidate');
2692 @header('Cache-Control: post-check=0, pre-check=0', false);
2693 @header('Pragma: no-cache');
2694 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2695 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2697 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2698 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
2700 @header('Accept-Ranges: none');
2702 $currentlanguage = current_language();
2704 if (empty($usexml)) {
2705 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2706 } else {
2707 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2708 if(!$mathplayer) {
2709 header('Content-Type: application/xhtml+xml');
2711 echo '<?xml version="1.0" ?>'."\n";
2712 if (!empty($CFG->xml_stylesheets)) {
2713 $stylesheets = explode(';', $CFG->xml_stylesheets);
2714 foreach ($stylesheets as $stylesheet) {
2715 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
2718 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
2719 if (!empty($CFG->xml_doctype_extra)) {
2720 echo ' plus '. $CFG->xml_doctype_extra;
2722 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
2723 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2724 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
2725 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2726 $direction";
2727 if($mathplayer) {
2728 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
2729 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2730 $meta .= '</object>'."\n";
2731 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2735 // Clean up the title
2737 $title = format_string($title); // fix for MDL-8582
2738 $title = str_replace('"', '&quot;', $title);
2740 // Create class and id for this page
2742 page_id_and_class($pageid, $pageclass);
2744 $pageclass .= ' course-'.$COURSE->id;
2746 if (!isloggedin()) {
2747 $pageclass .= ' notloggedin';
2750 if (!empty($USER->editing)) {
2751 $pageclass .= ' editing';
2754 if (!empty($CFG->blocksdrag)) {
2755 $pageclass .= ' drag';
2758 $pageclass .= ' dir-'.get_string('thisdirection');
2760 $pageclass .= ' lang-'.$currentlanguage;
2762 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
2764 ob_start();
2765 include($CFG->header);
2766 $output = ob_get_contents();
2767 ob_end_clean();
2769 // container debugging info
2770 $THEME->open_header_containers = open_containers();
2772 // Skip to main content, see skip_main_destination().
2773 if ($pageid=='course-view' or $pageid=='site-index' or $pageid=='course-index') {
2774 $skiplink = '<a class="skip" href="#maincontent">'.get_string('tocontent', 'access').'</a>';
2775 if (! preg_match('/(.*<div[^>]+id="page"[^>]*>)(.*)/s', $output, $matches)) {
2776 preg_match('/(.*<body.*?>)(.*)/s', $output, $matches);
2778 $output = $matches[1]."\n". $skiplink .$matches[2];
2781 $output = force_strict_header($output);
2783 if (!empty($CFG->messaging)) {
2784 $output .= message_popup_window();
2787 // Add in any extra JavaScript libraries that occurred during the header
2788 $output .= require_js('', 2);
2790 if ($return) {
2791 return $output;
2792 } else {
2793 echo $output;
2798 * Used to include JavaScript libraries.
2800 * When the $lib parameter is given, the function will ensure that the
2801 * named library is loaded onto the page - either in the HTML <head>,
2802 * just after the header, or at an arbitrary later point in the page,
2803 * depending on where this function is called.
2805 * Libraries will not be included more than once, so this works like
2806 * require_once in PHP.
2808 * There are two special-case calls to this function which are both used only
2809 * by weblib print_header:
2810 * $extracthtml = 1: this is used before printing the header.
2811 * It returns the script tag code that should go inside the <head>.
2812 * $extracthtml = 2: this is used after printing the header and handles any
2813 * require_js calls that occurred within the header itself.
2815 * @param mixed $lib - string or array of strings
2816 * string(s) should be the shortname for the library or the
2817 * full path to the library file.
2818 * @param int $extracthtml Do not set this parameter usually (leave 0), only
2819 * weblib should set this to 1 or 2 in print_header function.
2820 * @return mixed No return value, except when using $extracthtml it returns the html code.
2822 function require_js($lib,$extracthtml=0) {
2823 global $CFG;
2824 static $loadlibs = array();
2826 static $state = REQUIREJS_BEFOREHEADER;
2827 static $latecode = '';
2829 if (!empty($lib)) {
2830 // Add the lib to the list of libs to be loaded, if it isn't already
2831 // in the list.
2832 if (is_array($lib)) {
2833 foreach($lib as $singlelib) {
2834 require_js($singlelib);
2836 } else {
2837 $libpath = ajax_get_lib($lib);
2838 if (array_search($libpath, $loadlibs) === false) {
2839 $loadlibs[] = $libpath;
2841 // For state other than 0 we need to take action as well as just
2842 // adding it to loadlibs
2843 if($state != REQUIREJS_BEFOREHEADER) {
2844 // Get the script statement for this library
2845 $scriptstatement=get_require_js_code(array($libpath));
2847 if($state == REQUIREJS_AFTERHEADER) {
2848 // After the header, print it immediately
2849 print $scriptstatement;
2850 } else {
2851 // Haven't finished the header yet. Add it after the
2852 // header
2853 $latecode .= $scriptstatement;
2858 } else if($extracthtml==1) {
2859 if($state !== REQUIREJS_BEFOREHEADER) {
2860 debugging('Incorrect state in require_js (expected BEFOREHEADER): be careful not to call with empty $lib (except in print_header)');
2861 } else {
2862 $state = REQUIREJS_INHEADER;
2865 return get_require_js_code($loadlibs);
2866 } else if($extracthtml==2) {
2867 if($state !== REQUIREJS_INHEADER) {
2868 debugging('Incorrect state in require_js (expected INHEADER): be careful not to call with empty $lib (except in print_header)');
2869 return '';
2870 } else {
2871 $state = REQUIREJS_AFTERHEADER;
2872 return $latecode;
2874 } else {
2875 debugging('Unexpected value for $extracthtml');
2880 * Should not be called directly - use require_js. This function obtains the code
2881 * (script tags) needed to include JavaScript libraries.
2882 * @param array $loadlibs Array of library files to include
2883 * @return string HTML code to include them
2885 function get_require_js_code($loadlibs) {
2886 global $CFG;
2887 // Return the html needed to load the JavaScript files defined in
2888 // our list of libs to be loaded.
2889 $output = '';
2890 foreach ($loadlibs as $loadlib) {
2891 $output .= '<script type="text/javascript" ';
2892 $output .= " src=\"$loadlib\"></script>\n";
2893 if ($loadlib == $CFG->wwwroot.'/lib/yui/logger/logger-min.js') {
2894 // Special case, we need the CSS too.
2895 $output .= '<link type="text/css" rel="stylesheet" ';
2896 $output .= " href=\"{$CFG->wwwroot}/lib/yui/logger/assets/logger.css\" />\n";
2899 return $output;
2904 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2905 * and substitute the XHTML strict document type.
2906 * Note, requires the 'xmlns' fix in function print_header above.
2907 * See: http://tracker.moodle.org/browse/MDL-7883
2908 * TODO:
2910 function force_strict_header($output) {
2911 global $CFG;
2912 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2913 $xsl = '/lib/xhtml.xsl';
2915 if (!headers_sent() && !empty($CFG->xmlstrictheaders)) { // With xml strict headers, the browser will barf
2916 $ctype = 'Content-Type: ';
2917 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2919 if (isset($_SERVER['HTTP_ACCEPT'])
2920 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2921 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2922 // Firefox et al.
2923 $ctype .= 'application/xhtml+xml';
2924 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2926 } else if (file_exists($CFG->dirroot.$xsl)
2927 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2928 // XSL hack for IE 5+ on Windows.
2929 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2930 $www_xsl = $CFG->wwwroot .$xsl;
2931 $ctype .= 'application/xml';
2932 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2933 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2935 } else {
2936 //ELSE: Mac/IE, old/non-XML browsers.
2937 $ctype .= 'text/html';
2938 $prolog = '';
2940 @header($ctype.'; charset=utf-8');
2941 $output = $prolog . $output;
2943 // Test parser error-handling.
2944 if (isset($_GET['error'])) {
2945 $output .= "__ TEST: XML well-formed error < __\n";
2949 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
2951 return $output;
2957 * This version of print_header is simpler because the course name does not have to be
2958 * provided explicitly in the strings. It can be used on the site page as in courses
2959 * Eventually all print_header could be replaced by print_header_simple
2961 * @param string $title Appears at the top of the window
2962 * @param string $heading Appears at the top of the page
2963 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2964 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2965 * @param string $meta Meta tags to be added to the header
2966 * @param boolean $cache Should this page be cacheable?
2967 * @param string $button HTML code for a button (usually for module editing)
2968 * @param string $menu HTML code for a popup menu
2969 * @param boolean $usexml use XML for this page
2970 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2971 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2973 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
2974 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
2976 global $COURSE, $CFG;
2978 // if we have no navigation specified, build it
2979 if( empty($navigation) ){
2980 $navigation = build_navigation('');
2983 // If old style nav prepend course short name otherwise leave $navigation object alone
2984 if (!is_newnav($navigation)) {
2985 if ($COURSE->id != SITEID) {
2986 $shortname = '<a href="'.$CFG->wwwroot.'/course/view.php?id='. $COURSE->id .'">'. $COURSE->shortname .'</a> ->';
2987 $navigation = $shortname.' '.$navigation;
2991 $output = print_header($COURSE->shortname .': '. $title, $COURSE->fullname .' '. $heading, $navigation, $focus, $meta,
2992 $cache, $button, $menu, $usexml, $bodytags, true);
2994 if ($return) {
2995 return $output;
2996 } else {
2997 echo $output;
3003 * Can provide a course object to make the footer contain a link to
3004 * to the course home page, otherwise the link will go to the site home
3005 * @uses $USER
3006 * @param mixed $course course object, used for course link button or
3007 * 'none' means no user link, only docs link
3008 * 'empty' means nothing printed in footer
3009 * 'home' special frontpage footer
3010 * @param object $usercourse course used in user link
3011 * @param boolean $return output as string
3012 * @return mixed string or void
3014 function print_footer($course=NULL, $usercourse=NULL, $return=false) {
3015 global $USER, $CFG, $THEME, $COURSE;
3017 if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
3018 admin_externalpage_print_footer();
3019 return;
3022 /// Course links or special footer
3023 if ($course) {
3024 if ($course === 'empty') {
3025 // special hack - sometimes we do not want even the docs link in footer
3026 $output = '';
3027 if (!empty($THEME->open_header_containers)) {
3028 for ($i=0; $i<$THEME->open_header_containers; $i++) {
3029 $output .= print_container_end_all(); // containers opened from header
3031 } else {
3032 //1.8 theme compatibility
3033 $output .= "\n</div>"; // content div
3035 $output .= "\n</div>\n</body>\n</html>"; // close page div started in header
3036 if ($return) {
3037 return $output;
3038 } else {
3039 echo $output;
3040 return;
3043 } else if ($course === 'none') { // Don't print any links etc
3044 $homelink = '';
3045 $loggedinas = '';
3046 $home = false;
3048 } else if ($course === 'home') { // special case for site home page - please do not remove
3049 $course = get_site();
3050 $homelink = '<div class="sitelink">'.
3051 '<a title="Moodle" href="http://moodle.org/">'.
3052 '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
3053 $home = true;
3055 } else {
3056 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
3057 '/course/view.php?id='.$course->id.'">'.format_string($course->shortname).'</a></div>';
3058 $home = false;
3061 } else {
3062 $course = get_site(); // Set course as site course by default
3063 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
3064 $home = false;
3067 /// Set up some other navigation links (passed from print_header by ugly hack)
3068 $menu = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
3069 $title = isset($THEME->title) ? $THEME->title : '';
3070 $button = isset($THEME->button) ? $THEME->button : '';
3071 $heading = isset($THEME->heading) ? $THEME->heading : '';
3072 $navigation = isset($THEME->navigation) ? $THEME->navigation : '';
3073 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
3076 /// Set the user link if necessary
3077 if (!$usercourse and is_object($course)) {
3078 $usercourse = $course;
3081 if (!isset($loggedinas)) {
3082 $loggedinas = user_login_string($usercourse, $USER);
3085 if ($loggedinas == $menu) {
3086 $menu = '';
3089 /// there should be exactly the same number of open containers as after the header
3090 if ($THEME->open_header_containers != open_containers()) {
3091 debugging('Unexpected number of open containers: '.open_containers().', expecting '.$THEME->open_header_containers, DEBUG_DEVELOPER);
3094 /// Provide some performance info if required
3095 $performanceinfo = '';
3096 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
3097 $perf = get_performance_info();
3098 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
3099 error_log("PERF: " . $perf['txt']);
3101 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
3102 $performanceinfo = $perf['html'];
3106 /// Include the actual footer file
3108 ob_start();
3109 include($CFG->footer);
3110 $output = ob_get_contents();
3111 ob_end_clean();
3113 if ($return) {
3114 return $output;
3115 } else {
3116 echo $output;
3121 * Returns the name of the current theme
3123 * @uses $CFG
3124 * @uses $USER
3125 * @uses $SESSION
3126 * @uses $COURSE
3127 * @uses $FULLME
3128 * @return string
3130 function current_theme() {
3131 global $CFG, $USER, $SESSION, $COURSE, $FULLME;
3133 if (empty($CFG->themeorder)) {
3134 $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
3135 } else {
3136 $themeorder = $CFG->themeorder;
3139 if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id) {
3140 require_once($CFG->dirroot.'/mnet/peer.php');
3141 $mnet_peer = new mnet_peer();
3142 $mnet_peer->set_id($USER->mnethostid);
3145 $theme = '';
3146 foreach ($themeorder as $themetype) {
3148 if (!empty($theme)) continue;
3150 switch ($themetype) {
3151 case 'page': // Page theme is for special page-only themes set by code
3152 if (!empty($CFG->pagetheme)) {
3153 $theme = $CFG->pagetheme;
3155 break;
3156 case 'course':
3157 if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) {
3158 $theme = $COURSE->theme;
3160 break;
3161 case 'category':
3162 if (!empty($CFG->allowcategorythemes)) {
3163 /// Nasty hack to check if we're in a category page
3164 if (stripos($FULLME, 'course/category.php') !== false) {
3165 global $id;
3166 if (!empty($id)) {
3167 $theme = current_category_theme($id);
3169 /// Otherwise check if we're in a course that has a category theme set
3170 } else if (!empty($COURSE->category)) {
3171 $theme = current_category_theme($COURSE->category);
3174 break;
3175 case 'session':
3176 if (!empty($SESSION->theme)) {
3177 $theme = $SESSION->theme;
3179 break;
3180 case 'user':
3181 if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) {
3182 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
3183 $theme = $mnet_peer->theme;
3184 } else {
3185 $theme = $USER->theme;
3188 break;
3189 case 'site':
3190 if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
3191 $theme = $mnet_peer->theme;
3192 } else {
3193 $theme = $CFG->theme;
3195 break;
3196 default:
3197 /// do nothing
3201 /// A final check in case 'site' was not included in $CFG->themeorder
3202 if (empty($theme)) {
3203 $theme = $CFG->theme;
3206 return $theme;
3210 * Retrieves the category theme if one exists, otherwise checks the parent categories.
3211 * Recursive function.
3213 * @uses $COURSE
3214 * @param integer $categoryid id of the category to check
3215 * @return string theme name
3217 function current_category_theme($categoryid=0) {
3218 global $COURSE;
3220 /// Use the COURSE global if the categoryid not set
3221 if (empty($categoryid)) {
3222 if (!empty($COURSE->category)) {
3223 $categoryid = $COURSE->category;
3224 } else {
3225 return false;
3229 /// Retrieve the current category
3230 if ($category = get_record('course_categories', 'id', $categoryid)) {
3232 /// Return the category theme if it exists
3233 if (!empty($category->theme)) {
3234 return $category->theme;
3236 /// Otherwise try the parent category if one exists
3237 } else if (!empty($category->parent)) {
3238 return current_category_theme($category->parent);
3241 /// Return false if we can't find the category record
3242 } else {
3243 return false;
3248 * This function is called by stylesheets to set up the header
3249 * approriately as well as the current path
3251 * @uses $CFG
3252 * @param int $lastmodified ?
3253 * @param int $lifetime ?
3254 * @param string $thename ?
3256 function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
3258 global $CFG, $THEME;
3260 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
3261 $lastmodified = time();
3263 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
3264 header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
3265 header('Cache-Control: max-age='. $lifetime);
3266 header('Pragma: ');
3267 header('Content-type: text/css'); // Correct MIME type
3269 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
3271 if (empty($themename)) {
3272 $themename = current_theme(); // So we have something. Normally not needed.
3273 } else {
3274 $themename = clean_param($themename, PARAM_SAFEDIR);
3277 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
3278 unset($THEME);
3279 include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
3282 /// If this is the standard theme calling us, then find out what sheets we need
3284 if ($themename == 'standard') {
3285 if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
3286 $THEME->sheets = $DEFAULT_SHEET_LIST;
3287 } else if (empty($THEME->standardsheets)) { // We can stop right now!
3288 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3289 exit;
3290 } else { // Use the provided subset only
3291 $THEME->sheets = $THEME->standardsheets;
3294 /// If we are a parent theme, then check for parent definitions
3296 } else if (!empty($THEME->parent) && $themename == $THEME->parent) {
3297 if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have
3298 $THEME->sheets = $DEFAULT_SHEET_LIST;
3299 } else if (empty($THEME->parentsheets)) { // We can stop right now!
3300 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3301 exit;
3302 } else { // Use the provided subset only
3303 $THEME->sheets = $THEME->parentsheets;
3307 /// Work out the last modified date for this theme
3309 foreach ($THEME->sheets as $sheet) {
3310 if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
3311 $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
3312 if ($sheetmodified > $lastmodified) {
3313 $lastmodified = $sheetmodified;
3319 /// Get a list of all the files we want to include
3320 $files = array();
3322 foreach ($THEME->sheets as $sheet) {
3323 $files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
3326 if ($themename == 'standard') { // Add any standard styles included in any modules
3327 if (!empty($THEME->modsheets)) { // Search for styles.php within activity modules
3328 if ($mods = get_list_of_plugins('mod')) {
3329 foreach ($mods as $mod) {
3330 if (file_exists($CFG->dirroot.'/mod/'.$mod.'/styles.php')) {
3331 $files[] = array($CFG->dirroot, '/mod/'.$mod.'/styles.php');
3337 if (!empty($THEME->blocksheets)) { // Search for styles.php within block modules
3338 if ($mods = get_list_of_plugins('blocks')) {
3339 foreach ($mods as $mod) {
3340 if (file_exists($CFG->dirroot.'/blocks/'.$mod.'/styles.php')) {
3341 $files[] = array($CFG->dirroot, '/blocks/'.$mod.'/styles.php');
3347 if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
3348 if ($mods = get_list_of_plugins('format','',$CFG->dirroot.'/course')) {
3349 foreach ($mods as $mod) {
3350 if (file_exists($CFG->dirroot.'/course/format/'.$mod.'/styles.php')) {
3351 $files[] = array($CFG->dirroot, '/course/format/'.$mod.'/styles.php');
3357 if (!isset($THEME->gradereportsheets) || $THEME->gradereportsheets) { // Search for styles.php in grade reports
3358 if ($reports = get_list_of_plugins('grade/report')) {
3359 foreach ($reports as $report) {
3360 if (file_exists($CFG->dirroot.'/grade/report/'.$report.'/styles.php')) {
3361 $files[] = array($CFG->dirroot, '/grade/report/'.$report.'/styles.php');
3367 if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
3368 if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
3369 $files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
3374 if ($files) {
3375 /// Produce a list of all the files first
3376 echo '/**************************************'."\n";
3377 echo ' * THEME NAME: '.$themename."\n *\n";
3378 echo ' * Files included in this sheet:'."\n *\n";
3379 foreach ($files as $file) {
3380 echo ' * '.$file[1]."\n";
3382 echo ' **************************************/'."\n\n";
3385 /// check if csscobstants is set
3386 if (!empty($THEME->cssconstants)) {
3387 require_once("$CFG->libdir/cssconstants.php");
3388 /// Actually collect all the files in order.
3389 $css = '';
3390 foreach ($files as $file) {
3391 $css .= '/***** '.$file[1].' start *****/'."\n\n";
3392 $css .= file_get_contents($file[0].'/'.$file[1]);
3393 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
3395 /// replace css_constants with their values
3396 echo replace_cssconstants($css);
3397 } else {
3398 /// Actually output all the files in order.
3399 if (empty($CFG->CSSEdit) && empty($THEME->CSSEdit)) {
3400 foreach ($files as $file) {
3401 echo '/***** '.$file[1].' start *****/'."\n\n";
3402 @include_once($file[0].'/'.$file[1]);
3403 echo '/***** '.$file[1].' end *****/'."\n\n";
3405 } else {
3406 foreach ($files as $file) {
3407 echo '/* @group '.$file[1].' */'."\n\n";
3408 if (strstr($file[1], '.css') !== FALSE) {
3409 echo '@import url("'.$CFG->themewww.'/'.$file[1].'");'."\n\n";
3410 } else {
3411 @include_once($file[0].'/'.$file[1]);
3413 echo '/* @end */'."\n\n";
3419 return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
3423 function theme_setup($theme = '', $params=NULL) {
3424 /// Sets up global variables related to themes
3426 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
3428 /// Do not mess with THEME if header already printed - this would break all the extra stuff in global $THEME from print_header()!!
3429 if (defined('HEADER_PRINTED')) {
3430 return;
3433 if (empty($theme)) {
3434 $theme = current_theme();
3437 /// If the theme doesn't exist for some reason then revert to standardwhite
3438 if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
3439 $CFG->theme = $theme = 'standardwhite';
3442 /// Load up the theme config
3443 $THEME = NULL; // Just to be sure
3444 include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
3446 /// Put together the parameters
3447 if (!$params) {
3448 $params = array();
3451 if ($theme != $CFG->theme) {
3452 $params[] = 'forceconfig='.$theme;
3455 /// Force language too if required
3456 if (!empty($THEME->langsheets)) {
3457 $params[] = 'lang='.current_language();
3461 /// Convert params to string
3462 if ($params) {
3463 $paramstring = '?'.implode('&', $params);
3464 } else {
3465 $paramstring = '';
3468 /// Set up image paths
3469 if(isset($CFG->smartpix) && $CFG->smartpix==1) {
3470 if($CFG->slasharguments) { // Use this method if possible for better caching
3471 $extra='';
3472 } else {
3473 $extra='?file=';
3476 $CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
3477 $CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
3478 } else if (empty($THEME->custompix)) { // Could be set in the above file
3479 $CFG->pixpath = $CFG->wwwroot .'/pix';
3480 $CFG->modpixpath = $CFG->wwwroot .'/mod';
3481 } else {
3482 $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
3483 $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
3486 /// Header and footer paths
3487 $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
3488 $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
3490 /// Define stylesheet loading order
3491 $CFG->stylesheets = array();
3492 if ($theme != 'standard') { /// The standard sheet is always loaded first
3493 $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
3495 if (!empty($THEME->parent)) { /// Parent stylesheets are loaded next
3496 $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
3498 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
3500 /// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
3501 if (!empty($HTTPSPAGEREQUIRED)) {
3502 $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
3503 $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
3504 $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
3505 foreach ($CFG->stylesheets as $key => $stylesheet) {
3506 $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
3510 // RTL support - only for RTL languages, add RTL CSS
3511 if (get_string('thisdirection') == 'rtl') {
3512 $CFG->stylesheets[] = $CFG->themewww.'/standard/rtl.css'.$paramstring;
3513 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/rtl.css'.$paramstring;
3519 * Returns text to be displayed to the user which reflects their login status
3521 * @uses $CFG
3522 * @uses $USER
3523 * @param course $course {@link $COURSE} object containing course information
3524 * @param user $user {@link $USER} object containing user information
3525 * @return string
3527 function user_login_string($course=NULL, $user=NULL) {
3528 global $USER, $CFG, $SITE;
3530 if (empty($user) and !empty($USER->id)) {
3531 $user = $USER;
3534 if (empty($course)) {
3535 $course = $SITE;
3538 if (!empty($user->realuser)) {
3539 if ($realuser = get_record('user', 'id', $user->realuser)) {
3540 $fullname = fullname($realuser, true);
3541 $realuserinfo = " [<a $CFG->frametarget
3542 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=1&amp;sesskey=".sesskey()."\">$fullname</a>] ";
3544 } else {
3545 $realuserinfo = '';
3548 if (empty($CFG->loginhttps)) {
3549 $wwwroot = $CFG->wwwroot;
3550 } else {
3551 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
3554 if (empty($course->id)) {
3555 // $course->id is not defined during installation
3556 return '';
3557 } else if (!empty($user->id)) {
3558 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3560 $fullname = fullname($user, true);
3561 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a>";
3562 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid)) {
3563 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
3565 if (isset($user->username) && $user->username == 'guest') {
3566 $loggedinas = $realuserinfo.get_string('loggedinasguest').
3567 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3568 } else if (!empty($user->access['rsw'][$context->path])) {
3569 $rolename = '';
3570 if ($role = get_record('role', 'id', $user->access['rsw'][$context->path])) {
3571 $rolename = join("", role_fix_names(array($role->id=>$role->name), $context));
3572 $rolename = ': '.format_string($rolename);
3574 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
3575 " (<a $CFG->frametarget
3576 href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
3577 } else {
3578 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
3579 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
3581 } else {
3582 $loggedinas = get_string('loggedinnot', 'moodle').
3583 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3585 return '<div class="logininfo">'.$loggedinas.'</div>';
3589 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
3590 * If not it applies sensible defaults.
3592 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
3593 * search forum block, etc. Important: these are 'silent' in a screen-reader
3594 * (unlike &gt; &raquo;), and must be accompanied by text.
3595 * @uses $THEME
3597 function check_theme_arrows() {
3598 global $THEME;
3600 if (!isset($THEME->rarrow) and !isset($THEME->larrow)) {
3601 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
3602 // Also OK in Win 9x/2K/IE 5.x
3603 $THEME->rarrow = '&#x25BA;';
3604 $THEME->larrow = '&#x25C4;';
3605 if (empty($_SERVER['HTTP_USER_AGENT'])) {
3606 $uagent = '';
3607 } else {
3608 $uagent = $_SERVER['HTTP_USER_AGENT'];
3610 if (false !== strpos($uagent, 'Opera')
3611 || false !== strpos($uagent, 'Mac')) {
3612 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
3613 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
3614 $THEME->rarrow = '&#x25B6;';
3615 $THEME->larrow = '&#x25C0;';
3617 elseif (false !== strpos($uagent, 'Konqueror')) {
3618 $THEME->rarrow = '&rarr;';
3619 $THEME->larrow = '&larr;';
3621 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
3622 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
3623 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
3624 // To be safe, non-Unicode browsers!
3625 $THEME->rarrow = '&gt;';
3626 $THEME->larrow = '&lt;';
3629 /// RTL support - in RTL languages, swap r and l arrows
3630 if (right_to_left()) {
3631 $t = $THEME->rarrow;
3632 $THEME->rarrow = $THEME->larrow;
3633 $THEME->larrow = $t;
3640 * Return the right arrow with text ('next'), and optionally embedded in a link.
3641 * See function above, check_theme_arrows.
3642 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3643 * @param string $url An optional link to use in a surrounding HTML anchor.
3644 * @param bool $accesshide True if text should be hidden (for screen readers only).
3645 * @param string $addclass Additional class names for the link, or the arrow character.
3646 * @return string HTML string.
3648 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
3649 global $THEME;
3650 check_theme_arrows();
3651 $arrowclass = 'arrow ';
3652 if (! $url) {
3653 $arrowclass .= $addclass;
3655 $arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow.'</span>';
3656 $htmltext = '';
3657 if ($text) {
3658 $htmltext = $text.'&nbsp;';
3659 if ($accesshide) {
3660 $htmltext = get_accesshide($htmltext);
3663 if ($url) {
3664 $class = '';
3665 if ($addclass) {
3666 $class =" class=\"$addclass\"";
3668 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
3670 return $htmltext.$arrow;
3674 * Return the left arrow with text ('previous'), and optionally embedded in a link.
3675 * See function above, check_theme_arrows.
3676 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3677 * @param string $url An optional link to use in a surrounding HTML anchor.
3678 * @param bool $accesshide True if text should be hidden (for screen readers only).
3679 * @param string $addclass Additional class names for the link, or the arrow character.
3680 * @return string HTML string.
3682 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
3683 global $THEME;
3684 check_theme_arrows();
3685 $arrowclass = 'arrow ';
3686 if (! $url) {
3687 $arrowclass .= $addclass;
3689 $arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow.'</span>';
3690 $htmltext = '';
3691 if ($text) {
3692 $htmltext = '&nbsp;'.$text;
3693 if ($accesshide) {
3694 $htmltext = get_accesshide($htmltext);
3697 if ($url) {
3698 $class = '';
3699 if ($addclass) {
3700 $class =" class=\"$addclass\"";
3702 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
3704 return $arrow.$htmltext;
3708 * Return a HTML element with the class "accesshide", for accessibility.
3709 * Please use cautiously - where possible, text should be visible!
3710 * @param string $text Plain text.
3711 * @param string $elem Lowercase element name, default "span".
3712 * @param string $class Additional classes for the element.
3713 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
3714 * @return string HTML string.
3716 function get_accesshide($text, $elem='span', $class='', $attrs='') {
3717 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
3721 * Return the breadcrumb trail navigation separator.
3722 * @return string HTML string.
3724 function get_separator() {
3725 //Accessibility: the 'hidden' slash is preferred for screen readers.
3726 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
3730 * Prints breadcrumb trail of links, called in theme/-/header.html
3732 * @uses $CFG
3733 * @param mixed $navigation The breadcrumb navigation string to be printed
3734 * @param string $separator OBSOLETE, mostly not used any more. See build_navigation instead.
3735 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
3736 * @return string or null, depending on $return.
3738 function print_navigation ($navigation, $separator=0, $return=false) {
3739 global $CFG, $THEME;
3740 $output = '';
3742 if (0 === $separator) {
3743 $separator = get_separator();
3745 else {
3746 $separator = '<span class="sep">'. $separator .'</span>';
3749 if ($navigation) {
3751 if (is_newnav($navigation)) {
3752 if ($return) {
3753 return($navigation['navlinks']);
3754 } else {
3755 echo $navigation['navlinks'];
3756 return;
3758 } else {
3759 debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER);
3762 if (!is_array($navigation)) {
3763 $ar = explode('->', $navigation);
3764 $navigation = array();
3766 foreach ($ar as $a) {
3767 if (strpos($a, '</a>') === false) {
3768 $navigation[] = array('title' => $a, 'url' => '');
3769 } else {
3770 if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
3771 $navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
3777 if (! $site = get_site()) {
3778 $site = new object();
3779 $site->shortname = get_string('home');
3782 //Accessibility: breadcrumb links now in a list, &raquo; replaced with a 'silent' character.
3783 $output .= get_accesshide(get_string('youarehere','access'), 'h2')."<ul>\n";
3785 $output .= '<li class="first">'."\n".'<a '.$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3786 .$CFG->wwwroot.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))
3787 && !empty($USER->id) && !empty($CFG->mymoodleredirect) && !isguest())
3788 ? '/my' : '') .'/">'. format_string($site->shortname) ."</a>\n</li>\n";
3791 foreach ($navigation as $navitem) {
3792 $title = trim(strip_tags(format_string($navitem['title'], false)));
3793 $url = $navitem['url'];
3795 if (empty($url)) {
3796 $output .= '<li>'."$separator $title</li>\n";
3797 } else {
3798 $output .= '<li>'."$separator\n<a ".$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3799 .$url.'">'."$title</a>\n</li>\n";
3803 $output .= "</ul>\n";
3806 if ($return) {
3807 return $output;
3808 } else {
3809 echo $output;
3814 * This function will build the navigation string to be used by print_header
3815 * and others.
3817 * It automatically generates the site and course level (if appropriate) links.
3819 * If you pass in a $cm object, the method will also generate the activity (e.g. 'Forums')
3820 * and activityinstances (e.g. 'General Developer Forum') navigation levels.
3822 * If you want to add any further navigation links after the ones this function generates,
3823 * the pass an array of extra link arrays like this:
3824 * array(
3825 * array('name' => $linktext1, 'link' => $url1, 'type' => $linktype1),
3826 * array('name' => $linktext2, 'link' => $url2, 'type' => $linktype2)
3828 * The normal case is to just add one further link, for example 'Editing forum' after
3829 * 'General Developer Forum', with no link.
3830 * To do that, you need to pass
3831 * array(array('name' => $linktext, 'link' => '', 'type' => 'title'))
3832 * However, becuase this is a very common case, you can use a shortcut syntax, and just
3833 * pass the string 'Editing forum', instead of an array as $extranavlinks.
3835 * At the moment, the link types only have limited significance. Type 'activity' is
3836 * recognised in order to implement the $CFG->hideactivitytypenavlink feature. Types
3837 * that are known to appear are 'home', 'course', 'activity', 'activityinstance' and 'title'.
3838 * This really needs to be documented better. In the mean time, try to be consistent, it will
3839 * enable people to customise the navigation more in future.
3841 * When passing a $cm object, the fields used are $cm->modname, $cm->name and $cm->course.
3842 * If you get the $cm object using the function get_coursemodule_from_instance or
3843 * get_coursemodule_from_id (as recommended) then this will be done for you automatically.
3844 * If you don't have $cm->modname or $cm->name, this fuction will attempt to find them using
3845 * the $cm->module and $cm->instance fields, but this takes extra database queries, so a
3846 * warning is printed in developer debug mode.
3848 * @uses $CFG
3849 * @uses $THEME
3851 * @param mixed $extranavlinks - Normally an array of arrays, keys: name, link, type. If you
3852 * only want one extra item with no link, you can pass a string instead. If you don't want
3853 * any extra links, pass an empty string.
3854 * @param mixed $cm - optionally the $cm object, if you want this function to generate the
3855 * activity and activityinstance levels of navigation too.
3857 * @return $navigation as an object so it can be differentiated from old style
3858 * navigation strings.
3860 function build_navigation($extranavlinks, $cm = null) {
3861 global $CFG, $COURSE;
3863 if (is_string($extranavlinks)) {
3864 if ($extranavlinks == '') {
3865 $extranavlinks = array();
3866 } else {
3867 $extranavlinks = array(array('name' => $extranavlinks, 'link' => '', 'type' => 'title'));
3871 $navlinks = array();
3873 //Site name
3874 if ($site = get_site()) {
3875 $navlinks[] = array(
3876 'name' => format_string($site->shortname),
3877 'link' => "$CFG->wwwroot/",
3878 'type' => 'home');
3881 // Course name, if appropriate.
3882 if (isset($COURSE) && $COURSE->id != SITEID) {
3883 $navlinks[] = array(
3884 'name' => format_string($COURSE->shortname),
3885 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",
3886 'type' => 'course');
3889 // Activity type and instance, if appropriate.
3890 if (is_object($cm)) {
3891 if (!isset($cm->modname)) {
3892 debugging('The field $cm->modname should be set if you call build_navigation with '.
3893 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3894 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
3895 if (!$cm->modname = get_field('modules', 'name', 'id', $cm->module)) {
3896 error('Cannot get the module type in build navigation.');
3899 if (!isset($cm->name)) {
3900 debugging('The field $cm->name should be set if you call build_navigation with '.
3901 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3902 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
3903 if (!$cm->name = get_field($cm->modname, 'name', 'id', $cm->instance)) {
3904 error('Cannot get the module name in build navigation.');
3907 $navlinks[] = array(
3908 'name' => get_string('modulenameplural', $cm->modname),
3909 'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/index.php?id=' . $cm->course,
3910 'type' => 'activity');
3911 $navlinks[] = array(
3912 'name' => format_string($cm->name),
3913 'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/view.php?id=' . $cm->id,
3914 'type' => 'activityinstance');
3917 //Merge in extra navigation links
3918 $navlinks = array_merge($navlinks, $extranavlinks);
3920 // Work out whether we should be showing the activity (e.g. Forums) link.
3921 // Note: build_navigation() is called from many places --
3922 // install & upgrade for example -- where we cannot count on the
3923 // roles infrastructure to be defined. Hence the $CFG->rolesactive check.
3924 if (!isset($CFG->hideactivitytypenavlink)) {
3925 $CFG->hideactivitytypenavlink = 0;
3927 if ($CFG->hideactivitytypenavlink == 2) {
3928 $hideactivitylink = true;
3929 } else if ($CFG->hideactivitytypenavlink == 1 && $CFG->rolesactive &&
3930 !empty($COURSE->id) && $COURSE->id != SITEID) {
3931 if (!isset($COURSE->context)) {
3932 $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
3934 $hideactivitylink = !has_capability('moodle/course:manageactivities', $COURSE->context);
3935 } else {
3936 $hideactivitylink = false;
3939 //Construct an unordered list from $navlinks
3940 //Accessibility: heading hidden from visual browsers by default.
3941 $navigation = get_accesshide(get_string('youarehere','access'), 'h2')." <ul>\n";
3942 $lastindex = count($navlinks) - 1;
3943 $i = -1; // Used to count the times, so we know when we get to the last item.
3944 $first = true;
3945 foreach ($navlinks as $navlink) {
3946 $i++;
3947 $last = ($i == $lastindex);
3948 if (!is_array($navlink)) {
3949 continue;
3951 if (!empty($navlink['type']) && $navlink['type'] == 'activity' && !$last && $hideactivitylink) {
3952 continue;
3954 if ($first) {
3955 $navigation .= '<li class="first">';
3956 } else {
3957 $navigation .= '<li>';
3959 if (!$first) {
3960 $navigation .= get_separator();
3962 if ((!empty($navlink['link'])) && !$last) {
3963 $navigation .= "<a $CFG->frametarget onclick=\"this.target='$CFG->framename'\" href=\"{$navlink['link']}\">";
3965 $navigation .= "{$navlink['name']}";
3966 if ((!empty($navlink['link'])) && !$last) {
3967 $navigation .= "</a>";
3970 $navigation .= "</li>";
3971 $first = false;
3973 $navigation .= "</ul>";
3975 return(array('newnav' => true, 'navlinks' => $navigation));
3980 * Prints a string in a specified size (retained for backward compatibility)
3982 * @param string $text The text to be displayed
3983 * @param int $size The size to set the font for text display.
3985 function print_headline($text, $size=2, $return=false) {
3986 $output = print_heading($text, '', $size, true);
3987 if ($return) {
3988 return $output;
3989 } else {
3990 echo $output;
3995 * Prints text in a format for use in headings.
3997 * @param string $text The text to be displayed
3998 * @param string $align The alignment of the printed paragraph of text
3999 * @param int $size The size to set the font for text display.
4001 function print_heading($text, $align='', $size=2, $class='main', $return=false) {
4002 if ($align) {
4003 $align = ' style="text-align:'.$align.';"';
4005 if ($class) {
4006 $class = ' class="'.$class.'"';
4008 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
4010 if ($return) {
4011 return $output;
4012 } else {
4013 echo $output;
4018 * Centered heading with attached help button (same title text)
4019 * and optional icon attached
4021 * @param string $text The text to be displayed
4022 * @param string $helppage The help page to link to
4023 * @param string $module The module whose help should be linked to
4024 * @param string $icon Image to display if needed
4026 function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
4027 $output = '';
4028 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
4029 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
4030 $output .= '</h2>';
4032 if ($return) {
4033 return $output;
4034 } else {
4035 echo $output;
4040 function print_heading_block($heading, $class='', $return=false) {
4041 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
4042 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
4044 if ($return) {
4045 return $output;
4046 } else {
4047 echo $output;
4053 * Print a link to continue on to another page.
4055 * @uses $CFG
4056 * @param string $link The url to create a link to.
4058 function print_continue($link, $return=false) {
4060 global $CFG;
4062 // in case we are logging upgrade in admin/index.php stop it
4063 if (function_exists('upgrade_log_finish')) {
4064 upgrade_log_finish();
4067 $output = '';
4069 if ($link == '') {
4070 if (!empty($_SERVER['HTTP_REFERER'])) {
4071 $link = $_SERVER['HTTP_REFERER'];
4072 $link = str_replace('&', '&amp;', $link); // make it valid XHTML
4073 } else {
4074 $link = $CFG->wwwroot .'/';
4078 $options = array();
4079 $linkparts = parse_url(str_replace('&amp;', '&', $link));
4080 if (isset($linkparts['query'])) {
4081 parse_str($linkparts['query'], $options);
4084 $output .= '<div class="continuebutton">';
4086 $output .= print_single_button($link, $options, get_string('continue'), 'get', $CFG->framename, true);
4087 $output .= '</div>'."\n";
4089 if ($return) {
4090 return $output;
4091 } else {
4092 echo $output;
4098 * Print a message in a standard themed box.
4099 * Replaces print_simple_box (see deprecatedlib.php)
4101 * @param string $message, the content of the box
4102 * @param string $classes, space-separated class names.
4103 * @param string $idbase
4104 * @param boolean $return, return as string or just print it
4105 * @return mixed string or void
4107 function print_box($message, $classes='generalbox', $ids='', $return=false) {
4109 $output = print_box_start($classes, $ids, true);
4110 $output .= stripslashes_safe($message);
4111 $output .= print_box_end(true);
4113 if ($return) {
4114 return $output;
4115 } else {
4116 echo $output;
4121 * Starts a box using divs
4122 * Replaces print_simple_box_start (see deprecatedlib.php)
4124 * @param string $classes, space-separated class names.
4125 * @param string $idbase
4126 * @param boolean $return, return as string or just print it
4127 * @return mixed string or void
4129 function print_box_start($classes='generalbox', $ids='', $return=false) {
4130 global $THEME;
4132 if (strpos($classes, 'clearfix') !== false) {
4133 $clearfix = true;
4134 $classes = trim(str_replace('clearfix', '', $classes));
4135 } else {
4136 $clearfix = false;
4139 if (!empty($THEME->customcorners)) {
4140 $classes .= ' ccbox box';
4141 } else {
4142 $classes .= ' box';
4145 return print_container_start($clearfix, $classes, $ids, $return);
4149 * Simple function to end a box (see above)
4150 * Replaces print_simple_box_end (see deprecatedlib.php)
4152 * @param boolean $return, return as string or just print it
4154 function print_box_end($return=false) {
4155 return print_container_end($return);
4159 * Print a message in a standard themed container.
4161 * @param string $message, the content of the container
4162 * @param boolean $clearfix clear both sides
4163 * @param string $classes, space-separated class names.
4164 * @param string $idbase
4165 * @param boolean $return, return as string or just print it
4166 * @return string or void
4168 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
4170 $output = print_container_start($clearfix, $classes, $idbase, true);
4171 $output .= stripslashes_safe($message);
4172 $output .= print_container_end(true);
4174 if ($return) {
4175 return $output;
4176 } else {
4177 echo $output;
4182 * Starts a container using divs
4184 * @param boolean $clearfix clear both sides
4185 * @param string $classes, space-separated class names.
4186 * @param string $idbase
4187 * @param boolean $return, return as string or just print it
4188 * @return mixed string or void
4190 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
4191 global $THEME;
4193 if (!isset($THEME->open_containers)) {
4194 $THEME->open_containers = array();
4196 $THEME->open_containers[] = $idbase;
4199 if (!empty($THEME->customcorners)) {
4200 $output = _print_custom_corners_start($clearfix, $classes, $idbase);
4201 } else {
4202 if ($idbase) {
4203 $id = ' id="'.$idbase.'"';
4204 } else {
4205 $id = '';
4207 if ($clearfix) {
4208 $clearfix = ' clearfix';
4209 } else {
4210 $clearfix = '';
4212 if ($classes or $clearfix) {
4213 $class = ' class="'.$classes.$clearfix.'"';
4214 } else {
4215 $class = '';
4217 $output = '<div'.$id.$class.'>';
4220 if ($return) {
4221 return $output;
4222 } else {
4223 echo $output;
4228 * Simple function to end a container (see above)
4229 * @param boolean $return, return as string or just print it
4230 * @return mixed string or void
4232 function print_container_end($return=false) {
4233 global $THEME;
4235 if (empty($THEME->open_containers)) {
4236 debugging('Incorrect request to end container - no more open containers.', DEBUG_DEVELOPER);
4237 $idbase = '';
4238 } else {
4239 $idbase = array_pop($THEME->open_containers);
4242 if (!empty($THEME->customcorners)) {
4243 $output = _print_custom_corners_end($idbase);
4244 } else {
4245 $output = '</div>';
4248 if ($return) {
4249 return $output;
4250 } else {
4251 echo $output;
4256 * Returns number of currently open containers
4257 * @return int number of open containers
4259 function open_containers() {
4260 global $THEME;
4262 if (!isset($THEME->open_containers)) {
4263 $THEME->open_containers = array();
4266 return count($THEME->open_containers);
4270 * Force closing of open containers
4271 * @param boolean $return, return as string or just print it
4272 * @param int $keep number of containers to be kept open - usually theme or page containers
4273 * @return mixed string or void
4275 function print_container_end_all($return=false, $keep=0) {
4276 $output = '';
4277 while (open_containers() > $keep) {
4278 $output .= print_container_end($return);
4281 if ($return) {
4282 return $output;
4283 } else {
4284 echo $output;
4289 * Internal function - do not use directly!
4290 * Starting part of the surrounding divs for custom corners
4292 * @param boolean $clearfix, add CLASS "clearfix" to the inner div against collapsing
4293 * @param string $classes
4294 * @param mixed $idbase, optionally, define one idbase to be added to all the elements in the corners
4295 * @return string
4297 function _print_custom_corners_start($clearfix=false, $classes='', $idbase='') {
4298 /// Analise if we want ids for the custom corner elements
4299 $id = '';
4300 $idbt = '';
4301 $idi1 = '';
4302 $idi2 = '';
4303 $idi3 = '';
4305 if ($idbase) {
4306 $id = 'id="'.$idbase.'" ';
4307 $idbt = 'id="'.$idbase.'-bt" ';
4308 $idi1 = 'id="'.$idbase.'-i1" ';
4309 $idi2 = 'id="'.$idbase.'-i2" ';
4310 $idi3 = 'id="'.$idbase.'-i3" ';
4313 /// Calculate current level
4314 $level = open_containers();
4316 /// Output begins
4317 $output = '<div '.$id.'class="wrap wraplevel'.$level.' '.$classes.'">'."\n";
4318 $output .= '<div '.$idbt.'class="bt"><div>&nbsp;</div></div>';
4319 $output .= "\n";
4320 $output .= '<div '.$idi1.'class="i1"><div '.$idi2.'class="i2">';
4321 $output .= (!empty($clearfix)) ? '<div '.$idi3.'class="i3 clearfix">' : '<div '.$idi3.'class="i3">';
4323 return $output;
4328 * Internal function - do not use directly!
4329 * Ending part of the surrounding divs for custom corners
4330 * @param string $idbase
4331 * @return string
4333 function _print_custom_corners_end($idbase) {
4334 /// Analise if we want ids for the custom corner elements
4335 $idbb = '';
4337 if ($idbase) {
4338 $idbb = 'id="' . $idbase . '-bb" ';
4341 /// Output begins
4342 $output = '</div></div></div>';
4343 $output .= "\n";
4344 $output .= '<div '.$idbb.'class="bb"><div>&nbsp;</div></div>'."\n";
4345 $output .= '</div>';
4347 return $output;
4352 * Print a self contained form with a single submit button.
4354 * @param string $link used as the action attribute on the form, so the URL that will be hit if the button is clicked.
4355 * @param array $options these become hidden form fields, so these options get passed to the script at $link.
4356 * @param string $label the caption that appears on the button.
4357 * @param string $method HTTP method used on the request of the button is clicked. 'get' or 'post'.
4358 * @param string $target no longer used.
4359 * @param boolean $return if false, output the form directly, otherwise return the HTML as a string.
4360 * @param string $tooltip a tooltip to add to the button as a title attribute.
4361 * @param boolean $disabled if true, the button will be disabled.
4362 * @param string $jsconfirmmessage if not empty then display a confirm dialogue with this string as the question.
4363 * @return string / nothing depending on the $return paramter.
4365 function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='', $disabled = false, $jsconfirmmessage='') {
4366 $output = '';
4367 $link = str_replace('"', '&quot;', $link); //basic XSS protection
4368 $output .= '<div class="singlebutton">';
4369 // taking target out, will need to add later target="'.$target.'"
4370 $output .= '<form action="'. $link .'" method="'. $method .'">';
4371 $output .= '<div>';
4372 if ($options) {
4373 foreach ($options as $name => $value) {
4374 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
4377 if ($tooltip) {
4378 $tooltip = 'title="' . s($tooltip) . '"';
4379 } else {
4380 $tooltip = '';
4382 if ($disabled) {
4383 $disabled = 'disabled="disabled"';
4384 } else {
4385 $disabled = '';
4387 if ($jsconfirmmessage){
4388 $jsconfirmmessage = addslashes_js($jsconfirmmessage);
4389 $jsconfirmmessage = 'onclick="return confirm(\''. $jsconfirmmessage .'\');" ';
4391 $output .= '<input type="submit" value="'. s($label) ."\" $tooltip $disabled $jsconfirmmessage/></div></form></div>";
4393 if ($return) {
4394 return $output;
4395 } else {
4396 echo $output;
4402 * Print a spacer image with the option of including a line break.
4404 * @param int $height ?
4405 * @param int $width ?
4406 * @param boolean $br ?
4407 * @todo Finish documenting this function
4409 function print_spacer($height=1, $width=1, $br=true, $return=false) {
4410 global $CFG;
4411 $output = '';
4413 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot .'/pix/spacer.gif" alt="" />';
4414 if ($br) {
4415 $output .= '<br />'."\n";
4418 if ($return) {
4419 return $output;
4420 } else {
4421 echo $output;
4426 * Given the path to a picture file in a course, or a URL,
4427 * this function includes the picture in the page.
4429 * @param string $path ?
4430 * @param int $courseid ?
4431 * @param int $height ?
4432 * @param int $width ?
4433 * @param string $link ?
4434 * @todo Finish documenting this function
4436 function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
4437 global $CFG;
4438 $output = '';
4440 if ($height) {
4441 $height = 'height="'. $height .'"';
4443 if ($width) {
4444 $width = 'width="'. $width .'"';
4446 if ($link) {
4447 $output .= '<a href="'. $link .'">';
4449 if (substr(strtolower($path), 0, 7) == 'http://') {
4450 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
4452 } else if ($courseid) {
4453 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
4454 require_once($CFG->libdir.'/filelib.php');
4455 $output .= get_file_url("$courseid/$path");
4456 $output .= '" />';
4457 } else {
4458 $output .= 'Error: must pass URL or course';
4460 if ($link) {
4461 $output .= '</a>';
4464 if ($return) {
4465 return $output;
4466 } else {
4467 echo $output;
4472 * Print the specified user's avatar.
4474 * @param mixed $user Should be a $user object with at least fields id, picture, imagealt, firstname, lastname
4475 * If any of these are missing, or if a userid is passed, the the database is queried. Avoid this
4476 * if at all possible, particularly for reports. It is very bad for performance.
4477 * @param int $courseid The course id. Used when constructing the link to the user's profile.
4478 * @param boolean $picture The picture to print. By default (or if NULL is passed) $user->picture is used.
4479 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
4480 * @param boolean $return If false print picture to current page, otherwise return the output as string
4481 * @param boolean $link enclose printed image in a link the user's profile (default true).
4482 * @param string $target link target attribute. Makes the profile open in a popup window.
4483 * @param boolean $alttext add non-blank alt-text to the image. (Default true, set to false for purely
4484 * decorative images, or where the username will be printed anyway.)
4485 * @return string or nothing, depending on $return.
4487 function print_user_picture($user, $courseid, $picture=NULL, $size=0, $return=false, $link=true, $target='', $alttext=true) {
4488 global $CFG;
4490 $needrec = false;
4491 // only touch the DB if we are missing data...
4492 if (is_object($user)) {
4493 // Note - both picture and imagealt _can_ be empty
4494 // what we are trying to see here is if they have been fetched
4495 // from the DB. We should use isset() _except_ that some installs
4496 // have those fields as nullable, and isset() will return false
4497 // on null. The only safe thing is to ask array_key_exists()
4498 // which works on objects. property_exists() isn't quite
4499 // what we want here...
4500 if (! (array_key_exists('picture', $user)
4501 && ($alttext && array_key_exists('imagealt', $user)
4502 || (isset($user->firstname) && isset($user->lastname)))) ) {
4503 $needrec = true;
4504 $user = $user->id;
4506 } else {
4507 if ($alttext) {
4508 // we need firstname, lastname, imagealt, can't escape...
4509 $needrec = true;
4510 } else {
4511 $userobj = new StdClass; // fake it to save DB traffic
4512 $userobj->id = $user;
4513 $userobj->picture = $picture;
4514 $user = clone($userobj);
4515 unset($userobj);
4518 if ($needrec) {
4519 $user = get_record('user','id',$user, '', '', '', '', 'id,firstname,lastname,imagealt');
4522 if ($link) {
4523 $url = '/user/view.php?id='. $user->id .'&amp;course='. $courseid ;
4524 if ($target) {
4525 $target='onclick="return openpopup(\''.$url.'\');"';
4527 $output = '<a '.$target.' href="'. $CFG->wwwroot . $url .'">';
4528 } else {
4529 $output = '';
4531 if (empty($size)) {
4532 $file = 'f2';
4533 $size = 35;
4534 } else if ($size === true or $size == 1) {
4535 $file = 'f1';
4536 $size = 100;
4537 } else if ($size >= 50) {
4538 $file = 'f1';
4539 } else {
4540 $file = 'f2';
4542 $class = "userpicture";
4544 if (is_null($picture) and !empty($user->picture)) {
4545 $picture = $user->picture;
4548 if ($picture) { // Print custom user picture
4549 require_once($CFG->libdir.'/filelib.php');
4550 $src = get_file_url($user->id.'/'.$file.'.jpg', null, 'user');
4551 } else { // Print default user pictures (use theme version if available)
4552 $class .= " defaultuserpic";
4553 $src = "$CFG->pixpath/u/$file.png";
4555 $imagealt = '';
4556 if ($alttext) {
4557 if (!empty($user->imagealt)) {
4558 $imagealt = $user->imagealt;
4559 } else {
4560 $imagealt = get_string('pictureof','',fullname($user));
4564 $output .= "<img class=\"$class\" src=\"$src\" height=\"$size\" width=\"$size\" title=\"".s($imagealt)."\" alt=\"".s($imagealt).'" />';
4565 if ($link) {
4566 $output .= '</a>';
4569 if ($return) {
4570 return $output;
4571 } else {
4572 echo $output;
4577 * Prints a summary of a user in a nice little box.
4579 * @uses $CFG
4580 * @uses $USER
4581 * @param user $user A {@link $USER} object representing a user
4582 * @param course $course A {@link $COURSE} object representing a course
4584 function print_user($user, $course, $messageselect=false, $return=false) {
4586 global $CFG, $USER;
4588 $output = '';
4590 static $string;
4591 static $datestring;
4592 static $countries;
4594 $context = get_context_instance(CONTEXT_COURSE, $course->id);
4595 if (isset($user->context->id)) {
4596 $usercontext = $user->context;
4597 } else {
4598 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
4601 if (empty($string)) { // Cache all the strings for the rest of the page
4603 $string->email = get_string('email');
4604 $string->city = get_string('city');
4605 $string->lastaccess = get_string('lastaccess');
4606 $string->activity = get_string('activity');
4607 $string->unenrol = get_string('unenrol');
4608 $string->loginas = get_string('loginas');
4609 $string->fullprofile = get_string('fullprofile');
4610 $string->role = get_string('role');
4611 $string->name = get_string('name');
4612 $string->never = get_string('never');
4614 $datestring->day = get_string('day');
4615 $datestring->days = get_string('days');
4616 $datestring->hour = get_string('hour');
4617 $datestring->hours = get_string('hours');
4618 $datestring->min = get_string('min');
4619 $datestring->mins = get_string('mins');
4620 $datestring->sec = get_string('sec');
4621 $datestring->secs = get_string('secs');
4622 $datestring->year = get_string('year');
4623 $datestring->years = get_string('years');
4625 $countries = get_list_of_countries();
4628 /// Get the hidden field list
4629 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
4630 $hiddenfields = array();
4631 } else {
4632 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
4635 $output .= '<table class="userinfobox">';
4636 $output .= '<tr>';
4637 $output .= '<td class="left side">';
4638 $output .= print_user_picture($user, $course->id, $user->picture, true, true);
4639 $output .= '</td>';
4640 $output .= '<td class="content">';
4641 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
4642 $output .= '<div class="info">';
4643 if (!empty($user->role) and ($user->role <> $course->teacher)) {
4644 $output .= $string->role .': '. $user->role .'<br />';
4646 if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguest()) or
4647 has_capability('moodle/course:viewhiddenuserfields', $context)) {
4648 $output .= $string->email .': <a href="mailto:'. $user->email .'">'. $user->email .'</a><br />';
4650 if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
4651 $output .= $string->city .': ';
4652 if ($user->city && !isset($hiddenfields['city'])) {
4653 $output .= $user->city;
4655 if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
4656 if ($user->city && !isset($hiddenfields['city'])) {
4657 $output .= ', ';
4659 $output .= $countries[$user->country];
4661 $output .= '<br />';
4664 if (!isset($hiddenfields['lastaccess'])) {
4665 if ($user->lastaccess) {
4666 $output .= $string->lastaccess .': '. userdate($user->lastaccess);
4667 $output .= '&nbsp; ('. format_time(time() - $user->lastaccess, $datestring) .')';
4668 } else {
4669 $output .= $string->lastaccess .': '. $string->never;
4672 $output .= '</div></td><td class="links">';
4673 //link to blogs
4674 if ($CFG->bloglevel > 0) {
4675 $output .= '<a href="'.$CFG->wwwroot.'/blog/index.php?userid='.$user->id.'">'.get_string('blogs','blog').'</a><br />';
4677 //link to notes
4678 if (!empty($CFG->enablenotes) and (has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context))) {
4679 $output .= '<a href="'.$CFG->wwwroot.'/notes/index.php?course=' . $course->id. '&amp;user='.$user->id.'">'.get_string('notes','notes').'</a><br />';
4682 if (has_capability('moodle/site:viewreports', $context) or has_capability('moodle/user:viewuseractivitiesreport', $usercontext)) {
4683 $output .= '<a href="'. $CFG->wwwroot .'/course/user.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->activity .'</a><br />';
4685 if (has_capability('moodle/role:assign', $context) and get_user_roles($context, $user->id, false)) { // I can unassing and user has some role
4686 $output .= '<a href="'. $CFG->wwwroot .'/course/unenrol.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->unenrol .'</a><br />';
4688 if ($USER->id != $user->id && empty($USER->realuser) && has_capability('moodle/user:loginas', $context) &&
4689 ! has_capability('moodle/site:doanything', $context, $user->id, false)) {
4690 $output .= '<a href="'. $CFG->wwwroot .'/course/loginas.php?id='. $course->id .'&amp;user='. $user->id .'&amp;sesskey='. sesskey() .'">'. $string->loginas .'</a><br />';
4692 $output .= '<a href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&amp;course='. $course->id .'">'. $string->fullprofile .'...</a>';
4694 if (!empty($messageselect)) {
4695 $output .= '<br /><input type="checkbox" name="user'.$user->id.'" /> ';
4698 $output .= '</td></tr></table>';
4700 if ($return) {
4701 return $output;
4702 } else {
4703 echo $output;
4708 * Print a specified group's avatar.
4710 * @param group $group A single {@link group} object OR array of groups.
4711 * @param int $courseid The course ID.
4712 * @param boolean $large Default small picture, or large.
4713 * @param boolean $return If false print picture, otherwise return the output as string
4714 * @param boolean $link Enclose image in a link to view specified course?
4715 * @return string
4716 * @todo Finish documenting this function
4718 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
4719 global $CFG;
4721 if (is_array($group)) {
4722 $output = '';
4723 foreach($group as $g) {
4724 $output .= print_group_picture($g, $courseid, $large, true, $link);
4726 if ($return) {
4727 return $output;
4728 } else {
4729 echo $output;
4730 return;
4734 $context = get_context_instance(CONTEXT_COURSE, $courseid);
4736 // If there is no picture, do nothing
4737 if (!$group->picture) {
4738 return '';
4741 // If picture is hidden, only show to those with course:managegroups
4742 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
4743 return '';
4746 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4747 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
4748 } else {
4749 $output = '';
4751 if ($large) {
4752 $file = 'f1';
4753 } else {
4754 $file = 'f2';
4757 // Print custom group picture
4758 require_once($CFG->libdir.'/filelib.php');
4759 $grouppictureurl = get_file_url($group->id.'/'.$file.'.jpg', null, 'usergroup');
4760 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
4761 ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
4763 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4764 $output .= '</a>';
4767 if ($return) {
4768 return $output;
4769 } else {
4770 echo $output;
4775 * Print a png image.
4777 * @param string $url ?
4778 * @param int $sizex ?
4779 * @param int $sizey ?
4780 * @param boolean $return ?
4781 * @param string $parameters ?
4782 * @todo Finish documenting this function
4784 function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
4785 global $CFG;
4786 static $recentIE;
4788 if (!isset($recentIE)) {
4789 $recentIE = check_browser_version('MSIE', '5.0');
4792 if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
4793 $output .= '<img src="'. $CFG->pixpath .'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
4794 ' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
4795 ' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
4796 "'$url', sizingMethod='scale') ".
4797 ' '. $parameters .' />';
4798 } else {
4799 $output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
4802 if ($return) {
4803 return $output;
4804 } else {
4805 echo $output;
4810 * Print a nicely formatted table.
4812 * @param array $table is an object with several properties.
4813 * <ul>
4814 * <li>$table->head - An array of heading names.
4815 * <li>$table->align - An array of column alignments
4816 * <li>$table->size - An array of column sizes
4817 * <li>$table->wrap - An array of "nowrap"s or nothing
4818 * <li>$table->data[] - An array of arrays containing the data.
4819 * <li>$table->width - A percentage of the page
4820 * <li>$table->tablealign - Align the whole table
4821 * <li>$table->cellpadding - Padding on each cell
4822 * <li>$table->cellspacing - Spacing between cells
4823 * <li>$table->class - class attribute to put on the table
4824 * <li>$table->id - id attribute to put on the table.
4825 * <li>$table->rowclass[] - classes to add to particular rows.
4826 * <li>$table->summary - Description of the contents for screen readers.
4827 * </ul>
4828 * @param bool $return whether to return an output string or echo now
4829 * @return boolean or $string
4830 * @todo Finish documenting this function
4832 function print_table($table, $return=false) {
4833 $output = '';
4835 if (isset($table->align)) {
4836 foreach ($table->align as $key => $aa) {
4837 if ($aa) {
4838 $align[$key] = ' text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
4839 } else {
4840 $align[$key] = '';
4844 if (isset($table->size)) {
4845 foreach ($table->size as $key => $ss) {
4846 if ($ss) {
4847 $size[$key] = ' width:'. $ss .';';
4848 } else {
4849 $size[$key] = '';
4853 if (isset($table->wrap)) {
4854 foreach ($table->wrap as $key => $ww) {
4855 if ($ww) {
4856 $wrap[$key] = ' white-space:nowrap;';
4857 } else {
4858 $wrap[$key] = '';
4863 if (empty($table->width)) {
4864 $table->width = '80%';
4867 if (empty($table->tablealign)) {
4868 $table->tablealign = 'center';
4871 if (!isset($table->cellpadding)) {
4872 $table->cellpadding = '5';
4875 if (!isset($table->cellspacing)) {
4876 $table->cellspacing = '1';
4879 if (empty($table->class)) {
4880 $table->class = 'generaltable';
4883 $tableid = empty($table->id) ? '' : 'id="'.$table->id.'"';
4885 $output .= '<table width="'.$table->width.'" ';
4886 if (!empty($table->summary)) {
4887 $output .= " summary=\"$table->summary\"";
4889 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
4891 $countcols = 0;
4893 if (!empty($table->head)) {
4894 $countcols = count($table->head);
4895 $output .= '<tr>';
4896 $keys=array_keys($table->head);
4897 $lastkey = end($keys);
4898 foreach ($table->head as $key => $heading) {
4900 if (!isset($size[$key])) {
4901 $size[$key] = '';
4903 if (!isset($align[$key])) {
4904 $align[$key] = '';
4906 if ($key == $lastkey) {
4907 $extraclass = ' lastcol';
4908 } else {
4909 $extraclass = '';
4912 $output .= '<th style="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.$extraclass.'" scope="col">'. $heading .'</th>';
4914 $output .= '</tr>'."\n";
4917 if (!empty($table->data)) {
4918 $oddeven = 1;
4919 $keys=array_keys($table->data);
4920 $lastrowkey = end($keys);
4921 foreach ($table->data as $key => $row) {
4922 $oddeven = $oddeven ? 0 : 1;
4923 if (!isset($table->rowclass[$key])) {
4924 $table->rowclass[$key] = '';
4926 if ($key == $lastrowkey) {
4927 $table->rowclass[$key] .= ' lastrow';
4929 $output .= '<tr class="r'.$oddeven.' '.$table->rowclass[$key].'">'."\n";
4930 if ($row == 'hr' and $countcols) {
4931 $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
4932 } else { /// it's a normal row of data
4933 $keys2=array_keys($row);
4934 $lastkey = end($keys2);
4935 foreach ($row as $key => $item) {
4936 if (!isset($size[$key])) {
4937 $size[$key] = '';
4939 if (!isset($align[$key])) {
4940 $align[$key] = '';
4942 if (!isset($wrap[$key])) {
4943 $wrap[$key] = '';
4945 if ($key == $lastkey) {
4946 $extraclass = ' lastcol';
4947 } else {
4948 $extraclass = '';
4950 $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.$extraclass.'">'. $item .'</td>';
4953 $output .= '</tr>'."\n";
4956 $output .= '</table>'."\n";
4958 if ($return) {
4959 return $output;
4962 echo $output;
4963 return true;
4966 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
4967 static $strftimerecent = null;
4968 $output = '';
4970 if (is_null($viewfullnames)) {
4971 $context = get_context_instance(CONTEXT_SYSTEM);
4972 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
4975 if (is_null($strftimerecent)) {
4976 $strftimerecent = get_string('strftimerecent');
4979 $output .= '<div class="head">';
4980 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
4981 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
4982 $output .= '</div>';
4983 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
4985 if ($return) {
4986 return $output;
4987 } else {
4988 echo $output;
4994 * Prints a basic textarea field.
4996 * @uses $CFG
4997 * @param boolean $usehtmleditor ?
4998 * @param int $rows ?
4999 * @param int $cols ?
5000 * @param null $width <b>Legacy field no longer used!</b> Set to zero to get control over mincols
5001 * @param null $height <b>Legacy field no longer used!</b> Set to zero to get control over minrows
5002 * @param string $name ?
5003 * @param string $value ?
5004 * @param int $courseid ?
5005 * @todo Finish documenting this function
5007 function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $courseid=0, $return=false, $id='') {
5008 /// $width and height are legacy fields and no longer used as pixels like they used to be.
5009 /// However, you can set them to zero to override the mincols and minrows values below.
5011 global $CFG, $COURSE, $HTTPSPAGEREQUIRED;
5012 static $scriptcount = 0; // For loading the htmlarea script only once.
5014 $mincols = 65;
5015 $minrows = 10;
5016 $str = '';
5018 if ($id === '') {
5019 $id = 'edit-'.$name;
5022 if ( empty($CFG->editorsrc) ) { // for backward compatibility.
5023 if (empty($courseid)) {
5024 $courseid = $COURSE->id;
5027 if ($usehtmleditor) {
5028 if (!empty($courseid) and has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE, $courseid))) {
5029 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '&amp;httpsrequired=1';
5030 // needed for course file area browsing in image insert plugin
5031 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
5032 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php?id='.$courseid.$httpsrequired.'"></script>'."\n" : '';
5033 } else {
5034 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '?httpsrequired=1';
5035 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
5036 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php'.$httpsrequired.'"></script>'."\n" : '';
5039 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
5040 $CFG->httpswwwroot .'/lib/editor/htmlarea/lang/en.php?id='.$courseid.'"></script>'."\n" : '';
5041 $scriptcount++;
5043 if ($height) { // Usually with legacy calls
5044 if ($rows < $minrows) {
5045 $rows = $minrows;
5048 if ($width) { // Usually with legacy calls
5049 if ($cols < $mincols) {
5050 $cols = $mincols;
5055 $str .= '<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">';
5056 if ($usehtmleditor) {
5057 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
5058 } else {
5059 $str .= s($value);
5061 $str .= '</textarea>'."\n";
5063 if ($usehtmleditor) {
5064 // Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
5065 $str .= '<script type="text/javascript">
5066 //<![CDATA[
5067 document.write(\''.addslashes_js(editorshortcutshelpbutton()).'\');
5068 //]]>
5069 </script>';
5072 if ($return) {
5073 return $str;
5075 echo $str;
5079 * Sets up the HTML editor on textareas in the current page.
5080 * If a field name is provided, then it will only be
5081 * applied to that field - otherwise it will be used
5082 * on every textarea in the page.
5084 * In most cases no arguments need to be supplied
5086 * @param string $name Form element to replace with HTMl editor by name
5088 function use_html_editor($name='', $editorhidebuttons='', $id='') {
5089 global $THEME;
5091 $editor = 'editor_'.md5($name); //name might contain illegal characters
5092 if ($id === '') {
5093 $id = 'edit-'.$name;
5095 echo "\n".'<script type="text/javascript" defer="defer">'."\n";
5096 echo '//<![CDATA['."\n\n"; // Extra \n is to fix odd wiki problem, MDL-8185
5097 echo "$editor = new HTMLArea('$id');\n";
5098 echo "var config = $editor.config;\n";
5100 echo print_editor_config($editorhidebuttons);
5102 if (empty($THEME->htmleditorpostprocess)) {
5103 if (empty($name)) {
5104 echo "\nHTMLArea.replaceAll($editor.config);\n";
5105 } else {
5106 echo "\n$editor.generate();\n";
5108 } else {
5109 if (empty($name)) {
5110 echo "\nvar HTML_name = '';";
5111 } else {
5112 echo "\nvar HTML_name = \"$name;\"";
5114 echo "\nvar HTML_editor = $editor;";
5116 echo '//]]>'."\n";
5117 echo '</script>'."\n";
5120 function print_editor_config($editorhidebuttons='', $return=false) {
5121 global $CFG;
5123 $str = "config.pageStyle = \"body {";
5125 if (!(empty($CFG->editorbackgroundcolor))) {
5126 $str .= " background-color: $CFG->editorbackgroundcolor;";
5129 if (!(empty($CFG->editorfontfamily))) {
5130 $str .= " font-family: $CFG->editorfontfamily;";
5133 if (!(empty($CFG->editorfontsize))) {
5134 $str .= " font-size: $CFG->editorfontsize;";
5137 $str .= " }\";\n";
5138 $str .= "config.killWordOnPaste = ";
5139 $str .= (empty($CFG->editorkillword)) ? "false":"true";
5140 $str .= ';'."\n";
5141 $str .= 'config.fontname = {'."\n";
5143 $fontlist = isset($CFG->editorfontlist) ? explode(';', $CFG->editorfontlist) : array();
5144 $i = 1; // Counter is used to get rid of the last comma.
5146 foreach ($fontlist as $fontline) {
5147 if (!empty($fontline)) {
5148 if ($i > 1) {
5149 $str .= ','."\n";
5151 list($fontkey, $fontvalue) = split(':', $fontline);
5152 $str .= '"'. $fontkey ."\":\t'". $fontvalue ."'";
5154 $i++;
5157 $str .= '};';
5159 if (!empty($editorhidebuttons)) {
5160 $str .= "\nconfig.hideSomeButtons(\" ". $editorhidebuttons ." \");\n";
5161 } else if (!empty($CFG->editorhidebuttons)) {
5162 $str .= "\nconfig.hideSomeButtons(\" ". $CFG->editorhidebuttons ." \");\n";
5165 if (!empty($CFG->editorspelling) && !empty($CFG->aspellpath)) {
5166 $str .= print_speller_code($CFG->htmleditor, true);
5169 if ($return) {
5170 return $str;
5172 echo $str;
5176 * Returns a turn edit on/off button for course in a self contained form.
5177 * Used to be an icon, but it's now a simple form button
5179 * Note that the caller is responsible for capchecks.
5181 * @uses $CFG
5182 * @uses $USER
5183 * @param int $courseid The course to update by id as found in 'course' table
5184 * @return string
5186 function update_course_icon($courseid) {
5187 global $CFG, $USER;
5189 if (!empty($USER->editing)) {
5190 $string = get_string('turneditingoff');
5191 $edit = '0';
5192 } else {
5193 $string = get_string('turneditingon');
5194 $edit = '1';
5197 return '<form '.$CFG->frametarget.' method="get" action="'.$CFG->wwwroot.'/course/view.php">'.
5198 '<div>'.
5199 '<input type="hidden" name="id" value="'.$courseid.'" />'.
5200 '<input type="hidden" name="edit" value="'.$edit.'" />'.
5201 '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
5202 '<input type="submit" value="'.$string.'" />'.
5203 '</div></form>';
5207 * Returns a little popup menu for switching roles
5209 * @uses $CFG
5210 * @uses $USER
5211 * @param int $courseid The course to update by id as found in 'course' table
5212 * @return string
5214 function switchroles_form($courseid) {
5216 global $CFG, $USER;
5219 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
5220 return '';
5223 if (!empty($USER->access['rsw'][$context->path])){ // Just a button to return to normal
5224 $options = array();
5225 $options['id'] = $courseid;
5226 $options['sesskey'] = sesskey();
5227 $options['switchrole'] = 0;
5229 return print_single_button($CFG->wwwroot.'/course/view.php', $options,
5230 get_string('switchrolereturn'), 'post', '_self', true);
5233 if (has_capability('moodle/role:switchroles', $context)) {
5234 if (!$roles = get_assignable_roles_for_switchrole($context)) {
5235 return ''; // Nothing to show!
5237 // unset default user role - it would not work
5238 unset($roles[$CFG->guestroleid]);
5239 return popup_form($CFG->wwwroot.'/course/view.php?id='.$courseid.'&amp;sesskey='.sesskey().'&amp;switchrole=',
5240 $roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
5243 return '';
5248 * Returns a turn edit on/off button for course in a self contained form.
5249 * Used to be an icon, but it's now a simple form button
5251 * @uses $CFG
5252 * @uses $USER
5253 * @param int $courseid The course to update by id as found in 'course' table
5254 * @return string
5256 function update_mymoodle_icon() {
5258 global $CFG, $USER;
5260 if (!empty($USER->editing)) {
5261 $string = get_string('updatemymoodleoff');
5262 $edit = '0';
5263 } else {
5264 $string = get_string('updatemymoodleon');
5265 $edit = '1';
5268 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
5269 "<div>".
5270 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5271 "<input type=\"submit\" value=\"$string\" /></div></form>";
5275 * Returns a turn edit on/off button for tag in a self contained form.
5277 * @uses $CFG
5278 * @uses $USER
5279 * @return string
5281 function update_tag_button($tagid) {
5283 global $CFG, $USER;
5285 if (!empty($USER->editing)) {
5286 $string = get_string('turneditingoff');
5287 $edit = '0';
5288 } else {
5289 $string = get_string('turneditingon');
5290 $edit = '1';
5293 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/tag/index.php\">".
5294 "<div>".
5295 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5296 "<input type=\"hidden\" name=\"id\" value=\"$tagid\" />".
5297 "<input type=\"submit\" value=\"$string\" /></div></form>";
5301 * Prints the editing button on a module "view" page
5303 * @uses $CFG
5304 * @param type description
5305 * @todo Finish documenting this function
5307 function update_module_button($moduleid, $courseid, $string) {
5308 global $CFG, $USER;
5310 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $moduleid))) {
5311 $string = get_string('updatethis', '', $string);
5313 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
5314 "<div>".
5315 "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
5316 "<input type=\"hidden\" name=\"return\" value=\"true\" />".
5317 "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
5318 "<input type=\"submit\" value=\"$string\" /></div></form>";
5319 } else {
5320 return '';
5325 * Prints the editing button on search results listing
5326 * For bulk move courses to another category
5329 function update_categories_search_button($search,$page,$perpage) {
5330 global $CFG, $USER;
5332 // not sure if this capability is the best here
5333 if (has_capability('moodle/category:manage', get_context_instance(CONTEXT_SYSTEM))) {
5334 if (!empty($USER->categoryediting)) {
5335 $string = get_string("turneditingoff");
5336 $edit = "off";
5337 $perpage = 30;
5338 } else {
5339 $string = get_string("turneditingon");
5340 $edit = "on";
5343 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
5344 '<div>'.
5345 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5346 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5347 "<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
5348 "<input type=\"hidden\" name=\"page\" value=\"$page\" />".
5349 "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
5350 "<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
5355 * Given a course and a (current) coursemodule
5356 * This function returns a small popup menu with all the
5357 * course activity modules in it, as a navigation menu
5358 * The data is taken from the serialised array stored in
5359 * the course record
5361 * @param course $course A {@link $COURSE} object.
5362 * @param course $cm A {@link $COURSE} object.
5363 * @param string $targetwindow ?
5364 * @return string
5365 * @todo Finish documenting this function
5367 function navmenu($course, $cm=NULL, $targetwindow='self') {
5369 global $CFG, $THEME, $USER;
5371 if (empty($THEME->navmenuwidth)) {
5372 $width = 50;
5373 } else {
5374 $width = $THEME->navmenuwidth;
5377 if ($cm) {
5378 $cm = $cm->id;
5381 if ($course->format == 'weeks') {
5382 $strsection = get_string('week');
5383 } else {
5384 $strsection = get_string('topic');
5386 $strjumpto = get_string('jumpto');
5388 $modinfo = get_fast_modinfo($course);
5389 $context = get_context_instance(CONTEXT_COURSE, $course->id);
5391 $section = -1;
5392 $selected = '';
5393 $url = '';
5394 $previousmod = NULL;
5395 $backmod = NULL;
5396 $nextmod = NULL;
5397 $selectmod = NULL;
5398 $logslink = NULL;
5399 $flag = false;
5400 $menu = array();
5401 $menustyle = array();
5403 $sections = get_records('course_sections','course',$course->id,'section','section,visible,summary');
5405 if (!empty($THEME->makenavmenulist)) { /// A hack to produce an XHTML navmenu list for use in themes
5406 $THEME->navmenulist = navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
5409 foreach ($modinfo->cms as $mod) {
5410 if ($mod->modname == 'label') {
5411 continue;
5414 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
5415 break;
5418 if (!$mod->uservisible) { // do not icnlude empty sections at all
5419 continue;
5422 if ($mod->sectionnum > 0 and $section != $mod->sectionnum) {
5423 $thissection = $sections[$mod->sectionnum];
5425 if ($thissection->visible or !$course->hiddensections or
5426 has_capability('moodle/course:viewhiddensections', $context)) {
5427 $thissection->summary = strip_tags(format_string($thissection->summary,true));
5428 if ($course->format == 'weeks' or empty($thissection->summary)) {
5429 $menu[] = '--'.$strsection ." ". $mod->sectionnum;
5430 } else {
5431 if (strlen($thissection->summary) < ($width-3)) {
5432 $menu[] = '--'.$thissection->summary;
5433 } else {
5434 $menu[] = '--'.substr($thissection->summary, 0, $width).'...';
5437 $section = $mod->sectionnum;
5438 } else {
5439 // no activities from this hidden section shown
5440 continue;
5444 $url = $mod->modname.'/view.php?id='. $mod->id;
5445 if ($flag) { // the current mod is the "next" mod
5446 $nextmod = $mod;
5447 $flag = false;
5449 $localname = $mod->name;
5450 if ($cm == $mod->id) {
5451 $selected = $url;
5452 $selectmod = $mod;
5453 $backmod = $previousmod;
5454 $flag = true; // set flag so we know to use next mod for "next"
5455 $localname = $strjumpto;
5456 $strjumpto = '';
5457 } else {
5458 $localname = strip_tags(format_string($localname,true));
5459 $tl=textlib_get_instance();
5460 if ($tl->strlen($localname) > ($width+5)) {
5461 $localname = $tl->substr($localname, 0, $width).'...';
5463 if (!$mod->visible) {
5464 $localname = '('.$localname.')';
5467 $menu[$url] = $localname;
5468 if (empty($THEME->navmenuiconshide)) {
5469 $menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif);"'; // Unfortunately necessary to do this here
5471 $previousmod = $mod;
5473 //Accessibility: added Alt text, replaced &gt; &lt; with 'silent' character and 'accesshide' text.
5475 if ($selectmod and has_capability('coursereport/log:view', $context)) {
5476 $logstext = get_string('alllogs');
5477 $logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
5478 $CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\';"'.' href="'.
5479 $CFG->wwwroot.'/course/report/log/index.php?chooselog=1&amp;user=0&amp;date=0&amp;id='.
5480 $course->id.'&amp;modid='.$selectmod->id.'">'.
5481 '<img class="icon log" src="'.$CFG->pixpath.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
5484 if ($backmod) {
5485 $backtext= get_string('activityprev', 'access');
5486 $backmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$backmod->modname.'/view.php" '.$CFG->frametarget.' '.
5487 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
5488 '<input type="hidden" name="id" value="'.$backmod->id.'" />'.
5489 '<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
5490 '</button></fieldset></form></li>';
5492 if ($nextmod) {
5493 $nexttext= get_string('activitynext', 'access');
5494 $nextmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$nextmod->modname.'/view.php" '.$CFG->frametarget.' '.
5495 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
5496 '<input type="hidden" name="id" value="'.$nextmod->id.'" />'.
5497 '<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
5498 '</button></fieldset></form></li>';
5501 return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
5502 '<li>'.popup_form($CFG->wwwroot .'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
5503 '', '', true, $targetwindow, '', $menustyle).'</li>'.
5504 $nextmod . '</ul>'."\n".'</div>';
5508 * Given a course
5509 * This function returns a small popup menu with all the
5510 * course activity modules in it, as a navigation menu
5511 * outputs a simple list structure in XHTML
5512 * The data is taken from the serialised array stored in
5513 * the course record
5515 * @param course $course A {@link $COURSE} object.
5516 * @return string
5517 * @todo Finish documenting this function
5519 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
5521 global $CFG;
5523 $section = -1;
5524 $url = '';
5525 $menu = array();
5526 $doneheading = false;
5528 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
5530 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
5531 foreach ($modinfo->cms as $mod) {
5532 if ($mod->modname == 'label') {
5533 continue;
5536 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
5537 break;
5540 if (!$mod->uservisible) { // do not icnlude empty sections at all
5541 continue;
5544 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
5545 $thissection = $sections[$mod->sectionnum];
5547 if ($thissection->visible or !$course->hiddensections or
5548 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
5549 $thissection->summary = strip_tags(format_string($thissection->summary,true));
5550 if (!$doneheading) {
5551 $menu[] = '</ul></li>';
5553 if ($course->format == 'weeks' or empty($thissection->summary)) {
5554 $item = $strsection ." ". $mod->sectionnum;
5555 } else {
5556 if (strlen($thissection->summary) < ($width-3)) {
5557 $item = $thissection->summary;
5558 } else {
5559 $item = substr($thissection->summary, 0, $width).'...';
5562 $menu[] = '<li class="section"><span>'.$item.'</span>';
5563 $menu[] = '<ul>';
5564 $doneheading = true;
5566 $section = $mod->sectionnum;
5567 } else {
5568 // no activities from this hidden section shown
5569 continue;
5573 $url = $mod->modname .'/view.php?id='. $mod->id;
5574 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
5575 if (strlen($mod->name) > ($width+5)) {
5576 $mod->name = substr($mod->name, 0, $width).'...';
5578 if (!$mod->visible) {
5579 $mod->name = '('.$mod->name.')';
5581 $class = 'activity '.$mod->modname;
5582 $class .= ($cmid == $mod->id) ? ' selected' : '';
5583 $menu[] = '<li class="'.$class.'">'.
5584 '<img src="'.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif" alt="" />'.
5585 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
5588 if ($doneheading) {
5589 $menu[] = '</ul></li>';
5591 $menu[] = '</ul></li></ul>';
5593 return implode("\n", $menu);
5597 * Prints form items with the names $day, $month and $year
5599 * @param string $day fieldname
5600 * @param string $month fieldname
5601 * @param string $year fieldname
5602 * @param int $currenttime A default timestamp in GMT
5603 * @param boolean $return
5605 function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
5607 if (!$currenttime) {
5608 $currenttime = time();
5610 $currentdate = usergetdate($currenttime);
5612 for ($i=1; $i<=31; $i++) {
5613 $days[$i] = $i;
5615 for ($i=1; $i<=12; $i++) {
5616 $months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
5618 for ($i=1970; $i<=2020; $i++) {
5619 $years[$i] = $i;
5622 // Build or print result
5623 $result='';
5624 // Note: There should probably be a fieldset around these fields as they are
5625 // clearly grouped. However this causes problems with display. See Mozilla
5626 // bug 474415
5627 $result.='<label class="accesshide" for="menu'.$day.'">'.get_string('day','form').'</label>';
5628 $result.=choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', true);
5629 $result.='<label class="accesshide" for="menu'.$month.'">'.get_string('month','form').'</label>';
5630 $result.=choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', true);
5631 $result.='<label class="accesshide" for="menu'.$year.'">'.get_string('year','form').'</label>';
5632 $result.=choose_from_menu($years, $year, $currentdate['year'], '', '', '0', true);
5634 if ($return) {
5635 return $result;
5636 } else {
5637 echo $result;
5642 *Prints form items with the names $hour and $minute
5644 * @param string $hour fieldname
5645 * @param string ? $minute fieldname
5646 * @param $currenttime A default timestamp in GMT
5647 * @param int $step minute spacing
5648 * @param boolean $return
5650 function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
5652 if (!$currenttime) {
5653 $currenttime = time();
5655 $currentdate = usergetdate($currenttime);
5656 if ($step != 1) {
5657 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
5659 for ($i=0; $i<=23; $i++) {
5660 $hours[$i] = sprintf("%02d",$i);
5662 for ($i=0; $i<=59; $i+=$step) {
5663 $minutes[$i] = sprintf("%02d",$i);
5666 // Build or print result
5667 $result='';
5668 // Note: There should probably be a fieldset around these fields as they are
5669 // clearly grouped. However this causes problems with display. See Mozilla
5670 // bug 474415
5671 $result.='<label class="accesshide" for="menu'.$hour.'">'.get_string('hour','form').'</label>';
5672 $result.=choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',true);
5673 $result.='<label class="accesshide" for="menu'.$minute.'">'.get_string('minute','form').'</label>';
5674 $result.=choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',true);
5676 if ($return) {
5677 return $result;
5678 } else {
5679 echo $result;
5684 * Prints time limit value selector
5686 * @uses $CFG
5687 * @param int $timelimit default
5688 * @param string $unit
5689 * @param string $name
5690 * @param boolean $return
5692 function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
5694 global $CFG;
5696 if ($unit) {
5697 $unit = ' '.$unit;
5700 // Max timelimit is sessiontimeout - 10 minutes.
5701 $maxvalue = ($CFG->sessiontimeout / 60) - 10;
5703 for ($i=1; $i<=$maxvalue; $i++) {
5704 $minutes[$i] = $i.$unit;
5706 return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
5710 * Prints a grade menu (as part of an existing form) with help
5711 * Showing all possible numerical grades and scales
5713 * @uses $CFG
5714 * @param int $courseid ?
5715 * @param string $name ?
5716 * @param string $current ?
5717 * @param boolean $includenograde ?
5718 * @todo Finish documenting this function
5720 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
5722 global $CFG;
5724 $output = '';
5725 $strscale = get_string('scale');
5726 $strscales = get_string('scales');
5728 $scales = get_scales_menu($courseid);
5729 foreach ($scales as $i => $scalename) {
5730 $grades[-$i] = $strscale .': '. $scalename;
5732 if ($includenograde) {
5733 $grades[0] = get_string('nograde');
5735 for ($i=100; $i>=1; $i--) {
5736 $grades[$i] = $i;
5738 $output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
5740 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5741 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5742 $linkobject, 400, 500, $strscales, 'none', true);
5744 if ($return) {
5745 return $output;
5746 } else {
5747 echo $output;
5752 * Prints a scale menu (as part of an existing form) including help button
5753 * Just like {@link print_grade_menu()} but without the numeric grades
5755 * @param int $courseid ?
5756 * @param string $name ?
5757 * @param string $current ?
5758 * @todo Finish documenting this function
5760 function print_scale_menu($courseid, $name, $current, $return=false) {
5762 global $CFG;
5764 $output = '';
5765 $strscales = get_string('scales');
5766 $output .= choose_from_menu(get_scales_menu($courseid), $name, $current, '', '', 0, true);
5768 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5769 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5770 $linkobject, 400, 500, $strscales, 'none', true);
5771 if ($return) {
5772 return $output;
5773 } else {
5774 echo $output;
5779 * Prints a help button about a scale
5781 * @uses $CFG
5782 * @param id $courseid ?
5783 * @param object $scale ?
5784 * @todo Finish documenting this function
5786 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
5788 global $CFG;
5790 $output = '';
5791 $strscales = get_string('scales');
5793 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5794 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true&amp;scaleid='. $scale->id, 'ratingscale',
5795 $linkobject, 400, 500, $scale->name, 'none', true);
5796 if ($return) {
5797 return $output;
5798 } else {
5799 echo $output;
5804 * Print an error page displaying an error message. New method - use this for new code.
5806 * @uses $SESSION
5807 * @uses $CFG
5808 * @param string $errorcode The name of the string from error.php (or other specified file) to print
5809 * @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.
5810 * @param object $a Extra words and phrases that might be required in the error string
5811 * @param array $extralocations An array of strings with other locations to look for string files
5812 * @return does not return, terminates script
5814 function print_error($errorcode, $module='error', $link='', $a=NULL, $extralocations=NULL) {
5815 global $CFG, $SESSION, $THEME;
5817 if (empty($module) || $module === 'moodle' || $module === 'core') {
5818 $module = 'error';
5821 $message = get_string($errorcode, $module, $a, $extralocations);
5822 if ($module === 'error' and strpos($message, '[[') === 0) {
5823 //search in moodle file if error specified - needed for backwards compatibility
5824 $message = get_string($errorcode, 'moodle', $a, $extralocations);
5827 if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
5828 if ( !empty($SESSION->fromurl) ) {
5829 $link = $SESSION->fromurl;
5830 unset($SESSION->fromurl);
5831 } else {
5832 $link = $CFG->wwwroot .'/';
5836 if (!empty($CFG->errordocroot)) {
5837 $errordocroot = $CFG->errordocroot;
5838 } else if (!empty($CFG->docroot)) {
5839 $errordocroot = $CFG->docroot;
5840 } else {
5841 $errordocroot = 'http://docs.moodle.org';
5844 if (defined('FULLME') && FULLME == 'cron') {
5845 // Errors in cron should be mtrace'd.
5846 mtrace($message);
5847 die;
5850 if ($module === 'error') {
5851 $modulelink = 'moodle';
5852 } else {
5853 $modulelink = $module;
5856 $message = clean_text('<p class="errormessage">'.$message.'</p>'.
5857 '<p class="errorcode">'.
5858 '<a href="'.$errordocroot.'/en/error/'.$modulelink.'/'.$errorcode.'">'.
5859 get_string('moreinformation').'</a></p>');
5861 if (! defined('HEADER_PRINTED')) {
5862 //header not yet printed
5863 @header('HTTP/1.0 404 Not Found');
5864 print_header(get_string('error'));
5865 } else {
5866 print_container_end_all(false, $THEME->open_header_containers);
5869 echo '<br />';
5871 print_simple_box($message, '', '', '', '', 'errorbox');
5873 debugging('Stack trace:', DEBUG_DEVELOPER);
5875 // in case we are logging upgrade in admin/index.php stop it
5876 if (function_exists('upgrade_log_finish')) {
5877 upgrade_log_finish();
5880 if (!empty($link)) {
5881 print_continue($link);
5884 print_footer();
5886 for ($i=0;$i<512;$i++) { // Padding to help IE work with 404
5887 echo ' ';
5889 die;
5893 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
5894 * Default errorcode is 1.
5896 * Very useful for perl-like error-handling:
5898 * do_somethting() or mdie("Something went wrong");
5900 * @param string $msg Error message
5901 * @param integer $errorcode Error code to emit
5903 function mdie($msg='', $errorcode=1) {
5904 trigger_error($msg);
5905 exit($errorcode);
5909 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
5910 * Should be used only with htmleditor or textarea.
5911 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
5912 * helpbutton.
5913 * @return string
5915 function editorhelpbutton(){
5916 global $CFG, $SESSION;
5917 $items = func_get_args();
5918 $i = 1;
5919 $urlparams = array();
5920 $titles = array();
5921 foreach ($items as $item){
5922 if (is_array($item)){
5923 $urlparams[] = "keyword$i=".urlencode($item[0]);
5924 $urlparams[] = "title$i=".urlencode($item[1]);
5925 if (isset($item[2])){
5926 $urlparams[] = "module$i=".urlencode($item[2]);
5928 $titles[] = trim($item[1], ". \t");
5929 }elseif (is_string($item)){
5930 $urlparams[] = "button$i=".urlencode($item);
5931 switch ($item){
5932 case 'reading' :
5933 $titles[] = get_string("helpreading");
5934 break;
5935 case 'writing' :
5936 $titles[] = get_string("helpwriting");
5937 break;
5938 case 'questions' :
5939 $titles[] = get_string("helpquestions");
5940 break;
5941 case 'emoticons' :
5942 $titles[] = get_string("helpemoticons");
5943 break;
5944 case 'richtext' :
5945 $titles[] = get_string('helprichtext');
5946 break;
5947 case 'text' :
5948 $titles[] = get_string('helptext');
5949 break;
5950 default :
5951 error('Unknown help topic '.$item);
5954 $i++;
5956 if (count($titles)>1){
5957 //join last two items with an 'and'
5958 $a = new object();
5959 $a->one = $titles[count($titles) - 2];
5960 $a->two = $titles[count($titles) - 1];
5961 $titles[count($titles) - 2] = get_string('and', '', $a);
5962 unset($titles[count($titles) - 1]);
5964 $alttag = join (', ', $titles);
5966 $paramstring = join('&', $urlparams);
5967 $linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath .'/help.gif" />';
5968 return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), 'popup', $linkobject, 400, 500, $alttag, 'none', true);
5972 * Print a help button.
5974 * @uses $CFG
5975 * @param string $page The keyword that defines a help page
5976 * @param string $title The title of links, rollover tips, alt tags etc
5977 * 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
5978 * @param string $module Which module is the page defined in
5979 * @param mixed $image Use a help image for the link? (true/false/"both")
5980 * @param boolean $linktext If true, display the title next to the help icon.
5981 * @param string $text If defined then this text is used in the page, and
5982 * the $page variable is ignored.
5983 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
5984 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
5985 * @return string
5986 * @todo Finish documenting this function
5988 function helpbutton ($page, $title, $module='moodle', $image=true, $linktext=false, $text='', $return=false,
5989 $imagetext='') {
5990 global $CFG, $COURSE;
5992 //warning if ever $text parameter is used
5993 //$text option won't work properly because the text needs to be always cleaned and,
5994 // when cleaned... html tags always break, so it's unusable.
5995 if ( isset($text) && $text!='') {
5996 debugging('Warning: it\'s not recommended to use $text parameter in helpbutton ($page=' . $page . ', $module=' . $module . ') function', DEBUG_DEVELOPER);
5999 // fix for MDL-7734
6000 if (!empty($COURSE->lang)) {
6001 $forcelang = $COURSE->lang;
6002 } else {
6003 $forcelang = '';
6006 if ($module == '') {
6007 $module = 'moodle';
6010 if ($title == '' && $linktext == '') {
6011 debugging('Error in call to helpbutton function: at least one of $title and $linktext is required');
6014 // Warn users about new window for Accessibility
6015 $tooltip = get_string('helpprefix2', '', trim($title, ". \t")) .' ('.get_string('newwindow').')';
6017 $linkobject = '';
6019 if ($image) {
6020 if ($linktext) {
6021 // MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
6022 $linkobject .= $title.'&nbsp;';
6023 $tooltip = get_string('helpwiththis');
6025 if ($imagetext) {
6026 $linkobject .= $imagetext;
6027 } else {
6028 $linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
6029 $CFG->pixpath .'/help.gif" />';
6031 } else {
6032 $linkobject .= $tooltip;
6035 // fix for MDL-7734
6036 if ($text) {
6037 $url = '/help.php?module='. $module .'&amp;text='. s(urlencode($text).'&amp;forcelang='.$forcelang);
6038 } else {
6039 $url = '/help.php?module='. $module .'&amp;file='. $page .'.html&amp;forcelang='.$forcelang;
6042 $link = '<span class="helplink">'.
6043 link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
6044 '</span>';
6046 if ($return) {
6047 return $link;
6048 } else {
6049 echo $link;
6054 * Print a help button.
6056 * Prints a special help button that is a link to the "live" emoticon popup
6057 * @uses $CFG
6058 * @uses $SESSION
6059 * @param string $form ?
6060 * @param string $field ?
6061 * @todo Finish documenting this function
6063 function emoticonhelpbutton($form, $field, $return = false) {
6065 global $CFG, $SESSION;
6067 $SESSION->inserttextform = $form;
6068 $SESSION->inserttextfield = $field;
6069 $imagetext = '<img src="' . $CFG->pixpath . '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
6070 $help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
6071 if (!$return){
6072 echo $help;
6073 } else {
6074 return $help;
6079 * Print a help button.
6081 * Prints a special help button for html editors (htmlarea in this case)
6082 * @uses $CFG
6084 function editorshortcutshelpbutton() {
6086 global $CFG;
6087 $imagetext = '<img src="' . $CFG->httpswwwroot . '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
6088 get_string('editorshortcutkeys').'" class="iconkbhelp" />';
6090 return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
6094 * Print a message and exit.
6096 * @uses $CFG
6097 * @param string $message ?
6098 * @param string $link ?
6099 * @todo Finish documenting this function
6101 function notice ($message, $link='', $course=NULL) {
6102 global $CFG, $SITE, $THEME, $COURSE;
6104 $message = clean_text($message); // In case nasties are in here
6106 if (defined('FULLME') && FULLME == 'cron') {
6107 // notices in cron should be mtrace'd.
6108 mtrace($message);
6109 die;
6112 if (! defined('HEADER_PRINTED')) {
6113 //header not yet printed
6114 print_header(get_string('notice'));
6115 } else {
6116 print_container_end_all(false, $THEME->open_header_containers);
6119 print_box($message, 'generalbox', 'notice');
6120 print_continue($link);
6122 if (empty($course)) {
6123 print_footer($COURSE);
6124 } else {
6125 print_footer($course);
6127 exit;
6131 * Print a message along with "Yes" and "No" links for the user to continue.
6133 * @param string $message The text to display
6134 * @param string $linkyes The link to take the user to if they choose "Yes"
6135 * @param string $linkno The link to take the user to if they choose "No"
6136 * TODO Document remaining arguments
6138 function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
6140 global $CFG;
6142 $message = clean_text($message);
6143 $linkyes = clean_text($linkyes);
6144 $linkno = clean_text($linkno);
6146 print_box_start('generalbox', 'notice');
6147 echo '<p>'. $message .'</p>';
6148 echo '<div class="buttons">';
6149 print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename);
6150 print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename);
6151 echo '</div>';
6152 print_box_end();
6156 * Provide an definition of error_get_last for PHP before 5.2.0. This simply
6157 * returns NULL, since there is not way to get the right answer.
6159 if (!function_exists('error_get_last')) {
6160 // the eval is needed to prevent PHP 5.2+ from getting a parse error!
6161 eval('
6162 function error_get_last() {
6163 return NULL;
6169 * Redirects the user to another page, after printing a notice
6171 * @param string $url The url to take the user to
6172 * @param string $message The text message to display to the user about the redirect, if any
6173 * @param string $delay How long before refreshing to the new page at $url?
6174 * @todo '&' needs to be encoded into '&amp;' for XHTML compliance,
6175 * however, this is not true for javascript. Therefore we
6176 * first decode all entities in $url (since we cannot rely on)
6177 * the correct input) and then encode for where it's needed
6178 * echo "<script type='text/javascript'>alert('Redirect $url');</script>";
6180 function redirect($url, $message='', $delay=-1) {
6182 global $CFG, $THEME;
6184 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
6185 $url = sid_process_url($url);
6188 $message = clean_text($message);
6190 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
6191 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
6192 $url = str_replace('&amp;', '&', $encodedurl);
6194 /// At developer debug level. Don't redirect if errors have been printed on screen.
6195 /// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
6196 $lasterror = error_get_last();
6197 $error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER));
6198 $errorprinted = debugging('', DEBUG_ALL) && $CFG->debugdisplay && $error;
6199 if ($errorprinted) {
6200 $message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
6203 $performanceinfo = '';
6204 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
6205 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
6206 $perf = get_performance_info();
6207 error_log("PERF: " . $perf['txt']);
6211 /// when no message and header printed yet, try to redirect
6212 if (empty($message) and !defined('HEADER_PRINTED')) {
6214 // Technically, HTTP/1.1 requires Location: header to contain
6215 // the absolute path. (In practice browsers accept relative
6216 // paths - but still, might as well do it properly.)
6217 // This code turns relative into absolute.
6218 if (!preg_match('|^[a-z]+:|', $url)) {
6219 // Get host name http://www.wherever.com
6220 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
6221 if (preg_match('|^/|', $url)) {
6222 // URLs beginning with / are relative to web server root so we just add them in
6223 $url = $hostpart.$url;
6224 } else {
6225 // URLs not beginning with / are relative to path of current script, so add that on.
6226 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
6228 // Replace all ..s
6229 while (true) {
6230 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
6231 if ($newurl == $url) {
6232 break;
6234 $url = $newurl;
6238 $delay = 0;
6239 //try header redirection first
6240 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
6241 @header('Location: '.$url);
6242 //another way for older browsers and already sent headers (eg trailing whitespace in config.php)
6243 echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
6244 echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
6245 die;
6248 if ($delay == -1) {
6249 $delay = 3; // if no delay specified wait 3 seconds
6251 if (! defined('HEADER_PRINTED')) {
6252 // this type of redirect might not be working in some browsers - such as lynx :-(
6253 print_header('', '', '', '', $errorprinted ? '' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
6254 $delay += 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
6255 } else {
6256 print_container_end_all(false, $THEME->open_header_containers);
6258 echo '<div id="redirect">';
6259 echo '<div id="message">' . $message . '</div>';
6260 echo '<div id="continue">( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
6261 echo '</div>';
6263 if (!$errorprinted) {
6265 <script type="text/javascript">
6266 //<![CDATA[
6268 function redirect() {
6269 document.location.replace('<?php echo addslashes_js($url) ?>');
6271 setTimeout("redirect()", <?php echo ($delay * 1000) ?>);
6272 //]]>
6273 </script>
6274 <?php
6277 $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
6278 print_footer('none');
6279 die;
6283 * Print a bold message in an optional color.
6285 * @param string $message The message to print out
6286 * @param string $style Optional style to display message text in
6287 * @param string $align Alignment option
6288 * @param bool $return whether to return an output string or echo now
6290 function notify($message, $style='notifyproblem', $align='center', $return=false) {
6291 if ($style == 'green') {
6292 $style = 'notifysuccess'; // backward compatible with old color system
6295 $message = clean_text($message);
6297 $output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."\n";
6299 if ($return) {
6300 return $output;
6302 echo $output;
6307 * Given an email address, this function will return an obfuscated version of it
6309 * @param string $email The email address to obfuscate
6310 * @return string
6312 function obfuscate_email($email) {
6314 $i = 0;
6315 $length = strlen($email);
6316 $obfuscated = '';
6317 while ($i < $length) {
6318 if (rand(0,2) && $email{$i}!='@') { //MDL-20619 some browsers have problems unobfuscating @
6319 $obfuscated.='%'.dechex(ord($email{$i}));
6320 } else {
6321 $obfuscated.=$email{$i};
6323 $i++;
6325 return $obfuscated;
6329 * This function takes some text and replaces about half of the characters
6330 * with HTML entity equivalents. Return string is obviously longer.
6332 * @param string $plaintext The text to be obfuscated
6333 * @return string
6335 function obfuscate_text($plaintext) {
6337 $i=0;
6338 $length = strlen($plaintext);
6339 $obfuscated='';
6340 $prev_obfuscated = false;
6341 while ($i < $length) {
6342 $c = ord($plaintext{$i});
6343 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
6344 if ($prev_obfuscated and $numerical ) {
6345 $obfuscated.='&#'.ord($plaintext{$i}).';';
6346 } else if (rand(0,2)) {
6347 $obfuscated.='&#'.ord($plaintext{$i}).';';
6348 $prev_obfuscated = true;
6349 } else {
6350 $obfuscated.=$plaintext{$i};
6351 $prev_obfuscated = false;
6353 $i++;
6355 return $obfuscated;
6359 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
6360 * to generate a fully obfuscated email link, ready to use.
6362 * @param string $email The email address to display
6363 * @param string $label The text to dispalyed as hyperlink to $email
6364 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
6365 * @return string
6367 function obfuscate_mailto($email, $label='', $dimmed=false) {
6369 if (empty($label)) {
6370 $label = $email;
6372 if ($dimmed) {
6373 $title = get_string('emaildisable');
6374 $dimmed = ' class="dimmed"';
6375 } else {
6376 $title = '';
6377 $dimmed = '';
6379 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
6380 obfuscate_text('mailto'), obfuscate_email($email),
6381 obfuscate_text($label));
6385 * Prints a single paging bar to provide access to other pages (usually in a search)
6387 * @param int $totalcount Thetotal number of entries available to be paged through
6388 * @param int $page The page you are currently viewing
6389 * @param int $perpage The number of entries that should be shown per page
6390 * @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.
6391 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
6392 * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
6393 * @param bool $nocurr do not display the current page as a link
6394 * @param bool $return whether to return an output string or echo now
6395 * @return bool or string
6397 function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
6398 $maxdisplay = 18;
6399 $output = '';
6401 if ($totalcount > $perpage) {
6402 $output .= '<div class="paging">';
6403 $output .= get_string('page') .':';
6404 if ($page > 0) {
6405 $pagenum = $page - 1;
6406 if (!is_a($baseurl, 'moodle_url')){
6407 $output .= '&nbsp;(<a class="previous" href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>)&nbsp;';
6408 } else {
6409 $output .= '&nbsp;(<a class="previous" href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>)&nbsp;';
6412 if ($perpage > 0) {
6413 $lastpage = ceil($totalcount / $perpage);
6414 } else {
6415 $lastpage = 1;
6417 if ($page > 15) {
6418 $startpage = $page - 10;
6419 if (!is_a($baseurl, 'moodle_url')){
6420 $output .= '&nbsp;<a href="'. $baseurl . $pagevar .'=0">1</a>&nbsp;...';
6421 } else {
6422 $output .= '&nbsp;<a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a>&nbsp;...';
6424 } else {
6425 $startpage = 0;
6427 $currpage = $startpage;
6428 $displaycount = $displaypage = 0;
6429 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
6430 $displaypage = $currpage+1;
6431 if ($page == $currpage && empty($nocurr)) {
6432 $output .= '&nbsp;&nbsp;'. $displaypage;
6433 } else {
6434 if (!is_a($baseurl, 'moodle_url')){
6435 $output .= '&nbsp;&nbsp;<a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
6436 } else {
6437 $output .= '&nbsp;&nbsp;<a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
6441 $displaycount++;
6442 $currpage++;
6444 if ($currpage < $lastpage) {
6445 $lastpageactual = $lastpage - 1;
6446 if (!is_a($baseurl, 'moodle_url')){
6447 $output .= '&nbsp;...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a>&nbsp;';
6448 } else {
6449 $output .= '&nbsp;...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a>&nbsp;';
6452 $pagenum = $page + 1;
6453 if ($pagenum != $displaypage) {
6454 if (!is_a($baseurl, 'moodle_url')){
6455 $output .= '&nbsp;&nbsp;(<a class="next" href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
6456 } else {
6457 $output .= '&nbsp;&nbsp;(<a class="next" href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
6460 $output .= '</div>';
6463 if ($return) {
6464 return $output;
6467 echo $output;
6468 return true;
6472 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
6473 * will transform it to html entities
6475 * @param string $text Text to search for nolink tag in
6476 * @return string
6478 function rebuildnolinktag($text) {
6480 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
6482 return $text;
6486 * Prints a nice side block with an optional header. The content can either
6487 * be a block of HTML or a list of text with optional icons.
6489 * @param string $heading Block $title embedded in HTML tags, for example <h2>.
6490 * @param string $content ?
6491 * @param array $list ?
6492 * @param array $icons ?
6493 * @param string $footer ?
6494 * @param array $attributes ?
6495 * @param string $title Plain text title, as embedded in the $heading.
6496 * @todo Finish documenting this function. Show example of various attributes, etc.
6498 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
6500 //Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
6501 static $block_id = 0;
6502 $block_id++;
6503 $skip_text = get_string('skipa', 'access', strip_tags($title));
6504 $skip_link = '<a href="#sb-'.$block_id.'" class="skip-block">'.$skip_text.'</a>';
6505 $skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
6507 $strip_title = strip_tags($title);
6508 if (! empty($strip_title)) {
6509 echo $skip_link;
6511 //ELSE: a single link on a page "Skip block 4" is too confusing - ignore.
6513 print_side_block_start($heading, $attributes);
6515 if ($content) {
6516 echo $content;
6517 if ($footer) {
6518 echo '<div class="footer">'. $footer .'</div>';
6520 } else {
6521 if ($list) {
6522 $row = 0;
6523 //Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
6524 echo "\n<ul class='list'>\n";
6525 foreach ($list as $key => $string) {
6526 echo '<li class="r'. $row .'">';
6527 if ($icons) {
6528 echo '<div class="icon column c0">'. $icons[$key] .'</div>';
6530 echo '<div class="column c1">' . $string . '</div>';
6531 echo "</li>\n";
6532 $row = $row ? 0:1;
6534 echo "</ul>\n";
6536 if ($footer) {
6537 echo '<div class="footer">'. $footer .'</div>';
6542 print_side_block_end($attributes, $title);
6543 echo $skip_dest;
6547 * Starts a nice side block with an optional header.
6549 * @param string $heading ?
6550 * @param array $attributes ?
6551 * @todo Finish documenting this function
6553 function print_side_block_start($heading='', $attributes = array()) {
6555 global $CFG, $THEME;
6557 // If there are no special attributes, give a default CSS class
6558 if (empty($attributes) || !is_array($attributes)) {
6559 $attributes = array('class' => 'sideblock');
6561 } else if(!isset($attributes['class'])) {
6562 $attributes['class'] = 'sideblock';
6564 } else if(!strpos($attributes['class'], 'sideblock')) {
6565 $attributes['class'] .= ' sideblock';
6568 // OK, the class is surely there and in addition to anything
6569 // else, it's tagged as a sideblock
6573 // IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
6575 // If there is a cookie to hide this thing, start it hidden
6576 if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
6577 $attributes['class'] = 'hidden '.$attributes['class'];
6581 $attrtext = '';
6582 foreach ($attributes as $attr => $val) {
6583 $attrtext .= ' '.$attr.'="'.$val.'"';
6586 echo '<div '.$attrtext.'>';
6588 if (!empty($THEME->customcorners)) {
6589 echo '<div class="wrap">'."\n";
6591 if ($heading) {
6592 //Accessibility: H2 more appropriate in moodleblock.class.php: _title_html.
6593 echo '<div class="header">';
6594 if (!empty($THEME->customcorners)) {
6595 echo '<div class="bt"><div>&nbsp;</div></div>';
6596 echo '<div class="i1"><div class="i2">';
6597 echo '<div class="i3">';
6599 echo $heading;
6600 if (!empty($THEME->customcorners)) {
6601 echo '</div></div></div>';
6603 echo '</div>';
6604 } else {
6605 if (!empty($THEME->customcorners)) {
6606 echo '<div class="bt"><div>&nbsp;</div></div>';
6610 if (!empty($THEME->customcorners)) {
6611 echo '<div class="i1"><div class="i2">';
6612 echo '<div class="i3">';
6614 echo '<div class="content">';
6620 * Print table ending tags for a side block box.
6622 function print_side_block_end($attributes = array(), $title='') {
6623 global $CFG, $THEME;
6625 echo '</div>';
6627 if (!empty($THEME->customcorners)) {
6628 echo '</div></div></div><div class="bb"><div>&nbsp;</div></div></div>';
6631 echo '</div>';
6633 $strshow = addslashes_js(get_string('showblocka', 'access', strip_tags($title)));
6634 $strhide = addslashes_js(get_string('hideblocka', 'access', strip_tags($title)));
6636 // IE workaround: if I do it THIS way, it works! WTF?
6637 if (!empty($CFG->allowuserblockhiding) && isset($attributes['id'])) {
6638 echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].
6639 '","'.$strshow.'","'.$strhide."\");\n//]]>\n".'</script>';
6646 * Prints out code needed for spellchecking.
6647 * Original idea by Ludo (Marc Alier).
6649 * Opening CDATA and <script> are output by weblib::use_html_editor()
6650 * @uses $CFG
6651 * @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
6652 * @param boolean $return If false, echos the code instead of returning it
6653 * @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
6655 function print_speller_code ($usehtmleditor=false, $return=false) {
6656 global $CFG;
6657 $str = '';
6659 if(!$usehtmleditor) {
6660 $str .= 'function openSpellChecker() {'."\n";
6661 $str .= "\tvar speller = new spellChecker();\n";
6662 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot ."/lib/speller/spellchecker.html\";\n";
6663 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
6664 $str .= "\tspeller.spellCheckAll();\n";
6665 $str .= '}'."\n";
6666 } else {
6667 $str .= "function spellClickHandler(editor, buttonId) {\n";
6668 $str .= "\teditor._textArea.value = editor.getHTML();\n";
6669 $str .= "\tvar speller = new spellChecker( editor._textArea );\n";
6670 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot ."/lib/speller/spellchecker.html\";\n";
6671 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
6672 $str .= "\tspeller._moogle_edit=1;\n";
6673 $str .= "\tspeller._editor=editor;\n";
6674 $str .= "\tspeller.openChecker();\n";
6675 $str .= '}'."\n";
6678 if ($return) {
6679 return $str;
6681 echo $str;
6685 * Print button for spellchecking when editor is disabled
6687 function print_speller_button () {
6688 echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
6692 function page_id_and_class(&$getid, &$getclass) {
6693 // Create class and id for this page
6694 global $CFG, $ME;
6696 static $class = NULL;
6697 static $id = NULL;
6699 if (empty($CFG->pagepath)) {
6700 $CFG->pagepath = $ME;
6703 if (empty($class) || empty($id)) {
6704 $path = str_replace($CFG->httpswwwroot.'/', '', $CFG->pagepath); //Because the page could be HTTPSPAGEREQUIRED
6705 $path = str_replace('.php', '', $path);
6706 if (substr($path, -1) == '/') {
6707 $path .= 'index';
6709 if (empty($path) || $path == 'index') {
6710 $id = 'site-index';
6711 $class = 'course';
6712 } else if (substr($path, 0, 5) == 'admin') {
6713 $id = str_replace('/', '-', $path);
6714 $class = 'admin';
6715 } else {
6716 $id = str_replace('/', '-', $path);
6717 $class = explode('-', $id);
6718 array_pop($class);
6719 $class = implode('-', $class);
6723 $getid = $id;
6724 $getclass = $class;
6728 * Prints a maintenance message from /maintenance.html
6730 function print_maintenance_message () {
6731 global $CFG, $SITE;
6733 $CFG->pagepath = "index.php";
6734 print_header(strip_tags($SITE->fullname), $SITE->fullname, 'home');
6735 print_box_start();
6736 print_heading(get_string('sitemaintenance', 'admin'));
6737 @include($CFG->dataroot.'/'.SITEID.'/maintenance.html');
6738 print_box_end();
6739 print_footer();
6743 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
6745 function adjust_allowed_tags() {
6747 global $CFG, $ALLOWED_TAGS;
6749 if (!empty($CFG->allowobjectembed)) {
6750 $ALLOWED_TAGS .= '<embed><object>';
6754 /// Some code to print tabs
6756 /// A class for tabs
6757 class tabobject {
6758 var $id;
6759 var $link;
6760 var $text;
6761 var $linkedwhenselected;
6763 /// A constructor just because I like constructors
6764 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
6765 $this->id = $id;
6766 $this->link = $link;
6767 $this->text = $text;
6768 $this->title = $title ? $title : $text;
6769 $this->linkedwhenselected = $linkedwhenselected;
6776 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
6778 * @param array $tabrows An array of rows where each row is an array of tab objects
6779 * @param string $selected The id of the selected tab (whatever row it's on)
6780 * @param array $inactive An array of ids of inactive tabs that are not selectable.
6781 * @param array $activated An array of ids of other tabs that are currently activated
6783 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
6784 global $CFG;
6786 /// $inactive must be an array
6787 if (!is_array($inactive)) {
6788 $inactive = array();
6791 /// $activated must be an array
6792 if (!is_array($activated)) {
6793 $activated = array();
6796 /// Convert the tab rows into a tree that's easier to process
6797 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
6798 return false;
6801 /// Print out the current tree of tabs (this function is recursive)
6803 $output = convert_tree_to_html($tree);
6805 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
6807 /// We're done!
6809 if ($return) {
6810 return $output;
6812 echo $output;
6816 function convert_tree_to_html($tree, $row=0) {
6818 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
6820 $first = true;
6821 $count = count($tree);
6823 foreach ($tree as $tab) {
6824 $count--; // countdown to zero
6826 $liclass = '';
6828 if ($first && ($count == 0)) { // Just one in the row
6829 $liclass = 'first last';
6830 $first = false;
6831 } else if ($first) {
6832 $liclass = 'first';
6833 $first = false;
6834 } else if ($count == 0) {
6835 $liclass = 'last';
6838 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
6839 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
6842 if ($tab->inactive || $tab->active || $tab->selected) {
6843 if ($tab->selected) {
6844 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
6845 } else if ($tab->active) {
6846 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
6850 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
6852 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
6853 // The a tag is used for styling
6854 $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
6855 } else {
6856 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
6859 if (!empty($tab->subtree)) {
6860 $str .= convert_tree_to_html($tab->subtree, $row+1);
6861 } else if ($tab->selected) {
6862 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
6865 $str .= ' </li>'."\n";
6867 $str .= '</ul>'."\n";
6869 return $str;
6873 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
6875 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
6877 $tabrows = array_reverse($tabrows);
6879 $subtree = array();
6881 foreach ($tabrows as $row) {
6882 $tree = array();
6884 foreach ($row as $tab) {
6885 $tab->inactive = in_array((string)$tab->id, $inactive);
6886 $tab->active = in_array((string)$tab->id, $activated);
6887 $tab->selected = (string)$tab->id == $selected;
6889 if ($tab->active || $tab->selected) {
6890 if ($subtree) {
6891 $tab->subtree = $subtree;
6894 $tree[] = $tab;
6896 $subtree = $tree;
6899 return $subtree;
6904 * Returns a string containing a link to the user documentation for the current
6905 * page. Also contains an icon by default. Shown to teachers and admin only.
6907 * @param string $text The text to be displayed for the link
6908 * @param string $iconpath The path to the icon to be displayed
6910 function page_doc_link($text='', $iconpath='') {
6911 global $ME, $COURSE, $CFG;
6913 if (empty($CFG->docroot) or empty($CFG->rolesactive)) {
6914 return '';
6917 if (empty($COURSE->id)) {
6918 $context = get_context_instance(CONTEXT_SYSTEM);
6919 } else {
6920 $context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
6923 if (!has_capability('moodle/site:doclinks', $context)) {
6924 return '';
6927 if (empty($CFG->pagepath)) {
6928 $CFG->pagepath = $ME;
6931 $path = str_replace($CFG->httpswwwroot.'/','', $CFG->pagepath); // Because the page could be HTTPSPAGEREQUIRED
6932 $path = str_replace('.php', '', $path);
6934 if (empty($path)) { // Not for home page
6935 return '';
6937 return doc_link($path, $text, $iconpath);
6941 * Returns a string containing a link to the user documentation.
6942 * Also contains an icon by default. Shown to teachers and admin only.
6944 * @param string $path The page link after doc root and language, no
6945 * leading slash.
6946 * @param string $text The text to be displayed for the link
6947 * @param string $iconpath The path to the icon to be displayed
6949 function doc_link($path='', $text='', $iconpath='') {
6950 global $CFG;
6952 if (empty($CFG->docroot)) {
6953 return '';
6956 $target = '';
6957 if (!empty($CFG->doctonewwindow)) {
6958 $target = ' target="_blank"';
6961 $lang = str_replace('_utf8', '', current_language());
6963 $str = '<a href="' .$CFG->docroot. '/' .$lang. '/' .$path. '"' .$target. '>';
6965 if (empty($iconpath)) {
6966 $iconpath = $CFG->httpswwwroot . '/pix/docs.gif';
6969 // alt left blank intentionally to prevent repetition in screenreaders
6970 $str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
6972 return $str;
6977 * Returns true if the current site debugging settings are equal or above specified level.
6978 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
6979 * routing of notices is controlled by $CFG->debugdisplay
6980 * eg use like this:
6982 * 1) debugging('a normal debug notice');
6983 * 2) debugging('something really picky', DEBUG_ALL);
6984 * 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
6985 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
6987 * In code blocks controlled by debugging() (such as example 4)
6988 * any output should be routed via debugging() itself, or the lower-level
6989 * trigger_error() or error_log(). Using echo or print will break XHTML
6990 * JS and HTTP headers.
6993 * @param string $message a message to print
6994 * @param int $level the level at which this debugging statement should show
6995 * @return bool
6997 function debugging($message='', $level=DEBUG_NORMAL) {
6999 global $CFG;
7001 if (empty($CFG->debug)) {
7002 return false;
7005 if ($CFG->debug >= $level) {
7006 if ($message) {
7007 $callers = debug_backtrace();
7008 $from = '<ul style="text-align: left">';
7009 foreach ($callers as $caller) {
7010 if (!isset($caller['line'])) {
7011 $caller['line'] = '?'; // probably call_user_func()
7013 if (!isset($caller['file'])) {
7014 $caller['file'] = $CFG->dirroot.'/unknownfile'; // probably call_user_func()
7016 $from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
7017 if (isset($caller['function'])) {
7018 $from .= ': call to ';
7019 if (isset($caller['class'])) {
7020 $from .= $caller['class'] . $caller['type'];
7022 $from .= $caller['function'] . '()';
7024 $from .= '</li>';
7026 $from .= '</ul>';
7027 if (!isset($CFG->debugdisplay)) {
7028 $CFG->debugdisplay = ini_get_bool('display_errors');
7030 if ($CFG->debugdisplay) {
7031 if (!defined('DEBUGGING_PRINTED')) {
7032 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
7034 notify($message . $from, 'notifytiny');
7035 } else {
7036 trigger_error($message . $from, E_USER_NOTICE);
7039 return true;
7041 return false;
7045 * Disable debug messages from debugging(), while keeping PHP error reporting level as is.
7047 function disable_debugging() {
7048 global $CFG;
7049 $CFG->debug = $CFG->debug | 0x80000000; // switch the sign bit in integer number ;-)
7054 * Returns string to add a frame attribute, if required
7056 function frametarget() {
7057 global $CFG;
7059 if (empty($CFG->framename) or ($CFG->framename == '_top')) {
7060 return '';
7061 } else {
7062 return ' target="'.$CFG->framename.'" ';
7067 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
7068 * pages that use bits from many different files in very confusing ways (e.g. blocks).
7069 * @usage print_location_comment(__FILE__, __LINE__);
7070 * @param string $file
7071 * @param integer $line
7072 * @param boolean $return Whether to return or print the comment
7073 * @return mixed Void unless true given as third parameter
7075 function print_location_comment($file, $line, $return = false)
7077 if ($return) {
7078 return "<!-- $file at line $line -->\n";
7079 } else {
7080 echo "<!-- $file at line $line -->\n";
7086 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
7087 * provide this function with the language strings for sortasc and sortdesc.
7088 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
7089 * @param string $direction 'up' or 'down'
7090 * @param string $strsort The language string used for the alt attribute of this image
7091 * @param bool $return Whether to print directly or return the html string
7092 * @return string HTML for the image
7094 * TODO See if this isn't already defined somewhere. If not, move this to weblib
7096 function print_arrow($direction='up', $strsort=null, $return=false) {
7097 global $CFG;
7099 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
7100 return null;
7103 $return = null;
7105 switch ($direction) {
7106 case 'up':
7107 $sortdir = 'asc';
7108 break;
7109 case 'down':
7110 $sortdir = 'desc';
7111 break;
7112 case 'move':
7113 $sortdir = 'asc';
7114 break;
7115 default:
7116 $sortdir = null;
7117 break;
7120 // Prepare language string
7121 $strsort = '';
7122 if (empty($strsort) && !empty($sortdir)) {
7123 $strsort = get_string('sort' . $sortdir, 'grades');
7126 $return = ' <img src="'.$CFG->pixpath.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
7128 if ($return) {
7129 return $return;
7130 } else {
7131 echo $return;
7136 * Returns boolean true if the current language is right-to-left (Hebrew, Arabic etc)
7139 function right_to_left() {
7140 static $result;
7142 if (isset($result)) {
7143 return $result;
7145 return $result = (get_string('thisdirection') == 'rtl');
7150 * Returns swapped left<=>right if in RTL environment.
7151 * part of RTL support
7153 * @param string $align align to check
7154 * @return string
7156 function fix_align_rtl($align) {
7157 if (!right_to_left()) {
7158 return $align;
7160 if ($align=='left') { return 'right'; }
7161 if ($align=='right') { return 'left'; }
7162 return $align;
7167 * Returns true if the page is displayed in a popup window.
7168 * Gets the information from the URL parameter inpopup.
7170 * @return boolean
7172 * TODO Use a central function to create the popup calls allover Moodle and
7173 * TODO In the moment only works with resources and probably questions.
7175 function is_in_popup() {
7176 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
7178 return ($inpopup);
7182 * Return the authentication plugin title
7183 * @param string $authtype plugin type
7184 * @return string
7186 function auth_get_plugin_title ($authtype) {
7187 $authtitle = get_string("auth_{$authtype}title", "auth");
7188 if ($authtitle == "[[auth_{$authtype}title]]") {
7189 $authtitle = get_string("auth_{$authtype}title", "auth_{$authtype}");
7191 return $authtitle;
7195 * Returns a localized sentence in the current language summarizing the current password policy
7197 * @uses $CFG
7198 * @return string
7200 function print_password_policy() {
7201 global $CFG;
7203 $message = '';
7204 if (!empty($CFG->passwordpolicy)) {
7205 $messages = array();
7206 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
7207 if (!empty($CFG->minpassworddigits)) {
7208 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
7210 if (!empty($CFG->minpasswordlower)) {
7211 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
7213 if (!empty($CFG->minpasswordupper)) {
7214 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
7216 if (!empty($CFG->minpasswordnonalphanum)) {
7217 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
7220 $messages = join(', ', $messages); // this is ugly but we do not have anything better yet...
7221 $message = get_string('informpasswordpolicy', 'auth', $messages);
7223 return $message;
7226 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: