MDL-31642 added 'max attachments' to filemanager and 'drag and drop' message inside...
[moodle.git] / lib / outputrenderers.php
blob6e311be07f0a925b2c519d084e1bf90197a7c0f4
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
21 * for an overview.
23 * Included in this file are the primary renderer classes:
24 * - renderer_base: The renderer outline class that all renderers
25 * should inherit from.
26 * - core_renderer: The standard HTML renderer.
27 * - core_renderer_cli: An adaption of the standard renderer for CLI scripts.
28 * - core_renderer_ajax: An adaption of the standard renderer for AJAX scripts.
29 * - plugin_renderer_base: A renderer class that should be extended by all
30 * plugin renderers.
32 * @package core
33 * @category output
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') || die();
40 /**
41 * Simple base class for Moodle renderers.
43 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
45 * Also has methods to facilitate generating HTML output.
47 * @copyright 2009 Tim Hunt
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 * @since Moodle 2.0
50 * @package core
51 * @category output
53 class renderer_base {
54 /**
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
59 /**
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
62 protected $page;
64 /**
65 * @var string The requested rendering target.
67 protected $target;
69 /**
70 * Constructor
72 * The constructor takes two arguments. The first is the page that the renderer
73 * has been created to assist with, and the second is the target.
74 * The target is an additional identifier that can be used to load different
75 * renderers for different options.
77 * @param moodle_page $page the page we are doing output for.
78 * @param string $target one of rendering target constants
80 public function __construct(moodle_page $page, $target) {
81 $this->opencontainers = $page->opencontainers;
82 $this->page = $page;
83 $this->target = $target;
86 /**
87 * Returns rendered widget.
89 * The provided widget needs to be an object that extends the renderable
90 * interface.
91 * If will then be rendered by a method based upon the classname for the widget.
92 * For instance a widget of class `crazywidget` will be rendered by a protected
93 * render_crazywidget method of this renderer.
95 * @param renderable $widget instance with renderable interface
96 * @return string
98 public function render(renderable $widget) {
99 $rendermethod = 'render_'.get_class($widget);
100 if (method_exists($this, $rendermethod)) {
101 return $this->$rendermethod($widget);
103 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
107 * Adds a JS action for the element with the provided id.
109 * This method adds a JS event for the provided component action to the page
110 * and then returns the id that the event has been attached to.
111 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
113 * @param component_action $action
114 * @param string $id
115 * @return string id of element, either original submitted or random new if not supplied
117 public function add_action_handler(component_action $action, $id = null) {
118 if (!$id) {
119 $id = html_writer::random_id($action->event);
121 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
122 return $id;
126 * Returns true is output has already started, and false if not.
128 * @return boolean true if the header has been printed.
130 public function has_started() {
131 return $this->page->state >= moodle_page::STATE_IN_BODY;
135 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
137 * @param mixed $classes Space-separated string or array of classes
138 * @return string HTML class attribute value
140 public static function prepare_classes($classes) {
141 if (is_array($classes)) {
142 return implode(' ', array_unique($classes));
144 return $classes;
148 * Return the moodle_url for an image.
150 * The exact image location and extension is determined
151 * automatically by searching for gif|png|jpg|jpeg, please
152 * note there can not be diferent images with the different
153 * extension. The imagename is for historical reasons
154 * a relative path name, it may be changed later for core
155 * images. It is recommended to not use subdirectories
156 * in plugin and theme pix directories.
158 * There are three types of images:
159 * 1/ theme images - stored in theme/mytheme/pix/,
160 * use component 'theme'
161 * 2/ core images - stored in /pix/,
162 * overridden via theme/mytheme/pix_core/
163 * 3/ plugin images - stored in mod/mymodule/pix,
164 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
165 * example: pix_url('comment', 'mod_glossary')
167 * @param string $imagename the pathname of the image
168 * @param string $component full plugin name (aka component) or 'theme'
169 * @return moodle_url
171 public function pix_url($imagename, $component = 'moodle') {
172 return $this->page->theme->pix_url($imagename, $component);
178 * Basis for all plugin renderers.
180 * @copyright Petr Skoda (skodak)
181 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
182 * @since Moodle 2.0
183 * @package core
184 * @category output
186 class plugin_renderer_base extends renderer_base {
189 * @var renderer_base|core_renderer A reference to the current renderer.
190 * The renderer provided here will be determined by the page but will in 90%
191 * of cases by the {@link core_renderer}
193 protected $output;
196 * Constructor method, calls the parent constructor
198 * @param moodle_page $page
199 * @param string $target one of rendering target constants
201 public function __construct(moodle_page $page, $target) {
202 $this->output = $page->get_renderer('core', null, $target);
203 parent::__construct($page, $target);
207 * Renders the provided widget and returns the HTML to display it.
209 * @param renderable $widget instance with renderable interface
210 * @return string
212 public function render(renderable $widget) {
213 $rendermethod = 'render_'.get_class($widget);
214 if (method_exists($this, $rendermethod)) {
215 return $this->$rendermethod($widget);
217 // pass to core renderer if method not found here
218 return $this->output->render($widget);
222 * Magic method used to pass calls otherwise meant for the standard renderer
223 * to it to ensure we don't go causing unnecessary grief.
225 * @param string $method
226 * @param array $arguments
227 * @return mixed
229 public function __call($method, $arguments) {
230 if (method_exists('renderer_base', $method)) {
231 throw new coding_exception('Protected method called against '.__CLASS__.' :: '.$method);
233 if (method_exists($this->output, $method)) {
234 return call_user_func_array(array($this->output, $method), $arguments);
235 } else {
236 throw new coding_exception('Unknown method called against '.__CLASS__.' :: '.$method);
243 * The standard implementation of the core_renderer interface.
245 * @copyright 2009 Tim Hunt
246 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
247 * @since Moodle 2.0
248 * @package core
249 * @category output
251 class core_renderer extends renderer_base {
253 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
254 * in layout files instead.
255 * @deprecated
256 * @var string used in {@link core_renderer::header()}.
258 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
261 * @var string Used to pass information from {@link core_renderer::doctype()} to
262 * {@link core_renderer::standard_head_html()}.
264 protected $contenttype;
267 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
268 * with {@link core_renderer::header()}.
270 protected $metarefreshtag = '';
273 * @var string Unique token for the closing HTML
275 protected $unique_end_html_token;
278 * @var string Unique token for performance information
280 protected $unique_performance_info_token;
283 * @var string Unique token for the main content.
285 protected $unique_main_content_token;
288 * Constructor
290 * @param moodle_page $page the page we are doing output for.
291 * @param string $target one of rendering target constants
293 public function __construct(moodle_page $page, $target) {
294 $this->opencontainers = $page->opencontainers;
295 $this->page = $page;
296 $this->target = $target;
298 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
299 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
300 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
304 * Get the DOCTYPE declaration that should be used with this page. Designed to
305 * be called in theme layout.php files.
307 * @return string the DOCTYPE declaration (and any XML prologue) that should be used.
309 public function doctype() {
310 global $CFG;
312 $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n";
313 $this->contenttype = 'text/html; charset=utf-8';
315 if (empty($CFG->xmlstrictheaders)) {
316 return $doctype;
319 // We want to serve the page with an XML content type, to force well-formedness errors to be reported.
320 $prolog = '<?xml version="1.0" encoding="utf-8"?>' . "\n";
321 if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml') !== false) {
322 // Firefox and other browsers that can cope natively with XHTML.
323 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
325 } else if (preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
326 // IE can't cope with application/xhtml+xml, but it will cope if we send application/xml with an XSL stylesheet.
327 $this->contenttype = 'application/xml; charset=utf-8';
328 $prolog .= '<?xml-stylesheet type="text/xsl" href="' . $CFG->httpswwwroot . '/lib/xhtml.xsl"?>' . "\n";
330 } else {
331 $prolog = '';
334 return $prolog . $doctype;
338 * The attributes that should be added to the <html> tag. Designed to
339 * be called in theme layout.php files.
341 * @return string HTML fragment.
343 public function htmlattributes() {
344 return get_html_lang(true) . ' xmlns="http://www.w3.org/1999/xhtml"';
348 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
349 * that should be included in the <head> tag. Designed to be called in theme
350 * layout.php files.
352 * @return string HTML fragment.
354 public function standard_head_html() {
355 global $CFG, $SESSION;
356 $output = '';
357 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
358 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
359 if (!$this->page->cacheable) {
360 $output .= '<meta http-equiv="pragma" content="no-cache" />' . "\n";
361 $output .= '<meta http-equiv="expires" content="0" />' . "\n";
363 // This is only set by the {@link redirect()} method
364 $output .= $this->metarefreshtag;
366 // Check if a periodic refresh delay has been set and make sure we arn't
367 // already meta refreshing
368 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
369 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
372 // flow player embedding support
373 $this->page->requires->js_function_call('M.util.load_flowplayer');
375 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
377 $focus = $this->page->focuscontrol;
378 if (!empty($focus)) {
379 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
380 // This is a horrifically bad way to handle focus but it is passed in
381 // through messy formslib::moodleform
382 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
383 } else if (strpos($focus, '.')!==false) {
384 // Old style of focus, bad way to do it
385 debugging('This code is using the old style focus event, Please update this code to focus on an element id or the moodleform focus method.', DEBUG_DEVELOPER);
386 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
387 } else {
388 // Focus element with given id
389 $this->page->requires->js_function_call('focuscontrol', array($focus));
393 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
394 // any other custom CSS can not be overridden via themes and is highly discouraged
395 $urls = $this->page->theme->css_urls($this->page);
396 foreach ($urls as $url) {
397 $this->page->requires->css_theme($url);
400 // Get the theme javascript head and footer
401 $jsurl = $this->page->theme->javascript_url(true);
402 $this->page->requires->js($jsurl, true);
403 $jsurl = $this->page->theme->javascript_url(false);
404 $this->page->requires->js($jsurl);
406 // Get any HTML from the page_requirements_manager.
407 $output .= $this->page->requires->get_head_code($this->page, $this);
409 // List alternate versions.
410 foreach ($this->page->alternateversions as $type => $alt) {
411 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
412 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
415 if (!empty($CFG->additionalhtmlhead)) {
416 $output .= "\n".$CFG->additionalhtmlhead;
419 return $output;
423 * The standard tags (typically skip links) that should be output just inside
424 * the start of the <body> tag. Designed to be called in theme layout.php files.
426 * @return string HTML fragment.
428 public function standard_top_of_body_html() {
429 global $CFG;
430 $output = $this->page->requires->get_top_of_body_code();
431 if (!empty($CFG->additionalhtmltopofbody)) {
432 $output .= "\n".$CFG->additionalhtmltopofbody;
434 return $output;
438 * The standard tags (typically performance information and validation links,
439 * if we are in developer debug mode) that should be output in the footer area
440 * of the page. Designed to be called in theme layout.php files.
442 * @return string HTML fragment.
444 public function standard_footer_html() {
445 global $CFG, $SCRIPT;
447 // This function is normally called from a layout.php file in {@link core_renderer::header()}
448 // but some of the content won't be known until later, so we return a placeholder
449 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
450 $output = $this->unique_performance_info_token;
451 if ($this->page->devicetypeinuse == 'legacy') {
452 // The legacy theme is in use print the notification
453 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
456 // Get links to switch device types (only shown for users not on a default device)
457 $output .= $this->theme_switch_links();
459 if (!empty($CFG->debugpageinfo)) {
460 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
462 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { // Only in developer mode
463 // Add link to profiling report if necessary
464 if (function_exists('profiling_is_running') && profiling_is_running()) {
465 $txt = get_string('profiledscript', 'admin');
466 $title = get_string('profiledscriptview', 'admin');
467 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
468 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
469 $output .= '<div class="profilingfooter">' . $link . '</div>';
471 $output .= '<div class="purgecaches"><a href="'.$CFG->wwwroot.'/admin/purgecaches.php?confirm=1&amp;sesskey='.sesskey().'">'.get_string('purgecaches', 'admin').'</a></div>';
473 if (!empty($CFG->debugvalidators)) {
474 $output .= '<div class="validators"><ul>
475 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
476 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
477 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&amp;warnp2n3e=1&amp;url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
478 </ul></div>';
480 if (!empty($CFG->additionalhtmlfooter)) {
481 $output .= "\n".$CFG->additionalhtmlfooter;
483 return $output;
487 * Returns standard main content placeholder.
488 * Designed to be called in theme layout.php files.
490 * @return string HTML fragment.
492 public function main_content() {
493 return $this->unique_main_content_token;
497 * The standard tags (typically script tags that are not needed earlier) that
498 * should be output after everything else, . Designed to be called in theme layout.php files.
500 * @return string HTML fragment.
502 public function standard_end_of_body_html() {
503 // This function is normally called from a layout.php file in {@link core_renderer::header()}
504 // but some of the content won't be known until later, so we return a placeholder
505 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
506 return $this->unique_end_html_token;
510 * Return the standard string that says whether you are logged in (and switched
511 * roles/logged in as another user).
513 * @return string HTML fragment.
515 public function login_info() {
516 global $USER, $CFG, $DB, $SESSION;
518 if (during_initial_install()) {
519 return '';
522 $loginapge = ((string)$this->page->url === get_login_url());
523 $course = $this->page->course;
525 if (session_is_loggedinas()) {
526 $realuser = session_get_realuser();
527 $fullname = fullname($realuser, true);
528 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\">$fullname</a>] ";
529 } else {
530 $realuserinfo = '';
533 $loginurl = get_login_url();
535 if (empty($course->id)) {
536 // $course->id is not defined during installation
537 return '';
538 } else if (isloggedin()) {
539 $context = get_context_instance(CONTEXT_COURSE, $course->id);
541 $fullname = fullname($USER, true);
542 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
543 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\">$fullname</a>";
544 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
545 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
547 if (isguestuser()) {
548 $loggedinas = $realuserinfo.get_string('loggedinasguest');
549 if (!$loginapge) {
550 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
552 } else if (is_role_switched($course->id)) { // Has switched roles
553 $rolename = '';
554 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
555 $rolename = ': '.format_string($role->name);
557 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
558 " (<a href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
559 } else {
560 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
561 " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
563 } else {
564 $loggedinas = get_string('loggedinnot', 'moodle');
565 if (!$loginapge) {
566 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
570 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
572 if (isset($SESSION->justloggedin)) {
573 unset($SESSION->justloggedin);
574 if (!empty($CFG->displayloginfailures)) {
575 if (!isguestuser()) {
576 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
577 $loggedinas .= '&nbsp;<div class="loginfailures">';
578 if (empty($count->accounts)) {
579 $loggedinas .= get_string('failedloginattempts', '', $count);
580 } else {
581 $loggedinas .= get_string('failedloginattemptsall', '', $count);
583 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', get_context_instance(CONTEXT_SYSTEM))) {
584 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/report/log/index.php'.
585 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
587 $loggedinas .= '</div>';
593 return $loggedinas;
597 * Return the 'back' link that normally appears in the footer.
599 * @return string HTML fragment.
601 public function home_link() {
602 global $CFG, $SITE;
604 if ($this->page->pagetype == 'site-index') {
605 // Special case for site home page - please do not remove
606 return '<div class="sitelink">' .
607 '<a title="Moodle" href="http://moodle.org/">' .
608 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
610 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
611 // Special case for during install/upgrade.
612 return '<div class="sitelink">'.
613 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
614 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
616 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
617 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
618 get_string('home') . '</a></div>';
620 } else {
621 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
622 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
627 * Redirects the user by any means possible given the current state
629 * This function should not be called directly, it should always be called using
630 * the redirect function in lib/weblib.php
632 * The redirect function should really only be called before page output has started
633 * however it will allow itself to be called during the state STATE_IN_BODY
635 * @param string $encodedurl The URL to send to encoded if required
636 * @param string $message The message to display to the user if any
637 * @param int $delay The delay before redirecting a user, if $message has been
638 * set this is a requirement and defaults to 3, set to 0 no delay
639 * @param boolean $debugdisableredirect this redirect has been disabled for
640 * debugging purposes. Display a message that explains, and don't
641 * trigger the redirect.
642 * @return string The HTML to display to the user before dying, may contain
643 * meta refresh, javascript refresh, and may have set header redirects
645 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
646 global $CFG;
647 $url = str_replace('&amp;', '&', $encodedurl);
649 switch ($this->page->state) {
650 case moodle_page::STATE_BEFORE_HEADER :
651 // No output yet it is safe to delivery the full arsenal of redirect methods
652 if (!$debugdisableredirect) {
653 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
654 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
655 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
657 $output = $this->header();
658 break;
659 case moodle_page::STATE_PRINTING_HEADER :
660 // We should hopefully never get here
661 throw new coding_exception('You cannot redirect while printing the page header');
662 break;
663 case moodle_page::STATE_IN_BODY :
664 // We really shouldn't be here but we can deal with this
665 debugging("You should really redirect before you start page output");
666 if (!$debugdisableredirect) {
667 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
669 $output = $this->opencontainers->pop_all_but_last();
670 break;
671 case moodle_page::STATE_DONE :
672 // Too late to be calling redirect now
673 throw new coding_exception('You cannot redirect after the entire page has been generated');
674 break;
676 $output .= $this->notification($message, 'redirectmessage');
677 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
678 if ($debugdisableredirect) {
679 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
681 $output .= $this->footer();
682 return $output;
686 * Start output by sending the HTTP headers, and printing the HTML <head>
687 * and the start of the <body>.
689 * To control what is printed, you should set properties on $PAGE. If you
690 * are familiar with the old {@link print_header()} function from Moodle 1.9
691 * you will find that there are properties on $PAGE that correspond to most
692 * of the old parameters to could be passed to print_header.
694 * Not that, in due course, the remaining $navigation, $menu parameters here
695 * will be replaced by more properties of $PAGE, but that is still to do.
697 * @return string HTML that you must output this, preferably immediately.
699 public function header() {
700 global $USER, $CFG;
702 if (session_is_loggedinas()) {
703 $this->page->add_body_class('userloggedinas');
706 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
708 // Find the appropriate page layout file, based on $this->page->pagelayout.
709 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
710 // Render the layout using the layout file.
711 $rendered = $this->render_page_layout($layoutfile);
713 // Slice the rendered output into header and footer.
714 $cutpos = strpos($rendered, $this->unique_main_content_token);
715 if ($cutpos === false) {
716 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
717 $token = self::MAIN_CONTENT_TOKEN;
718 } else {
719 $token = $this->unique_main_content_token;
722 if ($cutpos === false) {
723 throw new coding_exception('page layout file ' . $layoutfile . ' does not contain the main content placeholder, please include "<?php echo $OUTPUT->main_content() ?>" in theme layout file.');
725 $header = substr($rendered, 0, $cutpos);
726 $footer = substr($rendered, $cutpos + strlen($token));
728 if (empty($this->contenttype)) {
729 debugging('The page layout file did not call $OUTPUT->doctype()');
730 $header = $this->doctype() . $header;
733 send_headers($this->contenttype, $this->page->cacheable);
735 $this->opencontainers->push('header/footer', $footer);
736 $this->page->set_state(moodle_page::STATE_IN_BODY);
738 return $header . $this->skip_link_target('maincontent');
742 * Renders and outputs the page layout file.
744 * This is done by preparing the normal globals available to a script, and
745 * then including the layout file provided by the current theme for the
746 * requested layout.
748 * @param string $layoutfile The name of the layout file
749 * @return string HTML code
751 protected function render_page_layout($layoutfile) {
752 global $CFG, $SITE, $USER;
753 // The next lines are a bit tricky. The point is, here we are in a method
754 // of a renderer class, and this object may, or may not, be the same as
755 // the global $OUTPUT object. When rendering the page layout file, we want to use
756 // this object. However, people writing Moodle code expect the current
757 // renderer to be called $OUTPUT, not $this, so define a variable called
758 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
759 $OUTPUT = $this;
760 $PAGE = $this->page;
761 $COURSE = $this->page->course;
763 ob_start();
764 include($layoutfile);
765 $rendered = ob_get_contents();
766 ob_end_clean();
767 return $rendered;
771 * Outputs the page's footer
773 * @return string HTML fragment
775 public function footer() {
776 global $CFG, $DB;
778 $output = $this->container_end_all(true);
780 $footer = $this->opencontainers->pop('header/footer');
782 if (debugging() and $DB and $DB->is_transaction_started()) {
783 // TODO: MDL-20625 print warning - transaction will be rolled back
786 // Provide some performance info if required
787 $performanceinfo = '';
788 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
789 $perf = get_performance_info();
790 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
791 error_log("PERF: " . $perf['txt']);
793 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
794 $performanceinfo = $perf['html'];
797 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
799 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
801 $this->page->set_state(moodle_page::STATE_DONE);
803 return $output . $footer;
807 * Close all but the last open container. This is useful in places like error
808 * handling, where you want to close all the open containers (apart from <body>)
809 * before outputting the error message.
811 * @param bool $shouldbenone assert that the stack should be empty now - causes a
812 * developer debug warning if it isn't.
813 * @return string the HTML required to close any open containers inside <body>.
815 public function container_end_all($shouldbenone = false) {
816 return $this->opencontainers->pop_all_but_last($shouldbenone);
820 * Returns lang menu or '', this method also checks forcing of languages in courses.
822 * @return string The lang menu HTML or empty string
824 public function lang_menu() {
825 global $CFG;
827 if (empty($CFG->langmenu)) {
828 return '';
831 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
832 // do not show lang menu if language forced
833 return '';
836 $currlang = current_language();
837 $langs = get_string_manager()->get_list_of_translations();
839 if (count($langs) < 2) {
840 return '';
843 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
844 $s->label = get_accesshide(get_string('language'));
845 $s->class = 'langmenu';
846 return $this->render($s);
850 * Output the row of editing icons for a block, as defined by the controls array.
852 * @param array $controls an array like {@link block_contents::$controls}.
853 * @return string HTML fragment.
855 public function block_controls($controls) {
856 if (empty($controls)) {
857 return '';
859 $controlshtml = array();
860 foreach ($controls as $control) {
861 $controlshtml[] = html_writer::tag('a',
862 html_writer::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
863 array('class' => 'icon','title' => $control['caption'], 'href' => $control['url']));
865 return html_writer::tag('div', implode('', $controlshtml), array('class' => 'commands'));
869 * Prints a nice side block with an optional header.
871 * The content is described
872 * by a {@link core_renderer::block_contents} object.
874 * <div id="inst{$instanceid}" class="block_{$blockname} block">
875 * <div class="header"></div>
876 * <div class="content">
877 * ...CONTENT...
878 * <div class="footer">
879 * </div>
880 * </div>
881 * <div class="annotation">
882 * </div>
883 * </div>
885 * @param block_contents $bc HTML for the content
886 * @param string $region the region the block is appearing in.
887 * @return string the HTML to be output.
889 public function block(block_contents $bc, $region) {
890 $bc = clone($bc); // Avoid messing up the object passed in.
891 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
892 $bc->collapsible = block_contents::NOT_HIDEABLE;
894 if ($bc->collapsible == block_contents::HIDDEN) {
895 $bc->add_class('hidden');
897 if (!empty($bc->controls)) {
898 $bc->add_class('block_with_controls');
901 $skiptitle = strip_tags($bc->title);
902 if (empty($skiptitle)) {
903 $output = '';
904 $skipdest = '';
905 } else {
906 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
907 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
910 $output .= html_writer::start_tag('div', $bc->attributes);
912 $output .= $this->block_header($bc);
913 $output .= $this->block_content($bc);
915 $output .= html_writer::end_tag('div');
917 $output .= $this->block_annotation($bc);
919 $output .= $skipdest;
921 $this->init_block_hider_js($bc);
922 return $output;
926 * Produces a header for a block
928 * @param block_contents $bc
929 * @return string
931 protected function block_header(block_contents $bc) {
933 $title = '';
934 if ($bc->title) {
935 $title = html_writer::tag('h2', $bc->title, null);
938 $controlshtml = $this->block_controls($bc->controls);
940 $output = '';
941 if ($title || $controlshtml) {
942 $output .= html_writer::tag('div', html_writer::tag('div', html_writer::tag('div', '', array('class'=>'block_action')). $title . $controlshtml, array('class' => 'title')), array('class' => 'header'));
944 return $output;
948 * Produces the content area for a block
950 * @param block_contents $bc
951 * @return string
953 protected function block_content(block_contents $bc) {
954 $output = html_writer::start_tag('div', array('class' => 'content'));
955 if (!$bc->title && !$this->block_controls($bc->controls)) {
956 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
958 $output .= $bc->content;
959 $output .= $this->block_footer($bc);
960 $output .= html_writer::end_tag('div');
962 return $output;
966 * Produces the footer for a block
968 * @param block_contents $bc
969 * @return string
971 protected function block_footer(block_contents $bc) {
972 $output = '';
973 if ($bc->footer) {
974 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
976 return $output;
980 * Produces the annotation for a block
982 * @param block_contents $bc
983 * @return string
985 protected function block_annotation(block_contents $bc) {
986 $output = '';
987 if ($bc->annotation) {
988 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
990 return $output;
994 * Calls the JS require function to hide a block.
996 * @param block_contents $bc A block_contents object
998 protected function init_block_hider_js(block_contents $bc) {
999 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1000 $config = new stdClass;
1001 $config->id = $bc->attributes['id'];
1002 $config->title = strip_tags($bc->title);
1003 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1004 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1005 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1007 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1008 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1013 * Render the contents of a block_list.
1015 * @param array $icons the icon for each item.
1016 * @param array $items the content of each item.
1017 * @return string HTML
1019 public function list_block_contents($icons, $items) {
1020 $row = 0;
1021 $lis = array();
1022 foreach ($items as $key => $string) {
1023 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1024 if (!empty($icons[$key])) { //test if the content has an assigned icon
1025 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1027 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1028 $item .= html_writer::end_tag('li');
1029 $lis[] = $item;
1030 $row = 1 - $row; // Flip even/odd.
1032 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1036 * Output all the blocks in a particular region.
1038 * @param string $region the name of a region on this page.
1039 * @return string the HTML to be output.
1041 public function blocks_for_region($region) {
1042 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1044 $output = '';
1045 foreach ($blockcontents as $bc) {
1046 if ($bc instanceof block_contents) {
1047 $output .= $this->block($bc, $region);
1048 } else if ($bc instanceof block_move_target) {
1049 $output .= $this->block_move_target($bc);
1050 } else {
1051 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1054 return $output;
1058 * Output a place where the block that is currently being moved can be dropped.
1060 * @param block_move_target $target with the necessary details.
1061 * @return string the HTML to be output.
1063 public function block_move_target($target) {
1064 return html_writer::tag('a', html_writer::tag('span', $target->text, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1068 * Renders a special html link with attached action
1070 * @param string|moodle_url $url
1071 * @param string $text HTML fragment
1072 * @param component_action $action
1073 * @param array $attributes associative array of html link attributes + disabled
1074 * @return string HTML fragment
1076 public function action_link($url, $text, component_action $action = null, array $attributes=null) {
1077 if (!($url instanceof moodle_url)) {
1078 $url = new moodle_url($url);
1080 $link = new action_link($url, $text, $action, $attributes);
1082 return $this->render($link);
1086 * Renders an action_link object.
1088 * The provided link is renderer and the HTML returned. At the same time the
1089 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1091 * @param action_link $link
1092 * @return string HTML fragment
1094 protected function render_action_link(action_link $link) {
1095 global $CFG;
1097 if ($link->text instanceof renderable) {
1098 $text = $this->render($link->text);
1099 } else {
1100 $text = $link->text;
1103 // A disabled link is rendered as formatted text
1104 if (!empty($link->attributes['disabled'])) {
1105 // do not use div here due to nesting restriction in xhtml strict
1106 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1109 $attributes = $link->attributes;
1110 unset($link->attributes['disabled']);
1111 $attributes['href'] = $link->url;
1113 if ($link->actions) {
1114 if (empty($attributes['id'])) {
1115 $id = html_writer::random_id('action_link');
1116 $attributes['id'] = $id;
1117 } else {
1118 $id = $attributes['id'];
1120 foreach ($link->actions as $action) {
1121 $this->add_action_handler($action, $id);
1125 return html_writer::tag('a', $text, $attributes);
1130 * Renders an action_icon.
1132 * This function uses the {@link core_renderer::action_link()} method for the
1133 * most part. What it does different is prepare the icon as HTML and use it
1134 * as the link text.
1136 * @param string|moodle_url $url A string URL or moodel_url
1137 * @param pix_icon $pixicon
1138 * @param component_action $action
1139 * @param array $attributes associative array of html link attributes + disabled
1140 * @param bool $linktext show title next to image in link
1141 * @return string HTML fragment
1143 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1144 if (!($url instanceof moodle_url)) {
1145 $url = new moodle_url($url);
1147 $attributes = (array)$attributes;
1149 if (empty($attributes['class'])) {
1150 // let ppl override the class via $options
1151 $attributes['class'] = 'action-icon';
1154 $icon = $this->render($pixicon);
1156 if ($linktext) {
1157 $text = $pixicon->attributes['alt'];
1158 } else {
1159 $text = '';
1162 return $this->action_link($url, $text.$icon, $action, $attributes);
1166 * Print a message along with button choices for Continue/Cancel
1168 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1170 * @param string $message The question to ask the user
1171 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1172 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1173 * @return string HTML fragment
1175 public function confirm($message, $continue, $cancel) {
1176 if ($continue instanceof single_button) {
1177 // ok
1178 } else if (is_string($continue)) {
1179 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1180 } else if ($continue instanceof moodle_url) {
1181 $continue = new single_button($continue, get_string('continue'), 'post');
1182 } else {
1183 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1186 if ($cancel instanceof single_button) {
1187 // ok
1188 } else if (is_string($cancel)) {
1189 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1190 } else if ($cancel instanceof moodle_url) {
1191 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1192 } else {
1193 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1196 $output = $this->box_start('generalbox', 'notice');
1197 $output .= html_writer::tag('p', $message);
1198 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1199 $output .= $this->box_end();
1200 return $output;
1204 * Returns a form with a single button.
1206 * @param string|moodle_url $url
1207 * @param string $label button text
1208 * @param string $method get or post submit method
1209 * @param array $options associative array {disabled, title, etc.}
1210 * @return string HTML fragment
1212 public function single_button($url, $label, $method='post', array $options=null) {
1213 if (!($url instanceof moodle_url)) {
1214 $url = new moodle_url($url);
1216 $button = new single_button($url, $label, $method);
1218 foreach ((array)$options as $key=>$value) {
1219 if (array_key_exists($key, $button)) {
1220 $button->$key = $value;
1224 return $this->render($button);
1228 * Renders a single button widget.
1230 * This will return HTML to display a form containing a single button.
1232 * @param single_button $button
1233 * @return string HTML fragment
1235 protected function render_single_button(single_button $button) {
1236 $attributes = array('type' => 'submit',
1237 'value' => $button->label,
1238 'disabled' => $button->disabled ? 'disabled' : null,
1239 'title' => $button->tooltip);
1241 if ($button->actions) {
1242 $id = html_writer::random_id('single_button');
1243 $attributes['id'] = $id;
1244 foreach ($button->actions as $action) {
1245 $this->add_action_handler($action, $id);
1249 // first the input element
1250 $output = html_writer::empty_tag('input', $attributes);
1252 // then hidden fields
1253 $params = $button->url->params();
1254 if ($button->method === 'post') {
1255 $params['sesskey'] = sesskey();
1257 foreach ($params as $var => $val) {
1258 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1261 // then div wrapper for xhtml strictness
1262 $output = html_writer::tag('div', $output);
1264 // now the form itself around it
1265 if ($button->method === 'get') {
1266 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1267 } else {
1268 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1270 if ($url === '') {
1271 $url = '#'; // there has to be always some action
1273 $attributes = array('method' => $button->method,
1274 'action' => $url,
1275 'id' => $button->formid);
1276 $output = html_writer::tag('form', $output, $attributes);
1278 // and finally one more wrapper with class
1279 return html_writer::tag('div', $output, array('class' => $button->class));
1283 * Returns a form with a single select widget.
1285 * @param moodle_url $url form action target, includes hidden fields
1286 * @param string $name name of selection field - the changing parameter in url
1287 * @param array $options list of options
1288 * @param string $selected selected element
1289 * @param array $nothing
1290 * @param string $formid
1291 * @return string HTML fragment
1293 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1294 if (!($url instanceof moodle_url)) {
1295 $url = new moodle_url($url);
1297 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1299 return $this->render($select);
1303 * Internal implementation of single_select rendering
1305 * @param single_select $select
1306 * @return string HTML fragment
1308 protected function render_single_select(single_select $select) {
1309 $select = clone($select);
1310 if (empty($select->formid)) {
1311 $select->formid = html_writer::random_id('single_select_f');
1314 $output = '';
1315 $params = $select->url->params();
1316 if ($select->method === 'post') {
1317 $params['sesskey'] = sesskey();
1319 foreach ($params as $name=>$value) {
1320 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1323 if (empty($select->attributes['id'])) {
1324 $select->attributes['id'] = html_writer::random_id('single_select');
1327 if ($select->disabled) {
1328 $select->attributes['disabled'] = 'disabled';
1331 if ($select->tooltip) {
1332 $select->attributes['title'] = $select->tooltip;
1335 if ($select->label) {
1336 $output .= html_writer::label($select->label, $select->attributes['id']);
1339 if ($select->helpicon instanceof help_icon) {
1340 $output .= $this->render($select->helpicon);
1341 } else if ($select->helpicon instanceof old_help_icon) {
1342 $output .= $this->render($select->helpicon);
1345 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1347 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1348 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('style'=>'inline'));
1350 $nothing = empty($select->nothing) ? false : key($select->nothing);
1351 $this->page->requires->js_init_call('M.util.init_select_autosubmit', array($select->formid, $select->attributes['id'], $nothing));
1353 // then div wrapper for xhtml strictness
1354 $output = html_writer::tag('div', $output);
1356 // now the form itself around it
1357 if ($select->method === 'get') {
1358 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1359 } else {
1360 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1362 $formattributes = array('method' => $select->method,
1363 'action' => $url,
1364 'id' => $select->formid);
1365 $output = html_writer::tag('form', $output, $formattributes);
1367 // and finally one more wrapper with class
1368 return html_writer::tag('div', $output, array('class' => $select->class));
1372 * Returns a form with a url select widget.
1374 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1375 * @param string $selected selected element
1376 * @param array $nothing
1377 * @param string $formid
1378 * @return string HTML fragment
1380 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1381 $select = new url_select($urls, $selected, $nothing, $formid);
1382 return $this->render($select);
1386 * Internal implementation of url_select rendering
1388 * @param url_select $select
1389 * @return string HTML fragment
1391 protected function render_url_select(url_select $select) {
1392 global $CFG;
1394 $select = clone($select);
1395 if (empty($select->formid)) {
1396 $select->formid = html_writer::random_id('url_select_f');
1399 if (empty($select->attributes['id'])) {
1400 $select->attributes['id'] = html_writer::random_id('url_select');
1403 if ($select->disabled) {
1404 $select->attributes['disabled'] = 'disabled';
1407 if ($select->tooltip) {
1408 $select->attributes['title'] = $select->tooltip;
1411 $output = '';
1413 if ($select->label) {
1414 $output .= html_writer::label($select->label, $select->attributes['id']);
1417 if ($select->helpicon instanceof help_icon) {
1418 $output .= $this->render($select->helpicon);
1419 } else if ($select->helpicon instanceof old_help_icon) {
1420 $output .= $this->render($select->helpicon);
1423 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1424 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1425 $urls = array();
1426 foreach ($select->urls as $k=>$v) {
1427 if (is_array($v)) {
1428 // optgroup structure
1429 foreach ($v as $optgrouptitle => $optgroupoptions) {
1430 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1431 if (empty($optionurl)) {
1432 $safeoptionurl = '';
1433 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1434 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1435 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1436 } else if (strpos($optionurl, '/') !== 0) {
1437 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1438 continue;
1439 } else {
1440 $safeoptionurl = $optionurl;
1442 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1445 } else {
1446 // plain list structure
1447 if (empty($k)) {
1448 // nothing selected option
1449 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1450 $k = str_replace($CFG->wwwroot, '', $k);
1451 } else if (strpos($k, '/') !== 0) {
1452 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1453 continue;
1455 $urls[$k] = $v;
1458 $selected = $select->selected;
1459 if (!empty($selected)) {
1460 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1461 $selected = str_replace($CFG->wwwroot, '', $selected);
1462 } else if (strpos($selected, '/') !== 0) {
1463 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1467 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1468 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1470 if (!$select->showbutton) {
1471 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1472 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('style'=>'inline'));
1473 $nothing = empty($select->nothing) ? false : key($select->nothing);
1474 $output .= $this->page->requires->js_init_call('M.util.init_url_select', array($select->formid, $select->attributes['id'], $nothing));
1475 } else {
1476 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1479 // then div wrapper for xhtml strictness
1480 $output = html_writer::tag('div', $output);
1482 // now the form itself around it
1483 $formattributes = array('method' => 'post',
1484 'action' => new moodle_url('/course/jumpto.php'),
1485 'id' => $select->formid);
1486 $output = html_writer::tag('form', $output, $formattributes);
1488 // and finally one more wrapper with class
1489 return html_writer::tag('div', $output, array('class' => $select->class));
1493 * Returns a string containing a link to the user documentation.
1494 * Also contains an icon by default. Shown to teachers and admin only.
1496 * @param string $path The page link after doc root and language, no leading slash.
1497 * @param string $text The text to be displayed for the link
1498 * @return string
1500 public function doc_link($path, $text = '') {
1501 global $CFG;
1503 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp'));
1505 $url = new moodle_url(get_docs_url($path));
1507 $attributes = array('href'=>$url);
1508 if (!empty($CFG->doctonewwindow)) {
1509 $attributes['id'] = $this->add_action_handler(new popup_action('click', $url));
1512 return html_writer::tag('a', $icon.$text, $attributes);
1516 * Return HTML for a pix_icon.
1518 * @param string $pix short pix name
1519 * @param string $alt mandatory alt attribute
1520 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1521 * @param array $attributes htm lattributes
1522 * @return string HTML fragment
1524 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1525 $icon = new pix_icon($pix, $alt, $component, $attributes);
1526 return $this->render($icon);
1530 * Renders a pix_icon widget and returns the HTML to display it.
1532 * @param pix_icon $icon
1533 * @return string HTML fragment
1535 protected function render_pix_icon(pix_icon $icon) {
1536 $attributes = $icon->attributes;
1537 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1538 return html_writer::empty_tag('img', $attributes);
1542 * Return HTML to display an emoticon icon.
1544 * @param pix_emoticon $emoticon
1545 * @return string HTML fragment
1547 protected function render_pix_emoticon(pix_emoticon $emoticon) {
1548 $attributes = $emoticon->attributes;
1549 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
1550 return html_writer::empty_tag('img', $attributes);
1554 * Produces the html that represents this rating in the UI
1556 * @param rating $rating the page object on which this rating will appear
1557 * @return string
1559 function render_rating(rating $rating) {
1560 global $CFG, $USER;
1562 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
1563 return null;//ratings are turned off
1566 $ratingmanager = new rating_manager();
1567 // Initialise the JavaScript so ratings can be done by AJAX.
1568 $ratingmanager->initialise_rating_javascript($this->page);
1570 $strrate = get_string("rate", "rating");
1571 $ratinghtml = ''; //the string we'll return
1573 // permissions check - can they view the aggregate?
1574 if ($rating->user_can_view_aggregate()) {
1576 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
1577 $aggregatestr = $rating->get_aggregate_string();
1579 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
1580 if ($rating->count > 0) {
1581 $countstr = "({$rating->count})";
1582 } else {
1583 $countstr = '-';
1585 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
1587 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
1588 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
1590 $nonpopuplink = $rating->get_view_ratings_url();
1591 $popuplink = $rating->get_view_ratings_url(true);
1593 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
1594 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
1595 } else {
1596 $ratinghtml .= $aggregatehtml;
1600 $formstart = null;
1601 // if the item doesn't belong to the current user, the user has permission to rate
1602 // and we're within the assessable period
1603 if ($rating->user_can_rate()) {
1605 $rateurl = $rating->get_rate_url();
1606 $inputs = $rateurl->params();
1608 //start the rating form
1609 $formattrs = array(
1610 'id' => "postrating{$rating->itemid}",
1611 'class' => 'postratingform',
1612 'method' => 'post',
1613 'action' => $rateurl->out_omit_querystring()
1615 $formstart = html_writer::start_tag('form', $formattrs);
1616 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
1618 // add the hidden inputs
1619 foreach ($inputs as $name => $value) {
1620 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
1621 $formstart .= html_writer::empty_tag('input', $attributes);
1624 if (empty($ratinghtml)) {
1625 $ratinghtml .= $strrate.': ';
1627 $ratinghtml = $formstart.$ratinghtml;
1629 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
1630 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
1631 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
1633 //output submit button
1634 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
1636 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
1637 $ratinghtml .= html_writer::empty_tag('input', $attributes);
1639 if (!$rating->settings->scale->isnumeric) {
1640 $ratinghtml .= $this->help_icon_scale($rating->settings->scale->courseid, $rating->settings->scale);
1642 $ratinghtml .= html_writer::end_tag('span');
1643 $ratinghtml .= html_writer::end_tag('div');
1644 $ratinghtml .= html_writer::end_tag('form');
1647 return $ratinghtml;
1651 * Centered heading with attached help button (same title text)
1652 * and optional icon attached.
1654 * @param string $text A heading text
1655 * @param string $helpidentifier The keyword that defines a help page
1656 * @param string $component component name
1657 * @param string|moodle_url $icon
1658 * @param string $iconalt icon alt text
1659 * @return string HTML fragment
1661 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '') {
1662 $image = '';
1663 if ($icon) {
1664 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
1667 $help = '';
1668 if ($helpidentifier) {
1669 $help = $this->help_icon($helpidentifier, $component);
1672 return $this->heading($image.$text.$help, 2, 'main help');
1676 * Returns HTML to display a help icon.
1678 * @deprecated since Moodle 2.0
1679 * @param string $helpidentifier The keyword that defines a help page
1680 * @param string $title A descriptive text for accessibility only
1681 * @param string $component component name
1682 * @param string|bool $linktext true means use $title as link text, string means link text value
1683 * @return string HTML fragment
1685 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
1686 debugging('The method old_help_icon() is deprecated, please fix the code and use help_icon() method instead', DEBUG_DEVELOPER);
1687 $icon = new old_help_icon($helpidentifier, $title, $component);
1688 if ($linktext === true) {
1689 $icon->linktext = $title;
1690 } else if (!empty($linktext)) {
1691 $icon->linktext = $linktext;
1693 return $this->render($icon);
1697 * Implementation of user image rendering.
1699 * @param old_help_icon $helpicon A help icon instance
1700 * @return string HTML fragment
1702 protected function render_old_help_icon(old_help_icon $helpicon) {
1703 global $CFG;
1705 // first get the help image icon
1706 $src = $this->pix_url('help');
1708 if (empty($helpicon->linktext)) {
1709 $alt = $helpicon->title;
1710 } else {
1711 $alt = get_string('helpwiththis');
1714 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1715 $output = html_writer::empty_tag('img', $attributes);
1717 // add the link text if given
1718 if (!empty($helpicon->linktext)) {
1719 // the spacing has to be done through CSS
1720 $output .= $helpicon->linktext;
1723 // now create the link around it - we need https on loginhttps pages
1724 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->helpidentifier, 'lang'=>current_language()));
1726 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1727 $title = get_string('helpprefix2', '', trim($helpicon->title, ". \t"));
1729 $attributes = array('href'=>$url, 'title'=>$title);
1730 $id = html_writer::random_id('helpicon');
1731 $attributes['id'] = $id;
1732 $output = html_writer::tag('a', $output, $attributes);
1734 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1736 // and finally span
1737 return html_writer::tag('span', $output, array('class' => 'helplink'));
1741 * Returns HTML to display a help icon.
1743 * @param string $identifier The keyword that defines a help page
1744 * @param string $component component name
1745 * @param string|bool $linktext true means use $title as link text, string means link text value
1746 * @return string HTML fragment
1748 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
1749 $icon = new help_icon($identifier, $component);
1750 $icon->diag_strings();
1751 if ($linktext === true) {
1752 $icon->linktext = get_string($icon->identifier, $icon->component);
1753 } else if (!empty($linktext)) {
1754 $icon->linktext = $linktext;
1756 return $this->render($icon);
1760 * Implementation of user image rendering.
1762 * @param help_icon $helpicon A help icon instance
1763 * @return string HTML fragment
1765 protected function render_help_icon(help_icon $helpicon) {
1766 global $CFG;
1768 // first get the help image icon
1769 $src = $this->pix_url('help');
1771 $title = get_string($helpicon->identifier, $helpicon->component);
1773 if (empty($helpicon->linktext)) {
1774 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
1775 } else {
1776 $alt = get_string('helpwiththis');
1779 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1780 $output = html_writer::empty_tag('img', $attributes);
1782 // add the link text if given
1783 if (!empty($helpicon->linktext)) {
1784 // the spacing has to be done through CSS
1785 $output .= $helpicon->linktext;
1788 // now create the link around it - we need https on loginhttps pages
1789 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
1791 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1792 $title = get_string('helpprefix2', '', trim($title, ". \t"));
1794 $attributes = array('href'=>$url, 'title'=>$title);
1795 $id = html_writer::random_id('helpicon');
1796 $attributes['id'] = $id;
1797 $output = html_writer::tag('a', $output, $attributes);
1799 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1801 // and finally span
1802 return html_writer::tag('span', $output, array('class' => 'helplink'));
1806 * Returns HTML to display a scale help icon.
1808 * @param int $courseid
1809 * @param stdClass $scale instance
1810 * @return string HTML fragment
1812 public function help_icon_scale($courseid, stdClass $scale) {
1813 global $CFG;
1815 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
1817 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
1819 $scaleid = abs($scale->id);
1821 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
1822 $action = new popup_action('click', $link, 'ratingscale');
1824 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
1828 * Creates and returns a spacer image with optional line break.
1830 * @param array $attributes Any HTML attributes to add to the spaced.
1831 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
1832 * laxy do it with CSS which is a much better solution.
1833 * @return string HTML fragment
1835 public function spacer(array $attributes = null, $br = false) {
1836 $attributes = (array)$attributes;
1837 if (empty($attributes['width'])) {
1838 $attributes['width'] = 1;
1840 if (empty($attributes['height'])) {
1841 $attributes['height'] = 1;
1843 $attributes['class'] = 'spacer';
1845 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
1847 if (!empty($br)) {
1848 $output .= '<br />';
1851 return $output;
1855 * Returns HTML to display the specified user's avatar.
1857 * User avatar may be obtained in two ways:
1858 * <pre>
1859 * // Option 1: (shortcut for simple cases, preferred way)
1860 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
1861 * $OUTPUT->user_picture($user, array('popup'=>true));
1863 * // Option 2:
1864 * $userpic = new user_picture($user);
1865 * // Set properties of $userpic
1866 * $userpic->popup = true;
1867 * $OUTPUT->render($userpic);
1868 * </pre>
1870 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
1871 * If any of these are missing, the database is queried. Avoid this
1872 * if at all possible, particularly for reports. It is very bad for performance.
1873 * @param array $options associative array with user picture options, used only if not a user_picture object,
1874 * options are:
1875 * - courseid=$this->page->course->id (course id of user profile in link)
1876 * - size=35 (size of image)
1877 * - link=true (make image clickable - the link leads to user profile)
1878 * - popup=false (open in popup)
1879 * - alttext=true (add image alt attribute)
1880 * - class = image class attribute (default 'userpicture')
1881 * @return string HTML fragment
1883 public function user_picture(stdClass $user, array $options = null) {
1884 $userpicture = new user_picture($user);
1885 foreach ((array)$options as $key=>$value) {
1886 if (array_key_exists($key, $userpicture)) {
1887 $userpicture->$key = $value;
1890 return $this->render($userpicture);
1894 * Internal implementation of user image rendering.
1896 * @param user_picture $userpicture
1897 * @return string
1899 protected function render_user_picture(user_picture $userpicture) {
1900 global $CFG, $DB;
1902 $user = $userpicture->user;
1904 if ($userpicture->alttext) {
1905 if (!empty($user->imagealt)) {
1906 $alt = $user->imagealt;
1907 } else {
1908 $alt = get_string('pictureof', '', fullname($user));
1910 } else {
1911 $alt = '';
1914 if (empty($userpicture->size)) {
1915 $size = 35;
1916 } else if ($userpicture->size === true or $userpicture->size == 1) {
1917 $size = 100;
1918 } else {
1919 $size = $userpicture->size;
1922 $class = $userpicture->class;
1924 if ($user->picture != 1 && $user->picture != 2) {
1925 $class .= ' defaultuserpic';
1928 $src = $userpicture->get_url($this->page, $this);
1930 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
1932 // get the image html output fisrt
1933 $output = html_writer::empty_tag('img', $attributes);;
1935 // then wrap it in link if needed
1936 if (!$userpicture->link) {
1937 return $output;
1940 if (empty($userpicture->courseid)) {
1941 $courseid = $this->page->course->id;
1942 } else {
1943 $courseid = $userpicture->courseid;
1946 if ($courseid == SITEID) {
1947 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
1948 } else {
1949 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
1952 $attributes = array('href'=>$url);
1954 if ($userpicture->popup) {
1955 $id = html_writer::random_id('userpicture');
1956 $attributes['id'] = $id;
1957 $this->add_action_handler(new popup_action('click', $url), $id);
1960 return html_writer::tag('a', $output, $attributes);
1964 * Internal implementation of file tree viewer items rendering.
1966 * @param array $dir
1967 * @return string
1969 public function htmllize_file_tree($dir) {
1970 if (empty($dir['subdirs']) and empty($dir['files'])) {
1971 return '';
1973 $result = '<ul>';
1974 foreach ($dir['subdirs'] as $subdir) {
1975 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
1977 foreach ($dir['files'] as $file) {
1978 $filename = $file->get_filename();
1979 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
1981 $result .= '</ul>';
1983 return $result;
1987 * Returns HTML to display the file picker
1989 * <pre>
1990 * $OUTPUT->file_picker($options);
1991 * </pre>
1993 * @param array $options associative array with file manager options
1994 * options are:
1995 * maxbytes=>-1,
1996 * itemid=>0,
1997 * client_id=>uniqid(),
1998 * acepted_types=>'*',
1999 * return_types=>FILE_INTERNAL,
2000 * context=>$PAGE->context
2001 * @return string HTML fragment
2003 public function file_picker($options) {
2004 $fp = new file_picker($options);
2005 return $this->render($fp);
2009 * Internal implementation of file picker rendering.
2011 * @param file_picker $fp
2012 * @return string
2014 public function render_file_picker(file_picker $fp) {
2015 global $CFG, $OUTPUT, $USER;
2016 $options = $fp->options;
2017 $client_id = $options->client_id;
2018 $strsaved = get_string('filesaved', 'repository');
2019 $straddfile = get_string('openpicker', 'repository');
2020 $strloading = get_string('loading', 'repository');
2021 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2022 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2024 $currentfile = $options->currentfile;
2025 if (empty($currentfile)) {
2026 $currentfile = get_string('nofilesattached', 'repository');
2028 if ($options->maxbytes) {
2029 $size = $options->maxbytes;
2030 } else {
2031 $size = get_max_upload_file_size();
2033 if ($size == -1) {
2034 $maxsize = '';
2035 } else {
2036 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2038 if ($options->buttonname) {
2039 $buttonname = ' name="' . $options->buttonname . '"';
2040 } else {
2041 $buttonname = '';
2043 $html = <<<EOD
2044 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2045 $icon_progress
2046 </div>
2047 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2048 <div>
2049 <input type="button" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2050 <span> $maxsize </span>
2051 </div>
2052 EOD;
2053 if ($options->env != 'url') {
2054 $html .= <<<EOD
2055 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist">
2056 $currentfile<span id="dndenabled-{$client_id}" style="display: none"> - $strdndenabled </span>
2057 </div>
2058 EOD;
2060 $html .= '</div>';
2061 return $html;
2065 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2067 * @param string $cmid the course_module id.
2068 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2069 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2071 public function update_module_button($cmid, $modulename) {
2072 global $CFG;
2073 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $cmid))) {
2074 $modulename = get_string('modulename', $modulename);
2075 $string = get_string('updatethis', '', $modulename);
2076 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2077 return $this->single_button($url, $string);
2078 } else {
2079 return '';
2084 * Returns HTML to display a "Turn editing on/off" button in a form.
2086 * @param moodle_url $url The URL + params to send through when clicking the button
2087 * @return string HTML the button
2089 public function edit_button(moodle_url $url) {
2091 $url->param('sesskey', sesskey());
2092 if ($this->page->user_is_editing()) {
2093 $url->param('edit', 'off');
2094 $editstring = get_string('turneditingoff');
2095 } else {
2096 $url->param('edit', 'on');
2097 $editstring = get_string('turneditingon');
2100 return $this->single_button($url, $editstring);
2104 * Returns HTML to display a simple button to close a window
2106 * @param string $text The lang string for the button's label (already output from get_string())
2107 * @return string html fragment
2109 public function close_window_button($text='') {
2110 if (empty($text)) {
2111 $text = get_string('closewindow');
2113 $button = new single_button(new moodle_url('#'), $text, 'get');
2114 $button->add_action(new component_action('click', 'close_window'));
2116 return $this->container($this->render($button), 'closewindow');
2120 * Output an error message. By default wraps the error message in <span class="error">.
2121 * If the error message is blank, nothing is output.
2123 * @param string $message the error message.
2124 * @return string the HTML to output.
2126 public function error_text($message) {
2127 if (empty($message)) {
2128 return '';
2130 return html_writer::tag('span', $message, array('class' => 'error'));
2134 * Do not call this function directly.
2136 * To terminate the current script with a fatal error, call the {@link print_error}
2137 * function, or throw an exception. Doing either of those things will then call this
2138 * function to display the error, before terminating the execution.
2140 * @param string $message The message to output
2141 * @param string $moreinfourl URL where more info can be found about the error
2142 * @param string $link Link for the Continue button
2143 * @param array $backtrace The execution backtrace
2144 * @param string $debuginfo Debugging information
2145 * @return string the HTML to output.
2147 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2148 global $CFG;
2150 $output = '';
2151 $obbuffer = '';
2153 if ($this->has_started()) {
2154 // we can not always recover properly here, we have problems with output buffering,
2155 // html tables, etc.
2156 $output .= $this->opencontainers->pop_all_but_last();
2158 } else {
2159 // It is really bad if library code throws exception when output buffering is on,
2160 // because the buffered text would be printed before our start of page.
2161 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2162 error_reporting(0); // disable notices from gzip compression, etc.
2163 while (ob_get_level() > 0) {
2164 $buff = ob_get_clean();
2165 if ($buff === false) {
2166 break;
2168 $obbuffer .= $buff;
2170 error_reporting($CFG->debug);
2172 // Header not yet printed
2173 if (isset($_SERVER['SERVER_PROTOCOL'])) {
2174 // server protocol should be always present, because this render
2175 // can not be used from command line or when outputting custom XML
2176 @header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
2178 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2179 $this->page->set_url('/'); // no url
2180 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2181 $this->page->set_title(get_string('error'));
2182 $this->page->set_heading($this->page->course->fullname);
2183 $output .= $this->header();
2186 $message = '<p class="errormessage">' . $message . '</p>'.
2187 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2188 get_string('moreinformation') . '</a></p>';
2189 if (empty($CFG->rolesactive)) {
2190 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2191 //It is usually not possible to recover from errors triggered during installation, you may need to create a new database or use a different database prefix for new installation.
2193 $output .= $this->box($message, 'errorbox');
2195 if (debugging('', DEBUG_DEVELOPER)) {
2196 if (!empty($debuginfo)) {
2197 $debuginfo = s($debuginfo); // removes all nasty JS
2198 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2199 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2201 if (!empty($backtrace)) {
2202 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2204 if ($obbuffer !== '' ) {
2205 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2209 if (empty($CFG->rolesactive)) {
2210 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2211 } else if (!empty($link)) {
2212 $output .= $this->continue_button($link);
2215 $output .= $this->footer();
2217 // Padding to encourage IE to display our error page, rather than its own.
2218 $output .= str_repeat(' ', 512);
2220 return $output;
2224 * Output a notification (that is, a status message about something that has
2225 * just happened).
2227 * @param string $message the message to print out
2228 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2229 * @return string the HTML to output.
2231 public function notification($message, $classes = 'notifyproblem') {
2232 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2236 * Returns HTML to display a continue button that goes to a particular URL.
2238 * @param string|moodle_url $url The url the button goes to.
2239 * @return string the HTML to output.
2241 public function continue_button($url) {
2242 if (!($url instanceof moodle_url)) {
2243 $url = new moodle_url($url);
2245 $button = new single_button($url, get_string('continue'), 'get');
2246 $button->class = 'continuebutton';
2248 return $this->render($button);
2252 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2254 * @param int $totalcount The total number of entries available to be paged through
2255 * @param int $page The page you are currently viewing
2256 * @param int $perpage The number of entries that should be shown per page
2257 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2258 * @param string $pagevar name of page parameter that holds the page number
2259 * @return string the HTML to output.
2261 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2262 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2263 return $this->render($pb);
2267 * Internal implementation of paging bar rendering.
2269 * @param paging_bar $pagingbar
2270 * @return string
2272 protected function render_paging_bar(paging_bar $pagingbar) {
2273 $output = '';
2274 $pagingbar = clone($pagingbar);
2275 $pagingbar->prepare($this, $this->page, $this->target);
2277 if ($pagingbar->totalcount > $pagingbar->perpage) {
2278 $output .= get_string('page') . ':';
2280 if (!empty($pagingbar->previouslink)) {
2281 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
2284 if (!empty($pagingbar->firstlink)) {
2285 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
2288 foreach ($pagingbar->pagelinks as $link) {
2289 $output .= "&#160;&#160;$link";
2292 if (!empty($pagingbar->lastlink)) {
2293 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
2296 if (!empty($pagingbar->nextlink)) {
2297 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
2301 return html_writer::tag('div', $output, array('class' => 'paging'));
2305 * Output the place a skip link goes to.
2307 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2308 * @return string the HTML to output.
2310 public function skip_link_target($id = null) {
2311 return html_writer::tag('span', '', array('id' => $id));
2315 * Outputs a heading
2317 * @param string $text The text of the heading
2318 * @param int $level The level of importance of the heading. Defaulting to 2
2319 * @param string $classes A space-separated list of CSS classes
2320 * @param string $id An optional ID
2321 * @return string the HTML to output.
2323 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2324 $level = (integer) $level;
2325 if ($level < 1 or $level > 6) {
2326 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2328 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2332 * Outputs a box.
2334 * @param string $contents The contents of the box
2335 * @param string $classes A space-separated list of CSS classes
2336 * @param string $id An optional ID
2337 * @return string the HTML to output.
2339 public function box($contents, $classes = 'generalbox', $id = null) {
2340 return $this->box_start($classes, $id) . $contents . $this->box_end();
2344 * Outputs the opening section of a box.
2346 * @param string $classes A space-separated list of CSS classes
2347 * @param string $id An optional ID
2348 * @return string the HTML to output.
2350 public function box_start($classes = 'generalbox', $id = null) {
2351 $this->opencontainers->push('box', html_writer::end_tag('div'));
2352 return html_writer::start_tag('div', array('id' => $id,
2353 'class' => 'box ' . renderer_base::prepare_classes($classes)));
2357 * Outputs the closing section of a box.
2359 * @return string the HTML to output.
2361 public function box_end() {
2362 return $this->opencontainers->pop('box');
2366 * Outputs a container.
2368 * @param string $contents The contents of the box
2369 * @param string $classes A space-separated list of CSS classes
2370 * @param string $id An optional ID
2371 * @return string the HTML to output.
2373 public function container($contents, $classes = null, $id = null) {
2374 return $this->container_start($classes, $id) . $contents . $this->container_end();
2378 * Outputs the opening section of a container.
2380 * @param string $classes A space-separated list of CSS classes
2381 * @param string $id An optional ID
2382 * @return string the HTML to output.
2384 public function container_start($classes = null, $id = null) {
2385 $this->opencontainers->push('container', html_writer::end_tag('div'));
2386 return html_writer::start_tag('div', array('id' => $id,
2387 'class' => renderer_base::prepare_classes($classes)));
2391 * Outputs the closing section of a container.
2393 * @return string the HTML to output.
2395 public function container_end() {
2396 return $this->opencontainers->pop('container');
2400 * Make nested HTML lists out of the items
2402 * The resulting list will look something like this:
2404 * <pre>
2405 * <<ul>>
2406 * <<li>><div class='tree_item parent'>(item contents)</div>
2407 * <<ul>
2408 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2409 * <</ul>>
2410 * <</li>>
2411 * <</ul>>
2412 * </pre>
2414 * @param array $items
2415 * @param array $attrs html attributes passed to the top ofs the list
2416 * @return string HTML
2418 public function tree_block_contents($items, $attrs = array()) {
2419 // exit if empty, we don't want an empty ul element
2420 if (empty($items)) {
2421 return '';
2423 // array of nested li elements
2424 $lis = array();
2425 foreach ($items as $item) {
2426 // this applies to the li item which contains all child lists too
2427 $content = $item->content($this);
2428 $liclasses = array($item->get_css_type());
2429 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2430 $liclasses[] = 'collapsed';
2432 if ($item->isactive === true) {
2433 $liclasses[] = 'current_branch';
2435 $liattr = array('class'=>join(' ',$liclasses));
2436 // class attribute on the div item which only contains the item content
2437 $divclasses = array('tree_item');
2438 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2439 $divclasses[] = 'branch';
2440 } else {
2441 $divclasses[] = 'leaf';
2443 if (!empty($item->classes) && count($item->classes)>0) {
2444 $divclasses[] = join(' ', $item->classes);
2446 $divattr = array('class'=>join(' ', $divclasses));
2447 if (!empty($item->id)) {
2448 $divattr['id'] = $item->id;
2450 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2451 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2452 $content = html_writer::empty_tag('hr') . $content;
2454 $content = html_writer::tag('li', $content, $liattr);
2455 $lis[] = $content;
2457 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2461 * Return the navbar content so that it can be echoed out by the layout
2463 * @return string XHTML navbar
2465 public function navbar() {
2466 $items = $this->page->navbar->get_items();
2468 $htmlblocks = array();
2469 // Iterate the navarray and display each node
2470 $itemcount = count($items);
2471 $separator = get_separator();
2472 for ($i=0;$i < $itemcount;$i++) {
2473 $item = $items[$i];
2474 $item->hideicon = true;
2475 if ($i===0) {
2476 $content = html_writer::tag('li', $this->render($item));
2477 } else {
2478 $content = html_writer::tag('li', $separator.$this->render($item));
2480 $htmlblocks[] = $content;
2483 //accessibility: heading for navbar list (MDL-20446)
2484 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2485 $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks));
2486 // XHTML
2487 return $navbarcontent;
2491 * Renders a navigation node object.
2493 * @param navigation_node $item The navigation node to render.
2494 * @return string HTML fragment
2496 protected function render_navigation_node(navigation_node $item) {
2497 $content = $item->get_content();
2498 $title = $item->get_title();
2499 if ($item->icon instanceof renderable && !$item->hideicon) {
2500 $icon = $this->render($item->icon);
2501 $content = $icon.$content; // use CSS for spacing of icons
2503 if ($item->helpbutton !== null) {
2504 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2506 if ($content === '') {
2507 return '';
2509 if ($item->action instanceof action_link) {
2510 $link = $item->action;
2511 if ($item->hidden) {
2512 $link->add_class('dimmed');
2514 $link->text = $content.$link->text; // add help icon
2515 $content = $this->render($link);
2516 } else if ($item->action instanceof moodle_url) {
2517 $attributes = array();
2518 if ($title !== '') {
2519 $attributes['title'] = $title;
2521 if ($item->hidden) {
2522 $attributes['class'] = 'dimmed_text';
2524 $content = html_writer::link($item->action, $content, $attributes);
2526 } else if (is_string($item->action) || empty($item->action)) {
2527 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2528 if ($title !== '') {
2529 $attributes['title'] = $title;
2531 if ($item->hidden) {
2532 $attributes['class'] = 'dimmed_text';
2534 $content = html_writer::tag('span', $content, $attributes);
2536 return $content;
2540 * Accessibility: Right arrow-like character is
2541 * used in the breadcrumb trail, course navigation menu
2542 * (previous/next activity), calendar, and search forum block.
2543 * If the theme does not set characters, appropriate defaults
2544 * are set automatically. Please DO NOT
2545 * use &lt; &gt; &raquo; - these are confusing for blind users.
2547 * @return string
2549 public function rarrow() {
2550 return $this->page->theme->rarrow;
2554 * Accessibility: Right arrow-like character is
2555 * used in the breadcrumb trail, course navigation menu
2556 * (previous/next activity), calendar, and search forum block.
2557 * If the theme does not set characters, appropriate defaults
2558 * are set automatically. Please DO NOT
2559 * use &lt; &gt; &raquo; - these are confusing for blind users.
2561 * @return string
2563 public function larrow() {
2564 return $this->page->theme->larrow;
2568 * Returns the custom menu if one has been set
2570 * A custom menu can be configured by browsing to
2571 * Settings: Administration > Appearance > Themes > Theme settings
2572 * and then configuring the custommenu config setting as described.
2574 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
2575 * @return string
2577 public function custom_menu($custommenuitems = '') {
2578 global $CFG;
2579 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
2580 $custommenuitems = $CFG->custommenuitems;
2582 if (empty($custommenuitems)) {
2583 return '';
2585 $custommenu = new custom_menu($custommenuitems, current_language());
2586 return $this->render_custom_menu($custommenu);
2590 * Renders a custom menu object (located in outputcomponents.php)
2592 * The custom menu this method produces makes use of the YUI3 menunav widget
2593 * and requires very specific html elements and classes.
2595 * @staticvar int $menucount
2596 * @param custom_menu $menu
2597 * @return string
2599 protected function render_custom_menu(custom_menu $menu) {
2600 static $menucount = 0;
2601 // If the menu has no children return an empty string
2602 if (!$menu->has_children()) {
2603 return '';
2605 // Increment the menu count. This is used for ID's that get worked with
2606 // in JavaScript as is essential
2607 $menucount++;
2608 // Initialise this custom menu (the custom menu object is contained in javascript-static
2609 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
2610 $jscode = "(function(){{$jscode}})";
2611 $this->page->requires->yui_module('node-menunav', $jscode);
2612 // Build the root nodes as required by YUI
2613 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled'));
2614 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2615 $content .= html_writer::start_tag('ul');
2616 // Render each child
2617 foreach ($menu->get_children() as $item) {
2618 $content .= $this->render_custom_menu_item($item);
2620 // Close the open tags
2621 $content .= html_writer::end_tag('ul');
2622 $content .= html_writer::end_tag('div');
2623 $content .= html_writer::end_tag('div');
2624 // Return the custom menu
2625 return $content;
2629 * Renders a custom menu node as part of a submenu
2631 * The custom menu this method produces makes use of the YUI3 menunav widget
2632 * and requires very specific html elements and classes.
2634 * @see core:renderer::render_custom_menu()
2636 * @staticvar int $submenucount
2637 * @param custom_menu_item $menunode
2638 * @return string
2640 protected function render_custom_menu_item(custom_menu_item $menunode) {
2641 // Required to ensure we get unique trackable id's
2642 static $submenucount = 0;
2643 if ($menunode->has_children()) {
2644 // If the child has menus render it as a sub menu
2645 $submenucount++;
2646 $content = html_writer::start_tag('li');
2647 if ($menunode->get_url() !== null) {
2648 $url = $menunode->get_url();
2649 } else {
2650 $url = '#cm_submenu_'.$submenucount;
2652 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
2653 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
2654 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2655 $content .= html_writer::start_tag('ul');
2656 foreach ($menunode->get_children() as $menunode) {
2657 $content .= $this->render_custom_menu_item($menunode);
2659 $content .= html_writer::end_tag('ul');
2660 $content .= html_writer::end_tag('div');
2661 $content .= html_writer::end_tag('div');
2662 $content .= html_writer::end_tag('li');
2663 } else {
2664 // The node doesn't have children so produce a final menuitem
2665 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
2666 if ($menunode->get_url() !== null) {
2667 $url = $menunode->get_url();
2668 } else {
2669 $url = '#';
2671 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
2672 $content .= html_writer::end_tag('li');
2674 // Return the sub menu
2675 return $content;
2679 * Renders theme links for switching between default and other themes.
2681 * @return string
2683 protected function theme_switch_links() {
2685 $actualdevice = get_device_type();
2686 $currentdevice = $this->page->devicetypeinuse;
2687 $switched = ($actualdevice != $currentdevice);
2689 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
2690 // The user is using the a default device and hasn't switched so don't shown the switch
2691 // device links.
2692 return '';
2695 if ($switched) {
2696 $linktext = get_string('switchdevicerecommended');
2697 $devicetype = $actualdevice;
2698 } else {
2699 $linktext = get_string('switchdevicedefault');
2700 $devicetype = 'default';
2702 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
2704 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
2705 $content .= html_writer::link($linkurl, $linktext);
2706 $content .= html_writer::end_tag('div');
2708 return $content;
2713 * A renderer that generates output for command-line scripts.
2715 * The implementation of this renderer is probably incomplete.
2717 * @copyright 2009 Tim Hunt
2718 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2719 * @since Moodle 2.0
2720 * @package core
2721 * @category output
2723 class core_renderer_cli extends core_renderer {
2726 * Returns the page header.
2728 * @return string HTML fragment
2730 public function header() {
2731 return $this->page->heading . "\n";
2735 * Returns a template fragment representing a Heading.
2737 * @param string $text The text of the heading
2738 * @param int $level The level of importance of the heading
2739 * @param string $classes A space-separated list of CSS classes
2740 * @param string $id An optional ID
2741 * @return string A template fragment for a heading
2743 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2744 $text .= "\n";
2745 switch ($level) {
2746 case 1:
2747 return '=>' . $text;
2748 case 2:
2749 return '-->' . $text;
2750 default:
2751 return $text;
2756 * Returns a template fragment representing a fatal error.
2758 * @param string $message The message to output
2759 * @param string $moreinfourl URL where more info can be found about the error
2760 * @param string $link Link for the Continue button
2761 * @param array $backtrace The execution backtrace
2762 * @param string $debuginfo Debugging information
2763 * @return string A template fragment for a fatal error
2765 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2766 $output = "!!! $message !!!\n";
2768 if (debugging('', DEBUG_DEVELOPER)) {
2769 if (!empty($debuginfo)) {
2770 $output .= $this->notification($debuginfo, 'notifytiny');
2772 if (!empty($backtrace)) {
2773 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
2777 return $output;
2781 * Returns a template fragment representing a notification.
2783 * @param string $message The message to include
2784 * @param string $classes A space-separated list of CSS classes
2785 * @return string A template fragment for a notification
2787 public function notification($message, $classes = 'notifyproblem') {
2788 $message = clean_text($message);
2789 if ($classes === 'notifysuccess') {
2790 return "++ $message ++\n";
2792 return "!! $message !!\n";
2798 * A renderer that generates output for ajax scripts.
2800 * This renderer prevents accidental sends back only json
2801 * encoded error messages, all other output is ignored.
2803 * @copyright 2010 Petr Skoda
2804 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2805 * @since Moodle 2.0
2806 * @package core
2807 * @category output
2809 class core_renderer_ajax extends core_renderer {
2812 * Returns a template fragment representing a fatal error.
2814 * @param string $message The message to output
2815 * @param string $moreinfourl URL where more info can be found about the error
2816 * @param string $link Link for the Continue button
2817 * @param array $backtrace The execution backtrace
2818 * @param string $debuginfo Debugging information
2819 * @return string A template fragment for a fatal error
2821 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2822 global $CFG;
2824 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2826 $e = new stdClass();
2827 $e->error = $message;
2828 $e->stacktrace = NULL;
2829 $e->debuginfo = NULL;
2830 $e->reproductionlink = NULL;
2831 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
2832 $e->reproductionlink = $link;
2833 if (!empty($debuginfo)) {
2834 $e->debuginfo = $debuginfo;
2836 if (!empty($backtrace)) {
2837 $e->stacktrace = format_backtrace($backtrace, true);
2840 $this->header();
2841 return json_encode($e);
2845 * Used to display a notification.
2846 * For the AJAX notifications are discarded.
2848 * @param string $message
2849 * @param string $classes
2851 public function notification($message, $classes = 'notifyproblem') {}
2854 * Used to display a redirection message.
2855 * AJAX redirections should not occur and as such redirection messages
2856 * are discarded.
2858 * @param moodle_url|string $encodedurl
2859 * @param string $message
2860 * @param int $delay
2861 * @param bool $debugdisableredirect
2863 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
2866 * Prepares the start of an AJAX output.
2868 public function header() {
2869 // unfortunately YUI iframe upload does not support application/json
2870 if (!empty($_FILES)) {
2871 @header('Content-type: text/plain; charset=utf-8');
2872 } else {
2873 @header('Content-type: application/json; charset=utf-8');
2876 // Headers to make it not cacheable and json
2877 @header('Cache-Control: no-store, no-cache, must-revalidate');
2878 @header('Cache-Control: post-check=0, pre-check=0', false);
2879 @header('Pragma: no-cache');
2880 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2881 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2882 @header('Accept-Ranges: none');
2886 * There is no footer for an AJAX request, however we must override the
2887 * footer method to prevent the default footer.
2889 public function footer() {}
2892 * No need for headers in an AJAX request... this should never happen.
2893 * @param string $text
2894 * @param int $level
2895 * @param string $classes
2896 * @param string $id
2898 public function heading($text, $level = 2, $classes = 'main', $id = null) {}