Merge branch 'MDL-71860-master' of git://github.com/lameze/moodle
[moodle.git] / lib / outputrenderers.php
blob8deb104e90c21f6969943bc9c5e8d43c75b05b7d
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 $quotehelper = new \core\output\mustache_quote_helper();
109 $jshelper = new \core\output\mustache_javascript_helper($this->page);
110 $pixhelper = new \core\output\mustache_pix_helper($this);
111 $shortentexthelper = new \core\output\mustache_shorten_text_helper();
112 $userdatehelper = new \core\output\mustache_user_date_helper();
114 // We only expose the variables that are exposed to JS templates.
115 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
117 $helpers = array('config' => $safeconfig,
118 'str' => array($stringhelper, 'str'),
119 'quote' => array($quotehelper, 'quote'),
120 'js' => array($jshelper, 'help'),
121 'pix' => array($pixhelper, 'pix'),
122 'shortentext' => array($shortentexthelper, 'shorten'),
123 'userdate' => array($userdatehelper, 'transform'),
126 $this->mustache = new \core\output\mustache_engine(array(
127 'cache' => $cachedir,
128 'escape' => 's',
129 'loader' => $loader,
130 'helpers' => $helpers,
131 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS],
132 // Don't allow the JavaScript helper to be executed from within another
133 // helper. If it's allowed it can be used by users to inject malicious
134 // JS into the page.
135 'disallowednestedhelpers' => ['js']));
139 return $this->mustache;
144 * Constructor
146 * The constructor takes two arguments. The first is the page that the renderer
147 * has been created to assist with, and the second is the target.
148 * The target is an additional identifier that can be used to load different
149 * renderers for different options.
151 * @param moodle_page $page the page we are doing output for.
152 * @param string $target one of rendering target constants
154 public function __construct(moodle_page $page, $target) {
155 $this->opencontainers = $page->opencontainers;
156 $this->page = $page;
157 $this->target = $target;
161 * Renders a template by name with the given context.
163 * The provided data needs to be array/stdClass made up of only simple types.
164 * Simple types are array,stdClass,bool,int,float,string
166 * @since 2.9
167 * @param array|stdClass $context Context containing data for the template.
168 * @return string|boolean
170 public function render_from_template($templatename, $context) {
171 static $templatecache = array();
172 $mustache = $this->get_mustache();
174 try {
175 // Grab a copy of the existing helper to be restored later.
176 $uniqidhelper = $mustache->getHelper('uniqid');
177 } catch (Mustache_Exception_UnknownHelperException $e) {
178 // Helper doesn't exist.
179 $uniqidhelper = null;
182 // Provide 1 random value that will not change within a template
183 // but will be different from template to template. This is useful for
184 // e.g. aria attributes that only work with id attributes and must be
185 // unique in a page.
186 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
187 if (isset($templatecache[$templatename])) {
188 $template = $templatecache[$templatename];
189 } else {
190 try {
191 $template = $mustache->loadTemplate($templatename);
192 $templatecache[$templatename] = $template;
193 } catch (Mustache_Exception_UnknownTemplateException $e) {
194 throw new moodle_exception('Unknown template: ' . $templatename);
198 $renderedtemplate = trim($template->render($context));
200 // If we had an existing uniqid helper then we need to restore it to allow
201 // handle nested calls of render_from_template.
202 if ($uniqidhelper) {
203 $mustache->addHelper('uniqid', $uniqidhelper);
206 return $renderedtemplate;
211 * Returns rendered widget.
213 * The provided widget needs to be an object that extends the renderable
214 * interface.
215 * If will then be rendered by a method based upon the classname for the widget.
216 * For instance a widget of class `crazywidget` will be rendered by a protected
217 * render_crazywidget method of this renderer.
218 * If no render_crazywidget method exists and crazywidget implements templatable,
219 * look for the 'crazywidget' template in the same component and render that.
221 * @param renderable $widget instance with renderable interface
222 * @return string
224 public function render(renderable $widget) {
225 $classparts = explode('\\', get_class($widget));
226 // Strip namespaces.
227 $classname = array_pop($classparts);
228 // Remove _renderable suffixes
229 $classname = preg_replace('/_renderable$/', '', $classname);
231 $rendermethod = 'render_'.$classname;
232 if (method_exists($this, $rendermethod)) {
233 return $this->$rendermethod($widget);
235 if ($widget instanceof templatable) {
236 $component = array_shift($classparts);
237 if (!$component) {
238 $component = 'core';
240 $template = $component . '/' . $classname;
241 $context = $widget->export_for_template($this);
242 return $this->render_from_template($template, $context);
244 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
248 * Adds a JS action for the element with the provided id.
250 * This method adds a JS event for the provided component action to the page
251 * and then returns the id that the event has been attached to.
252 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
254 * @param component_action $action
255 * @param string $id
256 * @return string id of element, either original submitted or random new if not supplied
258 public function add_action_handler(component_action $action, $id = null) {
259 if (!$id) {
260 $id = html_writer::random_id($action->event);
262 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
263 return $id;
267 * Returns true is output has already started, and false if not.
269 * @return boolean true if the header has been printed.
271 public function has_started() {
272 return $this->page->state >= moodle_page::STATE_IN_BODY;
276 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
278 * @param mixed $classes Space-separated string or array of classes
279 * @return string HTML class attribute value
281 public static function prepare_classes($classes) {
282 if (is_array($classes)) {
283 return implode(' ', array_unique($classes));
285 return $classes;
289 * Return the direct URL for an image from the pix folder.
291 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
293 * @deprecated since Moodle 3.3
294 * @param string $imagename the name of the icon.
295 * @param string $component specification of one plugin like in get_string()
296 * @return moodle_url
298 public function pix_url($imagename, $component = 'moodle') {
299 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
300 return $this->page->theme->image_url($imagename, $component);
304 * Return the moodle_url for an image.
306 * The exact image location and extension is determined
307 * automatically by searching for gif|png|jpg|jpeg, please
308 * note there can not be diferent images with the different
309 * extension. The imagename is for historical reasons
310 * a relative path name, it may be changed later for core
311 * images. It is recommended to not use subdirectories
312 * in plugin and theme pix directories.
314 * There are three types of images:
315 * 1/ theme images - stored in theme/mytheme/pix/,
316 * use component 'theme'
317 * 2/ core images - stored in /pix/,
318 * overridden via theme/mytheme/pix_core/
319 * 3/ plugin images - stored in mod/mymodule/pix,
320 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
321 * example: image_url('comment', 'mod_glossary')
323 * @param string $imagename the pathname of the image
324 * @param string $component full plugin name (aka component) or 'theme'
325 * @return moodle_url
327 public function image_url($imagename, $component = 'moodle') {
328 return $this->page->theme->image_url($imagename, $component);
332 * Return the site's logo URL, if any.
334 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
335 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
336 * @return moodle_url|false
338 public function get_logo_url($maxwidth = null, $maxheight = 200) {
339 global $CFG;
340 $logo = get_config('core_admin', 'logo');
341 if (empty($logo)) {
342 return false;
345 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
346 // It's not worth the overhead of detecting and serving 2 different images based on the device.
348 // Hide the requested size in the file path.
349 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
351 // Use $CFG->themerev to prevent browser caching when the file changes.
352 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
353 theme_get_revision(), $logo);
357 * Return the site's compact logo URL, if any.
359 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
360 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
361 * @return moodle_url|false
363 public function get_compact_logo_url($maxwidth = 300, $maxheight = 300) {
364 global $CFG;
365 $logo = get_config('core_admin', 'logocompact');
366 if (empty($logo)) {
367 return false;
370 // Hide the requested size in the file path.
371 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
373 // Use $CFG->themerev to prevent browser caching when the file changes.
374 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
375 theme_get_revision(), $logo);
379 * Whether we should display the logo in the navbar.
381 * We will when there are no main logos, and we have compact logo.
383 * @return bool
385 public function should_display_navbar_logo() {
386 $logo = $this->get_compact_logo_url();
387 return !empty($logo) && !$this->should_display_main_logo();
391 * Whether we should display the main logo.
393 * @param int $headinglevel The heading level we want to check against.
394 * @return bool
396 public function should_display_main_logo($headinglevel = 1) {
398 // Only render the logo if we're on the front page or login page and the we have a logo.
399 $logo = $this->get_logo_url();
400 if ($headinglevel == 1 && !empty($logo)) {
401 if ($this->page->pagelayout == 'frontpage' || $this->page->pagelayout == 'login') {
402 return true;
406 return false;
413 * Basis for all plugin renderers.
415 * @copyright Petr Skoda (skodak)
416 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
417 * @since Moodle 2.0
418 * @package core
419 * @category output
421 class plugin_renderer_base extends renderer_base {
424 * @var renderer_base|core_renderer A reference to the current renderer.
425 * The renderer provided here will be determined by the page but will in 90%
426 * of cases by the {@link core_renderer}
428 protected $output;
431 * Constructor method, calls the parent constructor
433 * @param moodle_page $page
434 * @param string $target one of rendering target constants
436 public function __construct(moodle_page $page, $target) {
437 if (empty($target) && $page->pagelayout === 'maintenance') {
438 // If the page is using the maintenance layout then we're going to force the target to maintenance.
439 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
440 // unavailable for this page layout.
441 $target = RENDERER_TARGET_MAINTENANCE;
443 $this->output = $page->get_renderer('core', null, $target);
444 parent::__construct($page, $target);
448 * Renders the provided widget and returns the HTML to display it.
450 * @param renderable $widget instance with renderable interface
451 * @return string
453 public function render(renderable $widget) {
454 $classname = get_class($widget);
455 // Strip namespaces.
456 $classname = preg_replace('/^.*\\\/', '', $classname);
457 // Keep a copy at this point, we may need to look for a deprecated method.
458 $deprecatedmethod = 'render_'.$classname;
459 // Remove _renderable suffixes
460 $classname = preg_replace('/_renderable$/', '', $classname);
462 $rendermethod = 'render_'.$classname;
463 if (method_exists($this, $rendermethod)) {
464 return $this->$rendermethod($widget);
466 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
467 // This is exactly where we don't want to be.
468 // If you have arrived here you have a renderable component within your plugin that has the name
469 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
470 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
471 // and the _renderable suffix now gets removed when looking for a render method.
472 // You need to change your renderers render_blah_renderable to render_blah.
473 // Until you do this it will not be possible for a theme to override the renderer to override your method.
474 // Please do it ASAP.
475 static $debugged = array();
476 if (!isset($debugged[$deprecatedmethod])) {
477 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
478 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
479 $debugged[$deprecatedmethod] = true;
481 return $this->$deprecatedmethod($widget);
483 // pass to core renderer if method not found here
484 return $this->output->render($widget);
488 * Magic method used to pass calls otherwise meant for the standard renderer
489 * to it to ensure we don't go causing unnecessary grief.
491 * @param string $method
492 * @param array $arguments
493 * @return mixed
495 public function __call($method, $arguments) {
496 if (method_exists('renderer_base', $method)) {
497 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
499 if (method_exists($this->output, $method)) {
500 return call_user_func_array(array($this->output, $method), $arguments);
501 } else {
502 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
509 * The standard implementation of the core_renderer interface.
511 * @copyright 2009 Tim Hunt
512 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
513 * @since Moodle 2.0
514 * @package core
515 * @category output
517 class core_renderer extends renderer_base {
519 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
520 * in layout files instead.
521 * @deprecated
522 * @var string used in {@link core_renderer::header()}.
524 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
527 * @var string Used to pass information from {@link core_renderer::doctype()} to
528 * {@link core_renderer::standard_head_html()}.
530 protected $contenttype;
533 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
534 * with {@link core_renderer::header()}.
536 protected $metarefreshtag = '';
539 * @var string Unique token for the closing HTML
541 protected $unique_end_html_token;
544 * @var string Unique token for performance information
546 protected $unique_performance_info_token;
549 * @var string Unique token for the main content.
551 protected $unique_main_content_token;
553 /** @var custom_menu_item language The language menu if created */
554 protected $language = null;
557 * Constructor
559 * @param moodle_page $page the page we are doing output for.
560 * @param string $target one of rendering target constants
562 public function __construct(moodle_page $page, $target) {
563 $this->opencontainers = $page->opencontainers;
564 $this->page = $page;
565 $this->target = $target;
567 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
568 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
569 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
573 * Get the DOCTYPE declaration that should be used with this page. Designed to
574 * be called in theme layout.php files.
576 * @return string the DOCTYPE declaration that should be used.
578 public function doctype() {
579 if ($this->page->theme->doctype === 'html5') {
580 $this->contenttype = 'text/html; charset=utf-8';
581 return "<!DOCTYPE html>\n";
583 } else if ($this->page->theme->doctype === 'xhtml5') {
584 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
585 return "<!DOCTYPE html>\n";
587 } else {
588 // legacy xhtml 1.0
589 $this->contenttype = 'text/html; charset=utf-8';
590 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
595 * The attributes that should be added to the <html> tag. Designed to
596 * be called in theme layout.php files.
598 * @return string HTML fragment.
600 public function htmlattributes() {
601 $return = get_html_lang(true);
602 $attributes = array();
603 if ($this->page->theme->doctype !== 'html5') {
604 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
607 // Give plugins an opportunity to add things like xml namespaces to the html element.
608 // This function should return an array of html attribute names => values.
609 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
610 foreach ($pluginswithfunction as $plugins) {
611 foreach ($plugins as $function) {
612 $newattrs = $function();
613 unset($newattrs['dir']);
614 unset($newattrs['lang']);
615 unset($newattrs['xmlns']);
616 unset($newattrs['xml:lang']);
617 $attributes += $newattrs;
621 foreach ($attributes as $key => $val) {
622 $val = s($val);
623 $return .= " $key=\"$val\"";
626 return $return;
630 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
631 * that should be included in the <head> tag. Designed to be called in theme
632 * layout.php files.
634 * @return string HTML fragment.
636 public function standard_head_html() {
637 global $CFG, $SESSION, $SITE;
639 // Before we output any content, we need to ensure that certain
640 // page components are set up.
642 // Blocks must be set up early as they may require javascript which
643 // has to be included in the page header before output is created.
644 foreach ($this->page->blocks->get_regions() as $region) {
645 $this->page->blocks->ensure_content_created($region, $this);
648 $output = '';
650 // Give plugins an opportunity to add any head elements. The callback
651 // must always return a string containing valid html head content.
652 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
653 foreach ($pluginswithfunction as $plugins) {
654 foreach ($plugins as $function) {
655 $output .= $function();
659 // Allow a url_rewrite plugin to setup any dynamic head content.
660 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
661 $class = $CFG->urlrewriteclass;
662 $output .= $class::html_head_setup();
665 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
666 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
667 // This is only set by the {@link redirect()} method
668 $output .= $this->metarefreshtag;
670 // Check if a periodic refresh delay has been set and make sure we arn't
671 // already meta refreshing
672 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
673 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
676 // Set up help link popups for all links with the helptooltip class
677 $this->page->requires->js_init_call('M.util.help_popups.setup');
679 $focus = $this->page->focuscontrol;
680 if (!empty($focus)) {
681 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
682 // This is a horrifically bad way to handle focus but it is passed in
683 // through messy formslib::moodleform
684 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
685 } else if (strpos($focus, '.')!==false) {
686 // Old style of focus, bad way to do it
687 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);
688 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
689 } else {
690 // Focus element with given id
691 $this->page->requires->js_function_call('focuscontrol', array($focus));
695 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
696 // any other custom CSS can not be overridden via themes and is highly discouraged
697 $urls = $this->page->theme->css_urls($this->page);
698 foreach ($urls as $url) {
699 $this->page->requires->css_theme($url);
702 // Get the theme javascript head and footer
703 if ($jsurl = $this->page->theme->javascript_url(true)) {
704 $this->page->requires->js($jsurl, true);
706 if ($jsurl = $this->page->theme->javascript_url(false)) {
707 $this->page->requires->js($jsurl);
710 // Get any HTML from the page_requirements_manager.
711 $output .= $this->page->requires->get_head_code($this->page, $this);
713 // List alternate versions.
714 foreach ($this->page->alternateversions as $type => $alt) {
715 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
716 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
719 // Add noindex tag if relevant page and setting applied.
720 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
721 $loginpages = array('login-index', 'login-signup');
722 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
723 if (!isset($CFG->additionalhtmlhead)) {
724 $CFG->additionalhtmlhead = '';
726 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
729 if (!empty($CFG->additionalhtmlhead)) {
730 $output .= "\n".$CFG->additionalhtmlhead;
733 if ($this->page->pagelayout == 'frontpage') {
734 $summary = s(strip_tags(format_text($SITE->summary, FORMAT_HTML)));
735 if (!empty($summary)) {
736 $output .= "<meta name=\"description\" content=\"$summary\" />\n";
740 return $output;
744 * The standard tags (typically skip links) that should be output just inside
745 * the start of the <body> tag. Designed to be called in theme layout.php files.
747 * @return string HTML fragment.
749 public function standard_top_of_body_html() {
750 global $CFG;
751 $output = $this->page->requires->get_top_of_body_code($this);
752 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
753 $output .= "\n".$CFG->additionalhtmltopofbody;
756 // Give subsystems an opportunity to inject extra html content. The callback
757 // must always return a string containing valid html.
758 foreach (\core_component::get_core_subsystems() as $name => $path) {
759 if ($path) {
760 $output .= component_callback($name, 'before_standard_top_of_body_html', [], '');
764 // Give plugins an opportunity to inject extra html content. The callback
765 // must always return a string containing valid html.
766 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
767 foreach ($pluginswithfunction as $plugins) {
768 foreach ($plugins as $function) {
769 $output .= $function();
773 $output .= $this->maintenance_warning();
775 return $output;
779 * Scheduled maintenance warning message.
781 * Note: This is a nasty hack to display maintenance notice, this should be moved
782 * to some general notification area once we have it.
784 * @return string
786 public function maintenance_warning() {
787 global $CFG;
789 $output = '';
790 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
791 $timeleft = $CFG->maintenance_later - time();
792 // If timeleft less than 30 sec, set the class on block to error to highlight.
793 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
794 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-3 alert');
795 $a = new stdClass();
796 $a->hour = (int)($timeleft / 3600);
797 $a->min = (int)(($timeleft / 60) % 60);
798 $a->sec = (int)($timeleft % 60);
799 if ($a->hour > 0) {
800 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
801 } else {
802 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
805 $output .= $this->box_end();
806 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
807 array(array('timeleftinsec' => $timeleft)));
808 $this->page->requires->strings_for_js(
809 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
810 'admin');
812 return $output;
816 * The standard tags (typically performance information and validation links,
817 * if we are in developer debug mode) that should be output in the footer area
818 * of the page. Designed to be called in theme layout.php files.
820 * @return string HTML fragment.
822 public function standard_footer_html() {
823 global $CFG, $SCRIPT;
825 $output = '';
826 if (during_initial_install()) {
827 // Debugging info can not work before install is finished,
828 // in any case we do not want any links during installation!
829 return $output;
832 // Give plugins an opportunity to add any footer elements.
833 // The callback must always return a string containing valid html footer content.
834 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
835 foreach ($pluginswithfunction as $plugins) {
836 foreach ($plugins as $function) {
837 $output .= $function();
841 if (core_userfeedback::can_give_feedback()) {
842 $output .= html_writer::div(
843 $this->render_from_template('core/userfeedback_footer_link', ['url' => core_userfeedback::make_link()->out(false)])
847 // This function is normally called from a layout.php file in {@link core_renderer::header()}
848 // but some of the content won't be known until later, so we return a placeholder
849 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
850 $output .= $this->unique_performance_info_token;
851 if ($this->page->devicetypeinuse == 'legacy') {
852 // The legacy theme is in use print the notification
853 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
856 // Get links to switch device types (only shown for users not on a default device)
857 $output .= $this->theme_switch_links();
859 if (!empty($CFG->debugpageinfo)) {
860 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
861 $this->page->debug_summary()) . '</div>';
863 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
864 // Add link to profiling report if necessary
865 if (function_exists('profiling_is_running') && profiling_is_running()) {
866 $txt = get_string('profiledscript', 'admin');
867 $title = get_string('profiledscriptview', 'admin');
868 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
869 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
870 $output .= '<div class="profilingfooter">' . $link . '</div>';
872 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
873 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
874 $output .= '<div class="purgecaches">' .
875 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
877 if (!empty($CFG->debugvalidators)) {
878 // NOTE: this is not a nice hack, $this->page->url is not always accurate and
879 // $FULLME neither, it is not a bug if it fails. --skodak.
880 $output .= '<div class="validators"><ul class="list-unstyled ml-1">
881 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
882 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
883 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&amp;warnp2n3e=1&amp;url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
884 </ul></div>';
886 return $output;
890 * Returns standard main content placeholder.
891 * Designed to be called in theme layout.php files.
893 * @return string HTML fragment.
895 public function main_content() {
896 // This is here because it is the only place we can inject the "main" role over the entire main content area
897 // without requiring all theme's to manually do it, and without creating yet another thing people need to
898 // remember in the theme.
899 // This is an unfortunate hack. DO NO EVER add anything more here.
900 // DO NOT add classes.
901 // DO NOT add an id.
902 return '<div role="main">'.$this->unique_main_content_token.'</div>';
906 * Returns information about an activity.
908 * @param cm_info $cminfo The course module information.
909 * @param cm_completion_details $completiondetails The completion details for this activity module.
910 * @param array $activitydates The dates for this activity module.
911 * @return string the activity information HTML.
912 * @throws coding_exception
914 public function activity_information(cm_info $cminfo, cm_completion_details $completiondetails, array $activitydates): string {
915 if (!$completiondetails->has_completion() && empty($activitydates)) {
916 // No need to render the activity information when there's no completion info and activity dates to show.
917 return '';
919 $activityinfo = new activity_information($cminfo, $completiondetails, $activitydates);
920 $renderer = $this->page->get_renderer('core', 'course');
921 return $renderer->render($activityinfo);
925 * Returns standard navigation between activities in a course.
927 * @return string the navigation HTML.
929 public function activity_navigation() {
930 // First we should check if we want to add navigation.
931 $context = $this->page->context;
932 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
933 || $context->contextlevel != CONTEXT_MODULE) {
934 return '';
937 // If the activity is in stealth mode, show no links.
938 if ($this->page->cm->is_stealth()) {
939 return '';
942 // Get a list of all the activities in the course.
943 $course = $this->page->cm->get_course();
944 $modules = get_fast_modinfo($course->id)->get_cms();
946 // Put the modules into an array in order by the position they are shown in the course.
947 $mods = [];
948 $activitylist = [];
949 foreach ($modules as $module) {
950 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
951 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
952 continue;
954 $mods[$module->id] = $module;
956 // No need to add the current module to the list for the activity dropdown menu.
957 if ($module->id == $this->page->cm->id) {
958 continue;
960 // Module name.
961 $modname = $module->get_formatted_name();
962 // Display the hidden text if necessary.
963 if (!$module->visible) {
964 $modname .= ' ' . get_string('hiddenwithbrackets');
966 // Module URL.
967 $linkurl = new moodle_url($module->url, array('forceview' => 1));
968 // Add module URL (as key) and name (as value) to the activity list array.
969 $activitylist[$linkurl->out(false)] = $modname;
972 $nummods = count($mods);
974 // If there is only one mod then do nothing.
975 if ($nummods == 1) {
976 return '';
979 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
980 $modids = array_keys($mods);
982 // Get the position in the array of the course module we are viewing.
983 $position = array_search($this->page->cm->id, $modids);
985 $prevmod = null;
986 $nextmod = null;
988 // Check if we have a previous mod to show.
989 if ($position > 0) {
990 $prevmod = $mods[$modids[$position - 1]];
993 // Check if we have a next mod to show.
994 if ($position < ($nummods - 1)) {
995 $nextmod = $mods[$modids[$position + 1]];
998 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
999 $renderer = $this->page->get_renderer('core', 'course');
1000 return $renderer->render($activitynav);
1004 * The standard tags (typically script tags that are not needed earlier) that
1005 * should be output after everything else. Designed to be called in theme layout.php files.
1007 * @return string HTML fragment.
1009 public function standard_end_of_body_html() {
1010 global $CFG;
1012 // This function is normally called from a layout.php file in {@link core_renderer::header()}
1013 // but some of the content won't be known until later, so we return a placeholder
1014 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
1015 $output = '';
1016 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
1017 $output .= "\n".$CFG->additionalhtmlfooter;
1019 $output .= $this->unique_end_html_token;
1020 return $output;
1024 * The standard HTML that should be output just before the <footer> tag.
1025 * Designed to be called in theme layout.php files.
1027 * @return string HTML fragment.
1029 public function standard_after_main_region_html() {
1030 global $CFG;
1031 $output = '';
1032 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlbottomofbody)) {
1033 $output .= "\n".$CFG->additionalhtmlbottomofbody;
1036 // Give subsystems an opportunity to inject extra html content. The callback
1037 // must always return a string containing valid html.
1038 foreach (\core_component::get_core_subsystems() as $name => $path) {
1039 if ($path) {
1040 $output .= component_callback($name, 'standard_after_main_region_html', [], '');
1044 // Give plugins an opportunity to inject extra html content. The callback
1045 // must always return a string containing valid html.
1046 $pluginswithfunction = get_plugins_with_function('standard_after_main_region_html', 'lib.php');
1047 foreach ($pluginswithfunction as $plugins) {
1048 foreach ($plugins as $function) {
1049 $output .= $function();
1053 return $output;
1057 * Return the standard string that says whether you are logged in (and switched
1058 * roles/logged in as another user).
1059 * @param bool $withlinks if false, then don't include any links in the HTML produced.
1060 * If not set, the default is the nologinlinks option from the theme config.php file,
1061 * and if that is not set, then links are included.
1062 * @return string HTML fragment.
1064 public function login_info($withlinks = null) {
1065 global $USER, $CFG, $DB, $SESSION;
1067 if (during_initial_install()) {
1068 return '';
1071 if (is_null($withlinks)) {
1072 $withlinks = empty($this->page->layout_options['nologinlinks']);
1075 $course = $this->page->course;
1076 if (\core\session\manager::is_loggedinas()) {
1077 $realuser = \core\session\manager::get_realuser();
1078 $fullname = fullname($realuser);
1079 if ($withlinks) {
1080 $loginastitle = get_string('loginas');
1081 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
1082 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
1083 } else {
1084 $realuserinfo = " [$fullname] ";
1086 } else {
1087 $realuserinfo = '';
1090 $loginpage = $this->is_login_page();
1091 $loginurl = get_login_url();
1093 if (empty($course->id)) {
1094 // $course->id is not defined during installation
1095 return '';
1096 } else if (isloggedin()) {
1097 $context = context_course::instance($course->id);
1099 $fullname = fullname($USER);
1100 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
1101 if ($withlinks) {
1102 $linktitle = get_string('viewprofile');
1103 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
1104 } else {
1105 $username = $fullname;
1107 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
1108 if ($withlinks) {
1109 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1110 } else {
1111 $username .= " from {$idprovider->name}";
1114 if (isguestuser()) {
1115 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1116 if (!$loginpage && $withlinks) {
1117 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1119 } else if (is_role_switched($course->id)) { // Has switched roles
1120 $rolename = '';
1121 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1122 $rolename = ': '.role_get_name($role, $context);
1124 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1125 if ($withlinks) {
1126 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1127 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1129 } else {
1130 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1131 if ($withlinks) {
1132 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1135 } else {
1136 $loggedinas = get_string('loggedinnot', 'moodle');
1137 if (!$loginpage && $withlinks) {
1138 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1142 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1144 if (isset($SESSION->justloggedin)) {
1145 unset($SESSION->justloggedin);
1146 if (!empty($CFG->displayloginfailures)) {
1147 if (!isguestuser()) {
1148 // Include this file only when required.
1149 require_once($CFG->dirroot . '/user/lib.php');
1150 if ($count = user_count_login_failures($USER)) {
1151 $loggedinas .= '<div class="loginfailures">';
1152 $a = new stdClass();
1153 $a->attempts = $count;
1154 $loggedinas .= get_string('failedloginattempts', '', $a);
1155 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1156 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1157 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1159 $loggedinas .= '</div>';
1165 return $loggedinas;
1169 * Check whether the current page is a login page.
1171 * @since Moodle 2.9
1172 * @return bool
1174 protected function is_login_page() {
1175 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1176 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1177 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1178 return in_array(
1179 $this->page->url->out_as_local_url(false, array()),
1180 array(
1181 '/login/index.php',
1182 '/login/forgot_password.php',
1188 * Return the 'back' link that normally appears in the footer.
1190 * @return string HTML fragment.
1192 public function home_link() {
1193 global $CFG, $SITE;
1195 if ($this->page->pagetype == 'site-index') {
1196 // Special case for site home page - please do not remove
1197 return '<div class="sitelink">' .
1198 '<a title="Moodle" class="d-inline-block aalink" href="http://moodle.org/">' .
1199 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1201 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1202 // Special case for during install/upgrade.
1203 return '<div class="sitelink">'.
1204 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1205 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1207 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1208 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1209 get_string('home') . '</a></div>';
1211 } else {
1212 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1213 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1218 * Redirects the user by any means possible given the current state
1220 * This function should not be called directly, it should always be called using
1221 * the redirect function in lib/weblib.php
1223 * The redirect function should really only be called before page output has started
1224 * however it will allow itself to be called during the state STATE_IN_BODY
1226 * @param string $encodedurl The URL to send to encoded if required
1227 * @param string $message The message to display to the user if any
1228 * @param int $delay The delay before redirecting a user, if $message has been
1229 * set this is a requirement and defaults to 3, set to 0 no delay
1230 * @param boolean $debugdisableredirect this redirect has been disabled for
1231 * debugging purposes. Display a message that explains, and don't
1232 * trigger the redirect.
1233 * @param string $messagetype The type of notification to show the message in.
1234 * See constants on \core\output\notification.
1235 * @return string The HTML to display to the user before dying, may contain
1236 * meta refresh, javascript refresh, and may have set header redirects
1238 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1239 $messagetype = \core\output\notification::NOTIFY_INFO) {
1240 global $CFG;
1241 $url = str_replace('&amp;', '&', $encodedurl);
1243 switch ($this->page->state) {
1244 case moodle_page::STATE_BEFORE_HEADER :
1245 // No output yet it is safe to delivery the full arsenal of redirect methods
1246 if (!$debugdisableredirect) {
1247 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1248 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1249 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1251 $output = $this->header();
1252 break;
1253 case moodle_page::STATE_PRINTING_HEADER :
1254 // We should hopefully never get here
1255 throw new coding_exception('You cannot redirect while printing the page header');
1256 break;
1257 case moodle_page::STATE_IN_BODY :
1258 // We really shouldn't be here but we can deal with this
1259 debugging("You should really redirect before you start page output");
1260 if (!$debugdisableredirect) {
1261 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1263 $output = $this->opencontainers->pop_all_but_last();
1264 break;
1265 case moodle_page::STATE_DONE :
1266 // Too late to be calling redirect now
1267 throw new coding_exception('You cannot redirect after the entire page has been generated');
1268 break;
1270 $output .= $this->notification($message, $messagetype);
1271 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1272 if ($debugdisableredirect) {
1273 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1275 $output .= $this->footer();
1276 return $output;
1280 * Start output by sending the HTTP headers, and printing the HTML <head>
1281 * and the start of the <body>.
1283 * To control what is printed, you should set properties on $PAGE.
1285 * @return string HTML that you must output this, preferably immediately.
1287 public function header() {
1288 global $USER, $CFG, $SESSION;
1290 // Give plugins an opportunity touch things before the http headers are sent
1291 // such as adding additional headers. The return value is ignored.
1292 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1293 foreach ($pluginswithfunction as $plugins) {
1294 foreach ($plugins as $function) {
1295 $function();
1299 if (\core\session\manager::is_loggedinas()) {
1300 $this->page->add_body_class('userloggedinas');
1303 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1304 require_once($CFG->dirroot . '/user/lib.php');
1305 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1306 if ($count = user_count_login_failures($USER, false)) {
1307 $this->page->add_body_class('loginfailures');
1311 // If the user is logged in, and we're not in initial install,
1312 // check to see if the user is role-switched and add the appropriate
1313 // CSS class to the body element.
1314 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1315 $this->page->add_body_class('userswitchedrole');
1318 // Give themes a chance to init/alter the page object.
1319 $this->page->theme->init_page($this->page);
1321 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1323 // Find the appropriate page layout file, based on $this->page->pagelayout.
1324 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1325 // Render the layout using the layout file.
1326 $rendered = $this->render_page_layout($layoutfile);
1328 // Slice the rendered output into header and footer.
1329 $cutpos = strpos($rendered, $this->unique_main_content_token);
1330 if ($cutpos === false) {
1331 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1332 $token = self::MAIN_CONTENT_TOKEN;
1333 } else {
1334 $token = $this->unique_main_content_token;
1337 if ($cutpos === false) {
1338 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.');
1340 $header = substr($rendered, 0, $cutpos);
1341 $footer = substr($rendered, $cutpos + strlen($token));
1343 if (empty($this->contenttype)) {
1344 debugging('The page layout file did not call $OUTPUT->doctype()');
1345 $header = $this->doctype() . $header;
1348 // If this theme version is below 2.4 release and this is a course view page
1349 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1350 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1351 // check if course content header/footer have not been output during render of theme layout
1352 $coursecontentheader = $this->course_content_header(true);
1353 $coursecontentfooter = $this->course_content_footer(true);
1354 if (!empty($coursecontentheader)) {
1355 // display debug message and add header and footer right above and below main content
1356 // Please note that course header and footer (to be displayed above and below the whole page)
1357 // are not displayed in this case at all.
1358 // Besides the content header and footer are not displayed on any other course page
1359 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);
1360 $header .= $coursecontentheader;
1361 $footer = $coursecontentfooter. $footer;
1365 send_headers($this->contenttype, $this->page->cacheable);
1367 $this->opencontainers->push('header/footer', $footer);
1368 $this->page->set_state(moodle_page::STATE_IN_BODY);
1370 return $header . $this->skip_link_target('maincontent');
1374 * Renders and outputs the page layout file.
1376 * This is done by preparing the normal globals available to a script, and
1377 * then including the layout file provided by the current theme for the
1378 * requested layout.
1380 * @param string $layoutfile The name of the layout file
1381 * @return string HTML code
1383 protected function render_page_layout($layoutfile) {
1384 global $CFG, $SITE, $USER;
1385 // The next lines are a bit tricky. The point is, here we are in a method
1386 // of a renderer class, and this object may, or may not, be the same as
1387 // the global $OUTPUT object. When rendering the page layout file, we want to use
1388 // this object. However, people writing Moodle code expect the current
1389 // renderer to be called $OUTPUT, not $this, so define a variable called
1390 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1391 $OUTPUT = $this;
1392 $PAGE = $this->page;
1393 $COURSE = $this->page->course;
1395 ob_start();
1396 include($layoutfile);
1397 $rendered = ob_get_contents();
1398 ob_end_clean();
1399 return $rendered;
1403 * Outputs the page's footer
1405 * @return string HTML fragment
1407 public function footer() {
1408 global $CFG, $DB;
1410 $output = '';
1412 // Give plugins an opportunity to touch the page before JS is finalized.
1413 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1414 foreach ($pluginswithfunction as $plugins) {
1415 foreach ($plugins as $function) {
1416 $extrafooter = $function();
1417 if (is_string($extrafooter)) {
1418 $output .= $extrafooter;
1423 $output .= $this->container_end_all(true);
1425 $footer = $this->opencontainers->pop('header/footer');
1427 if (debugging() and $DB and $DB->is_transaction_started()) {
1428 // TODO: MDL-20625 print warning - transaction will be rolled back
1431 // Provide some performance info if required
1432 $performanceinfo = '';
1433 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1434 $perf = get_performance_info();
1435 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1436 $performanceinfo = $perf['html'];
1440 // We always want performance data when running a performance test, even if the user is redirected to another page.
1441 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1442 $footer = $this->unique_performance_info_token . $footer;
1444 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1446 // Only show notifications when the current page has a context id.
1447 if (!empty($this->page->context->id)) {
1448 $this->page->requires->js_call_amd('core/notification', 'init', array(
1449 $this->page->context->id,
1450 \core\notification::fetch_as_array($this)
1453 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1455 $this->page->set_state(moodle_page::STATE_DONE);
1457 return $output . $footer;
1461 * Close all but the last open container. This is useful in places like error
1462 * handling, where you want to close all the open containers (apart from <body>)
1463 * before outputting the error message.
1465 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1466 * developer debug warning if it isn't.
1467 * @return string the HTML required to close any open containers inside <body>.
1469 public function container_end_all($shouldbenone = false) {
1470 return $this->opencontainers->pop_all_but_last($shouldbenone);
1474 * Returns course-specific information to be output immediately above content on any course page
1475 * (for the current course)
1477 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1478 * @return string
1480 public function course_content_header($onlyifnotcalledbefore = false) {
1481 global $CFG;
1482 static $functioncalled = false;
1483 if ($functioncalled && $onlyifnotcalledbefore) {
1484 // we have already output the content header
1485 return '';
1488 // Output any session notification.
1489 $notifications = \core\notification::fetch();
1491 $bodynotifications = '';
1492 foreach ($notifications as $notification) {
1493 $bodynotifications .= $this->render_from_template(
1494 $notification->get_template_name(),
1495 $notification->export_for_template($this)
1499 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1501 if ($this->page->course->id == SITEID) {
1502 // return immediately and do not include /course/lib.php if not necessary
1503 return $output;
1506 require_once($CFG->dirroot.'/course/lib.php');
1507 $functioncalled = true;
1508 $courseformat = course_get_format($this->page->course);
1509 if (($obj = $courseformat->course_content_header()) !== null) {
1510 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1512 return $output;
1516 * Returns course-specific information to be output immediately below content on any course page
1517 * (for the current course)
1519 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1520 * @return string
1522 public function course_content_footer($onlyifnotcalledbefore = false) {
1523 global $CFG;
1524 if ($this->page->course->id == SITEID) {
1525 // return immediately and do not include /course/lib.php if not necessary
1526 return '';
1528 static $functioncalled = false;
1529 if ($functioncalled && $onlyifnotcalledbefore) {
1530 // we have already output the content footer
1531 return '';
1533 $functioncalled = true;
1534 require_once($CFG->dirroot.'/course/lib.php');
1535 $courseformat = course_get_format($this->page->course);
1536 if (($obj = $courseformat->course_content_footer()) !== null) {
1537 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1539 return '';
1543 * Returns course-specific information to be output on any course page in the header area
1544 * (for the current course)
1546 * @return string
1548 public function course_header() {
1549 global $CFG;
1550 if ($this->page->course->id == SITEID) {
1551 // return immediately and do not include /course/lib.php if not necessary
1552 return '';
1554 require_once($CFG->dirroot.'/course/lib.php');
1555 $courseformat = course_get_format($this->page->course);
1556 if (($obj = $courseformat->course_header()) !== null) {
1557 return $courseformat->get_renderer($this->page)->render($obj);
1559 return '';
1563 * Returns course-specific information to be output on any course page in the footer area
1564 * (for the current course)
1566 * @return string
1568 public function course_footer() {
1569 global $CFG;
1570 if ($this->page->course->id == SITEID) {
1571 // return immediately and do not include /course/lib.php if not necessary
1572 return '';
1574 require_once($CFG->dirroot.'/course/lib.php');
1575 $courseformat = course_get_format($this->page->course);
1576 if (($obj = $courseformat->course_footer()) !== null) {
1577 return $courseformat->get_renderer($this->page)->render($obj);
1579 return '';
1583 * Get the course pattern datauri to show on a course card.
1585 * The datauri is an encoded svg that can be passed as a url.
1586 * @param int $id Id to use when generating the pattern
1587 * @return string datauri
1589 public function get_generated_image_for_id($id) {
1590 $color = $this->get_generated_color_for_id($id);
1591 $pattern = new \core_geopattern();
1592 $pattern->setColor($color);
1593 $pattern->patternbyid($id);
1594 return $pattern->datauri();
1598 * Get the course color to show on a course card.
1600 * @param int $id Id to use when generating the color.
1601 * @return string hex color code.
1603 public function get_generated_color_for_id($id) {
1604 $colornumbers = range(1, 10);
1605 $basecolors = [];
1606 foreach ($colornumbers as $number) {
1607 $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1610 $color = $basecolors[$id % 10];
1611 return $color;
1615 * Returns lang menu or '', this method also checks forcing of languages in courses.
1617 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1619 * @return string The lang menu HTML or empty string
1621 public function lang_menu() {
1622 global $CFG;
1624 if (empty($CFG->langmenu)) {
1625 return '';
1628 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1629 // do not show lang menu if language forced
1630 return '';
1633 $currlang = current_language();
1634 $langs = get_string_manager()->get_list_of_translations();
1636 if (count($langs) < 2) {
1637 return '';
1640 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1641 $s->label = get_accesshide(get_string('language'));
1642 $s->class = 'langmenu';
1643 return $this->render($s);
1647 * Output the row of editing icons for a block, as defined by the controls array.
1649 * @param array $controls an array like {@link block_contents::$controls}.
1650 * @param string $blockid The ID given to the block.
1651 * @return string HTML fragment.
1653 public function block_controls($actions, $blockid = null) {
1654 global $CFG;
1655 if (empty($actions)) {
1656 return '';
1658 $menu = new action_menu($actions);
1659 if ($blockid !== null) {
1660 $menu->set_owner_selector('#'.$blockid);
1662 $menu->set_constraint('.block-region');
1663 $menu->attributes['class'] .= ' block-control-actions commands';
1664 return $this->render($menu);
1668 * Returns the HTML for a basic textarea field.
1670 * @param string $name Name to use for the textarea element
1671 * @param string $id The id to use fort he textarea element
1672 * @param string $value Initial content to display in the textarea
1673 * @param int $rows Number of rows to display
1674 * @param int $cols Number of columns to display
1675 * @return string the HTML to display
1677 public function print_textarea($name, $id, $value, $rows, $cols) {
1678 editors_head_setup();
1679 $editor = editors_get_preferred_editor(FORMAT_HTML);
1680 $editor->set_text($value);
1681 $editor->use_editor($id, []);
1683 $context = [
1684 'id' => $id,
1685 'name' => $name,
1686 'value' => $value,
1687 'rows' => $rows,
1688 'cols' => $cols
1691 return $this->render_from_template('core_form/editor_textarea', $context);
1695 * Renders an action menu component.
1697 * @param action_menu $menu
1698 * @return string HTML
1700 public function render_action_menu(action_menu $menu) {
1702 // We don't want the class icon there!
1703 foreach ($menu->get_secondary_actions() as $action) {
1704 if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1705 $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1709 if ($menu->is_empty()) {
1710 return '';
1712 $context = $menu->export_for_template($this);
1714 return $this->render_from_template('core/action_menu', $context);
1718 * Renders a Check API result
1720 * @param result $result
1721 * @return string HTML fragment
1723 protected function render_check_result(core\check\result $result) {
1724 return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1728 * Renders a Check API result
1730 * @param result $result
1731 * @return string HTML fragment
1733 public function check_result(core\check\result $result) {
1734 return $this->render_check_result($result);
1738 * Renders an action_menu_link item.
1740 * @param action_menu_link $action
1741 * @return string HTML fragment
1743 protected function render_action_menu_link(action_menu_link $action) {
1744 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1748 * Renders a primary action_menu_filler item.
1750 * @param action_menu_link_filler $action
1751 * @return string HTML fragment
1753 protected function render_action_menu_filler(action_menu_filler $action) {
1754 return html_writer::span('&nbsp;', 'filler');
1758 * Renders a primary action_menu_link item.
1760 * @param action_menu_link_primary $action
1761 * @return string HTML fragment
1763 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1764 return $this->render_action_menu_link($action);
1768 * Renders a secondary action_menu_link item.
1770 * @param action_menu_link_secondary $action
1771 * @return string HTML fragment
1773 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1774 return $this->render_action_menu_link($action);
1778 * Prints a nice side block with an optional header.
1780 * @param block_contents $bc HTML for the content
1781 * @param string $region the region the block is appearing in.
1782 * @return string the HTML to be output.
1784 public function block(block_contents $bc, $region) {
1785 $bc = clone($bc); // Avoid messing up the object passed in.
1786 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1787 $bc->collapsible = block_contents::NOT_HIDEABLE;
1790 $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1791 $context = new stdClass();
1792 $context->skipid = $bc->skipid;
1793 $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
1794 $context->dockable = $bc->dockable;
1795 $context->id = $id;
1796 $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1797 $context->skiptitle = strip_tags($bc->title);
1798 $context->showskiplink = !empty($context->skiptitle);
1799 $context->arialabel = $bc->arialabel;
1800 $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
1801 $context->class = $bc->attributes['class'];
1802 $context->type = $bc->attributes['data-block'];
1803 $context->title = $bc->title;
1804 $context->content = $bc->content;
1805 $context->annotation = $bc->annotation;
1806 $context->footer = $bc->footer;
1807 $context->hascontrols = !empty($bc->controls);
1808 if ($context->hascontrols) {
1809 $context->controls = $this->block_controls($bc->controls, $id);
1812 return $this->render_from_template('core/block', $context);
1816 * Render the contents of a block_list.
1818 * @param array $icons the icon for each item.
1819 * @param array $items the content of each item.
1820 * @return string HTML
1822 public function list_block_contents($icons, $items) {
1823 $row = 0;
1824 $lis = array();
1825 foreach ($items as $key => $string) {
1826 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1827 if (!empty($icons[$key])) { //test if the content has an assigned icon
1828 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1830 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1831 $item .= html_writer::end_tag('li');
1832 $lis[] = $item;
1833 $row = 1 - $row; // Flip even/odd.
1835 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1839 * Output all the blocks in a particular region.
1841 * @param string $region the name of a region on this page.
1842 * @param boolean $fakeblocksonly Output fake block only.
1843 * @return string the HTML to be output.
1845 public function blocks_for_region($region, $fakeblocksonly = false) {
1846 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1847 $lastblock = null;
1848 $zones = array();
1849 foreach ($blockcontents as $bc) {
1850 if ($bc instanceof block_contents) {
1851 $zones[] = $bc->title;
1854 $output = '';
1856 foreach ($blockcontents as $bc) {
1857 if ($bc instanceof block_contents) {
1858 if ($fakeblocksonly && !$bc->is_fake()) {
1859 // Skip rendering real blocks if we only want to show fake blocks.
1860 continue;
1862 $output .= $this->block($bc, $region);
1863 $lastblock = $bc->title;
1864 } else if ($bc instanceof block_move_target) {
1865 if (!$fakeblocksonly) {
1866 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1868 } else {
1869 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1872 return $output;
1876 * Output a place where the block that is currently being moved can be dropped.
1878 * @param block_move_target $target with the necessary details.
1879 * @param array $zones array of areas where the block can be moved to
1880 * @param string $previous the block located before the area currently being rendered.
1881 * @param string $region the name of the region
1882 * @return string the HTML to be output.
1884 public function block_move_target($target, $zones, $previous, $region) {
1885 if ($previous == null) {
1886 if (empty($zones)) {
1887 // There are no zones, probably because there are no blocks.
1888 $regions = $this->page->theme->get_all_block_regions();
1889 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1890 } else {
1891 $position = get_string('moveblockbefore', 'block', $zones[0]);
1893 } else {
1894 $position = get_string('moveblockafter', 'block', $previous);
1896 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1900 * Renders a special html link with attached action
1902 * Theme developers: DO NOT OVERRIDE! Please override function
1903 * {@link core_renderer::render_action_link()} instead.
1905 * @param string|moodle_url $url
1906 * @param string $text HTML fragment
1907 * @param component_action $action
1908 * @param array $attributes associative array of html link attributes + disabled
1909 * @param pix_icon optional pix icon to render with the link
1910 * @return string HTML fragment
1912 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1913 if (!($url instanceof moodle_url)) {
1914 $url = new moodle_url($url);
1916 $link = new action_link($url, $text, $action, $attributes, $icon);
1918 return $this->render($link);
1922 * Renders an action_link object.
1924 * The provided link is renderer and the HTML returned. At the same time the
1925 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1927 * @param action_link $link
1928 * @return string HTML fragment
1930 protected function render_action_link(action_link $link) {
1931 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1935 * Renders an action_icon.
1937 * This function uses the {@link core_renderer::action_link()} method for the
1938 * most part. What it does different is prepare the icon as HTML and use it
1939 * as the link text.
1941 * Theme developers: If you want to change how action links and/or icons are rendered,
1942 * consider overriding function {@link core_renderer::render_action_link()} and
1943 * {@link core_renderer::render_pix_icon()}.
1945 * @param string|moodle_url $url A string URL or moodel_url
1946 * @param pix_icon $pixicon
1947 * @param component_action $action
1948 * @param array $attributes associative array of html link attributes + disabled
1949 * @param bool $linktext show title next to image in link
1950 * @return string HTML fragment
1952 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1953 if (!($url instanceof moodle_url)) {
1954 $url = new moodle_url($url);
1956 $attributes = (array)$attributes;
1958 if (empty($attributes['class'])) {
1959 // let ppl override the class via $options
1960 $attributes['class'] = 'action-icon';
1963 $icon = $this->render($pixicon);
1965 if ($linktext) {
1966 $text = $pixicon->attributes['alt'];
1967 } else {
1968 $text = '';
1971 return $this->action_link($url, $text.$icon, $action, $attributes);
1975 * Print a message along with button choices for Continue/Cancel
1977 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1979 * @param string $message The question to ask the user
1980 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1981 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1982 * @return string HTML fragment
1984 public function confirm($message, $continue, $cancel) {
1985 if ($continue instanceof single_button) {
1986 // ok
1987 $continue->primary = true;
1988 } else if (is_string($continue)) {
1989 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1990 } else if ($continue instanceof moodle_url) {
1991 $continue = new single_button($continue, get_string('continue'), 'post', true);
1992 } else {
1993 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1996 if ($cancel instanceof single_button) {
1997 // ok
1998 } else if (is_string($cancel)) {
1999 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
2000 } else if ($cancel instanceof moodle_url) {
2001 $cancel = new single_button($cancel, get_string('cancel'), 'get');
2002 } else {
2003 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2006 $attributes = [
2007 'role'=>'alertdialog',
2008 'aria-labelledby'=>'modal-header',
2009 'aria-describedby'=>'modal-body',
2010 'aria-modal'=>'true'
2013 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
2014 $output .= $this->box_start('modal-content', 'modal-content');
2015 $output .= $this->box_start('modal-header px-3', 'modal-header');
2016 $output .= html_writer::tag('h4', get_string('confirm'));
2017 $output .= $this->box_end();
2018 $attributes = [
2019 'role'=>'alert',
2020 'data-aria-autofocus'=>'true'
2022 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
2023 $output .= html_writer::tag('p', $message);
2024 $output .= $this->box_end();
2025 $output .= $this->box_start('modal-footer', 'modal-footer');
2026 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
2027 $output .= $this->box_end();
2028 $output .= $this->box_end();
2029 $output .= $this->box_end();
2030 return $output;
2034 * Returns a form with a single button.
2036 * Theme developers: DO NOT OVERRIDE! Please override function
2037 * {@link core_renderer::render_single_button()} instead.
2039 * @param string|moodle_url $url
2040 * @param string $label button text
2041 * @param string $method get or post submit method
2042 * @param array $options associative array {disabled, title, etc.}
2043 * @return string HTML fragment
2045 public function single_button($url, $label, $method='post', array $options=null) {
2046 if (!($url instanceof moodle_url)) {
2047 $url = new moodle_url($url);
2049 $button = new single_button($url, $label, $method);
2051 foreach ((array)$options as $key=>$value) {
2052 if (property_exists($button, $key)) {
2053 $button->$key = $value;
2054 } else {
2055 $button->set_attribute($key, $value);
2059 return $this->render($button);
2063 * Renders a single button widget.
2065 * This will return HTML to display a form containing a single button.
2067 * @param single_button $button
2068 * @return string HTML fragment
2070 protected function render_single_button(single_button $button) {
2071 return $this->render_from_template('core/single_button', $button->export_for_template($this));
2075 * Returns a form with a single select widget.
2077 * Theme developers: DO NOT OVERRIDE! Please override function
2078 * {@link core_renderer::render_single_select()} instead.
2080 * @param moodle_url $url form action target, includes hidden fields
2081 * @param string $name name of selection field - the changing parameter in url
2082 * @param array $options list of options
2083 * @param string $selected selected element
2084 * @param array $nothing
2085 * @param string $formid
2086 * @param array $attributes other attributes for the single select
2087 * @return string HTML fragment
2089 public function single_select($url, $name, array $options, $selected = '',
2090 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2091 if (!($url instanceof moodle_url)) {
2092 $url = new moodle_url($url);
2094 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2096 if (array_key_exists('label', $attributes)) {
2097 $select->set_label($attributes['label']);
2098 unset($attributes['label']);
2100 $select->attributes = $attributes;
2102 return $this->render($select);
2106 * Returns a dataformat selection and download form
2108 * @param string $label A text label
2109 * @param moodle_url|string $base The download page url
2110 * @param string $name The query param which will hold the type of the download
2111 * @param array $params Extra params sent to the download page
2112 * @return string HTML fragment
2114 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2116 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2117 $options = array();
2118 foreach ($formats as $format) {
2119 if ($format->is_enabled()) {
2120 $options[] = array(
2121 'value' => $format->name,
2122 'label' => get_string('dataformat', $format->component),
2126 $hiddenparams = array();
2127 foreach ($params as $key => $value) {
2128 $hiddenparams[] = array(
2129 'name' => $key,
2130 'value' => $value,
2133 $data = array(
2134 'label' => $label,
2135 'base' => $base,
2136 'name' => $name,
2137 'params' => $hiddenparams,
2138 'options' => $options,
2139 'sesskey' => sesskey(),
2140 'submit' => get_string('download'),
2143 return $this->render_from_template('core/dataformat_selector', $data);
2148 * Internal implementation of single_select rendering
2150 * @param single_select $select
2151 * @return string HTML fragment
2153 protected function render_single_select(single_select $select) {
2154 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2158 * Returns a form with a url select widget.
2160 * Theme developers: DO NOT OVERRIDE! Please override function
2161 * {@link core_renderer::render_url_select()} instead.
2163 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2164 * @param string $selected selected element
2165 * @param array $nothing
2166 * @param string $formid
2167 * @return string HTML fragment
2169 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2170 $select = new url_select($urls, $selected, $nothing, $formid);
2171 return $this->render($select);
2175 * Internal implementation of url_select rendering
2177 * @param url_select $select
2178 * @return string HTML fragment
2180 protected function render_url_select(url_select $select) {
2181 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2185 * Returns a string containing a link to the user documentation.
2186 * Also contains an icon by default. Shown to teachers and admin only.
2188 * @param string $path The page link after doc root and language, no leading slash.
2189 * @param string $text The text to be displayed for the link
2190 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2191 * @param array $attributes htm attributes
2192 * @return string
2194 public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
2195 global $CFG;
2197 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2199 $attributes['href'] = new moodle_url(get_docs_url($path));
2200 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2201 $attributes['class'] = 'helplinkpopup';
2204 return html_writer::tag('a', $icon.$text, $attributes);
2208 * Return HTML for an image_icon.
2210 * Theme developers: DO NOT OVERRIDE! Please override function
2211 * {@link core_renderer::render_image_icon()} instead.
2213 * @param string $pix short pix name
2214 * @param string $alt mandatory alt attribute
2215 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2216 * @param array $attributes htm attributes
2217 * @return string HTML fragment
2219 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2220 $icon = new image_icon($pix, $alt, $component, $attributes);
2221 return $this->render($icon);
2225 * Renders a pix_icon widget and returns the HTML to display it.
2227 * @param image_icon $icon
2228 * @return string HTML fragment
2230 protected function render_image_icon(image_icon $icon) {
2231 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2232 return $system->render_pix_icon($this, $icon);
2236 * Return HTML for a pix_icon.
2238 * Theme developers: DO NOT OVERRIDE! Please override function
2239 * {@link core_renderer::render_pix_icon()} instead.
2241 * @param string $pix short pix name
2242 * @param string $alt mandatory alt attribute
2243 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2244 * @param array $attributes htm lattributes
2245 * @return string HTML fragment
2247 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2248 $icon = new pix_icon($pix, $alt, $component, $attributes);
2249 return $this->render($icon);
2253 * Renders a pix_icon widget and returns the HTML to display it.
2255 * @param pix_icon $icon
2256 * @return string HTML fragment
2258 protected function render_pix_icon(pix_icon $icon) {
2259 $system = \core\output\icon_system::instance();
2260 return $system->render_pix_icon($this, $icon);
2264 * Return HTML to display an emoticon icon.
2266 * @param pix_emoticon $emoticon
2267 * @return string HTML fragment
2269 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2270 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2271 return $system->render_pix_icon($this, $emoticon);
2275 * Produces the html that represents this rating in the UI
2277 * @param rating $rating the page object on which this rating will appear
2278 * @return string
2280 function render_rating(rating $rating) {
2281 global $CFG, $USER;
2283 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2284 return null;//ratings are turned off
2287 $ratingmanager = new rating_manager();
2288 // Initialise the JavaScript so ratings can be done by AJAX.
2289 $ratingmanager->initialise_rating_javascript($this->page);
2291 $strrate = get_string("rate", "rating");
2292 $ratinghtml = ''; //the string we'll return
2294 // permissions check - can they view the aggregate?
2295 if ($rating->user_can_view_aggregate()) {
2297 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2298 $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2299 $aggregatestr = $rating->get_aggregate_string();
2301 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2302 if ($rating->count > 0) {
2303 $countstr = "({$rating->count})";
2304 } else {
2305 $countstr = '-';
2307 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2309 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2311 $nonpopuplink = $rating->get_view_ratings_url();
2312 $popuplink = $rating->get_view_ratings_url(true);
2314 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2315 $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
2318 $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
2321 $formstart = null;
2322 // if the item doesn't belong to the current user, the user has permission to rate
2323 // and we're within the assessable period
2324 if ($rating->user_can_rate()) {
2326 $rateurl = $rating->get_rate_url();
2327 $inputs = $rateurl->params();
2329 //start the rating form
2330 $formattrs = array(
2331 'id' => "postrating{$rating->itemid}",
2332 'class' => 'postratingform',
2333 'method' => 'post',
2334 'action' => $rateurl->out_omit_querystring()
2336 $formstart = html_writer::start_tag('form', $formattrs);
2337 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2339 // add the hidden inputs
2340 foreach ($inputs as $name => $value) {
2341 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2342 $formstart .= html_writer::empty_tag('input', $attributes);
2345 if (empty($ratinghtml)) {
2346 $ratinghtml .= $strrate.': ';
2348 $ratinghtml = $formstart.$ratinghtml;
2350 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2351 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2352 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2353 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2355 //output submit button
2356 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2358 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2359 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2361 if (!$rating->settings->scale->isnumeric) {
2362 // If a global scale, try to find current course ID from the context
2363 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2364 $courseid = $coursecontext->instanceid;
2365 } else {
2366 $courseid = $rating->settings->scale->courseid;
2368 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2370 $ratinghtml .= html_writer::end_tag('span');
2371 $ratinghtml .= html_writer::end_tag('div');
2372 $ratinghtml .= html_writer::end_tag('form');
2375 return $ratinghtml;
2379 * Centered heading with attached help button (same title text)
2380 * and optional icon attached.
2382 * @param string $text A heading text
2383 * @param string $helpidentifier The keyword that defines a help page
2384 * @param string $component component name
2385 * @param string|moodle_url $icon
2386 * @param string $iconalt icon alt text
2387 * @param int $level The level of importance of the heading. Defaulting to 2
2388 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2389 * @return string HTML fragment
2391 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2392 $image = '';
2393 if ($icon) {
2394 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2397 $help = '';
2398 if ($helpidentifier) {
2399 $help = $this->help_icon($helpidentifier, $component);
2402 return $this->heading($image.$text.$help, $level, $classnames);
2406 * Returns HTML to display a help icon.
2408 * @deprecated since Moodle 2.0
2410 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2411 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2415 * Returns HTML to display a help icon.
2417 * Theme developers: DO NOT OVERRIDE! Please override function
2418 * {@link core_renderer::render_help_icon()} instead.
2420 * @param string $identifier The keyword that defines a help page
2421 * @param string $component component name
2422 * @param string|bool $linktext true means use $title as link text, string means link text value
2423 * @return string HTML fragment
2425 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2426 $icon = new help_icon($identifier, $component);
2427 $icon->diag_strings();
2428 if ($linktext === true) {
2429 $icon->linktext = get_string($icon->identifier, $icon->component);
2430 } else if (!empty($linktext)) {
2431 $icon->linktext = $linktext;
2433 return $this->render($icon);
2437 * Implementation of user image rendering.
2439 * @param help_icon $helpicon A help icon instance
2440 * @return string HTML fragment
2442 protected function render_help_icon(help_icon $helpicon) {
2443 $context = $helpicon->export_for_template($this);
2444 return $this->render_from_template('core/help_icon', $context);
2448 * Returns HTML to display a scale help icon.
2450 * @param int $courseid
2451 * @param stdClass $scale instance
2452 * @return string HTML fragment
2454 public function help_icon_scale($courseid, stdClass $scale) {
2455 global $CFG;
2457 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2459 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2461 $scaleid = abs($scale->id);
2463 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2464 $action = new popup_action('click', $link, 'ratingscale');
2466 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2470 * Creates and returns a spacer image with optional line break.
2472 * @param array $attributes Any HTML attributes to add to the spaced.
2473 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2474 * laxy do it with CSS which is a much better solution.
2475 * @return string HTML fragment
2477 public function spacer(array $attributes = null, $br = false) {
2478 $attributes = (array)$attributes;
2479 if (empty($attributes['width'])) {
2480 $attributes['width'] = 1;
2482 if (empty($attributes['height'])) {
2483 $attributes['height'] = 1;
2485 $attributes['class'] = 'spacer';
2487 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2489 if (!empty($br)) {
2490 $output .= '<br />';
2493 return $output;
2497 * Returns HTML to display the specified user's avatar.
2499 * User avatar may be obtained in two ways:
2500 * <pre>
2501 * // Option 1: (shortcut for simple cases, preferred way)
2502 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2503 * $OUTPUT->user_picture($user, array('popup'=>true));
2505 * // Option 2:
2506 * $userpic = new user_picture($user);
2507 * // Set properties of $userpic
2508 * $userpic->popup = true;
2509 * $OUTPUT->render($userpic);
2510 * </pre>
2512 * Theme developers: DO NOT OVERRIDE! Please override function
2513 * {@link core_renderer::render_user_picture()} instead.
2515 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2516 * If any of these are missing, the database is queried. Avoid this
2517 * if at all possible, particularly for reports. It is very bad for performance.
2518 * @param array $options associative array with user picture options, used only if not a user_picture object,
2519 * options are:
2520 * - courseid=$this->page->course->id (course id of user profile in link)
2521 * - size=35 (size of image)
2522 * - link=true (make image clickable - the link leads to user profile)
2523 * - popup=false (open in popup)
2524 * - alttext=true (add image alt attribute)
2525 * - class = image class attribute (default 'userpicture')
2526 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2527 * - includefullname=false (whether to include the user's full name together with the user picture)
2528 * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2529 * @return string HTML fragment
2531 public function user_picture(stdClass $user, array $options = null) {
2532 $userpicture = new user_picture($user);
2533 foreach ((array)$options as $key=>$value) {
2534 if (property_exists($userpicture, $key)) {
2535 $userpicture->$key = $value;
2538 return $this->render($userpicture);
2542 * Internal implementation of user image rendering.
2544 * @param user_picture $userpicture
2545 * @return string
2547 protected function render_user_picture(user_picture $userpicture) {
2548 $user = $userpicture->user;
2549 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
2551 $alt = '';
2552 if ($userpicture->alttext) {
2553 if (!empty($user->imagealt)) {
2554 $alt = $user->imagealt;
2558 if (empty($userpicture->size)) {
2559 $size = 35;
2560 } else if ($userpicture->size === true or $userpicture->size == 1) {
2561 $size = 100;
2562 } else {
2563 $size = $userpicture->size;
2566 $class = $userpicture->class;
2568 if ($user->picture == 0) {
2569 $class .= ' defaultuserpic';
2572 $src = $userpicture->get_url($this->page, $this);
2574 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2575 if (!$userpicture->visibletoscreenreaders) {
2576 $alt = '';
2578 $attributes['alt'] = $alt;
2580 if (!empty($alt)) {
2581 $attributes['title'] = $alt;
2584 // get the image html output fisrt
2585 $output = html_writer::empty_tag('img', $attributes);
2587 // Show fullname together with the picture when desired.
2588 if ($userpicture->includefullname) {
2589 $output .= fullname($userpicture->user, $canviewfullnames);
2592 if (empty($userpicture->courseid)) {
2593 $courseid = $this->page->course->id;
2594 } else {
2595 $courseid = $userpicture->courseid;
2597 if ($courseid == SITEID) {
2598 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2599 } else {
2600 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2603 // Then wrap it in link if needed. Also we don't wrap it in link if the link redirects to itself.
2604 if (!$userpicture->link ||
2605 ($this->page->has_set_url() && $this->page->url == $url)) { // Protect against unset page->url.
2606 return $output;
2609 $attributes = array('href' => $url, 'class' => 'd-inline-block aabtn');
2610 if (!$userpicture->visibletoscreenreaders) {
2611 $attributes['tabindex'] = '-1';
2612 $attributes['aria-hidden'] = 'true';
2615 if ($userpicture->popup) {
2616 $id = html_writer::random_id('userpicture');
2617 $attributes['id'] = $id;
2618 $this->add_action_handler(new popup_action('click', $url), $id);
2621 return html_writer::tag('a', $output, $attributes);
2625 * Internal implementation of file tree viewer items rendering.
2627 * @param array $dir
2628 * @return string
2630 public function htmllize_file_tree($dir) {
2631 if (empty($dir['subdirs']) and empty($dir['files'])) {
2632 return '';
2634 $result = '<ul>';
2635 foreach ($dir['subdirs'] as $subdir) {
2636 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2638 foreach ($dir['files'] as $file) {
2639 $filename = $file->get_filename();
2640 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2642 $result .= '</ul>';
2644 return $result;
2648 * Returns HTML to display the file picker
2650 * <pre>
2651 * $OUTPUT->file_picker($options);
2652 * </pre>
2654 * Theme developers: DO NOT OVERRIDE! Please override function
2655 * {@link core_renderer::render_file_picker()} instead.
2657 * @param array $options associative array with file manager options
2658 * options are:
2659 * maxbytes=>-1,
2660 * itemid=>0,
2661 * client_id=>uniqid(),
2662 * acepted_types=>'*',
2663 * return_types=>FILE_INTERNAL,
2664 * context=>current page context
2665 * @return string HTML fragment
2667 public function file_picker($options) {
2668 $fp = new file_picker($options);
2669 return $this->render($fp);
2673 * Internal implementation of file picker rendering.
2675 * @param file_picker $fp
2676 * @return string
2678 public function render_file_picker(file_picker $fp) {
2679 $options = $fp->options;
2680 $client_id = $options->client_id;
2681 $strsaved = get_string('filesaved', 'repository');
2682 $straddfile = get_string('openpicker', 'repository');
2683 $strloading = get_string('loading', 'repository');
2684 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2685 $strdroptoupload = get_string('droptoupload', 'moodle');
2686 $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
2688 $currentfile = $options->currentfile;
2689 if (empty($currentfile)) {
2690 $currentfile = '';
2691 } else {
2692 $currentfile .= ' - ';
2694 if ($options->maxbytes) {
2695 $size = $options->maxbytes;
2696 } else {
2697 $size = get_max_upload_file_size();
2699 if ($size == -1) {
2700 $maxsize = '';
2701 } else {
2702 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2704 if ($options->buttonname) {
2705 $buttonname = ' name="' . $options->buttonname . '"';
2706 } else {
2707 $buttonname = '';
2709 $html = <<<EOD
2710 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2711 $iconprogress
2712 </div>
2713 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2714 <div>
2715 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2716 <span> $maxsize </span>
2717 </div>
2718 EOD;
2719 if ($options->env != 'url') {
2720 $html .= <<<EOD
2721 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2722 <div class="filepicker-filename">
2723 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2724 <div class="dndupload-progressbars"></div>
2725 </div>
2726 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2727 </div>
2728 EOD;
2730 $html .= '</div>';
2731 return $html;
2735 * @deprecated since Moodle 3.2
2737 public function update_module_button() {
2738 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2739 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2740 'Themes can choose to display the link in the buttons row consistently for all module types.');
2744 * Returns HTML to display a "Turn editing on/off" button in a form.
2746 * @param moodle_url $url The URL + params to send through when clicking the button
2747 * @return string HTML the button
2749 public function edit_button(moodle_url $url) {
2751 $url->param('sesskey', sesskey());
2752 if ($this->page->user_is_editing()) {
2753 $url->param('edit', 'off');
2754 $editstring = get_string('turneditingoff');
2755 } else {
2756 $url->param('edit', 'on');
2757 $editstring = get_string('turneditingon');
2760 return $this->single_button($url, $editstring);
2764 * Returns HTML to display a simple button to close a window
2766 * @param string $text The lang string for the button's label (already output from get_string())
2767 * @return string html fragment
2769 public function close_window_button($text='') {
2770 if (empty($text)) {
2771 $text = get_string('closewindow');
2773 $button = new single_button(new moodle_url('#'), $text, 'get');
2774 $button->add_action(new component_action('click', 'close_window'));
2776 return $this->container($this->render($button), 'closewindow');
2780 * Output an error message. By default wraps the error message in <span class="error">.
2781 * If the error message is blank, nothing is output.
2783 * @param string $message the error message.
2784 * @return string the HTML to output.
2786 public function error_text($message) {
2787 if (empty($message)) {
2788 return '';
2790 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2791 return html_writer::tag('span', $message, array('class' => 'error'));
2795 * Do not call this function directly.
2797 * To terminate the current script with a fatal error, call the {@link print_error}
2798 * function, or throw an exception. Doing either of those things will then call this
2799 * function to display the error, before terminating the execution.
2801 * @param string $message The message to output
2802 * @param string $moreinfourl URL where more info can be found about the error
2803 * @param string $link Link for the Continue button
2804 * @param array $backtrace The execution backtrace
2805 * @param string $debuginfo Debugging information
2806 * @return string the HTML to output.
2808 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2809 global $CFG;
2811 $output = '';
2812 $obbuffer = '';
2814 if ($this->has_started()) {
2815 // we can not always recover properly here, we have problems with output buffering,
2816 // html tables, etc.
2817 $output .= $this->opencontainers->pop_all_but_last();
2819 } else {
2820 // It is really bad if library code throws exception when output buffering is on,
2821 // because the buffered text would be printed before our start of page.
2822 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2823 error_reporting(0); // disable notices from gzip compression, etc.
2824 while (ob_get_level() > 0) {
2825 $buff = ob_get_clean();
2826 if ($buff === false) {
2827 break;
2829 $obbuffer .= $buff;
2831 error_reporting($CFG->debug);
2833 // Output not yet started.
2834 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2835 if (empty($_SERVER['HTTP_RANGE'])) {
2836 @header($protocol . ' 404 Not Found');
2837 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2838 // Coax iOS 10 into sending the session cookie.
2839 @header($protocol . ' 403 Forbidden');
2840 } else {
2841 // Must stop byteserving attempts somehow,
2842 // this is weird but Chrome PDF viewer can be stopped only with 407!
2843 @header($protocol . ' 407 Proxy Authentication Required');
2846 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2847 $this->page->set_url('/'); // no url
2848 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2849 $this->page->set_title(get_string('error'));
2850 $this->page->set_heading($this->page->course->fullname);
2851 $output .= $this->header();
2854 $message = '<p class="errormessage">' . s($message) . '</p>'.
2855 '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
2856 get_string('moreinformation') . '</a></p>';
2857 if (empty($CFG->rolesactive)) {
2858 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2859 //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.
2861 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2863 if ($CFG->debugdeveloper) {
2864 $labelsep = get_string('labelsep', 'langconfig');
2865 if (!empty($debuginfo)) {
2866 $debuginfo = s($debuginfo); // removes all nasty JS
2867 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2868 $label = get_string('debuginfo', 'debug') . $labelsep;
2869 $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
2871 if (!empty($backtrace)) {
2872 $label = get_string('stacktrace', 'debug') . $labelsep;
2873 $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
2875 if ($obbuffer !== '' ) {
2876 $label = get_string('outputbuffer', 'debug') . $labelsep;
2877 $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
2881 if (empty($CFG->rolesactive)) {
2882 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2883 } else if (!empty($link)) {
2884 $output .= $this->continue_button($link);
2887 $output .= $this->footer();
2889 // Padding to encourage IE to display our error page, rather than its own.
2890 $output .= str_repeat(' ', 512);
2892 return $output;
2896 * Output a notification (that is, a status message about something that has just happened).
2898 * Note: \core\notification::add() may be more suitable for your usage.
2900 * @param string $message The message to print out.
2901 * @param ?string $type The type of notification. See constants on \core\output\notification.
2902 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
2903 * @return string the HTML to output.
2905 public function notification($message, $type = null, $closebutton = true) {
2906 $typemappings = [
2907 // Valid types.
2908 'success' => \core\output\notification::NOTIFY_SUCCESS,
2909 'info' => \core\output\notification::NOTIFY_INFO,
2910 'warning' => \core\output\notification::NOTIFY_WARNING,
2911 'error' => \core\output\notification::NOTIFY_ERROR,
2913 // Legacy types mapped to current types.
2914 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2915 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2916 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2917 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2918 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2919 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2920 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2923 $extraclasses = [];
2925 if ($type) {
2926 if (strpos($type, ' ') === false) {
2927 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2928 if (isset($typemappings[$type])) {
2929 $type = $typemappings[$type];
2930 } else {
2931 // The value provided did not match a known type. It must be an extra class.
2932 $extraclasses = [$type];
2934 } else {
2935 // Identify what type of notification this is.
2936 $classarray = explode(' ', self::prepare_classes($type));
2938 // Separate out the type of notification from the extra classes.
2939 foreach ($classarray as $class) {
2940 if (isset($typemappings[$class])) {
2941 $type = $typemappings[$class];
2942 } else {
2943 $extraclasses[] = $class;
2949 $notification = new \core\output\notification($message, $type, $closebutton);
2950 if (count($extraclasses)) {
2951 $notification->set_extra_classes($extraclasses);
2954 // Return the rendered template.
2955 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2959 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2961 public function notify_problem() {
2962 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
2963 'please use \core\notification::add(), or \core\output\notification as required.');
2967 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2969 public function notify_success() {
2970 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
2971 'please use \core\notification::add(), or \core\output\notification as required.');
2975 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2977 public function notify_message() {
2978 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
2979 'please use \core\notification::add(), or \core\output\notification as required.');
2983 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2985 public function notify_redirect() {
2986 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
2987 'please use \core\notification::add(), or \core\output\notification as required.');
2991 * Render a notification (that is, a status message about something that has
2992 * just happened).
2994 * @param \core\output\notification $notification the notification to print out
2995 * @return string the HTML to output.
2997 protected function render_notification(\core\output\notification $notification) {
2998 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3002 * Returns HTML to display a continue button that goes to a particular URL.
3004 * @param string|moodle_url $url The url the button goes to.
3005 * @return string the HTML to output.
3007 public function continue_button($url) {
3008 if (!($url instanceof moodle_url)) {
3009 $url = new moodle_url($url);
3011 $button = new single_button($url, get_string('continue'), 'get', true);
3012 $button->class = 'continuebutton';
3014 return $this->render($button);
3018 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
3020 * Theme developers: DO NOT OVERRIDE! Please override function
3021 * {@link core_renderer::render_paging_bar()} instead.
3023 * @param int $totalcount The total number of entries available to be paged through
3024 * @param int $page The page you are currently viewing
3025 * @param int $perpage The number of entries that should be shown per page
3026 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3027 * @param string $pagevar name of page parameter that holds the page number
3028 * @return string the HTML to output.
3030 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3031 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3032 return $this->render($pb);
3036 * Returns HTML to display the paging bar.
3038 * @param paging_bar $pagingbar
3039 * @return string the HTML to output.
3041 protected function render_paging_bar(paging_bar $pagingbar) {
3042 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3043 $pagingbar->maxdisplay = 10;
3044 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3048 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3050 * @param string $current the currently selected letter.
3051 * @param string $class class name to add to this initial bar.
3052 * @param string $title the name to put in front of this initial bar.
3053 * @param string $urlvar URL parameter name for this initial.
3054 * @param string $url URL object.
3055 * @param array $alpha of letters in the alphabet.
3056 * @return string the HTML to output.
3058 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3059 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3060 return $this->render($ib);
3064 * Internal implementation of initials bar rendering.
3066 * @param initials_bar $initialsbar
3067 * @return string
3069 protected function render_initials_bar(initials_bar $initialsbar) {
3070 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3074 * Output the place a skip link goes to.
3076 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3077 * @return string the HTML to output.
3079 public function skip_link_target($id = null) {
3080 return html_writer::span('', '', array('id' => $id));
3084 * Outputs a heading
3086 * @param string $text The text of the heading
3087 * @param int $level The level of importance of the heading. Defaulting to 2
3088 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3089 * @param string $id An optional ID
3090 * @return string the HTML to output.
3092 public function heading($text, $level = 2, $classes = null, $id = null) {
3093 $level = (integer) $level;
3094 if ($level < 1 or $level > 6) {
3095 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3097 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3101 * Outputs a box.
3103 * @param string $contents The contents of the box
3104 * @param string $classes A space-separated list of CSS classes
3105 * @param string $id An optional ID
3106 * @param array $attributes An array of other attributes to give the box.
3107 * @return string the HTML to output.
3109 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3110 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3114 * Outputs the opening section of a box.
3116 * @param string $classes A space-separated list of CSS classes
3117 * @param string $id An optional ID
3118 * @param array $attributes An array of other attributes to give the box.
3119 * @return string the HTML to output.
3121 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3122 $this->opencontainers->push('box', html_writer::end_tag('div'));
3123 $attributes['id'] = $id;
3124 $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes);
3125 return html_writer::start_tag('div', $attributes);
3129 * Outputs the closing section of a box.
3131 * @return string the HTML to output.
3133 public function box_end() {
3134 return $this->opencontainers->pop('box');
3138 * Outputs a container.
3140 * @param string $contents The contents of the box
3141 * @param string $classes A space-separated list of CSS classes
3142 * @param string $id An optional ID
3143 * @return string the HTML to output.
3145 public function container($contents, $classes = null, $id = null) {
3146 return $this->container_start($classes, $id) . $contents . $this->container_end();
3150 * Outputs the opening section of a container.
3152 * @param string $classes A space-separated list of CSS classes
3153 * @param string $id An optional ID
3154 * @return string the HTML to output.
3156 public function container_start($classes = null, $id = null) {
3157 $this->opencontainers->push('container', html_writer::end_tag('div'));
3158 return html_writer::start_tag('div', array('id' => $id,
3159 'class' => renderer_base::prepare_classes($classes)));
3163 * Outputs the closing section of a container.
3165 * @return string the HTML to output.
3167 public function container_end() {
3168 return $this->opencontainers->pop('container');
3172 * Make nested HTML lists out of the items
3174 * The resulting list will look something like this:
3176 * <pre>
3177 * <<ul>>
3178 * <<li>><div class='tree_item parent'>(item contents)</div>
3179 * <<ul>
3180 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3181 * <</ul>>
3182 * <</li>>
3183 * <</ul>>
3184 * </pre>
3186 * @param array $items
3187 * @param array $attrs html attributes passed to the top ofs the list
3188 * @return string HTML
3190 public function tree_block_contents($items, $attrs = array()) {
3191 // exit if empty, we don't want an empty ul element
3192 if (empty($items)) {
3193 return '';
3195 // array of nested li elements
3196 $lis = array();
3197 foreach ($items as $item) {
3198 // this applies to the li item which contains all child lists too
3199 $content = $item->content($this);
3200 $liclasses = array($item->get_css_type());
3201 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3202 $liclasses[] = 'collapsed';
3204 if ($item->isactive === true) {
3205 $liclasses[] = 'current_branch';
3207 $liattr = array('class'=>join(' ',$liclasses));
3208 // class attribute on the div item which only contains the item content
3209 $divclasses = array('tree_item');
3210 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3211 $divclasses[] = 'branch';
3212 } else {
3213 $divclasses[] = 'leaf';
3215 if (!empty($item->classes) && count($item->classes)>0) {
3216 $divclasses[] = join(' ', $item->classes);
3218 $divattr = array('class'=>join(' ', $divclasses));
3219 if (!empty($item->id)) {
3220 $divattr['id'] = $item->id;
3222 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3223 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3224 $content = html_writer::empty_tag('hr') . $content;
3226 $content = html_writer::tag('li', $content, $liattr);
3227 $lis[] = $content;
3229 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3233 * Returns a search box.
3235 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3236 * @return string HTML with the search form hidden by default.
3238 public function search_box($id = false) {
3239 global $CFG;
3241 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3242 // result in an extra included file for each site, even the ones where global search
3243 // is disabled.
3244 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3245 return '';
3248 $data = [
3249 'action' => new moodle_url('/search/index.php'),
3250 'hiddenfields' => (object) ['name' => 'context', 'value' => $this->page->context->id],
3251 'inputname' => 'q',
3252 'searchstring' => get_string('search'),
3254 return $this->render_from_template('core/search_input_navbar', $data);
3258 * Allow plugins to provide some content to be rendered in the navbar.
3259 * The plugin must define a PLUGIN_render_navbar_output function that returns
3260 * the HTML they wish to add to the navbar.
3262 * @return string HTML for the navbar
3264 public function navbar_plugin_output() {
3265 $output = '';
3267 // Give subsystems an opportunity to inject extra html content. The callback
3268 // must always return a string containing valid html.
3269 foreach (\core_component::get_core_subsystems() as $name => $path) {
3270 if ($path) {
3271 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3275 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3276 foreach ($pluginsfunction as $plugintype => $plugins) {
3277 foreach ($plugins as $pluginfunction) {
3278 $output .= $pluginfunction($this);
3283 return $output;
3287 * Construct a user menu, returning HTML that can be echoed out by a
3288 * layout file.
3290 * @param stdClass $user A user object, usually $USER.
3291 * @param bool $withlinks true if a dropdown should be built.
3292 * @return string HTML fragment.
3294 public function user_menu($user = null, $withlinks = null) {
3295 global $USER, $CFG;
3296 require_once($CFG->dirroot . '/user/lib.php');
3298 if (is_null($user)) {
3299 $user = $USER;
3302 // Note: this behaviour is intended to match that of core_renderer::login_info,
3303 // but should not be considered to be good practice; layout options are
3304 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3305 if (is_null($withlinks)) {
3306 $withlinks = empty($this->page->layout_options['nologinlinks']);
3309 // Add a class for when $withlinks is false.
3310 $usermenuclasses = 'usermenu';
3311 if (!$withlinks) {
3312 $usermenuclasses .= ' withoutlinks';
3315 $returnstr = "";
3317 // If during initial install, return the empty return string.
3318 if (during_initial_install()) {
3319 return $returnstr;
3322 $loginpage = $this->is_login_page();
3323 $loginurl = get_login_url();
3325 // Get some navigation opts.
3326 $opts = user_get_user_navigation_info($user, $this->page);
3328 if (!empty($opts->unauthenticateduser)) {
3329 $returnstr = get_string($opts->unauthenticateduser['content'], 'moodle');
3330 // If not logged in, show the typical not-logged-in string.
3331 if (!$loginpage && (!$opts->unauthenticateduser['guest'] || $withlinks)) {
3332 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3335 return html_writer::div(
3336 html_writer::span(
3337 $returnstr,
3338 'login nav-link'
3340 $usermenuclasses
3344 $avatarclasses = "avatars";
3345 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3346 $usertextcontents = $opts->metadata['userfullname'];
3348 // Other user.
3349 if (!empty($opts->metadata['asotheruser'])) {
3350 $avatarcontents .= html_writer::span(
3351 $opts->metadata['realuseravatar'],
3352 'avatar realuser'
3354 $usertextcontents = $opts->metadata['realuserfullname'];
3355 $usertextcontents .= html_writer::tag(
3356 'span',
3357 get_string(
3358 'loggedinas',
3359 'moodle',
3360 html_writer::span(
3361 $opts->metadata['userfullname'],
3362 'value'
3365 array('class' => 'meta viewingas')
3369 // Role.
3370 if (!empty($opts->metadata['asotherrole'])) {
3371 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3372 $usertextcontents .= html_writer::span(
3373 $opts->metadata['rolename'],
3374 'meta role role-' . $role
3378 // User login failures.
3379 if (!empty($opts->metadata['userloginfail'])) {
3380 $usertextcontents .= html_writer::span(
3381 $opts->metadata['userloginfail'],
3382 'meta loginfailures'
3386 // MNet.
3387 if (!empty($opts->metadata['asmnetuser'])) {
3388 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3389 $usertextcontents .= html_writer::span(
3390 $opts->metadata['mnetidprovidername'],
3391 'meta mnet mnet-' . $mnet
3395 $returnstr .= html_writer::span(
3396 html_writer::span($usertextcontents, 'usertext mr-1') .
3397 html_writer::span($avatarcontents, $avatarclasses),
3398 'userbutton'
3401 // Create a divider (well, a filler).
3402 $divider = new action_menu_filler();
3403 $divider->primary = false;
3405 $am = new action_menu();
3406 $am->set_menu_trigger(
3407 $returnstr,
3408 'nav-link'
3410 $am->set_action_label(get_string('usermenu'));
3411 $am->set_alignment(action_menu::TR, action_menu::BR);
3412 $am->set_nowrap_on_items();
3413 if ($withlinks) {
3414 $navitemcount = count($opts->navitems);
3415 $idx = 0;
3416 foreach ($opts->navitems as $key => $value) {
3418 switch ($value->itemtype) {
3419 case 'divider':
3420 // If the nav item is a divider, add one and skip link processing.
3421 $am->add($divider);
3422 break;
3424 case 'invalid':
3425 // Silently skip invalid entries (should we post a notification?).
3426 break;
3428 case 'link':
3429 // Process this as a link item.
3430 $pix = null;
3431 if (isset($value->pix) && !empty($value->pix)) {
3432 $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
3433 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3434 $value->title = html_writer::img(
3435 $value->imgsrc,
3436 $value->title,
3437 array('class' => 'iconsmall')
3438 ) . $value->title;
3441 $al = new action_menu_link_secondary(
3442 $value->url,
3443 $pix,
3444 $value->title,
3445 array('class' => 'icon')
3447 if (!empty($value->titleidentifier)) {
3448 $al->attributes['data-title'] = $value->titleidentifier;
3450 $am->add($al);
3451 break;
3454 $idx++;
3456 // Add dividers after the first item and before the last item.
3457 if ($idx == 1 || $idx == $navitemcount - 1) {
3458 $am->add($divider);
3463 return html_writer::div(
3464 $this->render($am),
3465 $usermenuclasses
3470 * Secure layout login info.
3472 * @return string
3474 public function secure_layout_login_info() {
3475 if (get_config('core', 'logininfoinsecurelayout')) {
3476 return $this->login_info(false);
3477 } else {
3478 return '';
3483 * Returns the language menu in the secure layout.
3485 * No custom menu items are passed though, such that it will render only the language selection.
3487 * @return string
3489 public function secure_layout_language_menu() {
3490 if (get_config('core', 'langmenuinsecurelayout')) {
3491 $custommenu = new custom_menu('', current_language());
3492 return $this->render_custom_menu($custommenu);
3493 } else {
3494 return '';
3499 * This renders the navbar.
3500 * Uses bootstrap compatible html.
3502 public function navbar() {
3503 return $this->render_from_template('core/navbar', $this->page->navbar);
3507 * Renders a breadcrumb navigation node object.
3509 * @param breadcrumb_navigation_node $item The navigation node to render.
3510 * @return string HTML fragment
3512 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3514 if ($item->action instanceof moodle_url) {
3515 $content = $item->get_content();
3516 $title = $item->get_title();
3517 $attributes = array();
3518 $attributes['itemprop'] = 'url';
3519 if ($title !== '') {
3520 $attributes['title'] = $title;
3522 if ($item->hidden) {
3523 $attributes['class'] = 'dimmed_text';
3525 if ($item->is_last()) {
3526 $attributes['aria-current'] = 'page';
3528 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3529 $content = html_writer::link($item->action, $content, $attributes);
3531 $attributes = array();
3532 $attributes['itemscope'] = '';
3533 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3534 $content = html_writer::tag('span', $content, $attributes);
3536 } else {
3537 $content = $this->render_navigation_node($item);
3539 return $content;
3543 * Renders a navigation node object.
3545 * @param navigation_node $item The navigation node to render.
3546 * @return string HTML fragment
3548 protected function render_navigation_node(navigation_node $item) {
3549 $content = $item->get_content();
3550 $title = $item->get_title();
3551 if ($item->icon instanceof renderable && !$item->hideicon) {
3552 $icon = $this->render($item->icon);
3553 $content = $icon.$content; // use CSS for spacing of icons
3555 if ($item->helpbutton !== null) {
3556 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3558 if ($content === '') {
3559 return '';
3561 if ($item->action instanceof action_link) {
3562 $link = $item->action;
3563 if ($item->hidden) {
3564 $link->add_class('dimmed');
3566 if (!empty($content)) {
3567 // Providing there is content we will use that for the link content.
3568 $link->text = $content;
3570 $content = $this->render($link);
3571 } else if ($item->action instanceof moodle_url) {
3572 $attributes = array();
3573 if ($title !== '') {
3574 $attributes['title'] = $title;
3576 if ($item->hidden) {
3577 $attributes['class'] = 'dimmed_text';
3579 $content = html_writer::link($item->action, $content, $attributes);
3581 } else if (is_string($item->action) || empty($item->action)) {
3582 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3583 if ($title !== '') {
3584 $attributes['title'] = $title;
3586 if ($item->hidden) {
3587 $attributes['class'] = 'dimmed_text';
3589 $content = html_writer::tag('span', $content, $attributes);
3591 return $content;
3595 * Accessibility: Right arrow-like character is
3596 * used in the breadcrumb trail, course navigation menu
3597 * (previous/next activity), calendar, and search forum block.
3598 * If the theme does not set characters, appropriate defaults
3599 * are set automatically. Please DO NOT
3600 * use &lt; &gt; &raquo; - these are confusing for blind users.
3602 * @return string
3604 public function rarrow() {
3605 return $this->page->theme->rarrow;
3609 * Accessibility: Left arrow-like character is
3610 * used in the breadcrumb trail, course navigation menu
3611 * (previous/next activity), calendar, and search forum block.
3612 * If the theme does not set characters, appropriate defaults
3613 * are set automatically. Please DO NOT
3614 * use &lt; &gt; &raquo; - these are confusing for blind users.
3616 * @return string
3618 public function larrow() {
3619 return $this->page->theme->larrow;
3623 * Accessibility: Up arrow-like character is used in
3624 * the book heirarchical navigation.
3625 * If the theme does not set characters, appropriate defaults
3626 * are set automatically. Please DO NOT
3627 * use ^ - this is confusing for blind users.
3629 * @return string
3631 public function uarrow() {
3632 return $this->page->theme->uarrow;
3636 * Accessibility: Down arrow-like character.
3637 * If the theme does not set characters, appropriate defaults
3638 * are set automatically.
3640 * @return string
3642 public function darrow() {
3643 return $this->page->theme->darrow;
3647 * Returns the custom menu if one has been set
3649 * A custom menu can be configured by browsing to
3650 * Settings: Administration > Appearance > Themes > Theme settings
3651 * and then configuring the custommenu config setting as described.
3653 * Theme developers: DO NOT OVERRIDE! Please override function
3654 * {@link core_renderer::render_custom_menu()} instead.
3656 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3657 * @return string
3659 public function custom_menu($custommenuitems = '') {
3660 global $CFG;
3662 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3663 $custommenuitems = $CFG->custommenuitems;
3665 $custommenu = new custom_menu($custommenuitems, current_language());
3666 return $this->render_custom_menu($custommenu);
3670 * We want to show the custom menus as a list of links in the footer on small screens.
3671 * Just return the menu object exported so we can render it differently.
3673 public function custom_menu_flat() {
3674 global $CFG;
3675 $custommenuitems = '';
3677 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3678 $custommenuitems = $CFG->custommenuitems;
3680 $custommenu = new custom_menu($custommenuitems, current_language());
3681 $langs = get_string_manager()->get_list_of_translations();
3682 $haslangmenu = $this->lang_menu() != '';
3684 if ($haslangmenu) {
3685 $strlang = get_string('language');
3686 $currentlang = current_language();
3687 if (isset($langs[$currentlang])) {
3688 $currentlang = $langs[$currentlang];
3689 } else {
3690 $currentlang = $strlang;
3692 $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3693 foreach ($langs as $langtype => $langname) {
3694 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3698 return $custommenu->export_for_template($this);
3702 * Renders a custom menu object (located in outputcomponents.php)
3704 * The custom menu this method produces makes use of the YUI3 menunav widget
3705 * and requires very specific html elements and classes.
3707 * @staticvar int $menucount
3708 * @param custom_menu $menu
3709 * @return string
3711 protected function render_custom_menu(custom_menu $menu) {
3712 global $CFG;
3714 $langs = get_string_manager()->get_list_of_translations();
3715 $haslangmenu = $this->lang_menu() != '';
3717 if (!$menu->has_children() && !$haslangmenu) {
3718 return '';
3721 if ($haslangmenu) {
3722 $strlang = get_string('language');
3723 $currentlang = current_language();
3724 if (isset($langs[$currentlang])) {
3725 $currentlang = $langs[$currentlang];
3726 } else {
3727 $currentlang = $strlang;
3729 $this->language = $menu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3730 foreach ($langs as $langtype => $langname) {
3731 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3735 $content = '';
3736 foreach ($menu->get_children() as $item) {
3737 $context = $item->export_for_template($this);
3738 $content .= $this->render_from_template('core/custom_menu_item', $context);
3741 return $content;
3745 * Renders a custom menu node as part of a submenu
3747 * The custom menu this method produces makes use of the YUI3 menunav widget
3748 * and requires very specific html elements and classes.
3750 * @see core:renderer::render_custom_menu()
3752 * @staticvar int $submenucount
3753 * @param custom_menu_item $menunode
3754 * @return string
3756 protected function render_custom_menu_item(custom_menu_item $menunode) {
3757 // Required to ensure we get unique trackable id's
3758 static $submenucount = 0;
3759 if ($menunode->has_children()) {
3760 // If the child has menus render it as a sub menu
3761 $submenucount++;
3762 $content = html_writer::start_tag('li');
3763 if ($menunode->get_url() !== null) {
3764 $url = $menunode->get_url();
3765 } else {
3766 $url = '#cm_submenu_'.$submenucount;
3768 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3769 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3770 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3771 $content .= html_writer::start_tag('ul');
3772 foreach ($menunode->get_children() as $menunode) {
3773 $content .= $this->render_custom_menu_item($menunode);
3775 $content .= html_writer::end_tag('ul');
3776 $content .= html_writer::end_tag('div');
3777 $content .= html_writer::end_tag('div');
3778 $content .= html_writer::end_tag('li');
3779 } else {
3780 // The node doesn't have children so produce a final menuitem.
3781 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3782 $content = '';
3783 if (preg_match("/^#+$/", $menunode->get_text())) {
3785 // This is a divider.
3786 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3787 } else {
3788 $content = html_writer::start_tag(
3789 'li',
3790 array(
3791 'class' => 'yui3-menuitem'
3794 if ($menunode->get_url() !== null) {
3795 $url = $menunode->get_url();
3796 } else {
3797 $url = '#';
3799 $content .= html_writer::link(
3800 $url,
3801 $menunode->get_text(),
3802 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3805 $content .= html_writer::end_tag('li');
3807 // Return the sub menu
3808 return $content;
3812 * Renders theme links for switching between default and other themes.
3814 * @return string
3816 protected function theme_switch_links() {
3818 $actualdevice = core_useragent::get_device_type();
3819 $currentdevice = $this->page->devicetypeinuse;
3820 $switched = ($actualdevice != $currentdevice);
3822 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3823 // The user is using the a default device and hasn't switched so don't shown the switch
3824 // device links.
3825 return '';
3828 if ($switched) {
3829 $linktext = get_string('switchdevicerecommended');
3830 $devicetype = $actualdevice;
3831 } else {
3832 $linktext = get_string('switchdevicedefault');
3833 $devicetype = 'default';
3835 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3837 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3838 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3839 $content .= html_writer::end_tag('div');
3841 return $content;
3845 * Renders tabs
3847 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3849 * Theme developers: In order to change how tabs are displayed please override functions
3850 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3852 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3853 * @param string|null $selected which tab to mark as selected, all parent tabs will
3854 * automatically be marked as activated
3855 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3856 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3857 * @return string
3859 public final function tabtree($tabs, $selected = null, $inactive = null) {
3860 return $this->render(new tabtree($tabs, $selected, $inactive));
3864 * Renders tabtree
3866 * @param tabtree $tabtree
3867 * @return string
3869 protected function render_tabtree(tabtree $tabtree) {
3870 if (empty($tabtree->subtree)) {
3871 return '';
3873 $data = $tabtree->export_for_template($this);
3874 return $this->render_from_template('core/tabtree', $data);
3878 * Renders tabobject (part of tabtree)
3880 * This function is called from {@link core_renderer::render_tabtree()}
3881 * and also it calls itself when printing the $tabobject subtree recursively.
3883 * Property $tabobject->level indicates the number of row of tabs.
3885 * @param tabobject $tabobject
3886 * @return string HTML fragment
3888 protected function render_tabobject(tabobject $tabobject) {
3889 $str = '';
3891 // Print name of the current tab.
3892 if ($tabobject instanceof tabtree) {
3893 // No name for tabtree root.
3894 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3895 // Tab name without a link. The <a> tag is used for styling.
3896 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3897 } else {
3898 // Tab name with a link.
3899 if (!($tabobject->link instanceof moodle_url)) {
3900 // backward compartibility when link was passed as quoted string
3901 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3902 } else {
3903 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3907 if (empty($tabobject->subtree)) {
3908 if ($tabobject->selected) {
3909 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3911 return $str;
3914 // Print subtree.
3915 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
3916 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3917 $cnt = 0;
3918 foreach ($tabobject->subtree as $tab) {
3919 $liclass = '';
3920 if (!$cnt) {
3921 $liclass .= ' first';
3923 if ($cnt == count($tabobject->subtree) - 1) {
3924 $liclass .= ' last';
3926 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3927 $liclass .= ' onerow';
3930 if ($tab->selected) {
3931 $liclass .= ' here selected';
3932 } else if ($tab->activated) {
3933 $liclass .= ' here active';
3936 // This will recursively call function render_tabobject() for each item in subtree.
3937 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3938 $cnt++;
3940 $str .= html_writer::end_tag('ul');
3943 return $str;
3947 * Get the HTML for blocks in the given region.
3949 * @since Moodle 2.5.1 2.6
3950 * @param string $region The region to get HTML for.
3951 * @param array $classes Wrapping tag classes.
3952 * @param string $tag Wrapping tag.
3953 * @param boolean $fakeblocksonly Include fake blocks only.
3954 * @return string HTML.
3956 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
3957 $displayregion = $this->page->apply_theme_region_manipulations($region);
3958 $classes = (array)$classes;
3959 $classes[] = 'block-region';
3960 $attributes = array(
3961 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3962 'class' => join(' ', $classes),
3963 'data-blockregion' => $displayregion,
3964 'data-droptarget' => '1'
3966 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3967 $content = $this->blocks_for_region($displayregion, $fakeblocksonly);
3968 } else {
3969 $content = '';
3971 return html_writer::tag($tag, $content, $attributes);
3975 * Renders a custom block region.
3977 * Use this method if you want to add an additional block region to the content of the page.
3978 * Please note this should only be used in special situations.
3979 * We want to leave the theme is control where ever possible!
3981 * This method must use the same method that the theme uses within its layout file.
3982 * As such it asks the theme what method it is using.
3983 * It can be one of two values, blocks or blocks_for_region (deprecated).
3985 * @param string $regionname The name of the custom region to add.
3986 * @return string HTML for the block region.
3988 public function custom_block_region($regionname) {
3989 if ($this->page->theme->get_block_render_method() === 'blocks') {
3990 return $this->blocks($regionname);
3991 } else {
3992 return $this->blocks_for_region($regionname);
3997 * Returns the CSS classes to apply to the body tag.
3999 * @since Moodle 2.5.1 2.6
4000 * @param array $additionalclasses Any additional classes to apply.
4001 * @return string
4003 public function body_css_classes(array $additionalclasses = array()) {
4004 return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses);
4008 * The ID attribute to apply to the body tag.
4010 * @since Moodle 2.5.1 2.6
4011 * @return string
4013 public function body_id() {
4014 return $this->page->bodyid;
4018 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4020 * @since Moodle 2.5.1 2.6
4021 * @param string|array $additionalclasses Any additional classes to give the body tag,
4022 * @return string
4024 public function body_attributes($additionalclasses = array()) {
4025 if (!is_array($additionalclasses)) {
4026 $additionalclasses = explode(' ', $additionalclasses);
4028 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4032 * Gets HTML for the page heading.
4034 * @since Moodle 2.5.1 2.6
4035 * @param string $tag The tag to encase the heading in. h1 by default.
4036 * @return string HTML.
4038 public function page_heading($tag = 'h1') {
4039 return html_writer::tag($tag, $this->page->heading);
4043 * Gets the HTML for the page heading button.
4045 * @since Moodle 2.5.1 2.6
4046 * @return string HTML.
4048 public function page_heading_button() {
4049 return $this->page->button;
4053 * Returns the Moodle docs link to use for this page.
4055 * @since Moodle 2.5.1 2.6
4056 * @param string $text
4057 * @return string
4059 public function page_doc_link($text = null) {
4060 if ($text === null) {
4061 $text = get_string('moodledocslink');
4063 $path = page_get_doc_link_path($this->page);
4064 if (!$path) {
4065 return '';
4067 return $this->doc_link($path, $text);
4071 * Returns the page heading menu.
4073 * @since Moodle 2.5.1 2.6
4074 * @return string HTML.
4076 public function page_heading_menu() {
4077 return $this->page->headingmenu;
4081 * Returns the title to use on the page.
4083 * @since Moodle 2.5.1 2.6
4084 * @return string
4086 public function page_title() {
4087 return $this->page->title;
4091 * Returns the moodle_url for the favicon.
4093 * @since Moodle 2.5.1 2.6
4094 * @return moodle_url The moodle_url for the favicon
4096 public function favicon() {
4097 return $this->image_url('favicon', 'theme');
4101 * Renders preferences groups.
4103 * @param preferences_groups $renderable The renderable
4104 * @return string The output.
4106 public function render_preferences_groups(preferences_groups $renderable) {
4107 return $this->render_from_template('core/preferences_groups', $renderable);
4111 * Renders preferences group.
4113 * @param preferences_group $renderable The renderable
4114 * @return string The output.
4116 public function render_preferences_group(preferences_group $renderable) {
4117 $html = '';
4118 $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4119 $html .= $this->heading($renderable->title, 3);
4120 $html .= html_writer::start_tag('ul');
4121 foreach ($renderable->nodes as $node) {
4122 if ($node->has_children()) {
4123 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4125 $html .= html_writer::tag('li', $this->render($node));
4127 $html .= html_writer::end_tag('ul');
4128 $html .= html_writer::end_tag('div');
4129 return $html;
4132 public function context_header($headerinfo = null, $headinglevel = 1) {
4133 global $DB, $USER, $CFG, $SITE;
4134 require_once($CFG->dirroot . '/user/lib.php');
4135 $context = $this->page->context;
4136 $heading = null;
4137 $imagedata = null;
4138 $subheader = null;
4139 $userbuttons = null;
4141 // Make sure to use the heading if it has been set.
4142 if (isset($headerinfo['heading'])) {
4143 $heading = $headerinfo['heading'];
4144 } else {
4145 $heading = $this->page->heading;
4148 // The user context currently has images and buttons. Other contexts may follow.
4149 if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
4150 if (isset($headerinfo['user'])) {
4151 $user = $headerinfo['user'];
4152 } else {
4153 // Look up the user information if it is not supplied.
4154 $user = $DB->get_record('user', array('id' => $context->instanceid));
4157 // If the user context is set, then use that for capability checks.
4158 if (isset($headerinfo['usercontext'])) {
4159 $context = $headerinfo['usercontext'];
4162 // Only provide user information if the user is the current user, or a user which the current user can view.
4163 // When checking user_can_view_profile(), either:
4164 // If the page context is course, check the course context (from the page object) or;
4165 // If page context is NOT course, then check across all courses.
4166 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4168 if (user_can_view_profile($user, $course)) {
4169 // Use the user's full name if the heading isn't set.
4170 if (empty($heading)) {
4171 $heading = fullname($user);
4174 $imagedata = $this->user_picture($user, array('size' => 100));
4176 // Check to see if we should be displaying a message button.
4177 if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
4178 $userbuttons = array(
4179 'messages' => array(
4180 'buttontype' => 'message',
4181 'title' => get_string('message', 'message'),
4182 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4183 'image' => 'message',
4184 'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
4185 'page' => $this->page
4189 if ($USER->id != $user->id) {
4190 $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4191 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4192 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4193 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4194 $userbuttons['togglecontact'] = array(
4195 'buttontype' => 'togglecontact',
4196 'title' => get_string($contacttitle, 'message'),
4197 'url' => new moodle_url('/message/index.php', array(
4198 'user1' => $USER->id,
4199 'user2' => $user->id,
4200 $contacturlaction => $user->id,
4201 'sesskey' => sesskey())
4203 'image' => $contactimage,
4204 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4205 'page' => $this->page
4209 } else {
4210 $heading = null;
4214 if ($this->should_display_main_logo($headinglevel)) {
4215 $sitename = format_string($SITE->fullname, true, ['context' => context_course::instance(SITEID)]);
4216 // Logo.
4217 $html = html_writer::div(
4218 html_writer::empty_tag('img', [
4219 'src' => $this->get_logo_url(null, 150),
4220 'alt' => get_string('logoof', '', $sitename),
4221 'class' => 'img-fluid'
4223 'logo'
4225 // Heading.
4226 if (!isset($heading)) {
4227 $html .= $this->heading($this->page->heading, $headinglevel, 'sr-only');
4228 } else {
4229 $html .= $this->heading($heading, $headinglevel, 'sr-only');
4231 return $html;
4234 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4235 return $this->render_context_header($contextheader);
4239 * Renders the skip links for the page.
4241 * @param array $links List of skip links.
4242 * @return string HTML for the skip links.
4244 public function render_skip_links($links) {
4245 $context = [ 'links' => []];
4247 foreach ($links as $url => $text) {
4248 $context['links'][] = [ 'url' => $url, 'text' => $text];
4251 return $this->render_from_template('core/skip_links', $context);
4255 * Renders the header bar.
4257 * @param context_header $contextheader Header bar object.
4258 * @return string HTML for the header bar.
4260 protected function render_context_header(context_header $contextheader) {
4262 // Generate the heading first and before everything else as we might have to do an early return.
4263 if (!isset($contextheader->heading)) {
4264 $heading = $this->heading($this->page->heading, $contextheader->headinglevel);
4265 } else {
4266 $heading = $this->heading($contextheader->heading, $contextheader->headinglevel);
4269 $showheader = empty($this->page->layout_options['nocontextheader']);
4270 if (!$showheader) {
4271 // Return the heading wrapped in an sr-only element so it is only visible to screen-readers.
4272 return html_writer::div($heading, 'sr-only');
4275 // All the html stuff goes here.
4276 $html = html_writer::start_div('page-context-header');
4278 // Image data.
4279 if (isset($contextheader->imagedata)) {
4280 // Header specific image.
4281 $html .= html_writer::div($contextheader->imagedata, 'page-header-image icon-size-7');
4284 // Headings.
4285 if (isset($contextheader->prefix)) {
4286 $prefix = html_writer::div($contextheader->prefix, 'text-muted');
4287 $heading = $prefix . $heading;
4289 $html .= html_writer::tag('div', $heading, array('class' => 'page-header-headings'));
4291 // Buttons.
4292 if (isset($contextheader->additionalbuttons)) {
4293 $html .= html_writer::start_div('btn-group header-button-group');
4294 foreach ($contextheader->additionalbuttons as $button) {
4295 if (!isset($button->page)) {
4296 // Include js for messaging.
4297 if ($button['buttontype'] === 'togglecontact') {
4298 \core_message\helper::togglecontact_requirejs();
4300 if ($button['buttontype'] === 'message') {
4301 \core_message\helper::messageuser_requirejs();
4303 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4304 'class' => 'iconsmall',
4305 'role' => 'presentation'
4307 $image .= html_writer::span($button['title'], 'header-button-title');
4308 } else {
4309 $image = html_writer::empty_tag('img', array(
4310 'src' => $button['formattedimage'],
4311 'role' => 'presentation'
4314 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4316 $html .= html_writer::end_div();
4318 $html .= html_writer::end_div();
4320 return $html;
4324 * Wrapper for header elements.
4326 * @return string HTML to display the main header.
4328 public function full_header() {
4330 if ($this->page->include_region_main_settings_in_header_actions() &&
4331 !$this->page->blocks->is_block_present('settings')) {
4332 // Only include the region main settings if the page has requested it and it doesn't already have
4333 // the settings block on it. The region main settings are included in the settings block and
4334 // duplicating the content causes behat failures.
4335 $this->page->add_header_action(html_writer::div(
4336 $this->region_main_settings_menu(),
4337 'd-print-none',
4338 ['id' => 'region-main-settings-menu']
4342 $header = new stdClass();
4343 $header->settingsmenu = $this->context_header_settings_menu();
4344 $header->contextheader = $this->context_header();
4345 $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
4346 $header->navbar = $this->navbar();
4347 $header->pageheadingbutton = $this->page_heading_button();
4348 $header->courseheader = $this->course_header();
4349 $header->headeractions = $this->page->get_header_actions();
4350 return $this->render_from_template('core/full_header', $header);
4354 * This is an optional menu that can be added to a layout by a theme. It contains the
4355 * menu for the course administration, only on the course main page.
4357 * @return string
4359 public function context_header_settings_menu() {
4360 $context = $this->page->context;
4361 $menu = new action_menu();
4363 $items = $this->page->navbar->get_items();
4364 $currentnode = end($items);
4366 $showcoursemenu = false;
4367 $showfrontpagemenu = false;
4368 $showusermenu = false;
4370 // We are on the course home page.
4371 if (($context->contextlevel == CONTEXT_COURSE) &&
4372 !empty($currentnode) &&
4373 ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
4374 $showcoursemenu = true;
4377 $courseformat = course_get_format($this->page->course);
4378 // This is a single activity course format, always show the course menu on the activity main page.
4379 if ($context->contextlevel == CONTEXT_MODULE &&
4380 !$courseformat->has_view_page()) {
4382 $this->page->navigation->initialise();
4383 $activenode = $this->page->navigation->find_active_node();
4384 // If the settings menu has been forced then show the menu.
4385 if ($this->page->is_settings_menu_forced()) {
4386 $showcoursemenu = true;
4387 } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
4388 $activenode->type == navigation_node::TYPE_RESOURCE)) {
4390 // We only want to show the menu on the first page of the activity. This means
4391 // the breadcrumb has no additional nodes.
4392 if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
4393 $showcoursemenu = true;
4398 // This is the site front page.
4399 if ($context->contextlevel == CONTEXT_COURSE &&
4400 !empty($currentnode) &&
4401 $currentnode->key === 'home') {
4402 $showfrontpagemenu = true;
4405 // This is the user profile page.
4406 if ($context->contextlevel == CONTEXT_USER &&
4407 !empty($currentnode) &&
4408 ($currentnode->key === 'myprofile')) {
4409 $showusermenu = true;
4412 if ($showfrontpagemenu) {
4413 $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
4414 if ($settingsnode) {
4415 // Build an action menu based on the visible nodes from this navigation tree.
4416 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4418 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4419 if ($skipped) {
4420 $text = get_string('morenavigationlinks');
4421 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4422 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4423 $menu->add_secondary_action($link);
4426 } else if ($showcoursemenu) {
4427 $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
4428 if ($settingsnode) {
4429 // Build an action menu based on the visible nodes from this navigation tree.
4430 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4432 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4433 if ($skipped) {
4434 $text = get_string('morenavigationlinks');
4435 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4436 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4437 $menu->add_secondary_action($link);
4440 } else if ($showusermenu) {
4441 // Get the course admin node from the settings navigation.
4442 $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
4443 if ($settingsnode) {
4444 // Build an action menu based on the visible nodes from this navigation tree.
4445 $this->build_action_menu_from_navigation($menu, $settingsnode);
4449 return $this->render($menu);
4453 * Take a node in the nav tree and make an action menu out of it.
4454 * The links are injected in the action menu.
4456 * @param action_menu $menu
4457 * @param navigation_node $node
4458 * @param boolean $indent
4459 * @param boolean $onlytopleafnodes
4460 * @return boolean nodesskipped - True if nodes were skipped in building the menu
4462 protected function build_action_menu_from_navigation(action_menu $menu,
4463 navigation_node $node,
4464 $indent = false,
4465 $onlytopleafnodes = false) {
4466 $skipped = false;
4467 // Build an action menu based on the visible nodes from this navigation tree.
4468 foreach ($node->children as $menuitem) {
4469 if ($menuitem->display) {
4470 if ($onlytopleafnodes && $menuitem->children->count()) {
4471 $skipped = true;
4472 continue;
4474 if ($menuitem->action) {
4475 if ($menuitem->action instanceof action_link) {
4476 $link = $menuitem->action;
4477 // Give preference to setting icon over action icon.
4478 if (!empty($menuitem->icon)) {
4479 $link->icon = $menuitem->icon;
4481 } else {
4482 $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
4484 } else {
4485 if ($onlytopleafnodes) {
4486 $skipped = true;
4487 continue;
4489 $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
4491 if ($indent) {
4492 $link->add_class('ml-4');
4494 if (!empty($menuitem->classes)) {
4495 $link->add_class(implode(" ", $menuitem->classes));
4498 $menu->add_secondary_action($link);
4499 $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
4502 return $skipped;
4506 * This is an optional menu that can be added to a layout by a theme. It contains the
4507 * menu for the most specific thing from the settings block. E.g. Module administration.
4509 * @return string
4511 public function region_main_settings_menu() {
4512 $context = $this->page->context;
4513 $menu = new action_menu();
4515 if ($context->contextlevel == CONTEXT_MODULE) {
4517 $this->page->navigation->initialise();
4518 $node = $this->page->navigation->find_active_node();
4519 $buildmenu = false;
4520 // If the settings menu has been forced then show the menu.
4521 if ($this->page->is_settings_menu_forced()) {
4522 $buildmenu = true;
4523 } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
4524 $node->type == navigation_node::TYPE_RESOURCE)) {
4526 $items = $this->page->navbar->get_items();
4527 $navbarnode = end($items);
4528 // We only want to show the menu on the first page of the activity. This means
4529 // the breadcrumb has no additional nodes.
4530 if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
4531 $buildmenu = true;
4534 if ($buildmenu) {
4535 // Get the course admin node from the settings navigation.
4536 $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
4537 if ($node) {
4538 // Build an action menu based on the visible nodes from this navigation tree.
4539 $this->build_action_menu_from_navigation($menu, $node);
4543 } else if ($context->contextlevel == CONTEXT_COURSECAT) {
4544 // For course category context, show category settings menu, if we're on the course category page.
4545 if ($this->page->pagetype === 'course-index-category') {
4546 $node = $this->page->settingsnav->find('categorysettings', navigation_node::TYPE_CONTAINER);
4547 if ($node) {
4548 // Build an action menu based on the visible nodes from this navigation tree.
4549 $this->build_action_menu_from_navigation($menu, $node);
4553 } else {
4554 $items = $this->page->navbar->get_items();
4555 $navbarnode = end($items);
4557 if ($navbarnode && ($navbarnode->key === 'participants')) {
4558 $node = $this->page->settingsnav->find('users', navigation_node::TYPE_CONTAINER);
4559 if ($node) {
4560 // Build an action menu based on the visible nodes from this navigation tree.
4561 $this->build_action_menu_from_navigation($menu, $node);
4566 return $this->render($menu);
4570 * Displays the list of tags associated with an entry
4572 * @param array $tags list of instances of core_tag or stdClass
4573 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4574 * to use default, set to '' (empty string) to omit the label completely
4575 * @param string $classes additional classes for the enclosing div element
4576 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4577 * will be appended to the end, JS will toggle the rest of the tags
4578 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4579 * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
4580 * @return string
4582 public function tag_list($tags, $label = null, $classes = '', $limit = 10,
4583 $pagecontext = null, $accesshidelabel = false) {
4584 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
4585 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4589 * Renders element for inline editing of any value
4591 * @param \core\output\inplace_editable $element
4592 * @return string
4594 public function render_inplace_editable(\core\output\inplace_editable $element) {
4595 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4599 * Renders a bar chart.
4601 * @param \core\chart_bar $chart The chart.
4602 * @return string.
4604 public function render_chart_bar(\core\chart_bar $chart) {
4605 return $this->render_chart($chart);
4609 * Renders a line chart.
4611 * @param \core\chart_line $chart The chart.
4612 * @return string.
4614 public function render_chart_line(\core\chart_line $chart) {
4615 return $this->render_chart($chart);
4619 * Renders a pie chart.
4621 * @param \core\chart_pie $chart The chart.
4622 * @return string.
4624 public function render_chart_pie(\core\chart_pie $chart) {
4625 return $this->render_chart($chart);
4629 * Renders a chart.
4631 * @param \core\chart_base $chart The chart.
4632 * @param bool $withtable Whether to include a data table with the chart.
4633 * @return string.
4635 public function render_chart(\core\chart_base $chart, $withtable = true) {
4636 $chartdata = json_encode($chart);
4637 return $this->render_from_template('core/chart', (object) [
4638 'chartdata' => $chartdata,
4639 'withtable' => $withtable
4644 * Renders the login form.
4646 * @param \core_auth\output\login $form The renderable.
4647 * @return string
4649 public function render_login(\core_auth\output\login $form) {
4650 global $CFG, $SITE;
4652 $context = $form->export_for_template($this);
4654 // Override because rendering is not supported in template yet.
4655 if ($CFG->rememberusername == 0) {
4656 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabledonlysession');
4657 } else {
4658 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
4660 $context->errorformatted = $this->error_text($context->error);
4661 $url = $this->get_logo_url();
4662 if ($url) {
4663 $url = $url->out(false);
4665 $context->logourl = $url;
4666 $context->sitename = format_string($SITE->fullname, true,
4667 ['context' => context_course::instance(SITEID), "escape" => false]);
4669 return $this->render_from_template('core/loginform', $context);
4673 * Renders an mform element from a template.
4675 * @param HTML_QuickForm_element $element element
4676 * @param bool $required if input is required field
4677 * @param bool $advanced if input is an advanced field
4678 * @param string $error error message to display
4679 * @param bool $ingroup True if this element is rendered as part of a group
4680 * @return mixed string|bool
4682 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4683 $templatename = 'core_form/element-' . $element->getType();
4684 if ($ingroup) {
4685 $templatename .= "-inline";
4687 try {
4688 // We call this to generate a file not found exception if there is no template.
4689 // We don't want to call export_for_template if there is no template.
4690 core\output\mustache_template_finder::get_template_filepath($templatename);
4692 if ($element instanceof templatable) {
4693 $elementcontext = $element->export_for_template($this);
4695 $helpbutton = '';
4696 if (method_exists($element, 'getHelpButton')) {
4697 $helpbutton = $element->getHelpButton();
4699 $label = $element->getLabel();
4700 $text = '';
4701 if (method_exists($element, 'getText')) {
4702 // There currently exists code that adds a form element with an empty label.
4703 // If this is the case then set the label to the description.
4704 if (empty($label)) {
4705 $label = $element->getText();
4706 } else {
4707 $text = $element->getText();
4711 // Generate the form element wrapper ids and names to pass to the template.
4712 // This differs between group and non-group elements.
4713 if ($element->getType() === 'group') {
4714 // Group element.
4715 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
4716 $elementcontext['wrapperid'] = $elementcontext['id'];
4718 // Ensure group elements pass through the group name as the element name.
4719 $elementcontext['name'] = $elementcontext['groupname'];
4720 } else {
4721 // Non grouped element.
4722 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
4723 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
4726 $context = array(
4727 'element' => $elementcontext,
4728 'label' => $label,
4729 'text' => $text,
4730 'required' => $required,
4731 'advanced' => $advanced,
4732 'helpbutton' => $helpbutton,
4733 'error' => $error
4735 return $this->render_from_template($templatename, $context);
4737 } catch (Exception $e) {
4738 // No template for this element.
4739 return false;
4744 * Render the login signup form into a nice template for the theme.
4746 * @param mform $form
4747 * @return string
4749 public function render_login_signup_form($form) {
4750 global $SITE;
4752 $context = $form->export_for_template($this);
4753 $url = $this->get_logo_url();
4754 if ($url) {
4755 $url = $url->out(false);
4757 $context['logourl'] = $url;
4758 $context['sitename'] = format_string($SITE->fullname, true,
4759 ['context' => context_course::instance(SITEID), "escape" => false]);
4761 return $this->render_from_template('core/signup_form_layout', $context);
4765 * Render the verify age and location page into a nice template for the theme.
4767 * @param \core_auth\output\verify_age_location_page $page The renderable
4768 * @return string
4770 protected function render_verify_age_location_page($page) {
4771 $context = $page->export_for_template($this);
4773 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4777 * Render the digital minor contact information page into a nice template for the theme.
4779 * @param \core_auth\output\digital_minor_page $page The renderable
4780 * @return string
4782 protected function render_digital_minor_page($page) {
4783 $context = $page->export_for_template($this);
4785 return $this->render_from_template('core/auth_digital_minor_page', $context);
4789 * Renders a progress bar.
4791 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4793 * @param progress_bar $bar The bar.
4794 * @return string HTML fragment
4796 public function render_progress_bar(progress_bar $bar) {
4797 $data = $bar->export_for_template($this);
4798 return $this->render_from_template('core/progress_bar', $data);
4802 * Renders an update to a progress bar.
4804 * Note: This does not cleanly map to a renderable class and should
4805 * never be used directly.
4807 * @param string $id
4808 * @param float $percent
4809 * @param string $msg Message
4810 * @param string $estimate time remaining message
4811 * @return string ascii fragment
4813 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
4814 return html_writer::script(js_writer::function_call('updateProgressBar', [$id, $percent, $msg, $estimate]));
4818 * Renders element for a toggle-all checkbox.
4820 * @param \core\output\checkbox_toggleall $element
4821 * @return string
4823 public function render_checkbox_toggleall(\core\output\checkbox_toggleall $element) {
4824 return $this->render_from_template($element->get_template(), $element->export_for_template($this));
4829 * A renderer that generates output for command-line scripts.
4831 * The implementation of this renderer is probably incomplete.
4833 * @copyright 2009 Tim Hunt
4834 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4835 * @since Moodle 2.0
4836 * @package core
4837 * @category output
4839 class core_renderer_cli extends core_renderer {
4842 * @var array $progressmaximums stores the largest percentage for a progress bar.
4843 * @return string ascii fragment
4845 private $progressmaximums = [];
4848 * Returns the page header.
4850 * @return string HTML fragment
4852 public function header() {
4853 return $this->page->heading . "\n";
4857 * Renders a Check API result
4859 * To aid in CLI consistency this status is NOT translated and the visual
4860 * width is always exactly 10 chars.
4862 * @param result $result
4863 * @return string HTML fragment
4865 protected function render_check_result(core\check\result $result) {
4866 $status = $result->get_status();
4868 $labels = [
4869 core\check\result::NA => ' ' . cli_ansi_format('<colour:gray>' ) . ' NA ',
4870 core\check\result::OK => ' ' . cli_ansi_format('<colour:green>') . ' OK ',
4871 core\check\result::INFO => ' ' . cli_ansi_format('<colour:blue>' ) . ' INFO ',
4872 core\check\result::UNKNOWN => ' ' . cli_ansi_format('<colour:grey>' ) . ' UNKNOWN ',
4873 core\check\result::WARNING => ' ' . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
4874 core\check\result::ERROR => ' ' . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
4875 core\check\result::CRITICAL => '' . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
4877 $string = $labels[$status] . cli_ansi_format('<colour:normal>');
4878 return $string;
4882 * Renders a Check API result
4884 * @param result $result
4885 * @return string fragment
4887 public function check_result(core\check\result $result) {
4888 return $this->render_check_result($result);
4892 * Renders a progress bar.
4894 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4896 * @param progress_bar $bar The bar.
4897 * @return string ascii fragment
4899 public function render_progress_bar(progress_bar $bar) {
4900 global $CFG;
4902 $size = 55; // The width of the progress bar in chars.
4903 $ascii = "\n";
4905 if (stream_isatty(STDOUT)) {
4906 require_once($CFG->libdir.'/clilib.php');
4908 $ascii .= "[" . str_repeat(' ', $size) . "] 0% \n";
4909 return cli_ansi_format($ascii);
4912 $this->progressmaximums[$bar->get_id()] = 0;
4913 $ascii .= '[';
4914 return $ascii;
4918 * Renders an update to a progress bar.
4920 * Note: This does not cleanly map to a renderable class and should
4921 * never be used directly.
4923 * @param string $id
4924 * @param float $percent
4925 * @param string $msg Message
4926 * @param string $estimate time remaining message
4927 * @return string ascii fragment
4929 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
4930 $size = 55; // The width of the progress bar in chars.
4931 $ascii = '';
4933 // If we are rendering to a terminal then we can safely use ansii codes
4934 // to move the cursor and redraw the complete progress bar each time
4935 // it is updated.
4936 if (stream_isatty(STDOUT)) {
4937 $colour = $percent == 100 ? 'green' : 'blue';
4939 $done = $percent * $size * 0.01;
4940 $whole = floor($done);
4941 $bar = "<colour:$colour>";
4942 $bar .= str_repeat('█', $whole);
4944 if ($whole < $size) {
4945 // By using unicode chars for partial blocks we can have higher
4946 // precision progress bar.
4947 $fraction = floor(($done - $whole) * 8);
4948 $bar .= core_text::substr(' ▏▎▍▌▋▊▉', $fraction, 1);
4950 // Fill the rest of the empty bar.
4951 $bar .= str_repeat(' ', $size - $whole - 1);
4954 $bar .= '<colour:normal>';
4956 if ($estimate) {
4957 $estimate = "- $estimate";
4960 $ascii .= '<cursor:up>';
4961 $ascii .= '<cursor:up>';
4962 $ascii .= sprintf("[$bar] %3.1f%% %-22s\n", $percent, $estimate);
4963 $ascii .= sprintf("%-80s\n", $msg);
4964 return cli_ansi_format($ascii);
4967 // If we are not rendering to a tty, ie when piped to another command
4968 // or on windows we need to progressively render the progress bar
4969 // which can only ever go forwards.
4970 $done = round($percent * $size * 0.01);
4971 $delta = max(0, $done - $this->progressmaximums[$id]);
4973 $ascii .= str_repeat('#', $delta);
4974 if ($percent >= 100 && $delta > 0) {
4975 $ascii .= sprintf("] %3.1f%%\n$msg\n", $percent);
4977 $this->progressmaximums[$id] += $delta;
4978 return $ascii;
4982 * Returns a template fragment representing a Heading.
4984 * @param string $text The text of the heading
4985 * @param int $level The level of importance of the heading
4986 * @param string $classes A space-separated list of CSS classes
4987 * @param string $id An optional ID
4988 * @return string A template fragment for a heading
4990 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4991 $text .= "\n";
4992 switch ($level) {
4993 case 1:
4994 return '=>' . $text;
4995 case 2:
4996 return '-->' . $text;
4997 default:
4998 return $text;
5003 * Returns a template fragment representing a fatal error.
5005 * @param string $message The message to output
5006 * @param string $moreinfourl URL where more info can be found about the error
5007 * @param string $link Link for the Continue button
5008 * @param array $backtrace The execution backtrace
5009 * @param string $debuginfo Debugging information
5010 * @return string A template fragment for a fatal error
5012 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5013 global $CFG;
5015 $output = "!!! $message !!!\n";
5017 if ($CFG->debugdeveloper) {
5018 if (!empty($debuginfo)) {
5019 $output .= $this->notification($debuginfo, 'notifytiny');
5021 if (!empty($backtrace)) {
5022 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
5026 return $output;
5030 * Returns a template fragment representing a notification.
5032 * @param string $message The message to print out.
5033 * @param string $type The type of notification. See constants on \core\output\notification.
5034 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5035 * @return string A template fragment for a notification
5037 public function notification($message, $type = null, $closebutton = true) {
5038 $message = clean_text($message);
5039 if ($type === 'notifysuccess' || $type === 'success') {
5040 return "++ $message ++\n";
5042 return "!! $message !!\n";
5046 * There is no footer for a cli request, however we must override the
5047 * footer method to prevent the default footer.
5049 public function footer() {}
5052 * Render a notification (that is, a status message about something that has
5053 * just happened).
5055 * @param \core\output\notification $notification the notification to print out
5056 * @return string plain text output
5058 public function render_notification(\core\output\notification $notification) {
5059 return $this->notification($notification->get_message(), $notification->get_message_type());
5065 * A renderer that generates output for ajax scripts.
5067 * This renderer prevents accidental sends back only json
5068 * encoded error messages, all other output is ignored.
5070 * @copyright 2010 Petr Skoda
5071 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5072 * @since Moodle 2.0
5073 * @package core
5074 * @category output
5076 class core_renderer_ajax extends core_renderer {
5079 * Returns a template fragment representing a fatal error.
5081 * @param string $message The message to output
5082 * @param string $moreinfourl URL where more info can be found about the error
5083 * @param string $link Link for the Continue button
5084 * @param array $backtrace The execution backtrace
5085 * @param string $debuginfo Debugging information
5086 * @return string A template fragment for a fatal error
5088 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5089 global $CFG;
5091 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
5093 $e = new stdClass();
5094 $e->error = $message;
5095 $e->errorcode = $errorcode;
5096 $e->stacktrace = NULL;
5097 $e->debuginfo = NULL;
5098 $e->reproductionlink = NULL;
5099 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
5100 $link = (string) $link;
5101 if ($link) {
5102 $e->reproductionlink = $link;
5104 if (!empty($debuginfo)) {
5105 $e->debuginfo = $debuginfo;
5107 if (!empty($backtrace)) {
5108 $e->stacktrace = format_backtrace($backtrace, true);
5111 $this->header();
5112 return json_encode($e);
5116 * Used to display a notification.
5117 * For the AJAX notifications are discarded.
5119 * @param string $message The message to print out.
5120 * @param string $type The type of notification. See constants on \core\output\notification.
5121 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5123 public function notification($message, $type = null, $closebutton = true) {
5127 * Used to display a redirection message.
5128 * AJAX redirections should not occur and as such redirection messages
5129 * are discarded.
5131 * @param moodle_url|string $encodedurl
5132 * @param string $message
5133 * @param int $delay
5134 * @param bool $debugdisableredirect
5135 * @param string $messagetype The type of notification to show the message in.
5136 * See constants on \core\output\notification.
5138 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
5139 $messagetype = \core\output\notification::NOTIFY_INFO) {}
5142 * Prepares the start of an AJAX output.
5144 public function header() {
5145 // unfortunately YUI iframe upload does not support application/json
5146 if (!empty($_FILES)) {
5147 @header('Content-type: text/plain; charset=utf-8');
5148 if (!core_useragent::supports_json_contenttype()) {
5149 @header('X-Content-Type-Options: nosniff');
5151 } else if (!core_useragent::supports_json_contenttype()) {
5152 @header('Content-type: text/plain; charset=utf-8');
5153 @header('X-Content-Type-Options: nosniff');
5154 } else {
5155 @header('Content-type: application/json; charset=utf-8');
5158 // Headers to make it not cacheable and json
5159 @header('Cache-Control: no-store, no-cache, must-revalidate');
5160 @header('Cache-Control: post-check=0, pre-check=0', false);
5161 @header('Pragma: no-cache');
5162 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
5163 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
5164 @header('Accept-Ranges: none');
5168 * There is no footer for an AJAX request, however we must override the
5169 * footer method to prevent the default footer.
5171 public function footer() {}
5174 * No need for headers in an AJAX request... this should never happen.
5175 * @param string $text
5176 * @param int $level
5177 * @param string $classes
5178 * @param string $id
5180 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
5186 * The maintenance renderer.
5188 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
5189 * is running a maintenance related task.
5190 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
5192 * @since Moodle 2.6
5193 * @package core
5194 * @category output
5195 * @copyright 2013 Sam Hemelryk
5196 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5198 class core_renderer_maintenance extends core_renderer {
5201 * Initialises the renderer instance.
5203 * @param moodle_page $page
5204 * @param string $target
5205 * @throws coding_exception
5207 public function __construct(moodle_page $page, $target) {
5208 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
5209 throw new coding_exception('Invalid request for the maintenance renderer.');
5211 parent::__construct($page, $target);
5215 * Does nothing. The maintenance renderer cannot produce blocks.
5217 * @param block_contents $bc
5218 * @param string $region
5219 * @return string
5221 public function block(block_contents $bc, $region) {
5222 return '';
5226 * Does nothing. The maintenance renderer cannot produce blocks.
5228 * @param string $region
5229 * @param array $classes
5230 * @param string $tag
5231 * @param boolean $fakeblocksonly
5232 * @return string
5234 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
5235 return '';
5239 * Does nothing. The maintenance renderer cannot produce blocks.
5241 * @param string $region
5242 * @param boolean $fakeblocksonly Output fake block only.
5243 * @return string
5245 public function blocks_for_region($region, $fakeblocksonly = false) {
5246 return '';
5250 * Does nothing. The maintenance renderer cannot produce a course content header.
5252 * @param bool $onlyifnotcalledbefore
5253 * @return string
5255 public function course_content_header($onlyifnotcalledbefore = false) {
5256 return '';
5260 * Does nothing. The maintenance renderer cannot produce a course content footer.
5262 * @param bool $onlyifnotcalledbefore
5263 * @return string
5265 public function course_content_footer($onlyifnotcalledbefore = false) {
5266 return '';
5270 * Does nothing. The maintenance renderer cannot produce a course header.
5272 * @return string
5274 public function course_header() {
5275 return '';
5279 * Does nothing. The maintenance renderer cannot produce a course footer.
5281 * @return string
5283 public function course_footer() {
5284 return '';
5288 * Does nothing. The maintenance renderer cannot produce a custom menu.
5290 * @param string $custommenuitems
5291 * @return string
5293 public function custom_menu($custommenuitems = '') {
5294 return '';
5298 * Does nothing. The maintenance renderer cannot produce a file picker.
5300 * @param array $options
5301 * @return string
5303 public function file_picker($options) {
5304 return '';
5308 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
5310 * @param array $dir
5311 * @return string
5313 public function htmllize_file_tree($dir) {
5314 return '';
5319 * Overridden confirm message for upgrades.
5321 * @param string $message The question to ask the user
5322 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5323 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5324 * @return string HTML fragment
5326 public function confirm($message, $continue, $cancel) {
5327 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5328 // from any previous version of Moodle).
5329 if ($continue instanceof single_button) {
5330 $continue->primary = true;
5331 } else if (is_string($continue)) {
5332 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
5333 } else if ($continue instanceof moodle_url) {
5334 $continue = new single_button($continue, get_string('continue'), 'post', true);
5335 } else {
5336 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5337 ' (string/moodle_url) or a single_button instance.');
5340 if ($cancel instanceof single_button) {
5341 $output = '';
5342 } else if (is_string($cancel)) {
5343 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5344 } else if ($cancel instanceof moodle_url) {
5345 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5346 } else {
5347 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5348 ' (string/moodle_url) or a single_button instance.');
5351 $output = $this->box_start('generalbox', 'notice');
5352 $output .= html_writer::tag('h4', get_string('confirm'));
5353 $output .= html_writer::tag('p', $message);
5354 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
5355 $output .= $this->box_end();
5356 return $output;
5360 * Does nothing. The maintenance renderer does not support JS.
5362 * @param block_contents $bc
5364 public function init_block_hider_js(block_contents $bc) {
5365 // Does nothing.
5369 * Does nothing. The maintenance renderer cannot produce language menus.
5371 * @return string
5373 public function lang_menu() {
5374 return '';
5378 * Does nothing. The maintenance renderer has no need for login information.
5380 * @param null $withlinks
5381 * @return string
5383 public function login_info($withlinks = null) {
5384 return '';
5388 * Secure login info.
5390 * @return string
5392 public function secure_login_info() {
5393 return $this->login_info(false);
5397 * Does nothing. The maintenance renderer cannot produce user pictures.
5399 * @param stdClass $user
5400 * @param array $options
5401 * @return string
5403 public function user_picture(stdClass $user, array $options = null) {
5404 return '';