weekly release 3.2.1+
[moodle.git] / lib / outputrenderers.php
blob8993bf7abef63d6dc2493d36aa60f549b1272e8a
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 * @var Mustache_Engine $mustache The mustache template compiler
72 private $mustache;
74 /**
75 * Return an instance of the mustache class.
77 * @since 2.9
78 * @return Mustache_Engine
80 protected function get_mustache() {
81 global $CFG;
83 if ($this->mustache === null) {
84 $themename = $this->page->theme->name;
85 $themerev = theme_get_revision();
87 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
89 $loader = new \core\output\mustache_filesystem_loader();
90 $stringhelper = new \core\output\mustache_string_helper();
91 $quotehelper = new \core\output\mustache_quote_helper();
92 $jshelper = new \core\output\mustache_javascript_helper($this->page->requires);
93 $pixhelper = new \core\output\mustache_pix_helper($this);
95 // We only expose the variables that are exposed to JS templates.
96 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
98 $helpers = array('config' => $safeconfig,
99 'str' => array($stringhelper, 'str'),
100 'quote' => array($quotehelper, 'quote'),
101 'js' => array($jshelper, 'help'),
102 'pix' => array($pixhelper, 'pix'));
104 $this->mustache = new Mustache_Engine(array(
105 'cache' => $cachedir,
106 'escape' => 's',
107 'loader' => $loader,
108 'helpers' => $helpers,
109 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS]));
113 return $this->mustache;
118 * Constructor
120 * The constructor takes two arguments. The first is the page that the renderer
121 * has been created to assist with, and the second is the target.
122 * The target is an additional identifier that can be used to load different
123 * renderers for different options.
125 * @param moodle_page $page the page we are doing output for.
126 * @param string $target one of rendering target constants
128 public function __construct(moodle_page $page, $target) {
129 $this->opencontainers = $page->opencontainers;
130 $this->page = $page;
131 $this->target = $target;
135 * Renders a template by name with the given context.
137 * The provided data needs to be array/stdClass made up of only simple types.
138 * Simple types are array,stdClass,bool,int,float,string
140 * @since 2.9
141 * @param array|stdClass $context Context containing data for the template.
142 * @return string|boolean
144 public function render_from_template($templatename, $context) {
145 static $templatecache = array();
146 $mustache = $this->get_mustache();
148 try {
149 // Grab a copy of the existing helper to be restored later.
150 $uniqidhelper = $mustache->getHelper('uniqid');
151 } catch (Mustache_Exception_UnknownHelperException $e) {
152 // Helper doesn't exist.
153 $uniqidhelper = null;
156 // Provide 1 random value that will not change within a template
157 // but will be different from template to template. This is useful for
158 // e.g. aria attributes that only work with id attributes and must be
159 // unique in a page.
160 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
161 if (isset($templatecache[$templatename])) {
162 $template = $templatecache[$templatename];
163 } else {
164 try {
165 $template = $mustache->loadTemplate($templatename);
166 $templatecache[$templatename] = $template;
167 } catch (Mustache_Exception_UnknownTemplateException $e) {
168 throw new moodle_exception('Unknown template: ' . $templatename);
172 $renderedtemplate = trim($template->render($context));
174 // If we had an existing uniqid helper then we need to restore it to allow
175 // handle nested calls of render_from_template.
176 if ($uniqidhelper) {
177 $mustache->addHelper('uniqid', $uniqidhelper);
180 return $renderedtemplate;
185 * Returns rendered widget.
187 * The provided widget needs to be an object that extends the renderable
188 * interface.
189 * If will then be rendered by a method based upon the classname for the widget.
190 * For instance a widget of class `crazywidget` will be rendered by a protected
191 * render_crazywidget method of this renderer.
193 * @param renderable $widget instance with renderable interface
194 * @return string
196 public function render(renderable $widget) {
197 $classname = get_class($widget);
198 // Strip namespaces.
199 $classname = preg_replace('/^.*\\\/', '', $classname);
200 // Remove _renderable suffixes
201 $classname = preg_replace('/_renderable$/', '', $classname);
203 $rendermethod = 'render_'.$classname;
204 if (method_exists($this, $rendermethod)) {
205 return $this->$rendermethod($widget);
207 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
211 * Adds a JS action for the element with the provided id.
213 * This method adds a JS event for the provided component action to the page
214 * and then returns the id that the event has been attached to.
215 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
217 * @param component_action $action
218 * @param string $id
219 * @return string id of element, either original submitted or random new if not supplied
221 public function add_action_handler(component_action $action, $id = null) {
222 if (!$id) {
223 $id = html_writer::random_id($action->event);
225 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
226 return $id;
230 * Returns true is output has already started, and false if not.
232 * @return boolean true if the header has been printed.
234 public function has_started() {
235 return $this->page->state >= moodle_page::STATE_IN_BODY;
239 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
241 * @param mixed $classes Space-separated string or array of classes
242 * @return string HTML class attribute value
244 public static function prepare_classes($classes) {
245 if (is_array($classes)) {
246 return implode(' ', array_unique($classes));
248 return $classes;
252 * Return the moodle_url for an image.
254 * The exact image location and extension is determined
255 * automatically by searching for gif|png|jpg|jpeg, please
256 * note there can not be diferent images with the different
257 * extension. The imagename is for historical reasons
258 * a relative path name, it may be changed later for core
259 * images. It is recommended to not use subdirectories
260 * in plugin and theme pix directories.
262 * There are three types of images:
263 * 1/ theme images - stored in theme/mytheme/pix/,
264 * use component 'theme'
265 * 2/ core images - stored in /pix/,
266 * overridden via theme/mytheme/pix_core/
267 * 3/ plugin images - stored in mod/mymodule/pix,
268 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
269 * example: pix_url('comment', 'mod_glossary')
271 * @param string $imagename the pathname of the image
272 * @param string $component full plugin name (aka component) or 'theme'
273 * @return moodle_url
275 public function pix_url($imagename, $component = 'moodle') {
276 return $this->page->theme->pix_url($imagename, $component);
280 * Return the site's logo URL, if any.
282 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
283 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
284 * @return moodle_url|false
286 public function get_logo_url($maxwidth = null, $maxheight = 200) {
287 global $CFG;
288 $logo = get_config('core_admin', 'logo');
289 if (empty($logo)) {
290 return false;
293 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
294 // It's not worth the overhead of detecting and serving 2 different images based on the device.
296 // Hide the requested size in the file path.
297 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
299 // Use $CFG->themerev to prevent browser caching when the file changes.
300 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
301 theme_get_revision(), $logo);
305 * Return the site's compact logo URL, if any.
307 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
308 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
309 * @return moodle_url|false
311 public function get_compact_logo_url($maxwidth = 100, $maxheight = 100) {
312 global $CFG;
313 $logo = get_config('core_admin', 'logocompact');
314 if (empty($logo)) {
315 return false;
318 // Hide the requested size in the file path.
319 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
321 // Use $CFG->themerev to prevent browser caching when the file changes.
322 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
323 theme_get_revision(), $logo);
330 * Basis for all plugin renderers.
332 * @copyright Petr Skoda (skodak)
333 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
334 * @since Moodle 2.0
335 * @package core
336 * @category output
338 class plugin_renderer_base extends renderer_base {
341 * @var renderer_base|core_renderer A reference to the current renderer.
342 * The renderer provided here will be determined by the page but will in 90%
343 * of cases by the {@link core_renderer}
345 protected $output;
348 * Constructor method, calls the parent constructor
350 * @param moodle_page $page
351 * @param string $target one of rendering target constants
353 public function __construct(moodle_page $page, $target) {
354 if (empty($target) && $page->pagelayout === 'maintenance') {
355 // If the page is using the maintenance layout then we're going to force the target to maintenance.
356 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
357 // unavailable for this page layout.
358 $target = RENDERER_TARGET_MAINTENANCE;
360 $this->output = $page->get_renderer('core', null, $target);
361 parent::__construct($page, $target);
365 * Renders the provided widget and returns the HTML to display it.
367 * @param renderable $widget instance with renderable interface
368 * @return string
370 public function render(renderable $widget) {
371 $classname = get_class($widget);
372 // Strip namespaces.
373 $classname = preg_replace('/^.*\\\/', '', $classname);
374 // Keep a copy at this point, we may need to look for a deprecated method.
375 $deprecatedmethod = 'render_'.$classname;
376 // Remove _renderable suffixes
377 $classname = preg_replace('/_renderable$/', '', $classname);
379 $rendermethod = 'render_'.$classname;
380 if (method_exists($this, $rendermethod)) {
381 return $this->$rendermethod($widget);
383 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
384 // This is exactly where we don't want to be.
385 // If you have arrived here you have a renderable component within your plugin that has the name
386 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
387 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
388 // and the _renderable suffix now gets removed when looking for a render method.
389 // You need to change your renderers render_blah_renderable to render_blah.
390 // Until you do this it will not be possible for a theme to override the renderer to override your method.
391 // Please do it ASAP.
392 static $debugged = array();
393 if (!isset($debugged[$deprecatedmethod])) {
394 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
395 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
396 $debugged[$deprecatedmethod] = true;
398 return $this->$deprecatedmethod($widget);
400 // pass to core renderer if method not found here
401 return $this->output->render($widget);
405 * Magic method used to pass calls otherwise meant for the standard renderer
406 * to it to ensure we don't go causing unnecessary grief.
408 * @param string $method
409 * @param array $arguments
410 * @return mixed
412 public function __call($method, $arguments) {
413 if (method_exists('renderer_base', $method)) {
414 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
416 if (method_exists($this->output, $method)) {
417 return call_user_func_array(array($this->output, $method), $arguments);
418 } else {
419 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
426 * The standard implementation of the core_renderer interface.
428 * @copyright 2009 Tim Hunt
429 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
430 * @since Moodle 2.0
431 * @package core
432 * @category output
434 class core_renderer extends renderer_base {
436 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
437 * in layout files instead.
438 * @deprecated
439 * @var string used in {@link core_renderer::header()}.
441 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
444 * @var string Used to pass information from {@link core_renderer::doctype()} to
445 * {@link core_renderer::standard_head_html()}.
447 protected $contenttype;
450 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
451 * with {@link core_renderer::header()}.
453 protected $metarefreshtag = '';
456 * @var string Unique token for the closing HTML
458 protected $unique_end_html_token;
461 * @var string Unique token for performance information
463 protected $unique_performance_info_token;
466 * @var string Unique token for the main content.
468 protected $unique_main_content_token;
471 * Constructor
473 * @param moodle_page $page the page we are doing output for.
474 * @param string $target one of rendering target constants
476 public function __construct(moodle_page $page, $target) {
477 $this->opencontainers = $page->opencontainers;
478 $this->page = $page;
479 $this->target = $target;
481 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
482 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
483 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
487 * Get the DOCTYPE declaration that should be used with this page. Designed to
488 * be called in theme layout.php files.
490 * @return string the DOCTYPE declaration that should be used.
492 public function doctype() {
493 if ($this->page->theme->doctype === 'html5') {
494 $this->contenttype = 'text/html; charset=utf-8';
495 return "<!DOCTYPE html>\n";
497 } else if ($this->page->theme->doctype === 'xhtml5') {
498 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
499 return "<!DOCTYPE html>\n";
501 } else {
502 // legacy xhtml 1.0
503 $this->contenttype = 'text/html; charset=utf-8';
504 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
509 * The attributes that should be added to the <html> tag. Designed to
510 * be called in theme layout.php files.
512 * @return string HTML fragment.
514 public function htmlattributes() {
515 $return = get_html_lang(true);
516 if ($this->page->theme->doctype !== 'html5') {
517 $return .= ' xmlns="http://www.w3.org/1999/xhtml"';
519 return $return;
523 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
524 * that should be included in the <head> tag. Designed to be called in theme
525 * layout.php files.
527 * @return string HTML fragment.
529 public function standard_head_html() {
530 global $CFG, $SESSION;
532 // Before we output any content, we need to ensure that certain
533 // page components are set up.
535 // Blocks must be set up early as they may require javascript which
536 // has to be included in the page header before output is created.
537 foreach ($this->page->blocks->get_regions() as $region) {
538 $this->page->blocks->ensure_content_created($region, $this);
541 $output = '';
543 // Allow a url_rewrite plugin to setup any dynamic head content.
544 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
545 $class = $CFG->urlrewriteclass;
546 $output .= $class::html_head_setup();
549 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
550 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
551 // This is only set by the {@link redirect()} method
552 $output .= $this->metarefreshtag;
554 // Check if a periodic refresh delay has been set and make sure we arn't
555 // already meta refreshing
556 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
557 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
560 // Smart App Banners meta tag is only displayed if mobile services are enabled and configured.
561 if (!empty($CFG->enablemobilewebservice)) {
562 $mobilesettings = get_config('tool_mobile');
563 if (!empty($mobilesettings->enablesmartappbanners) and !empty($mobilesettings->iosappid)) {
564 $output .= '<meta name="apple-itunes-app" content="app-id=' . s($mobilesettings->iosappid) . ', ';
565 $output .= 'app-argument=' . $this->page->url->out() . '"/>';
569 // Set up help link popups for all links with the helptooltip class
570 $this->page->requires->js_init_call('M.util.help_popups.setup');
572 // Setup help icon overlays.
573 $this->page->requires->yui_module('moodle-core-popuphelp', 'M.core.init_popuphelp');
574 $this->page->requires->strings_for_js(array(
575 'morehelp',
576 'loadinghelp',
577 ), 'moodle');
579 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
581 $focus = $this->page->focuscontrol;
582 if (!empty($focus)) {
583 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
584 // This is a horrifically bad way to handle focus but it is passed in
585 // through messy formslib::moodleform
586 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
587 } else if (strpos($focus, '.')!==false) {
588 // Old style of focus, bad way to do it
589 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);
590 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
591 } else {
592 // Focus element with given id
593 $this->page->requires->js_function_call('focuscontrol', array($focus));
597 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
598 // any other custom CSS can not be overridden via themes and is highly discouraged
599 $urls = $this->page->theme->css_urls($this->page);
600 foreach ($urls as $url) {
601 $this->page->requires->css_theme($url);
604 // Get the theme javascript head and footer
605 if ($jsurl = $this->page->theme->javascript_url(true)) {
606 $this->page->requires->js($jsurl, true);
608 if ($jsurl = $this->page->theme->javascript_url(false)) {
609 $this->page->requires->js($jsurl);
612 // Get any HTML from the page_requirements_manager.
613 $output .= $this->page->requires->get_head_code($this->page, $this);
615 // List alternate versions.
616 foreach ($this->page->alternateversions as $type => $alt) {
617 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
618 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
621 if (!empty($CFG->additionalhtmlhead)) {
622 $output .= "\n".$CFG->additionalhtmlhead;
625 return $output;
629 * The standard tags (typically skip links) that should be output just inside
630 * the start of the <body> tag. Designed to be called in theme layout.php files.
632 * @return string HTML fragment.
634 public function standard_top_of_body_html() {
635 global $CFG;
636 $output = $this->page->requires->get_top_of_body_code($this);
637 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
638 $output .= "\n".$CFG->additionalhtmltopofbody;
640 $output .= $this->maintenance_warning();
641 return $output;
645 * Scheduled maintenance warning message.
647 * Note: This is a nasty hack to display maintenance notice, this should be moved
648 * to some general notification area once we have it.
650 * @return string
652 public function maintenance_warning() {
653 global $CFG;
655 $output = '';
656 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
657 $timeleft = $CFG->maintenance_later - time();
658 // If timeleft less than 30 sec, set the class on block to error to highlight.
659 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
660 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-a-1 alert');
661 $a = new stdClass();
662 $a->hour = (int)($timeleft / 3600);
663 $a->min = (int)(($timeleft / 60) % 60);
664 $a->sec = (int)($timeleft % 60);
665 if ($a->hour > 0) {
666 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
667 } else {
668 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
671 $output .= $this->box_end();
672 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
673 array(array('timeleftinsec' => $timeleft)));
674 $this->page->requires->strings_for_js(
675 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
676 'admin');
678 return $output;
682 * The standard tags (typically performance information and validation links,
683 * if we are in developer debug mode) that should be output in the footer area
684 * of the page. Designed to be called in theme layout.php files.
686 * @return string HTML fragment.
688 public function standard_footer_html() {
689 global $CFG, $SCRIPT;
691 if (during_initial_install()) {
692 // Debugging info can not work before install is finished,
693 // in any case we do not want any links during installation!
694 return '';
697 // This function is normally called from a layout.php file in {@link core_renderer::header()}
698 // but some of the content won't be known until later, so we return a placeholder
699 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
700 $output = $this->unique_performance_info_token;
701 if ($this->page->devicetypeinuse == 'legacy') {
702 // The legacy theme is in use print the notification
703 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
706 // Get links to switch device types (only shown for users not on a default device)
707 $output .= $this->theme_switch_links();
709 if (!empty($CFG->debugpageinfo)) {
710 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
712 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
713 // Add link to profiling report if necessary
714 if (function_exists('profiling_is_running') && profiling_is_running()) {
715 $txt = get_string('profiledscript', 'admin');
716 $title = get_string('profiledscriptview', 'admin');
717 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
718 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
719 $output .= '<div class="profilingfooter">' . $link . '</div>';
721 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
722 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
723 $output .= '<div class="purgecaches">' .
724 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
726 if (!empty($CFG->debugvalidators)) {
727 // NOTE: this is not a nice hack, $PAGE->url is not always accurate and $FULLME neither, it is not a bug if it fails. --skodak
728 $output .= '<div class="validators"><ul class="list-unstyled m-l-1">
729 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
730 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
731 <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>
732 </ul></div>';
734 return $output;
738 * Returns standard main content placeholder.
739 * Designed to be called in theme layout.php files.
741 * @return string HTML fragment.
743 public function main_content() {
744 // This is here because it is the only place we can inject the "main" role over the entire main content area
745 // without requiring all theme's to manually do it, and without creating yet another thing people need to
746 // remember in the theme.
747 // This is an unfortunate hack. DO NO EVER add anything more here.
748 // DO NOT add classes.
749 // DO NOT add an id.
750 return '<div role="main">'.$this->unique_main_content_token.'</div>';
754 * The standard tags (typically script tags that are not needed earlier) that
755 * should be output after everything else. Designed to be called in theme layout.php files.
757 * @return string HTML fragment.
759 public function standard_end_of_body_html() {
760 global $CFG;
762 // This function is normally called from a layout.php file in {@link core_renderer::header()}
763 // but some of the content won't be known until later, so we return a placeholder
764 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
765 $output = '';
766 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
767 $output .= "\n".$CFG->additionalhtmlfooter;
769 $output .= $this->unique_end_html_token;
770 return $output;
774 * Return the standard string that says whether you are logged in (and switched
775 * roles/logged in as another user).
776 * @param bool $withlinks if false, then don't include any links in the HTML produced.
777 * If not set, the default is the nologinlinks option from the theme config.php file,
778 * and if that is not set, then links are included.
779 * @return string HTML fragment.
781 public function login_info($withlinks = null) {
782 global $USER, $CFG, $DB, $SESSION;
784 if (during_initial_install()) {
785 return '';
788 if (is_null($withlinks)) {
789 $withlinks = empty($this->page->layout_options['nologinlinks']);
792 $course = $this->page->course;
793 if (\core\session\manager::is_loggedinas()) {
794 $realuser = \core\session\manager::get_realuser();
795 $fullname = fullname($realuser, true);
796 if ($withlinks) {
797 $loginastitle = get_string('loginas');
798 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
799 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
800 } else {
801 $realuserinfo = " [$fullname] ";
803 } else {
804 $realuserinfo = '';
807 $loginpage = $this->is_login_page();
808 $loginurl = get_login_url();
810 if (empty($course->id)) {
811 // $course->id is not defined during installation
812 return '';
813 } else if (isloggedin()) {
814 $context = context_course::instance($course->id);
816 $fullname = fullname($USER, true);
817 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
818 if ($withlinks) {
819 $linktitle = get_string('viewprofile');
820 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
821 } else {
822 $username = $fullname;
824 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
825 if ($withlinks) {
826 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
827 } else {
828 $username .= " from {$idprovider->name}";
831 if (isguestuser()) {
832 $loggedinas = $realuserinfo.get_string('loggedinasguest');
833 if (!$loginpage && $withlinks) {
834 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
836 } else if (is_role_switched($course->id)) { // Has switched roles
837 $rolename = '';
838 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
839 $rolename = ': '.role_get_name($role, $context);
841 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
842 if ($withlinks) {
843 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
844 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
846 } else {
847 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
848 if ($withlinks) {
849 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
852 } else {
853 $loggedinas = get_string('loggedinnot', 'moodle');
854 if (!$loginpage && $withlinks) {
855 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
859 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
861 if (isset($SESSION->justloggedin)) {
862 unset($SESSION->justloggedin);
863 if (!empty($CFG->displayloginfailures)) {
864 if (!isguestuser()) {
865 // Include this file only when required.
866 require_once($CFG->dirroot . '/user/lib.php');
867 if ($count = user_count_login_failures($USER)) {
868 $loggedinas .= '<div class="loginfailures">';
869 $a = new stdClass();
870 $a->attempts = $count;
871 $loggedinas .= get_string('failedloginattempts', '', $a);
872 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
873 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
874 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
876 $loggedinas .= '</div>';
882 return $loggedinas;
886 * Check whether the current page is a login page.
888 * @since Moodle 2.9
889 * @return bool
891 protected function is_login_page() {
892 // This is a real bit of a hack, but its a rarety that we need to do something like this.
893 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
894 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
895 return in_array(
896 $this->page->url->out_as_local_url(false, array()),
897 array(
898 '/login/index.php',
899 '/login/forgot_password.php',
905 * Return the 'back' link that normally appears in the footer.
907 * @return string HTML fragment.
909 public function home_link() {
910 global $CFG, $SITE;
912 if ($this->page->pagetype == 'site-index') {
913 // Special case for site home page - please do not remove
914 return '<div class="sitelink">' .
915 '<a title="Moodle" href="http://moodle.org/">' .
916 '<img src="' . $this->pix_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
918 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
919 // Special case for during install/upgrade.
920 return '<div class="sitelink">'.
921 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
922 '<img src="' . $this->pix_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
924 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
925 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
926 get_string('home') . '</a></div>';
928 } else {
929 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
930 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
935 * Redirects the user by any means possible given the current state
937 * This function should not be called directly, it should always be called using
938 * the redirect function in lib/weblib.php
940 * The redirect function should really only be called before page output has started
941 * however it will allow itself to be called during the state STATE_IN_BODY
943 * @param string $encodedurl The URL to send to encoded if required
944 * @param string $message The message to display to the user if any
945 * @param int $delay The delay before redirecting a user, if $message has been
946 * set this is a requirement and defaults to 3, set to 0 no delay
947 * @param boolean $debugdisableredirect this redirect has been disabled for
948 * debugging purposes. Display a message that explains, and don't
949 * trigger the redirect.
950 * @param string $messagetype The type of notification to show the message in.
951 * See constants on \core\output\notification.
952 * @return string The HTML to display to the user before dying, may contain
953 * meta refresh, javascript refresh, and may have set header redirects
955 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
956 $messagetype = \core\output\notification::NOTIFY_INFO) {
957 global $CFG;
958 $url = str_replace('&amp;', '&', $encodedurl);
960 switch ($this->page->state) {
961 case moodle_page::STATE_BEFORE_HEADER :
962 // No output yet it is safe to delivery the full arsenal of redirect methods
963 if (!$debugdisableredirect) {
964 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
965 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
966 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
968 $output = $this->header();
969 break;
970 case moodle_page::STATE_PRINTING_HEADER :
971 // We should hopefully never get here
972 throw new coding_exception('You cannot redirect while printing the page header');
973 break;
974 case moodle_page::STATE_IN_BODY :
975 // We really shouldn't be here but we can deal with this
976 debugging("You should really redirect before you start page output");
977 if (!$debugdisableredirect) {
978 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
980 $output = $this->opencontainers->pop_all_but_last();
981 break;
982 case moodle_page::STATE_DONE :
983 // Too late to be calling redirect now
984 throw new coding_exception('You cannot redirect after the entire page has been generated');
985 break;
987 $output .= $this->notification($message, $messagetype);
988 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
989 if ($debugdisableredirect) {
990 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
992 $output .= $this->footer();
993 return $output;
997 * Start output by sending the HTTP headers, and printing the HTML <head>
998 * and the start of the <body>.
1000 * To control what is printed, you should set properties on $PAGE. If you
1001 * are familiar with the old {@link print_header()} function from Moodle 1.9
1002 * you will find that there are properties on $PAGE that correspond to most
1003 * of the old parameters to could be passed to print_header.
1005 * Not that, in due course, the remaining $navigation, $menu parameters here
1006 * will be replaced by more properties of $PAGE, but that is still to do.
1008 * @return string HTML that you must output this, preferably immediately.
1010 public function header() {
1011 global $USER, $CFG, $SESSION;
1013 if (\core\session\manager::is_loggedinas()) {
1014 $this->page->add_body_class('userloggedinas');
1017 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1018 require_once($CFG->dirroot . '/user/lib.php');
1019 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1020 if ($count = user_count_login_failures($USER, false)) {
1021 $this->page->add_body_class('loginfailures');
1025 // If the user is logged in, and we're not in initial install,
1026 // check to see if the user is role-switched and add the appropriate
1027 // CSS class to the body element.
1028 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1029 $this->page->add_body_class('userswitchedrole');
1032 // Give themes a chance to init/alter the page object.
1033 $this->page->theme->init_page($this->page);
1035 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1037 // Find the appropriate page layout file, based on $this->page->pagelayout.
1038 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1039 // Render the layout using the layout file.
1040 $rendered = $this->render_page_layout($layoutfile);
1042 // Slice the rendered output into header and footer.
1043 $cutpos = strpos($rendered, $this->unique_main_content_token);
1044 if ($cutpos === false) {
1045 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1046 $token = self::MAIN_CONTENT_TOKEN;
1047 } else {
1048 $token = $this->unique_main_content_token;
1051 if ($cutpos === false) {
1052 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.');
1054 $header = substr($rendered, 0, $cutpos);
1055 $footer = substr($rendered, $cutpos + strlen($token));
1057 if (empty($this->contenttype)) {
1058 debugging('The page layout file did not call $OUTPUT->doctype()');
1059 $header = $this->doctype() . $header;
1062 // If this theme version is below 2.4 release and this is a course view page
1063 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1064 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1065 // check if course content header/footer have not been output during render of theme layout
1066 $coursecontentheader = $this->course_content_header(true);
1067 $coursecontentfooter = $this->course_content_footer(true);
1068 if (!empty($coursecontentheader)) {
1069 // display debug message and add header and footer right above and below main content
1070 // Please note that course header and footer (to be displayed above and below the whole page)
1071 // are not displayed in this case at all.
1072 // Besides the content header and footer are not displayed on any other course page
1073 debugging('The current theme is not optimised for 2.4, the course-specific header and footer defined in course format will not be output', DEBUG_DEVELOPER);
1074 $header .= $coursecontentheader;
1075 $footer = $coursecontentfooter. $footer;
1079 send_headers($this->contenttype, $this->page->cacheable);
1081 $this->opencontainers->push('header/footer', $footer);
1082 $this->page->set_state(moodle_page::STATE_IN_BODY);
1084 return $header . $this->skip_link_target('maincontent');
1088 * Renders and outputs the page layout file.
1090 * This is done by preparing the normal globals available to a script, and
1091 * then including the layout file provided by the current theme for the
1092 * requested layout.
1094 * @param string $layoutfile The name of the layout file
1095 * @return string HTML code
1097 protected function render_page_layout($layoutfile) {
1098 global $CFG, $SITE, $USER;
1099 // The next lines are a bit tricky. The point is, here we are in a method
1100 // of a renderer class, and this object may, or may not, be the same as
1101 // the global $OUTPUT object. When rendering the page layout file, we want to use
1102 // this object. However, people writing Moodle code expect the current
1103 // renderer to be called $OUTPUT, not $this, so define a variable called
1104 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1105 $OUTPUT = $this;
1106 $PAGE = $this->page;
1107 $COURSE = $this->page->course;
1109 ob_start();
1110 include($layoutfile);
1111 $rendered = ob_get_contents();
1112 ob_end_clean();
1113 return $rendered;
1117 * Outputs the page's footer
1119 * @return string HTML fragment
1121 public function footer() {
1122 global $CFG, $DB, $PAGE;
1124 $output = $this->container_end_all(true);
1126 $footer = $this->opencontainers->pop('header/footer');
1128 if (debugging() and $DB and $DB->is_transaction_started()) {
1129 // TODO: MDL-20625 print warning - transaction will be rolled back
1132 // Provide some performance info if required
1133 $performanceinfo = '';
1134 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1135 $perf = get_performance_info();
1136 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1137 $performanceinfo = $perf['html'];
1141 // We always want performance data when running a performance test, even if the user is redirected to another page.
1142 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1143 $footer = $this->unique_performance_info_token . $footer;
1145 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1147 // Only show notifications when we have a $PAGE context id.
1148 if (!empty($PAGE->context->id)) {
1149 $this->page->requires->js_call_amd('core/notification', 'init', array(
1150 $PAGE->context->id,
1151 \core\notification::fetch_as_array($this)
1154 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1156 $this->page->set_state(moodle_page::STATE_DONE);
1158 return $output . $footer;
1162 * Close all but the last open container. This is useful in places like error
1163 * handling, where you want to close all the open containers (apart from <body>)
1164 * before outputting the error message.
1166 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1167 * developer debug warning if it isn't.
1168 * @return string the HTML required to close any open containers inside <body>.
1170 public function container_end_all($shouldbenone = false) {
1171 return $this->opencontainers->pop_all_but_last($shouldbenone);
1175 * Returns course-specific information to be output immediately above content on any course page
1176 * (for the current course)
1178 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1179 * @return string
1181 public function course_content_header($onlyifnotcalledbefore = false) {
1182 global $CFG;
1183 static $functioncalled = false;
1184 if ($functioncalled && $onlyifnotcalledbefore) {
1185 // we have already output the content header
1186 return '';
1189 // Output any session notification.
1190 $notifications = \core\notification::fetch();
1192 $bodynotifications = '';
1193 foreach ($notifications as $notification) {
1194 $bodynotifications .= $this->render_from_template(
1195 $notification->get_template_name(),
1196 $notification->export_for_template($this)
1200 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1202 if ($this->page->course->id == SITEID) {
1203 // return immediately and do not include /course/lib.php if not necessary
1204 return $output;
1207 require_once($CFG->dirroot.'/course/lib.php');
1208 $functioncalled = true;
1209 $courseformat = course_get_format($this->page->course);
1210 if (($obj = $courseformat->course_content_header()) !== null) {
1211 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1213 return $output;
1217 * Returns course-specific information to be output immediately below content on any course page
1218 * (for the current course)
1220 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1221 * @return string
1223 public function course_content_footer($onlyifnotcalledbefore = false) {
1224 global $CFG;
1225 if ($this->page->course->id == SITEID) {
1226 // return immediately and do not include /course/lib.php if not necessary
1227 return '';
1229 static $functioncalled = false;
1230 if ($functioncalled && $onlyifnotcalledbefore) {
1231 // we have already output the content footer
1232 return '';
1234 $functioncalled = true;
1235 require_once($CFG->dirroot.'/course/lib.php');
1236 $courseformat = course_get_format($this->page->course);
1237 if (($obj = $courseformat->course_content_footer()) !== null) {
1238 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1240 return '';
1244 * Returns course-specific information to be output on any course page in the header area
1245 * (for the current course)
1247 * @return string
1249 public function course_header() {
1250 global $CFG;
1251 if ($this->page->course->id == SITEID) {
1252 // return immediately and do not include /course/lib.php if not necessary
1253 return '';
1255 require_once($CFG->dirroot.'/course/lib.php');
1256 $courseformat = course_get_format($this->page->course);
1257 if (($obj = $courseformat->course_header()) !== null) {
1258 return $courseformat->get_renderer($this->page)->render($obj);
1260 return '';
1264 * Returns course-specific information to be output on any course page in the footer area
1265 * (for the current course)
1267 * @return string
1269 public function course_footer() {
1270 global $CFG;
1271 if ($this->page->course->id == SITEID) {
1272 // return immediately and do not include /course/lib.php if not necessary
1273 return '';
1275 require_once($CFG->dirroot.'/course/lib.php');
1276 $courseformat = course_get_format($this->page->course);
1277 if (($obj = $courseformat->course_footer()) !== null) {
1278 return $courseformat->get_renderer($this->page)->render($obj);
1280 return '';
1284 * Returns lang menu or '', this method also checks forcing of languages in courses.
1286 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1288 * @return string The lang menu HTML or empty string
1290 public function lang_menu() {
1291 global $CFG;
1293 if (empty($CFG->langmenu)) {
1294 return '';
1297 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1298 // do not show lang menu if language forced
1299 return '';
1302 $currlang = current_language();
1303 $langs = get_string_manager()->get_list_of_translations();
1305 if (count($langs) < 2) {
1306 return '';
1309 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1310 $s->label = get_accesshide(get_string('language'));
1311 $s->class = 'langmenu';
1312 return $this->render($s);
1316 * Output the row of editing icons for a block, as defined by the controls array.
1318 * @param array $controls an array like {@link block_contents::$controls}.
1319 * @param string $blockid The ID given to the block.
1320 * @return string HTML fragment.
1322 public function block_controls($actions, $blockid = null) {
1323 global $CFG;
1324 if (empty($actions)) {
1325 return '';
1327 $menu = new action_menu($actions);
1328 if ($blockid !== null) {
1329 $menu->set_owner_selector('#'.$blockid);
1331 $menu->set_constraint('.block-region');
1332 $menu->attributes['class'] .= ' block-control-actions commands';
1333 return $this->render($menu);
1337 * Renders an action menu component.
1339 * ARIA references:
1340 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1341 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1343 * @param action_menu $menu
1344 * @return string HTML
1346 public function render_action_menu(action_menu $menu) {
1347 $context = $menu->export_for_template($this);
1348 return $this->render_from_template('core/action_menu', $context);
1352 * Renders an action_menu_link item.
1354 * @param action_menu_link $action
1355 * @return string HTML fragment
1357 protected function render_action_menu_link(action_menu_link $action) {
1358 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1362 * Renders a primary action_menu_filler item.
1364 * @param action_menu_link_filler $action
1365 * @return string HTML fragment
1367 protected function render_action_menu_filler(action_menu_filler $action) {
1368 return html_writer::span('&nbsp;', 'filler');
1372 * Renders a primary action_menu_link item.
1374 * @param action_menu_link_primary $action
1375 * @return string HTML fragment
1377 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1378 return $this->render_action_menu_link($action);
1382 * Renders a secondary action_menu_link item.
1384 * @param action_menu_link_secondary $action
1385 * @return string HTML fragment
1387 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1388 return $this->render_action_menu_link($action);
1392 * Prints a nice side block with an optional header.
1394 * The content is described
1395 * by a {@link core_renderer::block_contents} object.
1397 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1398 * <div class="header"></div>
1399 * <div class="content">
1400 * ...CONTENT...
1401 * <div class="footer">
1402 * </div>
1403 * </div>
1404 * <div class="annotation">
1405 * </div>
1406 * </div>
1408 * @param block_contents $bc HTML for the content
1409 * @param string $region the region the block is appearing in.
1410 * @return string the HTML to be output.
1412 public function block(block_contents $bc, $region) {
1413 $bc = clone($bc); // Avoid messing up the object passed in.
1414 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1415 $bc->collapsible = block_contents::NOT_HIDEABLE;
1417 if (!empty($bc->blockinstanceid)) {
1418 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1420 $skiptitle = strip_tags($bc->title);
1421 if ($bc->blockinstanceid && !empty($skiptitle)) {
1422 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1423 } else if (!empty($bc->arialabel)) {
1424 $bc->attributes['aria-label'] = $bc->arialabel;
1426 if ($bc->dockable) {
1427 $bc->attributes['data-dockable'] = 1;
1429 if ($bc->collapsible == block_contents::HIDDEN) {
1430 $bc->add_class('hidden');
1432 if (!empty($bc->controls)) {
1433 $bc->add_class('block_with_controls');
1437 if (empty($skiptitle)) {
1438 $output = '';
1439 $skipdest = '';
1440 } else {
1441 $output = html_writer::link('#sb-'.$bc->skipid, get_string('skipa', 'access', $skiptitle),
1442 array('class' => 'skip skip-block', 'id' => 'fsb-' . $bc->skipid));
1443 $skipdest = html_writer::span('', 'skip-block-to',
1444 array('id' => 'sb-' . $bc->skipid));
1447 $output .= html_writer::start_tag('div', $bc->attributes);
1449 $output .= $this->block_header($bc);
1450 $output .= $this->block_content($bc);
1452 $output .= html_writer::end_tag('div');
1454 $output .= $this->block_annotation($bc);
1456 $output .= $skipdest;
1458 $this->init_block_hider_js($bc);
1459 return $output;
1463 * Produces a header for a block
1465 * @param block_contents $bc
1466 * @return string
1468 protected function block_header(block_contents $bc) {
1470 $title = '';
1471 if ($bc->title) {
1472 $attributes = array();
1473 if ($bc->blockinstanceid) {
1474 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1476 $title = html_writer::tag('h2', $bc->title, $attributes);
1479 $blockid = null;
1480 if (isset($bc->attributes['id'])) {
1481 $blockid = $bc->attributes['id'];
1483 $controlshtml = $this->block_controls($bc->controls, $blockid);
1485 $output = '';
1486 if ($title || $controlshtml) {
1487 $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'));
1489 return $output;
1493 * Produces the content area for a block
1495 * @param block_contents $bc
1496 * @return string
1498 protected function block_content(block_contents $bc) {
1499 $output = html_writer::start_tag('div', array('class' => 'content'));
1500 if (!$bc->title && !$this->block_controls($bc->controls)) {
1501 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1503 $output .= $bc->content;
1504 $output .= $this->block_footer($bc);
1505 $output .= html_writer::end_tag('div');
1507 return $output;
1511 * Produces the footer for a block
1513 * @param block_contents $bc
1514 * @return string
1516 protected function block_footer(block_contents $bc) {
1517 $output = '';
1518 if ($bc->footer) {
1519 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1521 return $output;
1525 * Produces the annotation for a block
1527 * @param block_contents $bc
1528 * @return string
1530 protected function block_annotation(block_contents $bc) {
1531 $output = '';
1532 if ($bc->annotation) {
1533 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1535 return $output;
1539 * Calls the JS require function to hide a block.
1541 * @param block_contents $bc A block_contents object
1543 protected function init_block_hider_js(block_contents $bc) {
1544 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1545 $config = new stdClass;
1546 $config->id = $bc->attributes['id'];
1547 $config->title = strip_tags($bc->title);
1548 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1549 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1550 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1552 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1553 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1558 * Render the contents of a block_list.
1560 * @param array $icons the icon for each item.
1561 * @param array $items the content of each item.
1562 * @return string HTML
1564 public function list_block_contents($icons, $items) {
1565 $row = 0;
1566 $lis = array();
1567 foreach ($items as $key => $string) {
1568 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1569 if (!empty($icons[$key])) { //test if the content has an assigned icon
1570 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1572 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1573 $item .= html_writer::end_tag('li');
1574 $lis[] = $item;
1575 $row = 1 - $row; // Flip even/odd.
1577 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1581 * Output all the blocks in a particular region.
1583 * @param string $region the name of a region on this page.
1584 * @return string the HTML to be output.
1586 public function blocks_for_region($region) {
1587 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1588 $blocks = $this->page->blocks->get_blocks_for_region($region);
1589 $lastblock = null;
1590 $zones = array();
1591 foreach ($blocks as $block) {
1592 $zones[] = $block->title;
1594 $output = '';
1596 foreach ($blockcontents as $bc) {
1597 if ($bc instanceof block_contents) {
1598 $output .= $this->block($bc, $region);
1599 $lastblock = $bc->title;
1600 } else if ($bc instanceof block_move_target) {
1601 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1602 } else {
1603 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1606 return $output;
1610 * Output a place where the block that is currently being moved can be dropped.
1612 * @param block_move_target $target with the necessary details.
1613 * @param array $zones array of areas where the block can be moved to
1614 * @param string $previous the block located before the area currently being rendered.
1615 * @param string $region the name of the region
1616 * @return string the HTML to be output.
1618 public function block_move_target($target, $zones, $previous, $region) {
1619 if ($previous == null) {
1620 if (empty($zones)) {
1621 // There are no zones, probably because there are no blocks.
1622 $regions = $this->page->theme->get_all_block_regions();
1623 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1624 } else {
1625 $position = get_string('moveblockbefore', 'block', $zones[0]);
1627 } else {
1628 $position = get_string('moveblockafter', 'block', $previous);
1630 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1634 * Renders a special html link with attached action
1636 * Theme developers: DO NOT OVERRIDE! Please override function
1637 * {@link core_renderer::render_action_link()} instead.
1639 * @param string|moodle_url $url
1640 * @param string $text HTML fragment
1641 * @param component_action $action
1642 * @param array $attributes associative array of html link attributes + disabled
1643 * @param pix_icon optional pix icon to render with the link
1644 * @return string HTML fragment
1646 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1647 if (!($url instanceof moodle_url)) {
1648 $url = new moodle_url($url);
1650 $link = new action_link($url, $text, $action, $attributes, $icon);
1652 return $this->render($link);
1656 * Renders an action_link object.
1658 * The provided link is renderer and the HTML returned. At the same time the
1659 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1661 * @param action_link $link
1662 * @return string HTML fragment
1664 protected function render_action_link(action_link $link) {
1665 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1669 * Renders an action_icon.
1671 * This function uses the {@link core_renderer::action_link()} method for the
1672 * most part. What it does different is prepare the icon as HTML and use it
1673 * as the link text.
1675 * Theme developers: If you want to change how action links and/or icons are rendered,
1676 * consider overriding function {@link core_renderer::render_action_link()} and
1677 * {@link core_renderer::render_pix_icon()}.
1679 * @param string|moodle_url $url A string URL or moodel_url
1680 * @param pix_icon $pixicon
1681 * @param component_action $action
1682 * @param array $attributes associative array of html link attributes + disabled
1683 * @param bool $linktext show title next to image in link
1684 * @return string HTML fragment
1686 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1687 if (!($url instanceof moodle_url)) {
1688 $url = new moodle_url($url);
1690 $attributes = (array)$attributes;
1692 if (empty($attributes['class'])) {
1693 // let ppl override the class via $options
1694 $attributes['class'] = 'action-icon';
1697 $icon = $this->render($pixicon);
1699 if ($linktext) {
1700 $text = $pixicon->attributes['alt'];
1701 } else {
1702 $text = '';
1705 return $this->action_link($url, $text.$icon, $action, $attributes);
1709 * Print a message along with button choices for Continue/Cancel
1711 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1713 * @param string $message The question to ask the user
1714 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1715 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1716 * @return string HTML fragment
1718 public function confirm($message, $continue, $cancel) {
1719 if ($continue instanceof single_button) {
1720 // ok
1721 $continue->primary = true;
1722 } else if (is_string($continue)) {
1723 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1724 } else if ($continue instanceof moodle_url) {
1725 $continue = new single_button($continue, get_string('continue'), 'post', true);
1726 } else {
1727 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1730 if ($cancel instanceof single_button) {
1731 // ok
1732 } else if (is_string($cancel)) {
1733 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1734 } else if ($cancel instanceof moodle_url) {
1735 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1736 } else {
1737 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1740 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice');
1741 $output .= $this->box_start('modal-content', 'modal-content');
1742 $output .= $this->box_start('modal-header', 'modal-header');
1743 $output .= html_writer::tag('h4', get_string('confirm'));
1744 $output .= $this->box_end();
1745 $output .= $this->box_start('modal-body', 'modal-body');
1746 $output .= html_writer::tag('p', $message);
1747 $output .= $this->box_end();
1748 $output .= $this->box_start('modal-footer', 'modal-footer');
1749 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1750 $output .= $this->box_end();
1751 $output .= $this->box_end();
1752 $output .= $this->box_end();
1753 return $output;
1757 * Returns a form with a single button.
1759 * Theme developers: DO NOT OVERRIDE! Please override function
1760 * {@link core_renderer::render_single_button()} instead.
1762 * @param string|moodle_url $url
1763 * @param string $label button text
1764 * @param string $method get or post submit method
1765 * @param array $options associative array {disabled, title, etc.}
1766 * @return string HTML fragment
1768 public function single_button($url, $label, $method='post', array $options=null) {
1769 if (!($url instanceof moodle_url)) {
1770 $url = new moodle_url($url);
1772 $button = new single_button($url, $label, $method);
1774 foreach ((array)$options as $key=>$value) {
1775 if (array_key_exists($key, $button)) {
1776 $button->$key = $value;
1780 return $this->render($button);
1784 * Renders a single button widget.
1786 * This will return HTML to display a form containing a single button.
1788 * @param single_button $button
1789 * @return string HTML fragment
1791 protected function render_single_button(single_button $button) {
1792 $attributes = array('type' => 'submit',
1793 'value' => $button->label,
1794 'disabled' => $button->disabled ? 'disabled' : null,
1795 'title' => $button->tooltip);
1797 if ($button->actions) {
1798 $id = html_writer::random_id('single_button');
1799 $attributes['id'] = $id;
1800 foreach ($button->actions as $action) {
1801 $this->add_action_handler($action, $id);
1805 // first the input element
1806 $output = html_writer::empty_tag('input', $attributes);
1808 // then hidden fields
1809 $params = $button->url->params();
1810 if ($button->method === 'post') {
1811 $params['sesskey'] = sesskey();
1813 foreach ($params as $var => $val) {
1814 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1817 // then div wrapper for xhtml strictness
1818 $output = html_writer::tag('div', $output);
1820 // now the form itself around it
1821 if ($button->method === 'get') {
1822 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1823 } else {
1824 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1826 if ($url === '') {
1827 $url = '#'; // there has to be always some action
1829 $attributes = array('method' => $button->method,
1830 'action' => $url,
1831 'id' => $button->formid);
1832 $output = html_writer::tag('form', $output, $attributes);
1834 // and finally one more wrapper with class
1835 return html_writer::tag('div', $output, array('class' => $button->class));
1839 * Returns a form with a single select widget.
1841 * Theme developers: DO NOT OVERRIDE! Please override function
1842 * {@link core_renderer::render_single_select()} instead.
1844 * @param moodle_url $url form action target, includes hidden fields
1845 * @param string $name name of selection field - the changing parameter in url
1846 * @param array $options list of options
1847 * @param string $selected selected element
1848 * @param array $nothing
1849 * @param string $formid
1850 * @param array $attributes other attributes for the single select
1851 * @return string HTML fragment
1853 public function single_select($url, $name, array $options, $selected = '',
1854 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
1855 if (!($url instanceof moodle_url)) {
1856 $url = new moodle_url($url);
1858 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1860 if (array_key_exists('label', $attributes)) {
1861 $select->set_label($attributes['label']);
1862 unset($attributes['label']);
1864 $select->attributes = $attributes;
1866 return $this->render($select);
1870 * Returns a dataformat selection and download form
1872 * @param string $label A text label
1873 * @param moodle_url|string $base The download page url
1874 * @param string $name The query param which will hold the type of the download
1875 * @param array $params Extra params sent to the download page
1876 * @return string HTML fragment
1878 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
1880 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
1881 $options = array();
1882 foreach ($formats as $format) {
1883 if ($format->is_enabled()) {
1884 $options[] = array(
1885 'value' => $format->name,
1886 'label' => get_string('dataformat', $format->component),
1890 $hiddenparams = array();
1891 foreach ($params as $key => $value) {
1892 $hiddenparams[] = array(
1893 'name' => $key,
1894 'value' => $value,
1897 $data = array(
1898 'label' => $label,
1899 'base' => $base,
1900 'name' => $name,
1901 'params' => $hiddenparams,
1902 'options' => $options,
1903 'sesskey' => sesskey(),
1904 'submit' => get_string('download'),
1907 return $this->render_from_template('core/dataformat_selector', $data);
1912 * Internal implementation of single_select rendering
1914 * @param single_select $select
1915 * @return string HTML fragment
1917 protected function render_single_select(single_select $select) {
1918 $select = clone($select);
1919 if (empty($select->formid)) {
1920 $select->formid = html_writer::random_id('single_select_f');
1923 $output = '';
1924 $params = $select->url->params();
1925 if ($select->method === 'post') {
1926 $params['sesskey'] = sesskey();
1928 foreach ($params as $name=>$value) {
1929 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1932 if (empty($select->attributes['id'])) {
1933 $select->attributes['id'] = html_writer::random_id('single_select');
1936 if ($select->disabled) {
1937 $select->attributes['disabled'] = 'disabled';
1940 if ($select->tooltip) {
1941 $select->attributes['title'] = $select->tooltip;
1944 $select->attributes['class'] = 'autosubmit';
1945 if ($select->class) {
1946 $select->attributes['class'] .= ' ' . $select->class;
1949 if ($select->label) {
1950 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1953 if ($select->helpicon instanceof help_icon) {
1954 $output .= $this->render($select->helpicon);
1956 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1958 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1959 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1961 $nothing = empty($select->nothing) ? false : key($select->nothing);
1962 $this->page->requires->yui_module('moodle-core-formautosubmit',
1963 'M.core.init_formautosubmit',
1964 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1967 // then div wrapper for xhtml strictness
1968 $output = html_writer::tag('div', $output);
1970 // now the form itself around it
1971 if ($select->method === 'get') {
1972 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1973 } else {
1974 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1976 $formattributes = array('method' => $select->method,
1977 'action' => $url,
1978 'id' => $select->formid);
1979 $output = html_writer::tag('form', $output, $formattributes);
1981 // and finally one more wrapper with class
1982 return html_writer::tag('div', $output, array('class' => $select->class));
1986 * Returns a form with a url select widget.
1988 * Theme developers: DO NOT OVERRIDE! Please override function
1989 * {@link core_renderer::render_url_select()} instead.
1991 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1992 * @param string $selected selected element
1993 * @param array $nothing
1994 * @param string $formid
1995 * @return string HTML fragment
1997 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1998 $select = new url_select($urls, $selected, $nothing, $formid);
1999 return $this->render($select);
2003 * Internal implementation of url_select rendering
2005 * @param url_select $select
2006 * @return string HTML fragment
2008 protected function render_url_select(url_select $select) {
2009 global $CFG;
2011 $select = clone($select);
2012 if (empty($select->formid)) {
2013 $select->formid = html_writer::random_id('url_select_f');
2016 if (empty($select->attributes['id'])) {
2017 $select->attributes['id'] = html_writer::random_id('url_select');
2020 if ($select->disabled) {
2021 $select->attributes['disabled'] = 'disabled';
2024 if ($select->tooltip) {
2025 $select->attributes['title'] = $select->tooltip;
2028 $output = '';
2030 if ($select->label) {
2031 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
2034 $classes = array();
2035 if (!$select->showbutton) {
2036 $classes[] = 'autosubmit';
2038 if ($select->class) {
2039 $classes[] = $select->class;
2041 if (count($classes)) {
2042 $select->attributes['class'] = implode(' ', $classes);
2045 if ($select->helpicon instanceof help_icon) {
2046 $output .= $this->render($select->helpicon);
2049 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
2050 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
2051 $urls = array();
2052 foreach ($select->urls as $k=>$v) {
2053 if (is_array($v)) {
2054 // optgroup structure
2055 foreach ($v as $optgrouptitle => $optgroupoptions) {
2056 foreach ($optgroupoptions as $optionurl => $optiontitle) {
2057 if (empty($optionurl)) {
2058 $safeoptionurl = '';
2059 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
2060 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
2061 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
2062 } else if (strpos($optionurl, '/') !== 0) {
2063 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
2064 continue;
2065 } else {
2066 $safeoptionurl = $optionurl;
2068 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
2071 } else {
2072 // plain list structure
2073 if (empty($k)) {
2074 // nothing selected option
2075 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
2076 $k = str_replace($CFG->wwwroot, '', $k);
2077 } else if (strpos($k, '/') !== 0) {
2078 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
2079 continue;
2081 $urls[$k] = $v;
2084 $selected = $select->selected;
2085 if (!empty($selected)) {
2086 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
2087 $selected = str_replace($CFG->wwwroot, '', $selected);
2088 } else if (strpos($selected, '/') !== 0) {
2089 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
2093 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
2094 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
2096 if (!$select->showbutton) {
2097 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
2098 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
2099 $nothing = empty($select->nothing) ? false : key($select->nothing);
2100 $this->page->requires->yui_module('moodle-core-formautosubmit',
2101 'M.core.init_formautosubmit',
2102 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
2104 } else {
2105 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
2108 // then div wrapper for xhtml strictness
2109 $output = html_writer::tag('div', $output);
2111 // now the form itself around it
2112 $formattributes = array('method' => 'post',
2113 'action' => new moodle_url('/course/jumpto.php'),
2114 'id' => $select->formid);
2115 $output = html_writer::tag('form', $output, $formattributes);
2117 // and finally one more wrapper with class
2118 return html_writer::tag('div', $output, array('class' => $select->class));
2122 * Returns a string containing a link to the user documentation.
2123 * Also contains an icon by default. Shown to teachers and admin only.
2125 * @param string $path The page link after doc root and language, no leading slash.
2126 * @param string $text The text to be displayed for the link
2127 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2128 * @return string
2130 public function doc_link($path, $text = '', $forcepopup = false) {
2131 global $CFG;
2133 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2135 $url = new moodle_url(get_docs_url($path));
2137 $attributes = array('href'=>$url);
2138 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2139 $attributes['class'] = 'helplinkpopup';
2142 return html_writer::tag('a', $icon.$text, $attributes);
2146 * Return HTML for a pix_icon.
2148 * Theme developers: DO NOT OVERRIDE! Please override function
2149 * {@link core_renderer::render_pix_icon()} instead.
2151 * @param string $pix short pix name
2152 * @param string $alt mandatory alt attribute
2153 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2154 * @param array $attributes htm lattributes
2155 * @return string HTML fragment
2157 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2158 $icon = new pix_icon($pix, $alt, $component, $attributes);
2159 return $this->render($icon);
2163 * Renders a pix_icon widget and returns the HTML to display it.
2165 * @param pix_icon $icon
2166 * @return string HTML fragment
2168 protected function render_pix_icon(pix_icon $icon) {
2169 $data = $icon->export_for_template($this);
2170 return $this->render_from_template('core/pix_icon', $data);
2174 * Return HTML to display an emoticon icon.
2176 * @param pix_emoticon $emoticon
2177 * @return string HTML fragment
2179 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2180 $attributes = $emoticon->attributes;
2181 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
2182 return html_writer::empty_tag('img', $attributes);
2186 * Produces the html that represents this rating in the UI
2188 * @param rating $rating the page object on which this rating will appear
2189 * @return string
2191 function render_rating(rating $rating) {
2192 global $CFG, $USER;
2194 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2195 return null;//ratings are turned off
2198 $ratingmanager = new rating_manager();
2199 // Initialise the JavaScript so ratings can be done by AJAX.
2200 $ratingmanager->initialise_rating_javascript($this->page);
2202 $strrate = get_string("rate", "rating");
2203 $ratinghtml = ''; //the string we'll return
2205 // permissions check - can they view the aggregate?
2206 if ($rating->user_can_view_aggregate()) {
2208 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2209 $aggregatestr = $rating->get_aggregate_string();
2211 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2212 if ($rating->count > 0) {
2213 $countstr = "({$rating->count})";
2214 } else {
2215 $countstr = '-';
2217 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2219 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2220 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2222 $nonpopuplink = $rating->get_view_ratings_url();
2223 $popuplink = $rating->get_view_ratings_url(true);
2225 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2226 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2227 } else {
2228 $ratinghtml .= $aggregatehtml;
2232 $formstart = null;
2233 // if the item doesn't belong to the current user, the user has permission to rate
2234 // and we're within the assessable period
2235 if ($rating->user_can_rate()) {
2237 $rateurl = $rating->get_rate_url();
2238 $inputs = $rateurl->params();
2240 //start the rating form
2241 $formattrs = array(
2242 'id' => "postrating{$rating->itemid}",
2243 'class' => 'postratingform',
2244 'method' => 'post',
2245 'action' => $rateurl->out_omit_querystring()
2247 $formstart = html_writer::start_tag('form', $formattrs);
2248 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2250 // add the hidden inputs
2251 foreach ($inputs as $name => $value) {
2252 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2253 $formstart .= html_writer::empty_tag('input', $attributes);
2256 if (empty($ratinghtml)) {
2257 $ratinghtml .= $strrate.': ';
2259 $ratinghtml = $formstart.$ratinghtml;
2261 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2262 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2263 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2264 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2266 //output submit button
2267 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2269 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2270 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2272 if (!$rating->settings->scale->isnumeric) {
2273 // If a global scale, try to find current course ID from the context
2274 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2275 $courseid = $coursecontext->instanceid;
2276 } else {
2277 $courseid = $rating->settings->scale->courseid;
2279 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2281 $ratinghtml .= html_writer::end_tag('span');
2282 $ratinghtml .= html_writer::end_tag('div');
2283 $ratinghtml .= html_writer::end_tag('form');
2286 return $ratinghtml;
2290 * Centered heading with attached help button (same title text)
2291 * and optional icon attached.
2293 * @param string $text A heading text
2294 * @param string $helpidentifier The keyword that defines a help page
2295 * @param string $component component name
2296 * @param string|moodle_url $icon
2297 * @param string $iconalt icon alt text
2298 * @param int $level The level of importance of the heading. Defaulting to 2
2299 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2300 * @return string HTML fragment
2302 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2303 $image = '';
2304 if ($icon) {
2305 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2308 $help = '';
2309 if ($helpidentifier) {
2310 $help = $this->help_icon($helpidentifier, $component);
2313 return $this->heading($image.$text.$help, $level, $classnames);
2317 * Returns HTML to display a help icon.
2319 * @deprecated since Moodle 2.0
2321 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2322 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2326 * Returns HTML to display a help icon.
2328 * Theme developers: DO NOT OVERRIDE! Please override function
2329 * {@link core_renderer::render_help_icon()} instead.
2331 * @param string $identifier The keyword that defines a help page
2332 * @param string $component component name
2333 * @param string|bool $linktext true means use $title as link text, string means link text value
2334 * @return string HTML fragment
2336 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2337 $icon = new help_icon($identifier, $component);
2338 $icon->diag_strings();
2339 if ($linktext === true) {
2340 $icon->linktext = get_string($icon->identifier, $icon->component);
2341 } else if (!empty($linktext)) {
2342 $icon->linktext = $linktext;
2344 return $this->render($icon);
2348 * Implementation of user image rendering.
2350 * @param help_icon $helpicon A help icon instance
2351 * @return string HTML fragment
2353 protected function render_help_icon(help_icon $helpicon) {
2354 return $this->render_from_template('core/help_icon', $helpicon->export_for_template($this));
2358 * Returns HTML to display a scale help icon.
2360 * @param int $courseid
2361 * @param stdClass $scale instance
2362 * @return string HTML fragment
2364 public function help_icon_scale($courseid, stdClass $scale) {
2365 global $CFG;
2367 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2369 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2371 $scaleid = abs($scale->id);
2373 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2374 $action = new popup_action('click', $link, 'ratingscale');
2376 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2380 * Creates and returns a spacer image with optional line break.
2382 * @param array $attributes Any HTML attributes to add to the spaced.
2383 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2384 * laxy do it with CSS which is a much better solution.
2385 * @return string HTML fragment
2387 public function spacer(array $attributes = null, $br = false) {
2388 $attributes = (array)$attributes;
2389 if (empty($attributes['width'])) {
2390 $attributes['width'] = 1;
2392 if (empty($attributes['height'])) {
2393 $attributes['height'] = 1;
2395 $attributes['class'] = 'spacer';
2397 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2399 if (!empty($br)) {
2400 $output .= '<br />';
2403 return $output;
2407 * Returns HTML to display the specified user's avatar.
2409 * User avatar may be obtained in two ways:
2410 * <pre>
2411 * // Option 1: (shortcut for simple cases, preferred way)
2412 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2413 * $OUTPUT->user_picture($user, array('popup'=>true));
2415 * // Option 2:
2416 * $userpic = new user_picture($user);
2417 * // Set properties of $userpic
2418 * $userpic->popup = true;
2419 * $OUTPUT->render($userpic);
2420 * </pre>
2422 * Theme developers: DO NOT OVERRIDE! Please override function
2423 * {@link core_renderer::render_user_picture()} instead.
2425 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2426 * If any of these are missing, the database is queried. Avoid this
2427 * if at all possible, particularly for reports. It is very bad for performance.
2428 * @param array $options associative array with user picture options, used only if not a user_picture object,
2429 * options are:
2430 * - courseid=$this->page->course->id (course id of user profile in link)
2431 * - size=35 (size of image)
2432 * - link=true (make image clickable - the link leads to user profile)
2433 * - popup=false (open in popup)
2434 * - alttext=true (add image alt attribute)
2435 * - class = image class attribute (default 'userpicture')
2436 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2437 * @return string HTML fragment
2439 public function user_picture(stdClass $user, array $options = null) {
2440 $userpicture = new user_picture($user);
2441 foreach ((array)$options as $key=>$value) {
2442 if (array_key_exists($key, $userpicture)) {
2443 $userpicture->$key = $value;
2446 return $this->render($userpicture);
2450 * Internal implementation of user image rendering.
2452 * @param user_picture $userpicture
2453 * @return string
2455 protected function render_user_picture(user_picture $userpicture) {
2456 global $CFG, $DB;
2458 $user = $userpicture->user;
2460 if ($userpicture->alttext) {
2461 if (!empty($user->imagealt)) {
2462 $alt = $user->imagealt;
2463 } else {
2464 $alt = get_string('pictureof', '', fullname($user));
2466 } else {
2467 $alt = '';
2470 if (empty($userpicture->size)) {
2471 $size = 35;
2472 } else if ($userpicture->size === true or $userpicture->size == 1) {
2473 $size = 100;
2474 } else {
2475 $size = $userpicture->size;
2478 $class = $userpicture->class;
2480 if ($user->picture == 0) {
2481 $class .= ' defaultuserpic';
2484 $src = $userpicture->get_url($this->page, $this);
2486 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2487 if (!$userpicture->visibletoscreenreaders) {
2488 $attributes['role'] = 'presentation';
2491 // get the image html output fisrt
2492 $output = html_writer::empty_tag('img', $attributes);
2494 // then wrap it in link if needed
2495 if (!$userpicture->link) {
2496 return $output;
2499 if (empty($userpicture->courseid)) {
2500 $courseid = $this->page->course->id;
2501 } else {
2502 $courseid = $userpicture->courseid;
2505 if ($courseid == SITEID) {
2506 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2507 } else {
2508 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2511 $attributes = array('href'=>$url);
2512 if (!$userpicture->visibletoscreenreaders) {
2513 $attributes['tabindex'] = '-1';
2514 $attributes['aria-hidden'] = 'true';
2517 if ($userpicture->popup) {
2518 $id = html_writer::random_id('userpicture');
2519 $attributes['id'] = $id;
2520 $this->add_action_handler(new popup_action('click', $url), $id);
2523 return html_writer::tag('a', $output, $attributes);
2527 * Internal implementation of file tree viewer items rendering.
2529 * @param array $dir
2530 * @return string
2532 public function htmllize_file_tree($dir) {
2533 if (empty($dir['subdirs']) and empty($dir['files'])) {
2534 return '';
2536 $result = '<ul>';
2537 foreach ($dir['subdirs'] as $subdir) {
2538 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2540 foreach ($dir['files'] as $file) {
2541 $filename = $file->get_filename();
2542 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2544 $result .= '</ul>';
2546 return $result;
2550 * Returns HTML to display the file picker
2552 * <pre>
2553 * $OUTPUT->file_picker($options);
2554 * </pre>
2556 * Theme developers: DO NOT OVERRIDE! Please override function
2557 * {@link core_renderer::render_file_picker()} instead.
2559 * @param array $options associative array with file manager options
2560 * options are:
2561 * maxbytes=>-1,
2562 * itemid=>0,
2563 * client_id=>uniqid(),
2564 * acepted_types=>'*',
2565 * return_types=>FILE_INTERNAL,
2566 * context=>$PAGE->context
2567 * @return string HTML fragment
2569 public function file_picker($options) {
2570 $fp = new file_picker($options);
2571 return $this->render($fp);
2575 * Internal implementation of file picker rendering.
2577 * @param file_picker $fp
2578 * @return string
2580 public function render_file_picker(file_picker $fp) {
2581 global $CFG, $OUTPUT, $USER;
2582 $options = $fp->options;
2583 $client_id = $options->client_id;
2584 $strsaved = get_string('filesaved', 'repository');
2585 $straddfile = get_string('openpicker', 'repository');
2586 $strloading = get_string('loading', 'repository');
2587 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2588 $strdroptoupload = get_string('droptoupload', 'moodle');
2589 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2591 $currentfile = $options->currentfile;
2592 if (empty($currentfile)) {
2593 $currentfile = '';
2594 } else {
2595 $currentfile .= ' - ';
2597 if ($options->maxbytes) {
2598 $size = $options->maxbytes;
2599 } else {
2600 $size = get_max_upload_file_size();
2602 if ($size == -1) {
2603 $maxsize = '';
2604 } else {
2605 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2607 if ($options->buttonname) {
2608 $buttonname = ' name="' . $options->buttonname . '"';
2609 } else {
2610 $buttonname = '';
2612 $html = <<<EOD
2613 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2614 $icon_progress
2615 </div>
2616 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2617 <div>
2618 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2619 <span> $maxsize </span>
2620 </div>
2621 EOD;
2622 if ($options->env != 'url') {
2623 $html .= <<<EOD
2624 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2625 <div class="filepicker-filename">
2626 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2627 <div class="dndupload-progressbars"></div>
2628 </div>
2629 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2630 </div>
2631 EOD;
2633 $html .= '</div>';
2634 return $html;
2638 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2640 * @deprecated since Moodle 3.2
2642 * @param string $cmid the course_module id.
2643 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2644 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2646 public function update_module_button($cmid, $modulename) {
2647 global $CFG;
2649 debugging('core_renderer::update_module_button() has been deprecated and should not be used anymore. Activity modules ' .
2650 'should not add the edit module button, the link is already available in the Administration block. Themes can choose ' .
2651 'to display the link in the buttons row consistently for all module types.', DEBUG_DEVELOPER);
2653 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2654 $modulename = get_string('modulename', $modulename);
2655 $string = get_string('updatethis', '', $modulename);
2656 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2657 return $this->single_button($url, $string);
2658 } else {
2659 return '';
2664 * Returns HTML to display a "Turn editing on/off" button in a form.
2666 * @param moodle_url $url The URL + params to send through when clicking the button
2667 * @return string HTML the button
2669 public function edit_button(moodle_url $url) {
2671 $url->param('sesskey', sesskey());
2672 if ($this->page->user_is_editing()) {
2673 $url->param('edit', 'off');
2674 $editstring = get_string('turneditingoff');
2675 } else {
2676 $url->param('edit', 'on');
2677 $editstring = get_string('turneditingon');
2680 return $this->single_button($url, $editstring);
2684 * Returns HTML to display a simple button to close a window
2686 * @param string $text The lang string for the button's label (already output from get_string())
2687 * @return string html fragment
2689 public function close_window_button($text='') {
2690 if (empty($text)) {
2691 $text = get_string('closewindow');
2693 $button = new single_button(new moodle_url('#'), $text, 'get');
2694 $button->add_action(new component_action('click', 'close_window'));
2696 return $this->container($this->render($button), 'closewindow');
2700 * Output an error message. By default wraps the error message in <span class="error">.
2701 * If the error message is blank, nothing is output.
2703 * @param string $message the error message.
2704 * @return string the HTML to output.
2706 public function error_text($message) {
2707 if (empty($message)) {
2708 return '';
2710 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2711 return html_writer::tag('span', $message, array('class' => 'error'));
2715 * Do not call this function directly.
2717 * To terminate the current script with a fatal error, call the {@link print_error}
2718 * function, or throw an exception. Doing either of those things will then call this
2719 * function to display the error, before terminating the execution.
2721 * @param string $message The message to output
2722 * @param string $moreinfourl URL where more info can be found about the error
2723 * @param string $link Link for the Continue button
2724 * @param array $backtrace The execution backtrace
2725 * @param string $debuginfo Debugging information
2726 * @return string the HTML to output.
2728 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2729 global $CFG;
2731 $output = '';
2732 $obbuffer = '';
2734 if ($this->has_started()) {
2735 // we can not always recover properly here, we have problems with output buffering,
2736 // html tables, etc.
2737 $output .= $this->opencontainers->pop_all_but_last();
2739 } else {
2740 // It is really bad if library code throws exception when output buffering is on,
2741 // because the buffered text would be printed before our start of page.
2742 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2743 error_reporting(0); // disable notices from gzip compression, etc.
2744 while (ob_get_level() > 0) {
2745 $buff = ob_get_clean();
2746 if ($buff === false) {
2747 break;
2749 $obbuffer .= $buff;
2751 error_reporting($CFG->debug);
2753 // Output not yet started.
2754 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2755 if (empty($_SERVER['HTTP_RANGE'])) {
2756 @header($protocol . ' 404 Not Found');
2757 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2758 // Coax iOS 10 into sending the session cookie.
2759 @header($protocol . ' 403 Forbidden');
2760 } else {
2761 // Must stop byteserving attempts somehow,
2762 // this is weird but Chrome PDF viewer can be stopped only with 407!
2763 @header($protocol . ' 407 Proxy Authentication Required');
2766 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2767 $this->page->set_url('/'); // no url
2768 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2769 $this->page->set_title(get_string('error'));
2770 $this->page->set_heading($this->page->course->fullname);
2771 $output .= $this->header();
2774 $message = '<p class="errormessage">' . $message . '</p>'.
2775 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2776 get_string('moreinformation') . '</a></p>';
2777 if (empty($CFG->rolesactive)) {
2778 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2779 //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.
2781 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
2783 if ($CFG->debugdeveloper) {
2784 if (!empty($debuginfo)) {
2785 $debuginfo = s($debuginfo); // removes all nasty JS
2786 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2787 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2789 if (!empty($backtrace)) {
2790 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2792 if ($obbuffer !== '' ) {
2793 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2797 if (empty($CFG->rolesactive)) {
2798 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2799 } else if (!empty($link)) {
2800 $output .= $this->continue_button($link);
2803 $output .= $this->footer();
2805 // Padding to encourage IE to display our error page, rather than its own.
2806 $output .= str_repeat(' ', 512);
2808 return $output;
2812 * Output a notification (that is, a status message about something that has just happened).
2814 * Note: \core\notification::add() may be more suitable for your usage.
2816 * @param string $message The message to print out.
2817 * @param string $type The type of notification. See constants on \core\output\notification.
2818 * @return string the HTML to output.
2820 public function notification($message, $type = null) {
2821 $typemappings = [
2822 // Valid types.
2823 'success' => \core\output\notification::NOTIFY_SUCCESS,
2824 'info' => \core\output\notification::NOTIFY_INFO,
2825 'warning' => \core\output\notification::NOTIFY_WARNING,
2826 'error' => \core\output\notification::NOTIFY_ERROR,
2828 // Legacy types mapped to current types.
2829 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2830 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2831 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2832 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2833 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2834 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2835 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2838 $extraclasses = [];
2840 if ($type) {
2841 if (strpos($type, ' ') === false) {
2842 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2843 if (isset($typemappings[$type])) {
2844 $type = $typemappings[$type];
2845 } else {
2846 // The value provided did not match a known type. It must be an extra class.
2847 $extraclasses = [$type];
2849 } else {
2850 // Identify what type of notification this is.
2851 $classarray = explode(' ', self::prepare_classes($type));
2853 // Separate out the type of notification from the extra classes.
2854 foreach ($classarray as $class) {
2855 if (isset($typemappings[$class])) {
2856 $type = $typemappings[$class];
2857 } else {
2858 $extraclasses[] = $class;
2864 $notification = new \core\output\notification($message, $type);
2865 if (count($extraclasses)) {
2866 $notification->set_extra_classes($extraclasses);
2869 // Return the rendered template.
2870 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2874 * Output a notification at a particular level - in this case, NOTIFY_PROBLEM.
2876 * @param string $message the message to print out
2877 * @return string HTML fragment.
2878 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2879 * @todo MDL-53113 This will be removed in Moodle 3.5.
2880 * @see \core\output\notification
2882 public function notify_problem($message) {
2883 debugging(__FUNCTION__ . ' is deprecated.' .
2884 'Please use \core\notification::add, or \core\output\notification as required',
2885 DEBUG_DEVELOPER);
2886 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_ERROR);
2887 return $this->render($n);
2891 * Output a notification at a particular level - in this case, NOTIFY_SUCCESS.
2893 * @param string $message the message to print out
2894 * @return string HTML fragment.
2895 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2896 * @todo MDL-53113 This will be removed in Moodle 3.5.
2897 * @see \core\output\notification
2899 public function notify_success($message) {
2900 debugging(__FUNCTION__ . ' is deprecated.' .
2901 'Please use \core\notification::add, or \core\output\notification as required',
2902 DEBUG_DEVELOPER);
2903 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_SUCCESS);
2904 return $this->render($n);
2908 * Output a notification at a particular level - in this case, NOTIFY_MESSAGE.
2910 * @param string $message the message to print out
2911 * @return string HTML fragment.
2912 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2913 * @todo MDL-53113 This will be removed in Moodle 3.5.
2914 * @see \core\output\notification
2916 public function notify_message($message) {
2917 debugging(__FUNCTION__ . ' is deprecated.' .
2918 'Please use \core\notification::add, or \core\output\notification as required',
2919 DEBUG_DEVELOPER);
2920 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_INFO);
2921 return $this->render($n);
2925 * Output a notification at a particular level - in this case, NOTIFY_REDIRECT.
2927 * @param string $message the message to print out
2928 * @return string HTML fragment.
2929 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2930 * @todo MDL-53113 This will be removed in Moodle 3.5.
2931 * @see \core\output\notification
2933 public function notify_redirect($message) {
2934 debugging(__FUNCTION__ . ' is deprecated.' .
2935 'Please use \core\notification::add, or \core\output\notification as required',
2936 DEBUG_DEVELOPER);
2937 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_INFO);
2938 return $this->render($n);
2942 * Render a notification (that is, a status message about something that has
2943 * just happened).
2945 * @param \core\output\notification $notification the notification to print out
2946 * @return string the HTML to output.
2948 protected function render_notification(\core\output\notification $notification) {
2949 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2953 * Returns HTML to display a continue button that goes to a particular URL.
2955 * @param string|moodle_url $url The url the button goes to.
2956 * @return string the HTML to output.
2958 public function continue_button($url) {
2959 if (!($url instanceof moodle_url)) {
2960 $url = new moodle_url($url);
2962 $button = new single_button($url, get_string('continue'), 'get', true);
2963 $button->class = 'continuebutton';
2965 return $this->render($button);
2969 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2971 * Theme developers: DO NOT OVERRIDE! Please override function
2972 * {@link core_renderer::render_paging_bar()} instead.
2974 * @param int $totalcount The total number of entries available to be paged through
2975 * @param int $page The page you are currently viewing
2976 * @param int $perpage The number of entries that should be shown per page
2977 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2978 * @param string $pagevar name of page parameter that holds the page number
2979 * @return string the HTML to output.
2981 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2982 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2983 return $this->render($pb);
2987 * Internal implementation of paging bar rendering.
2989 * @param paging_bar $pagingbar
2990 * @return string
2992 protected function render_paging_bar(paging_bar $pagingbar) {
2993 $output = '';
2994 $pagingbar = clone($pagingbar);
2995 $pagingbar->prepare($this, $this->page, $this->target);
2997 if ($pagingbar->totalcount > $pagingbar->perpage) {
2998 $output .= get_string('page') . ':';
3000 if (!empty($pagingbar->previouslink)) {
3001 $output .= ' (' . $pagingbar->previouslink . ') ';
3004 if (!empty($pagingbar->firstlink)) {
3005 $output .= ' ' . $pagingbar->firstlink . ' ...';
3008 foreach ($pagingbar->pagelinks as $link) {
3009 $output .= " $link";
3012 if (!empty($pagingbar->lastlink)) {
3013 $output .= ' ... ' . $pagingbar->lastlink . ' ';
3016 if (!empty($pagingbar->nextlink)) {
3017 $output .= ' (' . $pagingbar->nextlink . ')';
3021 return html_writer::tag('div', $output, array('class' => 'paging'));
3025 * Output the place a skip link goes to.
3027 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3028 * @return string the HTML to output.
3030 public function skip_link_target($id = null) {
3031 return html_writer::span('', '', array('id' => $id));
3035 * Outputs a heading
3037 * @param string $text The text of the heading
3038 * @param int $level The level of importance of the heading. Defaulting to 2
3039 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3040 * @param string $id An optional ID
3041 * @return string the HTML to output.
3043 public function heading($text, $level = 2, $classes = null, $id = null) {
3044 $level = (integer) $level;
3045 if ($level < 1 or $level > 6) {
3046 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3048 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3052 * Outputs a box.
3054 * @param string $contents The contents of the box
3055 * @param string $classes A space-separated list of CSS classes
3056 * @param string $id An optional ID
3057 * @param array $attributes An array of other attributes to give the box.
3058 * @return string the HTML to output.
3060 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3061 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3065 * Outputs the opening section of a box.
3067 * @param string $classes A space-separated list of CSS classes
3068 * @param string $id An optional ID
3069 * @param array $attributes An array of other attributes to give the box.
3070 * @return string the HTML to output.
3072 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3073 $this->opencontainers->push('box', html_writer::end_tag('div'));
3074 $attributes['id'] = $id;
3075 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
3076 return html_writer::start_tag('div', $attributes);
3080 * Outputs the closing section of a box.
3082 * @return string the HTML to output.
3084 public function box_end() {
3085 return $this->opencontainers->pop('box');
3089 * Outputs a container.
3091 * @param string $contents The contents of the box
3092 * @param string $classes A space-separated list of CSS classes
3093 * @param string $id An optional ID
3094 * @return string the HTML to output.
3096 public function container($contents, $classes = null, $id = null) {
3097 return $this->container_start($classes, $id) . $contents . $this->container_end();
3101 * Outputs the opening section of a container.
3103 * @param string $classes A space-separated list of CSS classes
3104 * @param string $id An optional ID
3105 * @return string the HTML to output.
3107 public function container_start($classes = null, $id = null) {
3108 $this->opencontainers->push('container', html_writer::end_tag('div'));
3109 return html_writer::start_tag('div', array('id' => $id,
3110 'class' => renderer_base::prepare_classes($classes)));
3114 * Outputs the closing section of a container.
3116 * @return string the HTML to output.
3118 public function container_end() {
3119 return $this->opencontainers->pop('container');
3123 * Make nested HTML lists out of the items
3125 * The resulting list will look something like this:
3127 * <pre>
3128 * <<ul>>
3129 * <<li>><div class='tree_item parent'>(item contents)</div>
3130 * <<ul>
3131 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3132 * <</ul>>
3133 * <</li>>
3134 * <</ul>>
3135 * </pre>
3137 * @param array $items
3138 * @param array $attrs html attributes passed to the top ofs the list
3139 * @return string HTML
3141 public function tree_block_contents($items, $attrs = array()) {
3142 // exit if empty, we don't want an empty ul element
3143 if (empty($items)) {
3144 return '';
3146 // array of nested li elements
3147 $lis = array();
3148 foreach ($items as $item) {
3149 // this applies to the li item which contains all child lists too
3150 $content = $item->content($this);
3151 $liclasses = array($item->get_css_type());
3152 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3153 $liclasses[] = 'collapsed';
3155 if ($item->isactive === true) {
3156 $liclasses[] = 'current_branch';
3158 $liattr = array('class'=>join(' ',$liclasses));
3159 // class attribute on the div item which only contains the item content
3160 $divclasses = array('tree_item');
3161 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3162 $divclasses[] = 'branch';
3163 } else {
3164 $divclasses[] = 'leaf';
3166 if (!empty($item->classes) && count($item->classes)>0) {
3167 $divclasses[] = join(' ', $item->classes);
3169 $divattr = array('class'=>join(' ', $divclasses));
3170 if (!empty($item->id)) {
3171 $divattr['id'] = $item->id;
3173 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3174 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3175 $content = html_writer::empty_tag('hr') . $content;
3177 $content = html_writer::tag('li', $content, $liattr);
3178 $lis[] = $content;
3180 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3184 * Returns a search box.
3186 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3187 * @return string HTML with the search form hidden by default.
3189 public function search_box($id = false) {
3190 global $CFG;
3192 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3193 // result in an extra included file for each site, even the ones where global search
3194 // is disabled.
3195 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3196 return '';
3199 if ($id == false) {
3200 $id = uniqid();
3201 } else {
3202 // Needs to be cleaned, we use it for the input id.
3203 $id = clean_param($id, PARAM_ALPHANUMEXT);
3206 // JS to animate the form.
3207 $this->page->requires->js_call_amd('core/search-input', 'init', array($id));
3209 $searchicon = html_writer::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
3210 array('role' => 'button', 'tabindex' => 0));
3211 $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot . '/search/index.php');
3212 $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
3213 'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id);
3215 $contents = html_writer::tag('label', get_string('enteryoursearchquery', 'search'),
3216 array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer::tag('input', '', $inputattrs);
3217 $searchinput = html_writer::tag('form', $contents, $formattrs);
3219 return html_writer::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper nav-link', 'id' => $id));
3223 * Allow plugins to provide some content to be rendered in the navbar.
3224 * The plugin must define a PLUGIN_render_navbar_output function that returns
3225 * the HTML they wish to add to the navbar.
3227 * @return string HTML for the navbar
3229 public function navbar_plugin_output() {
3230 $output = '';
3232 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3233 foreach ($pluginsfunction as $plugintype => $plugins) {
3234 foreach ($plugins as $pluginfunction) {
3235 $output .= $pluginfunction($this);
3240 return $output;
3244 * Construct a user menu, returning HTML that can be echoed out by a
3245 * layout file.
3247 * @param stdClass $user A user object, usually $USER.
3248 * @param bool $withlinks true if a dropdown should be built.
3249 * @return string HTML fragment.
3251 public function user_menu($user = null, $withlinks = null) {
3252 global $USER, $CFG;
3253 require_once($CFG->dirroot . '/user/lib.php');
3255 if (is_null($user)) {
3256 $user = $USER;
3259 // Note: this behaviour is intended to match that of core_renderer::login_info,
3260 // but should not be considered to be good practice; layout options are
3261 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3262 if (is_null($withlinks)) {
3263 $withlinks = empty($this->page->layout_options['nologinlinks']);
3266 // Add a class for when $withlinks is false.
3267 $usermenuclasses = 'usermenu';
3268 if (!$withlinks) {
3269 $usermenuclasses .= ' withoutlinks';
3272 $returnstr = "";
3274 // If during initial install, return the empty return string.
3275 if (during_initial_install()) {
3276 return $returnstr;
3279 $loginpage = $this->is_login_page();
3280 $loginurl = get_login_url();
3281 // If not logged in, show the typical not-logged-in string.
3282 if (!isloggedin()) {
3283 $returnstr = get_string('loggedinnot', 'moodle');
3284 if (!$loginpage) {
3285 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3287 return html_writer::div(
3288 html_writer::span(
3289 $returnstr,
3290 'login'
3292 $usermenuclasses
3297 // If logged in as a guest user, show a string to that effect.
3298 if (isguestuser()) {
3299 $returnstr = get_string('loggedinasguest');
3300 if (!$loginpage && $withlinks) {
3301 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3304 return html_writer::div(
3305 html_writer::span(
3306 $returnstr,
3307 'login'
3309 $usermenuclasses
3313 // Get some navigation opts.
3314 $opts = user_get_user_navigation_info($user, $this->page);
3316 $avatarclasses = "avatars";
3317 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3318 $usertextcontents = $opts->metadata['userfullname'];
3320 // Other user.
3321 if (!empty($opts->metadata['asotheruser'])) {
3322 $avatarcontents .= html_writer::span(
3323 $opts->metadata['realuseravatar'],
3324 'avatar realuser'
3326 $usertextcontents = $opts->metadata['realuserfullname'];
3327 $usertextcontents .= html_writer::tag(
3328 'span',
3329 get_string(
3330 'loggedinas',
3331 'moodle',
3332 html_writer::span(
3333 $opts->metadata['userfullname'],
3334 'value'
3337 array('class' => 'meta viewingas')
3341 // Role.
3342 if (!empty($opts->metadata['asotherrole'])) {
3343 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3344 $usertextcontents .= html_writer::span(
3345 $opts->metadata['rolename'],
3346 'meta role role-' . $role
3350 // User login failures.
3351 if (!empty($opts->metadata['userloginfail'])) {
3352 $usertextcontents .= html_writer::span(
3353 $opts->metadata['userloginfail'],
3354 'meta loginfailures'
3358 // MNet.
3359 if (!empty($opts->metadata['asmnetuser'])) {
3360 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3361 $usertextcontents .= html_writer::span(
3362 $opts->metadata['mnetidprovidername'],
3363 'meta mnet mnet-' . $mnet
3367 $returnstr .= html_writer::span(
3368 html_writer::span($usertextcontents, 'usertext') .
3369 html_writer::span($avatarcontents, $avatarclasses),
3370 'userbutton'
3373 // Create a divider (well, a filler).
3374 $divider = new action_menu_filler();
3375 $divider->primary = false;
3377 $am = new action_menu();
3378 $am->set_menu_trigger(
3379 $returnstr
3381 $am->set_alignment(action_menu::TR, action_menu::BR);
3382 $am->set_nowrap_on_items();
3383 if ($withlinks) {
3384 $navitemcount = count($opts->navitems);
3385 $idx = 0;
3386 foreach ($opts->navitems as $key => $value) {
3388 switch ($value->itemtype) {
3389 case 'divider':
3390 // If the nav item is a divider, add one and skip link processing.
3391 $am->add($divider);
3392 break;
3394 case 'invalid':
3395 // Silently skip invalid entries (should we post a notification?).
3396 break;
3398 case 'link':
3399 // Process this as a link item.
3400 $pix = null;
3401 if (isset($value->pix) && !empty($value->pix)) {
3402 $pix = new pix_icon($value->pix, $value->title, null, array('class' => 'iconsmall'));
3403 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3404 $value->title = html_writer::img(
3405 $value->imgsrc,
3406 $value->title,
3407 array('class' => 'iconsmall')
3408 ) . $value->title;
3411 $al = new action_menu_link_secondary(
3412 $value->url,
3413 $pix,
3414 $value->title,
3415 array('class' => 'icon')
3417 if (!empty($value->titleidentifier)) {
3418 $al->attributes['data-title'] = $value->titleidentifier;
3420 $am->add($al);
3421 break;
3424 $idx++;
3426 // Add dividers after the first item and before the last item.
3427 if ($idx == 1 || $idx == $navitemcount - 1) {
3428 $am->add($divider);
3433 return html_writer::div(
3434 $this->render($am),
3435 $usermenuclasses
3440 * Return the navbar content so that it can be echoed out by the layout
3442 * @return string XHTML navbar
3444 public function navbar() {
3445 $items = $this->page->navbar->get_items();
3446 $itemcount = count($items);
3447 if ($itemcount === 0) {
3448 return '';
3451 $htmlblocks = array();
3452 // Iterate the navarray and display each node
3453 $separator = get_separator();
3454 for ($i=0;$i < $itemcount;$i++) {
3455 $item = $items[$i];
3456 $item->hideicon = true;
3457 if ($i===0) {
3458 $content = html_writer::tag('li', $this->render($item));
3459 } else {
3460 $content = html_writer::tag('li', $separator.$this->render($item));
3462 $htmlblocks[] = $content;
3465 //accessibility: heading for navbar list (MDL-20446)
3466 $navbarcontent = html_writer::tag('span', get_string('pagepath'),
3467 array('class' => 'accesshide', 'id' => 'navbar-label'));
3468 $navbarcontent .= html_writer::tag('nav',
3469 html_writer::tag('ul', join('', $htmlblocks)),
3470 array('aria-labelledby' => 'navbar-label'));
3471 // XHTML
3472 return $navbarcontent;
3476 * Renders a breadcrumb navigation node object.
3478 * @param breadcrumb_navigation_node $item The navigation node to render.
3479 * @return string HTML fragment
3481 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3483 if ($item->action instanceof moodle_url) {
3484 $content = $item->get_content();
3485 $title = $item->get_title();
3486 $attributes = array();
3487 $attributes['itemprop'] = 'url';
3488 if ($title !== '') {
3489 $attributes['title'] = $title;
3491 if ($item->hidden) {
3492 $attributes['class'] = 'dimmed_text';
3494 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3495 $content = html_writer::link($item->action, $content, $attributes);
3497 $attributes = array();
3498 $attributes['itemscope'] = '';
3499 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3500 $content = html_writer::tag('span', $content, $attributes);
3502 } else {
3503 $content = $this->render_navigation_node($item);
3505 return $content;
3509 * Renders a navigation node object.
3511 * @param navigation_node $item The navigation node to render.
3512 * @return string HTML fragment
3514 protected function render_navigation_node(navigation_node $item) {
3515 $content = $item->get_content();
3516 $title = $item->get_title();
3517 if ($item->icon instanceof renderable && !$item->hideicon) {
3518 $icon = $this->render($item->icon);
3519 $content = $icon.$content; // use CSS for spacing of icons
3521 if ($item->helpbutton !== null) {
3522 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3524 if ($content === '') {
3525 return '';
3527 if ($item->action instanceof action_link) {
3528 $link = $item->action;
3529 if ($item->hidden) {
3530 $link->add_class('dimmed');
3532 if (!empty($content)) {
3533 // Providing there is content we will use that for the link content.
3534 $link->text = $content;
3536 $content = $this->render($link);
3537 } else if ($item->action instanceof moodle_url) {
3538 $attributes = array();
3539 if ($title !== '') {
3540 $attributes['title'] = $title;
3542 if ($item->hidden) {
3543 $attributes['class'] = 'dimmed_text';
3545 $content = html_writer::link($item->action, $content, $attributes);
3547 } else if (is_string($item->action) || empty($item->action)) {
3548 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3549 if ($title !== '') {
3550 $attributes['title'] = $title;
3552 if ($item->hidden) {
3553 $attributes['class'] = 'dimmed_text';
3555 $content = html_writer::tag('span', $content, $attributes);
3557 return $content;
3561 * Accessibility: Right arrow-like character is
3562 * used in the breadcrumb trail, course navigation menu
3563 * (previous/next activity), calendar, and search forum block.
3564 * If the theme does not set characters, appropriate defaults
3565 * are set automatically. Please DO NOT
3566 * use &lt; &gt; &raquo; - these are confusing for blind users.
3568 * @return string
3570 public function rarrow() {
3571 return $this->page->theme->rarrow;
3575 * Accessibility: Left arrow-like character is
3576 * used in the breadcrumb trail, course navigation menu
3577 * (previous/next activity), calendar, and search forum block.
3578 * If the theme does not set characters, appropriate defaults
3579 * are set automatically. Please DO NOT
3580 * use &lt; &gt; &raquo; - these are confusing for blind users.
3582 * @return string
3584 public function larrow() {
3585 return $this->page->theme->larrow;
3589 * Accessibility: Up arrow-like character is used in
3590 * the book heirarchical navigation.
3591 * If the theme does not set characters, appropriate defaults
3592 * are set automatically. Please DO NOT
3593 * use ^ - this is confusing for blind users.
3595 * @return string
3597 public function uarrow() {
3598 return $this->page->theme->uarrow;
3602 * Accessibility: Down arrow-like character.
3603 * If the theme does not set characters, appropriate defaults
3604 * are set automatically.
3606 * @return string
3608 public function darrow() {
3609 return $this->page->theme->darrow;
3613 * Returns the custom menu if one has been set
3615 * A custom menu can be configured by browsing to
3616 * Settings: Administration > Appearance > Themes > Theme settings
3617 * and then configuring the custommenu config setting as described.
3619 * Theme developers: DO NOT OVERRIDE! Please override function
3620 * {@link core_renderer::render_custom_menu()} instead.
3622 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3623 * @return string
3625 public function custom_menu($custommenuitems = '') {
3626 global $CFG;
3627 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3628 $custommenuitems = $CFG->custommenuitems;
3630 if (empty($custommenuitems)) {
3631 return '';
3633 $custommenu = new custom_menu($custommenuitems, current_language());
3634 return $this->render($custommenu);
3638 * Renders a custom menu object (located in outputcomponents.php)
3640 * The custom menu this method produces makes use of the YUI3 menunav widget
3641 * and requires very specific html elements and classes.
3643 * @staticvar int $menucount
3644 * @param custom_menu $menu
3645 * @return string
3647 protected function render_custom_menu(custom_menu $menu) {
3648 static $menucount = 0;
3649 // If the menu has no children return an empty string
3650 if (!$menu->has_children()) {
3651 return '';
3653 // Increment the menu count. This is used for ID's that get worked with
3654 // in JavaScript as is essential
3655 $menucount++;
3656 // Initialise this custom menu (the custom menu object is contained in javascript-static
3657 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
3658 $jscode = "(function(){{$jscode}})";
3659 $this->page->requires->yui_module('node-menunav', $jscode);
3660 // Build the root nodes as required by YUI
3661 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
3662 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3663 $content .= html_writer::start_tag('ul');
3664 // Render each child
3665 foreach ($menu->get_children() as $item) {
3666 $content .= $this->render_custom_menu_item($item);
3668 // Close the open tags
3669 $content .= html_writer::end_tag('ul');
3670 $content .= html_writer::end_tag('div');
3671 $content .= html_writer::end_tag('div');
3672 // Return the custom menu
3673 return $content;
3677 * Renders a custom menu node as part of a submenu
3679 * The custom menu this method produces makes use of the YUI3 menunav widget
3680 * and requires very specific html elements and classes.
3682 * @see core:renderer::render_custom_menu()
3684 * @staticvar int $submenucount
3685 * @param custom_menu_item $menunode
3686 * @return string
3688 protected function render_custom_menu_item(custom_menu_item $menunode) {
3689 // Required to ensure we get unique trackable id's
3690 static $submenucount = 0;
3691 if ($menunode->has_children()) {
3692 // If the child has menus render it as a sub menu
3693 $submenucount++;
3694 $content = html_writer::start_tag('li');
3695 if ($menunode->get_url() !== null) {
3696 $url = $menunode->get_url();
3697 } else {
3698 $url = '#cm_submenu_'.$submenucount;
3700 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3701 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3702 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3703 $content .= html_writer::start_tag('ul');
3704 foreach ($menunode->get_children() as $menunode) {
3705 $content .= $this->render_custom_menu_item($menunode);
3707 $content .= html_writer::end_tag('ul');
3708 $content .= html_writer::end_tag('div');
3709 $content .= html_writer::end_tag('div');
3710 $content .= html_writer::end_tag('li');
3711 } else {
3712 // The node doesn't have children so produce a final menuitem.
3713 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3714 $content = '';
3715 if (preg_match("/^#+$/", $menunode->get_text())) {
3717 // This is a divider.
3718 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3719 } else {
3720 $content = html_writer::start_tag(
3721 'li',
3722 array(
3723 'class' => 'yui3-menuitem'
3726 if ($menunode->get_url() !== null) {
3727 $url = $menunode->get_url();
3728 } else {
3729 $url = '#';
3731 $content .= html_writer::link(
3732 $url,
3733 $menunode->get_text(),
3734 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3737 $content .= html_writer::end_tag('li');
3739 // Return the sub menu
3740 return $content;
3744 * Renders theme links for switching between default and other themes.
3746 * @return string
3748 protected function theme_switch_links() {
3750 $actualdevice = core_useragent::get_device_type();
3751 $currentdevice = $this->page->devicetypeinuse;
3752 $switched = ($actualdevice != $currentdevice);
3754 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3755 // The user is using the a default device and hasn't switched so don't shown the switch
3756 // device links.
3757 return '';
3760 if ($switched) {
3761 $linktext = get_string('switchdevicerecommended');
3762 $devicetype = $actualdevice;
3763 } else {
3764 $linktext = get_string('switchdevicedefault');
3765 $devicetype = 'default';
3767 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3769 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3770 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3771 $content .= html_writer::end_tag('div');
3773 return $content;
3777 * Renders tabs
3779 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3781 * Theme developers: In order to change how tabs are displayed please override functions
3782 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3784 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3785 * @param string|null $selected which tab to mark as selected, all parent tabs will
3786 * automatically be marked as activated
3787 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3788 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3789 * @return string
3791 public final function tabtree($tabs, $selected = null, $inactive = null) {
3792 return $this->render(new tabtree($tabs, $selected, $inactive));
3796 * Renders tabtree
3798 * @param tabtree $tabtree
3799 * @return string
3801 protected function render_tabtree(tabtree $tabtree) {
3802 if (empty($tabtree->subtree)) {
3803 return '';
3805 $str = '';
3806 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
3807 $str .= $this->render_tabobject($tabtree);
3808 $str .= html_writer::end_tag('div').
3809 html_writer::tag('div', ' ', array('class' => 'clearer'));
3810 return $str;
3814 * Renders tabobject (part of tabtree)
3816 * This function is called from {@link core_renderer::render_tabtree()}
3817 * and also it calls itself when printing the $tabobject subtree recursively.
3819 * Property $tabobject->level indicates the number of row of tabs.
3821 * @param tabobject $tabobject
3822 * @return string HTML fragment
3824 protected function render_tabobject(tabobject $tabobject) {
3825 $str = '';
3827 // Print name of the current tab.
3828 if ($tabobject instanceof tabtree) {
3829 // No name for tabtree root.
3830 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3831 // Tab name without a link. The <a> tag is used for styling.
3832 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3833 } else {
3834 // Tab name with a link.
3835 if (!($tabobject->link instanceof moodle_url)) {
3836 // backward compartibility when link was passed as quoted string
3837 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3838 } else {
3839 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3843 if (empty($tabobject->subtree)) {
3844 if ($tabobject->selected) {
3845 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3847 return $str;
3850 // Print subtree.
3851 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
3852 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3853 $cnt = 0;
3854 foreach ($tabobject->subtree as $tab) {
3855 $liclass = '';
3856 if (!$cnt) {
3857 $liclass .= ' first';
3859 if ($cnt == count($tabobject->subtree) - 1) {
3860 $liclass .= ' last';
3862 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3863 $liclass .= ' onerow';
3866 if ($tab->selected) {
3867 $liclass .= ' here selected';
3868 } else if ($tab->activated) {
3869 $liclass .= ' here active';
3872 // This will recursively call function render_tabobject() for each item in subtree.
3873 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3874 $cnt++;
3876 $str .= html_writer::end_tag('ul');
3879 return $str;
3883 * Get the HTML for blocks in the given region.
3885 * @since Moodle 2.5.1 2.6
3886 * @param string $region The region to get HTML for.
3887 * @return string HTML.
3889 public function blocks($region, $classes = array(), $tag = 'aside') {
3890 $displayregion = $this->page->apply_theme_region_manipulations($region);
3891 $classes = (array)$classes;
3892 $classes[] = 'block-region';
3893 $attributes = array(
3894 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3895 'class' => join(' ', $classes),
3896 'data-blockregion' => $displayregion,
3897 'data-droptarget' => '1'
3899 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3900 $content = $this->blocks_for_region($displayregion);
3901 } else {
3902 $content = '';
3904 return html_writer::tag($tag, $content, $attributes);
3908 * Renders a custom block region.
3910 * Use this method if you want to add an additional block region to the content of the page.
3911 * Please note this should only be used in special situations.
3912 * We want to leave the theme is control where ever possible!
3914 * This method must use the same method that the theme uses within its layout file.
3915 * As such it asks the theme what method it is using.
3916 * It can be one of two values, blocks or blocks_for_region (deprecated).
3918 * @param string $regionname The name of the custom region to add.
3919 * @return string HTML for the block region.
3921 public function custom_block_region($regionname) {
3922 if ($this->page->theme->get_block_render_method() === 'blocks') {
3923 return $this->blocks($regionname);
3924 } else {
3925 return $this->blocks_for_region($regionname);
3930 * Returns the CSS classes to apply to the body tag.
3932 * @since Moodle 2.5.1 2.6
3933 * @param array $additionalclasses Any additional classes to apply.
3934 * @return string
3936 public function body_css_classes(array $additionalclasses = array()) {
3937 // Add a class for each block region on the page.
3938 // We use the block manager here because the theme object makes get_string calls.
3939 $usedregions = array();
3940 foreach ($this->page->blocks->get_regions() as $region) {
3941 $additionalclasses[] = 'has-region-'.$region;
3942 if ($this->page->blocks->region_has_content($region, $this)) {
3943 $additionalclasses[] = 'used-region-'.$region;
3944 $usedregions[] = $region;
3945 } else {
3946 $additionalclasses[] = 'empty-region-'.$region;
3948 if ($this->page->blocks->region_completely_docked($region, $this)) {
3949 $additionalclasses[] = 'docked-region-'.$region;
3952 if (!$usedregions) {
3953 // No regions means there is only content, add 'content-only' class.
3954 $additionalclasses[] = 'content-only';
3955 } else if (count($usedregions) === 1) {
3956 // Add the -only class for the only used region.
3957 $region = array_shift($usedregions);
3958 $additionalclasses[] = $region . '-only';
3960 foreach ($this->page->layout_options as $option => $value) {
3961 if ($value) {
3962 $additionalclasses[] = 'layout-option-'.$option;
3965 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
3966 return $css;
3970 * The ID attribute to apply to the body tag.
3972 * @since Moodle 2.5.1 2.6
3973 * @return string
3975 public function body_id() {
3976 return $this->page->bodyid;
3980 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
3982 * @since Moodle 2.5.1 2.6
3983 * @param string|array $additionalclasses Any additional classes to give the body tag,
3984 * @return string
3986 public function body_attributes($additionalclasses = array()) {
3987 if (!is_array($additionalclasses)) {
3988 $additionalclasses = explode(' ', $additionalclasses);
3990 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
3994 * Gets HTML for the page heading.
3996 * @since Moodle 2.5.1 2.6
3997 * @param string $tag The tag to encase the heading in. h1 by default.
3998 * @return string HTML.
4000 public function page_heading($tag = 'h1') {
4001 return html_writer::tag($tag, $this->page->heading);
4005 * Gets the HTML for the page heading button.
4007 * @since Moodle 2.5.1 2.6
4008 * @return string HTML.
4010 public function page_heading_button() {
4011 return $this->page->button;
4015 * Returns the Moodle docs link to use for this page.
4017 * @since Moodle 2.5.1 2.6
4018 * @param string $text
4019 * @return string
4021 public function page_doc_link($text = null) {
4022 if ($text === null) {
4023 $text = get_string('moodledocslink');
4025 $path = page_get_doc_link_path($this->page);
4026 if (!$path) {
4027 return '';
4029 return $this->doc_link($path, $text);
4033 * Returns the page heading menu.
4035 * @since Moodle 2.5.1 2.6
4036 * @return string HTML.
4038 public function page_heading_menu() {
4039 return $this->page->headingmenu;
4043 * Returns the title to use on the page.
4045 * @since Moodle 2.5.1 2.6
4046 * @return string
4048 public function page_title() {
4049 return $this->page->title;
4053 * Returns the URL for the favicon.
4055 * @since Moodle 2.5.1 2.6
4056 * @return string The favicon URL
4058 public function favicon() {
4059 return $this->pix_url('favicon', 'theme');
4063 * Renders preferences groups.
4065 * @param preferences_groups $renderable The renderable
4066 * @return string The output.
4068 public function render_preferences_groups(preferences_groups $renderable) {
4069 $html = '';
4070 $html .= html_writer::start_div('row-fluid');
4071 $html .= html_writer::start_tag('div', array('class' => 'span12 preferences-groups'));
4072 $i = 0;
4073 $open = false;
4074 foreach ($renderable->groups as $group) {
4075 if ($i == 0 || $i % 3 == 0) {
4076 if ($open) {
4077 $html .= html_writer::end_tag('div');
4079 $html .= html_writer::start_tag('div', array('class' => 'row-fluid'));
4080 $open = true;
4082 $html .= $this->render($group);
4083 $i++;
4086 $html .= html_writer::end_tag('div');
4088 $html .= html_writer::end_tag('ul');
4089 $html .= html_writer::end_tag('div');
4090 $html .= html_writer::end_div();
4091 return $html;
4095 * Renders preferences group.
4097 * @param preferences_group $renderable The renderable
4098 * @return string The output.
4100 public function render_preferences_group(preferences_group $renderable) {
4101 $html = '';
4102 $html .= html_writer::start_tag('div', array('class' => 'span4 preferences-group'));
4103 $html .= $this->heading($renderable->title, 3);
4104 $html .= html_writer::start_tag('ul');
4105 foreach ($renderable->nodes as $node) {
4106 if ($node->has_children()) {
4107 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4109 $html .= html_writer::tag('li', $this->render($node));
4111 $html .= html_writer::end_tag('ul');
4112 $html .= html_writer::end_tag('div');
4113 return $html;
4116 public function context_header($headerinfo = null, $headinglevel = 1) {
4117 global $DB, $USER, $CFG;
4118 $context = $this->page->context;
4119 // Make sure to use the heading if it has been set.
4120 if (isset($headerinfo['heading'])) {
4121 $heading = $headerinfo['heading'];
4122 } else {
4123 $heading = null;
4125 $imagedata = null;
4126 $subheader = null;
4127 $userbuttons = null;
4128 // The user context currently has images and buttons. Other contexts may follow.
4129 if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
4130 if (isset($headerinfo['user'])) {
4131 $user = $headerinfo['user'];
4132 } else {
4133 // Look up the user information if it is not supplied.
4134 $user = $DB->get_record('user', array('id' => $context->instanceid));
4136 // If the user context is set, then use that for capability checks.
4137 if (isset($headerinfo['usercontext'])) {
4138 $context = $headerinfo['usercontext'];
4140 // Use the user's full name if the heading isn't set.
4141 if (!isset($heading)) {
4142 $heading = fullname($user);
4145 $imagedata = $this->user_picture($user, array('size' => 100));
4146 // Check to see if we should be displaying a message button.
4147 if (!empty($CFG->messaging) && $USER->id != $user->id && has_capability('moodle/site:sendmessage', $context)) {
4148 $iscontact = !empty(message_get_contact($user->id));
4149 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4150 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4151 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4152 $userbuttons = array(
4153 'messages' => array(
4154 'buttontype' => 'message',
4155 'title' => get_string('message', 'message'),
4156 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4157 'image' => 'message',
4158 'linkattributes' => array('role' => 'button'),
4159 'page' => $this->page
4161 'togglecontact' => array(
4162 'buttontype' => 'togglecontact',
4163 'title' => get_string($contacttitle, 'message'),
4164 'url' => new moodle_url('/message/index.php', array(
4165 'user1' => $USER->id,
4166 'user2' => $user->id,
4167 $contacturlaction => $user->id,
4168 'sesskey' => sesskey())
4170 'image' => $contactimage,
4171 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4172 'page' => $this->page
4176 $this->page->requires->string_for_js('changesmadereallygoaway', 'moodle');
4180 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4181 return $this->render_context_header($contextheader);
4185 * Renders the skip links for the page.
4187 * @param array $links List of skip links.
4188 * @return string HTML for the skip links.
4190 public function render_skip_links($links) {
4191 $context = [ 'links' => []];
4193 foreach ($links as $url => $text) {
4194 $context['links'][] = [ 'url' => $url, 'text' => $text];
4197 return $this->render_from_template('core/skip_links', $context);
4201 * Renders the header bar.
4203 * @param context_header $contextheader Header bar object.
4204 * @return string HTML for the header bar.
4206 protected function render_context_header(context_header $contextheader) {
4208 // All the html stuff goes here.
4209 $html = html_writer::start_div('page-context-header');
4211 // Image data.
4212 if (isset($contextheader->imagedata)) {
4213 // Header specific image.
4214 $html .= html_writer::div($contextheader->imagedata, 'page-header-image');
4217 // Headings.
4218 if (!isset($contextheader->heading)) {
4219 $headings = $this->heading($this->page->heading, $contextheader->headinglevel);
4220 } else {
4221 $headings = $this->heading($contextheader->heading, $contextheader->headinglevel);
4224 $html .= html_writer::tag('div', $headings, array('class' => 'page-header-headings'));
4226 // Buttons.
4227 if (isset($contextheader->additionalbuttons)) {
4228 $html .= html_writer::start_div('btn-group header-button-group');
4229 foreach ($contextheader->additionalbuttons as $button) {
4230 if (!isset($button->page)) {
4231 // Include js for messaging.
4232 if ($button['buttontype'] === 'togglecontact') {
4233 \core_message\helper::togglecontact_requirejs();
4235 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4236 'class' => 'iconsmall',
4237 'role' => 'presentation'
4239 $image .= html_writer::span($button['title'], 'header-button-title');
4240 } else {
4241 $image = html_writer::empty_tag('img', array(
4242 'src' => $button['formattedimage'],
4243 'role' => 'presentation'
4246 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4248 $html .= html_writer::end_div();
4250 $html .= html_writer::end_div();
4252 return $html;
4256 * Wrapper for header elements.
4258 * @return string HTML to display the main header.
4260 public function full_header() {
4261 $html = html_writer::start_tag('header', array('id' => 'page-header', 'class' => 'clearfix'));
4262 $html .= $this->context_header();
4263 $html .= html_writer::start_div('clearfix', array('id' => 'page-navbar'));
4264 $html .= html_writer::tag('div', $this->navbar(), array('class' => 'breadcrumb-nav'));
4265 $html .= html_writer::div($this->page_heading_button(), 'breadcrumb-button');
4266 $html .= html_writer::end_div();
4267 $html .= html_writer::tag('div', $this->course_header(), array('id' => 'course-header'));
4268 $html .= html_writer::end_tag('header');
4269 return $html;
4273 * Displays the list of tags associated with an entry
4275 * @param array $tags list of instances of core_tag or stdClass
4276 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4277 * to use default, set to '' (empty string) to omit the label completely
4278 * @param string $classes additional classes for the enclosing div element
4279 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4280 * will be appended to the end, JS will toggle the rest of the tags
4281 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4282 * @return string
4284 public function tag_list($tags, $label = null, $classes = '', $limit = 10, $pagecontext = null) {
4285 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext);
4286 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4290 * Renders element for inline editing of any value
4292 * @param \core\output\inplace_editable $element
4293 * @return string
4295 public function render_inplace_editable(\core\output\inplace_editable $element) {
4296 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4300 * Renders a bar chart.
4302 * @param \core\chart_bar $chart The chart.
4303 * @return string.
4305 public function render_chart_bar(\core\chart_bar $chart) {
4306 return $this->render_chart($chart);
4310 * Renders a line chart.
4312 * @param \core\chart_line $chart The chart.
4313 * @return string.
4315 public function render_chart_line(\core\chart_line $chart) {
4316 return $this->render_chart($chart);
4320 * Renders a pie chart.
4322 * @param \core\chart_pie $chart The chart.
4323 * @return string.
4325 public function render_chart_pie(\core\chart_pie $chart) {
4326 return $this->render_chart($chart);
4330 * Renders a chart.
4332 * @param \core\chart_base $chart The chart.
4333 * @param bool $withtable Whether to include a data table with the chart.
4334 * @return string.
4336 public function render_chart(\core\chart_base $chart, $withtable = true) {
4337 $chartdata = json_encode($chart);
4338 return $this->render_from_template('core/chart', (object) [
4339 'chartdata' => $chartdata,
4340 'withtable' => $withtable
4345 * Renders the login form.
4347 * @param \core_auth\output\login $form The renderable.
4348 * @return string
4350 public function render_login(\core_auth\output\login $form) {
4351 $context = $form->export_for_template($this);
4353 // Override because rendering is not supported in template yet.
4354 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
4355 $context->errorformatted = $this->error_text($context->error);
4357 return $this->render_from_template('core/login', $context);
4361 * Renders an mform element from a template.
4363 * @param HTML_QuickForm_element $element element
4364 * @param bool $required if input is required field
4365 * @param bool $advanced if input is an advanced field
4366 * @param string $error error message to display
4367 * @param bool $ingroup True if this element is rendered as part of a group
4368 * @return mixed string|bool
4370 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4371 $templatename = 'core_form/element-' . $element->getType();
4372 if ($ingroup) {
4373 $templatename .= "-inline";
4375 try {
4376 // We call this to generate a file not found exception if there is no template.
4377 // We don't want to call export_for_template if there is no template.
4378 core\output\mustache_template_finder::get_template_filepath($templatename);
4380 if ($element instanceof templatable) {
4381 $elementcontext = $element->export_for_template($this);
4383 $helpbutton = '';
4384 if (method_exists($element, 'getHelpButton')) {
4385 $helpbutton = $element->getHelpButton();
4387 $label = $element->getLabel();
4388 $text = '';
4389 if (method_exists($element, 'getText')) {
4390 // There currently exists code that adds a form element with an empty label.
4391 // If this is the case then set the label to the description.
4392 if (empty($label)) {
4393 $label = $element->getText();
4394 } else {
4395 $text = $element->getText();
4399 $context = array(
4400 'element' => $elementcontext,
4401 'label' => $label,
4402 'text' => $text,
4403 'required' => $required,
4404 'advanced' => $advanced,
4405 'helpbutton' => $helpbutton,
4406 'error' => $error
4408 return $this->render_from_template($templatename, $context);
4410 } catch (Exception $e) {
4411 // No template for this element.
4412 return false;
4417 * Render the login signup form into a nice template for the theme.
4419 * @param mform $form
4420 * @return string
4422 public function render_login_signup_form($form) {
4423 $context = $form->export_for_template($this);
4425 return $this->render_from_template('core/signup_form_layout', $context);
4429 * Renders a progress bar.
4431 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4433 * @param progress_bar $bar The bar.
4434 * @return string HTML fragment
4436 public function render_progress_bar(progress_bar $bar) {
4437 global $PAGE;
4438 $data = $bar->export_for_template($this);
4439 return $this->render_from_template('core/progress_bar', $data);
4444 * A renderer that generates output for command-line scripts.
4446 * The implementation of this renderer is probably incomplete.
4448 * @copyright 2009 Tim Hunt
4449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4450 * @since Moodle 2.0
4451 * @package core
4452 * @category output
4454 class core_renderer_cli extends core_renderer {
4457 * Returns the page header.
4459 * @return string HTML fragment
4461 public function header() {
4462 return $this->page->heading . "\n";
4466 * Returns a template fragment representing a Heading.
4468 * @param string $text The text of the heading
4469 * @param int $level The level of importance of the heading
4470 * @param string $classes A space-separated list of CSS classes
4471 * @param string $id An optional ID
4472 * @return string A template fragment for a heading
4474 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4475 $text .= "\n";
4476 switch ($level) {
4477 case 1:
4478 return '=>' . $text;
4479 case 2:
4480 return '-->' . $text;
4481 default:
4482 return $text;
4487 * Returns a template fragment representing a fatal error.
4489 * @param string $message The message to output
4490 * @param string $moreinfourl URL where more info can be found about the error
4491 * @param string $link Link for the Continue button
4492 * @param array $backtrace The execution backtrace
4493 * @param string $debuginfo Debugging information
4494 * @return string A template fragment for a fatal error
4496 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4497 global $CFG;
4499 $output = "!!! $message !!!\n";
4501 if ($CFG->debugdeveloper) {
4502 if (!empty($debuginfo)) {
4503 $output .= $this->notification($debuginfo, 'notifytiny');
4505 if (!empty($backtrace)) {
4506 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
4510 return $output;
4514 * Returns a template fragment representing a notification.
4516 * @param string $message The message to print out.
4517 * @param string $type The type of notification. See constants on \core\output\notification.
4518 * @return string A template fragment for a notification
4520 public function notification($message, $type = null) {
4521 $message = clean_text($message);
4522 if ($type === 'notifysuccess' || $type === 'success') {
4523 return "++ $message ++\n";
4525 return "!! $message !!\n";
4529 * There is no footer for a cli request, however we must override the
4530 * footer method to prevent the default footer.
4532 public function footer() {}
4535 * Render a notification (that is, a status message about something that has
4536 * just happened).
4538 * @param \core\output\notification $notification the notification to print out
4539 * @return string plain text output
4541 public function render_notification(\core\output\notification $notification) {
4542 return $this->notification($notification->get_message(), $notification->get_message_type());
4548 * A renderer that generates output for ajax scripts.
4550 * This renderer prevents accidental sends back only json
4551 * encoded error messages, all other output is ignored.
4553 * @copyright 2010 Petr Skoda
4554 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4555 * @since Moodle 2.0
4556 * @package core
4557 * @category output
4559 class core_renderer_ajax extends core_renderer {
4562 * Returns a template fragment representing a fatal error.
4564 * @param string $message The message to output
4565 * @param string $moreinfourl URL where more info can be found about the error
4566 * @param string $link Link for the Continue button
4567 * @param array $backtrace The execution backtrace
4568 * @param string $debuginfo Debugging information
4569 * @return string A template fragment for a fatal error
4571 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4572 global $CFG;
4574 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
4576 $e = new stdClass();
4577 $e->error = $message;
4578 $e->errorcode = $errorcode;
4579 $e->stacktrace = NULL;
4580 $e->debuginfo = NULL;
4581 $e->reproductionlink = NULL;
4582 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
4583 $link = (string) $link;
4584 if ($link) {
4585 $e->reproductionlink = $link;
4587 if (!empty($debuginfo)) {
4588 $e->debuginfo = $debuginfo;
4590 if (!empty($backtrace)) {
4591 $e->stacktrace = format_backtrace($backtrace, true);
4594 $this->header();
4595 return json_encode($e);
4599 * Used to display a notification.
4600 * For the AJAX notifications are discarded.
4602 * @param string $message The message to print out.
4603 * @param string $type The type of notification. See constants on \core\output\notification.
4605 public function notification($message, $type = null) {}
4608 * Used to display a redirection message.
4609 * AJAX redirections should not occur and as such redirection messages
4610 * are discarded.
4612 * @param moodle_url|string $encodedurl
4613 * @param string $message
4614 * @param int $delay
4615 * @param bool $debugdisableredirect
4616 * @param string $messagetype The type of notification to show the message in.
4617 * See constants on \core\output\notification.
4619 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
4620 $messagetype = \core\output\notification::NOTIFY_INFO) {}
4623 * Prepares the start of an AJAX output.
4625 public function header() {
4626 // unfortunately YUI iframe upload does not support application/json
4627 if (!empty($_FILES)) {
4628 @header('Content-type: text/plain; charset=utf-8');
4629 if (!core_useragent::supports_json_contenttype()) {
4630 @header('X-Content-Type-Options: nosniff');
4632 } else if (!core_useragent::supports_json_contenttype()) {
4633 @header('Content-type: text/plain; charset=utf-8');
4634 @header('X-Content-Type-Options: nosniff');
4635 } else {
4636 @header('Content-type: application/json; charset=utf-8');
4639 // Headers to make it not cacheable and json
4640 @header('Cache-Control: no-store, no-cache, must-revalidate');
4641 @header('Cache-Control: post-check=0, pre-check=0', false);
4642 @header('Pragma: no-cache');
4643 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
4644 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
4645 @header('Accept-Ranges: none');
4649 * There is no footer for an AJAX request, however we must override the
4650 * footer method to prevent the default footer.
4652 public function footer() {}
4655 * No need for headers in an AJAX request... this should never happen.
4656 * @param string $text
4657 * @param int $level
4658 * @param string $classes
4659 * @param string $id
4661 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
4666 * Renderer for media files.
4668 * Used in file resources, media filter, and any other places that need to
4669 * output embedded media.
4671 * @deprecated since Moodle 3.2
4672 * @copyright 2011 The Open University
4673 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4675 class core_media_renderer extends plugin_renderer_base {
4676 /** @var array Array of available 'player' objects */
4677 private $players;
4678 /** @var string Regex pattern for links which may contain embeddable content */
4679 private $embeddablemarkers;
4682 * Constructor
4684 * This is needed in the constructor (not later) so that you can use the
4685 * constants and static functions that are defined in core_media class
4686 * before you call renderer functions.
4688 public function __construct() {
4689 debugging('Class core_media_renderer is deprecated, please use core_media_manager::instance()', DEBUG_DEVELOPER);
4693 * Renders a media file (audio or video) using suitable embedded player.
4695 * See embed_alternatives function for full description of parameters.
4696 * This function calls through to that one.
4698 * When using this function you can also specify width and height in the
4699 * URL by including ?d=100x100 at the end. If specified in the URL, this
4700 * will override the $width and $height parameters.
4702 * @param moodle_url $url Full URL of media file
4703 * @param string $name Optional user-readable name to display in download link
4704 * @param int $width Width in pixels (optional)
4705 * @param int $height Height in pixels (optional)
4706 * @param array $options Array of key/value pairs
4707 * @return string HTML content of embed
4709 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
4710 $options = array()) {
4711 return core_media_manager::instance()->embed_url($url, $name, $width, $height, $options);
4715 * Renders media files (audio or video) using suitable embedded player.
4716 * The list of URLs should be alternative versions of the same content in
4717 * multiple formats. If there is only one format it should have a single
4718 * entry.
4720 * If the media files are not in a supported format, this will give students
4721 * a download link to each format. The download link uses the filename
4722 * unless you supply the optional name parameter.
4724 * Width and height are optional. If specified, these are suggested sizes
4725 * and should be the exact values supplied by the user, if they come from
4726 * user input. These will be treated as relating to the size of the video
4727 * content, not including any player control bar.
4729 * For audio files, height will be ignored. For video files, a few formats
4730 * work if you specify only width, but in general if you specify width
4731 * you must specify height as well.
4733 * The $options array is passed through to the core_media_player classes
4734 * that render the object tag. The keys can contain values from
4735 * core_media::OPTION_xx.
4737 * @param array $alternatives Array of moodle_url to media files
4738 * @param string $name Optional user-readable name to display in download link
4739 * @param int $width Width in pixels (optional)
4740 * @param int $height Height in pixels (optional)
4741 * @param array $options Array of key/value pairs
4742 * @return string HTML content of embed
4744 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
4745 $options = array()) {
4746 return core_media_manager::instance()->embed_alternatives($alternatives, $name, $width, $height, $options);
4750 * Checks whether a file can be embedded. If this returns true you will get
4751 * an embedded player; if this returns false, you will just get a download
4752 * link.
4754 * This is a wrapper for can_embed_urls.
4756 * @param moodle_url $url URL of media file
4757 * @param array $options Options (same as when embedding)
4758 * @return bool True if file can be embedded
4760 public function can_embed_url(moodle_url $url, $options = array()) {
4761 return core_media_manager::instance()->can_embed_url($url, $options);
4765 * Checks whether a file can be embedded. If this returns true you will get
4766 * an embedded player; if this returns false, you will just get a download
4767 * link.
4769 * @param array $urls URL of media file and any alternatives (moodle_url)
4770 * @param array $options Options (same as when embedding)
4771 * @return bool True if file can be embedded
4773 public function can_embed_urls(array $urls, $options = array()) {
4774 return core_media_manager::instance()->can_embed_urls($urls, $options);
4778 * Obtains a list of markers that can be used in a regular expression when
4779 * searching for URLs that can be embedded by any player type.
4781 * This string is used to improve peformance of regex matching by ensuring
4782 * that the (presumably C) regex code can do a quick keyword check on the
4783 * URL part of a link to see if it matches one of these, rather than having
4784 * to go into PHP code for every single link to see if it can be embedded.
4786 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
4788 public function get_embeddable_markers() {
4789 return core_media_manager::instance()->get_embeddable_markers();
4794 * The maintenance renderer.
4796 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
4797 * is running a maintenance related task.
4798 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
4800 * @since Moodle 2.6
4801 * @package core
4802 * @category output
4803 * @copyright 2013 Sam Hemelryk
4804 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4806 class core_renderer_maintenance extends core_renderer {
4809 * Initialises the renderer instance.
4810 * @param moodle_page $page
4811 * @param string $target
4812 * @throws coding_exception
4814 public function __construct(moodle_page $page, $target) {
4815 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
4816 throw new coding_exception('Invalid request for the maintenance renderer.');
4818 parent::__construct($page, $target);
4822 * Does nothing. The maintenance renderer cannot produce blocks.
4824 * @param block_contents $bc
4825 * @param string $region
4826 * @return string
4828 public function block(block_contents $bc, $region) {
4829 // Computer says no blocks.
4830 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4831 return '';
4835 * Does nothing. The maintenance renderer cannot produce blocks.
4837 * @param string $region
4838 * @param array $classes
4839 * @param string $tag
4840 * @return string
4842 public function blocks($region, $classes = array(), $tag = 'aside') {
4843 // Computer says no blocks.
4844 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4845 return '';
4849 * Does nothing. The maintenance renderer cannot produce blocks.
4851 * @param string $region
4852 * @return string
4854 public function blocks_for_region($region) {
4855 // Computer says no blocks for region.
4856 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4857 return '';
4861 * Does nothing. The maintenance renderer cannot produce a course content header.
4863 * @param bool $onlyifnotcalledbefore
4864 * @return string
4866 public function course_content_header($onlyifnotcalledbefore = false) {
4867 // Computer says no course content header.
4868 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4869 return '';
4873 * Does nothing. The maintenance renderer cannot produce a course content footer.
4875 * @param bool $onlyifnotcalledbefore
4876 * @return string
4878 public function course_content_footer($onlyifnotcalledbefore = false) {
4879 // Computer says no course content footer.
4880 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4881 return '';
4885 * Does nothing. The maintenance renderer cannot produce a course header.
4887 * @return string
4889 public function course_header() {
4890 // Computer says no course header.
4891 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4892 return '';
4896 * Does nothing. The maintenance renderer cannot produce a course footer.
4898 * @return string
4900 public function course_footer() {
4901 // Computer says no course footer.
4902 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4903 return '';
4907 * Does nothing. The maintenance renderer cannot produce a custom menu.
4909 * @param string $custommenuitems
4910 * @return string
4912 public function custom_menu($custommenuitems = '') {
4913 // Computer says no custom menu.
4914 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4915 return '';
4919 * Does nothing. The maintenance renderer cannot produce a file picker.
4921 * @param array $options
4922 * @return string
4924 public function file_picker($options) {
4925 // Computer says no file picker.
4926 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4927 return '';
4931 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
4933 * @param array $dir
4934 * @return string
4936 public function htmllize_file_tree($dir) {
4937 // Hell no we don't want no htmllized file tree.
4938 // Also why on earth is this function on the core renderer???
4939 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4940 return '';
4945 * Overridden confirm message for upgrades.
4947 * @param string $message The question to ask the user
4948 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
4949 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
4950 * @return string HTML fragment
4952 public function confirm($message, $continue, $cancel) {
4953 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
4954 // from any previous version of Moodle).
4955 if ($continue instanceof single_button) {
4956 $continue->primary = true;
4957 } else if (is_string($continue)) {
4958 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
4959 } else if ($continue instanceof moodle_url) {
4960 $continue = new single_button($continue, get_string('continue'), 'post', true);
4961 } else {
4962 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
4963 ' (string/moodle_url) or a single_button instance.');
4966 if ($cancel instanceof single_button) {
4967 $output = '';
4968 } else if (is_string($cancel)) {
4969 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
4970 } else if ($cancel instanceof moodle_url) {
4971 $cancel = new single_button($cancel, get_string('cancel'), 'get');
4972 } else {
4973 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
4974 ' (string/moodle_url) or a single_button instance.');
4977 $output = $this->box_start('generalbox', 'notice');
4978 $output .= html_writer::tag('h4', get_string('confirm'));
4979 $output .= html_writer::tag('p', $message);
4980 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
4981 $output .= $this->box_end();
4982 return $output;
4986 * Does nothing. The maintenance renderer does not support JS.
4988 * @param block_contents $bc
4990 public function init_block_hider_js(block_contents $bc) {
4991 // Computer says no JavaScript.
4992 // Do nothing, ridiculous method.
4996 * Does nothing. The maintenance renderer cannot produce language menus.
4998 * @return string
5000 public function lang_menu() {
5001 // Computer says no lang menu.
5002 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5003 return '';
5007 * Does nothing. The maintenance renderer has no need for login information.
5009 * @param null $withlinks
5010 * @return string
5012 public function login_info($withlinks = null) {
5013 // Computer says no login info.
5014 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5015 return '';
5019 * Does nothing. The maintenance renderer cannot produce user pictures.
5021 * @param stdClass $user
5022 * @param array $options
5023 * @return string
5025 public function user_picture(stdClass $user, array $options = null) {
5026 // Computer says no user pictures.
5027 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5028 return '';