MDL-23726 fixed phpdocs - credit goes to Henning Bostelmann
[moodle.git] / lib / weblib.php
blob7e63178df311e4d001c2572de874e28e990059a5
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', 'margin', 'padding', 'background', 'background-color', 'text-decoration'); // CSS as well to get through kses
107 /// Functions
110 * Add quotes to HTML characters
112 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
113 * This function is very similar to {@link p()}
115 * @param string $var the string potentially containing HTML characters
116 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
117 * true should be used to print data from forms and false for data from DB.
118 * @return string
120 function s($var, $strip=false) {
122 if ($var === '0' or $var === false or $var === 0) {
123 return '0';
126 if ($strip) {
127 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars(stripslashes_safe($var)));
128 } else {
129 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars($var));
134 * Add quotes to HTML characters
136 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
137 * This function is very similar to {@link s()}
139 * @param string $var the string potentially containing HTML characters
140 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
141 * true should be used to print data from forms and false for data from DB.
142 * @return string
144 function p($var, $strip=false) {
145 echo s($var, $strip);
149 * Does proper javascript quoting.
150 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
152 * @since 1.8 - 22/02/2007
153 * @param mixed value
154 * @return mixed quoted result
156 function addslashes_js($var) {
157 if (is_string($var)) {
158 $var = str_replace('\\', '\\\\', $var);
159 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
160 $var = str_replace('</', '<\/', $var); // XHTML compliance
161 } else if (is_array($var)) {
162 $var = array_map('addslashes_js', $var);
163 } else if (is_object($var)) {
164 $a = get_object_vars($var);
165 foreach ($a as $key=>$value) {
166 $a[$key] = addslashes_js($value);
168 $var = (object)$a;
170 return $var;
174 * Remove query string from url
176 * Takes in a URL and returns it without the querystring portion
178 * @param string $url the url which may have a query string attached
179 * @return string
181 function strip_querystring($url) {
183 if ($commapos = strpos($url, '?')) {
184 return substr($url, 0, $commapos);
185 } else {
186 return $url;
191 * Returns the URL of the HTTP_REFERER, less the querystring portion if required
192 * @param boolean $stripquery if true, also removes the query part of the url.
193 * @return string
195 function get_referer($stripquery=true) {
196 if (isset($_SERVER['HTTP_REFERER'])) {
197 if ($stripquery) {
198 return strip_querystring($_SERVER['HTTP_REFERER']);
199 } else {
200 return $_SERVER['HTTP_REFERER'];
202 } else {
203 return '';
209 * Returns the name of the current script, WITH the querystring portion.
210 * this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
211 * return different things depending on a lot of things like your OS, Web
212 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
213 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
215 * @return string
217 function me() {
219 if (!empty($_SERVER['REQUEST_URI'])) {
220 return $_SERVER['REQUEST_URI'];
222 } else if (!empty($_SERVER['PHP_SELF'])) {
223 if (!empty($_SERVER['QUERY_STRING'])) {
224 return $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
226 return $_SERVER['PHP_SELF'];
228 } else if (!empty($_SERVER['SCRIPT_NAME'])) {
229 if (!empty($_SERVER['QUERY_STRING'])) {
230 return $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
232 return $_SERVER['SCRIPT_NAME'];
234 } else if (!empty($_SERVER['URL'])) { // May help IIS (not well tested)
235 if (!empty($_SERVER['QUERY_STRING'])) {
236 return $_SERVER['URL'] .'?'. $_SERVER['QUERY_STRING'];
238 return $_SERVER['URL'];
240 } else {
241 notify('Warning: Could not find any of these web server variables: $REQUEST_URI, $PHP_SELF, $SCRIPT_NAME or $URL');
242 return false;
247 * Like {@link me()} but returns a full URL
248 * @see me()
249 * @return string
251 function qualified_me() {
253 global $CFG;
255 if (!empty($CFG->wwwroot)) {
256 $url = parse_url($CFG->wwwroot);
259 if (!empty($url['host'])) {
260 $hostname = $url['host'];
261 } else if (!empty($_SERVER['SERVER_NAME'])) {
262 $hostname = $_SERVER['SERVER_NAME'];
263 } else if (!empty($_ENV['SERVER_NAME'])) {
264 $hostname = $_ENV['SERVER_NAME'];
265 } else if (!empty($_SERVER['HTTP_HOST'])) {
266 $hostname = $_SERVER['HTTP_HOST'];
267 } else if (!empty($_ENV['HTTP_HOST'])) {
268 $hostname = $_ENV['HTTP_HOST'];
269 } else {
270 notify('Warning: could not find the name of this server!');
271 return false;
274 if (!empty($url['port'])) {
275 $hostname .= ':'.$url['port'];
276 } else if (!empty($_SERVER['SERVER_PORT'])) {
277 if ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
278 $hostname .= ':'.$_SERVER['SERVER_PORT'];
282 // TODO, this does not work in the situation described in MDL-11061, but
283 // I don't know how to fix it. Possibly believe $CFG->wwwroot ahead of what
284 // the server reports.
285 if (isset($_SERVER['HTTPS'])) {
286 $protocol = ($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
287 } else if (isset($_SERVER['SERVER_PORT'])) { # Apache2 does not export $_SERVER['HTTPS']
288 $protocol = ($_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
289 } else {
290 $protocol = 'http://';
293 $url_prefix = $protocol.$hostname;
294 return $url_prefix . me();
299 * Class for creating and manipulating urls.
301 * See short write up here http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url
303 class moodle_url {
304 var $scheme = '';// e.g. http
305 var $host = '';
306 var $port = '';
307 var $user = '';
308 var $pass = '';
309 var $path = '';
310 var $fragment = '';
311 var $params = array(); //associative array of query string params
314 * Pass no arguments to create a url that refers to this page. Use empty string to create empty url.
316 * @param string $url url default null means use this page url with no query string
317 * empty string means empty url.
318 * if you pass any other type of url it will be parsed into it's bits, including query string
319 * @param array $params these params override anything in the query string where params have the same name.
321 function moodle_url($url = null, $params = array()){
322 global $FULLME;
323 if ($url !== ''){
324 if ($url === null){
325 $url = strip_querystring($FULLME);
327 $parts = parse_url($url);
328 if ($parts === FALSE){
329 error('invalidurl');
331 if (isset($parts['query'])){
332 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
334 unset($parts['query']);
335 foreach ($parts as $key => $value){
336 $this->$key = $value;
338 $this->params($params);
343 * Add an array of params to the params for this page.
345 * The added params override existing ones if they have the same name.
347 * @param array $params Defaults to null. If null then return value of param 'name'.
348 * @return array Array of Params for url.
350 function params($params = null) {
351 if (!is_null($params)) {
352 return $this->params = $params + $this->params;
353 } else {
354 return $this->params;
359 * Remove all params if no arguments passed. Or else remove param $arg1, $arg2, etc.
361 * @param string $arg1
362 * @param string $arg2
363 * @param string $arg3
365 function remove_params(){
366 if ($thisargs = func_get_args()){
367 foreach ($thisargs as $arg){
368 if (isset($this->params[$arg])){
369 unset($this->params[$arg]);
372 } else { // no args
373 $this->params = array();
378 * Add a param to the params for this page. The added param overrides existing one if they
379 * have the same name.
381 * @param string $paramname name
382 * @param string $param value
384 function param($paramname, $param){
385 $this->params = array($paramname => $param) + $this->params;
389 function get_query_string($overrideparams = array()){
390 $arr = array();
391 $params = $overrideparams + $this->params;
392 foreach ($params as $key => $val){
393 $arr[] = urlencode($key)."=".urlencode($val);
395 return implode($arr, "&amp;");
398 * Outputs params as hidden form elements.
400 * @param array $exclude params to ignore
401 * @param integer $indent indentation
402 * @param array $overrideparams params to add to the output params, these
403 * override existing ones with the same name.
404 * @return string html for form elements.
406 function hidden_params_out($exclude = array(), $indent = 0, $overrideparams=array()){
407 $tabindent = str_repeat("\t", $indent);
408 $str = '';
409 $params = $overrideparams + $this->params;
410 foreach ($params as $key => $val){
411 if (FALSE === array_search($key, $exclude)) {
412 $val = s($val);
413 $str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
416 return $str;
419 * Output url
421 * @param boolean $noquerystring whether to output page params as a query string in the url.
422 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
423 * @return string url
425 function out($noquerystring = false, $overrideparams = array()) {
426 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
427 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
428 $uri .= $this->host ? $this->host : '';
429 $uri .= $this->port ? ':'.$this->port : '';
430 $uri .= $this->path ? $this->path : '';
431 if (!$noquerystring){
432 $uri .= (count($this->params)||count($overrideparams)) ? '?'.$this->get_query_string($overrideparams) : '';
434 $uri .= $this->fragment ? '#'.$this->fragment : '';
435 return $uri;
438 * Output action url with sesskey
440 * @param boolean $noquerystring whether to output page params as a query string in the url.
441 * @return string url
443 function out_action($overrideparams = array()) {
444 $overrideparams = array('sesskey'=> sesskey()) + $overrideparams;
445 return $this->out(false, $overrideparams);
450 * Determine if there is data waiting to be processed from a form
452 * Used on most forms in Moodle to check for data
453 * Returns the data as an object, if it's found.
454 * This object can be used in foreach loops without
455 * casting because it's cast to (array) automatically
457 * Checks that submitted POST data exists and returns it as object.
459 * @param string $url not used anymore
460 * @return mixed false or object
462 function data_submitted($url='') {
464 if (empty($_POST)) {
465 return false;
466 } else {
467 return (object)$_POST;
472 * Moodle replacement for php stripslashes() function,
473 * works also for objects and arrays.
475 * The standard php stripslashes() removes ALL backslashes
476 * even from strings - so C:\temp becomes C:temp - this isn't good.
477 * This function should work as a fairly safe replacement
478 * to be called on quoted AND unquoted strings (to be sure)
480 * @param mixed something to remove unsafe slashes from
481 * @return mixed
483 function stripslashes_safe($mixed) {
484 // there is no need to remove slashes from int, float and bool types
485 if (empty($mixed)) {
486 //nothing to do...
487 } else if (is_string($mixed)) {
488 if (ini_get_bool('magic_quotes_sybase')) { //only unescape single quotes
489 $mixed = str_replace("''", "'", $mixed);
490 } else { //the rest, simple and double quotes and backslashes
491 $mixed = str_replace("\\'", "'", $mixed);
492 $mixed = str_replace('\\"', '"', $mixed);
493 $mixed = str_replace('\\\\', '\\', $mixed);
495 } else if (is_array($mixed)) {
496 foreach ($mixed as $key => $value) {
497 $mixed[$key] = stripslashes_safe($value);
499 } else if (is_object($mixed)) {
500 $vars = get_object_vars($mixed);
501 foreach ($vars as $key => $value) {
502 $mixed->$key = stripslashes_safe($value);
506 return $mixed;
510 * Recursive implementation of stripslashes()
512 * This function will allow you to strip the slashes from a variable.
513 * If the variable is an array or object, slashes will be stripped
514 * from the items (or properties) it contains, even if they are arrays
515 * or objects themselves.
517 * @param mixed the variable to remove slashes from
518 * @return mixed
520 function stripslashes_recursive($var) {
521 if (is_object($var)) {
522 $new_var = new object();
523 $properties = get_object_vars($var);
524 foreach($properties as $property => $value) {
525 $new_var->$property = stripslashes_recursive($value);
528 } else if(is_array($var)) {
529 $new_var = array();
530 foreach($var as $property => $value) {
531 $new_var[$property] = stripslashes_recursive($value);
534 } else if(is_string($var)) {
535 $new_var = stripslashes($var);
537 } else {
538 $new_var = $var;
541 return $new_var;
545 * Recursive implementation of addslashes()
547 * This function will allow you to add the slashes from a variable.
548 * If the variable is an array or object, slashes will be added
549 * to the items (or properties) it contains, even if they are arrays
550 * or objects themselves.
552 * @param mixed the variable to add slashes from
553 * @return mixed
555 function addslashes_recursive($var) {
556 if (is_object($var)) {
557 $new_var = new object();
558 $properties = get_object_vars($var);
559 foreach($properties as $property => $value) {
560 $new_var->$property = addslashes_recursive($value);
563 } else if (is_array($var)) {
564 $new_var = array();
565 foreach($var as $property => $value) {
566 $new_var[$property] = addslashes_recursive($value);
569 } else if (is_string($var)) {
570 $new_var = addslashes($var);
572 } else { // nulls, integers, etc.
573 $new_var = $var;
576 return $new_var;
580 * Given some normal text this function will break up any
581 * long words to a given size by inserting the given character
583 * It's multibyte savvy and doesn't change anything inside html tags.
585 * @param string $string the string to be modified
586 * @param int $maxsize maximum length of the string to be returned
587 * @param string $cutchar the string used to represent word breaks
588 * @return string
590 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
592 /// Loading the textlib singleton instance. We are going to need it.
593 $textlib = textlib_get_instance();
595 /// First of all, save all the tags inside the text to skip them
596 $tags = array();
597 filter_save_tags($string,$tags);
599 /// Process the string adding the cut when necessary
600 $output = '';
601 $length = $textlib->strlen($string);
602 $wordlength = 0;
604 for ($i=0; $i<$length; $i++) {
605 $char = $textlib->substr($string, $i, 1);
606 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
607 $wordlength = 0;
608 } else {
609 $wordlength++;
610 if ($wordlength > $maxsize) {
611 $output .= $cutchar;
612 $wordlength = 0;
615 $output .= $char;
618 /// Finally load the tags back again
619 if (!empty($tags)) {
620 $output = str_replace(array_keys($tags), $tags, $output);
623 return $output;
627 * This does a search and replace, ignoring case
628 * This function is only used for versions of PHP older than version 5
629 * which do not have a native version of this function.
630 * Taken from the PHP manual, by bradhuizenga @ softhome.net
632 * @param string $find the string to search for
633 * @param string $replace the string to replace $find with
634 * @param string $string the string to search through
635 * return string
637 if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
638 function str_ireplace($find, $replace, $string) {
640 if (!is_array($find)) {
641 $find = array($find);
644 if(!is_array($replace)) {
645 if (!is_array($find)) {
646 $replace = array($replace);
647 } else {
648 // this will duplicate the string into an array the size of $find
649 $c = count($find);
650 $rString = $replace;
651 unset($replace);
652 for ($i = 0; $i < $c; $i++) {
653 $replace[$i] = $rString;
658 foreach ($find as $fKey => $fItem) {
659 $between = explode(strtolower($fItem),strtolower($string));
660 $pos = 0;
661 foreach($between as $bKey => $bItem) {
662 $between[$bKey] = substr($string,$pos,strlen($bItem));
663 $pos += strlen($bItem) + strlen($fItem);
665 $string = implode($replace[$fKey],$between);
667 return ($string);
672 * Locate the position of a string in another string
674 * This function is only used for versions of PHP older than version 5
675 * which do not have a native version of this function.
676 * Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
678 * @param string $haystack The string to be searched
679 * @param string $needle The string to search for
680 * @param int $offset The position in $haystack where the search should begin.
682 if (!function_exists('stripos')) { /// Only exists in PHP 5
683 function stripos($haystack, $needle, $offset=0) {
685 return strpos(strtoupper($haystack), strtoupper($needle), $offset);
690 * This function will print a button/link/etc. form element
691 * that will work on both Javascript and non-javascript browsers.
692 * Relies on the Javascript function openpopup in javascript.php
694 * All parameters default to null, only $type and $url are mandatory.
696 * $url must be relative to home page eg /mod/survey/stuff.php
697 * @param string $url Web link relative to home page
698 * @param string $name Name to be assigned to the popup window (this is used by
699 * client-side scripts to "talk" to the popup window)
700 * @param string $linkname Text to be displayed as web link
701 * @param int $height Height to assign to popup window
702 * @param int $width Height to assign to popup window
703 * @param string $title Text to be displayed as popup page title
704 * @param string $options List of additional options for popup window
705 * @param string $return If true, return as a string, otherwise print
706 * @param string $id id added to the element
707 * @param string $class class added to the element
708 * @return string
709 * @uses $CFG
711 function element_to_popup_window ($type=null, $url=null, $name=null, $linkname=null,
712 $height=400, $width=500, $title=null,
713 $options=null, $return=false, $id=null, $class=null) {
715 if (is_null($url)) {
716 debugging('You must give the url to display in the popup. URL is missing - can\'t create popup window.', DEBUG_DEVELOPER);
719 global $CFG;
721 if ($options == 'none') { // 'none' is legacy, should be removed in v2.0
722 $options = null;
725 // add some sane default options for popup windows
726 if (!$options) {
727 $options = 'menubar=0,location=0,scrollbars,resizable';
729 if ($width) {
730 $options .= ',width='. $width;
732 if ($height) {
733 $options .= ',height='. $height;
735 if ($id) {
736 $id = ' id="'.$id.'" ';
738 if ($class) {
739 $class = ' class="'.$class.'" ';
741 if ($name) {
742 $_name = $name;
743 if (($name = preg_replace("/\s/", '_', $name)) != $_name) {
744 debugging('The $name of a popup window shouldn\'t contain spaces - string modified. '. $_name .' changed to '. $name, DEBUG_DEVELOPER);
746 } else {
747 $name = 'popup';
750 // get some default string, using the localized version of legacy defaults
751 if (is_null($linkname) || $linkname === '') {
752 $linkname = get_string('clickhere');
754 if (!$title) {
755 $title = get_string('popupwindowname');
758 $fullscreen = 0; // must be passed to openpopup
759 $element = '';
761 switch ($type) {
762 case 'button' :
763 $element = '<input type="button" name="'. $name .'" title="'. $title .'" value="'. $linkname .'" '. $id . $class .
764 "onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
765 break;
766 case 'link' :
767 // some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
768 if (!(strpos($url,$CFG->wwwroot) === false)) {
769 $url = substr($url, strlen($CFG->wwwroot));
771 $element = '<a title="'. s(strip_tags($title)) .'" href="'. $CFG->wwwroot . $url .'" '.
772 "$CFG->frametarget onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
773 break;
774 default :
775 error('Undefined element - can\'t create popup window.');
776 break;
779 if ($return) {
780 return $element;
781 } else {
782 echo $element;
787 * Creates and displays (or returns) a link to a popup window, using element_to_popup_window function.
789 * @return string html code to display a link to a popup window.
790 * @see element_to_popup_window()
792 function link_to_popup_window ($url, $name=null, $linkname=null,
793 $height=400, $width=500, $title=null,
794 $options=null, $return=false) {
796 return element_to_popup_window('link', $url, $name, $linkname, $height, $width, $title, $options, $return, null, null);
800 * Creates and displays (or returns) a buttons to a popup window, using element_to_popup_window function.
802 * @return string html code to display a button to a popup window.
803 * @see element_to_popup_window()
805 function button_to_popup_window ($url, $name=null, $linkname=null,
806 $height=400, $width=500, $title=null, $options=null, $return=false,
807 $id=null, $class=null) {
809 return element_to_popup_window('button', $url, $name, $linkname, $height, $width, $title, $options, $return, $id, $class);
814 * Prints a simple button to close a window
815 * @param string $name name of the window to close
816 * @param boolean $return whether this function should return a string or output it
817 * @return string if $return is true, nothing otherwise
819 function close_window_button($name='closewindow', $return=false) {
820 global $CFG;
822 $output = '';
824 $output .= '<div class="closewindow">' . "\n";
825 $output .= '<form action="#"><div>';
826 $output .= '<input type="button" onclick="self.close();" value="'.get_string($name).'" />';
827 $output .= '</div></form>';
828 $output .= '</div>' . "\n";
830 if ($return) {
831 return $output;
832 } else {
833 echo $output;
838 * Try and close the current window immediately using Javascript
839 * @param int $delay the delay in seconds before closing the window
841 function close_window($delay=0) {
843 <script type="text/javascript">
844 //<![CDATA[
845 function close_this_window() {
846 self.close();
848 setTimeout("close_this_window()", <?php echo $delay * 1000 ?>);
849 //]]>
850 </script>
851 <noscript><center>
852 <?php print_string('pleaseclose') ?>
853 </center></noscript>
854 <?php
855 die;
859 * Given an array of values, output the HTML for a select element with those options.
860 * Normally, you only need to use the first few parameters.
862 * @param array $options The options to offer. An array of the form
863 * $options[{value}] = {text displayed for that option};
864 * @param string $name the name of this form control, as in &lt;select name="..." ...
865 * @param string $selected the option to select initially, default none.
866 * @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
867 * Set this to '' if you don't want a 'nothing is selected' option.
868 * @param string $script in not '', then this is added to the &lt;select> element as an onchange handler.
869 * @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
870 * @param boolean $return if false (the default) the the output is printed directly, If true, the
871 * generated HTML is returned as a string.
872 * @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
873 * @param int $tabindex if give, sets the tabindex attribute on the &lt;select> element. Default none.
874 * @param string $id value to use for the id attribute of the &lt;select> element. If none is given,
875 * then a suitable one is constructed.
876 * @param mixed $listbox if false, display as a dropdown menu. If true, display as a list box.
877 * By default, the list box will have a number of rows equal to min(10, count($options)), but if
878 * $listbox is an integer, that number is used for size instead.
879 * @param boolean $multiple if true, enable multiple selections, else only 1 item can be selected. Used
880 * when $listbox display is enabled
881 * @param string $class value to use for the class attribute of the &lt;select> element. If none is given,
882 * then a suitable one is constructed.
884 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
885 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0,
886 $id='', $listbox=false, $multiple=false, $class='') {
888 if ($nothing == 'choose') {
889 $nothing = get_string('choose') .'...';
892 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
893 if ($disabled) {
894 $attributes .= ' disabled="disabled"';
897 if ($tabindex) {
898 $attributes .= ' tabindex="'.$tabindex.'"';
901 if ($id ==='') {
902 $id = 'menu'.$name;
903 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
904 $id = str_replace('[', '', $id);
905 $id = str_replace(']', '', $id);
908 if ($class ==='') {
909 $class = 'menu'.$name;
910 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
911 $class = str_replace('[', '', $class);
912 $class = str_replace(']', '', $class);
914 $class = 'select ' . $class; /// Add 'select' selector always
916 if ($listbox) {
917 if (is_integer($listbox)) {
918 $size = $listbox;
919 } else {
920 $numchoices = count($options);
921 if ($nothing) {
922 $numchoices += 1;
924 $size = min(10, $numchoices);
926 $attributes .= ' size="' . $size . '"';
927 if ($multiple) {
928 $attributes .= ' multiple="multiple"';
932 $output = '<select id="'. $id .'" class="'. $class .'" name="'. $name .'" '. $attributes .'>' . "\n";
933 if ($nothing) {
934 $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
935 if ($nothingvalue === $selected) {
936 $output .= ' selected="selected"';
938 $output .= '>'. $nothing .'</option>' . "\n";
941 if (!empty($options)) {
942 foreach ($options as $value => $label) {
943 $output .= ' <option value="'. s($value) .'"';
944 if ((string)$value == (string)$selected ||
945 (is_array($selected) && in_array($value, $selected))) {
946 $output .= ' selected="selected"';
948 if ($label === '') {
949 $output .= '>'. $value .'</option>' . "\n";
950 } else {
951 $output .= '>'. $label .'</option>' . "\n";
955 $output .= '</select>' . "\n";
957 if ($return) {
958 return $output;
959 } else {
960 echo $output;
965 * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
966 * Other options like choose_from_menu.
967 * @param string $name
968 * @param string $selected
969 * @param string $string (defaults to '')
970 * @param boolean $return whether this function should return a string or output it (defaults to false)
971 * @param boolean $disabled (defaults to false)
972 * @param int $tabindex
974 function choose_from_menu_yesno($name, $selected, $script = '',
975 $return = false, $disabled = false, $tabindex = 0) {
976 return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
977 $selected, '', $script, '0', $return, $disabled, $tabindex);
981 * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
982 * including option headings with the first level.
984 function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
985 $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
987 if ($nothing == 'choose') {
988 $nothing = get_string('choose') .'...';
991 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
992 if ($disabled) {
993 $attributes .= ' disabled="disabled"';
996 if ($tabindex) {
997 $attributes .= ' tabindex="'.$tabindex.'"';
1000 $output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
1001 if ($nothing) {
1002 $output .= ' <option value="'. $nothingvalue .'"'. "\n";
1003 if ($nothingvalue === $selected) {
1004 $output .= ' selected="selected"';
1006 $output .= '>'. $nothing .'</option>' . "\n";
1008 if (!empty($options)) {
1009 foreach ($options as $section => $values) {
1010 $output .= ' <optgroup label="'. s(strip_tags(format_string($section))) .'">'."\n";
1011 foreach ($values as $value => $label) {
1012 $output .= ' <option value="'. format_string($value) .'"';
1013 if ((string)$value == (string)$selected) {
1014 $output .= ' selected="selected"';
1016 if ($label === '') {
1017 $output .= '>'. $value .'</option>' . "\n";
1018 } else {
1019 $output .= '>'. $label .'</option>' . "\n";
1022 $output .= ' </optgroup>'."\n";
1025 $output .= '</select>' . "\n";
1027 if ($return) {
1028 return $output;
1029 } else {
1030 echo $output;
1036 * Given an array of values, creates a group of radio buttons to be part of a form
1038 * @param array $options An array of value-label pairs for the radio group (values as keys)
1039 * @param string $name Name of the radiogroup (unique in the form)
1040 * @param string $checked The value that is already checked
1042 function choose_from_radio ($options, $name, $checked='', $return=false) {
1044 static $idcounter = 0;
1046 if (!$name) {
1047 $name = 'unnamed';
1050 $output = '<span class="radiogroup '.$name."\">\n";
1052 if (!empty($options)) {
1053 $currentradio = 0;
1054 foreach ($options as $value => $label) {
1055 $htmlid = 'auto-rb'.sprintf('%04d', ++$idcounter);
1056 $output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
1057 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
1058 if ($value == $checked) {
1059 $output .= ' checked="checked"';
1061 if ($label === '') {
1062 $output .= ' /> <label for="'.$htmlid.'">'. $value .'</label></span>' . "\n";
1063 } else {
1064 $output .= ' /> <label for="'.$htmlid.'">'. $label .'</label></span>' . "\n";
1066 $currentradio = ($currentradio + 1) % 2;
1070 $output .= '</span>' . "\n";
1072 if ($return) {
1073 return $output;
1074 } else {
1075 echo $output;
1079 /** Display an standard html checkbox with an optional label
1081 * @param string $name The name of the checkbox
1082 * @param string $value The valus that the checkbox will pass when checked
1083 * @param boolean $checked The flag to tell the checkbox initial state
1084 * @param string $label The label to be showed near the checkbox
1085 * @param string $alt The info to be inserted in the alt tag
1087 function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
1089 static $idcounter = 0;
1091 if (!$name) {
1092 $name = 'unnamed';
1095 if ($alt) {
1096 $alt = strip_tags($alt);
1097 } else {
1098 $alt = 'checkbox';
1101 if ($checked) {
1102 $strchecked = ' checked="checked"';
1103 } else {
1104 $strchecked = '';
1107 $htmlid = 'auto-cb'.sprintf('%04d', ++$idcounter);
1108 $output = '<span class="checkbox '.$name."\">";
1109 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ? ' onclick="'.$script.'" ' : '').' />';
1110 if(!empty($label)) {
1111 $output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
1113 $output .= '</span>'."\n";
1115 if (empty($return)) {
1116 echo $output;
1117 } else {
1118 return $output;
1123 /** Display an standard html text field with an optional label
1125 * @param string $name The name of the text field
1126 * @param string $value The value of the text field
1127 * @param string $label The label to be showed near the text field
1128 * @param string $alt The info to be inserted in the alt tag
1130 function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
1132 static $idcounter = 0;
1134 if (empty($name)) {
1135 $name = 'unnamed';
1138 if (empty($alt)) {
1139 $alt = 'textfield';
1142 if (!empty($maxlength)) {
1143 $maxlength = ' maxlength="'.$maxlength.'" ';
1146 $htmlid = 'auto-tf'.sprintf('%04d', ++$idcounter);
1147 $output = '<span class="textfield '.$name."\">";
1148 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
1150 $output .= '</span>'."\n";
1152 if (empty($return)) {
1153 echo $output;
1154 } else {
1155 return $output;
1162 * Implements a complete little popup form
1164 * @uses $CFG
1165 * @param string $common The URL up to the point of the variable that changes
1166 * @param array $options Alist of value-label pairs for the popup list
1167 * @param string $formid Id must be unique on the page (originaly $formname)
1168 * @param string $selected The option that is already selected
1169 * @param string $nothing The label for the "no choice" option
1170 * @param string $help The name of a help page if help is required
1171 * @param string $helptext The name of the label for the help button
1172 * @param boolean $return Indicates whether the function should return the text
1173 * as a string or echo it directly to the page being rendered
1174 * @param string $targetwindow The name of the target page to open the linked page in.
1175 * @param string $selectlabel Text to place in a [label] element - preferred for accessibility.
1176 * @param array $optionsextra TODO, an array?
1177 * @param mixed $gobutton If set, this turns off the JavaScript and uses a 'go'
1178 * button instead (as is always included for JS-disabled users). Set to true
1179 * for a literal 'Go' button, or to a string to change the name of the button.
1180 * @return string If $return is true then the entire form is returned as a string.
1181 * @todo Finish documenting this function<br>
1183 function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
1184 $targetwindow='self', $selectlabel='', $optionsextra=NULL, $gobutton=NULL) {
1186 global $CFG;
1187 static $go, $choose; /// Locally cached, in case there's lots on a page
1189 if (empty($options)) {
1190 return '';
1193 if (!isset($go)) {
1194 $go = get_string('go');
1197 if ($nothing == 'choose') {
1198 if (!isset($choose)) {
1199 $choose = get_string('choose');
1201 $nothing = $choose.'...';
1204 // changed reference to document.getElementById('id_abc') instead of document.abc
1205 // MDL-7861
1206 $output = '<form action="'.$CFG->wwwroot.'/course/jumpto.php"'.
1207 ' method="get" '.
1208 $CFG->frametarget.
1209 ' id="'.$formid.'"'.
1210 ' class="popupform">';
1211 if ($help) {
1212 $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
1213 } else {
1214 $button = '';
1217 if ($selectlabel) {
1218 $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
1221 if ($gobutton) {
1222 // Using the no-JavaScript version
1223 $javascript = '';
1224 } else if (check_browser_version('MSIE') || (check_browser_version('Opera') && !check_browser_operating_system("Linux"))) {
1225 //IE and Opera fire the onchange when ever you move into a dropdown list with the keyboard.
1226 //onfocus will call a function inside dropdown.js. It fixes this IE/Opera behavior.
1227 //Note: There is a bug on Opera+Linux with the javascript code (first mouse selection is inactive),
1228 //so we do not fix the Opera behavior on Linux
1229 $javascript = ' onfocus="initSelect(\''.$formid.'\','.$targetwindow.')"';
1230 } else {
1231 //Other browser
1232 $javascript = ' onchange="'.$targetwindow.
1233 '.location=document.getElementById(\''.$formid.
1234 '\').jump.options[document.getElementById(\''.
1235 $formid.'\').jump.selectedIndex].value;"';
1238 $output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" name="jump"'.$javascript.'>'."\n";
1240 if ($nothing != '') {
1241 $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
1244 $inoptgroup = false;
1246 foreach ($options as $value => $label) {
1248 if ($label == '--') { /// we are ending previous optgroup
1249 /// Check to see if we already have a valid open optgroup
1250 /// XHTML demands that there be at least 1 option within an optgroup
1251 if ($inoptgroup and (count($optgr) > 1) ) {
1252 $output .= implode('', $optgr);
1253 $output .= ' </optgroup>';
1255 $optgr = array();
1256 $inoptgroup = false;
1257 continue;
1258 } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
1260 /// Check to see if we already have a valid open optgroup
1261 /// XHTML demands that there be at least 1 option within an optgroup
1262 if ($inoptgroup and (count($optgr) > 1) ) {
1263 $output .= implode('', $optgr);
1264 $output .= ' </optgroup>';
1267 unset($optgr);
1268 $optgr = array();
1270 $optgr[] = ' <optgroup label="'. s(format_string(substr($label,2))) .'">'; // Plain labels
1272 $inoptgroup = true; /// everything following will be in an optgroup
1273 continue;
1275 } else {
1276 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()]))
1278 $url=sid_process_url( $common . $value );
1279 } else
1281 $url=$common . $value;
1283 $optstr = ' <option value="' . $url . '"';
1285 if ($value == $selected) {
1286 $optstr .= ' selected="selected"';
1289 if (!empty($optionsextra[$value])) {
1290 $optstr .= ' '.$optionsextra[$value];
1293 if ($label) {
1294 $optstr .= '>'. $label .'</option>' . "\n";
1295 } else {
1296 $optstr .= '>'. $value .'</option>' . "\n";
1299 if ($inoptgroup) {
1300 $optgr[] = $optstr;
1301 } else {
1302 $output .= $optstr;
1308 /// catch the final group if not closed
1309 if ($inoptgroup and count($optgr) > 1) {
1310 $output .= implode('', $optgr);
1311 $output .= ' </optgroup>';
1314 $output .= '</select>';
1315 $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1316 if ($gobutton) {
1317 $output .= '<input type="submit" value="'.
1318 ($gobutton===true ? $go : $gobutton).'" />';
1319 } else {
1320 $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
1321 $output .= '<input type="submit" value="'.$go.'" /></div>';
1322 $output .= '<script type="text/javascript">'.
1323 "\n//<![CDATA[\n".
1324 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
1325 "\n//]]>\n".'</script>';
1327 $output .= '</div></form>';
1329 if ($return) {
1330 return $output;
1331 } else {
1332 echo $output;
1338 * Prints some red text
1340 * @param string $error The text to be displayed in red
1342 function formerr($error) {
1344 if (!empty($error)) {
1345 echo '<span class="error">'. $error .'</span>';
1350 * Validates an email to make sure it makes sense.
1352 * @param string $address The email address to validate.
1353 * @return boolean
1355 function validate_email($address) {
1357 return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1358 '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1359 '@'.
1360 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1361 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
1362 $address));
1366 * Extracts file argument either from file parameter or PATH_INFO
1368 * @param string $scriptname name of the calling script
1369 * @return string file path (only safe characters)
1371 function get_file_argument($scriptname) {
1372 global $_SERVER;
1374 $relativepath = FALSE;
1376 // first try normal parameter (compatible method == no relative links!)
1377 $relativepath = optional_param('file', FALSE, PARAM_PATH);
1378 if ($relativepath === '/testslasharguments') {
1379 echo 'test -1 : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
1380 die;
1383 // then try extract file from PATH_INFO (slasharguments method)
1384 if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
1385 $path_info = $_SERVER['PATH_INFO'];
1386 // check that PATH_INFO works == must not contain the script name
1387 if (!strpos($path_info, $scriptname)) {
1388 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1389 if ($relativepath === '/testslasharguments') {
1390 echo 'test 1 : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
1391 die;
1396 // now if both fail try the old way
1397 // (for compatibility with misconfigured or older buggy php implementations)
1398 if (!$relativepath) {
1399 $arr = explode($scriptname, me());
1400 if (!empty($arr[1])) {
1401 $path_info = strip_querystring($arr[1]);
1402 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1403 if ($relativepath === '/testslasharguments') {
1404 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
1405 die;
1410 return $relativepath;
1414 * Searches the current environment variables for some slash arguments
1416 * @param string $file ?
1417 * @todo Finish documenting this function
1419 function get_slash_arguments($file='file.php') {
1421 if (!$string = me()) {
1422 return false;
1425 $pathinfo = explode($file, $string);
1427 if (!empty($pathinfo[1])) {
1428 return addslashes($pathinfo[1]);
1429 } else {
1430 return false;
1435 * Extracts arguments from "/foo/bar/something"
1436 * eg http://mysite.com/script.php/foo/bar/something
1438 * @param string $string ?
1439 * @param int $i ?
1440 * @return array|string
1441 * @todo Finish documenting this function
1443 function parse_slash_arguments($string, $i=0) {
1445 if (detect_munged_arguments($string)) {
1446 return false;
1448 $args = explode('/', $string);
1450 if ($i) { // return just the required argument
1451 return $args[$i];
1453 } else { // return the whole array
1454 array_shift($args); // get rid of the empty first one
1455 return $args;
1460 * Just returns an array of text formats suitable for a popup menu
1462 * @uses FORMAT_MOODLE
1463 * @uses FORMAT_HTML
1464 * @uses FORMAT_PLAIN
1465 * @uses FORMAT_MARKDOWN
1466 * @return array
1468 function format_text_menu() {
1470 return array (FORMAT_MOODLE => get_string('formattext'),
1471 FORMAT_HTML => get_string('formathtml'),
1472 FORMAT_PLAIN => get_string('formatplain'),
1473 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1477 * Given text in a variety of format codings, this function returns
1478 * the text as safe HTML.
1480 * This function should mainly be used for long strings like posts,
1481 * answers, glossary items etc. For short strings @see format_string().
1483 * @uses $CFG
1484 * @uses FORMAT_MOODLE
1485 * @uses FORMAT_HTML
1486 * @uses FORMAT_PLAIN
1487 * @uses FORMAT_WIKI
1488 * @uses FORMAT_MARKDOWN
1489 * @param string $text The text to be formatted. This is raw text originally from user input.
1490 * @param int $format Identifier of the text format to be used
1491 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1492 * @param array $options ?
1493 * @param int $courseid ?
1494 * @return string
1495 * @todo Finish documenting this function
1497 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1499 global $CFG, $COURSE;
1501 static $croncache = array();
1503 if ($text === '') {
1504 return ''; // no need to do any filters and cleaning
1507 if (!isset($options->trusttext)) {
1508 $options->trusttext = false;
1511 if (!isset($options->noclean)) {
1512 $options->noclean=false;
1514 if (!isset($options->nocache)) {
1515 $options->nocache=false;
1517 if (!isset($options->smiley)) {
1518 $options->smiley=true;
1520 if (!isset($options->filter)) {
1521 $options->filter=true;
1523 if (!isset($options->para)) {
1524 $options->para=true;
1526 if (!isset($options->newlines)) {
1527 $options->newlines=true;
1530 if (empty($courseid)) {
1531 $courseid = $COURSE->id;
1534 if (!empty($CFG->cachetext) and empty($options->nocache)) {
1535 $time = time() - $CFG->cachetext;
1536 $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);
1538 if (defined('FULLME') and FULLME == 'cron') {
1539 if (isset($croncache[$md5key])) {
1540 return $croncache[$md5key];
1544 if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
1545 if ($oldcacheitem->timemodified >= $time) {
1546 if (defined('FULLME') and FULLME == 'cron') {
1547 if (count($croncache) > 150) {
1548 reset($croncache);
1549 $key = key($croncache);
1550 unset($croncache[$key]);
1552 $croncache[$md5key] = $oldcacheitem->formattedtext;
1554 return $oldcacheitem->formattedtext;
1559 // trusttext overrides the noclean option!
1560 if ($options->trusttext) {
1561 if (trusttext_present($text)) {
1562 $text = trusttext_strip($text);
1563 if (!empty($CFG->enabletrusttext)) {
1564 $options->noclean = true;
1565 } else {
1566 $options->noclean = false;
1568 } else {
1569 $options->noclean = false;
1571 } else if (!debugging('', DEBUG_DEVELOPER)) {
1572 // strip any forgotten trusttext in non-developer mode
1573 // do not forget to disable text cache when debugging trusttext!!
1574 $text = trusttext_strip($text);
1577 $CFG->currenttextiscacheable = true; // Default status - can be changed by any filter
1579 switch ($format) {
1580 case FORMAT_HTML:
1581 if ($options->smiley) {
1582 replace_smilies($text);
1584 if (!$options->noclean) {
1585 $text = clean_text($text, FORMAT_HTML);
1587 if ($options->filter) {
1588 $text = filter_text($text, $courseid);
1590 break;
1592 case FORMAT_PLAIN:
1593 $text = s($text); // cleans dangerous JS
1594 $text = rebuildnolinktag($text);
1595 $text = str_replace(' ', '&nbsp; ', $text);
1596 $text = nl2br($text);
1597 break;
1599 case FORMAT_WIKI:
1600 // this format is deprecated
1601 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1602 this message as all texts should have been converted to Markdown format instead.
1603 Please post a bug report to http://moodle.org/bugs with information about where you
1604 saw this message.</p>'.s($text);
1605 break;
1607 case FORMAT_MARKDOWN:
1608 $text = markdown_to_html($text);
1609 if ($options->smiley) {
1610 replace_smilies($text);
1612 if (!$options->noclean) {
1613 $text = clean_text($text, FORMAT_HTML);
1616 if ($options->filter) {
1617 $text = filter_text($text, $courseid);
1619 break;
1621 default: // FORMAT_MOODLE or anything else
1622 $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
1623 if (!$options->noclean) {
1624 $text = clean_text($text, FORMAT_HTML);
1627 if ($options->filter) {
1628 $text = filter_text($text, $courseid);
1630 break;
1633 if (empty($options->nocache) and !empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
1634 if (defined('FULLME') and FULLME == 'cron') {
1635 // special static cron cache - no need to store it in db if its not already there
1636 if (count($croncache) > 150) {
1637 reset($croncache);
1638 $key = key($croncache);
1639 unset($croncache[$key]);
1641 $croncache[$md5key] = $text;
1642 return $text;
1645 $newcacheitem = new object();
1646 $newcacheitem->md5key = $md5key;
1647 $newcacheitem->formattedtext = addslashes($text);
1648 $newcacheitem->timemodified = time();
1649 if ($oldcacheitem) { // See bug 4677 for discussion
1650 $newcacheitem->id = $oldcacheitem->id;
1651 @update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1652 // It's unlikely that the cron cache cleaner could have
1653 // deleted this entry in the meantime, as it allows
1654 // some extra time to cover these cases.
1655 } else {
1656 @insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1657 // Again, it's possible that another user has caused this
1658 // record to be created already in the time that it took
1659 // to traverse this function. That's OK too, as the
1660 // call above handles duplicate entries, and eventually
1661 // the cron cleaner will delete them.
1665 return $text;
1668 /** Converts the text format from the value to the 'internal'
1669 * name or vice versa. $key can either be the value or the name
1670 * and you get the other back.
1672 * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1673 * @return mixed as above but the other way around!
1675 function text_format_name( $key ) {
1676 $lookup = array();
1677 $lookup[FORMAT_MOODLE] = 'moodle';
1678 $lookup[FORMAT_HTML] = 'html';
1679 $lookup[FORMAT_PLAIN] = 'plain';
1680 $lookup[FORMAT_MARKDOWN] = 'markdown';
1681 $value = "error";
1682 if (!is_numeric($key)) {
1683 $key = strtolower( $key );
1684 $value = array_search( $key, $lookup );
1686 else {
1687 if (isset( $lookup[$key] )) {
1688 $value = $lookup[ $key ];
1691 return $value;
1695 * Resets all data related to filters, called during upgrade or when filter settings change.
1696 * @return void
1698 function reset_text_filters_cache() {
1699 global $CFG;
1701 delete_records('cache_text');
1702 $purifdir = $CFG->dataroot.'/cache/htmlpurifier';
1703 remove_dir($purifdir, true);
1706 /** Given a simple string, this function returns the string
1707 * processed by enabled string filters if $CFG->filterall is enabled
1709 * This function should be used to print short strings (non html) that
1710 * need filter processing e.g. activity titles, post subjects,
1711 * glossary concepts.
1713 * @param string $string The string to be filtered.
1714 * @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
1715 * @param int $courseid Current course as filters can, potentially, use it
1716 * @return string
1718 function format_string ($string, $striplinks=true, $courseid=NULL ) {
1720 global $CFG, $COURSE;
1722 //We'll use a in-memory cache here to speed up repeated strings
1723 static $strcache = false;
1725 if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
1726 $strcache = array();
1729 //init course id
1730 if (empty($courseid)) {
1731 $courseid = $COURSE->id;
1734 //Calculate md5
1735 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
1737 //Fetch from cache if possible
1738 if (isset($strcache[$md5])) {
1739 return $strcache[$md5];
1742 // First replace all ampersands not followed by html entity code
1743 $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1745 if (!empty($CFG->filterall)) {
1746 $string = filter_string($string, $courseid);
1749 // If the site requires it, strip ALL tags from this string
1750 if (!empty($CFG->formatstringstriptags)) {
1751 $string = strip_tags($string);
1753 } else {
1754 // Otherwise strip just links if that is required (default)
1755 if ($striplinks) { //strip links in string
1756 $string = preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1758 $string = clean_text($string);
1761 //Store to cache
1762 $strcache[$md5] = $string;
1764 return $string;
1768 * Given text in a variety of format codings, this function returns
1769 * the text as plain text suitable for plain email.
1771 * @uses FORMAT_MOODLE
1772 * @uses FORMAT_HTML
1773 * @uses FORMAT_PLAIN
1774 * @uses FORMAT_WIKI
1775 * @uses FORMAT_MARKDOWN
1776 * @param string $text The text to be formatted. This is raw text originally from user input.
1777 * @param int $format Identifier of the text format to be used
1778 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1779 * @return string
1781 function format_text_email($text, $format) {
1783 switch ($format) {
1785 case FORMAT_PLAIN:
1786 return $text;
1787 break;
1789 case FORMAT_WIKI:
1790 // there should not be any of these any more!
1791 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1792 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
1793 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1794 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1795 break;
1797 case FORMAT_HTML:
1798 return html_to_text($text);
1799 break;
1801 case FORMAT_MOODLE:
1802 case FORMAT_MARKDOWN:
1803 default:
1804 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1805 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1806 break;
1811 * Given some text in HTML format, this function will pass it
1812 * through any filters that have been defined in $CFG->textfilterx
1813 * The variable defines a filepath to a file containing the
1814 * filter function. The file must contain a variable called
1815 * $textfilter_function which contains the name of the function
1816 * with $courseid and $text parameters
1818 * @param string $text The text to be passed through format filters
1819 * @param int $courseid ?
1820 * @return string
1821 * @todo Finish documenting this function
1823 function filter_text($text, $courseid=NULL) {
1824 global $CFG, $COURSE;
1826 if (empty($courseid)) {
1827 $courseid = $COURSE->id; // (copied from format_text)
1830 if (!empty($CFG->textfilters)) {
1831 require_once($CFG->libdir.'/filterlib.php');
1832 $textfilters = explode(',', $CFG->textfilters);
1833 foreach ($textfilters as $textfilter) {
1834 if (is_readable($CFG->dirroot .'/'. $textfilter .'/filter.php')) {
1835 include_once($CFG->dirroot .'/'. $textfilter .'/filter.php');
1836 $functionname = basename($textfilter).'_filter';
1837 if (function_exists($functionname)) {
1838 $text = $functionname($courseid, $text);
1844 /// <nolink> tags removed for XHTML compatibility
1845 $text = str_replace('<nolink>', '', $text);
1846 $text = str_replace('</nolink>', '', $text);
1848 return $text;
1853 * Given a string (short text) in HTML format, this function will pass it
1854 * through any filters that have been defined in $CFG->stringfilters
1855 * The variable defines a filepath to a file containing the
1856 * filter function. The file must contain a variable called
1857 * $textfilter_function which contains the name of the function
1858 * with $courseid and $text parameters
1860 * @param string $string The text to be passed through format filters
1861 * @param int $courseid The id of a course
1862 * @return string
1864 function filter_string($string, $courseid=NULL) {
1865 global $CFG, $COURSE;
1867 if (empty($CFG->textfilters)) { // All filters are disabled anyway so quit
1868 return $string;
1871 if (empty($courseid)) {
1872 $courseid = $COURSE->id;
1875 require_once($CFG->libdir.'/filterlib.php');
1877 if (isset($CFG->stringfilters)) { // We have a predefined list to use, great!
1878 if (empty($CFG->stringfilters)) { // but it's blank, so finish now
1879 return $string;
1881 $stringfilters = explode(',', $CFG->stringfilters); // ..use the list we have
1883 } else { // Otherwise try to derive a list from textfilters
1884 if (strpos($CFG->textfilters, 'filter/multilang') !== false) { // Multilang is here
1885 $stringfilters = array('filter/multilang'); // Let's use just that
1886 $CFG->stringfilters = 'filter/multilang'; // Save it for next time through
1887 } else {
1888 $CFG->stringfilters = ''; // Save the result and return
1889 return $string;
1894 foreach ($stringfilters as $stringfilter) {
1895 if (is_readable($CFG->dirroot .'/'. $stringfilter .'/filter.php')) {
1896 include_once($CFG->dirroot .'/'. $stringfilter .'/filter.php');
1897 $functionname = basename($stringfilter).'_filter';
1898 if (function_exists($functionname)) {
1899 $string = $functionname($courseid, $string);
1904 /// <nolink> tags removed for XHTML compatibility
1905 $string = str_replace('<nolink>', '', $string);
1906 $string = str_replace('</nolink>', '', $string);
1908 return $string;
1912 * Is the text marked as trusted?
1914 * @param string $text text to be searched for TRUSTTEXT marker
1915 * @return boolean
1917 function trusttext_present($text) {
1918 if (strpos($text, TRUSTTEXT) !== FALSE) {
1919 return true;
1920 } else {
1921 return false;
1926 * This funtion MUST be called before the cleaning or any other
1927 * function that modifies the data! We do not know the origin of trusttext
1928 * in database, if it gets there in tweaked form we must not convert it
1929 * to supported form!!!
1931 * Please be carefull not to use stripslashes on data from database
1932 * or twice stripslashes when processing data recieved from user.
1934 * @param string $text text that may contain TRUSTTEXT marker
1935 * @return text without any TRUSTTEXT marker
1937 function trusttext_strip($text) {
1938 global $CFG;
1940 while (true) { //removing nested TRUSTTEXT
1941 $orig = $text;
1942 $text = str_replace(TRUSTTEXT, '', $text);
1943 if (strcmp($orig, $text) === 0) {
1944 return $text;
1950 * Mark text as trusted, such text may contain any HTML tags because the
1951 * normal text cleaning will be bypassed.
1952 * Please make sure that the text comes from trusted user before storing
1953 * it into database!
1955 function trusttext_mark($text) {
1956 global $CFG;
1957 if (!empty($CFG->enabletrusttext) and (strpos($text, TRUSTTEXT) === FALSE)) {
1958 return TRUSTTEXT.$text;
1959 } else {
1960 return $text;
1963 function trusttext_after_edit(&$text, $context) {
1964 if (has_capability('moodle/site:trustcontent', $context)) {
1965 $text = trusttext_strip($text);
1966 $text = trusttext_mark($text);
1967 } else {
1968 $text = trusttext_strip($text);
1972 function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
1973 global $CFG;
1975 $options = new object();
1976 $options->smiley = false;
1977 $options->filter = false;
1978 if (!empty($CFG->enabletrusttext)
1979 and has_capability('moodle/site:trustcontent', $context)
1980 and trusttext_present($text)) {
1981 $options->noclean = true;
1982 } else {
1983 $options->noclean = false;
1985 $text = trusttext_strip($text);
1986 if ($usehtmleditor) {
1987 $text = format_text($text, $format, $options);
1988 $format = FORMAT_HTML;
1989 } else if (!$options->noclean){
1990 $text = clean_text($text, $format);
1995 * Given raw text (eg typed in by a user), this function cleans it up
1996 * and removes any nasty tags that could mess up Moodle pages.
1998 * @uses FORMAT_MOODLE
1999 * @uses FORMAT_PLAIN
2000 * @uses ALLOWED_TAGS
2001 * @param string $text The text to be cleaned
2002 * @param int $format Identifier of the text format to be used
2003 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
2004 * @return string The cleaned up text
2006 function clean_text($text, $format=FORMAT_MOODLE) {
2008 global $ALLOWED_TAGS, $CFG;
2010 if (empty($text) or is_numeric($text)) {
2011 return (string)$text;
2014 switch ($format) {
2015 case FORMAT_PLAIN:
2016 case FORMAT_MARKDOWN:
2017 return $text;
2019 default:
2021 if (!empty($CFG->enablehtmlpurifier)) {
2022 //this is PHP5 only, the lib/setup.php contains a disabler for PHP4
2023 $text = purify_html($text);
2024 } else {
2025 /// Fix non standard entity notations
2026 $text = preg_replace('/&#0*([0-9]+);?/', "&#\\1;", $text);
2027 $text = preg_replace('/&#x0*([0-9a-fA-F]+);?/', "&#x\\1;", $text);
2029 /// Remove tags that are not allowed
2030 $text = strip_tags($text, $ALLOWED_TAGS);
2032 /// Clean up embedded scripts and , using kses
2033 $text = cleanAttributes($text);
2035 /// Again remove tags that are not allowed
2036 $text = strip_tags($text, $ALLOWED_TAGS);
2040 /// Remove potential script events - some extra protection for undiscovered bugs in our code
2041 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
2042 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
2044 return $text;
2049 * KSES replacement cleaning function - uses HTML Purifier.
2051 * @global object
2052 * @param string $text The (X)HTML string to purify
2054 function purify_html($text) {
2055 global $CFG;
2057 // this can not be done only once because we sometimes need to reset the cache
2058 $cachedir = $CFG->dataroot.'/cache/htmlpurifier';
2059 $status = check_dir_exists($cachedir, true, true);
2061 static $purifier = false;
2062 static $config;
2063 if ($purifier === false) {
2064 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
2065 $config = HTMLPurifier_Config::createDefault();
2066 $config->set('Output.Newline', "\n");
2067 $config->set('Core.ConvertDocumentToFragment', true);
2068 $config->set('Core.Encoding', 'UTF-8');
2069 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
2070 $config->set('Cache.SerializerPath', $cachedir);
2071 $config->set('URI.AllowedSchemes', array('http'=>1, 'https'=>1, 'ftp'=>1, 'irc'=>1, 'nntp'=>1, 'news'=>1, 'rtsp'=>1, 'teamspeak'=>1, 'gopher'=>1, 'mms'=>1));
2072 $config->set('Attr.AllowedFrameTargets', array('_blank'));
2073 $purifier = new HTMLPurifier($config);
2075 return $purifier->purify($text);
2079 * This function takes a string and examines it for HTML tags.
2080 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
2081 * which checks for attributes and filters them for malicious content
2082 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2084 * @param string $str The string to be examined for html tags
2085 * @return string
2087 function cleanAttributes($str){
2088 $result = preg_replace_callback(
2089 '%(<[^>]*(>|$)|>)%m', #search for html tags
2090 "cleanAttributes2",
2091 $str
2093 return $result;
2097 * This function takes a string with an html tag and strips out any unallowed
2098 * protocols e.g. javascript:
2099 * It calls ancillary functions in kses which are prefixed by kses
2100 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2102 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
2103 * element the html to be cleared
2104 * @return string
2106 function cleanAttributes2($htmlArray){
2108 global $CFG, $ALLOWED_PROTOCOLS;
2109 require_once($CFG->libdir .'/kses.php');
2111 $htmlTag = $htmlArray[1];
2112 if (substr($htmlTag, 0, 1) != '<') {
2113 return '&gt;'; //a single character ">" detected
2115 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
2116 return ''; // It's seriously malformed
2118 $slash = trim($matches[1]); //trailing xhtml slash
2119 $elem = $matches[2]; //the element name
2120 $attrlist = $matches[3]; // the list of attributes as a string
2122 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
2124 $attStr = '';
2125 foreach ($attrArray as $arreach) {
2126 $arreach['name'] = strtolower($arreach['name']);
2127 if ($arreach['name'] == 'style') {
2128 $value = $arreach['value'];
2129 while (true) {
2130 $prevvalue = $value;
2131 $value = kses_no_null($value);
2132 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
2133 $value = kses_decode_entities($value);
2134 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
2135 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
2136 if ($value === $prevvalue) {
2137 $arreach['value'] = $value;
2138 break;
2141 $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']);
2142 $arreach['value'] = preg_replace("/v\s*b\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xvbscript", $arreach['value']);
2143 $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']);
2144 $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
2145 } else if ($arreach['name'] == 'href') {
2146 //Adobe Acrobat Reader XSS protection
2147 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd)[^#]*)#.*$/i', '$1', $arreach['value']);
2149 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
2152 $xhtml_slash = '';
2153 if (preg_match('%/\s*$%', $attrlist)) {
2154 $xhtml_slash = ' /';
2156 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
2160 * Replaces all known smileys in the text with image equivalents
2162 * @uses $CFG
2163 * @param string $text Passed by reference. The string to search for smily strings.
2164 * @return string
2166 function replace_smilies(&$text) {
2168 global $CFG;
2170 if (empty($CFG->emoticons)) { /// No emoticons defined, nothing to process here
2171 return;
2174 $lang = current_language();
2175 $emoticonstring = $CFG->emoticons;
2176 static $e = array();
2177 static $img = array();
2178 static $emoticons = null;
2180 if (is_null($emoticons)) {
2181 $emoticons = array();
2182 if ($emoticonstring) {
2183 $items = explode('{;}', $CFG->emoticons);
2184 foreach ($items as $item) {
2185 $item = explode('{:}', $item);
2186 $emoticons[$item[0]] = $item[1];
2192 if (empty($img[$lang])) { /// After the first time this is not run again
2193 $e[$lang] = array();
2194 $img[$lang] = array();
2195 foreach ($emoticons as $emoticon => $image){
2196 $alttext = get_string($image, 'pix');
2197 $alttext = preg_replace('/^\[\[(.*)\]\]$/', '$1', $alttext); /// Clean alttext in case there isn't lang string for it.
2198 $e[$lang][] = $emoticon;
2199 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath .'/s/'. $image .'.gif" />';
2203 // Exclude from transformations all the code inside <script> tags
2204 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
2205 // Based on code from glossary fiter by Williams Castillo.
2206 // - Eloy
2208 // Detect all the <script> zones to take out
2209 $excludes = array();
2210 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
2212 // Take out all the <script> zones from text
2213 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
2214 $excludes['<+'.$key.'+>'] = $value;
2216 if ($excludes) {
2217 $text = str_replace($excludes,array_keys($excludes),$text);
2220 /// this is the meat of the code - this is run every time
2221 $text = str_replace($e[$lang], $img[$lang], $text);
2223 // Recover all the <script> zones to text
2224 if ($excludes) {
2225 $text = str_replace(array_keys($excludes),$excludes,$text);
2230 * Given plain text, makes it into HTML as nicely as possible.
2231 * May contain HTML tags already
2233 * @uses $CFG
2234 * @param string $text The string to convert.
2235 * @param boolean $smiley Convert any smiley characters to smiley images?
2236 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
2237 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2238 * @return string
2241 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
2244 global $CFG;
2246 /// Remove any whitespace that may be between HTML tags
2247 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
2249 /// Remove any returns that precede or follow HTML tags
2250 $text = eregi_replace("([\n\r])<", " <", $text);
2251 $text = eregi_replace(">([\n\r])", "> ", $text);
2253 convert_urls_into_links($text);
2255 /// Make returns into HTML newlines.
2256 if ($newlines) {
2257 $text = nl2br($text);
2260 /// Turn smileys into images.
2261 if ($smiley) {
2262 replace_smilies($text);
2265 /// Wrap the whole thing in a paragraph tag if required
2266 if ($para) {
2267 return '<p>'.$text.'</p>';
2268 } else {
2269 return $text;
2274 * Given Markdown formatted text, make it into XHTML using external function
2276 * @uses $CFG
2277 * @param string $text The markdown formatted text to be converted.
2278 * @return string Converted text
2280 function markdown_to_html($text) {
2281 global $CFG;
2283 require_once($CFG->libdir .'/markdown.php');
2285 return Markdown($text);
2289 * Given HTML text, make it into plain text using external function
2291 * @param string $html The text to be converted.
2292 * @param integer $width Width to wrap the text at. (optional, default 75 which
2293 * is a good value for email. 0 means do not limit line length.)
2294 * @return string plain text equivalent of the HTML.
2296 function html_to_text($html, $width = 75) {
2298 global $CFG;
2300 require_once($CFG->libdir .'/html2text.php');
2302 $h2t = new html2text($html, false, true, $width);
2303 $result = $h2t->get_text();
2305 return $result;
2309 * Given some text this function converts any URLs it finds into HTML links
2311 * @param string $text Passed in by reference. The string to be searched for urls.
2313 function convert_urls_into_links(&$text) {
2314 //I've added img tags to this list of tags to ignore.
2315 //See MDL-21168 for more info. A better way to ignore tags whether or not
2316 //they are escaped partially or completely would be desirable. For example:
2317 //<a href="blah">
2318 //&lt;a href="blah"&gt;
2319 //&lt;a href="blah">
2320 $filterignoretagsopen = array('<a\s[^>]+?>');
2321 $filterignoretagsclose = array('</a>');
2322 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
2324 // Check if we support unicode modifiers in regular expressions. Cache it.
2325 // TODO: this check should be a environment requirement in Moodle 2.0, as far as unicode
2326 // chars are going to arrive to URLs officially really soon (2010?)
2327 // Original RFC regex from: http://www.bytemycode.com/snippets/snippet/796/
2328 // Various ideas from: http://alanstorm.com/url_regex_explained
2329 // Unicode check, negative assertion and other bits from Moodle.
2330 static $unicoderegexp;
2331 if (!isset($unicoderegexp)) {
2332 $unicoderegexp = @preg_match('/\pL/u', 'a'); // This will fail silenty, returning false,
2335 $unicoderegexp = false;//force non use of unicode modifiers. MDL-21296
2336 if ($unicoderegexp) { //We can use unicode modifiers
2337 $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',
2338 '<a href="\\1" target="_blank">\\1</a>', $text);
2339 $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',
2340 '<a href="http://\\1" target="_blank">\\1</a>', $text);
2341 } else { //We cannot use unicode modifiers
2342 $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',
2343 '<a href="\\1" target="_blank">\\1</a>', $text);
2344 $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',
2345 '<a href="http://\\1" target="_blank">\\1</a>', $text);
2348 if (!empty($ignoretags)) {
2349 $ignoretags = array_reverse($ignoretags); /// Reversed so "progressive" str_replace() will solve some nesting problems.
2350 $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
2355 * This function will highlight search words in a given string
2356 * It cares about HTML and will not ruin links. It's best to use
2357 * this function after performing any conversions to HTML.
2359 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
2360 * @param string $haystack The string (HTML) within which to highlight the search terms.
2361 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
2362 * @param string $prefix the string to put before each search term found.
2363 * @param string $suffix the string to put after each search term found.
2364 * @return string The highlighted HTML.
2366 function highlight($needle, $haystack, $matchcase = false,
2367 $prefix = '<span class="highlight">', $suffix = '</span>') {
2369 /// Quick bail-out in trivial cases.
2370 if (empty($needle) or empty($haystack)) {
2371 return $haystack;
2374 /// Break up the search term into words, discard any -words and build a regexp.
2375 $words = preg_split('/ +/', trim($needle));
2376 foreach ($words as $index => $word) {
2377 if (strpos($word, '-') === 0) {
2378 unset($words[$index]);
2379 } else if (strpos($word, '+') === 0) {
2380 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
2381 } else {
2382 $words[$index] = preg_quote($word, '/');
2385 $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
2386 if (!$matchcase) {
2387 $regexp .= 'i';
2390 /// Another chance to bail-out if $search was only -words
2391 if (empty($words)) {
2392 return $haystack;
2395 /// Find all the HTML tags in the input, and store them in a placeholders array.
2396 $placeholders = array();
2397 $matches = array();
2398 preg_match_all('/<[^>]*>/', $haystack, $matches);
2399 foreach (array_unique($matches[0]) as $key => $htmltag) {
2400 $placeholders['<|' . $key . '|>'] = $htmltag;
2403 /// In $hastack, replace each HTML tag with the corresponding placeholder.
2404 $haystack = str_replace($placeholders, array_keys($placeholders), $haystack);
2406 /// In the resulting string, Do the highlighting.
2407 $haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack);
2409 /// Turn the placeholders back into HTML tags.
2410 $haystack = str_replace(array_keys($placeholders), $placeholders, $haystack);
2412 return $haystack;
2416 * This function will highlight instances of $needle in $haystack
2417 * It's faster that the above function and doesn't care about
2418 * HTML or anything.
2420 * @param string $needle The string to search for
2421 * @param string $haystack The string to search for $needle in
2422 * @return string
2424 function highlightfast($needle, $haystack) {
2426 if (empty($needle) or empty($haystack)) {
2427 return $haystack;
2430 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
2432 if (count($parts) === 1) {
2433 return $haystack;
2436 $pos = 0;
2438 foreach ($parts as $key => $part) {
2439 $parts[$key] = substr($haystack, $pos, strlen($part));
2440 $pos += strlen($part);
2442 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2443 $pos += strlen($needle);
2446 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2450 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2451 * Internationalisation, for print_header and backup/restorelib.
2452 * @param $dir Default false.
2453 * @return string Attributes.
2455 function get_html_lang($dir = false) {
2456 $direction = '';
2457 if ($dir) {
2458 if (get_string('thisdirection') == 'rtl') {
2459 $direction = ' dir="rtl"';
2460 } else {
2461 $direction = ' dir="ltr"';
2464 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2465 $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
2466 @header('Content-Language: '.$language);
2467 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2471 * Return the markup for the destination of the 'Skip to main content' links.
2472 * Accessibility improvement for keyboard-only users.
2473 * Used in course formats, /index.php and /course/index.php
2474 * @return string HTML element.
2476 function skip_main_destination() {
2477 return '<span id="maincontent"></span>';
2481 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
2484 * Print a standard header
2486 * @uses $USER
2487 * @uses $CFG
2488 * @uses $SESSION
2489 * @param string $title Appears at the top of the window
2490 * @param string $heading Appears at the top of the page
2491 * @param array $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
2492 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2493 * @param string $meta Meta tags to be added to the header
2494 * @param boolean $cache Should this page be cacheable?
2495 * @param string $button HTML code for a button (usually for module editing)
2496 * @param string $menu HTML code for a popup menu
2497 * @param boolean $usexml use XML for this page
2498 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2499 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2501 function print_header ($title='', $heading='', $navigation='', $focus='',
2502 $meta='', $cache=true, $button='&nbsp;', $menu='',
2503 $usexml=false, $bodytags='', $return=false) {
2505 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
2507 if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
2508 debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
2509 . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.", DEBUG_DEVELOPER);
2512 $heading = format_string($heading); // Fix for MDL-8582
2514 /// This makes sure that the header is never repeated twice on a page
2515 if (defined('HEADER_PRINTED')) {
2516 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().');
2517 return;
2519 define('HEADER_PRINTED', 'true');
2521 /// Perform a browser environment check for the flash version. Should only run once per login session.
2522 if (isloggedin() && !empty($CFG->excludeoldflashclients) && empty($SESSION->flashversion)) {
2523 // Unfortunately we can't use require_js here and keep it all clean in 1.9 ...
2524 // require_js(array('yui_yahoo', 'yui_event', 'yui_connection', $CFG->httpswwwroot."/lib/swfobject/swfobject.js"));
2525 $meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot.'/lib/yui/yahoo/yahoo-min.js"></script>';
2526 $meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot.'/lib/yui/event/event-min.js"></script>';
2527 $meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot.'/lib/yui/connection/connection-min.js"></script>';
2528 $meta .= '<script type="text/javascript" src="'.$CFG->httpswwwroot.'/lib/swfobject/swfobject.js"></script>';
2529 $meta .=
2530 "<script type=\"text/javascript\">\n".
2531 "//<![CDATA[\n".
2532 " var flashversion = swfobject.getFlashPlayerVersion();\n".
2533 " YAHOO.util.Connect.asyncRequest('GET','".$CFG->httpswwwroot."/login/environment.php?sesskey=".sesskey()."&flashversion='+flashversion.major+'.'+flashversion.minor+'.'+flashversion.release);\n".
2534 "//]]>\n".
2535 "</script>";
2539 /// Add the required stylesheets
2540 $stylesheetshtml = '';
2541 foreach ($CFG->stylesheets as $stylesheet) {
2542 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2544 $meta = $stylesheetshtml.$meta;
2547 /// Add the meta page from the themes if any were requested
2549 $metapage = '';
2551 if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
2552 ob_start();
2553 include_once($CFG->dirroot.'/theme/standard/meta.php');
2554 $metapage .= ob_get_contents();
2555 ob_end_clean();
2558 if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
2559 if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
2560 ob_start();
2561 include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
2562 $metapage .= ob_get_contents();
2563 ob_end_clean();
2567 if (!isset($THEME->metainclude) || $THEME->metainclude) {
2568 if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
2569 ob_start();
2570 include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
2571 $metapage .= ob_get_contents();
2572 ob_end_clean();
2576 $meta = $meta."\n".$metapage;
2578 $meta .= "\n".require_js('',1);
2580 /// Set up some navigation variables
2582 if (is_newnav($navigation)){
2583 $home = false;
2584 } else {
2585 if ($navigation == 'home') {
2586 $home = true;
2587 $navigation = '';
2588 } else {
2589 $home = false;
2593 /// This is another ugly hack to make navigation elements available to print_footer later
2594 $THEME->title = $title;
2595 $THEME->heading = $heading;
2596 $THEME->navigation = $navigation;
2597 $THEME->button = $button;
2598 $THEME->menu = $menu;
2599 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2601 if ($button == '') {
2602 $button = '&nbsp;';
2605 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
2606 $button = '<a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/maintenance.php">'.get_string('maintenancemode', 'admin').'</a> '.$button;
2607 if(!empty($title)) {
2608 $title .= ' - ';
2610 $title .= get_string('maintenancemode', 'admin');
2613 if (!$menu and $navigation) {
2614 if (empty($CFG->loginhttps)) {
2615 $wwwroot = $CFG->wwwroot;
2616 } else {
2618 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
2620 $menu = user_login_string($COURSE);
2623 if (isset($SESSION->justloggedin)) {
2624 unset($SESSION->justloggedin);
2625 if (!empty($CFG->displayloginfailures)) {
2626 if (!empty($USER->username) and $USER->username != 'guest') {
2627 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
2628 $menu .= '&nbsp;<font size="1">';
2629 if (empty($count->accounts)) {
2630 $menu .= get_string('failedloginattempts', '', $count);
2631 } else {
2632 $menu .= get_string('failedloginattemptsall', '', $count);
2634 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM))) {
2635 $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
2636 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
2638 $menu .= '</font>';
2645 $meta = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' .
2646 "\n" . $meta . "\n";
2647 if (!$usexml) {
2648 @header('Content-Type: text/html; charset=utf-8');
2650 @header('Content-Script-Type: text/javascript');
2651 @header('Content-Style-Type: text/css');
2653 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2654 $direction = get_html_lang($dir=true);
2656 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2657 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2658 @header('Pragma: no-cache');
2659 @header('Expires: ');
2660 } else { // Do everything we can to always prevent clients and proxies caching
2661 @header('Cache-Control: no-store, no-cache, must-revalidate');
2662 @header('Cache-Control: post-check=0, pre-check=0', false);
2663 @header('Pragma: no-cache');
2664 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2665 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2667 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2668 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
2670 @header('Accept-Ranges: none');
2672 $currentlanguage = current_language();
2674 if (empty($usexml)) {
2675 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2676 } else {
2677 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2678 if(!$mathplayer) {
2679 header('Content-Type: application/xhtml+xml');
2681 echo '<?xml version="1.0" ?>'."\n";
2682 if (!empty($CFG->xml_stylesheets)) {
2683 $stylesheets = explode(';', $CFG->xml_stylesheets);
2684 foreach ($stylesheets as $stylesheet) {
2685 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
2688 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
2689 if (!empty($CFG->xml_doctype_extra)) {
2690 echo ' plus '. $CFG->xml_doctype_extra;
2692 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
2693 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2694 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
2695 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2696 $direction";
2697 if($mathplayer) {
2698 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
2699 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2700 $meta .= '</object>'."\n";
2701 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2705 // Clean up the title
2707 $title = format_string($title); // fix for MDL-8582
2708 $title = str_replace('"', '&quot;', $title);
2710 // Create class and id for this page
2712 page_id_and_class($pageid, $pageclass);
2714 $pageclass .= ' course-'.$COURSE->id;
2716 if (!isloggedin()) {
2717 $pageclass .= ' notloggedin';
2720 if (!empty($USER->editing)) {
2721 $pageclass .= ' editing';
2724 if (!empty($CFG->blocksdrag)) {
2725 $pageclass .= ' drag';
2728 $pageclass .= ' dir-'.get_string('thisdirection');
2730 $pageclass .= ' lang-'.$currentlanguage;
2732 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
2734 ob_start();
2735 include($CFG->header);
2736 $output = ob_get_contents();
2737 ob_end_clean();
2739 // container debugging info
2740 $THEME->open_header_containers = open_containers();
2742 // Skip to main content, see skip_main_destination().
2743 if ($pageid=='course-view' or $pageid=='site-index' or $pageid=='course-index') {
2744 $skiplink = '<a class="skip" href="#maincontent">'.get_string('tocontent', 'access').'</a>';
2745 if (! preg_match('/(.*<div[^>]+id="page"[^>]*>)(.*)/s', $output, $matches)) {
2746 preg_match('/(.*<body.*?>)(.*)/s', $output, $matches);
2748 $output = $matches[1]."\n". $skiplink .$matches[2];
2751 $output = force_strict_header($output);
2753 if (!empty($CFG->messaging)) {
2754 $output .= message_popup_window();
2757 // Add in any extra JavaScript libraries that occurred during the header
2758 $output .= require_js('', 2);
2760 if ($return) {
2761 return $output;
2762 } else {
2763 echo $output;
2768 * Used to include JavaScript libraries.
2770 * When the $lib parameter is given, the function will ensure that the
2771 * named library is loaded onto the page - either in the HTML <head>,
2772 * just after the header, or at an arbitrary later point in the page,
2773 * depending on where this function is called.
2775 * Libraries will not be included more than once, so this works like
2776 * require_once in PHP.
2778 * There are two special-case calls to this function which are both used only
2779 * by weblib print_header:
2780 * $extracthtml = 1: this is used before printing the header.
2781 * It returns the script tag code that should go inside the <head>.
2782 * $extracthtml = 2: this is used after printing the header and handles any
2783 * require_js calls that occurred within the header itself.
2785 * @param mixed $lib - string or array of strings
2786 * string(s) should be the shortname for the library or the
2787 * full path to the library file.
2788 * @param int $extracthtml Do not set this parameter usually (leave 0), only
2789 * weblib should set this to 1 or 2 in print_header function.
2790 * @return mixed No return value, except when using $extracthtml it returns the html code.
2792 function require_js($lib,$extracthtml=0) {
2793 global $CFG;
2794 static $loadlibs = array();
2796 static $state = REQUIREJS_BEFOREHEADER;
2797 static $latecode = '';
2799 if (!empty($lib)) {
2800 // Add the lib to the list of libs to be loaded, if it isn't already
2801 // in the list.
2802 if (is_array($lib)) {
2803 foreach($lib as $singlelib) {
2804 require_js($singlelib);
2806 } else {
2807 $libpath = ajax_get_lib($lib);
2808 if (array_search($libpath, $loadlibs) === false) {
2809 $loadlibs[] = $libpath;
2811 // For state other than 0 we need to take action as well as just
2812 // adding it to loadlibs
2813 if($state != REQUIREJS_BEFOREHEADER) {
2814 // Get the script statement for this library
2815 $scriptstatement=get_require_js_code(array($libpath));
2817 if($state == REQUIREJS_AFTERHEADER) {
2818 // After the header, print it immediately
2819 print $scriptstatement;
2820 } else {
2821 // Haven't finished the header yet. Add it after the
2822 // header
2823 $latecode .= $scriptstatement;
2828 } else if($extracthtml==1) {
2829 if($state !== REQUIREJS_BEFOREHEADER) {
2830 debugging('Incorrect state in require_js (expected BEFOREHEADER): be careful not to call with empty $lib (except in print_header)');
2831 } else {
2832 $state = REQUIREJS_INHEADER;
2835 return get_require_js_code($loadlibs);
2836 } else if($extracthtml==2) {
2837 if($state !== REQUIREJS_INHEADER) {
2838 debugging('Incorrect state in require_js (expected INHEADER): be careful not to call with empty $lib (except in print_header)');
2839 return '';
2840 } else {
2841 $state = REQUIREJS_AFTERHEADER;
2842 return $latecode;
2844 } else {
2845 debugging('Unexpected value for $extracthtml');
2850 * Should not be called directly - use require_js. This function obtains the code
2851 * (script tags) needed to include JavaScript libraries.
2852 * @param array $loadlibs Array of library files to include
2853 * @return string HTML code to include them
2855 function get_require_js_code($loadlibs) {
2856 global $CFG;
2857 // Return the html needed to load the JavaScript files defined in
2858 // our list of libs to be loaded.
2859 $output = '';
2860 foreach ($loadlibs as $loadlib) {
2861 $output .= '<script type="text/javascript" ';
2862 $output .= " src=\"$loadlib\"></script>\n";
2863 if ($loadlib == $CFG->wwwroot.'/lib/yui/logger/logger-min.js') {
2864 // Special case, we need the CSS too.
2865 $output .= '<link type="text/css" rel="stylesheet" ';
2866 $output .= " href=\"{$CFG->wwwroot}/lib/yui/logger/assets/logger.css\" />\n";
2869 return $output;
2874 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2875 * and substitute the XHTML strict document type.
2876 * Note, requires the 'xmlns' fix in function print_header above.
2877 * See: http://tracker.moodle.org/browse/MDL-7883
2878 * TODO:
2880 function force_strict_header($output) {
2881 global $CFG;
2882 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2883 $xsl = '/lib/xhtml.xsl';
2885 if (!headers_sent() && !empty($CFG->xmlstrictheaders)) { // With xml strict headers, the browser will barf
2886 $ctype = 'Content-Type: ';
2887 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2889 if (isset($_SERVER['HTTP_ACCEPT'])
2890 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2891 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2892 // Firefox et al.
2893 $ctype .= 'application/xhtml+xml';
2894 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2896 } else if (file_exists($CFG->dirroot.$xsl)
2897 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2898 // XSL hack for IE 5+ on Windows.
2899 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2900 $www_xsl = $CFG->wwwroot .$xsl;
2901 $ctype .= 'application/xml';
2902 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2903 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2905 } else {
2906 //ELSE: Mac/IE, old/non-XML browsers.
2907 $ctype .= 'text/html';
2908 $prolog = '';
2910 @header($ctype.'; charset=utf-8');
2911 $output = $prolog . $output;
2913 // Test parser error-handling.
2914 if (isset($_GET['error'])) {
2915 $output .= "__ TEST: XML well-formed error < __\n";
2919 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
2921 return $output;
2927 * This version of print_header is simpler because the course name does not have to be
2928 * provided explicitly in the strings. It can be used on the site page as in courses
2929 * Eventually all print_header could be replaced by print_header_simple
2931 * @param string $title Appears at the top of the window
2932 * @param string $heading Appears at the top of the page
2933 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2934 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2935 * @param string $meta Meta tags to be added to the header
2936 * @param boolean $cache Should this page be cacheable?
2937 * @param string $button HTML code for a button (usually for module editing)
2938 * @param string $menu HTML code for a popup menu
2939 * @param boolean $usexml use XML for this page
2940 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2941 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2943 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
2944 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
2946 global $COURSE, $CFG;
2948 // if we have no navigation specified, build it
2949 if( empty($navigation) ){
2950 $navigation = build_navigation('');
2953 // If old style nav prepend course short name otherwise leave $navigation object alone
2954 if (!is_newnav($navigation)) {
2955 if ($COURSE->id != SITEID) {
2956 $shortname = '<a href="'.$CFG->wwwroot.'/course/view.php?id='. $COURSE->id .'">'. $COURSE->shortname .'</a> ->';
2957 $navigation = $shortname.' '.$navigation;
2961 $output = print_header($COURSE->shortname .': '. $title, $COURSE->fullname .' '. $heading, $navigation, $focus, $meta,
2962 $cache, $button, $menu, $usexml, $bodytags, true);
2964 if ($return) {
2965 return $output;
2966 } else {
2967 echo $output;
2973 * Can provide a course object to make the footer contain a link to
2974 * to the course home page, otherwise the link will go to the site home
2975 * @uses $USER
2976 * @param mixed $course course object, used for course link button or
2977 * 'none' means no user link, only docs link
2978 * 'empty' means nothing printed in footer
2979 * 'home' special frontpage footer
2980 * @param object $usercourse course used in user link
2981 * @param boolean $return output as string
2982 * @return mixed string or void
2984 function print_footer($course=NULL, $usercourse=NULL, $return=false) {
2985 global $USER, $CFG, $THEME, $COURSE;
2987 if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
2988 admin_externalpage_print_footer();
2989 return;
2992 /// Course links or special footer
2993 if ($course) {
2994 if ($course === 'empty') {
2995 // special hack - sometimes we do not want even the docs link in footer
2996 $output = '';
2997 if (!empty($THEME->open_header_containers)) {
2998 for ($i=0; $i<$THEME->open_header_containers; $i++) {
2999 $output .= print_container_end_all(); // containers opened from header
3001 } else {
3002 //1.8 theme compatibility
3003 $output .= "\n</div>"; // content div
3005 $output .= "\n</div>\n</body>\n</html>"; // close page div started in header
3006 if ($return) {
3007 return $output;
3008 } else {
3009 echo $output;
3010 return;
3013 } else if ($course === 'none') { // Don't print any links etc
3014 $homelink = '';
3015 $loggedinas = '';
3016 $home = false;
3018 } else if ($course === 'home') { // special case for site home page - please do not remove
3019 $course = get_site();
3020 $homelink = '<div class="sitelink">'.
3021 '<a title="Moodle" href="http://moodle.org/">'.
3022 '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
3023 $home = true;
3025 } else {
3026 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
3027 '/course/view.php?id='.$course->id.'">'.format_string($course->shortname).'</a></div>';
3028 $home = false;
3031 } else {
3032 $course = get_site(); // Set course as site course by default
3033 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
3034 $home = false;
3037 /// Set up some other navigation links (passed from print_header by ugly hack)
3038 $menu = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
3039 $title = isset($THEME->title) ? $THEME->title : '';
3040 $button = isset($THEME->button) ? $THEME->button : '';
3041 $heading = isset($THEME->heading) ? $THEME->heading : '';
3042 $navigation = isset($THEME->navigation) ? $THEME->navigation : '';
3043 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
3046 /// Set the user link if necessary
3047 if (!$usercourse and is_object($course)) {
3048 $usercourse = $course;
3051 if (!isset($loggedinas)) {
3052 $loggedinas = user_login_string($usercourse, $USER);
3055 if ($loggedinas == $menu) {
3056 $menu = '';
3059 /// there should be exactly the same number of open containers as after the header
3060 if ($THEME->open_header_containers != open_containers()) {
3061 debugging('Unexpected number of open containers: '.open_containers().', expecting '.$THEME->open_header_containers, DEBUG_DEVELOPER);
3064 /// Provide some performance info if required
3065 $performanceinfo = '';
3066 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
3067 $perf = get_performance_info();
3068 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
3069 error_log("PERF: " . $perf['txt']);
3071 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
3072 $performanceinfo = $perf['html'];
3076 /// Include the actual footer file
3078 ob_start();
3079 include($CFG->footer);
3080 $output = ob_get_contents();
3081 ob_end_clean();
3083 if ($return) {
3084 return $output;
3085 } else {
3086 echo $output;
3091 * Returns the name of the current theme
3093 * @uses $CFG
3094 * @uses $USER
3095 * @uses $SESSION
3096 * @uses $COURSE
3097 * @uses $FULLME
3098 * @return string
3100 function current_theme() {
3101 global $CFG, $USER, $SESSION, $COURSE, $FULLME;
3103 if (empty($CFG->themeorder)) {
3104 $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
3105 } else {
3106 $themeorder = $CFG->themeorder;
3109 if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id) {
3110 require_once($CFG->dirroot.'/mnet/peer.php');
3111 $mnet_peer = new mnet_peer();
3112 $mnet_peer->set_id($USER->mnethostid);
3115 $theme = '';
3116 foreach ($themeorder as $themetype) {
3118 if (!empty($theme)) continue;
3120 switch ($themetype) {
3121 case 'page': // Page theme is for special page-only themes set by code
3122 if (!empty($CFG->pagetheme)) {
3123 $theme = $CFG->pagetheme;
3125 break;
3126 case 'course':
3127 if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) {
3128 $theme = $COURSE->theme;
3130 break;
3131 case 'category':
3132 if (!empty($CFG->allowcategorythemes)) {
3133 /// Nasty hack to check if we're in a category page
3134 if (stripos($FULLME, 'course/category.php') !== false) {
3135 global $id;
3136 if (!empty($id)) {
3137 $theme = current_category_theme($id);
3139 /// Otherwise check if we're in a course that has a category theme set
3140 } else if (!empty($COURSE->category)) {
3141 $theme = current_category_theme($COURSE->category);
3144 break;
3145 case 'session':
3146 if (!empty($SESSION->theme)) {
3147 $theme = $SESSION->theme;
3149 break;
3150 case 'user':
3151 if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) {
3152 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
3153 $theme = $mnet_peer->theme;
3154 } else {
3155 $theme = $USER->theme;
3158 break;
3159 case 'site':
3160 if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
3161 $theme = $mnet_peer->theme;
3162 } else {
3163 $theme = $CFG->theme;
3165 break;
3166 default:
3167 /// do nothing
3171 /// A final check in case 'site' was not included in $CFG->themeorder
3172 if (empty($theme)) {
3173 $theme = $CFG->theme;
3176 return $theme;
3180 * Retrieves the category theme if one exists, otherwise checks the parent categories.
3181 * Recursive function.
3183 * @uses $COURSE
3184 * @param integer $categoryid id of the category to check
3185 * @return string theme name
3187 function current_category_theme($categoryid=0) {
3188 global $COURSE;
3190 /// Use the COURSE global if the categoryid not set
3191 if (empty($categoryid)) {
3192 if (!empty($COURSE->category)) {
3193 $categoryid = $COURSE->category;
3194 } else {
3195 return false;
3199 /// Retrieve the current category
3200 if ($category = get_record('course_categories', 'id', $categoryid)) {
3202 /// Return the category theme if it exists
3203 if (!empty($category->theme)) {
3204 return $category->theme;
3206 /// Otherwise try the parent category if one exists
3207 } else if (!empty($category->parent)) {
3208 return current_category_theme($category->parent);
3211 /// Return false if we can't find the category record
3212 } else {
3213 return false;
3218 * This function is called by stylesheets to set up the header
3219 * approriately as well as the current path
3221 * @uses $CFG
3222 * @param int $lastmodified ?
3223 * @param int $lifetime ?
3224 * @param string $thename ?
3226 function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
3228 global $CFG, $THEME;
3230 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
3231 $lastmodified = time();
3233 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
3234 header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
3235 header('Cache-Control: max-age='. $lifetime);
3236 header('Pragma: ');
3237 header('Content-type: text/css'); // Correct MIME type
3239 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
3241 if (empty($themename)) {
3242 $themename = current_theme(); // So we have something. Normally not needed.
3243 } else {
3244 $themename = clean_param($themename, PARAM_SAFEDIR);
3247 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
3248 unset($THEME);
3249 include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
3252 /// If this is the standard theme calling us, then find out what sheets we need
3254 if ($themename == 'standard') {
3255 if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
3256 $THEME->sheets = $DEFAULT_SHEET_LIST;
3257 } else if (empty($THEME->standardsheets)) { // We can stop right now!
3258 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3259 exit;
3260 } else { // Use the provided subset only
3261 $THEME->sheets = $THEME->standardsheets;
3264 /// If we are a parent theme, then check for parent definitions
3266 } else if (!empty($THEME->parent) && $themename == $THEME->parent) {
3267 if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have
3268 $THEME->sheets = $DEFAULT_SHEET_LIST;
3269 } else if (empty($THEME->parentsheets)) { // We can stop right now!
3270 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3271 exit;
3272 } else { // Use the provided subset only
3273 $THEME->sheets = $THEME->parentsheets;
3277 /// Work out the last modified date for this theme
3279 foreach ($THEME->sheets as $sheet) {
3280 if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
3281 $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
3282 if ($sheetmodified > $lastmodified) {
3283 $lastmodified = $sheetmodified;
3289 /// Get a list of all the files we want to include
3290 $files = array();
3292 foreach ($THEME->sheets as $sheet) {
3293 $files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
3296 if ($themename == 'standard') { // Add any standard styles included in any modules
3297 if (!empty($THEME->modsheets)) { // Search for styles.php within activity modules
3298 if ($mods = get_list_of_plugins('mod')) {
3299 foreach ($mods as $mod) {
3300 if (file_exists($CFG->dirroot.'/mod/'.$mod.'/styles.php')) {
3301 $files[] = array($CFG->dirroot, '/mod/'.$mod.'/styles.php');
3307 if (!empty($THEME->blocksheets)) { // Search for styles.php within block modules
3308 if ($mods = get_list_of_plugins('blocks')) {
3309 foreach ($mods as $mod) {
3310 if (file_exists($CFG->dirroot.'/blocks/'.$mod.'/styles.php')) {
3311 $files[] = array($CFG->dirroot, '/blocks/'.$mod.'/styles.php');
3317 if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
3318 if ($mods = get_list_of_plugins('format','',$CFG->dirroot.'/course')) {
3319 foreach ($mods as $mod) {
3320 if (file_exists($CFG->dirroot.'/course/format/'.$mod.'/styles.php')) {
3321 $files[] = array($CFG->dirroot, '/course/format/'.$mod.'/styles.php');
3327 if (!isset($THEME->gradereportsheets) || $THEME->gradereportsheets) { // Search for styles.php in grade reports
3328 if ($reports = get_list_of_plugins('grade/report')) {
3329 foreach ($reports as $report) {
3330 if (file_exists($CFG->dirroot.'/grade/report/'.$report.'/styles.php')) {
3331 $files[] = array($CFG->dirroot, '/grade/report/'.$report.'/styles.php');
3337 if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
3338 if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
3339 $files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
3344 if ($files) {
3345 /// Produce a list of all the files first
3346 echo '/**************************************'."\n";
3347 echo ' * THEME NAME: '.$themename."\n *\n";
3348 echo ' * Files included in this sheet:'."\n *\n";
3349 foreach ($files as $file) {
3350 echo ' * '.$file[1]."\n";
3352 echo ' **************************************/'."\n\n";
3355 /// check if csscobstants is set
3356 if (!empty($THEME->cssconstants)) {
3357 require_once("$CFG->libdir/cssconstants.php");
3358 /// Actually collect all the files in order.
3359 $css = '';
3360 foreach ($files as $file) {
3361 $css .= '/***** '.$file[1].' start *****/'."\n\n";
3362 $css .= file_get_contents($file[0].'/'.$file[1]);
3363 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
3365 /// replace css_constants with their values
3366 echo replace_cssconstants($css);
3367 } else {
3368 /// Actually output all the files in order.
3369 if (empty($CFG->CSSEdit) && empty($THEME->CSSEdit)) {
3370 foreach ($files as $file) {
3371 echo '/***** '.$file[1].' start *****/'."\n\n";
3372 @include_once($file[0].'/'.$file[1]);
3373 echo '/***** '.$file[1].' end *****/'."\n\n";
3375 } else {
3376 foreach ($files as $file) {
3377 echo '/* @group '.$file[1].' */'."\n\n";
3378 if (strstr($file[1], '.css') !== FALSE) {
3379 echo '@import url("'.$CFG->themewww.'/'.$file[1].'");'."\n\n";
3380 } else {
3381 @include_once($file[0].'/'.$file[1]);
3383 echo '/* @end */'."\n\n";
3389 return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
3393 function theme_setup($theme = '', $params=NULL) {
3394 /// Sets up global variables related to themes
3396 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
3398 /// Do not mess with THEME if header already printed - this would break all the extra stuff in global $THEME from print_header()!!
3399 if (defined('HEADER_PRINTED')) {
3400 return;
3403 if (empty($theme)) {
3404 $theme = current_theme();
3407 /// If the theme doesn't exist for some reason then revert to standardwhite
3408 if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
3409 $CFG->theme = $theme = 'standardwhite';
3412 /// Load up the theme config
3413 $THEME = NULL; // Just to be sure
3414 include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
3416 /// Put together the parameters
3417 if (!$params) {
3418 $params = array();
3421 if ($theme != $CFG->theme) {
3422 $params[] = 'forceconfig='.$theme;
3425 /// Force language too if required
3426 if (!empty($THEME->langsheets)) {
3427 $params[] = 'lang='.current_language();
3431 /// Convert params to string
3432 if ($params) {
3433 $paramstring = '?'.implode('&', $params);
3434 } else {
3435 $paramstring = '';
3438 /// Set up image paths
3439 if(isset($CFG->smartpix) && $CFG->smartpix==1) {
3440 if($CFG->slasharguments) { // Use this method if possible for better caching
3441 $extra='';
3442 } else {
3443 $extra='?file=';
3446 $CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
3447 $CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
3448 } else if (empty($THEME->custompix)) { // Could be set in the above file
3449 $CFG->pixpath = $CFG->wwwroot .'/pix';
3450 $CFG->modpixpath = $CFG->wwwroot .'/mod';
3451 } else {
3452 $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
3453 $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
3456 /// Header and footer paths
3457 $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
3458 $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
3460 /// Define stylesheet loading order
3461 $CFG->stylesheets = array();
3462 if ($theme != 'standard') { /// The standard sheet is always loaded first
3463 $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
3465 if (!empty($THEME->parent)) { /// Parent stylesheets are loaded next
3466 $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
3468 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
3470 /// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
3471 if (!empty($HTTPSPAGEREQUIRED)) {
3472 $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
3473 $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
3474 $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
3475 foreach ($CFG->stylesheets as $key => $stylesheet) {
3476 $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
3480 // RTL support - only for RTL languages, add RTL CSS
3481 if (get_string('thisdirection') == 'rtl') {
3482 $CFG->stylesheets[] = $CFG->themewww.'/standard/rtl.css'.$paramstring;
3483 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/rtl.css'.$paramstring;
3489 * Returns text to be displayed to the user which reflects their login status
3491 * @uses $CFG
3492 * @uses $USER
3493 * @param course $course {@link $COURSE} object containing course information
3494 * @param user $user {@link $USER} object containing user information
3495 * @return string
3497 function user_login_string($course=NULL, $user=NULL) {
3498 global $USER, $CFG, $SITE;
3500 if (empty($user) and !empty($USER->id)) {
3501 $user = $USER;
3504 if (empty($course)) {
3505 $course = $SITE;
3508 if (!empty($user->realuser)) {
3509 if ($realuser = get_record('user', 'id', $user->realuser)) {
3510 $fullname = fullname($realuser, true);
3511 $realuserinfo = " [<a $CFG->frametarget
3512 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=1&amp;sesskey=".sesskey()."\">$fullname</a>] ";
3514 } else {
3515 $realuserinfo = '';
3518 if (empty($CFG->loginhttps)) {
3519 $wwwroot = $CFG->wwwroot;
3520 } else {
3521 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
3524 if (empty($course->id)) {
3525 // $course->id is not defined during installation
3526 return '';
3527 } else if (!empty($user->id)) {
3528 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3530 $fullname = fullname($user, true);
3531 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a>";
3532 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid)) {
3533 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
3535 if (isset($user->username) && $user->username == 'guest') {
3536 $loggedinas = $realuserinfo.get_string('loggedinasguest').
3537 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3538 } else if (!empty($user->access['rsw'][$context->path])) {
3539 $rolename = '';
3540 if ($role = get_record('role', 'id', $user->access['rsw'][$context->path])) {
3541 $rolename = join("", role_fix_names(array($role->id=>$role->name), $context));
3542 $rolename = ': '.format_string($rolename);
3544 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
3545 " (<a $CFG->frametarget
3546 href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
3547 } else {
3548 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
3549 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
3551 } else {
3552 $loggedinas = get_string('loggedinnot', 'moodle').
3553 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3555 return '<div class="logininfo">'.$loggedinas.'</div>';
3559 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
3560 * If not it applies sensible defaults.
3562 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
3563 * search forum block, etc. Important: these are 'silent' in a screen-reader
3564 * (unlike &gt; &raquo;), and must be accompanied by text.
3565 * @uses $THEME
3567 function check_theme_arrows() {
3568 global $THEME;
3570 if (!isset($THEME->rarrow) and !isset($THEME->larrow)) {
3571 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
3572 // Also OK in Win 9x/2K/IE 5.x
3573 $THEME->rarrow = '&#x25BA;';
3574 $THEME->larrow = '&#x25C4;';
3575 if (empty($_SERVER['HTTP_USER_AGENT'])) {
3576 $uagent = '';
3577 } else {
3578 $uagent = $_SERVER['HTTP_USER_AGENT'];
3580 if (false !== strpos($uagent, 'Opera')
3581 || false !== strpos($uagent, 'Mac')) {
3582 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
3583 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
3584 $THEME->rarrow = '&#x25B6;';
3585 $THEME->larrow = '&#x25C0;';
3587 elseif (false !== strpos($uagent, 'Konqueror')) {
3588 $THEME->rarrow = '&rarr;';
3589 $THEME->larrow = '&larr;';
3591 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
3592 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
3593 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
3594 // To be safe, non-Unicode browsers!
3595 $THEME->rarrow = '&gt;';
3596 $THEME->larrow = '&lt;';
3599 /// RTL support - in RTL languages, swap r and l arrows
3600 if (right_to_left()) {
3601 $t = $THEME->rarrow;
3602 $THEME->rarrow = $THEME->larrow;
3603 $THEME->larrow = $t;
3610 * Return the right arrow with text ('next'), and optionally embedded in a link.
3611 * See function above, check_theme_arrows.
3612 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3613 * @param string $url An optional link to use in a surrounding HTML anchor.
3614 * @param bool $accesshide True if text should be hidden (for screen readers only).
3615 * @param string $addclass Additional class names for the link, or the arrow character.
3616 * @return string HTML string.
3618 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
3619 global $THEME;
3620 check_theme_arrows();
3621 $arrowclass = 'arrow ';
3622 if (! $url) {
3623 $arrowclass .= $addclass;
3625 $arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow.'</span>';
3626 $htmltext = '';
3627 if ($text) {
3628 $htmltext = $text.'&nbsp;';
3629 if ($accesshide) {
3630 $htmltext = get_accesshide($htmltext);
3633 if ($url) {
3634 $class = '';
3635 if ($addclass) {
3636 $class =" class=\"$addclass\"";
3638 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
3640 return $htmltext.$arrow;
3644 * Return the left arrow with text ('previous'), and optionally embedded in a link.
3645 * See function above, check_theme_arrows.
3646 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3647 * @param string $url An optional link to use in a surrounding HTML anchor.
3648 * @param bool $accesshide True if text should be hidden (for screen readers only).
3649 * @param string $addclass Additional class names for the link, or the arrow character.
3650 * @return string HTML string.
3652 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
3653 global $THEME;
3654 check_theme_arrows();
3655 $arrowclass = 'arrow ';
3656 if (! $url) {
3657 $arrowclass .= $addclass;
3659 $arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow.'</span>';
3660 $htmltext = '';
3661 if ($text) {
3662 $htmltext = '&nbsp;'.$text;
3663 if ($accesshide) {
3664 $htmltext = get_accesshide($htmltext);
3667 if ($url) {
3668 $class = '';
3669 if ($addclass) {
3670 $class =" class=\"$addclass\"";
3672 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
3674 return $arrow.$htmltext;
3678 * Return a HTML element with the class "accesshide", for accessibility.
3679 * Please use cautiously - where possible, text should be visible!
3680 * @param string $text Plain text.
3681 * @param string $elem Lowercase element name, default "span".
3682 * @param string $class Additional classes for the element.
3683 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
3684 * @return string HTML string.
3686 function get_accesshide($text, $elem='span', $class='', $attrs='') {
3687 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
3691 * Return the breadcrumb trail navigation separator.
3692 * @return string HTML string.
3694 function get_separator() {
3695 //Accessibility: the 'hidden' slash is preferred for screen readers.
3696 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
3700 * Prints breadcrumb trail of links, called in theme/-/header.html
3702 * @uses $CFG
3703 * @param mixed $navigation The breadcrumb navigation string to be printed
3704 * @param string $separator OBSOLETE, mostly not used any more. See build_navigation instead.
3705 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
3706 * @return string or null, depending on $return.
3708 function print_navigation ($navigation, $separator=0, $return=false) {
3709 global $CFG, $THEME;
3710 $output = '';
3712 if (0 === $separator) {
3713 $separator = get_separator();
3715 else {
3716 $separator = '<span class="sep">'. $separator .'</span>';
3719 if ($navigation) {
3721 if (is_newnav($navigation)) {
3722 if ($return) {
3723 return($navigation['navlinks']);
3724 } else {
3725 echo $navigation['navlinks'];
3726 return;
3728 } else {
3729 debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER);
3732 if (!is_array($navigation)) {
3733 $ar = explode('->', $navigation);
3734 $navigation = array();
3736 foreach ($ar as $a) {
3737 if (strpos($a, '</a>') === false) {
3738 $navigation[] = array('title' => $a, 'url' => '');
3739 } else {
3740 if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
3741 $navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
3747 if (! $site = get_site()) {
3748 $site = new object();
3749 $site->shortname = get_string('home');
3752 //Accessibility: breadcrumb links now in a list, &raquo; replaced with a 'silent' character.
3753 $output .= get_accesshide(get_string('youarehere','access'), 'h2')."<ul>\n";
3755 $output .= '<li class="first">'."\n".'<a '.$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3756 .$CFG->wwwroot.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))
3757 && !empty($USER->id) && !empty($CFG->mymoodleredirect) && !isguest())
3758 ? '/my' : '') .'/">'. format_string($site->shortname) ."</a>\n</li>\n";
3761 foreach ($navigation as $navitem) {
3762 $title = trim(strip_tags(format_string($navitem['title'], false)));
3763 $url = $navitem['url'];
3765 if (empty($url)) {
3766 $output .= '<li>'."$separator $title</li>\n";
3767 } else {
3768 $output .= '<li>'."$separator\n<a ".$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3769 .$url.'">'."$title</a>\n</li>\n";
3773 $output .= "</ul>\n";
3776 if ($return) {
3777 return $output;
3778 } else {
3779 echo $output;
3784 * This function will build the navigation string to be used by print_header
3785 * and others.
3787 * It automatically generates the site and course level (if appropriate) links.
3789 * If you pass in a $cm object, the method will also generate the activity (e.g. 'Forums')
3790 * and activityinstances (e.g. 'General Developer Forum') navigation levels.
3792 * If you want to add any further navigation links after the ones this function generates,
3793 * the pass an array of extra link arrays like this:
3794 * array(
3795 * array('name' => $linktext1, 'link' => $url1, 'type' => $linktype1),
3796 * array('name' => $linktext2, 'link' => $url2, 'type' => $linktype2)
3798 * The normal case is to just add one further link, for example 'Editing forum' after
3799 * 'General Developer Forum', with no link.
3800 * To do that, you need to pass
3801 * array(array('name' => $linktext, 'link' => '', 'type' => 'title'))
3802 * However, becuase this is a very common case, you can use a shortcut syntax, and just
3803 * pass the string 'Editing forum', instead of an array as $extranavlinks.
3805 * At the moment, the link types only have limited significance. Type 'activity' is
3806 * recognised in order to implement the $CFG->hideactivitytypenavlink feature. Types
3807 * that are known to appear are 'home', 'course', 'activity', 'activityinstance' and 'title'.
3808 * This really needs to be documented better. In the mean time, try to be consistent, it will
3809 * enable people to customise the navigation more in future.
3811 * When passing a $cm object, the fields used are $cm->modname, $cm->name and $cm->course.
3812 * If you get the $cm object using the function get_coursemodule_from_instance or
3813 * get_coursemodule_from_id (as recommended) then this will be done for you automatically.
3814 * If you don't have $cm->modname or $cm->name, this fuction will attempt to find them using
3815 * the $cm->module and $cm->instance fields, but this takes extra database queries, so a
3816 * warning is printed in developer debug mode.
3818 * @uses $CFG
3819 * @uses $THEME
3821 * @param mixed $extranavlinks - Normally an array of arrays, keys: name, link, type. If you
3822 * only want one extra item with no link, you can pass a string instead. If you don't want
3823 * any extra links, pass an empty string.
3824 * @param mixed $cm - optionally the $cm object, if you want this function to generate the
3825 * activity and activityinstance levels of navigation too.
3827 * @return $navigation as an object so it can be differentiated from old style
3828 * navigation strings.
3830 function build_navigation($extranavlinks, $cm = null) {
3831 global $CFG, $COURSE;
3833 if (is_string($extranavlinks)) {
3834 if ($extranavlinks == '') {
3835 $extranavlinks = array();
3836 } else {
3837 $extranavlinks = array(array('name' => $extranavlinks, 'link' => '', 'type' => 'title'));
3841 $navlinks = array();
3843 //Site name
3844 if ($site = get_site()) {
3845 $navlinks[] = array(
3846 'name' => format_string($site->shortname),
3847 'link' => "$CFG->wwwroot/",
3848 'type' => 'home');
3851 // Course name, if appropriate.
3852 if (isset($COURSE) && $COURSE->id != SITEID) {
3853 $navlinks[] = array(
3854 'name' => format_string($COURSE->shortname),
3855 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",
3856 'type' => 'course');
3859 // Activity type and instance, if appropriate.
3860 if (is_object($cm)) {
3861 if (!isset($cm->modname)) {
3862 debugging('The field $cm->modname should be set if you call build_navigation with '.
3863 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3864 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
3865 if (!$cm->modname = get_field('modules', 'name', 'id', $cm->module)) {
3866 error('Cannot get the module type in build navigation.');
3869 if (!isset($cm->name)) {
3870 debugging('The field $cm->name should be set if you call build_navigation with '.
3871 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3872 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
3873 if (!$cm->name = get_field($cm->modname, 'name', 'id', $cm->instance)) {
3874 error('Cannot get the module name in build navigation.');
3877 $navlinks[] = array(
3878 'name' => get_string('modulenameplural', $cm->modname),
3879 'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/index.php?id=' . $cm->course,
3880 'type' => 'activity');
3881 $navlinks[] = array(
3882 'name' => format_string($cm->name),
3883 'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/view.php?id=' . $cm->id,
3884 'type' => 'activityinstance');
3887 //Merge in extra navigation links
3888 $navlinks = array_merge($navlinks, $extranavlinks);
3890 // Work out whether we should be showing the activity (e.g. Forums) link.
3891 // Note: build_navigation() is called from many places --
3892 // install & upgrade for example -- where we cannot count on the
3893 // roles infrastructure to be defined. Hence the $CFG->rolesactive check.
3894 if (!isset($CFG->hideactivitytypenavlink)) {
3895 $CFG->hideactivitytypenavlink = 0;
3897 if ($CFG->hideactivitytypenavlink == 2) {
3898 $hideactivitylink = true;
3899 } else if ($CFG->hideactivitytypenavlink == 1 && $CFG->rolesactive &&
3900 !empty($COURSE->id) && $COURSE->id != SITEID) {
3901 if (!isset($COURSE->context)) {
3902 $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
3904 $hideactivitylink = !has_capability('moodle/course:manageactivities', $COURSE->context);
3905 } else {
3906 $hideactivitylink = false;
3909 //Construct an unordered list from $navlinks
3910 //Accessibility: heading hidden from visual browsers by default.
3911 $navigation = get_accesshide(get_string('youarehere','access'), 'h2')." <ul>\n";
3912 $lastindex = count($navlinks) - 1;
3913 $i = -1; // Used to count the times, so we know when we get to the last item.
3914 $first = true;
3915 foreach ($navlinks as $navlink) {
3916 $i++;
3917 $last = ($i == $lastindex);
3918 if (!is_array($navlink)) {
3919 continue;
3921 if (!empty($navlink['type']) && $navlink['type'] == 'activity' && !$last && $hideactivitylink) {
3922 continue;
3924 if ($first) {
3925 $navigation .= '<li class="first">';
3926 } else {
3927 $navigation .= '<li>';
3929 if (!$first) {
3930 $navigation .= get_separator();
3932 if ((!empty($navlink['link'])) && !$last) {
3933 $navigation .= "<a $CFG->frametarget onclick=\"this.target='$CFG->framename'\" href=\"{$navlink['link']}\">";
3935 $navigation .= "{$navlink['name']}";
3936 if ((!empty($navlink['link'])) && !$last) {
3937 $navigation .= "</a>";
3940 $navigation .= "</li>";
3941 $first = false;
3943 $navigation .= "</ul>";
3945 return(array('newnav' => true, 'navlinks' => $navigation));
3950 * Prints a string in a specified size (retained for backward compatibility)
3952 * @param string $text The text to be displayed
3953 * @param int $size The size to set the font for text display.
3955 function print_headline($text, $size=2, $return=false) {
3956 $output = print_heading($text, '', $size, true);
3957 if ($return) {
3958 return $output;
3959 } else {
3960 echo $output;
3965 * Prints text in a format for use in headings.
3967 * @param string $text The text to be displayed
3968 * @param string $align The alignment of the printed paragraph of text
3969 * @param int $size The size to set the font for text display.
3971 function print_heading($text, $align='', $size=2, $class='main', $return=false) {
3972 if ($align) {
3973 $align = ' style="text-align:'.$align.';"';
3975 if ($class) {
3976 $class = ' class="'.$class.'"';
3978 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
3980 if ($return) {
3981 return $output;
3982 } else {
3983 echo $output;
3988 * Centered heading with attached help button (same title text)
3989 * and optional icon attached
3991 * @param string $text The text to be displayed
3992 * @param string $helppage The help page to link to
3993 * @param string $module The module whose help should be linked to
3994 * @param string $icon Image to display if needed
3996 function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
3997 $output = '';
3998 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
3999 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
4000 $output .= '</h2>';
4002 if ($return) {
4003 return $output;
4004 } else {
4005 echo $output;
4010 function print_heading_block($heading, $class='', $return=false) {
4011 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
4012 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
4014 if ($return) {
4015 return $output;
4016 } else {
4017 echo $output;
4023 * Print a link to continue on to another page.
4025 * @uses $CFG
4026 * @param string $link The url to create a link to.
4028 function print_continue($link, $return=false) {
4030 global $CFG;
4032 // in case we are logging upgrade in admin/index.php stop it
4033 if (function_exists('upgrade_log_finish')) {
4034 upgrade_log_finish();
4037 $output = '';
4039 if ($link == '') {
4040 if (!empty($_SERVER['HTTP_REFERER'])) {
4041 $link = $_SERVER['HTTP_REFERER'];
4042 $link = str_replace('&', '&amp;', $link); // make it valid XHTML
4043 } else {
4044 $link = $CFG->wwwroot .'/';
4048 $options = array();
4049 $linkparts = parse_url(str_replace('&amp;', '&', $link));
4050 if (isset($linkparts['query'])) {
4051 parse_str($linkparts['query'], $options);
4054 $output .= '<div class="continuebutton">';
4056 $output .= print_single_button($link, $options, get_string('continue'), 'get', $CFG->framename, true);
4057 $output .= '</div>'."\n";
4059 if ($return) {
4060 return $output;
4061 } else {
4062 echo $output;
4068 * Print a message in a standard themed box.
4069 * Replaces print_simple_box (see deprecatedlib.php)
4071 * @param string $message, the content of the box
4072 * @param string $classes, space-separated class names.
4073 * @param string $idbase
4074 * @param boolean $return, return as string or just print it
4075 * @return mixed string or void
4077 function print_box($message, $classes='generalbox', $ids='', $return=false) {
4079 $output = print_box_start($classes, $ids, true);
4080 $output .= stripslashes_safe($message);
4081 $output .= print_box_end(true);
4083 if ($return) {
4084 return $output;
4085 } else {
4086 echo $output;
4091 * Starts a box using divs
4092 * Replaces print_simple_box_start (see deprecatedlib.php)
4094 * @param string $classes, space-separated class names.
4095 * @param string $idbase
4096 * @param boolean $return, return as string or just print it
4097 * @return mixed string or void
4099 function print_box_start($classes='generalbox', $ids='', $return=false) {
4100 global $THEME;
4102 if (strpos($classes, 'clearfix') !== false) {
4103 $clearfix = true;
4104 $classes = trim(str_replace('clearfix', '', $classes));
4105 } else {
4106 $clearfix = false;
4109 if (!empty($THEME->customcorners)) {
4110 $classes .= ' ccbox box';
4111 } else {
4112 $classes .= ' box';
4115 return print_container_start($clearfix, $classes, $ids, $return);
4119 * Simple function to end a box (see above)
4120 * Replaces print_simple_box_end (see deprecatedlib.php)
4122 * @param boolean $return, return as string or just print it
4124 function print_box_end($return=false) {
4125 return print_container_end($return);
4129 * Print a message in a standard themed container.
4131 * @param string $message, the content of the container
4132 * @param boolean $clearfix clear both sides
4133 * @param string $classes, space-separated class names.
4134 * @param string $idbase
4135 * @param boolean $return, return as string or just print it
4136 * @return string or void
4138 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
4140 $output = print_container_start($clearfix, $classes, $idbase, true);
4141 $output .= stripslashes_safe($message);
4142 $output .= print_container_end(true);
4144 if ($return) {
4145 return $output;
4146 } else {
4147 echo $output;
4152 * Starts a container using divs
4154 * @param boolean $clearfix clear both sides
4155 * @param string $classes, space-separated class names.
4156 * @param string $idbase
4157 * @param boolean $return, return as string or just print it
4158 * @return mixed string or void
4160 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
4161 global $THEME;
4163 if (!isset($THEME->open_containers)) {
4164 $THEME->open_containers = array();
4166 $THEME->open_containers[] = $idbase;
4169 if (!empty($THEME->customcorners)) {
4170 $output = _print_custom_corners_start($clearfix, $classes, $idbase);
4171 } else {
4172 if ($idbase) {
4173 $id = ' id="'.$idbase.'"';
4174 } else {
4175 $id = '';
4177 if ($clearfix) {
4178 $clearfix = ' clearfix';
4179 } else {
4180 $clearfix = '';
4182 if ($classes or $clearfix) {
4183 $class = ' class="'.$classes.$clearfix.'"';
4184 } else {
4185 $class = '';
4187 $output = '<div'.$id.$class.'>';
4190 if ($return) {
4191 return $output;
4192 } else {
4193 echo $output;
4198 * Simple function to end a container (see above)
4199 * @param boolean $return, return as string or just print it
4200 * @return mixed string or void
4202 function print_container_end($return=false) {
4203 global $THEME;
4205 if (empty($THEME->open_containers)) {
4206 debugging('Incorrect request to end container - no more open containers.', DEBUG_DEVELOPER);
4207 $idbase = '';
4208 } else {
4209 $idbase = array_pop($THEME->open_containers);
4212 if (!empty($THEME->customcorners)) {
4213 $output = _print_custom_corners_end($idbase);
4214 } else {
4215 $output = '</div>';
4218 if ($return) {
4219 return $output;
4220 } else {
4221 echo $output;
4226 * Returns number of currently open containers
4227 * @return int number of open containers
4229 function open_containers() {
4230 global $THEME;
4232 if (!isset($THEME->open_containers)) {
4233 $THEME->open_containers = array();
4236 return count($THEME->open_containers);
4240 * Force closing of open containers
4241 * @param boolean $return, return as string or just print it
4242 * @param int $keep number of containers to be kept open - usually theme or page containers
4243 * @return mixed string or void
4245 function print_container_end_all($return=false, $keep=0) {
4246 $output = '';
4247 while (open_containers() > $keep) {
4248 $output .= print_container_end($return);
4251 if ($return) {
4252 return $output;
4253 } else {
4254 echo $output;
4259 * Internal function - do not use directly!
4260 * Starting part of the surrounding divs for custom corners
4262 * @param boolean $clearfix, add CLASS "clearfix" to the inner div against collapsing
4263 * @param string $classes
4264 * @param mixed $idbase, optionally, define one idbase to be added to all the elements in the corners
4265 * @return string
4267 function _print_custom_corners_start($clearfix=false, $classes='', $idbase='') {
4268 /// Analise if we want ids for the custom corner elements
4269 $id = '';
4270 $idbt = '';
4271 $idi1 = '';
4272 $idi2 = '';
4273 $idi3 = '';
4275 if ($idbase) {
4276 $id = 'id="'.$idbase.'" ';
4277 $idbt = 'id="'.$idbase.'-bt" ';
4278 $idi1 = 'id="'.$idbase.'-i1" ';
4279 $idi2 = 'id="'.$idbase.'-i2" ';
4280 $idi3 = 'id="'.$idbase.'-i3" ';
4283 /// Calculate current level
4284 $level = open_containers();
4286 /// Output begins
4287 $output = '<div '.$id.'class="wrap wraplevel'.$level.' '.$classes.'">'."\n";
4288 $output .= '<div '.$idbt.'class="bt"><div>&nbsp;</div></div>';
4289 $output .= "\n";
4290 $output .= '<div '.$idi1.'class="i1"><div '.$idi2.'class="i2">';
4291 $output .= (!empty($clearfix)) ? '<div '.$idi3.'class="i3 clearfix">' : '<div '.$idi3.'class="i3">';
4293 return $output;
4298 * Internal function - do not use directly!
4299 * Ending part of the surrounding divs for custom corners
4300 * @param string $idbase
4301 * @return string
4303 function _print_custom_corners_end($idbase) {
4304 /// Analise if we want ids for the custom corner elements
4305 $idbb = '';
4307 if ($idbase) {
4308 $idbb = 'id="' . $idbase . '-bb" ';
4311 /// Output begins
4312 $output = '</div></div></div>';
4313 $output .= "\n";
4314 $output .= '<div '.$idbb.'class="bb"><div>&nbsp;</div></div>'."\n";
4315 $output .= '</div>';
4317 return $output;
4322 * Print a self contained form with a single submit button.
4324 * @param string $link used as the action attribute on the form, so the URL that will be hit if the button is clicked.
4325 * @param array $options these become hidden form fields, so these options get passed to the script at $link.
4326 * @param string $label the caption that appears on the button.
4327 * @param string $method HTTP method used on the request of the button is clicked. 'get' or 'post'.
4328 * @param string $target no longer used.
4329 * @param boolean $return if false, output the form directly, otherwise return the HTML as a string.
4330 * @param string $tooltip a tooltip to add to the button as a title attribute.
4331 * @param boolean $disabled if true, the button will be disabled.
4332 * @param string $jsconfirmmessage if not empty then display a confirm dialogue with this string as the question.
4333 * @return string / nothing depending on the $return paramter.
4335 function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='', $disabled = false, $jsconfirmmessage='') {
4336 $output = '';
4337 $link = str_replace('"', '&quot;', $link); //basic XSS protection
4338 $output .= '<div class="singlebutton">';
4339 // taking target out, will need to add later target="'.$target.'"
4340 $output .= '<form action="'. $link .'" method="'. $method .'">';
4341 $output .= '<div>';
4342 if ($options) {
4343 foreach ($options as $name => $value) {
4344 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
4347 if ($tooltip) {
4348 $tooltip = 'title="' . s($tooltip) . '"';
4349 } else {
4350 $tooltip = '';
4352 if ($disabled) {
4353 $disabled = 'disabled="disabled"';
4354 } else {
4355 $disabled = '';
4357 if ($jsconfirmmessage){
4358 $jsconfirmmessage = addslashes_js($jsconfirmmessage);
4359 $jsconfirmmessage = 'onclick="return confirm(\''. $jsconfirmmessage .'\');" ';
4361 $output .= '<input type="submit" value="'. s($label) ."\" $tooltip $disabled $jsconfirmmessage/></div></form></div>";
4363 if ($return) {
4364 return $output;
4365 } else {
4366 echo $output;
4372 * Print a spacer image with the option of including a line break.
4374 * @param int $height ?
4375 * @param int $width ?
4376 * @param boolean $br ?
4377 * @todo Finish documenting this function
4379 function print_spacer($height=1, $width=1, $br=true, $return=false) {
4380 global $CFG;
4381 $output = '';
4383 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot .'/pix/spacer.gif" alt="" />';
4384 if ($br) {
4385 $output .= '<br />'."\n";
4388 if ($return) {
4389 return $output;
4390 } else {
4391 echo $output;
4396 * Given the path to a picture file in a course, or a URL,
4397 * this function includes the picture in the page.
4399 * @param string $path ?
4400 * @param int $courseid ?
4401 * @param int $height ?
4402 * @param int $width ?
4403 * @param string $link ?
4404 * @todo Finish documenting this function
4406 function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
4407 global $CFG;
4408 $output = '';
4410 if ($height) {
4411 $height = 'height="'. $height .'"';
4413 if ($width) {
4414 $width = 'width="'. $width .'"';
4416 if ($link) {
4417 $output .= '<a href="'. $link .'">';
4419 if (substr(strtolower($path), 0, 7) == 'http://') {
4420 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
4422 } else if ($courseid) {
4423 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
4424 require_once($CFG->libdir.'/filelib.php');
4425 $output .= get_file_url("$courseid/$path");
4426 $output .= '" />';
4427 } else {
4428 $output .= 'Error: must pass URL or course';
4430 if ($link) {
4431 $output .= '</a>';
4434 if ($return) {
4435 return $output;
4436 } else {
4437 echo $output;
4442 * Print the specified user's avatar.
4444 * @param mixed $user Should be a $user object with at least fields id, picture, imagealt, firstname, lastname
4445 * If any of these are missing, or if a userid is passed, the the database is queried. Avoid this
4446 * if at all possible, particularly for reports. It is very bad for performance.
4447 * @param int $courseid The course id. Used when constructing the link to the user's profile.
4448 * @param boolean $picture The picture to print. By default (or if NULL is passed) $user->picture is used.
4449 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
4450 * @param boolean $return If false print picture to current page, otherwise return the output as string
4451 * @param boolean $link enclose printed image in a link the user's profile (default true).
4452 * @param string $target link target attribute. Makes the profile open in a popup window.
4453 * @param boolean $alttext add non-blank alt-text to the image. (Default true, set to false for purely
4454 * decorative images, or where the username will be printed anyway.)
4455 * @return string or nothing, depending on $return.
4457 function print_user_picture($user, $courseid, $picture=NULL, $size=0, $return=false, $link=true, $target='', $alttext=true) {
4458 global $CFG;
4460 $needrec = false;
4461 // only touch the DB if we are missing data...
4462 if (is_object($user)) {
4463 // Note - both picture and imagealt _can_ be empty
4464 // what we are trying to see here is if they have been fetched
4465 // from the DB. We should use isset() _except_ that some installs
4466 // have those fields as nullable, and isset() will return false
4467 // on null. The only safe thing is to ask array_key_exists()
4468 // which works on objects. property_exists() isn't quite
4469 // what we want here...
4470 if (! (array_key_exists('picture', $user)
4471 && ($alttext && array_key_exists('imagealt', $user)
4472 || (isset($user->firstname) && isset($user->lastname)))) ) {
4473 $needrec = true;
4474 $user = $user->id;
4476 } else {
4477 if ($alttext) {
4478 // we need firstname, lastname, imagealt, can't escape...
4479 $needrec = true;
4480 } else {
4481 $userobj = new StdClass; // fake it to save DB traffic
4482 $userobj->id = $user;
4483 $userobj->picture = $picture;
4484 $user = clone($userobj);
4485 unset($userobj);
4488 if ($needrec) {
4489 $user = get_record('user','id',$user, '', '', '', '', 'id,firstname,lastname,imagealt');
4492 if ($link) {
4493 $url = '/user/view.php?id='. $user->id .'&amp;course='. $courseid ;
4494 if ($target) {
4495 $target='onclick="return openpopup(\''.$url.'\');"';
4497 $output = '<a '.$target.' href="'. $CFG->wwwroot . $url .'">';
4498 } else {
4499 $output = '';
4501 if (empty($size)) {
4502 $file = 'f2';
4503 $size = 35;
4504 } else if ($size === true or $size == 1) {
4505 $file = 'f1';
4506 $size = 100;
4507 } else if ($size >= 50) {
4508 $file = 'f1';
4509 } else {
4510 $file = 'f2';
4512 $class = "userpicture";
4514 if (is_null($picture) and !empty($user->picture)) {
4515 $picture = $user->picture;
4518 if ($picture) { // Print custom user picture
4519 require_once($CFG->libdir.'/filelib.php');
4520 $src = get_file_url($user->id.'/'.$file.'.jpg', null, 'user');
4521 } else { // Print default user pictures (use theme version if available)
4522 $class .= " defaultuserpic";
4523 $src = "$CFG->pixpath/u/$file.png";
4525 $imagealt = '';
4526 if ($alttext) {
4527 if (!empty($user->imagealt)) {
4528 $imagealt = $user->imagealt;
4529 } else {
4530 $imagealt = get_string('pictureof','',fullname($user));
4534 $output .= "<img class=\"$class\" src=\"$src\" height=\"$size\" width=\"$size\" alt=\"".s($imagealt).'" />';
4535 if ($link) {
4536 $output .= '</a>';
4539 if ($return) {
4540 return $output;
4541 } else {
4542 echo $output;
4547 * Prints a summary of a user in a nice little box.
4549 * @uses $CFG
4550 * @uses $USER
4551 * @param user $user A {@link $USER} object representing a user
4552 * @param course $course A {@link $COURSE} object representing a course
4554 function print_user($user, $course, $messageselect=false, $return=false) {
4556 global $CFG, $USER;
4558 $output = '';
4560 static $string;
4561 static $datestring;
4562 static $countries;
4564 $context = get_context_instance(CONTEXT_COURSE, $course->id);
4565 if (isset($user->context->id)) {
4566 $usercontext = $user->context;
4567 } else {
4568 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
4571 if (empty($string)) { // Cache all the strings for the rest of the page
4573 $string->email = get_string('email');
4574 $string->city = get_string('city');
4575 $string->lastaccess = get_string('lastaccess');
4576 $string->activity = get_string('activity');
4577 $string->unenrol = get_string('unenrol');
4578 $string->loginas = get_string('loginas');
4579 $string->fullprofile = get_string('fullprofile');
4580 $string->role = get_string('role');
4581 $string->name = get_string('name');
4582 $string->never = get_string('never');
4584 $datestring->day = get_string('day');
4585 $datestring->days = get_string('days');
4586 $datestring->hour = get_string('hour');
4587 $datestring->hours = get_string('hours');
4588 $datestring->min = get_string('min');
4589 $datestring->mins = get_string('mins');
4590 $datestring->sec = get_string('sec');
4591 $datestring->secs = get_string('secs');
4592 $datestring->year = get_string('year');
4593 $datestring->years = get_string('years');
4595 $countries = get_list_of_countries();
4598 /// Get the hidden field list
4599 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
4600 $hiddenfields = array();
4601 } else {
4602 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
4605 $output .= '<table class="userinfobox">';
4606 $output .= '<tr>';
4607 $output .= '<td class="left side">';
4608 $output .= print_user_picture($user, $course->id, $user->picture, true, true);
4609 $output .= '</td>';
4610 $output .= '<td class="content">';
4611 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
4612 $output .= '<div class="info">';
4613 if (!empty($user->role) and ($user->role <> $course->teacher)) {
4614 $output .= $string->role .': '. $user->role .'<br />';
4616 if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguest()) or
4617 has_capability('moodle/course:viewhiddenuserfields', $context)) {
4618 $output .= $string->email .': <a href="mailto:'. $user->email .'">'. $user->email .'</a><br />';
4620 if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
4621 $output .= $string->city .': ';
4622 if ($user->city && !isset($hiddenfields['city'])) {
4623 $output .= $user->city;
4625 if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
4626 if ($user->city && !isset($hiddenfields['city'])) {
4627 $output .= ', ';
4629 $output .= $countries[$user->country];
4631 $output .= '<br />';
4634 if (!isset($hiddenfields['lastaccess'])) {
4635 if ($user->lastaccess) {
4636 $output .= $string->lastaccess .': '. userdate($user->lastaccess);
4637 $output .= '&nbsp; ('. format_time(time() - $user->lastaccess, $datestring) .')';
4638 } else {
4639 $output .= $string->lastaccess .': '. $string->never;
4642 $output .= '</div></td><td class="links">';
4643 //link to blogs
4644 if ($CFG->bloglevel > 0) {
4645 $output .= '<a href="'.$CFG->wwwroot.'/blog/index.php?userid='.$user->id.'">'.get_string('blogs','blog').'</a><br />';
4647 //link to notes
4648 if (!empty($CFG->enablenotes) and (has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context))) {
4649 $output .= '<a href="'.$CFG->wwwroot.'/notes/index.php?course=' . $course->id. '&amp;user='.$user->id.'">'.get_string('notes','notes').'</a><br />';
4652 if (has_capability('moodle/site:viewreports', $context) or has_capability('moodle/user:viewuseractivitiesreport', $usercontext)) {
4653 $output .= '<a href="'. $CFG->wwwroot .'/course/user.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->activity .'</a><br />';
4655 if (has_capability('moodle/role:assign', $context) and get_user_roles($context, $user->id, false)) { // I can unassing and user has some role
4656 $output .= '<a href="'. $CFG->wwwroot .'/course/unenrol.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->unenrol .'</a><br />';
4658 if ($USER->id != $user->id && empty($USER->realuser) && has_capability('moodle/user:loginas', $context) &&
4659 ! has_capability('moodle/site:doanything', $context, $user->id, false)) {
4660 $output .= '<a href="'. $CFG->wwwroot .'/course/loginas.php?id='. $course->id .'&amp;user='. $user->id .'&amp;sesskey='. sesskey() .'">'. $string->loginas .'</a><br />';
4662 $output .= '<a href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&amp;course='. $course->id .'">'. $string->fullprofile .'...</a>';
4664 if (!empty($messageselect)) {
4665 $output .= '<br /><input type="checkbox" name="user'.$user->id.'" /> ';
4668 $output .= '</td></tr></table>';
4670 if ($return) {
4671 return $output;
4672 } else {
4673 echo $output;
4678 * Print a specified group's avatar.
4680 * @param group $group A single {@link group} object OR array of groups.
4681 * @param int $courseid The course ID.
4682 * @param boolean $large Default small picture, or large.
4683 * @param boolean $return If false print picture, otherwise return the output as string
4684 * @param boolean $link Enclose image in a link to view specified course?
4685 * @return string
4686 * @todo Finish documenting this function
4688 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
4689 global $CFG;
4691 if (is_array($group)) {
4692 $output = '';
4693 foreach($group as $g) {
4694 $output .= print_group_picture($g, $courseid, $large, true, $link);
4696 if ($return) {
4697 return $output;
4698 } else {
4699 echo $output;
4700 return;
4704 $context = get_context_instance(CONTEXT_COURSE, $courseid);
4706 // If there is no picture, do nothing
4707 if (!$group->picture) {
4708 return '';
4711 // If picture is hidden, only show to those with course:managegroups
4712 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
4713 return '';
4716 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4717 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
4718 } else {
4719 $output = '';
4721 if ($large) {
4722 $file = 'f1';
4723 } else {
4724 $file = 'f2';
4727 // Print custom group picture
4728 require_once($CFG->libdir.'/filelib.php');
4729 $grouppictureurl = get_file_url($group->id.'/'.$file.'.jpg', null, 'usergroup');
4730 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
4731 ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
4733 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4734 $output .= '</a>';
4737 if ($return) {
4738 return $output;
4739 } else {
4740 echo $output;
4745 * Print a png image.
4747 * @param string $url ?
4748 * @param int $sizex ?
4749 * @param int $sizey ?
4750 * @param boolean $return ?
4751 * @param string $parameters ?
4752 * @todo Finish documenting this function
4754 function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
4755 global $CFG;
4756 static $recentIE;
4758 if (!isset($recentIE)) {
4759 $recentIE = check_browser_version('MSIE', '5.0');
4762 if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
4763 $output .= '<img src="'. $CFG->pixpath .'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
4764 ' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
4765 ' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
4766 "'$url', sizingMethod='scale') ".
4767 ' '. $parameters .' />';
4768 } else {
4769 $output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
4772 if ($return) {
4773 return $output;
4774 } else {
4775 echo $output;
4780 * Print a nicely formatted table.
4782 * @param array $table is an object with several properties.
4783 * <ul>
4784 * <li>$table->head - An array of heading names.
4785 * <li>$table->align - An array of column alignments
4786 * <li>$table->size - An array of column sizes
4787 * <li>$table->wrap - An array of "nowrap"s or nothing
4788 * <li>$table->data[] - An array of arrays containing the data.
4789 * <li>$table->width - A percentage of the page
4790 * <li>$table->tablealign - Align the whole table
4791 * <li>$table->cellpadding - Padding on each cell
4792 * <li>$table->cellspacing - Spacing between cells
4793 * <li>$table->class - class attribute to put on the table
4794 * <li>$table->id - id attribute to put on the table.
4795 * <li>$table->rowclass[] - classes to add to particular rows.
4796 * <li>$table->summary - Description of the contents for screen readers.
4797 * </ul>
4798 * @param bool $return whether to return an output string or echo now
4799 * @return boolean or $string
4800 * @todo Finish documenting this function
4802 function print_table($table, $return=false) {
4803 $output = '';
4805 if (isset($table->align)) {
4806 foreach ($table->align as $key => $aa) {
4807 if ($aa) {
4808 $align[$key] = ' text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
4809 } else {
4810 $align[$key] = '';
4814 if (isset($table->size)) {
4815 foreach ($table->size as $key => $ss) {
4816 if ($ss) {
4817 $size[$key] = ' width:'. $ss .';';
4818 } else {
4819 $size[$key] = '';
4823 if (isset($table->wrap)) {
4824 foreach ($table->wrap as $key => $ww) {
4825 if ($ww) {
4826 $wrap[$key] = ' white-space:nowrap;';
4827 } else {
4828 $wrap[$key] = '';
4833 if (empty($table->width)) {
4834 $table->width = '80%';
4837 if (empty($table->tablealign)) {
4838 $table->tablealign = 'center';
4841 if (!isset($table->cellpadding)) {
4842 $table->cellpadding = '5';
4845 if (!isset($table->cellspacing)) {
4846 $table->cellspacing = '1';
4849 if (empty($table->class)) {
4850 $table->class = 'generaltable';
4853 $tableid = empty($table->id) ? '' : 'id="'.$table->id.'"';
4855 $output .= '<table width="'.$table->width.'" ';
4856 if (!empty($table->summary)) {
4857 $output .= " summary=\"$table->summary\"";
4859 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
4861 $countcols = 0;
4863 if (!empty($table->head)) {
4864 $countcols = count($table->head);
4865 $output .= '<tr>';
4866 $keys=array_keys($table->head);
4867 $lastkey = end($keys);
4868 foreach ($table->head as $key => $heading) {
4870 if (!isset($size[$key])) {
4871 $size[$key] = '';
4873 if (!isset($align[$key])) {
4874 $align[$key] = '';
4876 if ($key == $lastkey) {
4877 $extraclass = ' lastcol';
4878 } else {
4879 $extraclass = '';
4882 $output .= '<th style="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.$extraclass.'" scope="col">'. $heading .'</th>';
4884 $output .= '</tr>'."\n";
4887 if (!empty($table->data)) {
4888 $oddeven = 1;
4889 $keys=array_keys($table->data);
4890 $lastrowkey = end($keys);
4891 foreach ($table->data as $key => $row) {
4892 $oddeven = $oddeven ? 0 : 1;
4893 if (!isset($table->rowclass[$key])) {
4894 $table->rowclass[$key] = '';
4896 if ($key == $lastrowkey) {
4897 $table->rowclass[$key] .= ' lastrow';
4899 $output .= '<tr class="r'.$oddeven.' '.$table->rowclass[$key].'">'."\n";
4900 if ($row == 'hr' and $countcols) {
4901 $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
4902 } else { /// it's a normal row of data
4903 $keys2=array_keys($row);
4904 $lastkey = end($keys2);
4905 foreach ($row as $key => $item) {
4906 if (!isset($size[$key])) {
4907 $size[$key] = '';
4909 if (!isset($align[$key])) {
4910 $align[$key] = '';
4912 if (!isset($wrap[$key])) {
4913 $wrap[$key] = '';
4915 if ($key == $lastkey) {
4916 $extraclass = ' lastcol';
4917 } else {
4918 $extraclass = '';
4920 $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.$extraclass.'">'. $item .'</td>';
4923 $output .= '</tr>'."\n";
4926 $output .= '</table>'."\n";
4928 if ($return) {
4929 return $output;
4932 echo $output;
4933 return true;
4936 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
4937 static $strftimerecent = null;
4938 $output = '';
4940 if (is_null($viewfullnames)) {
4941 $context = get_context_instance(CONTEXT_SYSTEM);
4942 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
4945 if (is_null($strftimerecent)) {
4946 $strftimerecent = get_string('strftimerecent');
4949 $output .= '<div class="head">';
4950 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
4951 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
4952 $output .= '</div>';
4953 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
4955 if ($return) {
4956 return $output;
4957 } else {
4958 echo $output;
4964 * Prints a basic textarea field.
4966 * @uses $CFG
4967 * @param boolean $usehtmleditor ?
4968 * @param int $rows ?
4969 * @param int $cols ?
4970 * @param null $width <b>Legacy field no longer used!</b> Set to zero to get control over mincols
4971 * @param null $height <b>Legacy field no longer used!</b> Set to zero to get control over minrows
4972 * @param string $name ?
4973 * @param string $value ?
4974 * @param int $courseid ?
4975 * @todo Finish documenting this function
4977 function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $courseid=0, $return=false, $id='') {
4978 /// $width and height are legacy fields and no longer used as pixels like they used to be.
4979 /// However, you can set them to zero to override the mincols and minrows values below.
4981 global $CFG, $COURSE, $HTTPSPAGEREQUIRED;
4982 static $scriptcount = 0; // For loading the htmlarea script only once.
4984 $mincols = 65;
4985 $minrows = 10;
4986 $str = '';
4988 if ($id === '') {
4989 $id = 'edit-'.$name;
4992 if ( empty($CFG->editorsrc) ) { // for backward compatibility.
4993 if (empty($courseid)) {
4994 $courseid = $COURSE->id;
4997 if ($usehtmleditor) {
4998 if (!empty($courseid) and has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE, $courseid))) {
4999 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '&amp;httpsrequired=1';
5000 // needed for course file area browsing in image insert plugin
5001 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
5002 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php?id='.$courseid.$httpsrequired.'"></script>'."\n" : '';
5003 } else {
5004 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '?httpsrequired=1';
5005 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
5006 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php'.$httpsrequired.'"></script>'."\n" : '';
5009 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
5010 $CFG->httpswwwroot .'/lib/editor/htmlarea/lang/en.php?id='.$courseid.'"></script>'."\n" : '';
5011 $scriptcount++;
5013 if ($height) { // Usually with legacy calls
5014 if ($rows < $minrows) {
5015 $rows = $minrows;
5018 if ($width) { // Usually with legacy calls
5019 if ($cols < $mincols) {
5020 $cols = $mincols;
5025 $str .= '<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">';
5026 if ($usehtmleditor) {
5027 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
5028 } else {
5029 $str .= s($value);
5031 $str .= '</textarea>'."\n";
5033 if ($usehtmleditor) {
5034 // Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
5035 $str .= '<script type="text/javascript">
5036 //<![CDATA[
5037 document.write(\''.addslashes_js(editorshortcutshelpbutton()).'\');
5038 //]]>
5039 </script>';
5042 if ($return) {
5043 return $str;
5045 echo $str;
5049 * Sets up the HTML editor on textareas in the current page.
5050 * If a field name is provided, then it will only be
5051 * applied to that field - otherwise it will be used
5052 * on every textarea in the page.
5054 * In most cases no arguments need to be supplied
5056 * @param string $name Form element to replace with HTMl editor by name
5058 function use_html_editor($name='', $editorhidebuttons='', $id='') {
5059 global $THEME;
5061 $editor = 'editor_'.md5($name); //name might contain illegal characters
5062 if ($id === '') {
5063 $id = 'edit-'.$name;
5065 echo "\n".'<script type="text/javascript" defer="defer">'."\n";
5066 echo '//<![CDATA['."\n\n"; // Extra \n is to fix odd wiki problem, MDL-8185
5067 echo "$editor = new HTMLArea('$id');\n";
5068 echo "var config = $editor.config;\n";
5070 echo print_editor_config($editorhidebuttons);
5072 if (empty($THEME->htmleditorpostprocess)) {
5073 if (empty($name)) {
5074 echo "\nHTMLArea.replaceAll($editor.config);\n";
5075 } else {
5076 echo "\n$editor.generate();\n";
5078 } else {
5079 if (empty($name)) {
5080 echo "\nvar HTML_name = '';";
5081 } else {
5082 echo "\nvar HTML_name = \"$name;\"";
5084 echo "\nvar HTML_editor = $editor;";
5086 echo '//]]>'."\n";
5087 echo '</script>'."\n";
5090 function print_editor_config($editorhidebuttons='', $return=false) {
5091 global $CFG;
5093 $str = "config.pageStyle = \"body {";
5095 if (!(empty($CFG->editorbackgroundcolor))) {
5096 $str .= " background-color: $CFG->editorbackgroundcolor;";
5099 if (!(empty($CFG->editorfontfamily))) {
5100 $str .= " font-family: $CFG->editorfontfamily;";
5103 if (!(empty($CFG->editorfontsize))) {
5104 $str .= " font-size: $CFG->editorfontsize;";
5107 $str .= " }\";\n";
5108 $str .= "config.killWordOnPaste = ";
5109 $str .= (empty($CFG->editorkillword)) ? "false":"true";
5110 $str .= ';'."\n";
5111 $str .= 'config.fontname = {'."\n";
5113 $fontlist = isset($CFG->editorfontlist) ? explode(';', $CFG->editorfontlist) : array();
5114 $i = 1; // Counter is used to get rid of the last comma.
5116 foreach ($fontlist as $fontline) {
5117 if (!empty($fontline)) {
5118 if ($i > 1) {
5119 $str .= ','."\n";
5121 list($fontkey, $fontvalue) = split(':', $fontline);
5122 $str .= '"'. $fontkey ."\":\t'". $fontvalue ."'";
5124 $i++;
5127 $str .= '};';
5129 if (!empty($editorhidebuttons)) {
5130 $str .= "\nconfig.hideSomeButtons(\" ". $editorhidebuttons ." \");\n";
5131 } else if (!empty($CFG->editorhidebuttons)) {
5132 $str .= "\nconfig.hideSomeButtons(\" ". $CFG->editorhidebuttons ." \");\n";
5135 if (!empty($CFG->editorspelling) && !empty($CFG->aspellpath)) {
5136 $str .= print_speller_code($CFG->htmleditor, true);
5139 if ($return) {
5140 return $str;
5142 echo $str;
5146 * Returns a turn edit on/off button for course in a self contained form.
5147 * Used to be an icon, but it's now a simple form button
5149 * Note that the caller is responsible for capchecks.
5151 * @uses $CFG
5152 * @uses $USER
5153 * @param int $courseid The course to update by id as found in 'course' table
5154 * @return string
5156 function update_course_icon($courseid) {
5157 global $CFG, $USER;
5159 if (!empty($USER->editing)) {
5160 $string = get_string('turneditingoff');
5161 $edit = '0';
5162 } else {
5163 $string = get_string('turneditingon');
5164 $edit = '1';
5167 return '<form '.$CFG->frametarget.' method="get" action="'.$CFG->wwwroot.'/course/view.php">'.
5168 '<div>'.
5169 '<input type="hidden" name="id" value="'.$courseid.'" />'.
5170 '<input type="hidden" name="edit" value="'.$edit.'" />'.
5171 '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
5172 '<input type="submit" value="'.$string.'" />'.
5173 '</div></form>';
5177 * Returns a little popup menu for switching roles
5179 * @uses $CFG
5180 * @uses $USER
5181 * @param int $courseid The course to update by id as found in 'course' table
5182 * @return string
5184 function switchroles_form($courseid) {
5186 global $CFG, $USER;
5189 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
5190 return '';
5193 if (!empty($USER->access['rsw'][$context->path])){ // Just a button to return to normal
5194 $options = array();
5195 $options['id'] = $courseid;
5196 $options['sesskey'] = sesskey();
5197 $options['switchrole'] = 0;
5199 return print_single_button($CFG->wwwroot.'/course/view.php', $options,
5200 get_string('switchrolereturn'), 'post', '_self', true);
5203 if (has_capability('moodle/role:switchroles', $context)) {
5204 if (!$roles = get_assignable_roles_for_switchrole($context)) {
5205 return ''; // Nothing to show!
5207 // unset default user role - it would not work
5208 unset($roles[$CFG->guestroleid]);
5209 return popup_form($CFG->wwwroot.'/course/view.php?id='.$courseid.'&amp;sesskey='.sesskey().'&amp;switchrole=',
5210 $roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
5213 return '';
5218 * Returns a turn edit on/off button for course in a self contained form.
5219 * Used to be an icon, but it's now a simple form button
5221 * @uses $CFG
5222 * @uses $USER
5223 * @param int $courseid The course to update by id as found in 'course' table
5224 * @return string
5226 function update_mymoodle_icon() {
5228 global $CFG, $USER;
5230 if (!empty($USER->editing)) {
5231 $string = get_string('updatemymoodleoff');
5232 $edit = '0';
5233 } else {
5234 $string = get_string('updatemymoodleon');
5235 $edit = '1';
5238 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
5239 "<div>".
5240 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5241 "<input type=\"submit\" value=\"$string\" /></div></form>";
5245 * Returns a turn edit on/off button for tag in a self contained form.
5247 * @uses $CFG
5248 * @uses $USER
5249 * @return string
5251 function update_tag_button($tagid) {
5253 global $CFG, $USER;
5255 if (!empty($USER->editing)) {
5256 $string = get_string('turneditingoff');
5257 $edit = '0';
5258 } else {
5259 $string = get_string('turneditingon');
5260 $edit = '1';
5263 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/tag/index.php\">".
5264 "<div>".
5265 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5266 "<input type=\"hidden\" name=\"id\" value=\"$tagid\" />".
5267 "<input type=\"submit\" value=\"$string\" /></div></form>";
5271 * Prints the editing button on a module "view" page
5273 * @uses $CFG
5274 * @param type description
5275 * @todo Finish documenting this function
5277 function update_module_button($moduleid, $courseid, $string) {
5278 global $CFG, $USER;
5280 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $moduleid))) {
5281 $string = get_string('updatethis', '', $string);
5283 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
5284 "<div>".
5285 "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
5286 "<input type=\"hidden\" name=\"return\" value=\"true\" />".
5287 "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
5288 "<input type=\"submit\" value=\"$string\" /></div></form>";
5289 } else {
5290 return '';
5295 * Prints the editing button on search results listing
5296 * For bulk move courses to another category
5299 function update_categories_search_button($search,$page,$perpage) {
5300 global $CFG, $USER;
5302 // not sure if this capability is the best here
5303 if (has_capability('moodle/category:manage', get_context_instance(CONTEXT_SYSTEM))) {
5304 if (!empty($USER->categoryediting)) {
5305 $string = get_string("turneditingoff");
5306 $edit = "off";
5307 $perpage = 30;
5308 } else {
5309 $string = get_string("turneditingon");
5310 $edit = "on";
5313 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
5314 '<div>'.
5315 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5316 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5317 "<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
5318 "<input type=\"hidden\" name=\"page\" value=\"$page\" />".
5319 "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
5320 "<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
5325 * Given a course and a (current) coursemodule
5326 * This function returns a small popup menu with all the
5327 * course activity modules in it, as a navigation menu
5328 * The data is taken from the serialised array stored in
5329 * the course record
5331 * @param course $course A {@link $COURSE} object.
5332 * @param course $cm A {@link $COURSE} object.
5333 * @param string $targetwindow ?
5334 * @return string
5335 * @todo Finish documenting this function
5337 function navmenu($course, $cm=NULL, $targetwindow='self') {
5339 global $CFG, $THEME, $USER;
5341 if (empty($THEME->navmenuwidth)) {
5342 $width = 50;
5343 } else {
5344 $width = $THEME->navmenuwidth;
5347 if ($cm) {
5348 $cm = $cm->id;
5351 if ($course->format == 'weeks') {
5352 $strsection = get_string('week');
5353 } else {
5354 $strsection = get_string('topic');
5356 $strjumpto = get_string('jumpto');
5358 $modinfo = get_fast_modinfo($course);
5359 $context = get_context_instance(CONTEXT_COURSE, $course->id);
5361 $section = -1;
5362 $selected = '';
5363 $url = '';
5364 $previousmod = NULL;
5365 $backmod = NULL;
5366 $nextmod = NULL;
5367 $selectmod = NULL;
5368 $logslink = NULL;
5369 $flag = false;
5370 $menu = array();
5371 $menustyle = array();
5373 $sections = get_records('course_sections','course',$course->id,'section','section,visible,summary');
5375 if (!empty($THEME->makenavmenulist)) { /// A hack to produce an XHTML navmenu list for use in themes
5376 $THEME->navmenulist = navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
5379 foreach ($modinfo->cms as $mod) {
5380 if ($mod->modname == 'label') {
5381 continue;
5384 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
5385 break;
5388 if (!$mod->uservisible) { // do not icnlude empty sections at all
5389 continue;
5392 if ($mod->sectionnum > 0 and $section != $mod->sectionnum) {
5393 $thissection = $sections[$mod->sectionnum];
5395 if ($thissection->visible or !$course->hiddensections or
5396 has_capability('moodle/course:viewhiddensections', $context)) {
5397 $thissection->summary = strip_tags(format_string($thissection->summary,true));
5398 if ($course->format == 'weeks' or empty($thissection->summary)) {
5399 $menu[] = '--'.$strsection ." ". $mod->sectionnum;
5400 } else {
5401 if (strlen($thissection->summary) < ($width-3)) {
5402 $menu[] = '--'.$thissection->summary;
5403 } else {
5404 $menu[] = '--'.substr($thissection->summary, 0, $width).'...';
5407 $section = $mod->sectionnum;
5408 } else {
5409 // no activities from this hidden section shown
5410 continue;
5414 $url = $mod->modname.'/view.php?id='. $mod->id;
5415 if ($flag) { // the current mod is the "next" mod
5416 $nextmod = $mod;
5417 $flag = false;
5419 $localname = $mod->name;
5420 if ($cm == $mod->id) {
5421 $selected = $url;
5422 $selectmod = $mod;
5423 $backmod = $previousmod;
5424 $flag = true; // set flag so we know to use next mod for "next"
5425 $localname = $strjumpto;
5426 $strjumpto = '';
5427 } else {
5428 $localname = strip_tags(format_string($localname,true));
5429 $tl=textlib_get_instance();
5430 if ($tl->strlen($localname) > ($width+5)) {
5431 $localname = $tl->substr($localname, 0, $width).'...';
5433 if (!$mod->visible) {
5434 $localname = '('.$localname.')';
5437 $menu[$url] = $localname;
5438 if (empty($THEME->navmenuiconshide)) {
5439 $menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif);"'; // Unfortunately necessary to do this here
5441 $previousmod = $mod;
5443 //Accessibility: added Alt text, replaced &gt; &lt; with 'silent' character and 'accesshide' text.
5445 if ($selectmod and has_capability('coursereport/log:view', $context)) {
5446 $logstext = get_string('alllogs');
5447 $logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
5448 $CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\';"'.' href="'.
5449 $CFG->wwwroot.'/course/report/log/index.php?chooselog=1&amp;user=0&amp;date=0&amp;id='.
5450 $course->id.'&amp;modid='.$selectmod->id.'">'.
5451 '<img class="icon log" src="'.$CFG->pixpath.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
5454 if ($backmod) {
5455 $backtext= get_string('activityprev', 'access');
5456 $backmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$backmod->modname.'/view.php" '.$CFG->frametarget.' '.
5457 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
5458 '<input type="hidden" name="id" value="'.$backmod->id.'" />'.
5459 '<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
5460 '</button></fieldset></form></li>';
5462 if ($nextmod) {
5463 $nexttext= get_string('activitynext', 'access');
5464 $nextmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$nextmod->modname.'/view.php" '.$CFG->frametarget.' '.
5465 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
5466 '<input type="hidden" name="id" value="'.$nextmod->id.'" />'.
5467 '<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
5468 '</button></fieldset></form></li>';
5471 return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
5472 '<li>'.popup_form($CFG->wwwroot .'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
5473 '', '', true, $targetwindow, '', $menustyle).'</li>'.
5474 $nextmod . '</ul>'."\n".'</div>';
5478 * Given a course
5479 * This function returns a small popup menu with all the
5480 * course activity modules in it, as a navigation menu
5481 * outputs a simple list structure in XHTML
5482 * The data is taken from the serialised array stored in
5483 * the course record
5485 * @param course $course A {@link $COURSE} object.
5486 * @return string
5487 * @todo Finish documenting this function
5489 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
5491 global $CFG;
5493 $section = -1;
5494 $url = '';
5495 $menu = array();
5496 $doneheading = false;
5498 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
5500 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
5501 foreach ($modinfo->cms as $mod) {
5502 if ($mod->modname == 'label') {
5503 continue;
5506 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
5507 break;
5510 if (!$mod->uservisible) { // do not icnlude empty sections at all
5511 continue;
5514 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
5515 $thissection = $sections[$mod->sectionnum];
5517 if ($thissection->visible or !$course->hiddensections or
5518 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
5519 $thissection->summary = strip_tags(format_string($thissection->summary,true));
5520 if (!$doneheading) {
5521 $menu[] = '</ul></li>';
5523 if ($course->format == 'weeks' or empty($thissection->summary)) {
5524 $item = $strsection ." ". $mod->sectionnum;
5525 } else {
5526 if (strlen($thissection->summary) < ($width-3)) {
5527 $item = $thissection->summary;
5528 } else {
5529 $item = substr($thissection->summary, 0, $width).'...';
5532 $menu[] = '<li class="section"><span>'.$item.'</span>';
5533 $menu[] = '<ul>';
5534 $doneheading = true;
5536 $section = $mod->sectionnum;
5537 } else {
5538 // no activities from this hidden section shown
5539 continue;
5543 $url = $mod->modname .'/view.php?id='. $mod->id;
5544 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
5545 if (strlen($mod->name) > ($width+5)) {
5546 $mod->name = substr($mod->name, 0, $width).'...';
5548 if (!$mod->visible) {
5549 $mod->name = '('.$mod->name.')';
5551 $class = 'activity '.$mod->modname;
5552 $class .= ($cmid == $mod->id) ? ' selected' : '';
5553 $menu[] = '<li class="'.$class.'">'.
5554 '<img src="'.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif" alt="" />'.
5555 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
5558 if ($doneheading) {
5559 $menu[] = '</ul></li>';
5561 $menu[] = '</ul></li></ul>';
5563 return implode("\n", $menu);
5567 * Prints form items with the names $day, $month and $year
5569 * @param string $day fieldname
5570 * @param string $month fieldname
5571 * @param string $year fieldname
5572 * @param int $currenttime A default timestamp in GMT
5573 * @param boolean $return
5575 function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
5577 if (!$currenttime) {
5578 $currenttime = time();
5580 $currentdate = usergetdate($currenttime);
5582 for ($i=1; $i<=31; $i++) {
5583 $days[$i] = $i;
5585 for ($i=1; $i<=12; $i++) {
5586 $months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
5588 for ($i=1970; $i<=2020; $i++) {
5589 $years[$i] = $i;
5592 // Build or print result
5593 $result='';
5594 // Note: There should probably be a fieldset around these fields as they are
5595 // clearly grouped. However this causes problems with display. See Mozilla
5596 // bug 474415
5597 $result.='<label class="accesshide" for="menu'.$day.'">'.get_string('day','form').'</label>';
5598 $result.=choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', true);
5599 $result.='<label class="accesshide" for="menu'.$month.'">'.get_string('month','form').'</label>';
5600 $result.=choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', true);
5601 $result.='<label class="accesshide" for="menu'.$year.'">'.get_string('year','form').'</label>';
5602 $result.=choose_from_menu($years, $year, $currentdate['year'], '', '', '0', true);
5604 if ($return) {
5605 return $result;
5606 } else {
5607 echo $result;
5612 *Prints form items with the names $hour and $minute
5614 * @param string $hour fieldname
5615 * @param string ? $minute fieldname
5616 * @param $currenttime A default timestamp in GMT
5617 * @param int $step minute spacing
5618 * @param boolean $return
5620 function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
5622 if (!$currenttime) {
5623 $currenttime = time();
5625 $currentdate = usergetdate($currenttime);
5626 if ($step != 1) {
5627 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
5629 for ($i=0; $i<=23; $i++) {
5630 $hours[$i] = sprintf("%02d",$i);
5632 for ($i=0; $i<=59; $i+=$step) {
5633 $minutes[$i] = sprintf("%02d",$i);
5636 // Build or print result
5637 $result='';
5638 // Note: There should probably be a fieldset around these fields as they are
5639 // clearly grouped. However this causes problems with display. See Mozilla
5640 // bug 474415
5641 $result.='<label class="accesshide" for="menu'.$hour.'">'.get_string('hour','form').'</label>';
5642 $result.=choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',true);
5643 $result.='<label class="accesshide" for="menu'.$minute.'">'.get_string('minute','form').'</label>';
5644 $result.=choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',true);
5646 if ($return) {
5647 return $result;
5648 } else {
5649 echo $result;
5654 * Prints time limit value selector
5656 * @uses $CFG
5657 * @param int $timelimit default
5658 * @param string $unit
5659 * @param string $name
5660 * @param boolean $return
5662 function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
5664 global $CFG;
5666 if ($unit) {
5667 $unit = ' '.$unit;
5670 // Max timelimit is sessiontimeout - 10 minutes.
5671 $maxvalue = ($CFG->sessiontimeout / 60) - 10;
5673 for ($i=1; $i<=$maxvalue; $i++) {
5674 $minutes[$i] = $i.$unit;
5676 return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
5680 * Prints a grade menu (as part of an existing form) with help
5681 * Showing all possible numerical grades and scales
5683 * @uses $CFG
5684 * @param int $courseid ?
5685 * @param string $name ?
5686 * @param string $current ?
5687 * @param boolean $includenograde ?
5688 * @todo Finish documenting this function
5690 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
5692 global $CFG;
5694 $output = '';
5695 $strscale = get_string('scale');
5696 $strscales = get_string('scales');
5698 $scales = get_scales_menu($courseid);
5699 foreach ($scales as $i => $scalename) {
5700 $grades[-$i] = $strscale .': '. $scalename;
5702 if ($includenograde) {
5703 $grades[0] = get_string('nograde');
5705 for ($i=100; $i>=1; $i--) {
5706 $grades[$i] = $i;
5708 $output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
5710 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5711 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5712 $linkobject, 400, 500, $strscales, 'none', true);
5714 if ($return) {
5715 return $output;
5716 } else {
5717 echo $output;
5722 * Prints a scale menu (as part of an existing form) including help button
5723 * Just like {@link print_grade_menu()} but without the numeric grades
5725 * @param int $courseid ?
5726 * @param string $name ?
5727 * @param string $current ?
5728 * @todo Finish documenting this function
5730 function print_scale_menu($courseid, $name, $current, $return=false) {
5732 global $CFG;
5734 $output = '';
5735 $strscales = get_string('scales');
5736 $output .= choose_from_menu(get_scales_menu($courseid), $name, $current, '', '', 0, true);
5738 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5739 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5740 $linkobject, 400, 500, $strscales, 'none', true);
5741 if ($return) {
5742 return $output;
5743 } else {
5744 echo $output;
5749 * Prints a help button about a scale
5751 * @uses $CFG
5752 * @param id $courseid ?
5753 * @param object $scale ?
5754 * @todo Finish documenting this function
5756 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
5758 global $CFG;
5760 $output = '';
5761 $strscales = get_string('scales');
5763 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5764 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true&amp;scaleid='. $scale->id, 'ratingscale',
5765 $linkobject, 400, 500, $scale->name, 'none', true);
5766 if ($return) {
5767 return $output;
5768 } else {
5769 echo $output;
5774 * Print an error page displaying an error message. New method - use this for new code.
5776 * @uses $SESSION
5777 * @uses $CFG
5778 * @param string $errorcode The name of the string from error.php (or other specified file) to print
5779 * @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.
5780 * @param object $a Extra words and phrases that might be required in the error string
5781 * @param array $extralocations An array of strings with other locations to look for string files
5782 * @return does not return, terminates script
5784 function print_error($errorcode, $module='error', $link='', $a=NULL, $extralocations=NULL) {
5785 global $CFG, $SESSION, $THEME;
5787 if (empty($module) || $module === 'moodle' || $module === 'core') {
5788 $module = 'error';
5791 $message = get_string($errorcode, $module, $a, $extralocations);
5792 if ($module === 'error' and strpos($message, '[[') === 0) {
5793 //search in moodle file if error specified - needed for backwards compatibility
5794 $message = get_string($errorcode, 'moodle', $a, $extralocations);
5797 if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
5798 if ( !empty($SESSION->fromurl) ) {
5799 $link = $SESSION->fromurl;
5800 unset($SESSION->fromurl);
5801 } else {
5802 $link = $CFG->wwwroot .'/';
5806 if (!empty($CFG->errordocroot)) {
5807 $errordocroot = $CFG->errordocroot;
5808 } else if (!empty($CFG->docroot)) {
5809 $errordocroot = $CFG->docroot;
5810 } else {
5811 $errordocroot = 'http://docs.moodle.org';
5814 if (defined('FULLME') && FULLME == 'cron') {
5815 // Errors in cron should be mtrace'd.
5816 mtrace($message);
5817 die;
5820 if ($module === 'error') {
5821 $modulelink = 'moodle';
5822 } else {
5823 $modulelink = $module;
5826 $message = clean_text('<p class="errormessage">'.$message.'</p>'.
5827 '<p class="errorcode">'.
5828 '<a href="'.$errordocroot.'/en/error/'.$modulelink.'/'.$errorcode.'">'.
5829 get_string('moreinformation').'</a></p>');
5831 if (! defined('HEADER_PRINTED')) {
5832 //header not yet printed
5833 @header('HTTP/1.0 404 Not Found');
5834 print_header(get_string('error'));
5835 } else {
5836 print_container_end_all(false, $THEME->open_header_containers);
5839 echo '<br />';
5841 print_simple_box($message, '', '', '', '', 'errorbox');
5843 debugging('Stack trace:', DEBUG_DEVELOPER);
5845 // in case we are logging upgrade in admin/index.php stop it
5846 if (function_exists('upgrade_log_finish')) {
5847 upgrade_log_finish();
5850 if (!empty($link)) {
5851 print_continue($link);
5854 print_footer();
5856 for ($i=0;$i<512;$i++) { // Padding to help IE work with 404
5857 echo ' ';
5859 die;
5863 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
5864 * Default errorcode is 1.
5866 * Very useful for perl-like error-handling:
5868 * do_somethting() or mdie("Something went wrong");
5870 * @param string $msg Error message
5871 * @param integer $errorcode Error code to emit
5873 function mdie($msg='', $errorcode=1) {
5874 trigger_error($msg);
5875 exit($errorcode);
5879 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
5880 * Should be used only with htmleditor or textarea.
5881 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
5882 * helpbutton.
5883 * @return string
5885 function editorhelpbutton(){
5886 global $CFG, $SESSION;
5887 $items = func_get_args();
5888 $i = 1;
5889 $urlparams = array();
5890 $titles = array();
5891 foreach ($items as $item){
5892 if (is_array($item)){
5893 $urlparams[] = "keyword$i=".urlencode($item[0]);
5894 $urlparams[] = "title$i=".urlencode($item[1]);
5895 if (isset($item[2])){
5896 $urlparams[] = "module$i=".urlencode($item[2]);
5898 $titles[] = trim($item[1], ". \t");
5899 }elseif (is_string($item)){
5900 $urlparams[] = "button$i=".urlencode($item);
5901 switch ($item){
5902 case 'reading' :
5903 $titles[] = get_string("helpreading");
5904 break;
5905 case 'writing' :
5906 $titles[] = get_string("helpwriting");
5907 break;
5908 case 'questions' :
5909 $titles[] = get_string("helpquestions");
5910 break;
5911 case 'emoticons' :
5912 $titles[] = get_string("helpemoticons");
5913 break;
5914 case 'richtext' :
5915 $titles[] = get_string('helprichtext');
5916 break;
5917 case 'text' :
5918 $titles[] = get_string('helptext');
5919 break;
5920 default :
5921 error('Unknown help topic '.$item);
5924 $i++;
5926 if (count($titles)>1){
5927 //join last two items with an 'and'
5928 $a = new object();
5929 $a->one = $titles[count($titles) - 2];
5930 $a->two = $titles[count($titles) - 1];
5931 $titles[count($titles) - 2] = get_string('and', '', $a);
5932 unset($titles[count($titles) - 1]);
5934 $alttag = join (', ', $titles);
5936 $paramstring = join('&', $urlparams);
5937 $linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath .'/help.gif" />';
5938 return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), 'popup', $linkobject, 400, 500, $alttag, 'none', true);
5942 * Print a help button.
5944 * @uses $CFG
5945 * @param string $page The keyword that defines a help page
5946 * @param string $title The title of links, rollover tips, alt tags etc
5947 * 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
5948 * @param string $module Which module is the page defined in
5949 * @param mixed $image Use a help image for the link? (true/false/"both")
5950 * @param boolean $linktext If true, display the title next to the help icon.
5951 * @param string $text If defined then this text is used in the page, and
5952 * the $page variable is ignored.
5953 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
5954 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
5955 * @return string
5956 * @todo Finish documenting this function
5958 function helpbutton ($page, $title, $module='moodle', $image=true, $linktext=false, $text='', $return=false,
5959 $imagetext='') {
5960 global $CFG, $COURSE;
5962 //warning if ever $text parameter is used
5963 //$text option won't work properly because the text needs to be always cleaned and,
5964 // when cleaned... html tags always break, so it's unusable.
5965 if ( isset($text) && $text!='') {
5966 debugging('Warning: it\'s not recommended to use $text parameter in helpbutton ($page=' . $page . ', $module=' . $module . ') function', DEBUG_DEVELOPER);
5969 // fix for MDL-7734
5970 if (!empty($COURSE->lang)) {
5971 $forcelang = $COURSE->lang;
5972 } else {
5973 $forcelang = '';
5976 if ($module == '') {
5977 $module = 'moodle';
5980 if ($title == '' && $linktext == '') {
5981 debugging('Error in call to helpbutton function: at least one of $title and $linktext is required');
5984 // Warn users about new window for Accessibility
5985 $tooltip = get_string('helpprefix2', '', trim($title, ". \t")) .' ('.get_string('newwindow').')';
5987 $linkobject = '';
5989 if ($image) {
5990 if ($linktext) {
5991 // MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
5992 $linkobject .= $title.'&nbsp;';
5993 $tooltip = get_string('helpwiththis');
5995 if ($imagetext) {
5996 $linkobject .= $imagetext;
5997 } else {
5998 $linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
5999 $CFG->pixpath .'/help.gif" />';
6001 } else {
6002 $linkobject .= $tooltip;
6005 // fix for MDL-7734
6006 if ($text) {
6007 $url = '/help.php?module='. $module .'&amp;text='. s(urlencode($text).'&amp;forcelang='.$forcelang);
6008 } else {
6009 $url = '/help.php?module='. $module .'&amp;file='. $page .'.html&amp;forcelang='.$forcelang;
6012 $link = '<span class="helplink">'.
6013 link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
6014 '</span>';
6016 if ($return) {
6017 return $link;
6018 } else {
6019 echo $link;
6024 * Print a help button.
6026 * Prints a special help button that is a link to the "live" emoticon popup
6027 * @uses $CFG
6028 * @uses $SESSION
6029 * @param string $form ?
6030 * @param string $field ?
6031 * @todo Finish documenting this function
6033 function emoticonhelpbutton($form, $field, $return = false) {
6035 global $CFG, $SESSION;
6037 $SESSION->inserttextform = $form;
6038 $SESSION->inserttextfield = $field;
6039 $imagetext = '<img src="' . $CFG->pixpath . '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
6040 $help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
6041 if (!$return){
6042 echo $help;
6043 } else {
6044 return $help;
6049 * Print a help button.
6051 * Prints a special help button for html editors (htmlarea in this case)
6052 * @uses $CFG
6054 function editorshortcutshelpbutton() {
6056 global $CFG;
6057 $imagetext = '<img src="' . $CFG->httpswwwroot . '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
6058 get_string('editorshortcutkeys').'" class="iconkbhelp" />';
6060 return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
6064 * Print a message and exit.
6066 * @uses $CFG
6067 * @param string $message ?
6068 * @param string $link ?
6069 * @todo Finish documenting this function
6071 function notice ($message, $link='', $course=NULL) {
6072 global $CFG, $SITE, $THEME, $COURSE;
6074 $message = clean_text($message); // In case nasties are in here
6076 if (defined('FULLME') && FULLME == 'cron') {
6077 // notices in cron should be mtrace'd.
6078 mtrace($message);
6079 die;
6082 if (! defined('HEADER_PRINTED')) {
6083 //header not yet printed
6084 print_header(get_string('notice'));
6085 } else {
6086 print_container_end_all(false, $THEME->open_header_containers);
6089 print_box($message, 'generalbox', 'notice');
6090 print_continue($link);
6092 if (empty($course)) {
6093 print_footer($COURSE);
6094 } else {
6095 print_footer($course);
6097 exit;
6101 * Print a message along with "Yes" and "No" links for the user to continue.
6103 * @param string $message The text to display
6104 * @param string $linkyes The link to take the user to if they choose "Yes"
6105 * @param string $linkno The link to take the user to if they choose "No"
6106 * TODO Document remaining arguments
6108 function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
6110 global $CFG;
6112 $message = clean_text($message);
6113 $linkyes = clean_text($linkyes);
6114 $linkno = clean_text($linkno);
6116 print_box_start('generalbox', 'notice');
6117 echo '<p>'. $message .'</p>';
6118 echo '<div class="buttons">';
6119 print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename);
6120 print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename);
6121 echo '</div>';
6122 print_box_end();
6126 * Provide an definition of error_get_last for PHP before 5.2.0. This simply
6127 * returns NULL, since there is not way to get the right answer.
6129 if (!function_exists('error_get_last')) {
6130 // the eval is needed to prevent PHP 5.2+ from getting a parse error!
6131 eval('
6132 function error_get_last() {
6133 return NULL;
6139 * Redirects the user to another page, after printing a notice
6141 * @param string $url The url to take the user to
6142 * @param string $message The text message to display to the user about the redirect, if any
6143 * @param string $delay How long before refreshing to the new page at $url?
6144 * @todo '&' needs to be encoded into '&amp;' for XHTML compliance,
6145 * however, this is not true for javascript. Therefore we
6146 * first decode all entities in $url (since we cannot rely on)
6147 * the correct input) and then encode for where it's needed
6148 * echo "<script type='text/javascript'>alert('Redirect $url');</script>";
6150 function redirect($url, $message='', $delay=-1) {
6152 global $CFG, $THEME;
6154 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
6155 $url = sid_process_url($url);
6158 $message = clean_text($message);
6160 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
6161 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
6162 $url = str_replace('&amp;', '&', $encodedurl);
6164 /// At developer debug level. Don't redirect if errors have been printed on screen.
6165 /// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
6166 $lasterror = error_get_last();
6167 $error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER));
6168 $errorprinted = debugging('', DEBUG_ALL) && $CFG->debugdisplay && $error;
6169 if ($errorprinted) {
6170 $message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
6173 $performanceinfo = '';
6174 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
6175 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
6176 $perf = get_performance_info();
6177 error_log("PERF: " . $perf['txt']);
6181 /// when no message and header printed yet, try to redirect
6182 if (empty($message) and !defined('HEADER_PRINTED')) {
6184 // Technically, HTTP/1.1 requires Location: header to contain
6185 // the absolute path. (In practice browsers accept relative
6186 // paths - but still, might as well do it properly.)
6187 // This code turns relative into absolute.
6188 if (!preg_match('|^[a-z]+:|', $url)) {
6189 // Get host name http://www.wherever.com
6190 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
6191 if (preg_match('|^/|', $url)) {
6192 // URLs beginning with / are relative to web server root so we just add them in
6193 $url = $hostpart.$url;
6194 } else {
6195 // URLs not beginning with / are relative to path of current script, so add that on.
6196 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
6198 // Replace all ..s
6199 while (true) {
6200 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
6201 if ($newurl == $url) {
6202 break;
6204 $url = $newurl;
6208 $delay = 0;
6209 //try header redirection first
6210 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
6211 @header('Location: '.$url);
6212 //another way for older browsers and already sent headers (eg trailing whitespace in config.php)
6213 echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
6214 echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
6215 die;
6218 if ($delay == -1) {
6219 $delay = 3; // if no delay specified wait 3 seconds
6221 if (! defined('HEADER_PRINTED')) {
6222 // this type of redirect might not be working in some browsers - such as lynx :-(
6223 print_header('', '', '', '', $errorprinted ? '' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
6224 $delay += 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
6225 } else {
6226 print_container_end_all(false, $THEME->open_header_containers);
6228 echo '<div id="redirect">';
6229 echo '<div id="message">' . $message . '</div>';
6230 echo '<div id="continue">( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
6231 echo '</div>';
6233 if (!$errorprinted) {
6235 <script type="text/javascript">
6236 //<![CDATA[
6238 function redirect() {
6239 document.location.replace('<?php echo addslashes_js($url) ?>');
6241 setTimeout("redirect()", <?php echo ($delay * 1000) ?>);
6242 //]]>
6243 </script>
6244 <?php
6247 $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
6248 print_footer('none');
6249 die;
6253 * Print a bold message in an optional color.
6255 * @param string $message The message to print out
6256 * @param string $style Optional style to display message text in
6257 * @param string $align Alignment option
6258 * @param bool $return whether to return an output string or echo now
6260 function notify($message, $style='notifyproblem', $align='center', $return=false) {
6261 if ($style == 'green') {
6262 $style = 'notifysuccess'; // backward compatible with old color system
6265 $message = clean_text($message);
6267 $output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."\n";
6269 if ($return) {
6270 return $output;
6272 echo $output;
6277 * Given an email address, this function will return an obfuscated version of it
6279 * @param string $email The email address to obfuscate
6280 * @return string
6282 function obfuscate_email($email) {
6284 $i = 0;
6285 $length = strlen($email);
6286 $obfuscated = '';
6287 while ($i < $length) {
6288 if (rand(0,2) && $email{$i}!='@') { //MDL-20619 some browsers have problems unobfuscating @
6289 $obfuscated.='%'.dechex(ord($email{$i}));
6290 } else {
6291 $obfuscated.=$email{$i};
6293 $i++;
6295 return $obfuscated;
6299 * This function takes some text and replaces about half of the characters
6300 * with HTML entity equivalents. Return string is obviously longer.
6302 * @param string $plaintext The text to be obfuscated
6303 * @return string
6305 function obfuscate_text($plaintext) {
6307 $i=0;
6308 $length = strlen($plaintext);
6309 $obfuscated='';
6310 $prev_obfuscated = false;
6311 while ($i < $length) {
6312 $c = ord($plaintext{$i});
6313 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
6314 if ($prev_obfuscated and $numerical ) {
6315 $obfuscated.='&#'.ord($plaintext{$i}).';';
6316 } else if (rand(0,2)) {
6317 $obfuscated.='&#'.ord($plaintext{$i}).';';
6318 $prev_obfuscated = true;
6319 } else {
6320 $obfuscated.=$plaintext{$i};
6321 $prev_obfuscated = false;
6323 $i++;
6325 return $obfuscated;
6329 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
6330 * to generate a fully obfuscated email link, ready to use.
6332 * @param string $email The email address to display
6333 * @param string $label The text to dispalyed as hyperlink to $email
6334 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
6335 * @return string
6337 function obfuscate_mailto($email, $label='', $dimmed=false) {
6339 if (empty($label)) {
6340 $label = $email;
6342 if ($dimmed) {
6343 $title = get_string('emaildisable');
6344 $dimmed = ' class="dimmed"';
6345 } else {
6346 $title = '';
6347 $dimmed = '';
6349 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
6350 obfuscate_text('mailto'), obfuscate_email($email),
6351 obfuscate_text($label));
6355 * Prints a single paging bar to provide access to other pages (usually in a search)
6357 * @param int $totalcount Thetotal number of entries available to be paged through
6358 * @param int $page The page you are currently viewing
6359 * @param int $perpage The number of entries that should be shown per page
6360 * @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.
6361 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
6362 * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
6363 * @param bool $nocurr do not display the current page as a link
6364 * @param bool $return whether to return an output string or echo now
6365 * @return bool or string
6367 function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
6368 $maxdisplay = 18;
6369 $output = '';
6371 if ($totalcount > $perpage) {
6372 $output .= '<div class="paging">';
6373 $output .= get_string('page') .':';
6374 if ($page > 0) {
6375 $pagenum = $page - 1;
6376 if (!is_a($baseurl, 'moodle_url')){
6377 $output .= '&nbsp;(<a class="previous" href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>)&nbsp;';
6378 } else {
6379 $output .= '&nbsp;(<a class="previous" href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>)&nbsp;';
6382 if ($perpage > 0) {
6383 $lastpage = ceil($totalcount / $perpage);
6384 } else {
6385 $lastpage = 1;
6387 if ($page > 15) {
6388 $startpage = $page - 10;
6389 if (!is_a($baseurl, 'moodle_url')){
6390 $output .= '&nbsp;<a href="'. $baseurl . $pagevar .'=0">1</a>&nbsp;...';
6391 } else {
6392 $output .= '&nbsp;<a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a>&nbsp;...';
6394 } else {
6395 $startpage = 0;
6397 $currpage = $startpage;
6398 $displaycount = $displaypage = 0;
6399 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
6400 $displaypage = $currpage+1;
6401 if ($page == $currpage && empty($nocurr)) {
6402 $output .= '&nbsp;&nbsp;'. $displaypage;
6403 } else {
6404 if (!is_a($baseurl, 'moodle_url')){
6405 $output .= '&nbsp;&nbsp;<a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
6406 } else {
6407 $output .= '&nbsp;&nbsp;<a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
6411 $displaycount++;
6412 $currpage++;
6414 if ($currpage < $lastpage) {
6415 $lastpageactual = $lastpage - 1;
6416 if (!is_a($baseurl, 'moodle_url')){
6417 $output .= '&nbsp;...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a>&nbsp;';
6418 } else {
6419 $output .= '&nbsp;...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a>&nbsp;';
6422 $pagenum = $page + 1;
6423 if ($pagenum != $displaypage) {
6424 if (!is_a($baseurl, 'moodle_url')){
6425 $output .= '&nbsp;&nbsp;(<a class="next" href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
6426 } else {
6427 $output .= '&nbsp;&nbsp;(<a class="next" href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
6430 $output .= '</div>';
6433 if ($return) {
6434 return $output;
6437 echo $output;
6438 return true;
6442 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
6443 * will transform it to html entities
6445 * @param string $text Text to search for nolink tag in
6446 * @return string
6448 function rebuildnolinktag($text) {
6450 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
6452 return $text;
6456 * Prints a nice side block with an optional header. The content can either
6457 * be a block of HTML or a list of text with optional icons.
6459 * @param string $heading Block $title embedded in HTML tags, for example <h2>.
6460 * @param string $content ?
6461 * @param array $list ?
6462 * @param array $icons ?
6463 * @param string $footer ?
6464 * @param array $attributes ?
6465 * @param string $title Plain text title, as embedded in the $heading.
6466 * @todo Finish documenting this function. Show example of various attributes, etc.
6468 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
6470 //Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
6471 static $block_id = 0;
6472 $block_id++;
6473 $skip_text = get_string('skipa', 'access', strip_tags($title));
6474 $skip_link = '<a href="#sb-'.$block_id.'" class="skip-block">'.$skip_text.'</a>';
6475 $skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
6477 $strip_title = strip_tags($title);
6478 if (! empty($strip_title)) {
6479 echo $skip_link;
6481 //ELSE: a single link on a page "Skip block 4" is too confusing - ignore.
6483 print_side_block_start($heading, $attributes);
6485 if ($content) {
6486 echo $content;
6487 if ($footer) {
6488 echo '<div class="footer">'. $footer .'</div>';
6490 } else {
6491 if ($list) {
6492 $row = 0;
6493 //Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
6494 echo "\n<ul class='list'>\n";
6495 foreach ($list as $key => $string) {
6496 echo '<li class="r'. $row .'">';
6497 if ($icons) {
6498 echo '<div class="icon column c0">'. $icons[$key] .'</div>';
6500 echo '<div class="column c1">' . $string . '</div>';
6501 echo "</li>\n";
6502 $row = $row ? 0:1;
6504 echo "</ul>\n";
6506 if ($footer) {
6507 echo '<div class="footer">'. $footer .'</div>';
6512 print_side_block_end($attributes, $title);
6513 echo $skip_dest;
6517 * Starts a nice side block with an optional header.
6519 * @param string $heading ?
6520 * @param array $attributes ?
6521 * @todo Finish documenting this function
6523 function print_side_block_start($heading='', $attributes = array()) {
6525 global $CFG, $THEME;
6527 // If there are no special attributes, give a default CSS class
6528 if (empty($attributes) || !is_array($attributes)) {
6529 $attributes = array('class' => 'sideblock');
6531 } else if(!isset($attributes['class'])) {
6532 $attributes['class'] = 'sideblock';
6534 } else if(!strpos($attributes['class'], 'sideblock')) {
6535 $attributes['class'] .= ' sideblock';
6538 // OK, the class is surely there and in addition to anything
6539 // else, it's tagged as a sideblock
6543 // IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
6545 // If there is a cookie to hide this thing, start it hidden
6546 if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
6547 $attributes['class'] = 'hidden '.$attributes['class'];
6551 $attrtext = '';
6552 foreach ($attributes as $attr => $val) {
6553 $attrtext .= ' '.$attr.'="'.$val.'"';
6556 echo '<div '.$attrtext.'>';
6558 if (!empty($THEME->customcorners)) {
6559 echo '<div class="wrap">'."\n";
6561 if ($heading) {
6562 //Accessibility: H2 more appropriate in moodleblock.class.php: _title_html.
6563 echo '<div class="header">';
6564 if (!empty($THEME->customcorners)) {
6565 echo '<div class="bt"><div>&nbsp;</div></div>';
6566 echo '<div class="i1"><div class="i2">';
6567 echo '<div class="i3">';
6569 echo $heading;
6570 if (!empty($THEME->customcorners)) {
6571 echo '</div></div></div>';
6573 echo '</div>';
6574 } else {
6575 if (!empty($THEME->customcorners)) {
6576 echo '<div class="bt"><div>&nbsp;</div></div>';
6580 if (!empty($THEME->customcorners)) {
6581 echo '<div class="i1"><div class="i2">';
6582 echo '<div class="i3">';
6584 echo '<div class="content">';
6590 * Print table ending tags for a side block box.
6592 function print_side_block_end($attributes = array(), $title='') {
6593 global $CFG, $THEME;
6595 echo '</div>';
6597 if (!empty($THEME->customcorners)) {
6598 echo '</div></div></div><div class="bb"><div>&nbsp;</div></div></div>';
6601 echo '</div>';
6603 $strshow = addslashes_js(get_string('showblocka', 'access', strip_tags($title)));
6604 $strhide = addslashes_js(get_string('hideblocka', 'access', strip_tags($title)));
6606 // IE workaround: if I do it THIS way, it works! WTF?
6607 if (!empty($CFG->allowuserblockhiding) && isset($attributes['id'])) {
6608 echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].
6609 '","'.$strshow.'","'.$strhide."\");\n//]]>\n".'</script>';
6616 * Prints out code needed for spellchecking.
6617 * Original idea by Ludo (Marc Alier).
6619 * Opening CDATA and <script> are output by weblib::use_html_editor()
6620 * @uses $CFG
6621 * @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
6622 * @param boolean $return If false, echos the code instead of returning it
6623 * @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
6625 function print_speller_code ($usehtmleditor=false, $return=false) {
6626 global $CFG;
6627 $str = '';
6629 if(!$usehtmleditor) {
6630 $str .= 'function openSpellChecker() {'."\n";
6631 $str .= "\tvar speller = new spellChecker();\n";
6632 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot ."/lib/speller/spellchecker.html\";\n";
6633 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
6634 $str .= "\tspeller.spellCheckAll();\n";
6635 $str .= '}'."\n";
6636 } else {
6637 $str .= "function spellClickHandler(editor, buttonId) {\n";
6638 $str .= "\teditor._textArea.value = editor.getHTML();\n";
6639 $str .= "\tvar speller = new spellChecker( editor._textArea );\n";
6640 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot ."/lib/speller/spellchecker.html\";\n";
6641 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
6642 $str .= "\tspeller._moogle_edit=1;\n";
6643 $str .= "\tspeller._editor=editor;\n";
6644 $str .= "\tspeller.openChecker();\n";
6645 $str .= '}'."\n";
6648 if ($return) {
6649 return $str;
6651 echo $str;
6655 * Print button for spellchecking when editor is disabled
6657 function print_speller_button () {
6658 echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
6662 function page_id_and_class(&$getid, &$getclass) {
6663 // Create class and id for this page
6664 global $CFG, $ME;
6666 static $class = NULL;
6667 static $id = NULL;
6669 if (empty($CFG->pagepath)) {
6670 $CFG->pagepath = $ME;
6673 if (empty($class) || empty($id)) {
6674 $path = str_replace($CFG->httpswwwroot.'/', '', $CFG->pagepath); //Because the page could be HTTPSPAGEREQUIRED
6675 $path = str_replace('.php', '', $path);
6676 if (substr($path, -1) == '/') {
6677 $path .= 'index';
6679 if (empty($path) || $path == 'index') {
6680 $id = 'site-index';
6681 $class = 'course';
6682 } else if (substr($path, 0, 5) == 'admin') {
6683 $id = str_replace('/', '-', $path);
6684 $class = 'admin';
6685 } else {
6686 $id = str_replace('/', '-', $path);
6687 $class = explode('-', $id);
6688 array_pop($class);
6689 $class = implode('-', $class);
6693 $getid = $id;
6694 $getclass = $class;
6698 * Prints a maintenance message from /maintenance.html
6700 function print_maintenance_message () {
6701 global $CFG, $SITE;
6703 $CFG->pagepath = "index.php";
6704 print_header(strip_tags($SITE->fullname), $SITE->fullname, 'home');
6705 print_box_start();
6706 print_heading(get_string('sitemaintenance', 'admin'));
6707 @include($CFG->dataroot.'/'.SITEID.'/maintenance.html');
6708 print_box_end();
6709 print_footer();
6713 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
6715 function adjust_allowed_tags() {
6717 global $CFG, $ALLOWED_TAGS;
6719 if (!empty($CFG->allowobjectembed)) {
6720 $ALLOWED_TAGS .= '<embed><object>';
6724 /// Some code to print tabs
6726 /// A class for tabs
6727 class tabobject {
6728 var $id;
6729 var $link;
6730 var $text;
6731 var $linkedwhenselected;
6733 /// A constructor just because I like constructors
6734 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
6735 $this->id = $id;
6736 $this->link = $link;
6737 $this->text = $text;
6738 $this->title = $title ? $title : $text;
6739 $this->linkedwhenselected = $linkedwhenselected;
6746 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
6748 * @param array $tabrows An array of rows where each row is an array of tab objects
6749 * @param string $selected The id of the selected tab (whatever row it's on)
6750 * @param array $inactive An array of ids of inactive tabs that are not selectable.
6751 * @param array $activated An array of ids of other tabs that are currently activated
6753 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
6754 global $CFG;
6756 /// $inactive must be an array
6757 if (!is_array($inactive)) {
6758 $inactive = array();
6761 /// $activated must be an array
6762 if (!is_array($activated)) {
6763 $activated = array();
6766 /// Convert the tab rows into a tree that's easier to process
6767 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
6768 return false;
6771 /// Print out the current tree of tabs (this function is recursive)
6773 $output = convert_tree_to_html($tree);
6775 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
6777 /// We're done!
6779 if ($return) {
6780 return $output;
6782 echo $output;
6786 function convert_tree_to_html($tree, $row=0) {
6788 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
6790 $first = true;
6791 $count = count($tree);
6793 foreach ($tree as $tab) {
6794 $count--; // countdown to zero
6796 $liclass = '';
6798 if ($first && ($count == 0)) { // Just one in the row
6799 $liclass = 'first last';
6800 $first = false;
6801 } else if ($first) {
6802 $liclass = 'first';
6803 $first = false;
6804 } else if ($count == 0) {
6805 $liclass = 'last';
6808 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
6809 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
6812 if ($tab->inactive || $tab->active || $tab->selected) {
6813 if ($tab->selected) {
6814 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
6815 } else if ($tab->active) {
6816 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
6820 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
6822 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
6823 // The a tag is used for styling
6824 $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
6825 } else {
6826 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
6829 if (!empty($tab->subtree)) {
6830 $str .= convert_tree_to_html($tab->subtree, $row+1);
6831 } else if ($tab->selected) {
6832 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
6835 $str .= ' </li>'."\n";
6837 $str .= '</ul>'."\n";
6839 return $str;
6843 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
6845 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
6847 $tabrows = array_reverse($tabrows);
6849 $subtree = array();
6851 foreach ($tabrows as $row) {
6852 $tree = array();
6854 foreach ($row as $tab) {
6855 $tab->inactive = in_array((string)$tab->id, $inactive);
6856 $tab->active = in_array((string)$tab->id, $activated);
6857 $tab->selected = (string)$tab->id == $selected;
6859 if ($tab->active || $tab->selected) {
6860 if ($subtree) {
6861 $tab->subtree = $subtree;
6864 $tree[] = $tab;
6866 $subtree = $tree;
6869 return $subtree;
6874 * Returns a string containing a link to the user documentation for the current
6875 * page. Also contains an icon by default. Shown to teachers and admin only.
6877 * @param string $text The text to be displayed for the link
6878 * @param string $iconpath The path to the icon to be displayed
6880 function page_doc_link($text='', $iconpath='') {
6881 global $ME, $COURSE, $CFG;
6883 if (empty($CFG->docroot) or empty($CFG->rolesactive)) {
6884 return '';
6887 if (empty($COURSE->id)) {
6888 $context = get_context_instance(CONTEXT_SYSTEM);
6889 } else {
6890 $context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
6893 if (!has_capability('moodle/site:doclinks', $context)) {
6894 return '';
6897 if (empty($CFG->pagepath)) {
6898 $CFG->pagepath = $ME;
6901 $path = str_replace($CFG->httpswwwroot.'/','', $CFG->pagepath); // Because the page could be HTTPSPAGEREQUIRED
6902 $path = str_replace('.php', '', $path);
6904 if (empty($path)) { // Not for home page
6905 return '';
6907 return doc_link($path, $text, $iconpath);
6911 * Returns a string containing a link to the user documentation.
6912 * Also contains an icon by default. Shown to teachers and admin only.
6914 * @param string $path The page link after doc root and language, no
6915 * leading slash.
6916 * @param string $text The text to be displayed for the link
6917 * @param string $iconpath The path to the icon to be displayed
6919 function doc_link($path='', $text='', $iconpath='') {
6920 global $CFG;
6922 if (empty($CFG->docroot)) {
6923 return '';
6926 $target = '';
6927 if (!empty($CFG->doctonewwindow)) {
6928 $target = ' target="_blank"';
6931 $lang = str_replace('_utf8', '', current_language());
6933 $str = '<a href="' .$CFG->docroot. '/' .$lang. '/' .$path. '"' .$target. '>';
6935 if (empty($iconpath)) {
6936 $iconpath = $CFG->httpswwwroot . '/pix/docs.gif';
6939 // alt left blank intentionally to prevent repetition in screenreaders
6940 $str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
6942 return $str;
6947 * Returns true if the current site debugging settings are equal or above specified level.
6948 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
6949 * routing of notices is controlled by $CFG->debugdisplay
6950 * eg use like this:
6952 * 1) debugging('a normal debug notice');
6953 * 2) debugging('something really picky', DEBUG_ALL);
6954 * 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
6955 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
6957 * In code blocks controlled by debugging() (such as example 4)
6958 * any output should be routed via debugging() itself, or the lower-level
6959 * trigger_error() or error_log(). Using echo or print will break XHTML
6960 * JS and HTTP headers.
6963 * @param string $message a message to print
6964 * @param int $level the level at which this debugging statement should show
6965 * @return bool
6967 function debugging($message='', $level=DEBUG_NORMAL) {
6969 global $CFG;
6971 if (empty($CFG->debug)) {
6972 return false;
6975 if ($CFG->debug >= $level) {
6976 if ($message) {
6977 $callers = debug_backtrace();
6978 $from = '<ul style="text-align: left">';
6979 foreach ($callers as $caller) {
6980 if (!isset($caller['line'])) {
6981 $caller['line'] = '?'; // probably call_user_func()
6983 if (!isset($caller['file'])) {
6984 $caller['file'] = $CFG->dirroot.'/unknownfile'; // probably call_user_func()
6986 $from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
6987 if (isset($caller['function'])) {
6988 $from .= ': call to ';
6989 if (isset($caller['class'])) {
6990 $from .= $caller['class'] . $caller['type'];
6992 $from .= $caller['function'] . '()';
6994 $from .= '</li>';
6996 $from .= '</ul>';
6997 if (!isset($CFG->debugdisplay)) {
6998 $CFG->debugdisplay = ini_get_bool('display_errors');
7000 if ($CFG->debugdisplay) {
7001 if (!defined('DEBUGGING_PRINTED')) {
7002 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
7004 notify($message . $from, 'notifytiny');
7005 } else {
7006 trigger_error($message . $from, E_USER_NOTICE);
7009 return true;
7011 return false;
7015 * Disable debug messages from debugging(), while keeping PHP error reporting level as is.
7017 function disable_debugging() {
7018 global $CFG;
7019 $CFG->debug = $CFG->debug | 0x80000000; // switch the sign bit in integer number ;-)
7024 * Returns string to add a frame attribute, if required
7026 function frametarget() {
7027 global $CFG;
7029 if (empty($CFG->framename) or ($CFG->framename == '_top')) {
7030 return '';
7031 } else {
7032 return ' target="'.$CFG->framename.'" ';
7037 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
7038 * pages that use bits from many different files in very confusing ways (e.g. blocks).
7039 * @usage print_location_comment(__FILE__, __LINE__);
7040 * @param string $file
7041 * @param integer $line
7042 * @param boolean $return Whether to return or print the comment
7043 * @return mixed Void unless true given as third parameter
7045 function print_location_comment($file, $line, $return = false)
7047 if ($return) {
7048 return "<!-- $file at line $line -->\n";
7049 } else {
7050 echo "<!-- $file at line $line -->\n";
7056 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
7057 * provide this function with the language strings for sortasc and sortdesc.
7058 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
7059 * @param string $direction 'up' or 'down'
7060 * @param string $strsort The language string used for the alt attribute of this image
7061 * @param bool $return Whether to print directly or return the html string
7062 * @return string HTML for the image
7064 * TODO See if this isn't already defined somewhere. If not, move this to weblib
7066 function print_arrow($direction='up', $strsort=null, $return=false) {
7067 global $CFG;
7069 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
7070 return null;
7073 $return = null;
7075 switch ($direction) {
7076 case 'up':
7077 $sortdir = 'asc';
7078 break;
7079 case 'down':
7080 $sortdir = 'desc';
7081 break;
7082 case 'move':
7083 $sortdir = 'asc';
7084 break;
7085 default:
7086 $sortdir = null;
7087 break;
7090 // Prepare language string
7091 $strsort = '';
7092 if (empty($strsort) && !empty($sortdir)) {
7093 $strsort = get_string('sort' . $sortdir, 'grades');
7096 $return = ' <img src="'.$CFG->pixpath.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
7098 if ($return) {
7099 return $return;
7100 } else {
7101 echo $return;
7106 * Returns boolean true if the current language is right-to-left (Hebrew, Arabic etc)
7109 function right_to_left() {
7110 static $result;
7112 if (isset($result)) {
7113 return $result;
7115 return $result = (get_string('thisdirection') == 'rtl');
7120 * Returns swapped left<=>right if in RTL environment.
7121 * part of RTL support
7123 * @param string $align align to check
7124 * @return string
7126 function fix_align_rtl($align) {
7127 if (!right_to_left()) {
7128 return $align;
7130 if ($align=='left') { return 'right'; }
7131 if ($align=='right') { return 'left'; }
7132 return $align;
7137 * Returns true if the page is displayed in a popup window.
7138 * Gets the information from the URL parameter inpopup.
7140 * @return boolean
7142 * TODO Use a central function to create the popup calls allover Moodle and
7143 * TODO In the moment only works with resources and probably questions.
7145 function is_in_popup() {
7146 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
7148 return ($inpopup);
7152 * Return the authentication plugin title
7153 * @param string $authtype plugin type
7154 * @return string
7156 function auth_get_plugin_title ($authtype) {
7157 $authtitle = get_string("auth_{$authtype}title", "auth");
7158 if ($authtitle == "[[auth_{$authtype}title]]") {
7159 $authtitle = get_string("auth_{$authtype}title", "auth_{$authtype}");
7161 return $authtitle;
7165 * Returns a localized sentence in the current language summarizing the current password policy
7167 * @uses $CFG
7168 * @return string
7170 function print_password_policy() {
7171 global $CFG;
7173 $message = '';
7174 if (!empty($CFG->passwordpolicy)) {
7175 $messages = array();
7176 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
7177 if (!empty($CFG->minpassworddigits)) {
7178 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
7180 if (!empty($CFG->minpasswordlower)) {
7181 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
7183 if (!empty($CFG->minpasswordupper)) {
7184 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
7186 if (!empty($CFG->minpasswordnonalphanum)) {
7187 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
7190 $messages = join(', ', $messages); // this is ugly but we do not have anything better yet...
7191 $message = get_string('informpasswordpolicy', 'auth', $messages);
7193 return $message;
7196 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: