MDL-74741 javascript: A11y fix for dialogues visible from beginning
[moodle.git] / lib / outputrenderers.php
blob09ad28616040c5c561984c6e0a76ba43eaeaedc2
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 use core_completion\cm_completion_details;
39 use core_course\output\activity_information;
41 defined('MOODLE_INTERNAL') || die();
43 /**
44 * Simple base class for Moodle renderers.
46 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
48 * Also has methods to facilitate generating HTML output.
50 * @copyright 2009 Tim Hunt
51 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
52 * @since Moodle 2.0
53 * @package core
54 * @category output
56 class renderer_base {
57 /**
58 * @var xhtml_container_stack The xhtml_container_stack to use.
60 protected $opencontainers;
62 /**
63 * @var moodle_page The Moodle page the renderer has been created to assist with.
65 protected $page;
67 /**
68 * @var string The requested rendering target.
70 protected $target;
72 /**
73 * @var Mustache_Engine $mustache The mustache template compiler
75 private $mustache;
77 /**
78 * Return an instance of the mustache class.
80 * @since 2.9
81 * @return Mustache_Engine
83 protected function get_mustache() {
84 global $CFG;
86 if ($this->mustache === null) {
87 require_once("{$CFG->libdir}/filelib.php");
89 $themename = $this->page->theme->name;
90 $themerev = theme_get_revision();
92 // Create new localcache directory.
93 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
95 // Remove old localcache directories.
96 $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR);
97 foreach ($mustachecachedirs as $localcachedir) {
98 $cachedrev = [];
99 preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
100 $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
101 if ($cachedrev > 0 && $cachedrev < $themerev) {
102 fulldelete($localcachedir);
106 $loader = new \core\output\mustache_filesystem_loader();
107 $stringhelper = new \core\output\mustache_string_helper();
108 $cleanstringhelper = new \core\output\mustache_clean_string_helper();
109 $quotehelper = new \core\output\mustache_quote_helper();
110 $jshelper = new \core\output\mustache_javascript_helper($this->page);
111 $pixhelper = new \core\output\mustache_pix_helper($this);
112 $shortentexthelper = new \core\output\mustache_shorten_text_helper();
113 $userdatehelper = new \core\output\mustache_user_date_helper();
115 // We only expose the variables that are exposed to JS templates.
116 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
118 $helpers = array('config' => $safeconfig,
119 'str' => array($stringhelper, 'str'),
120 'cleanstr' => array($cleanstringhelper, 'cleanstr'),
121 'quote' => array($quotehelper, 'quote'),
122 'js' => array($jshelper, 'help'),
123 'pix' => array($pixhelper, 'pix'),
124 'shortentext' => array($shortentexthelper, 'shorten'),
125 'userdate' => array($userdatehelper, 'transform'),
128 $this->mustache = new \core\output\mustache_engine(array(
129 'cache' => $cachedir,
130 'escape' => 's',
131 'loader' => $loader,
132 'helpers' => $helpers,
133 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS],
134 // Don't allow the JavaScript helper to be executed from within another
135 // helper. If it's allowed it can be used by users to inject malicious
136 // JS into the page.
137 'disallowednestedhelpers' => ['js']));
141 return $this->mustache;
146 * Constructor
148 * The constructor takes two arguments. The first is the page that the renderer
149 * has been created to assist with, and the second is the target.
150 * The target is an additional identifier that can be used to load different
151 * renderers for different options.
153 * @param moodle_page $page the page we are doing output for.
154 * @param string $target one of rendering target constants
156 public function __construct(moodle_page $page, $target) {
157 $this->opencontainers = $page->opencontainers;
158 $this->page = $page;
159 $this->target = $target;
163 * Renders a template by name with the given context.
165 * The provided data needs to be array/stdClass made up of only simple types.
166 * Simple types are array,stdClass,bool,int,float,string
168 * @since 2.9
169 * @param array|stdClass $context Context containing data for the template.
170 * @return string|boolean
172 public function render_from_template($templatename, $context) {
173 static $templatecache = array();
174 $mustache = $this->get_mustache();
176 try {
177 // Grab a copy of the existing helper to be restored later.
178 $uniqidhelper = $mustache->getHelper('uniqid');
179 } catch (Mustache_Exception_UnknownHelperException $e) {
180 // Helper doesn't exist.
181 $uniqidhelper = null;
184 // Provide 1 random value that will not change within a template
185 // but will be different from template to template. This is useful for
186 // e.g. aria attributes that only work with id attributes and must be
187 // unique in a page.
188 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
189 if (isset($templatecache[$templatename])) {
190 $template = $templatecache[$templatename];
191 } else {
192 try {
193 $template = $mustache->loadTemplate($templatename);
194 $templatecache[$templatename] = $template;
195 } catch (Mustache_Exception_UnknownTemplateException $e) {
196 throw new moodle_exception('Unknown template: ' . $templatename);
200 $renderedtemplate = trim($template->render($context));
202 // If we had an existing uniqid helper then we need to restore it to allow
203 // handle nested calls of render_from_template.
204 if ($uniqidhelper) {
205 $mustache->addHelper('uniqid', $uniqidhelper);
208 return $renderedtemplate;
213 * Returns rendered widget.
215 * The provided widget needs to be an object that extends the renderable
216 * interface.
217 * If will then be rendered by a method based upon the classname for the widget.
218 * For instance a widget of class `crazywidget` will be rendered by a protected
219 * render_crazywidget method of this renderer.
220 * If no render_crazywidget method exists and crazywidget implements templatable,
221 * look for the 'crazywidget' template in the same component and render that.
223 * @param renderable $widget instance with renderable interface
224 * @return string
226 public function render(renderable $widget) {
227 $classparts = explode('\\', get_class($widget));
228 // Strip namespaces.
229 $classname = array_pop($classparts);
230 // Remove _renderable suffixes
231 $classname = preg_replace('/_renderable$/', '', $classname);
233 $rendermethod = 'render_'.$classname;
234 if (method_exists($this, $rendermethod)) {
235 return $this->$rendermethod($widget);
237 if ($widget instanceof templatable) {
238 $component = array_shift($classparts);
239 if (!$component) {
240 $component = 'core';
242 $template = $component . '/' . $classname;
243 $context = $widget->export_for_template($this);
244 return $this->render_from_template($template, $context);
246 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
250 * Adds a JS action for the element with the provided id.
252 * This method adds a JS event for the provided component action to the page
253 * and then returns the id that the event has been attached to.
254 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
256 * @param component_action $action
257 * @param string $id
258 * @return string id of element, either original submitted or random new if not supplied
260 public function add_action_handler(component_action $action, $id = null) {
261 if (!$id) {
262 $id = html_writer::random_id($action->event);
264 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
265 return $id;
269 * Returns true is output has already started, and false if not.
271 * @return boolean true if the header has been printed.
273 public function has_started() {
274 return $this->page->state >= moodle_page::STATE_IN_BODY;
278 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
280 * @param mixed $classes Space-separated string or array of classes
281 * @return string HTML class attribute value
283 public static function prepare_classes($classes) {
284 if (is_array($classes)) {
285 return implode(' ', array_unique($classes));
287 return $classes;
291 * Return the direct URL for an image from the pix folder.
293 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
295 * @deprecated since Moodle 3.3
296 * @param string $imagename the name of the icon.
297 * @param string $component specification of one plugin like in get_string()
298 * @return moodle_url
300 public function pix_url($imagename, $component = 'moodle') {
301 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
302 return $this->page->theme->image_url($imagename, $component);
306 * Return the moodle_url for an image.
308 * The exact image location and extension is determined
309 * automatically by searching for gif|png|jpg|jpeg, please
310 * note there can not be diferent images with the different
311 * extension. The imagename is for historical reasons
312 * a relative path name, it may be changed later for core
313 * images. It is recommended to not use subdirectories
314 * in plugin and theme pix directories.
316 * There are three types of images:
317 * 1/ theme images - stored in theme/mytheme/pix/,
318 * use component 'theme'
319 * 2/ core images - stored in /pix/,
320 * overridden via theme/mytheme/pix_core/
321 * 3/ plugin images - stored in mod/mymodule/pix,
322 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
323 * example: image_url('comment', 'mod_glossary')
325 * @param string $imagename the pathname of the image
326 * @param string $component full plugin name (aka component) or 'theme'
327 * @return moodle_url
329 public function image_url($imagename, $component = 'moodle') {
330 return $this->page->theme->image_url($imagename, $component);
334 * Return the site's logo URL, if any.
336 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
337 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
338 * @return moodle_url|false
340 public function get_logo_url($maxwidth = null, $maxheight = 200) {
341 global $CFG;
342 $logo = get_config('core_admin', 'logo');
343 if (empty($logo)) {
344 return false;
347 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
348 // It's not worth the overhead of detecting and serving 2 different images based on the device.
350 // Hide the requested size in the file path.
351 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
353 // Use $CFG->themerev to prevent browser caching when the file changes.
354 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
355 theme_get_revision(), $logo);
359 * Return the site's compact logo URL, if any.
361 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
362 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
363 * @return moodle_url|false
365 public function get_compact_logo_url($maxwidth = 300, $maxheight = 300) {
366 global $CFG;
367 $logo = get_config('core_admin', 'logocompact');
368 if (empty($logo)) {
369 return false;
372 // Hide the requested size in the file path.
373 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
375 // Use $CFG->themerev to prevent browser caching when the file changes.
376 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
377 theme_get_revision(), $logo);
381 * Whether we should display the logo in the navbar.
383 * We will when there are no main logos, and we have compact logo.
385 * @return bool
387 public function should_display_navbar_logo() {
388 $logo = $this->get_compact_logo_url();
389 return !empty($logo) && !$this->should_display_main_logo();
393 * Whether we should display the main logo.
395 * @param int $headinglevel The heading level we want to check against.
396 * @return bool
398 public function should_display_main_logo($headinglevel = 1) {
400 // Only render the logo if we're on the front page or login page and the we have a logo.
401 $logo = $this->get_logo_url();
402 if ($headinglevel == 1 && !empty($logo)) {
403 if ($this->page->pagelayout == 'frontpage' || $this->page->pagelayout == 'login') {
404 return true;
408 return false;
415 * Basis for all plugin renderers.
417 * @copyright Petr Skoda (skodak)
418 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
419 * @since Moodle 2.0
420 * @package core
421 * @category output
423 class plugin_renderer_base extends renderer_base {
426 * @var renderer_base|core_renderer A reference to the current renderer.
427 * The renderer provided here will be determined by the page but will in 90%
428 * of cases by the {@link core_renderer}
430 protected $output;
433 * Constructor method, calls the parent constructor
435 * @param moodle_page $page
436 * @param string $target one of rendering target constants
438 public function __construct(moodle_page $page, $target) {
439 if (empty($target) && $page->pagelayout === 'maintenance') {
440 // If the page is using the maintenance layout then we're going to force the target to maintenance.
441 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
442 // unavailable for this page layout.
443 $target = RENDERER_TARGET_MAINTENANCE;
445 $this->output = $page->get_renderer('core', null, $target);
446 parent::__construct($page, $target);
450 * Renders the provided widget and returns the HTML to display it.
452 * @param renderable $widget instance with renderable interface
453 * @return string
455 public function render(renderable $widget) {
456 $classname = get_class($widget);
457 // Strip namespaces.
458 $classname = preg_replace('/^.*\\\/', '', $classname);
459 // Keep a copy at this point, we may need to look for a deprecated method.
460 $deprecatedmethod = 'render_'.$classname;
461 // Remove _renderable suffixes
462 $classname = preg_replace('/_renderable$/', '', $classname);
464 $rendermethod = 'render_'.$classname;
465 if (method_exists($this, $rendermethod)) {
466 return $this->$rendermethod($widget);
468 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
469 // This is exactly where we don't want to be.
470 // If you have arrived here you have a renderable component within your plugin that has the name
471 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
472 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
473 // and the _renderable suffix now gets removed when looking for a render method.
474 // You need to change your renderers render_blah_renderable to render_blah.
475 // Until you do this it will not be possible for a theme to override the renderer to override your method.
476 // Please do it ASAP.
477 static $debugged = array();
478 if (!isset($debugged[$deprecatedmethod])) {
479 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
480 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
481 $debugged[$deprecatedmethod] = true;
483 return $this->$deprecatedmethod($widget);
485 // pass to core renderer if method not found here
486 return $this->output->render($widget);
490 * Magic method used to pass calls otherwise meant for the standard renderer
491 * to it to ensure we don't go causing unnecessary grief.
493 * @param string $method
494 * @param array $arguments
495 * @return mixed
497 public function __call($method, $arguments) {
498 if (method_exists('renderer_base', $method)) {
499 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
501 if (method_exists($this->output, $method)) {
502 return call_user_func_array(array($this->output, $method), $arguments);
503 } else {
504 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
511 * The standard implementation of the core_renderer interface.
513 * @copyright 2009 Tim Hunt
514 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
515 * @since Moodle 2.0
516 * @package core
517 * @category output
519 class core_renderer extends renderer_base {
521 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
522 * in layout files instead.
523 * @deprecated
524 * @var string used in {@link core_renderer::header()}.
526 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
529 * @var string Used to pass information from {@link core_renderer::doctype()} to
530 * {@link core_renderer::standard_head_html()}.
532 protected $contenttype;
535 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
536 * with {@link core_renderer::header()}.
538 protected $metarefreshtag = '';
541 * @var string Unique token for the closing HTML
543 protected $unique_end_html_token;
546 * @var string Unique token for performance information
548 protected $unique_performance_info_token;
551 * @var string Unique token for the main content.
553 protected $unique_main_content_token;
555 /** @var custom_menu_item language The language menu if created */
556 protected $language = null;
559 * Constructor
561 * @param moodle_page $page the page we are doing output for.
562 * @param string $target one of rendering target constants
564 public function __construct(moodle_page $page, $target) {
565 $this->opencontainers = $page->opencontainers;
566 $this->page = $page;
567 $this->target = $target;
569 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
570 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
571 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
575 * Get the DOCTYPE declaration that should be used with this page. Designed to
576 * be called in theme layout.php files.
578 * @return string the DOCTYPE declaration that should be used.
580 public function doctype() {
581 if ($this->page->theme->doctype === 'html5') {
582 $this->contenttype = 'text/html; charset=utf-8';
583 return "<!DOCTYPE html>\n";
585 } else if ($this->page->theme->doctype === 'xhtml5') {
586 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
587 return "<!DOCTYPE html>\n";
589 } else {
590 // legacy xhtml 1.0
591 $this->contenttype = 'text/html; charset=utf-8';
592 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
597 * The attributes that should be added to the <html> tag. Designed to
598 * be called in theme layout.php files.
600 * @return string HTML fragment.
602 public function htmlattributes() {
603 $return = get_html_lang(true);
604 $attributes = array();
605 if ($this->page->theme->doctype !== 'html5') {
606 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
609 // Give plugins an opportunity to add things like xml namespaces to the html element.
610 // This function should return an array of html attribute names => values.
611 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
612 foreach ($pluginswithfunction as $plugins) {
613 foreach ($plugins as $function) {
614 $newattrs = $function();
615 unset($newattrs['dir']);
616 unset($newattrs['lang']);
617 unset($newattrs['xmlns']);
618 unset($newattrs['xml:lang']);
619 $attributes += $newattrs;
623 foreach ($attributes as $key => $val) {
624 $val = s($val);
625 $return .= " $key=\"$val\"";
628 return $return;
632 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
633 * that should be included in the <head> tag. Designed to be called in theme
634 * layout.php files.
636 * @return string HTML fragment.
638 public function standard_head_html() {
639 global $CFG, $SESSION, $SITE;
641 // Before we output any content, we need to ensure that certain
642 // page components are set up.
644 // Blocks must be set up early as they may require javascript which
645 // has to be included in the page header before output is created.
646 foreach ($this->page->blocks->get_regions() as $region) {
647 $this->page->blocks->ensure_content_created($region, $this);
650 $output = '';
652 // Give plugins an opportunity to add any head elements. The callback
653 // must always return a string containing valid html head content.
654 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
655 foreach ($pluginswithfunction as $plugins) {
656 foreach ($plugins as $function) {
657 $output .= $function();
661 // Allow a url_rewrite plugin to setup any dynamic head content.
662 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
663 $class = $CFG->urlrewriteclass;
664 $output .= $class::html_head_setup();
667 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
668 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
669 // This is only set by the {@link redirect()} method
670 $output .= $this->metarefreshtag;
672 // Check if a periodic refresh delay has been set and make sure we arn't
673 // already meta refreshing
674 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
675 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
678 // Set up help link popups for all links with the helptooltip class
679 $this->page->requires->js_init_call('M.util.help_popups.setup');
681 $focus = $this->page->focuscontrol;
682 if (!empty($focus)) {
683 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
684 // This is a horrifically bad way to handle focus but it is passed in
685 // through messy formslib::moodleform
686 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
687 } else if (strpos($focus, '.')!==false) {
688 // Old style of focus, bad way to do it
689 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);
690 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
691 } else {
692 // Focus element with given id
693 $this->page->requires->js_function_call('focuscontrol', array($focus));
697 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
698 // any other custom CSS can not be overridden via themes and is highly discouraged
699 $urls = $this->page->theme->css_urls($this->page);
700 foreach ($urls as $url) {
701 $this->page->requires->css_theme($url);
704 // Get the theme javascript head and footer
705 if ($jsurl = $this->page->theme->javascript_url(true)) {
706 $this->page->requires->js($jsurl, true);
708 if ($jsurl = $this->page->theme->javascript_url(false)) {
709 $this->page->requires->js($jsurl);
712 // Get any HTML from the page_requirements_manager.
713 $output .= $this->page->requires->get_head_code($this->page, $this);
715 // List alternate versions.
716 foreach ($this->page->alternateversions as $type => $alt) {
717 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
718 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
721 // Add noindex tag if relevant page and setting applied.
722 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
723 $loginpages = array('login-index', 'login-signup');
724 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
725 if (!isset($CFG->additionalhtmlhead)) {
726 $CFG->additionalhtmlhead = '';
728 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
731 if (!empty($CFG->additionalhtmlhead)) {
732 $output .= "\n".$CFG->additionalhtmlhead;
735 if ($this->page->pagelayout == 'frontpage') {
736 $summary = s(strip_tags(format_text($SITE->summary, FORMAT_HTML)));
737 if (!empty($summary)) {
738 $output .= "<meta name=\"description\" content=\"$summary\" />\n";
742 return $output;
746 * The standard tags (typically skip links) that should be output just inside
747 * the start of the <body> tag. Designed to be called in theme layout.php files.
749 * @return string HTML fragment.
751 public function standard_top_of_body_html() {
752 global $CFG;
753 $output = $this->page->requires->get_top_of_body_code($this);
754 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
755 $output .= "\n".$CFG->additionalhtmltopofbody;
758 // Give subsystems an opportunity to inject extra html content. The callback
759 // must always return a string containing valid html.
760 foreach (\core_component::get_core_subsystems() as $name => $path) {
761 if ($path) {
762 $output .= component_callback($name, 'before_standard_top_of_body_html', [], '');
766 // Give plugins an opportunity to inject extra html content. The callback
767 // must always return a string containing valid html.
768 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
769 foreach ($pluginswithfunction as $plugins) {
770 foreach ($plugins as $function) {
771 $output .= $function();
775 $output .= $this->maintenance_warning();
777 return $output;
781 * Scheduled maintenance warning message.
783 * Note: This is a nasty hack to display maintenance notice, this should be moved
784 * to some general notification area once we have it.
786 * @return string
788 public function maintenance_warning() {
789 global $CFG;
791 $output = '';
792 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
793 $timeleft = $CFG->maintenance_later - time();
794 // If timeleft less than 30 sec, set the class on block to error to highlight.
795 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
796 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-3 alert');
797 $a = new stdClass();
798 $a->hour = (int)($timeleft / 3600);
799 $a->min = (int)(($timeleft / 60) % 60);
800 $a->sec = (int)($timeleft % 60);
801 if ($a->hour > 0) {
802 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
803 } else {
804 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
807 $output .= $this->box_end();
808 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
809 array(array('timeleftinsec' => $timeleft)));
810 $this->page->requires->strings_for_js(
811 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
812 'admin');
814 return $output;
818 * The standard tags (typically performance information and validation links,
819 * if we are in developer debug mode) that should be output in the footer area
820 * of the page. Designed to be called in theme layout.php files.
822 * @return string HTML fragment.
824 public function standard_footer_html() {
825 global $CFG, $SCRIPT;
827 $output = '';
828 if (during_initial_install()) {
829 // Debugging info can not work before install is finished,
830 // in any case we do not want any links during installation!
831 return $output;
834 // Give plugins an opportunity to add any footer elements.
835 // The callback must always return a string containing valid html footer content.
836 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
837 foreach ($pluginswithfunction as $plugins) {
838 foreach ($plugins as $function) {
839 $output .= $function();
843 if (core_userfeedback::can_give_feedback()) {
844 $output .= html_writer::div(
845 $this->render_from_template('core/userfeedback_footer_link', ['url' => core_userfeedback::make_link()->out(false)])
849 // This function is normally called from a layout.php file in {@link core_renderer::header()}
850 // but some of the content won't be known until later, so we return a placeholder
851 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
852 $output .= $this->unique_performance_info_token;
853 if ($this->page->devicetypeinuse == 'legacy') {
854 // The legacy theme is in use print the notification
855 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
858 // Get links to switch device types (only shown for users not on a default device)
859 $output .= $this->theme_switch_links();
861 if (!empty($CFG->debugpageinfo)) {
862 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
863 $this->page->debug_summary()) . '</div>';
865 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
866 // Add link to profiling report if necessary
867 if (function_exists('profiling_is_running') && profiling_is_running()) {
868 $txt = get_string('profiledscript', 'admin');
869 $title = get_string('profiledscriptview', 'admin');
870 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
871 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
872 $output .= '<div class="profilingfooter">' . $link . '</div>';
874 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
875 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
876 $output .= '<div class="purgecaches">' .
877 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
879 if (!empty($CFG->debugvalidators)) {
880 $siteurl = qualified_me();
881 $nuurl = new moodle_url('https://validator.w3.org/nu/', ['doc' => $siteurl, 'showsource' => 'yes']);
882 $waveurl = new moodle_url('https://wave.webaim.org/report#/' . urlencode($siteurl));
883 $validatorlinks = [
884 html_writer::link($nuurl, get_string('validatehtml')),
885 html_writer::link($waveurl, get_string('wcagcheck'))
887 $validatorlinkslist = html_writer::alist($validatorlinks, ['class' => 'list-unstyled ml-1']);
888 $output .= html_writer::div($validatorlinkslist, 'validators');
890 return $output;
894 * Returns standard main content placeholder.
895 * Designed to be called in theme layout.php files.
897 * @return string HTML fragment.
899 public function main_content() {
900 // This is here because it is the only place we can inject the "main" role over the entire main content area
901 // without requiring all theme's to manually do it, and without creating yet another thing people need to
902 // remember in the theme.
903 // This is an unfortunate hack. DO NO EVER add anything more here.
904 // DO NOT add classes.
905 // DO NOT add an id.
906 return '<div role="main">'.$this->unique_main_content_token.'</div>';
910 * Returns information about an activity.
912 * @param cm_info $cminfo The course module information.
913 * @param cm_completion_details $completiondetails The completion details for this activity module.
914 * @param array $activitydates The dates for this activity module.
915 * @return string the activity information HTML.
916 * @throws coding_exception
918 public function activity_information(cm_info $cminfo, cm_completion_details $completiondetails, array $activitydates): string {
919 if (!$completiondetails->has_completion() && empty($activitydates)) {
920 // No need to render the activity information when there's no completion info and activity dates to show.
921 return '';
923 $activityinfo = new activity_information($cminfo, $completiondetails, $activitydates);
924 $renderer = $this->page->get_renderer('core', 'course');
925 return $renderer->render($activityinfo);
929 * Returns standard navigation between activities in a course.
931 * @return string the navigation HTML.
933 public function activity_navigation() {
934 // First we should check if we want to add navigation.
935 $context = $this->page->context;
936 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
937 || $context->contextlevel != CONTEXT_MODULE) {
938 return '';
941 // If the activity is in stealth mode, show no links.
942 if ($this->page->cm->is_stealth()) {
943 return '';
946 // Get a list of all the activities in the course.
947 $course = $this->page->cm->get_course();
948 $modules = get_fast_modinfo($course->id)->get_cms();
950 // Put the modules into an array in order by the position they are shown in the course.
951 $mods = [];
952 $activitylist = [];
953 foreach ($modules as $module) {
954 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
955 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
956 continue;
958 $mods[$module->id] = $module;
960 // No need to add the current module to the list for the activity dropdown menu.
961 if ($module->id == $this->page->cm->id) {
962 continue;
964 // Module name.
965 $modname = $module->get_formatted_name();
966 // Display the hidden text if necessary.
967 if (!$module->visible) {
968 $modname .= ' ' . get_string('hiddenwithbrackets');
970 // Module URL.
971 $linkurl = new moodle_url($module->url, array('forceview' => 1));
972 // Add module URL (as key) and name (as value) to the activity list array.
973 $activitylist[$linkurl->out(false)] = $modname;
976 $nummods = count($mods);
978 // If there is only one mod then do nothing.
979 if ($nummods == 1) {
980 return '';
983 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
984 $modids = array_keys($mods);
986 // Get the position in the array of the course module we are viewing.
987 $position = array_search($this->page->cm->id, $modids);
989 $prevmod = null;
990 $nextmod = null;
992 // Check if we have a previous mod to show.
993 if ($position > 0) {
994 $prevmod = $mods[$modids[$position - 1]];
997 // Check if we have a next mod to show.
998 if ($position < ($nummods - 1)) {
999 $nextmod = $mods[$modids[$position + 1]];
1002 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
1003 $renderer = $this->page->get_renderer('core', 'course');
1004 return $renderer->render($activitynav);
1008 * The standard tags (typically script tags that are not needed earlier) that
1009 * should be output after everything else. Designed to be called in theme layout.php files.
1011 * @return string HTML fragment.
1013 public function standard_end_of_body_html() {
1014 global $CFG;
1016 // This function is normally called from a layout.php file in {@link core_renderer::header()}
1017 // but some of the content won't be known until later, so we return a placeholder
1018 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
1019 $output = '';
1020 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
1021 $output .= "\n".$CFG->additionalhtmlfooter;
1023 $output .= $this->unique_end_html_token;
1024 return $output;
1028 * The standard HTML that should be output just before the <footer> tag.
1029 * Designed to be called in theme layout.php files.
1031 * @return string HTML fragment.
1033 public function standard_after_main_region_html() {
1034 global $CFG;
1035 $output = '';
1036 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlbottomofbody)) {
1037 $output .= "\n".$CFG->additionalhtmlbottomofbody;
1040 // Give subsystems an opportunity to inject extra html content. The callback
1041 // must always return a string containing valid html.
1042 foreach (\core_component::get_core_subsystems() as $name => $path) {
1043 if ($path) {
1044 $output .= component_callback($name, 'standard_after_main_region_html', [], '');
1048 // Give plugins an opportunity to inject extra html content. The callback
1049 // must always return a string containing valid html.
1050 $pluginswithfunction = get_plugins_with_function('standard_after_main_region_html', 'lib.php');
1051 foreach ($pluginswithfunction as $plugins) {
1052 foreach ($plugins as $function) {
1053 $output .= $function();
1057 return $output;
1061 * Return the standard string that says whether you are logged in (and switched
1062 * roles/logged in as another user).
1063 * @param bool $withlinks if false, then don't include any links in the HTML produced.
1064 * If not set, the default is the nologinlinks option from the theme config.php file,
1065 * and if that is not set, then links are included.
1066 * @return string HTML fragment.
1068 public function login_info($withlinks = null) {
1069 global $USER, $CFG, $DB, $SESSION;
1071 if (during_initial_install()) {
1072 return '';
1075 if (is_null($withlinks)) {
1076 $withlinks = empty($this->page->layout_options['nologinlinks']);
1079 $course = $this->page->course;
1080 if (\core\session\manager::is_loggedinas()) {
1081 $realuser = \core\session\manager::get_realuser();
1082 $fullname = fullname($realuser);
1083 if ($withlinks) {
1084 $loginastitle = get_string('loginas');
1085 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
1086 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
1087 } else {
1088 $realuserinfo = " [$fullname] ";
1090 } else {
1091 $realuserinfo = '';
1094 $loginpage = $this->is_login_page();
1095 $loginurl = get_login_url();
1097 if (empty($course->id)) {
1098 // $course->id is not defined during installation
1099 return '';
1100 } else if (isloggedin()) {
1101 $context = context_course::instance($course->id);
1103 $fullname = fullname($USER);
1104 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
1105 if ($withlinks) {
1106 $linktitle = get_string('viewprofile');
1107 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
1108 } else {
1109 $username = $fullname;
1111 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
1112 if ($withlinks) {
1113 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1114 } else {
1115 $username .= " from {$idprovider->name}";
1118 if (isguestuser()) {
1119 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1120 if (!$loginpage && $withlinks) {
1121 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1123 } else if (is_role_switched($course->id)) { // Has switched roles
1124 $rolename = '';
1125 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1126 $rolename = ': '.role_get_name($role, $context);
1128 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1129 if ($withlinks) {
1130 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1131 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1133 } else {
1134 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1135 if ($withlinks) {
1136 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1139 } else {
1140 $loggedinas = get_string('loggedinnot', 'moodle');
1141 if (!$loginpage && $withlinks) {
1142 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1146 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1148 if (isset($SESSION->justloggedin)) {
1149 unset($SESSION->justloggedin);
1150 if (!isguestuser()) {
1151 // Include this file only when required.
1152 require_once($CFG->dirroot . '/user/lib.php');
1153 if (($count = user_count_login_failures($USER)) && !empty($CFG->displayloginfailures)) {
1154 $loggedinas .= '<div class="loginfailures">';
1155 $a = new stdClass();
1156 $a->attempts = $count;
1157 $loggedinas .= get_string('failedloginattempts', '', $a);
1158 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1159 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1160 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1162 $loggedinas .= '</div>';
1167 return $loggedinas;
1171 * Check whether the current page is a login page.
1173 * @since Moodle 2.9
1174 * @return bool
1176 protected function is_login_page() {
1177 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1178 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1179 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1180 return in_array(
1181 $this->page->url->out_as_local_url(false, array()),
1182 array(
1183 '/login/index.php',
1184 '/login/forgot_password.php',
1190 * Return the 'back' link that normally appears in the footer.
1192 * @return string HTML fragment.
1194 public function home_link() {
1195 global $CFG, $SITE;
1197 if ($this->page->pagetype == 'site-index') {
1198 // Special case for site home page - please do not remove
1199 return '<div class="sitelink">' .
1200 '<a title="Moodle" class="d-inline-block aalink" href="http://moodle.org/">' .
1201 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1203 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1204 // Special case for during install/upgrade.
1205 return '<div class="sitelink">'.
1206 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1207 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1209 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1210 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1211 get_string('home') . '</a></div>';
1213 } else {
1214 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1215 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1220 * Redirects the user by any means possible given the current state
1222 * This function should not be called directly, it should always be called using
1223 * the redirect function in lib/weblib.php
1225 * The redirect function should really only be called before page output has started
1226 * however it will allow itself to be called during the state STATE_IN_BODY
1228 * @param string $encodedurl The URL to send to encoded if required
1229 * @param string $message The message to display to the user if any
1230 * @param int $delay The delay before redirecting a user, if $message has been
1231 * set this is a requirement and defaults to 3, set to 0 no delay
1232 * @param boolean $debugdisableredirect this redirect has been disabled for
1233 * debugging purposes. Display a message that explains, and don't
1234 * trigger the redirect.
1235 * @param string $messagetype The type of notification to show the message in.
1236 * See constants on \core\output\notification.
1237 * @return string The HTML to display to the user before dying, may contain
1238 * meta refresh, javascript refresh, and may have set header redirects
1240 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1241 $messagetype = \core\output\notification::NOTIFY_INFO) {
1242 global $CFG;
1243 $url = str_replace('&amp;', '&', $encodedurl);
1245 switch ($this->page->state) {
1246 case moodle_page::STATE_BEFORE_HEADER :
1247 // No output yet it is safe to delivery the full arsenal of redirect methods
1248 if (!$debugdisableredirect) {
1249 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1250 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1251 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1253 $output = $this->header();
1254 break;
1255 case moodle_page::STATE_PRINTING_HEADER :
1256 // We should hopefully never get here
1257 throw new coding_exception('You cannot redirect while printing the page header');
1258 break;
1259 case moodle_page::STATE_IN_BODY :
1260 // We really shouldn't be here but we can deal with this
1261 debugging("You should really redirect before you start page output");
1262 if (!$debugdisableredirect) {
1263 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1265 $output = $this->opencontainers->pop_all_but_last();
1266 break;
1267 case moodle_page::STATE_DONE :
1268 // Too late to be calling redirect now
1269 throw new coding_exception('You cannot redirect after the entire page has been generated');
1270 break;
1272 $output .= $this->notification($message, $messagetype);
1273 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1274 if ($debugdisableredirect) {
1275 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1277 $output .= $this->footer();
1278 return $output;
1282 * Start output by sending the HTTP headers, and printing the HTML <head>
1283 * and the start of the <body>.
1285 * To control what is printed, you should set properties on $PAGE.
1287 * @return string HTML that you must output this, preferably immediately.
1289 public function header() {
1290 global $USER, $CFG, $SESSION;
1292 // Give plugins an opportunity touch things before the http headers are sent
1293 // such as adding additional headers. The return value is ignored.
1294 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1295 foreach ($pluginswithfunction as $plugins) {
1296 foreach ($plugins as $function) {
1297 $function();
1301 if (\core\session\manager::is_loggedinas()) {
1302 $this->page->add_body_class('userloggedinas');
1305 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1306 require_once($CFG->dirroot . '/user/lib.php');
1307 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1308 if ($count = user_count_login_failures($USER, false)) {
1309 $this->page->add_body_class('loginfailures');
1313 // If the user is logged in, and we're not in initial install,
1314 // check to see if the user is role-switched and add the appropriate
1315 // CSS class to the body element.
1316 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1317 $this->page->add_body_class('userswitchedrole');
1320 // Give themes a chance to init/alter the page object.
1321 $this->page->theme->init_page($this->page);
1323 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1325 // Find the appropriate page layout file, based on $this->page->pagelayout.
1326 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1327 // Render the layout using the layout file.
1328 $rendered = $this->render_page_layout($layoutfile);
1330 // Slice the rendered output into header and footer.
1331 $cutpos = strpos($rendered, $this->unique_main_content_token);
1332 if ($cutpos === false) {
1333 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1334 $token = self::MAIN_CONTENT_TOKEN;
1335 } else {
1336 $token = $this->unique_main_content_token;
1339 if ($cutpos === false) {
1340 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.');
1342 $header = substr($rendered, 0, $cutpos);
1343 $footer = substr($rendered, $cutpos + strlen($token));
1345 if (empty($this->contenttype)) {
1346 debugging('The page layout file did not call $OUTPUT->doctype()');
1347 $header = $this->doctype() . $header;
1350 // If this theme version is below 2.4 release and this is a course view page
1351 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1352 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1353 // check if course content header/footer have not been output during render of theme layout
1354 $coursecontentheader = $this->course_content_header(true);
1355 $coursecontentfooter = $this->course_content_footer(true);
1356 if (!empty($coursecontentheader)) {
1357 // display debug message and add header and footer right above and below main content
1358 // Please note that course header and footer (to be displayed above and below the whole page)
1359 // are not displayed in this case at all.
1360 // Besides the content header and footer are not displayed on any other course page
1361 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);
1362 $header .= $coursecontentheader;
1363 $footer = $coursecontentfooter. $footer;
1367 send_headers($this->contenttype, $this->page->cacheable);
1369 $this->opencontainers->push('header/footer', $footer);
1370 $this->page->set_state(moodle_page::STATE_IN_BODY);
1372 return $header . $this->skip_link_target('maincontent');
1376 * Renders and outputs the page layout file.
1378 * This is done by preparing the normal globals available to a script, and
1379 * then including the layout file provided by the current theme for the
1380 * requested layout.
1382 * @param string $layoutfile The name of the layout file
1383 * @return string HTML code
1385 protected function render_page_layout($layoutfile) {
1386 global $CFG, $SITE, $USER;
1387 // The next lines are a bit tricky. The point is, here we are in a method
1388 // of a renderer class, and this object may, or may not, be the same as
1389 // the global $OUTPUT object. When rendering the page layout file, we want to use
1390 // this object. However, people writing Moodle code expect the current
1391 // renderer to be called $OUTPUT, not $this, so define a variable called
1392 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1393 $OUTPUT = $this;
1394 $PAGE = $this->page;
1395 $COURSE = $this->page->course;
1397 ob_start();
1398 include($layoutfile);
1399 $rendered = ob_get_contents();
1400 ob_end_clean();
1401 return $rendered;
1405 * Outputs the page's footer
1407 * @return string HTML fragment
1409 public function footer() {
1410 global $CFG, $DB;
1412 $output = '';
1414 // Give plugins an opportunity to touch the page before JS is finalized.
1415 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1416 foreach ($pluginswithfunction as $plugins) {
1417 foreach ($plugins as $function) {
1418 $extrafooter = $function();
1419 if (is_string($extrafooter)) {
1420 $output .= $extrafooter;
1425 $output .= $this->container_end_all(true);
1427 $footer = $this->opencontainers->pop('header/footer');
1429 if (debugging() and $DB and $DB->is_transaction_started()) {
1430 // TODO: MDL-20625 print warning - transaction will be rolled back
1433 // Provide some performance info if required
1434 $performanceinfo = '';
1435 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1436 $perf = get_performance_info();
1437 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1438 $performanceinfo = $perf['html'];
1442 // We always want performance data when running a performance test, even if the user is redirected to another page.
1443 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1444 $footer = $this->unique_performance_info_token . $footer;
1446 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1448 // Only show notifications when the current page has a context id.
1449 if (!empty($this->page->context->id)) {
1450 $this->page->requires->js_call_amd('core/notification', 'init', array(
1451 $this->page->context->id,
1452 \core\notification::fetch_as_array($this)
1455 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1457 $this->page->set_state(moodle_page::STATE_DONE);
1459 return $output . $footer;
1463 * Close all but the last open container. This is useful in places like error
1464 * handling, where you want to close all the open containers (apart from <body>)
1465 * before outputting the error message.
1467 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1468 * developer debug warning if it isn't.
1469 * @return string the HTML required to close any open containers inside <body>.
1471 public function container_end_all($shouldbenone = false) {
1472 return $this->opencontainers->pop_all_but_last($shouldbenone);
1476 * Returns course-specific information to be output immediately above content on any course page
1477 * (for the current course)
1479 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1480 * @return string
1482 public function course_content_header($onlyifnotcalledbefore = false) {
1483 global $CFG;
1484 static $functioncalled = false;
1485 if ($functioncalled && $onlyifnotcalledbefore) {
1486 // we have already output the content header
1487 return '';
1490 // Output any session notification.
1491 $notifications = \core\notification::fetch();
1493 $bodynotifications = '';
1494 foreach ($notifications as $notification) {
1495 $bodynotifications .= $this->render_from_template(
1496 $notification->get_template_name(),
1497 $notification->export_for_template($this)
1501 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1503 if ($this->page->course->id == SITEID) {
1504 // return immediately and do not include /course/lib.php if not necessary
1505 return $output;
1508 require_once($CFG->dirroot.'/course/lib.php');
1509 $functioncalled = true;
1510 $courseformat = course_get_format($this->page->course);
1511 if (($obj = $courseformat->course_content_header()) !== null) {
1512 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1514 return $output;
1518 * Returns course-specific information to be output immediately below content on any course page
1519 * (for the current course)
1521 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1522 * @return string
1524 public function course_content_footer($onlyifnotcalledbefore = false) {
1525 global $CFG;
1526 if ($this->page->course->id == SITEID) {
1527 // return immediately and do not include /course/lib.php if not necessary
1528 return '';
1530 static $functioncalled = false;
1531 if ($functioncalled && $onlyifnotcalledbefore) {
1532 // we have already output the content footer
1533 return '';
1535 $functioncalled = true;
1536 require_once($CFG->dirroot.'/course/lib.php');
1537 $courseformat = course_get_format($this->page->course);
1538 if (($obj = $courseformat->course_content_footer()) !== null) {
1539 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1541 return '';
1545 * Returns course-specific information to be output on any course page in the header area
1546 * (for the current course)
1548 * @return string
1550 public function course_header() {
1551 global $CFG;
1552 if ($this->page->course->id == SITEID) {
1553 // return immediately and do not include /course/lib.php if not necessary
1554 return '';
1556 require_once($CFG->dirroot.'/course/lib.php');
1557 $courseformat = course_get_format($this->page->course);
1558 if (($obj = $courseformat->course_header()) !== null) {
1559 return $courseformat->get_renderer($this->page)->render($obj);
1561 return '';
1565 * Returns course-specific information to be output on any course page in the footer area
1566 * (for the current course)
1568 * @return string
1570 public function course_footer() {
1571 global $CFG;
1572 if ($this->page->course->id == SITEID) {
1573 // return immediately and do not include /course/lib.php if not necessary
1574 return '';
1576 require_once($CFG->dirroot.'/course/lib.php');
1577 $courseformat = course_get_format($this->page->course);
1578 if (($obj = $courseformat->course_footer()) !== null) {
1579 return $courseformat->get_renderer($this->page)->render($obj);
1581 return '';
1585 * Get the course pattern datauri to show on a course card.
1587 * The datauri is an encoded svg that can be passed as a url.
1588 * @param int $id Id to use when generating the pattern
1589 * @return string datauri
1591 public function get_generated_image_for_id($id) {
1592 $color = $this->get_generated_color_for_id($id);
1593 $pattern = new \core_geopattern();
1594 $pattern->setColor($color);
1595 $pattern->patternbyid($id);
1596 return $pattern->datauri();
1600 * Get the course color to show on a course card.
1602 * @param int $id Id to use when generating the color.
1603 * @return string hex color code.
1605 public function get_generated_color_for_id($id) {
1606 $colornumbers = range(1, 10);
1607 $basecolors = [];
1608 foreach ($colornumbers as $number) {
1609 $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1612 $color = $basecolors[$id % 10];
1613 return $color;
1617 * Returns lang menu or '', this method also checks forcing of languages in courses.
1619 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1621 * @return string The lang menu HTML or empty string
1623 public function lang_menu() {
1624 global $CFG;
1626 if (empty($CFG->langmenu)) {
1627 return '';
1630 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1631 // do not show lang menu if language forced
1632 return '';
1635 $currlang = current_language();
1636 $langs = get_string_manager()->get_list_of_translations();
1638 if (count($langs) < 2) {
1639 return '';
1642 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1643 $s->label = get_accesshide(get_string('language'));
1644 $s->class = 'langmenu';
1645 return $this->render($s);
1649 * Output the row of editing icons for a block, as defined by the controls array.
1651 * @param array $controls an array like {@link block_contents::$controls}.
1652 * @param string $blockid The ID given to the block.
1653 * @return string HTML fragment.
1655 public function block_controls($actions, $blockid = null) {
1656 global $CFG;
1657 if (empty($actions)) {
1658 return '';
1660 $menu = new action_menu($actions);
1661 if ($blockid !== null) {
1662 $menu->set_owner_selector('#'.$blockid);
1664 $menu->set_constraint('.block-region');
1665 $menu->attributes['class'] .= ' block-control-actions commands';
1666 return $this->render($menu);
1670 * Returns the HTML for a basic textarea field.
1672 * @param string $name Name to use for the textarea element
1673 * @param string $id The id to use fort he textarea element
1674 * @param string $value Initial content to display in the textarea
1675 * @param int $rows Number of rows to display
1676 * @param int $cols Number of columns to display
1677 * @return string the HTML to display
1679 public function print_textarea($name, $id, $value, $rows, $cols) {
1680 editors_head_setup();
1681 $editor = editors_get_preferred_editor(FORMAT_HTML);
1682 $editor->set_text($value);
1683 $editor->use_editor($id, []);
1685 $context = [
1686 'id' => $id,
1687 'name' => $name,
1688 'value' => $value,
1689 'rows' => $rows,
1690 'cols' => $cols
1693 return $this->render_from_template('core_form/editor_textarea', $context);
1697 * Renders an action menu component.
1699 * @param action_menu $menu
1700 * @return string HTML
1702 public function render_action_menu(action_menu $menu) {
1704 // We don't want the class icon there!
1705 foreach ($menu->get_secondary_actions() as $action) {
1706 if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1707 $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1711 if ($menu->is_empty()) {
1712 return '';
1714 $context = $menu->export_for_template($this);
1716 return $this->render_from_template('core/action_menu', $context);
1720 * Renders a Check API result
1722 * @param result $result
1723 * @return string HTML fragment
1725 protected function render_check_result(core\check\result $result) {
1726 return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1730 * Renders a Check API result
1732 * @param result $result
1733 * @return string HTML fragment
1735 public function check_result(core\check\result $result) {
1736 return $this->render_check_result($result);
1740 * Renders an action_menu_link item.
1742 * @param action_menu_link $action
1743 * @return string HTML fragment
1745 protected function render_action_menu_link(action_menu_link $action) {
1746 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1750 * Renders a primary action_menu_filler item.
1752 * @param action_menu_link_filler $action
1753 * @return string HTML fragment
1755 protected function render_action_menu_filler(action_menu_filler $action) {
1756 return html_writer::span('&nbsp;', 'filler');
1760 * Renders a primary action_menu_link item.
1762 * @param action_menu_link_primary $action
1763 * @return string HTML fragment
1765 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1766 return $this->render_action_menu_link($action);
1770 * Renders a secondary action_menu_link item.
1772 * @param action_menu_link_secondary $action
1773 * @return string HTML fragment
1775 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1776 return $this->render_action_menu_link($action);
1780 * Prints a nice side block with an optional header.
1782 * @param block_contents $bc HTML for the content
1783 * @param string $region the region the block is appearing in.
1784 * @return string the HTML to be output.
1786 public function block(block_contents $bc, $region) {
1787 $bc = clone($bc); // Avoid messing up the object passed in.
1788 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1789 $bc->collapsible = block_contents::NOT_HIDEABLE;
1792 $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1793 $context = new stdClass();
1794 $context->skipid = $bc->skipid;
1795 $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
1796 $context->dockable = $bc->dockable;
1797 $context->id = $id;
1798 $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1799 $context->skiptitle = strip_tags($bc->title);
1800 $context->showskiplink = !empty($context->skiptitle);
1801 $context->arialabel = $bc->arialabel;
1802 $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
1803 $context->class = $bc->attributes['class'];
1804 $context->type = $bc->attributes['data-block'];
1805 $context->title = $bc->title;
1806 $context->content = $bc->content;
1807 $context->annotation = $bc->annotation;
1808 $context->footer = $bc->footer;
1809 $context->hascontrols = !empty($bc->controls);
1810 if ($context->hascontrols) {
1811 $context->controls = $this->block_controls($bc->controls, $id);
1814 return $this->render_from_template('core/block', $context);
1818 * Render the contents of a block_list.
1820 * @param array $icons the icon for each item.
1821 * @param array $items the content of each item.
1822 * @return string HTML
1824 public function list_block_contents($icons, $items) {
1825 $row = 0;
1826 $lis = array();
1827 foreach ($items as $key => $string) {
1828 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1829 if (!empty($icons[$key])) { //test if the content has an assigned icon
1830 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1832 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1833 $item .= html_writer::end_tag('li');
1834 $lis[] = $item;
1835 $row = 1 - $row; // Flip even/odd.
1837 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1841 * Output all the blocks in a particular region.
1843 * @param string $region the name of a region on this page.
1844 * @param boolean $fakeblocksonly Output fake block only.
1845 * @return string the HTML to be output.
1847 public function blocks_for_region($region, $fakeblocksonly = false) {
1848 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1849 $lastblock = null;
1850 $zones = array();
1851 foreach ($blockcontents as $bc) {
1852 if ($bc instanceof block_contents) {
1853 $zones[] = $bc->title;
1856 $output = '';
1858 foreach ($blockcontents as $bc) {
1859 if ($bc instanceof block_contents) {
1860 if ($fakeblocksonly && !$bc->is_fake()) {
1861 // Skip rendering real blocks if we only want to show fake blocks.
1862 continue;
1864 $output .= $this->block($bc, $region);
1865 $lastblock = $bc->title;
1866 } else if ($bc instanceof block_move_target) {
1867 if (!$fakeblocksonly) {
1868 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1870 } else {
1871 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1874 return $output;
1878 * Output a place where the block that is currently being moved can be dropped.
1880 * @param block_move_target $target with the necessary details.
1881 * @param array $zones array of areas where the block can be moved to
1882 * @param string $previous the block located before the area currently being rendered.
1883 * @param string $region the name of the region
1884 * @return string the HTML to be output.
1886 public function block_move_target($target, $zones, $previous, $region) {
1887 if ($previous == null) {
1888 if (empty($zones)) {
1889 // There are no zones, probably because there are no blocks.
1890 $regions = $this->page->theme->get_all_block_regions();
1891 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1892 } else {
1893 $position = get_string('moveblockbefore', 'block', $zones[0]);
1895 } else {
1896 $position = get_string('moveblockafter', 'block', $previous);
1898 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1902 * Renders a special html link with attached action
1904 * Theme developers: DO NOT OVERRIDE! Please override function
1905 * {@link core_renderer::render_action_link()} instead.
1907 * @param string|moodle_url $url
1908 * @param string $text HTML fragment
1909 * @param component_action $action
1910 * @param array $attributes associative array of html link attributes + disabled
1911 * @param pix_icon optional pix icon to render with the link
1912 * @return string HTML fragment
1914 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1915 if (!($url instanceof moodle_url)) {
1916 $url = new moodle_url($url);
1918 $link = new action_link($url, $text, $action, $attributes, $icon);
1920 return $this->render($link);
1924 * Renders an action_link object.
1926 * The provided link is renderer and the HTML returned. At the same time the
1927 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1929 * @param action_link $link
1930 * @return string HTML fragment
1932 protected function render_action_link(action_link $link) {
1933 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1937 * Renders an action_icon.
1939 * This function uses the {@link core_renderer::action_link()} method for the
1940 * most part. What it does different is prepare the icon as HTML and use it
1941 * as the link text.
1943 * Theme developers: If you want to change how action links and/or icons are rendered,
1944 * consider overriding function {@link core_renderer::render_action_link()} and
1945 * {@link core_renderer::render_pix_icon()}.
1947 * @param string|moodle_url $url A string URL or moodel_url
1948 * @param pix_icon $pixicon
1949 * @param component_action $action
1950 * @param array $attributes associative array of html link attributes + disabled
1951 * @param bool $linktext show title next to image in link
1952 * @return string HTML fragment
1954 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1955 if (!($url instanceof moodle_url)) {
1956 $url = new moodle_url($url);
1958 $attributes = (array)$attributes;
1960 if (empty($attributes['class'])) {
1961 // let ppl override the class via $options
1962 $attributes['class'] = 'action-icon';
1965 $icon = $this->render($pixicon);
1967 if ($linktext) {
1968 $text = $pixicon->attributes['alt'];
1969 } else {
1970 $text = '';
1973 return $this->action_link($url, $text.$icon, $action, $attributes);
1977 * Print a message along with button choices for Continue/Cancel
1979 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1981 * @param string $message The question to ask the user
1982 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1983 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1984 * @return string HTML fragment
1986 public function confirm($message, $continue, $cancel) {
1987 if ($continue instanceof single_button) {
1988 // ok
1989 $continue->primary = true;
1990 } else if (is_string($continue)) {
1991 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1992 } else if ($continue instanceof moodle_url) {
1993 $continue = new single_button($continue, get_string('continue'), 'post', true);
1994 } else {
1995 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1998 if ($cancel instanceof single_button) {
1999 // ok
2000 } else if (is_string($cancel)) {
2001 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
2002 } else if ($cancel instanceof moodle_url) {
2003 $cancel = new single_button($cancel, get_string('cancel'), 'get');
2004 } else {
2005 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2008 $attributes = [
2009 'role'=>'alertdialog',
2010 'aria-labelledby'=>'modal-header',
2011 'aria-describedby'=>'modal-body',
2012 'aria-modal'=>'true'
2015 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
2016 $output .= $this->box_start('modal-content', 'modal-content');
2017 $output .= $this->box_start('modal-header px-3', 'modal-header');
2018 $output .= html_writer::tag('h4', get_string('confirm'));
2019 $output .= $this->box_end();
2020 $attributes = [
2021 'role'=>'alert',
2022 'data-aria-autofocus'=>'true'
2024 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
2025 $output .= html_writer::tag('p', $message);
2026 $output .= $this->box_end();
2027 $output .= $this->box_start('modal-footer', 'modal-footer');
2028 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
2029 $output .= $this->box_end();
2030 $output .= $this->box_end();
2031 $output .= $this->box_end();
2032 return $output;
2036 * Returns a form with a single button.
2038 * Theme developers: DO NOT OVERRIDE! Please override function
2039 * {@link core_renderer::render_single_button()} instead.
2041 * @param string|moodle_url $url
2042 * @param string $label button text
2043 * @param string $method get or post submit method
2044 * @param array $options associative array {disabled, title, etc.}
2045 * @return string HTML fragment
2047 public function single_button($url, $label, $method='post', array $options=null) {
2048 if (!($url instanceof moodle_url)) {
2049 $url = new moodle_url($url);
2051 $button = new single_button($url, $label, $method);
2053 foreach ((array)$options as $key=>$value) {
2054 if (property_exists($button, $key)) {
2055 $button->$key = $value;
2056 } else {
2057 $button->set_attribute($key, $value);
2061 return $this->render($button);
2065 * Renders a single button widget.
2067 * This will return HTML to display a form containing a single button.
2069 * @param single_button $button
2070 * @return string HTML fragment
2072 protected function render_single_button(single_button $button) {
2073 return $this->render_from_template('core/single_button', $button->export_for_template($this));
2077 * Returns a form with a single select widget.
2079 * Theme developers: DO NOT OVERRIDE! Please override function
2080 * {@link core_renderer::render_single_select()} instead.
2082 * @param moodle_url $url form action target, includes hidden fields
2083 * @param string $name name of selection field - the changing parameter in url
2084 * @param array $options list of options
2085 * @param string $selected selected element
2086 * @param array $nothing
2087 * @param string $formid
2088 * @param array $attributes other attributes for the single select
2089 * @return string HTML fragment
2091 public function single_select($url, $name, array $options, $selected = '',
2092 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2093 if (!($url instanceof moodle_url)) {
2094 $url = new moodle_url($url);
2096 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2098 if (array_key_exists('label', $attributes)) {
2099 $select->set_label($attributes['label']);
2100 unset($attributes['label']);
2102 $select->attributes = $attributes;
2104 return $this->render($select);
2108 * Returns a dataformat selection and download form
2110 * @param string $label A text label
2111 * @param moodle_url|string $base The download page url
2112 * @param string $name The query param which will hold the type of the download
2113 * @param array $params Extra params sent to the download page
2114 * @return string HTML fragment
2116 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2118 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2119 $options = array();
2120 foreach ($formats as $format) {
2121 if ($format->is_enabled()) {
2122 $options[] = array(
2123 'value' => $format->name,
2124 'label' => get_string('dataformat', $format->component),
2128 $hiddenparams = array();
2129 foreach ($params as $key => $value) {
2130 $hiddenparams[] = array(
2131 'name' => $key,
2132 'value' => $value,
2135 $data = array(
2136 'label' => $label,
2137 'base' => $base,
2138 'name' => $name,
2139 'params' => $hiddenparams,
2140 'options' => $options,
2141 'sesskey' => sesskey(),
2142 'submit' => get_string('download'),
2145 return $this->render_from_template('core/dataformat_selector', $data);
2150 * Internal implementation of single_select rendering
2152 * @param single_select $select
2153 * @return string HTML fragment
2155 protected function render_single_select(single_select $select) {
2156 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2160 * Returns a form with a url select widget.
2162 * Theme developers: DO NOT OVERRIDE! Please override function
2163 * {@link core_renderer::render_url_select()} instead.
2165 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2166 * @param string $selected selected element
2167 * @param array $nothing
2168 * @param string $formid
2169 * @return string HTML fragment
2171 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2172 $select = new url_select($urls, $selected, $nothing, $formid);
2173 return $this->render($select);
2177 * Internal implementation of url_select rendering
2179 * @param url_select $select
2180 * @return string HTML fragment
2182 protected function render_url_select(url_select $select) {
2183 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2187 * Returns a string containing a link to the user documentation.
2188 * Also contains an icon by default. Shown to teachers and admin only.
2190 * @param string $path The page link after doc root and language, no leading slash.
2191 * @param string $text The text to be displayed for the link
2192 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2193 * @param array $attributes htm attributes
2194 * @return string
2196 public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
2197 global $CFG;
2199 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2201 $attributes['href'] = new moodle_url(get_docs_url($path));
2202 $newwindowicon = '';
2203 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2204 $attributes['target'] = '_blank';
2205 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle',
2206 ['class' => 'fa fa-externallink fa-fw']);
2209 return html_writer::tag('a', $icon . $text . $newwindowicon, $attributes);
2213 * Return HTML for an image_icon.
2215 * Theme developers: DO NOT OVERRIDE! Please override function
2216 * {@link core_renderer::render_image_icon()} instead.
2218 * @param string $pix short pix name
2219 * @param string $alt mandatory alt attribute
2220 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2221 * @param array $attributes htm attributes
2222 * @return string HTML fragment
2224 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2225 $icon = new image_icon($pix, $alt, $component, $attributes);
2226 return $this->render($icon);
2230 * Renders a pix_icon widget and returns the HTML to display it.
2232 * @param image_icon $icon
2233 * @return string HTML fragment
2235 protected function render_image_icon(image_icon $icon) {
2236 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2237 return $system->render_pix_icon($this, $icon);
2241 * Return HTML for a pix_icon.
2243 * Theme developers: DO NOT OVERRIDE! Please override function
2244 * {@link core_renderer::render_pix_icon()} instead.
2246 * @param string $pix short pix name
2247 * @param string $alt mandatory alt attribute
2248 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2249 * @param array $attributes htm lattributes
2250 * @return string HTML fragment
2252 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2253 $icon = new pix_icon($pix, $alt, $component, $attributes);
2254 return $this->render($icon);
2258 * Renders a pix_icon widget and returns the HTML to display it.
2260 * @param pix_icon $icon
2261 * @return string HTML fragment
2263 protected function render_pix_icon(pix_icon $icon) {
2264 $system = \core\output\icon_system::instance();
2265 return $system->render_pix_icon($this, $icon);
2269 * Return HTML to display an emoticon icon.
2271 * @param pix_emoticon $emoticon
2272 * @return string HTML fragment
2274 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2275 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2276 return $system->render_pix_icon($this, $emoticon);
2280 * Produces the html that represents this rating in the UI
2282 * @param rating $rating the page object on which this rating will appear
2283 * @return string
2285 function render_rating(rating $rating) {
2286 global $CFG, $USER;
2288 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2289 return null;//ratings are turned off
2292 $ratingmanager = new rating_manager();
2293 // Initialise the JavaScript so ratings can be done by AJAX.
2294 $ratingmanager->initialise_rating_javascript($this->page);
2296 $strrate = get_string("rate", "rating");
2297 $ratinghtml = ''; //the string we'll return
2299 // permissions check - can they view the aggregate?
2300 if ($rating->user_can_view_aggregate()) {
2302 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2303 $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2304 $aggregatestr = $rating->get_aggregate_string();
2306 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2307 if ($rating->count > 0) {
2308 $countstr = "({$rating->count})";
2309 } else {
2310 $countstr = '-';
2312 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2314 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2316 $nonpopuplink = $rating->get_view_ratings_url();
2317 $popuplink = $rating->get_view_ratings_url(true);
2319 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2320 $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
2323 $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
2326 $formstart = null;
2327 // if the item doesn't belong to the current user, the user has permission to rate
2328 // and we're within the assessable period
2329 if ($rating->user_can_rate()) {
2331 $rateurl = $rating->get_rate_url();
2332 $inputs = $rateurl->params();
2334 //start the rating form
2335 $formattrs = array(
2336 'id' => "postrating{$rating->itemid}",
2337 'class' => 'postratingform',
2338 'method' => 'post',
2339 'action' => $rateurl->out_omit_querystring()
2341 $formstart = html_writer::start_tag('form', $formattrs);
2342 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2344 // add the hidden inputs
2345 foreach ($inputs as $name => $value) {
2346 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2347 $formstart .= html_writer::empty_tag('input', $attributes);
2350 if (empty($ratinghtml)) {
2351 $ratinghtml .= $strrate.': ';
2353 $ratinghtml = $formstart.$ratinghtml;
2355 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2356 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2357 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2358 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2360 //output submit button
2361 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2363 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2364 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2366 if (!$rating->settings->scale->isnumeric) {
2367 // If a global scale, try to find current course ID from the context
2368 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2369 $courseid = $coursecontext->instanceid;
2370 } else {
2371 $courseid = $rating->settings->scale->courseid;
2373 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2375 $ratinghtml .= html_writer::end_tag('span');
2376 $ratinghtml .= html_writer::end_tag('div');
2377 $ratinghtml .= html_writer::end_tag('form');
2380 return $ratinghtml;
2384 * Centered heading with attached help button (same title text)
2385 * and optional icon attached.
2387 * @param string $text A heading text
2388 * @param string $helpidentifier The keyword that defines a help page
2389 * @param string $component component name
2390 * @param string|moodle_url $icon
2391 * @param string $iconalt icon alt text
2392 * @param int $level The level of importance of the heading. Defaulting to 2
2393 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2394 * @return string HTML fragment
2396 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2397 $image = '';
2398 if ($icon) {
2399 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2402 $help = '';
2403 if ($helpidentifier) {
2404 $help = $this->help_icon($helpidentifier, $component);
2407 return $this->heading($image.$text.$help, $level, $classnames);
2411 * Returns HTML to display a help icon.
2413 * @deprecated since Moodle 2.0
2415 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2416 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2420 * Returns HTML to display a help icon.
2422 * Theme developers: DO NOT OVERRIDE! Please override function
2423 * {@link core_renderer::render_help_icon()} instead.
2425 * @param string $identifier The keyword that defines a help page
2426 * @param string $component component name
2427 * @param string|bool $linktext true means use $title as link text, string means link text value
2428 * @return string HTML fragment
2430 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2431 $icon = new help_icon($identifier, $component);
2432 $icon->diag_strings();
2433 if ($linktext === true) {
2434 $icon->linktext = get_string($icon->identifier, $icon->component);
2435 } else if (!empty($linktext)) {
2436 $icon->linktext = $linktext;
2438 return $this->render($icon);
2442 * Implementation of user image rendering.
2444 * @param help_icon $helpicon A help icon instance
2445 * @return string HTML fragment
2447 protected function render_help_icon(help_icon $helpicon) {
2448 $context = $helpicon->export_for_template($this);
2449 return $this->render_from_template('core/help_icon', $context);
2453 * Returns HTML to display a scale help icon.
2455 * @param int $courseid
2456 * @param stdClass $scale instance
2457 * @return string HTML fragment
2459 public function help_icon_scale($courseid, stdClass $scale) {
2460 global $CFG;
2462 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2464 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2466 $scaleid = abs($scale->id);
2468 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2469 $action = new popup_action('click', $link, 'ratingscale');
2471 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2475 * Creates and returns a spacer image with optional line break.
2477 * @param array $attributes Any HTML attributes to add to the spaced.
2478 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2479 * laxy do it with CSS which is a much better solution.
2480 * @return string HTML fragment
2482 public function spacer(array $attributes = null, $br = false) {
2483 $attributes = (array)$attributes;
2484 if (empty($attributes['width'])) {
2485 $attributes['width'] = 1;
2487 if (empty($attributes['height'])) {
2488 $attributes['height'] = 1;
2490 $attributes['class'] = 'spacer';
2492 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2494 if (!empty($br)) {
2495 $output .= '<br />';
2498 return $output;
2502 * Returns HTML to display the specified user's avatar.
2504 * User avatar may be obtained in two ways:
2505 * <pre>
2506 * // Option 1: (shortcut for simple cases, preferred way)
2507 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2508 * $OUTPUT->user_picture($user, array('popup'=>true));
2510 * // Option 2:
2511 * $userpic = new user_picture($user);
2512 * // Set properties of $userpic
2513 * $userpic->popup = true;
2514 * $OUTPUT->render($userpic);
2515 * </pre>
2517 * Theme developers: DO NOT OVERRIDE! Please override function
2518 * {@link core_renderer::render_user_picture()} instead.
2520 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2521 * If any of these are missing, the database is queried. Avoid this
2522 * if at all possible, particularly for reports. It is very bad for performance.
2523 * @param array $options associative array with user picture options, used only if not a user_picture object,
2524 * options are:
2525 * - courseid=$this->page->course->id (course id of user profile in link)
2526 * - size=35 (size of image)
2527 * - link=true (make image clickable - the link leads to user profile)
2528 * - popup=false (open in popup)
2529 * - alttext=true (add image alt attribute)
2530 * - class = image class attribute (default 'userpicture')
2531 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2532 * - includefullname=false (whether to include the user's full name together with the user picture)
2533 * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2534 * @return string HTML fragment
2536 public function user_picture(stdClass $user, array $options = null) {
2537 $userpicture = new user_picture($user);
2538 foreach ((array)$options as $key=>$value) {
2539 if (property_exists($userpicture, $key)) {
2540 $userpicture->$key = $value;
2543 return $this->render($userpicture);
2547 * Internal implementation of user image rendering.
2549 * @param user_picture $userpicture
2550 * @return string
2552 protected function render_user_picture(user_picture $userpicture) {
2553 $user = $userpicture->user;
2554 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
2556 $alt = '';
2557 if ($userpicture->alttext) {
2558 if (!empty($user->imagealt)) {
2559 $alt = $user->imagealt;
2563 if (empty($userpicture->size)) {
2564 $size = 35;
2565 } else if ($userpicture->size === true or $userpicture->size == 1) {
2566 $size = 100;
2567 } else {
2568 $size = $userpicture->size;
2571 $class = $userpicture->class;
2573 if ($user->picture == 0) {
2574 $class .= ' defaultuserpic';
2577 $src = $userpicture->get_url($this->page, $this);
2579 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2580 if (!$userpicture->visibletoscreenreaders) {
2581 $alt = '';
2583 $attributes['alt'] = $alt;
2585 if (!empty($alt)) {
2586 $attributes['title'] = $alt;
2589 // get the image html output fisrt
2590 $output = html_writer::empty_tag('img', $attributes);
2592 // Show fullname together with the picture when desired.
2593 if ($userpicture->includefullname) {
2594 $output .= fullname($userpicture->user, $canviewfullnames);
2597 if (empty($userpicture->courseid)) {
2598 $courseid = $this->page->course->id;
2599 } else {
2600 $courseid = $userpicture->courseid;
2602 if ($courseid == SITEID) {
2603 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2604 } else {
2605 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2608 // Then wrap it in link if needed. Also we don't wrap it in link if the link redirects to itself.
2609 if (!$userpicture->link ||
2610 ($this->page->has_set_url() && $this->page->url == $url)) { // Protect against unset page->url.
2611 return $output;
2614 $attributes = array('href' => $url, 'class' => 'd-inline-block aabtn');
2615 if (!$userpicture->visibletoscreenreaders) {
2616 $attributes['tabindex'] = '-1';
2617 $attributes['aria-hidden'] = 'true';
2620 if ($userpicture->popup) {
2621 $id = html_writer::random_id('userpicture');
2622 $attributes['id'] = $id;
2623 $this->add_action_handler(new popup_action('click', $url), $id);
2626 return html_writer::tag('a', $output, $attributes);
2630 * Internal implementation of file tree viewer items rendering.
2632 * @param array $dir
2633 * @return string
2635 public function htmllize_file_tree($dir) {
2636 if (empty($dir['subdirs']) and empty($dir['files'])) {
2637 return '';
2639 $result = '<ul>';
2640 foreach ($dir['subdirs'] as $subdir) {
2641 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2643 foreach ($dir['files'] as $file) {
2644 $filename = $file->get_filename();
2645 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2647 $result .= '</ul>';
2649 return $result;
2653 * Returns HTML to display the file picker
2655 * <pre>
2656 * $OUTPUT->file_picker($options);
2657 * </pre>
2659 * Theme developers: DO NOT OVERRIDE! Please override function
2660 * {@link core_renderer::render_file_picker()} instead.
2662 * @param array $options associative array with file manager options
2663 * options are:
2664 * maxbytes=>-1,
2665 * itemid=>0,
2666 * client_id=>uniqid(),
2667 * acepted_types=>'*',
2668 * return_types=>FILE_INTERNAL,
2669 * context=>current page context
2670 * @return string HTML fragment
2672 public function file_picker($options) {
2673 $fp = new file_picker($options);
2674 return $this->render($fp);
2678 * Internal implementation of file picker rendering.
2680 * @param file_picker $fp
2681 * @return string
2683 public function render_file_picker(file_picker $fp) {
2684 $options = $fp->options;
2685 $client_id = $options->client_id;
2686 $strsaved = get_string('filesaved', 'repository');
2687 $straddfile = get_string('openpicker', 'repository');
2688 $strloading = get_string('loading', 'repository');
2689 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2690 $strdroptoupload = get_string('droptoupload', 'moodle');
2691 $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
2693 $currentfile = $options->currentfile;
2694 if (empty($currentfile)) {
2695 $currentfile = '';
2696 } else {
2697 $currentfile .= ' - ';
2699 if ($options->maxbytes) {
2700 $size = $options->maxbytes;
2701 } else {
2702 $size = get_max_upload_file_size();
2704 if ($size == -1) {
2705 $maxsize = '';
2706 } else {
2707 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2709 if ($options->buttonname) {
2710 $buttonname = ' name="' . $options->buttonname . '"';
2711 } else {
2712 $buttonname = '';
2714 $html = <<<EOD
2715 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2716 $iconprogress
2717 </div>
2718 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2719 <div>
2720 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2721 <span> $maxsize </span>
2722 </div>
2723 EOD;
2724 if ($options->env != 'url') {
2725 $html .= <<<EOD
2726 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2727 <div class="filepicker-filename">
2728 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2729 <div class="dndupload-progressbars"></div>
2730 </div>
2731 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2732 </div>
2733 EOD;
2735 $html .= '</div>';
2736 return $html;
2740 * @deprecated since Moodle 3.2
2742 public function update_module_button() {
2743 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2744 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2745 'Themes can choose to display the link in the buttons row consistently for all module types.');
2749 * Returns HTML to display a "Turn editing on/off" button in a form.
2751 * @param moodle_url $url The URL + params to send through when clicking the button
2752 * @return string HTML the button
2754 public function edit_button(moodle_url $url) {
2756 $url->param('sesskey', sesskey());
2757 if ($this->page->user_is_editing()) {
2758 $url->param('edit', 'off');
2759 $editstring = get_string('turneditingoff');
2760 } else {
2761 $url->param('edit', 'on');
2762 $editstring = get_string('turneditingon');
2765 return $this->single_button($url, $editstring);
2769 * Returns HTML to display a simple button to close a window
2771 * @param string $text The lang string for the button's label (already output from get_string())
2772 * @return string html fragment
2774 public function close_window_button($text='') {
2775 if (empty($text)) {
2776 $text = get_string('closewindow');
2778 $button = new single_button(new moodle_url('#'), $text, 'get');
2779 $button->add_action(new component_action('click', 'close_window'));
2781 return $this->container($this->render($button), 'closewindow');
2785 * Output an error message. By default wraps the error message in <span class="error">.
2786 * If the error message is blank, nothing is output.
2788 * @param string $message the error message.
2789 * @return string the HTML to output.
2791 public function error_text($message) {
2792 if (empty($message)) {
2793 return '';
2795 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2796 return html_writer::tag('span', $message, array('class' => 'error'));
2800 * Do not call this function directly.
2802 * To terminate the current script with a fatal error, call the {@link print_error}
2803 * function, or throw an exception. Doing either of those things will then call this
2804 * function to display the error, before terminating the execution.
2806 * @param string $message The message to output
2807 * @param string $moreinfourl URL where more info can be found about the error
2808 * @param string $link Link for the Continue button
2809 * @param array $backtrace The execution backtrace
2810 * @param string $debuginfo Debugging information
2811 * @return string the HTML to output.
2813 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2814 global $CFG;
2816 $output = '';
2817 $obbuffer = '';
2819 if ($this->has_started()) {
2820 // we can not always recover properly here, we have problems with output buffering,
2821 // html tables, etc.
2822 $output .= $this->opencontainers->pop_all_but_last();
2824 } else {
2825 // It is really bad if library code throws exception when output buffering is on,
2826 // because the buffered text would be printed before our start of page.
2827 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2828 error_reporting(0); // disable notices from gzip compression, etc.
2829 while (ob_get_level() > 0) {
2830 $buff = ob_get_clean();
2831 if ($buff === false) {
2832 break;
2834 $obbuffer .= $buff;
2836 error_reporting($CFG->debug);
2838 // Output not yet started.
2839 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2840 if (empty($_SERVER['HTTP_RANGE'])) {
2841 @header($protocol . ' 404 Not Found');
2842 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2843 // Coax iOS 10 into sending the session cookie.
2844 @header($protocol . ' 403 Forbidden');
2845 } else {
2846 // Must stop byteserving attempts somehow,
2847 // this is weird but Chrome PDF viewer can be stopped only with 407!
2848 @header($protocol . ' 407 Proxy Authentication Required');
2851 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2852 $this->page->set_url('/'); // no url
2853 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2854 $this->page->set_title(get_string('error'));
2855 $this->page->set_heading($this->page->course->fullname);
2856 $output .= $this->header();
2859 $message = '<p class="errormessage">' . s($message) . '</p>'.
2860 '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
2861 get_string('moreinformation') . '</a></p>';
2862 if (empty($CFG->rolesactive)) {
2863 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2864 //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.
2866 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2868 if ($CFG->debugdeveloper) {
2869 $labelsep = get_string('labelsep', 'langconfig');
2870 if (!empty($debuginfo)) {
2871 $debuginfo = s($debuginfo); // removes all nasty JS
2872 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2873 $label = get_string('debuginfo', 'debug') . $labelsep;
2874 $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
2876 if (!empty($backtrace)) {
2877 $label = get_string('stacktrace', 'debug') . $labelsep;
2878 $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
2880 if ($obbuffer !== '' ) {
2881 $label = get_string('outputbuffer', 'debug') . $labelsep;
2882 $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
2886 if (empty($CFG->rolesactive)) {
2887 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2888 } else if (!empty($link)) {
2889 $output .= $this->continue_button($link);
2892 $output .= $this->footer();
2894 // Padding to encourage IE to display our error page, rather than its own.
2895 $output .= str_repeat(' ', 512);
2897 return $output;
2901 * Output a notification (that is, a status message about something that has just happened).
2903 * Note: \core\notification::add() may be more suitable for your usage.
2905 * @param string $message The message to print out.
2906 * @param ?string $type The type of notification. See constants on \core\output\notification.
2907 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
2908 * @return string the HTML to output.
2910 public function notification($message, $type = null, $closebutton = true) {
2911 $typemappings = [
2912 // Valid types.
2913 'success' => \core\output\notification::NOTIFY_SUCCESS,
2914 'info' => \core\output\notification::NOTIFY_INFO,
2915 'warning' => \core\output\notification::NOTIFY_WARNING,
2916 'error' => \core\output\notification::NOTIFY_ERROR,
2918 // Legacy types mapped to current types.
2919 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2920 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2921 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2922 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2923 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2924 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2925 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2928 $extraclasses = [];
2930 if ($type) {
2931 if (strpos($type, ' ') === false) {
2932 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2933 if (isset($typemappings[$type])) {
2934 $type = $typemappings[$type];
2935 } else {
2936 // The value provided did not match a known type. It must be an extra class.
2937 $extraclasses = [$type];
2939 } else {
2940 // Identify what type of notification this is.
2941 $classarray = explode(' ', self::prepare_classes($type));
2943 // Separate out the type of notification from the extra classes.
2944 foreach ($classarray as $class) {
2945 if (isset($typemappings[$class])) {
2946 $type = $typemappings[$class];
2947 } else {
2948 $extraclasses[] = $class;
2954 $notification = new \core\output\notification($message, $type, $closebutton);
2955 if (count($extraclasses)) {
2956 $notification->set_extra_classes($extraclasses);
2959 // Return the rendered template.
2960 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2964 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2966 public function notify_problem() {
2967 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
2968 'please use \core\notification::add(), or \core\output\notification as required.');
2972 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2974 public function notify_success() {
2975 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
2976 'please use \core\notification::add(), or \core\output\notification as required.');
2980 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2982 public function notify_message() {
2983 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
2984 'please use \core\notification::add(), or \core\output\notification as required.');
2988 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2990 public function notify_redirect() {
2991 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
2992 'please use \core\notification::add(), or \core\output\notification as required.');
2996 * Render a notification (that is, a status message about something that has
2997 * just happened).
2999 * @param \core\output\notification $notification the notification to print out
3000 * @return string the HTML to output.
3002 protected function render_notification(\core\output\notification $notification) {
3003 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3007 * Returns HTML to display a continue button that goes to a particular URL.
3009 * @param string|moodle_url $url The url the button goes to.
3010 * @return string the HTML to output.
3012 public function continue_button($url) {
3013 if (!($url instanceof moodle_url)) {
3014 $url = new moodle_url($url);
3016 $button = new single_button($url, get_string('continue'), 'get', true);
3017 $button->class = 'continuebutton';
3019 return $this->render($button);
3023 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
3025 * Theme developers: DO NOT OVERRIDE! Please override function
3026 * {@link core_renderer::render_paging_bar()} instead.
3028 * @param int $totalcount The total number of entries available to be paged through
3029 * @param int $page The page you are currently viewing
3030 * @param int $perpage The number of entries that should be shown per page
3031 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3032 * @param string $pagevar name of page parameter that holds the page number
3033 * @return string the HTML to output.
3035 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3036 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3037 return $this->render($pb);
3041 * Returns HTML to display the paging bar.
3043 * @param paging_bar $pagingbar
3044 * @return string the HTML to output.
3046 protected function render_paging_bar(paging_bar $pagingbar) {
3047 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3048 $pagingbar->maxdisplay = 10;
3049 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3053 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3055 * @param string $current the currently selected letter.
3056 * @param string $class class name to add to this initial bar.
3057 * @param string $title the name to put in front of this initial bar.
3058 * @param string $urlvar URL parameter name for this initial.
3059 * @param string $url URL object.
3060 * @param array $alpha of letters in the alphabet.
3061 * @return string the HTML to output.
3063 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3064 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3065 return $this->render($ib);
3069 * Internal implementation of initials bar rendering.
3071 * @param initials_bar $initialsbar
3072 * @return string
3074 protected function render_initials_bar(initials_bar $initialsbar) {
3075 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3079 * Output the place a skip link goes to.
3081 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3082 * @return string the HTML to output.
3084 public function skip_link_target($id = null) {
3085 return html_writer::span('', '', array('id' => $id));
3089 * Outputs a heading
3091 * @param string $text The text of the heading
3092 * @param int $level The level of importance of the heading. Defaulting to 2
3093 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3094 * @param string $id An optional ID
3095 * @return string the HTML to output.
3097 public function heading($text, $level = 2, $classes = null, $id = null) {
3098 $level = (integer) $level;
3099 if ($level < 1 or $level > 6) {
3100 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3102 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3106 * Outputs a box.
3108 * @param string $contents The contents of the box
3109 * @param string $classes A space-separated list of CSS classes
3110 * @param string $id An optional ID
3111 * @param array $attributes An array of other attributes to give the box.
3112 * @return string the HTML to output.
3114 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3115 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3119 * Outputs the opening section of a box.
3121 * @param string $classes A space-separated list of CSS classes
3122 * @param string $id An optional ID
3123 * @param array $attributes An array of other attributes to give the box.
3124 * @return string the HTML to output.
3126 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3127 $this->opencontainers->push('box', html_writer::end_tag('div'));
3128 $attributes['id'] = $id;
3129 $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes);
3130 return html_writer::start_tag('div', $attributes);
3134 * Outputs the closing section of a box.
3136 * @return string the HTML to output.
3138 public function box_end() {
3139 return $this->opencontainers->pop('box');
3143 * Outputs a container.
3145 * @param string $contents The contents of the box
3146 * @param string $classes A space-separated list of CSS classes
3147 * @param string $id An optional ID
3148 * @return string the HTML to output.
3150 public function container($contents, $classes = null, $id = null) {
3151 return $this->container_start($classes, $id) . $contents . $this->container_end();
3155 * Outputs the opening section of a container.
3157 * @param string $classes A space-separated list of CSS classes
3158 * @param string $id An optional ID
3159 * @return string the HTML to output.
3161 public function container_start($classes = null, $id = null) {
3162 $this->opencontainers->push('container', html_writer::end_tag('div'));
3163 return html_writer::start_tag('div', array('id' => $id,
3164 'class' => renderer_base::prepare_classes($classes)));
3168 * Outputs the closing section of a container.
3170 * @return string the HTML to output.
3172 public function container_end() {
3173 return $this->opencontainers->pop('container');
3177 * Make nested HTML lists out of the items
3179 * The resulting list will look something like this:
3181 * <pre>
3182 * <<ul>>
3183 * <<li>><div class='tree_item parent'>(item contents)</div>
3184 * <<ul>
3185 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3186 * <</ul>>
3187 * <</li>>
3188 * <</ul>>
3189 * </pre>
3191 * @param array $items
3192 * @param array $attrs html attributes passed to the top ofs the list
3193 * @return string HTML
3195 public function tree_block_contents($items, $attrs = array()) {
3196 // exit if empty, we don't want an empty ul element
3197 if (empty($items)) {
3198 return '';
3200 // array of nested li elements
3201 $lis = array();
3202 foreach ($items as $item) {
3203 // this applies to the li item which contains all child lists too
3204 $content = $item->content($this);
3205 $liclasses = array($item->get_css_type());
3206 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3207 $liclasses[] = 'collapsed';
3209 if ($item->isactive === true) {
3210 $liclasses[] = 'current_branch';
3212 $liattr = array('class'=>join(' ',$liclasses));
3213 // class attribute on the div item which only contains the item content
3214 $divclasses = array('tree_item');
3215 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3216 $divclasses[] = 'branch';
3217 } else {
3218 $divclasses[] = 'leaf';
3220 if (!empty($item->classes) && count($item->classes)>0) {
3221 $divclasses[] = join(' ', $item->classes);
3223 $divattr = array('class'=>join(' ', $divclasses));
3224 if (!empty($item->id)) {
3225 $divattr['id'] = $item->id;
3227 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3228 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3229 $content = html_writer::empty_tag('hr') . $content;
3231 $content = html_writer::tag('li', $content, $liattr);
3232 $lis[] = $content;
3234 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3238 * Returns a search box.
3240 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3241 * @return string HTML with the search form hidden by default.
3243 public function search_box($id = false) {
3244 global $CFG;
3246 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3247 // result in an extra included file for each site, even the ones where global search
3248 // is disabled.
3249 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3250 return '';
3253 $data = [
3254 'action' => new moodle_url('/search/index.php'),
3255 'hiddenfields' => (object) ['name' => 'context', 'value' => $this->page->context->id],
3256 'inputname' => 'q',
3257 'searchstring' => get_string('search'),
3259 return $this->render_from_template('core/search_input_navbar', $data);
3263 * Allow plugins to provide some content to be rendered in the navbar.
3264 * The plugin must define a PLUGIN_render_navbar_output function that returns
3265 * the HTML they wish to add to the navbar.
3267 * @return string HTML for the navbar
3269 public function navbar_plugin_output() {
3270 $output = '';
3272 // Give subsystems an opportunity to inject extra html content. The callback
3273 // must always return a string containing valid html.
3274 foreach (\core_component::get_core_subsystems() as $name => $path) {
3275 if ($path) {
3276 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3280 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3281 foreach ($pluginsfunction as $plugintype => $plugins) {
3282 foreach ($plugins as $pluginfunction) {
3283 $output .= $pluginfunction($this);
3288 return $output;
3292 * Construct a user menu, returning HTML that can be echoed out by a
3293 * layout file.
3295 * @param stdClass $user A user object, usually $USER.
3296 * @param bool $withlinks true if a dropdown should be built.
3297 * @return string HTML fragment.
3299 public function user_menu($user = null, $withlinks = null) {
3300 global $USER, $CFG;
3301 require_once($CFG->dirroot . '/user/lib.php');
3303 if (is_null($user)) {
3304 $user = $USER;
3307 // Note: this behaviour is intended to match that of core_renderer::login_info,
3308 // but should not be considered to be good practice; layout options are
3309 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3310 if (is_null($withlinks)) {
3311 $withlinks = empty($this->page->layout_options['nologinlinks']);
3314 // Add a class for when $withlinks is false.
3315 $usermenuclasses = 'usermenu';
3316 if (!$withlinks) {
3317 $usermenuclasses .= ' withoutlinks';
3320 $returnstr = "";
3322 // If during initial install, return the empty return string.
3323 if (during_initial_install()) {
3324 return $returnstr;
3327 $loginpage = $this->is_login_page();
3328 $loginurl = get_login_url();
3329 // If not logged in, show the typical not-logged-in string.
3330 if (!isloggedin()) {
3331 $returnstr = get_string('loggedinnot', 'moodle');
3332 if (!$loginpage) {
3333 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3335 return html_writer::div(
3336 html_writer::span(
3337 $returnstr,
3338 'login'
3340 $usermenuclasses
3345 // If logged in as a guest user, show a string to that effect.
3346 if (isguestuser()) {
3347 $returnstr = get_string('loggedinasguest');
3348 if (!$loginpage && $withlinks) {
3349 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3352 return html_writer::div(
3353 html_writer::span(
3354 $returnstr,
3355 'login'
3357 $usermenuclasses
3361 // Get some navigation opts.
3362 $opts = user_get_user_navigation_info($user, $this->page);
3364 $avatarclasses = "avatars";
3365 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3366 $usertextcontents = $opts->metadata['userfullname'];
3368 // Other user.
3369 if (!empty($opts->metadata['asotheruser'])) {
3370 $avatarcontents .= html_writer::span(
3371 $opts->metadata['realuseravatar'],
3372 'avatar realuser'
3374 $usertextcontents = $opts->metadata['realuserfullname'];
3375 $usertextcontents .= html_writer::tag(
3376 'span',
3377 get_string(
3378 'loggedinas',
3379 'moodle',
3380 html_writer::span(
3381 $opts->metadata['userfullname'],
3382 'value'
3385 array('class' => 'meta viewingas')
3389 // Role.
3390 if (!empty($opts->metadata['asotherrole'])) {
3391 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3392 $usertextcontents .= html_writer::span(
3393 $opts->metadata['rolename'],
3394 'meta role role-' . $role
3398 // User login failures.
3399 if (!empty($opts->metadata['userloginfail'])) {
3400 $usertextcontents .= html_writer::span(
3401 $opts->metadata['userloginfail'],
3402 'meta loginfailures'
3406 // MNet.
3407 if (!empty($opts->metadata['asmnetuser'])) {
3408 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3409 $usertextcontents .= html_writer::span(
3410 $opts->metadata['mnetidprovidername'],
3411 'meta mnet mnet-' . $mnet
3415 $returnstr .= html_writer::span(
3416 html_writer::span($usertextcontents, 'usertext mr-1') .
3417 html_writer::span($avatarcontents, $avatarclasses),
3418 'userbutton'
3421 // Create a divider (well, a filler).
3422 $divider = new action_menu_filler();
3423 $divider->primary = false;
3425 $am = new action_menu();
3426 $am->set_menu_trigger(
3427 $returnstr
3429 $am->set_action_label(get_string('usermenu'));
3430 $am->set_alignment(action_menu::TR, action_menu::BR);
3431 $am->set_nowrap_on_items();
3432 if ($withlinks) {
3433 $navitemcount = count($opts->navitems);
3434 $idx = 0;
3435 foreach ($opts->navitems as $key => $value) {
3437 switch ($value->itemtype) {
3438 case 'divider':
3439 // If the nav item is a divider, add one and skip link processing.
3440 $am->add($divider);
3441 break;
3443 case 'invalid':
3444 // Silently skip invalid entries (should we post a notification?).
3445 break;
3447 case 'link':
3448 // Process this as a link item.
3449 $pix = null;
3450 if (isset($value->pix) && !empty($value->pix)) {
3451 $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
3452 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3453 $value->title = html_writer::img(
3454 $value->imgsrc,
3455 $value->title,
3456 array('class' => 'iconsmall')
3457 ) . $value->title;
3460 $al = new action_menu_link_secondary(
3461 $value->url,
3462 $pix,
3463 $value->title,
3464 array('class' => 'icon')
3466 if (!empty($value->titleidentifier)) {
3467 $al->attributes['data-title'] = $value->titleidentifier;
3469 $am->add($al);
3470 break;
3473 $idx++;
3475 // Add dividers after the first item and before the last item.
3476 if ($idx == 1 || $idx == $navitemcount - 1) {
3477 $am->add($divider);
3482 return html_writer::div(
3483 $this->render($am),
3484 $usermenuclasses
3489 * Secure layout login info.
3491 * @return string
3493 public function secure_layout_login_info() {
3494 if (get_config('core', 'logininfoinsecurelayout')) {
3495 return $this->login_info(false);
3496 } else {
3497 return '';
3502 * Returns the language menu in the secure layout.
3504 * No custom menu items are passed though, such that it will render only the language selection.
3506 * @return string
3508 public function secure_layout_language_menu() {
3509 if (get_config('core', 'langmenuinsecurelayout')) {
3510 $custommenu = new custom_menu('', current_language());
3511 return $this->render_custom_menu($custommenu);
3512 } else {
3513 return '';
3518 * This renders the navbar.
3519 * Uses bootstrap compatible html.
3521 public function navbar() {
3522 return $this->render_from_template('core/navbar', $this->page->navbar);
3526 * Renders a breadcrumb navigation node object.
3528 * @param breadcrumb_navigation_node $item The navigation node to render.
3529 * @return string HTML fragment
3531 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3533 if ($item->action instanceof moodle_url) {
3534 $content = $item->get_content();
3535 $title = $item->get_title();
3536 $attributes = array();
3537 $attributes['itemprop'] = 'url';
3538 if ($title !== '') {
3539 $attributes['title'] = $title;
3541 if ($item->hidden) {
3542 $attributes['class'] = 'dimmed_text';
3544 if ($item->is_last()) {
3545 $attributes['aria-current'] = 'page';
3547 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3548 $content = html_writer::link($item->action, $content, $attributes);
3550 $attributes = array();
3551 $attributes['itemscope'] = '';
3552 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3553 $content = html_writer::tag('span', $content, $attributes);
3555 } else {
3556 $content = $this->render_navigation_node($item);
3558 return $content;
3562 * Renders a navigation node object.
3564 * @param navigation_node $item The navigation node to render.
3565 * @return string HTML fragment
3567 protected function render_navigation_node(navigation_node $item) {
3568 $content = $item->get_content();
3569 $title = $item->get_title();
3570 if ($item->icon instanceof renderable && !$item->hideicon) {
3571 $icon = $this->render($item->icon);
3572 $content = $icon.$content; // use CSS for spacing of icons
3574 if ($item->helpbutton !== null) {
3575 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3577 if ($content === '') {
3578 return '';
3580 if ($item->action instanceof action_link) {
3581 $link = $item->action;
3582 if ($item->hidden) {
3583 $link->add_class('dimmed');
3585 if (!empty($content)) {
3586 // Providing there is content we will use that for the link content.
3587 $link->text = $content;
3589 $content = $this->render($link);
3590 } else if ($item->action instanceof moodle_url) {
3591 $attributes = array();
3592 if ($title !== '') {
3593 $attributes['title'] = $title;
3595 if ($item->hidden) {
3596 $attributes['class'] = 'dimmed_text';
3598 $content = html_writer::link($item->action, $content, $attributes);
3600 } else if (is_string($item->action) || empty($item->action)) {
3601 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3602 if ($title !== '') {
3603 $attributes['title'] = $title;
3605 if ($item->hidden) {
3606 $attributes['class'] = 'dimmed_text';
3608 $content = html_writer::tag('span', $content, $attributes);
3610 return $content;
3614 * Accessibility: Right arrow-like character is
3615 * used in the breadcrumb trail, course navigation menu
3616 * (previous/next activity), calendar, and search forum block.
3617 * If the theme does not set characters, appropriate defaults
3618 * are set automatically. Please DO NOT
3619 * use &lt; &gt; &raquo; - these are confusing for blind users.
3621 * @return string
3623 public function rarrow() {
3624 return $this->page->theme->rarrow;
3628 * Accessibility: Left arrow-like character is
3629 * used in the breadcrumb trail, course navigation menu
3630 * (previous/next activity), calendar, and search forum block.
3631 * If the theme does not set characters, appropriate defaults
3632 * are set automatically. Please DO NOT
3633 * use &lt; &gt; &raquo; - these are confusing for blind users.
3635 * @return string
3637 public function larrow() {
3638 return $this->page->theme->larrow;
3642 * Accessibility: Up arrow-like character is used in
3643 * the book heirarchical navigation.
3644 * If the theme does not set characters, appropriate defaults
3645 * are set automatically. Please DO NOT
3646 * use ^ - this is confusing for blind users.
3648 * @return string
3650 public function uarrow() {
3651 return $this->page->theme->uarrow;
3655 * Accessibility: Down arrow-like character.
3656 * If the theme does not set characters, appropriate defaults
3657 * are set automatically.
3659 * @return string
3661 public function darrow() {
3662 return $this->page->theme->darrow;
3666 * Returns the custom menu if one has been set
3668 * A custom menu can be configured by browsing to
3669 * Settings: Administration > Appearance > Themes > Theme settings
3670 * and then configuring the custommenu config setting as described.
3672 * Theme developers: DO NOT OVERRIDE! Please override function
3673 * {@link core_renderer::render_custom_menu()} instead.
3675 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3676 * @return string
3678 public function custom_menu($custommenuitems = '') {
3679 global $CFG;
3681 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3682 $custommenuitems = $CFG->custommenuitems;
3684 $custommenu = new custom_menu($custommenuitems, current_language());
3685 return $this->render_custom_menu($custommenu);
3689 * We want to show the custom menus as a list of links in the footer on small screens.
3690 * Just return the menu object exported so we can render it differently.
3692 public function custom_menu_flat() {
3693 global $CFG;
3694 $custommenuitems = '';
3696 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3697 $custommenuitems = $CFG->custommenuitems;
3699 $custommenu = new custom_menu($custommenuitems, current_language());
3700 $langs = get_string_manager()->get_list_of_translations();
3701 $haslangmenu = $this->lang_menu() != '';
3703 if ($haslangmenu) {
3704 $strlang = get_string('language');
3705 $currentlang = current_language();
3706 if (isset($langs[$currentlang])) {
3707 $currentlang = $langs[$currentlang];
3708 } else {
3709 $currentlang = $strlang;
3711 $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3712 foreach ($langs as $langtype => $langname) {
3713 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3717 return $custommenu->export_for_template($this);
3721 * Renders a custom menu object (located in outputcomponents.php)
3723 * The custom menu this method produces makes use of the YUI3 menunav widget
3724 * and requires very specific html elements and classes.
3726 * @staticvar int $menucount
3727 * @param custom_menu $menu
3728 * @return string
3730 protected function render_custom_menu(custom_menu $menu) {
3731 global $CFG;
3733 $langs = get_string_manager()->get_list_of_translations();
3734 $haslangmenu = $this->lang_menu() != '';
3736 if (!$menu->has_children() && !$haslangmenu) {
3737 return '';
3740 if ($haslangmenu) {
3741 $strlang = get_string('language');
3742 $currentlang = current_language();
3743 if (isset($langs[$currentlang])) {
3744 $currentlang = $langs[$currentlang];
3745 } else {
3746 $currentlang = $strlang;
3748 $this->language = $menu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3749 foreach ($langs as $langtype => $langname) {
3750 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3754 $content = '';
3755 foreach ($menu->get_children() as $item) {
3756 $context = $item->export_for_template($this);
3757 $content .= $this->render_from_template('core/custom_menu_item', $context);
3760 return $content;
3764 * Renders a custom menu node as part of a submenu
3766 * The custom menu this method produces makes use of the YUI3 menunav widget
3767 * and requires very specific html elements and classes.
3769 * @see core:renderer::render_custom_menu()
3771 * @staticvar int $submenucount
3772 * @param custom_menu_item $menunode
3773 * @return string
3775 protected function render_custom_menu_item(custom_menu_item $menunode) {
3776 // Required to ensure we get unique trackable id's
3777 static $submenucount = 0;
3778 if ($menunode->has_children()) {
3779 // If the child has menus render it as a sub menu
3780 $submenucount++;
3781 $content = html_writer::start_tag('li');
3782 if ($menunode->get_url() !== null) {
3783 $url = $menunode->get_url();
3784 } else {
3785 $url = '#cm_submenu_'.$submenucount;
3787 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3788 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3789 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3790 $content .= html_writer::start_tag('ul');
3791 foreach ($menunode->get_children() as $menunode) {
3792 $content .= $this->render_custom_menu_item($menunode);
3794 $content .= html_writer::end_tag('ul');
3795 $content .= html_writer::end_tag('div');
3796 $content .= html_writer::end_tag('div');
3797 $content .= html_writer::end_tag('li');
3798 } else {
3799 // The node doesn't have children so produce a final menuitem.
3800 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3801 $content = '';
3802 if (preg_match("/^#+$/", $menunode->get_text())) {
3804 // This is a divider.
3805 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3806 } else {
3807 $content = html_writer::start_tag(
3808 'li',
3809 array(
3810 'class' => 'yui3-menuitem'
3813 if ($menunode->get_url() !== null) {
3814 $url = $menunode->get_url();
3815 } else {
3816 $url = '#';
3818 $content .= html_writer::link(
3819 $url,
3820 $menunode->get_text(),
3821 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3824 $content .= html_writer::end_tag('li');
3826 // Return the sub menu
3827 return $content;
3831 * Renders theme links for switching between default and other themes.
3833 * @return string
3835 protected function theme_switch_links() {
3837 $actualdevice = core_useragent::get_device_type();
3838 $currentdevice = $this->page->devicetypeinuse;
3839 $switched = ($actualdevice != $currentdevice);
3841 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3842 // The user is using the a default device and hasn't switched so don't shown the switch
3843 // device links.
3844 return '';
3847 if ($switched) {
3848 $linktext = get_string('switchdevicerecommended');
3849 $devicetype = $actualdevice;
3850 } else {
3851 $linktext = get_string('switchdevicedefault');
3852 $devicetype = 'default';
3854 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3856 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3857 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3858 $content .= html_writer::end_tag('div');
3860 return $content;
3864 * Renders tabs
3866 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3868 * Theme developers: In order to change how tabs are displayed please override functions
3869 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3871 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3872 * @param string|null $selected which tab to mark as selected, all parent tabs will
3873 * automatically be marked as activated
3874 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3875 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3876 * @return string
3878 public final function tabtree($tabs, $selected = null, $inactive = null) {
3879 return $this->render(new tabtree($tabs, $selected, $inactive));
3883 * Renders tabtree
3885 * @param tabtree $tabtree
3886 * @return string
3888 protected function render_tabtree(tabtree $tabtree) {
3889 if (empty($tabtree->subtree)) {
3890 return '';
3892 $data = $tabtree->export_for_template($this);
3893 return $this->render_from_template('core/tabtree', $data);
3897 * Renders tabobject (part of tabtree)
3899 * This function is called from {@link core_renderer::render_tabtree()}
3900 * and also it calls itself when printing the $tabobject subtree recursively.
3902 * Property $tabobject->level indicates the number of row of tabs.
3904 * @param tabobject $tabobject
3905 * @return string HTML fragment
3907 protected function render_tabobject(tabobject $tabobject) {
3908 $str = '';
3910 // Print name of the current tab.
3911 if ($tabobject instanceof tabtree) {
3912 // No name for tabtree root.
3913 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3914 // Tab name without a link. The <a> tag is used for styling.
3915 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3916 } else {
3917 // Tab name with a link.
3918 if (!($tabobject->link instanceof moodle_url)) {
3919 // backward compartibility when link was passed as quoted string
3920 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3921 } else {
3922 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3926 if (empty($tabobject->subtree)) {
3927 if ($tabobject->selected) {
3928 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3930 return $str;
3933 // Print subtree.
3934 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
3935 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3936 $cnt = 0;
3937 foreach ($tabobject->subtree as $tab) {
3938 $liclass = '';
3939 if (!$cnt) {
3940 $liclass .= ' first';
3942 if ($cnt == count($tabobject->subtree) - 1) {
3943 $liclass .= ' last';
3945 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3946 $liclass .= ' onerow';
3949 if ($tab->selected) {
3950 $liclass .= ' here selected';
3951 } else if ($tab->activated) {
3952 $liclass .= ' here active';
3955 // This will recursively call function render_tabobject() for each item in subtree.
3956 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3957 $cnt++;
3959 $str .= html_writer::end_tag('ul');
3962 return $str;
3966 * Get the HTML for blocks in the given region.
3968 * @since Moodle 2.5.1 2.6
3969 * @param string $region The region to get HTML for.
3970 * @param array $classes Wrapping tag classes.
3971 * @param string $tag Wrapping tag.
3972 * @param boolean $fakeblocksonly Include fake blocks only.
3973 * @return string HTML.
3975 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
3976 $displayregion = $this->page->apply_theme_region_manipulations($region);
3977 $classes = (array)$classes;
3978 $classes[] = 'block-region';
3979 $attributes = array(
3980 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3981 'class' => join(' ', $classes),
3982 'data-blockregion' => $displayregion,
3983 'data-droptarget' => '1'
3985 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3986 $content = $this->blocks_for_region($displayregion, $fakeblocksonly);
3987 } else {
3988 $content = '';
3990 return html_writer::tag($tag, $content, $attributes);
3994 * Renders a custom block region.
3996 * Use this method if you want to add an additional block region to the content of the page.
3997 * Please note this should only be used in special situations.
3998 * We want to leave the theme is control where ever possible!
4000 * This method must use the same method that the theme uses within its layout file.
4001 * As such it asks the theme what method it is using.
4002 * It can be one of two values, blocks or blocks_for_region (deprecated).
4004 * @param string $regionname The name of the custom region to add.
4005 * @return string HTML for the block region.
4007 public function custom_block_region($regionname) {
4008 if ($this->page->theme->get_block_render_method() === 'blocks') {
4009 return $this->blocks($regionname);
4010 } else {
4011 return $this->blocks_for_region($regionname);
4016 * Returns the CSS classes to apply to the body tag.
4018 * @since Moodle 2.5.1 2.6
4019 * @param array $additionalclasses Any additional classes to apply.
4020 * @return string
4022 public function body_css_classes(array $additionalclasses = array()) {
4023 return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses);
4027 * The ID attribute to apply to the body tag.
4029 * @since Moodle 2.5.1 2.6
4030 * @return string
4032 public function body_id() {
4033 return $this->page->bodyid;
4037 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4039 * @since Moodle 2.5.1 2.6
4040 * @param string|array $additionalclasses Any additional classes to give the body tag,
4041 * @return string
4043 public function body_attributes($additionalclasses = array()) {
4044 if (!is_array($additionalclasses)) {
4045 $additionalclasses = explode(' ', $additionalclasses);
4047 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4051 * Gets HTML for the page heading.
4053 * @since Moodle 2.5.1 2.6
4054 * @param string $tag The tag to encase the heading in. h1 by default.
4055 * @return string HTML.
4057 public function page_heading($tag = 'h1') {
4058 return html_writer::tag($tag, $this->page->heading);
4062 * Gets the HTML for the page heading button.
4064 * @since Moodle 2.5.1 2.6
4065 * @return string HTML.
4067 public function page_heading_button() {
4068 return $this->page->button;
4072 * Returns the Moodle docs link to use for this page.
4074 * @since Moodle 2.5.1 2.6
4075 * @param string $text
4076 * @return string
4078 public function page_doc_link($text = null) {
4079 if ($text === null) {
4080 $text = get_string('moodledocslink');
4082 $path = page_get_doc_link_path($this->page);
4083 if (!$path) {
4084 return '';
4086 return $this->doc_link($path, $text);
4090 * Returns the page heading menu.
4092 * @since Moodle 2.5.1 2.6
4093 * @return string HTML.
4095 public function page_heading_menu() {
4096 return $this->page->headingmenu;
4100 * Returns the title to use on the page.
4102 * @since Moodle 2.5.1 2.6
4103 * @return string
4105 public function page_title() {
4106 return $this->page->title;
4110 * Returns the moodle_url for the favicon.
4112 * @since Moodle 2.5.1 2.6
4113 * @return moodle_url The moodle_url for the favicon
4115 public function favicon() {
4116 return $this->image_url('favicon', 'theme');
4120 * Renders preferences groups.
4122 * @param preferences_groups $renderable The renderable
4123 * @return string The output.
4125 public function render_preferences_groups(preferences_groups $renderable) {
4126 return $this->render_from_template('core/preferences_groups', $renderable);
4130 * Renders preferences group.
4132 * @param preferences_group $renderable The renderable
4133 * @return string The output.
4135 public function render_preferences_group(preferences_group $renderable) {
4136 $html = '';
4137 $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4138 $html .= $this->heading($renderable->title, 3);
4139 $html .= html_writer::start_tag('ul');
4140 foreach ($renderable->nodes as $node) {
4141 if ($node->has_children()) {
4142 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4144 $html .= html_writer::tag('li', $this->render($node));
4146 $html .= html_writer::end_tag('ul');
4147 $html .= html_writer::end_tag('div');
4148 return $html;
4151 public function context_header($headerinfo = null, $headinglevel = 1) {
4152 global $DB, $USER, $CFG, $SITE;
4153 require_once($CFG->dirroot . '/user/lib.php');
4154 $context = $this->page->context;
4155 $heading = null;
4156 $imagedata = null;
4157 $subheader = null;
4158 $userbuttons = null;
4160 // Make sure to use the heading if it has been set.
4161 if (isset($headerinfo['heading'])) {
4162 $heading = $headerinfo['heading'];
4163 } else {
4164 $heading = $this->page->heading;
4167 // The user context currently has images and buttons. Other contexts may follow.
4168 if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
4169 if (isset($headerinfo['user'])) {
4170 $user = $headerinfo['user'];
4171 } else {
4172 // Look up the user information if it is not supplied.
4173 $user = $DB->get_record('user', array('id' => $context->instanceid));
4176 // If the user context is set, then use that for capability checks.
4177 if (isset($headerinfo['usercontext'])) {
4178 $context = $headerinfo['usercontext'];
4181 // Only provide user information if the user is the current user, or a user which the current user can view.
4182 // When checking user_can_view_profile(), either:
4183 // If the page context is course, check the course context (from the page object) or;
4184 // If page context is NOT course, then check across all courses.
4185 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4187 if (user_can_view_profile($user, $course)) {
4188 // Use the user's full name if the heading isn't set.
4189 if (empty($heading)) {
4190 $heading = fullname($user);
4193 $imagedata = $this->user_picture($user, array('size' => 100));
4195 // Check to see if we should be displaying a message button.
4196 if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
4197 $userbuttons = array(
4198 'messages' => array(
4199 'buttontype' => 'message',
4200 'title' => get_string('message', 'message'),
4201 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4202 'image' => 'message',
4203 'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
4204 'page' => $this->page
4208 if ($USER->id != $user->id) {
4209 $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4210 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4211 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4212 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4213 $userbuttons['togglecontact'] = array(
4214 'buttontype' => 'togglecontact',
4215 'title' => get_string($contacttitle, 'message'),
4216 'url' => new moodle_url('/message/index.php', array(
4217 'user1' => $USER->id,
4218 'user2' => $user->id,
4219 $contacturlaction => $user->id,
4220 'sesskey' => sesskey())
4222 'image' => $contactimage,
4223 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4224 'page' => $this->page
4228 $this->page->requires->string_for_js('changesmadereallygoaway', 'moodle');
4230 } else {
4231 $heading = null;
4235 if ($this->should_display_main_logo($headinglevel)) {
4236 $sitename = format_string($SITE->fullname, true, ['context' => context_course::instance(SITEID)]);
4237 // Logo.
4238 $html = html_writer::div(
4239 html_writer::empty_tag('img', [
4240 'src' => $this->get_logo_url(null, 150),
4241 'alt' => get_string('logoof', '', $sitename),
4242 'class' => 'img-fluid'
4244 'logo'
4246 // Heading.
4247 if (!isset($heading)) {
4248 $html .= $this->heading($this->page->heading, $headinglevel, 'sr-only');
4249 } else {
4250 $html .= $this->heading($heading, $headinglevel, 'sr-only');
4252 return $html;
4255 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4256 return $this->render_context_header($contextheader);
4260 * Renders the skip links for the page.
4262 * @param array $links List of skip links.
4263 * @return string HTML for the skip links.
4265 public function render_skip_links($links) {
4266 $context = [ 'links' => []];
4268 foreach ($links as $url => $text) {
4269 $context['links'][] = [ 'url' => $url, 'text' => $text];
4272 return $this->render_from_template('core/skip_links', $context);
4276 * Renders the header bar.
4278 * @param context_header $contextheader Header bar object.
4279 * @return string HTML for the header bar.
4281 protected function render_context_header(context_header $contextheader) {
4283 // Generate the heading first and before everything else as we might have to do an early return.
4284 if (!isset($contextheader->heading)) {
4285 $heading = $this->heading($this->page->heading, $contextheader->headinglevel);
4286 } else {
4287 $heading = $this->heading($contextheader->heading, $contextheader->headinglevel);
4290 $showheader = empty($this->page->layout_options['nocontextheader']);
4291 if (!$showheader) {
4292 // Return the heading wrapped in an sr-only element so it is only visible to screen-readers.
4293 return html_writer::div($heading, 'sr-only');
4296 // All the html stuff goes here.
4297 $html = html_writer::start_div('page-context-header');
4299 // Image data.
4300 if (isset($contextheader->imagedata)) {
4301 // Header specific image.
4302 $html .= html_writer::div($contextheader->imagedata, 'page-header-image');
4305 // Headings.
4306 $html .= html_writer::tag('div', $heading, array('class' => 'page-header-headings'));
4308 // Buttons.
4309 if (isset($contextheader->additionalbuttons)) {
4310 $html .= html_writer::start_div('btn-group header-button-group');
4311 foreach ($contextheader->additionalbuttons as $button) {
4312 if (!isset($button->page)) {
4313 // Include js for messaging.
4314 if ($button['buttontype'] === 'togglecontact') {
4315 \core_message\helper::togglecontact_requirejs();
4317 if ($button['buttontype'] === 'message') {
4318 \core_message\helper::messageuser_requirejs();
4320 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4321 'class' => 'iconsmall',
4322 'role' => 'presentation'
4324 $image .= html_writer::span($button['title'], 'header-button-title');
4325 } else {
4326 $image = html_writer::empty_tag('img', array(
4327 'src' => $button['formattedimage'],
4328 'role' => 'presentation'
4331 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4333 $html .= html_writer::end_div();
4335 $html .= html_writer::end_div();
4337 return $html;
4341 * Wrapper for header elements.
4343 * @return string HTML to display the main header.
4345 public function full_header() {
4347 if ($this->page->include_region_main_settings_in_header_actions() &&
4348 !$this->page->blocks->is_block_present('settings')) {
4349 // Only include the region main settings if the page has requested it and it doesn't already have
4350 // the settings block on it. The region main settings are included in the settings block and
4351 // duplicating the content causes behat failures.
4352 $this->page->add_header_action(html_writer::div(
4353 $this->region_main_settings_menu(),
4354 'd-print-none',
4355 ['id' => 'region-main-settings-menu']
4359 $header = new stdClass();
4360 $header->settingsmenu = $this->context_header_settings_menu();
4361 $header->contextheader = $this->context_header();
4362 $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
4363 $header->navbar = $this->navbar();
4364 $header->pageheadingbutton = $this->page_heading_button();
4365 $header->courseheader = $this->course_header();
4366 $header->headeractions = $this->page->get_header_actions();
4367 return $this->render_from_template('core/full_header', $header);
4371 * This is an optional menu that can be added to a layout by a theme. It contains the
4372 * menu for the course administration, only on the course main page.
4374 * @return string
4376 public function context_header_settings_menu() {
4377 $context = $this->page->context;
4378 $menu = new action_menu();
4380 $items = $this->page->navbar->get_items();
4381 $currentnode = end($items);
4383 $showcoursemenu = false;
4384 $showfrontpagemenu = false;
4385 $showusermenu = false;
4387 // We are on the course home page.
4388 if (($context->contextlevel == CONTEXT_COURSE) &&
4389 !empty($currentnode) &&
4390 ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
4391 $showcoursemenu = true;
4394 $courseformat = course_get_format($this->page->course);
4395 // This is a single activity course format, always show the course menu on the activity main page.
4396 if ($context->contextlevel == CONTEXT_MODULE &&
4397 !$courseformat->has_view_page()) {
4399 $this->page->navigation->initialise();
4400 $activenode = $this->page->navigation->find_active_node();
4401 // If the settings menu has been forced then show the menu.
4402 if ($this->page->is_settings_menu_forced()) {
4403 $showcoursemenu = true;
4404 } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
4405 $activenode->type == navigation_node::TYPE_RESOURCE)) {
4407 // We only want to show the menu on the first page of the activity. This means
4408 // the breadcrumb has no additional nodes.
4409 if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
4410 $showcoursemenu = true;
4415 // This is the site front page.
4416 if ($context->contextlevel == CONTEXT_COURSE &&
4417 !empty($currentnode) &&
4418 $currentnode->key === 'home') {
4419 $showfrontpagemenu = true;
4422 // This is the user profile page.
4423 if ($context->contextlevel == CONTEXT_USER &&
4424 !empty($currentnode) &&
4425 ($currentnode->key === 'myprofile')) {
4426 $showusermenu = true;
4429 if ($showfrontpagemenu) {
4430 $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
4431 if ($settingsnode) {
4432 // Build an action menu based on the visible nodes from this navigation tree.
4433 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4435 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4436 if ($skipped) {
4437 $text = get_string('morenavigationlinks');
4438 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4439 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4440 $menu->add_secondary_action($link);
4443 } else if ($showcoursemenu) {
4444 $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
4445 if ($settingsnode) {
4446 // Build an action menu based on the visible nodes from this navigation tree.
4447 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4449 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4450 if ($skipped) {
4451 $text = get_string('morenavigationlinks');
4452 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4453 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4454 $menu->add_secondary_action($link);
4457 } else if ($showusermenu) {
4458 // Get the course admin node from the settings navigation.
4459 $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
4460 if ($settingsnode) {
4461 // Build an action menu based on the visible nodes from this navigation tree.
4462 $this->build_action_menu_from_navigation($menu, $settingsnode);
4466 return $this->render($menu);
4470 * Take a node in the nav tree and make an action menu out of it.
4471 * The links are injected in the action menu.
4473 * @param action_menu $menu
4474 * @param navigation_node $node
4475 * @param boolean $indent
4476 * @param boolean $onlytopleafnodes
4477 * @return boolean nodesskipped - True if nodes were skipped in building the menu
4479 protected function build_action_menu_from_navigation(action_menu $menu,
4480 navigation_node $node,
4481 $indent = false,
4482 $onlytopleafnodes = false) {
4483 $skipped = false;
4484 // Build an action menu based on the visible nodes from this navigation tree.
4485 foreach ($node->children as $menuitem) {
4486 if ($menuitem->display) {
4487 if ($onlytopleafnodes && $menuitem->children->count()) {
4488 $skipped = true;
4489 continue;
4491 if ($menuitem->action) {
4492 if ($menuitem->action instanceof action_link) {
4493 $link = $menuitem->action;
4494 // Give preference to setting icon over action icon.
4495 if (!empty($menuitem->icon)) {
4496 $link->icon = $menuitem->icon;
4498 } else {
4499 $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
4501 } else {
4502 if ($onlytopleafnodes) {
4503 $skipped = true;
4504 continue;
4506 $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
4508 if ($indent) {
4509 $link->add_class('ml-4');
4511 if (!empty($menuitem->classes)) {
4512 $link->add_class(implode(" ", $menuitem->classes));
4515 $menu->add_secondary_action($link);
4516 $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
4519 return $skipped;
4523 * This is an optional menu that can be added to a layout by a theme. It contains the
4524 * menu for the most specific thing from the settings block. E.g. Module administration.
4526 * @return string
4528 public function region_main_settings_menu() {
4529 $context = $this->page->context;
4530 $menu = new action_menu();
4532 if ($context->contextlevel == CONTEXT_MODULE) {
4534 $this->page->navigation->initialise();
4535 $node = $this->page->navigation->find_active_node();
4536 $buildmenu = false;
4537 // If the settings menu has been forced then show the menu.
4538 if ($this->page->is_settings_menu_forced()) {
4539 $buildmenu = true;
4540 } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
4541 $node->type == navigation_node::TYPE_RESOURCE)) {
4543 $items = $this->page->navbar->get_items();
4544 $navbarnode = end($items);
4545 // We only want to show the menu on the first page of the activity. This means
4546 // the breadcrumb has no additional nodes.
4547 if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
4548 $buildmenu = true;
4551 if ($buildmenu) {
4552 // Get the course admin node from the settings navigation.
4553 $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
4554 if ($node) {
4555 // Build an action menu based on the visible nodes from this navigation tree.
4556 $this->build_action_menu_from_navigation($menu, $node);
4560 } else if ($context->contextlevel == CONTEXT_COURSECAT) {
4561 // For course category context, show category settings menu, if we're on the course category page.
4562 if ($this->page->pagetype === 'course-index-category') {
4563 $node = $this->page->settingsnav->find('categorysettings', navigation_node::TYPE_CONTAINER);
4564 if ($node) {
4565 // Build an action menu based on the visible nodes from this navigation tree.
4566 $this->build_action_menu_from_navigation($menu, $node);
4570 } else {
4571 $items = $this->page->navbar->get_items();
4572 $navbarnode = end($items);
4574 if ($navbarnode && ($navbarnode->key === 'participants')) {
4575 $node = $this->page->settingsnav->find('users', navigation_node::TYPE_CONTAINER);
4576 if ($node) {
4577 // Build an action menu based on the visible nodes from this navigation tree.
4578 $this->build_action_menu_from_navigation($menu, $node);
4583 return $this->render($menu);
4587 * Displays the list of tags associated with an entry
4589 * @param array $tags list of instances of core_tag or stdClass
4590 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4591 * to use default, set to '' (empty string) to omit the label completely
4592 * @param string $classes additional classes for the enclosing div element
4593 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4594 * will be appended to the end, JS will toggle the rest of the tags
4595 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4596 * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
4597 * @return string
4599 public function tag_list($tags, $label = null, $classes = '', $limit = 10,
4600 $pagecontext = null, $accesshidelabel = false) {
4601 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
4602 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4606 * Renders element for inline editing of any value
4608 * @param \core\output\inplace_editable $element
4609 * @return string
4611 public function render_inplace_editable(\core\output\inplace_editable $element) {
4612 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4616 * Renders a bar chart.
4618 * @param \core\chart_bar $chart The chart.
4619 * @return string.
4621 public function render_chart_bar(\core\chart_bar $chart) {
4622 return $this->render_chart($chart);
4626 * Renders a line chart.
4628 * @param \core\chart_line $chart The chart.
4629 * @return string.
4631 public function render_chart_line(\core\chart_line $chart) {
4632 return $this->render_chart($chart);
4636 * Renders a pie chart.
4638 * @param \core\chart_pie $chart The chart.
4639 * @return string.
4641 public function render_chart_pie(\core\chart_pie $chart) {
4642 return $this->render_chart($chart);
4646 * Renders a chart.
4648 * @param \core\chart_base $chart The chart.
4649 * @param bool $withtable Whether to include a data table with the chart.
4650 * @return string.
4652 public function render_chart(\core\chart_base $chart, $withtable = true) {
4653 $chartdata = json_encode($chart);
4654 return $this->render_from_template('core/chart', (object) [
4655 'chartdata' => $chartdata,
4656 'withtable' => $withtable
4661 * Renders the login form.
4663 * @param \core_auth\output\login $form The renderable.
4664 * @return string
4666 public function render_login(\core_auth\output\login $form) {
4667 global $CFG, $SITE;
4669 $context = $form->export_for_template($this);
4671 // Override because rendering is not supported in template yet.
4672 if ($CFG->rememberusername == 0) {
4673 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabledonlysession');
4674 } else {
4675 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
4677 $context->errorformatted = $this->error_text($context->error);
4678 $url = $this->get_logo_url();
4679 if ($url) {
4680 $url = $url->out(false);
4682 $context->logourl = $url;
4683 $context->sitename = format_string($SITE->fullname, true,
4684 ['context' => context_course::instance(SITEID), "escape" => false]);
4686 return $this->render_from_template('core/loginform', $context);
4690 * Renders an mform element from a template.
4692 * @param HTML_QuickForm_element $element element
4693 * @param bool $required if input is required field
4694 * @param bool $advanced if input is an advanced field
4695 * @param string $error error message to display
4696 * @param bool $ingroup True if this element is rendered as part of a group
4697 * @return mixed string|bool
4699 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4700 $templatename = 'core_form/element-' . $element->getType();
4701 if ($ingroup) {
4702 $templatename .= "-inline";
4704 try {
4705 // We call this to generate a file not found exception if there is no template.
4706 // We don't want to call export_for_template if there is no template.
4707 core\output\mustache_template_finder::get_template_filepath($templatename);
4709 if ($element instanceof templatable) {
4710 $elementcontext = $element->export_for_template($this);
4712 $helpbutton = '';
4713 if (method_exists($element, 'getHelpButton')) {
4714 $helpbutton = $element->getHelpButton();
4716 $label = $element->getLabel();
4717 $text = '';
4718 if (method_exists($element, 'getText')) {
4719 // There currently exists code that adds a form element with an empty label.
4720 // If this is the case then set the label to the description.
4721 if (empty($label)) {
4722 $label = $element->getText();
4723 } else {
4724 $text = $element->getText();
4728 // Generate the form element wrapper ids and names to pass to the template.
4729 // This differs between group and non-group elements.
4730 if ($element->getType() === 'group') {
4731 // Group element.
4732 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
4733 $elementcontext['wrapperid'] = $elementcontext['id'];
4735 // Ensure group elements pass through the group name as the element name.
4736 $elementcontext['name'] = $elementcontext['groupname'];
4737 } else {
4738 // Non grouped element.
4739 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
4740 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
4743 $context = array(
4744 'element' => $elementcontext,
4745 'label' => $label,
4746 'text' => $text,
4747 'required' => $required,
4748 'advanced' => $advanced,
4749 'helpbutton' => $helpbutton,
4750 'error' => $error
4752 return $this->render_from_template($templatename, $context);
4754 } catch (Exception $e) {
4755 // No template for this element.
4756 return false;
4761 * Render the login signup form into a nice template for the theme.
4763 * @param mform $form
4764 * @return string
4766 public function render_login_signup_form($form) {
4767 global $SITE;
4769 $context = $form->export_for_template($this);
4770 $url = $this->get_logo_url();
4771 if ($url) {
4772 $url = $url->out(false);
4774 $context['logourl'] = $url;
4775 $context['sitename'] = format_string($SITE->fullname, true,
4776 ['context' => context_course::instance(SITEID), "escape" => false]);
4778 return $this->render_from_template('core/signup_form_layout', $context);
4782 * Render the verify age and location page into a nice template for the theme.
4784 * @param \core_auth\output\verify_age_location_page $page The renderable
4785 * @return string
4787 protected function render_verify_age_location_page($page) {
4788 $context = $page->export_for_template($this);
4790 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4794 * Render the digital minor contact information page into a nice template for the theme.
4796 * @param \core_auth\output\digital_minor_page $page The renderable
4797 * @return string
4799 protected function render_digital_minor_page($page) {
4800 $context = $page->export_for_template($this);
4802 return $this->render_from_template('core/auth_digital_minor_page', $context);
4806 * Renders a progress bar.
4808 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4810 * @param progress_bar $bar The bar.
4811 * @return string HTML fragment
4813 public function render_progress_bar(progress_bar $bar) {
4814 $data = $bar->export_for_template($this);
4815 return $this->render_from_template('core/progress_bar', $data);
4819 * Renders an update to a progress bar.
4821 * Note: This does not cleanly map to a renderable class and should
4822 * never be used directly.
4824 * @param string $id
4825 * @param float $percent
4826 * @param string $msg Message
4827 * @param string $estimate time remaining message
4828 * @return string ascii fragment
4830 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
4831 return html_writer::script(js_writer::function_call('updateProgressBar', [$id, $percent, $msg, $estimate]));
4835 * Renders element for a toggle-all checkbox.
4837 * @param \core\output\checkbox_toggleall $element
4838 * @return string
4840 public function render_checkbox_toggleall(\core\output\checkbox_toggleall $element) {
4841 return $this->render_from_template($element->get_template(), $element->export_for_template($this));
4846 * A renderer that generates output for command-line scripts.
4848 * The implementation of this renderer is probably incomplete.
4850 * @copyright 2009 Tim Hunt
4851 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4852 * @since Moodle 2.0
4853 * @package core
4854 * @category output
4856 class core_renderer_cli extends core_renderer {
4859 * @var array $progressmaximums stores the largest percentage for a progress bar.
4860 * @return string ascii fragment
4862 private $progressmaximums = [];
4865 * Returns the page header.
4867 * @return string HTML fragment
4869 public function header() {
4870 return $this->page->heading . "\n";
4874 * Renders a Check API result
4876 * To aid in CLI consistency this status is NOT translated and the visual
4877 * width is always exactly 10 chars.
4879 * @param core\check\result $result
4880 * @return string HTML fragment
4882 protected function render_check_result(core\check\result $result) {
4883 $status = $result->get_status();
4885 $labels = [
4886 core\check\result::NA => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' NA ',
4887 core\check\result::OK => ' ' . cli_ansi_format('<colour:green>') . ' OK ',
4888 core\check\result::INFO => ' ' . cli_ansi_format('<colour:blue>' ) . ' INFO ',
4889 core\check\result::UNKNOWN => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' UNKNOWN ',
4890 core\check\result::WARNING => ' ' . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
4891 core\check\result::ERROR => ' ' . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
4892 core\check\result::CRITICAL => '' . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
4894 $string = $labels[$status] . cli_ansi_format('<colour:normal>');
4895 return $string;
4899 * Renders a Check API result
4901 * @param result $result
4902 * @return string fragment
4904 public function check_result(core\check\result $result) {
4905 return $this->render_check_result($result);
4909 * Renders a progress bar.
4911 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4913 * @param progress_bar $bar The bar.
4914 * @return string ascii fragment
4916 public function render_progress_bar(progress_bar $bar) {
4917 global $CFG;
4919 $size = 55; // The width of the progress bar in chars.
4920 $ascii = "\n";
4922 if (stream_isatty(STDOUT)) {
4923 require_once($CFG->libdir.'/clilib.php');
4925 $ascii .= "[" . str_repeat(' ', $size) . "] 0% \n";
4926 return cli_ansi_format($ascii);
4929 $this->progressmaximums[$bar->get_id()] = 0;
4930 $ascii .= '[';
4931 return $ascii;
4935 * Renders an update to a progress bar.
4937 * Note: This does not cleanly map to a renderable class and should
4938 * never be used directly.
4940 * @param string $id
4941 * @param float $percent
4942 * @param string $msg Message
4943 * @param string $estimate time remaining message
4944 * @return string ascii fragment
4946 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
4947 $size = 55; // The width of the progress bar in chars.
4948 $ascii = '';
4950 // If we are rendering to a terminal then we can safely use ansii codes
4951 // to move the cursor and redraw the complete progress bar each time
4952 // it is updated.
4953 if (stream_isatty(STDOUT)) {
4954 $colour = $percent == 100 ? 'green' : 'blue';
4956 $done = $percent * $size * 0.01;
4957 $whole = floor($done);
4958 $bar = "<colour:$colour>";
4959 $bar .= str_repeat('█', $whole);
4961 if ($whole < $size) {
4962 // By using unicode chars for partial blocks we can have higher
4963 // precision progress bar.
4964 $fraction = floor(($done - $whole) * 8);
4965 $bar .= core_text::substr(' ▏▎▍▌▋▊▉', $fraction, 1);
4967 // Fill the rest of the empty bar.
4968 $bar .= str_repeat(' ', $size - $whole - 1);
4971 $bar .= '<colour:normal>';
4973 if ($estimate) {
4974 $estimate = "- $estimate";
4977 $ascii .= '<cursor:up>';
4978 $ascii .= '<cursor:up>';
4979 $ascii .= sprintf("[$bar] %3.1f%% %-22s\n", $percent, $estimate);
4980 $ascii .= sprintf("%-80s\n", $msg);
4981 return cli_ansi_format($ascii);
4984 // If we are not rendering to a tty, ie when piped to another command
4985 // or on windows we need to progressively render the progress bar
4986 // which can only ever go forwards.
4987 $done = round($percent * $size * 0.01);
4988 $delta = max(0, $done - $this->progressmaximums[$id]);
4990 $ascii .= str_repeat('#', $delta);
4991 if ($percent >= 100 && $delta > 0) {
4992 $ascii .= sprintf("] %3.1f%%\n$msg\n", $percent);
4994 $this->progressmaximums[$id] += $delta;
4995 return $ascii;
4999 * Returns a template fragment representing a Heading.
5001 * @param string $text The text of the heading
5002 * @param int $level The level of importance of the heading
5003 * @param string $classes A space-separated list of CSS classes
5004 * @param string $id An optional ID
5005 * @return string A template fragment for a heading
5007 public function heading($text, $level = 2, $classes = 'main', $id = null) {
5008 $text .= "\n";
5009 switch ($level) {
5010 case 1:
5011 return '=>' . $text;
5012 case 2:
5013 return '-->' . $text;
5014 default:
5015 return $text;
5020 * Returns a template fragment representing a fatal error.
5022 * @param string $message The message to output
5023 * @param string $moreinfourl URL where more info can be found about the error
5024 * @param string $link Link for the Continue button
5025 * @param array $backtrace The execution backtrace
5026 * @param string $debuginfo Debugging information
5027 * @return string A template fragment for a fatal error
5029 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5030 global $CFG;
5032 $output = "!!! $message !!!\n";
5034 if ($CFG->debugdeveloper) {
5035 if (!empty($debuginfo)) {
5036 $output .= $this->notification($debuginfo, 'notifytiny');
5038 if (!empty($backtrace)) {
5039 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
5043 return $output;
5047 * Returns a template fragment representing a notification.
5049 * @param string $message The message to print out.
5050 * @param string $type The type of notification. See constants on \core\output\notification.
5051 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5052 * @return string A template fragment for a notification
5054 public function notification($message, $type = null, $closebutton = true) {
5055 $message = clean_text($message);
5056 if ($type === 'notifysuccess' || $type === 'success') {
5057 return "++ $message ++\n";
5059 return "!! $message !!\n";
5063 * There is no footer for a cli request, however we must override the
5064 * footer method to prevent the default footer.
5066 public function footer() {}
5069 * Render a notification (that is, a status message about something that has
5070 * just happened).
5072 * @param \core\output\notification $notification the notification to print out
5073 * @return string plain text output
5075 public function render_notification(\core\output\notification $notification) {
5076 return $this->notification($notification->get_message(), $notification->get_message_type());
5082 * A renderer that generates output for ajax scripts.
5084 * This renderer prevents accidental sends back only json
5085 * encoded error messages, all other output is ignored.
5087 * @copyright 2010 Petr Skoda
5088 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5089 * @since Moodle 2.0
5090 * @package core
5091 * @category output
5093 class core_renderer_ajax extends core_renderer {
5096 * Returns a template fragment representing a fatal error.
5098 * @param string $message The message to output
5099 * @param string $moreinfourl URL where more info can be found about the error
5100 * @param string $link Link for the Continue button
5101 * @param array $backtrace The execution backtrace
5102 * @param string $debuginfo Debugging information
5103 * @return string A template fragment for a fatal error
5105 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5106 global $CFG;
5108 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
5110 $e = new stdClass();
5111 $e->error = $message;
5112 $e->errorcode = $errorcode;
5113 $e->stacktrace = NULL;
5114 $e->debuginfo = NULL;
5115 $e->reproductionlink = NULL;
5116 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
5117 $link = (string) $link;
5118 if ($link) {
5119 $e->reproductionlink = $link;
5121 if (!empty($debuginfo)) {
5122 $e->debuginfo = $debuginfo;
5124 if (!empty($backtrace)) {
5125 $e->stacktrace = format_backtrace($backtrace, true);
5128 $this->header();
5129 return json_encode($e);
5133 * Used to display a notification.
5134 * For the AJAX notifications are discarded.
5136 * @param string $message The message to print out.
5137 * @param string $type The type of notification. See constants on \core\output\notification.
5138 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5140 public function notification($message, $type = null, $closebutton = true) {
5144 * Used to display a redirection message.
5145 * AJAX redirections should not occur and as such redirection messages
5146 * are discarded.
5148 * @param moodle_url|string $encodedurl
5149 * @param string $message
5150 * @param int $delay
5151 * @param bool $debugdisableredirect
5152 * @param string $messagetype The type of notification to show the message in.
5153 * See constants on \core\output\notification.
5155 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
5156 $messagetype = \core\output\notification::NOTIFY_INFO) {}
5159 * Prepares the start of an AJAX output.
5161 public function header() {
5162 // unfortunately YUI iframe upload does not support application/json
5163 if (!empty($_FILES)) {
5164 @header('Content-type: text/plain; charset=utf-8');
5165 if (!core_useragent::supports_json_contenttype()) {
5166 @header('X-Content-Type-Options: nosniff');
5168 } else if (!core_useragent::supports_json_contenttype()) {
5169 @header('Content-type: text/plain; charset=utf-8');
5170 @header('X-Content-Type-Options: nosniff');
5171 } else {
5172 @header('Content-type: application/json; charset=utf-8');
5175 // Headers to make it not cacheable and json
5176 @header('Cache-Control: no-store, no-cache, must-revalidate');
5177 @header('Cache-Control: post-check=0, pre-check=0', false);
5178 @header('Pragma: no-cache');
5179 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
5180 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
5181 @header('Accept-Ranges: none');
5185 * There is no footer for an AJAX request, however we must override the
5186 * footer method to prevent the default footer.
5188 public function footer() {}
5191 * No need for headers in an AJAX request... this should never happen.
5192 * @param string $text
5193 * @param int $level
5194 * @param string $classes
5195 * @param string $id
5197 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
5203 * The maintenance renderer.
5205 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
5206 * is running a maintenance related task.
5207 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
5209 * @since Moodle 2.6
5210 * @package core
5211 * @category output
5212 * @copyright 2013 Sam Hemelryk
5213 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5215 class core_renderer_maintenance extends core_renderer {
5218 * Initialises the renderer instance.
5220 * @param moodle_page $page
5221 * @param string $target
5222 * @throws coding_exception
5224 public function __construct(moodle_page $page, $target) {
5225 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
5226 throw new coding_exception('Invalid request for the maintenance renderer.');
5228 parent::__construct($page, $target);
5232 * Does nothing. The maintenance renderer cannot produce blocks.
5234 * @param block_contents $bc
5235 * @param string $region
5236 * @return string
5238 public function block(block_contents $bc, $region) {
5239 return '';
5243 * Does nothing. The maintenance renderer cannot produce blocks.
5245 * @param string $region
5246 * @param array $classes
5247 * @param string $tag
5248 * @param boolean $fakeblocksonly
5249 * @return string
5251 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
5252 return '';
5256 * Does nothing. The maintenance renderer cannot produce blocks.
5258 * @param string $region
5259 * @param boolean $fakeblocksonly Output fake block only.
5260 * @return string
5262 public function blocks_for_region($region, $fakeblocksonly = false) {
5263 return '';
5267 * Does nothing. The maintenance renderer cannot produce a course content header.
5269 * @param bool $onlyifnotcalledbefore
5270 * @return string
5272 public function course_content_header($onlyifnotcalledbefore = false) {
5273 return '';
5277 * Does nothing. The maintenance renderer cannot produce a course content footer.
5279 * @param bool $onlyifnotcalledbefore
5280 * @return string
5282 public function course_content_footer($onlyifnotcalledbefore = false) {
5283 return '';
5287 * Does nothing. The maintenance renderer cannot produce a course header.
5289 * @return string
5291 public function course_header() {
5292 return '';
5296 * Does nothing. The maintenance renderer cannot produce a course footer.
5298 * @return string
5300 public function course_footer() {
5301 return '';
5305 * Does nothing. The maintenance renderer cannot produce a custom menu.
5307 * @param string $custommenuitems
5308 * @return string
5310 public function custom_menu($custommenuitems = '') {
5311 return '';
5315 * Does nothing. The maintenance renderer cannot produce a file picker.
5317 * @param array $options
5318 * @return string
5320 public function file_picker($options) {
5321 return '';
5325 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
5327 * @param array $dir
5328 * @return string
5330 public function htmllize_file_tree($dir) {
5331 return '';
5336 * Overridden confirm message for upgrades.
5338 * @param string $message The question to ask the user
5339 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5340 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5341 * @return string HTML fragment
5343 public function confirm($message, $continue, $cancel) {
5344 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5345 // from any previous version of Moodle).
5346 if ($continue instanceof single_button) {
5347 $continue->primary = true;
5348 } else if (is_string($continue)) {
5349 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
5350 } else if ($continue instanceof moodle_url) {
5351 $continue = new single_button($continue, get_string('continue'), 'post', true);
5352 } else {
5353 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5354 ' (string/moodle_url) or a single_button instance.');
5357 if ($cancel instanceof single_button) {
5358 $output = '';
5359 } else if (is_string($cancel)) {
5360 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5361 } else if ($cancel instanceof moodle_url) {
5362 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5363 } else {
5364 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5365 ' (string/moodle_url) or a single_button instance.');
5368 $output = $this->box_start('generalbox', 'notice');
5369 $output .= html_writer::tag('h4', get_string('confirm'));
5370 $output .= html_writer::tag('p', $message);
5371 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
5372 $output .= $this->box_end();
5373 return $output;
5377 * Does nothing. The maintenance renderer does not support JS.
5379 * @param block_contents $bc
5381 public function init_block_hider_js(block_contents $bc) {
5382 // Does nothing.
5386 * Does nothing. The maintenance renderer cannot produce language menus.
5388 * @return string
5390 public function lang_menu() {
5391 return '';
5395 * Does nothing. The maintenance renderer has no need for login information.
5397 * @param null $withlinks
5398 * @return string
5400 public function login_info($withlinks = null) {
5401 return '';
5405 * Secure login info.
5407 * @return string
5409 public function secure_login_info() {
5410 return $this->login_info(false);
5414 * Does nothing. The maintenance renderer cannot produce user pictures.
5416 * @param stdClass $user
5417 * @param array $options
5418 * @return string
5420 public function user_picture(stdClass $user, array $options = null) {
5421 return '';