MDL-81587 quiz: fix layout of the add/edit random UI
[moodle.git] / lib / outputrenderers.php
blobeadf44544d3694b57c357401a8b7f0c08efef766
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\di;
39 use core\hook\manager as hook_manager;
40 use core\hook\output\after_standard_main_region_html_generation;
41 use core\hook\output\before_footer_html_generation;
42 use core\hook\output\before_html_attributes;
43 use core\hook\output\before_http_headers;
44 use core\hook\output\before_standard_footer_html_generation;
45 use core\hook\output\before_standard_top_of_body_html_generation;
46 use core\output\named_templatable;
47 use core_completion\cm_completion_details;
48 use core_course\output\activity_information;
50 defined('MOODLE_INTERNAL') || die();
52 /**
53 * Simple base class for Moodle renderers.
55 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
57 * Also has methods to facilitate generating HTML output.
59 * @copyright 2009 Tim Hunt
60 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
61 * @since Moodle 2.0
62 * @package core
63 * @category output
65 class renderer_base {
66 /**
67 * @var xhtml_container_stack The xhtml_container_stack to use.
69 protected $opencontainers;
71 /**
72 * @var moodle_page The Moodle page the renderer has been created to assist with.
74 protected $page;
76 /**
77 * @var string The requested rendering target.
79 protected $target;
81 /**
82 * @var Mustache_Engine $mustache The mustache template compiler
84 private $mustache;
86 /**
87 * @var array $templatecache The mustache template cache.
89 protected $templatecache = [];
91 /**
92 * Return an instance of the mustache class.
94 * @since 2.9
95 * @return Mustache_Engine
97 protected function get_mustache() {
98 global $CFG;
100 if ($this->mustache === null) {
101 require_once("{$CFG->libdir}/filelib.php");
103 $themename = $this->page->theme->name;
104 $themerev = theme_get_revision();
106 // Create new localcache directory.
107 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
109 // Remove old localcache directories.
110 $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR);
111 foreach ($mustachecachedirs as $localcachedir) {
112 $cachedrev = [];
113 preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
114 $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
115 if ($cachedrev > 0 && $cachedrev < $themerev) {
116 fulldelete($localcachedir);
120 $loader = new \core\output\mustache_filesystem_loader();
121 $stringhelper = new \core\output\mustache_string_helper();
122 $cleanstringhelper = new \core\output\mustache_clean_string_helper();
123 $quotehelper = new \core\output\mustache_quote_helper();
124 $jshelper = new \core\output\mustache_javascript_helper($this->page);
125 $pixhelper = new \core\output\mustache_pix_helper($this);
126 $shortentexthelper = new \core\output\mustache_shorten_text_helper();
127 $userdatehelper = new \core\output\mustache_user_date_helper();
129 // We only expose the variables that are exposed to JS templates.
130 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
132 $helpers = array('config' => $safeconfig,
133 'str' => array($stringhelper, 'str'),
134 'cleanstr' => array($cleanstringhelper, 'cleanstr'),
135 'quote' => array($quotehelper, 'quote'),
136 'js' => array($jshelper, 'help'),
137 'pix' => array($pixhelper, 'pix'),
138 'shortentext' => array($shortentexthelper, 'shorten'),
139 'userdate' => array($userdatehelper, 'transform'),
142 $this->mustache = new \core\output\mustache_engine(array(
143 'cache' => $cachedir,
144 'escape' => 's',
145 'loader' => $loader,
146 'helpers' => $helpers,
147 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS],
148 // Don't allow the JavaScript helper to be executed from within another
149 // helper. If it's allowed it can be used by users to inject malicious
150 // JS into the page.
151 'disallowednestedhelpers' => ['js'],
152 // Disable lambda rendering - content in helpers is already rendered, no need to render it again.
153 'disable_lambda_rendering' => true,
158 return $this->mustache;
163 * Constructor
165 * The constructor takes two arguments. The first is the page that the renderer
166 * has been created to assist with, and the second is the target.
167 * The target is an additional identifier that can be used to load different
168 * renderers for different options.
170 * @param moodle_page $page the page we are doing output for.
171 * @param string $target one of rendering target constants
173 public function __construct(moodle_page $page, $target) {
174 $this->opencontainers = $page->opencontainers;
175 $this->page = $page;
176 $this->target = $target;
180 * Renders a template by name with the given context.
182 * The provided data needs to be array/stdClass made up of only simple types.
183 * Simple types are array,stdClass,bool,int,float,string
185 * @since 2.9
186 * @param array|stdClass $context Context containing data for the template.
187 * @return string|boolean
189 public function render_from_template($templatename, $context) {
190 $mustache = $this->get_mustache();
192 if ($mustache->hasHelper('uniqid')) {
193 // Grab a copy of the existing helper to be restored later.
194 $uniqidhelper = $mustache->getHelper('uniqid');
195 } else {
196 // Helper doesn't exist.
197 $uniqidhelper = null;
200 // Provide 1 random value that will not change within a template
201 // but will be different from template to template. This is useful for
202 // e.g. aria attributes that only work with id attributes and must be
203 // unique in a page.
204 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
205 if (isset($this->templatecache[$templatename])) {
206 $template = $this->templatecache[$templatename];
207 } else {
208 try {
209 $template = $mustache->loadTemplate($templatename);
210 $this->templatecache[$templatename] = $template;
211 } catch (Mustache_Exception_UnknownTemplateException $e) {
212 throw new moodle_exception('Unknown template: ' . $templatename);
216 $renderedtemplate = trim($template->render($context));
218 // If we had an existing uniqid helper then we need to restore it to allow
219 // handle nested calls of render_from_template.
220 if ($uniqidhelper) {
221 $mustache->addHelper('uniqid', $uniqidhelper);
224 return $renderedtemplate;
229 * Returns rendered widget.
231 * The provided widget needs to be an object that extends the renderable
232 * interface.
233 * If will then be rendered by a method based upon the classname for the widget.
234 * For instance a widget of class `crazywidget` will be rendered by a protected
235 * render_crazywidget method of this renderer.
236 * If no render_crazywidget method exists and crazywidget implements templatable,
237 * look for the 'crazywidget' template in the same component and render that.
239 * @param renderable $widget instance with renderable interface
240 * @return string
242 public function render(renderable $widget) {
243 $classparts = explode('\\', get_class($widget));
244 // Strip namespaces.
245 $classname = array_pop($classparts);
246 // Remove _renderable suffixes.
247 $classname = preg_replace('/_renderable$/', '', $classname);
249 $rendermethod = "render_{$classname}";
250 if (method_exists($this, $rendermethod)) {
251 // Call the render_[widget_name] function.
252 // Note: This has a higher priority than the named_templatable to allow the theme to override the template.
253 return $this->$rendermethod($widget);
256 if ($widget instanceof named_templatable) {
257 // This is a named templatable.
258 // Fetch the template name from the get_template_name function instead.
259 // Note: This has higher priority than the guessed template name.
260 return $this->render_from_template(
261 $widget->get_template_name($this),
262 $widget->export_for_template($this)
266 if ($widget instanceof templatable) {
267 // Guess the templat ename based on the class name.
268 // Note: There's no benefit to moving this aboved the named_templatable and this approach is more costly.
269 $component = array_shift($classparts);
270 if (!$component) {
271 $component = 'core';
273 $template = $component . '/' . $classname;
274 $context = $widget->export_for_template($this);
275 return $this->render_from_template($template, $context);
277 throw new coding_exception("Can not render widget, renderer method ('{$rendermethod}') not found.");
281 * Adds a JS action for the element with the provided id.
283 * This method adds a JS event for the provided component action to the page
284 * and then returns the id that the event has been attached to.
285 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
287 * @param component_action $action
288 * @param string $id
289 * @return string id of element, either original submitted or random new if not supplied
291 public function add_action_handler(component_action $action, $id = null) {
292 if (!$id) {
293 $id = html_writer::random_id($action->event);
295 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
296 return $id;
300 * Returns true is output has already started, and false if not.
302 * @return boolean true if the header has been printed.
304 public function has_started() {
305 return $this->page->state >= moodle_page::STATE_IN_BODY;
309 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
311 * @param mixed $classes Space-separated string or array of classes
312 * @return string HTML class attribute value
314 public static function prepare_classes($classes) {
315 if (is_array($classes)) {
316 return implode(' ', array_unique($classes));
318 return $classes;
322 * Return the direct URL for an image from the pix folder.
324 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
326 * @deprecated since Moodle 3.3
327 * @param string $imagename the name of the icon.
328 * @param string $component specification of one plugin like in get_string()
329 * @return moodle_url
331 public function pix_url($imagename, $component = 'moodle') {
332 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
333 return $this->page->theme->image_url($imagename, $component);
337 * Return the moodle_url for an image.
339 * The exact image location and extension is determined
340 * automatically by searching for gif|png|jpg|jpeg, please
341 * note there can not be diferent images with the different
342 * extension. The imagename is for historical reasons
343 * a relative path name, it may be changed later for core
344 * images. It is recommended to not use subdirectories
345 * in plugin and theme pix directories.
347 * There are three types of images:
348 * 1/ theme images - stored in theme/mytheme/pix/,
349 * use component 'theme'
350 * 2/ core images - stored in /pix/,
351 * overridden via theme/mytheme/pix_core/
352 * 3/ plugin images - stored in mod/mymodule/pix,
353 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
354 * example: image_url('comment', 'mod_glossary')
356 * @param string $imagename the pathname of the image
357 * @param string $component full plugin name (aka component) or 'theme'
358 * @return moodle_url
360 public function image_url($imagename, $component = 'moodle') {
361 return $this->page->theme->image_url($imagename, $component);
365 * Return the site's logo URL, if any.
367 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
368 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
369 * @return moodle_url|false
371 public function get_logo_url($maxwidth = null, $maxheight = 200) {
372 global $CFG;
373 $logo = get_config('core_admin', 'logo');
374 if (empty($logo)) {
375 return false;
378 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
379 // It's not worth the overhead of detecting and serving 2 different images based on the device.
381 // Hide the requested size in the file path.
382 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
384 // Use $CFG->themerev to prevent browser caching when the file changes.
385 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
386 theme_get_revision(), $logo);
390 * Return the site's compact logo URL, if any.
392 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
393 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
394 * @return moodle_url|false
396 public function get_compact_logo_url($maxwidth = 300, $maxheight = 300) {
397 global $CFG;
398 $logo = get_config('core_admin', 'logocompact');
399 if (empty($logo)) {
400 return false;
403 // Hide the requested size in the file path.
404 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
406 // Use $CFG->themerev to prevent browser caching when the file changes.
407 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
408 theme_get_revision(), $logo);
412 * Whether we should display the logo in the navbar.
414 * We will when there are no main logos, and we have compact logo.
416 * @return bool
418 public function should_display_navbar_logo() {
419 $logo = $this->get_compact_logo_url();
420 return !empty($logo);
424 * Whether we should display the main logo.
425 * @deprecated since Moodle 4.0
426 * @todo final deprecation. To be removed in Moodle 4.4 MDL-73165.
427 * @param int $headinglevel The heading level we want to check against.
428 * @return bool
430 public function should_display_main_logo($headinglevel = 1) {
431 debugging('should_display_main_logo() is deprecated and will be removed in Moodle 4.4.', DEBUG_DEVELOPER);
432 // Only render the logo if we're on the front page or login page and the we have a logo.
433 $logo = $this->get_logo_url();
434 if ($headinglevel == 1 && !empty($logo)) {
435 if ($this->page->pagelayout == 'frontpage' || $this->page->pagelayout == 'login') {
436 return true;
440 return false;
447 * Basis for all plugin renderers.
449 * @copyright Petr Skoda (skodak)
450 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
451 * @since Moodle 2.0
452 * @package core
453 * @category output
455 class plugin_renderer_base extends renderer_base {
458 * @var renderer_base|core_renderer A reference to the current renderer.
459 * The renderer provided here will be determined by the page but will in 90%
460 * of cases by the {@link core_renderer}
462 protected $output;
465 * Constructor method, calls the parent constructor
467 * @param moodle_page $page
468 * @param string $target one of rendering target constants
470 public function __construct(moodle_page $page, $target) {
471 if (empty($target) && $page->pagelayout === 'maintenance') {
472 // If the page is using the maintenance layout then we're going to force the target to maintenance.
473 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
474 // unavailable for this page layout.
475 $target = RENDERER_TARGET_MAINTENANCE;
477 $this->output = $page->get_renderer('core', null, $target);
478 parent::__construct($page, $target);
482 * Renders the provided widget and returns the HTML to display it.
484 * @param renderable $widget instance with renderable interface
485 * @return string
487 public function render(renderable $widget) {
488 $classname = get_class($widget);
490 // Strip namespaces.
491 $classname = preg_replace('/^.*\\\/', '', $classname);
493 // Keep a copy at this point, we may need to look for a deprecated method.
494 $deprecatedmethod = "render_{$classname}";
496 // Remove _renderable suffixes.
497 $classname = preg_replace('/_renderable$/', '', $classname);
498 $rendermethod = "render_{$classname}";
500 if (method_exists($this, $rendermethod)) {
501 // Call the render_[widget_name] function.
502 // Note: This has a higher priority than the named_templatable to allow the theme to override the template.
503 return $this->$rendermethod($widget);
506 if ($widget instanceof named_templatable) {
507 // This is a named templatable.
508 // Fetch the template name from the get_template_name function instead.
509 // Note: This has higher priority than the deprecated method which is not overridable by themes anyway.
510 return $this->render_from_template(
511 $widget->get_template_name($this),
512 $widget->export_for_template($this)
516 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
517 // This is exactly where we don't want to be.
518 // If you have arrived here you have a renderable component within your plugin that has the name
519 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
520 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
521 // and the _renderable suffix now gets removed when looking for a render method.
522 // You need to change your renderers render_blah_renderable to render_blah.
523 // Until you do this it will not be possible for a theme to override the renderer to override your method.
524 // Please do it ASAP.
525 static $debugged = [];
526 if (!isset($debugged[$deprecatedmethod])) {
527 debugging(sprintf(
528 'Deprecated call. Please rename your renderables render method from %s to %s.',
529 $deprecatedmethod,
530 $rendermethod
531 ), DEBUG_DEVELOPER);
532 $debugged[$deprecatedmethod] = true;
534 return $this->$deprecatedmethod($widget);
537 // Pass to core renderer if method not found here.
538 // Note: this is not a parent. This is _new_ renderer which respects the requested format, and output type.
539 return $this->output->render($widget);
543 * Magic method used to pass calls otherwise meant for the standard renderer
544 * to it to ensure we don't go causing unnecessary grief.
546 * @param string $method
547 * @param array $arguments
548 * @return mixed
550 public function __call($method, $arguments) {
551 if (method_exists('renderer_base', $method)) {
552 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
554 if (method_exists($this->output, $method)) {
555 return call_user_func_array(array($this->output, $method), $arguments);
556 } else {
557 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
564 * The standard implementation of the core_renderer interface.
566 * @copyright 2009 Tim Hunt
567 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
568 * @since Moodle 2.0
569 * @package core
570 * @category output
572 class core_renderer extends renderer_base {
574 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
575 * in layout files instead.
576 * @deprecated
577 * @var string used in {@link core_renderer::header()}.
579 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
582 * @var string Used to pass information from {@link core_renderer::doctype()} to
583 * {@link core_renderer::standard_head_html()}.
585 protected $contenttype;
588 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
589 * with {@link core_renderer::header()}.
591 protected $metarefreshtag = '';
594 * @var string Unique token for the closing HTML
596 protected $unique_end_html_token;
599 * @var string Unique token for performance information
601 protected $unique_performance_info_token;
604 * @var string Unique token for the main content.
606 protected $unique_main_content_token;
608 /** @var custom_menu_item language The language menu if created */
609 protected $language = null;
611 /** @var string The current selector for an element being streamed into */
612 protected $currentselector = '';
614 /** @var string The current element tag which is being streamed into */
615 protected $currentelement = '';
618 * Constructor
620 * @param moodle_page $page the page we are doing output for.
621 * @param string $target one of rendering target constants
623 public function __construct(moodle_page $page, $target) {
624 $this->opencontainers = $page->opencontainers;
625 $this->page = $page;
626 $this->target = $target;
628 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
629 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
630 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
634 * Get the DOCTYPE declaration that should be used with this page. Designed to
635 * be called in theme layout.php files.
637 * @return string the DOCTYPE declaration that should be used.
639 public function doctype() {
640 if ($this->page->theme->doctype === 'html5') {
641 $this->contenttype = 'text/html; charset=utf-8';
642 return "<!DOCTYPE html>\n";
644 } else if ($this->page->theme->doctype === 'xhtml5') {
645 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
646 return "<!DOCTYPE html>\n";
648 } else {
649 // legacy xhtml 1.0
650 $this->contenttype = 'text/html; charset=utf-8';
651 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
656 * The attributes that should be added to the <html> tag. Designed to
657 * be called in theme layout.php files.
659 * @return string HTML fragment.
661 public function htmlattributes() {
662 $return = get_html_lang(true);
664 // Ensure that the callback exists prior to cache purge.
665 // This is a critical page path.
666 // TODO MDL-81134 Remove after LTS+1.
667 require_once(__DIR__ . '/classes/hook/output/before_html_attributes.php');
669 $hook = new before_html_attributes($this);
671 if ($this->page->theme->doctype !== 'html5') {
672 $hook->add_attribute('xmlns', 'http://www.w3.org/1999/xhtml');
675 $hook->process_legacy_callbacks();
676 di::get(hook_manager::class)->dispatch($hook);
678 foreach ($hook->get_attributes() as $key => $val) {
679 $val = s($val);
680 $return .= " $key=\"$val\"";
683 return $return;
687 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
688 * that should be included in the <head> tag. Designed to be called in theme
689 * layout.php files.
691 * @return string HTML fragment.
693 public function standard_head_html() {
694 global $CFG, $SESSION, $SITE;
696 // Before we output any content, we need to ensure that certain
697 // page components are set up.
699 // Blocks must be set up early as they may require javascript which
700 // has to be included in the page header before output is created.
701 foreach ($this->page->blocks->get_regions() as $region) {
702 $this->page->blocks->ensure_content_created($region, $this);
705 // Give plugins an opportunity to add any head elements. The callback
706 // must always return a string containing valid html head content.
708 $hook = new \core\hook\output\before_standard_head_html_generation($this);
709 $hook->process_legacy_callbacks();
710 di::get(hook_manager::class)->dispatch($hook);
712 // Allow a url_rewrite plugin to setup any dynamic head content.
713 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
714 $class = $CFG->urlrewriteclass;
715 $hook->add_html($class::html_head_setup());
718 $hook->add_html('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n");
719 $hook->add_html('<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n");
720 // This is only set by the {@link redirect()} method
721 $hook->add_html($this->metarefreshtag);
723 // Check if a periodic refresh delay has been set and make sure we arn't
724 // already meta refreshing
725 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
726 $hook->add_html(
727 html_writer::empty_tag('meta', [
728 'http-equiv' => 'refresh',
729 'content' => $this->page->periodicrefreshdelay . ';url='.$this->page->url->out(),
734 $output = $hook->get_output();
736 // Set up help link popups for all links with the helptooltip class
737 $this->page->requires->js_init_call('M.util.help_popups.setup');
739 $focus = $this->page->focuscontrol;
740 if (!empty($focus)) {
741 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
742 // This is a horrifically bad way to handle focus but it is passed in
743 // through messy formslib::moodleform
744 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
745 } else if (strpos($focus, '.')!==false) {
746 // Old style of focus, bad way to do it
747 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);
748 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
749 } else {
750 // Focus element with given id
751 $this->page->requires->js_function_call('focuscontrol', array($focus));
755 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
756 // any other custom CSS can not be overridden via themes and is highly discouraged
757 $urls = $this->page->theme->css_urls($this->page);
758 foreach ($urls as $url) {
759 $this->page->requires->css_theme($url);
762 // Get the theme javascript head and footer
763 if ($jsurl = $this->page->theme->javascript_url(true)) {
764 $this->page->requires->js($jsurl, true);
766 if ($jsurl = $this->page->theme->javascript_url(false)) {
767 $this->page->requires->js($jsurl);
770 // Get any HTML from the page_requirements_manager.
771 $output .= $this->page->requires->get_head_code($this->page, $this);
773 // List alternate versions.
774 foreach ($this->page->alternateversions as $type => $alt) {
775 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
776 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
779 // Add noindex tag if relevant page and setting applied.
780 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
781 $loginpages = array('login-index', 'login-signup');
782 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
783 if (!isset($CFG->additionalhtmlhead)) {
784 $CFG->additionalhtmlhead = '';
786 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
789 if (!empty($CFG->additionalhtmlhead)) {
790 $output .= "\n".$CFG->additionalhtmlhead;
793 if ($this->page->pagelayout == 'frontpage') {
794 $summary = s(strip_tags(format_text($SITE->summary, FORMAT_HTML)));
795 if (!empty($summary)) {
796 $output .= "<meta name=\"description\" content=\"$summary\" />\n";
800 return $output;
804 * The standard tags (typically skip links) that should be output just inside
805 * the start of the <body> tag. Designed to be called in theme layout.php files.
807 * @return string HTML fragment.
809 public function standard_top_of_body_html() {
810 global $CFG;
811 $output = $this->page->requires->get_top_of_body_code($this);
812 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
813 $output .= "\n".$CFG->additionalhtmltopofbody;
816 // Ensure that the callback exists prior to cache purge.
817 // This is a critical page path.
818 // TODO MDL-81134 Remove after LTS+1.
819 require_once(__DIR__ . '/classes/hook/output/before_standard_top_of_body_html_generation.php');
821 // Allow components to add content to the top of the body.
822 $hook = new before_standard_top_of_body_html_generation($this, $output);
823 $hook->process_legacy_callbacks();
824 di::get(hook_manager::class)->dispatch($hook);
825 $output = $hook->get_output();
827 $output .= $this->maintenance_warning();
829 return $output;
833 * Scheduled maintenance warning message.
835 * Note: This is a nasty hack to display maintenance notice, this should be moved
836 * to some general notification area once we have it.
838 * @return string
840 public function maintenance_warning() {
841 global $CFG;
843 $output = '';
844 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
845 $timeleft = $CFG->maintenance_later - time();
846 // If timeleft less than 30 sec, set the class on block to error to highlight.
847 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
848 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-3 alert');
849 $a = new stdClass();
850 $a->hour = (int)($timeleft / 3600);
851 $a->min = (int)(floor($timeleft / 60) % 60);
852 $a->sec = (int)($timeleft % 60);
853 if ($a->hour > 0) {
854 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
855 } else {
856 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
859 $output .= $this->box_end();
860 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
861 array(array('timeleftinsec' => $timeleft)));
862 $this->page->requires->strings_for_js(
863 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
864 'admin');
866 return $output;
870 * content that should be output in the footer area
871 * of the page. Designed to be called in theme layout.php files.
873 * @return string HTML fragment.
875 public function standard_footer_html() {
876 if (during_initial_install()) {
877 // Debugging info can not work before install is finished,
878 // in any case we do not want any links during installation!
879 return '';
882 // Ensure that the callback exists prior to cache purge.
883 // This is a critical page path.
884 // TODO MDL-81134 Remove after LTS+1.
885 require_once(__DIR__ . '/classes/hook/output/before_standard_footer_html_generation.php');
887 $hook = new before_standard_footer_html_generation($this);
888 $hook->process_legacy_callbacks();
889 di::get(hook_manager::class)->dispatch($hook);
890 $output = $hook->get_output();
892 if ($this->page->devicetypeinuse == 'legacy') {
893 // The legacy theme is in use print the notification
894 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
897 // Get links to switch device types (only shown for users not on a default device)
898 $output .= $this->theme_switch_links();
900 return $output;
904 * Performance information and validation links for debugging.
906 * @return string HTML fragment.
908 public function debug_footer_html() {
909 global $CFG, $SCRIPT;
910 $output = '';
912 if (during_initial_install()) {
913 // Debugging info can not work before install is finished.
914 return $output;
917 // This function is normally called from a layout.php file
918 // but some of the content won't be known until later, so we return a placeholder
919 // for now. This will be replaced with the real content in the footer.
920 $output .= $this->unique_performance_info_token;
922 if (!empty($CFG->debugpageinfo)) {
923 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
924 $this->page->debug_summary()) . '</div>';
926 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
928 // Add link to profiling report if necessary
929 if (function_exists('profiling_is_running') && profiling_is_running()) {
930 $txt = get_string('profiledscript', 'admin');
931 $title = get_string('profiledscriptview', 'admin');
932 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
933 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
934 $output .= '<div class="profilingfooter">' . $link . '</div>';
936 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
937 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
938 $output .= '<div class="purgecaches">' .
939 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
941 // Reactive module debug panel.
942 $output .= $this->render_from_template('core/local/reactive/debugpanel', []);
944 if (!empty($CFG->debugvalidators)) {
945 $siteurl = qualified_me();
946 $nuurl = new moodle_url('https://validator.w3.org/nu/', ['doc' => $siteurl, 'showsource' => 'yes']);
947 $waveurl = new moodle_url('https://wave.webaim.org/report#/' . urlencode($siteurl));
948 $validatorlinks = [
949 html_writer::link($nuurl, get_string('validatehtml')),
950 html_writer::link($waveurl, get_string('wcagcheck'))
952 $validatorlinkslist = html_writer::alist($validatorlinks, ['class' => 'list-unstyled ml-1']);
953 $output .= html_writer::div($validatorlinkslist, 'validators');
955 return $output;
959 * Returns standard main content placeholder.
960 * Designed to be called in theme layout.php files.
962 * @return string HTML fragment.
964 public function main_content() {
965 // This is here because it is the only place we can inject the "main" role over the entire main content area
966 // without requiring all theme's to manually do it, and without creating yet another thing people need to
967 // remember in the theme.
968 // This is an unfortunate hack. DO NO EVER add anything more here.
969 // DO NOT add classes.
970 // DO NOT add an id.
971 return '<div role="main">'.$this->unique_main_content_token.'</div>';
975 * Returns information about an activity.
977 * @deprecated since Moodle 4.3 MDL-78744
978 * @todo MDL-78926 This method will be deleted in Moodle 4.7
979 * @param cm_info $cminfo The course module information.
980 * @param cm_completion_details $completiondetails The completion details for this activity module.
981 * @param array $activitydates The dates for this activity module.
982 * @return string the activity information HTML.
983 * @throws coding_exception
985 public function activity_information(cm_info $cminfo, cm_completion_details $completiondetails, array $activitydates): string {
986 debugging('activity_information method is deprecated.', DEBUG_DEVELOPER);
987 if (!$completiondetails->has_completion() && empty($activitydates)) {
988 // No need to render the activity information when there's no completion info and activity dates to show.
989 return '';
991 $activityinfo = new activity_information($cminfo, $completiondetails, $activitydates);
992 $renderer = $this->page->get_renderer('core', 'course');
993 return $renderer->render($activityinfo);
997 * Returns standard navigation between activities in a course.
999 * @return string the navigation HTML.
1001 public function activity_navigation() {
1002 // First we should check if we want to add navigation.
1003 $context = $this->page->context;
1004 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
1005 || $context->contextlevel != CONTEXT_MODULE) {
1006 return '';
1009 // If the activity is in stealth mode, show no links.
1010 if ($this->page->cm->is_stealth()) {
1011 return '';
1014 $course = $this->page->cm->get_course();
1015 $courseformat = course_get_format($course);
1017 // If the theme implements course index and the current course format uses course index and the current
1018 // page layout is not 'frametop' (this layout does not support course index), show no links.
1019 if ($this->page->theme->usescourseindex && $courseformat->uses_course_index() &&
1020 $this->page->pagelayout !== 'frametop') {
1021 return '';
1024 // Get a list of all the activities in the course.
1025 $modules = get_fast_modinfo($course->id)->get_cms();
1027 // Put the modules into an array in order by the position they are shown in the course.
1028 $mods = [];
1029 $activitylist = [];
1030 foreach ($modules as $module) {
1031 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
1032 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
1033 continue;
1035 $mods[$module->id] = $module;
1037 // No need to add the current module to the list for the activity dropdown menu.
1038 if ($module->id == $this->page->cm->id) {
1039 continue;
1041 // Module name.
1042 $modname = $module->get_formatted_name();
1043 // Display the hidden text if necessary.
1044 if (!$module->visible) {
1045 $modname .= ' ' . get_string('hiddenwithbrackets');
1047 // Module URL.
1048 $linkurl = new moodle_url($module->url, array('forceview' => 1));
1049 // Add module URL (as key) and name (as value) to the activity list array.
1050 $activitylist[$linkurl->out(false)] = $modname;
1053 $nummods = count($mods);
1055 // If there is only one mod then do nothing.
1056 if ($nummods == 1) {
1057 return '';
1060 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
1061 $modids = array_keys($mods);
1063 // Get the position in the array of the course module we are viewing.
1064 $position = array_search($this->page->cm->id, $modids);
1066 $prevmod = null;
1067 $nextmod = null;
1069 // Check if we have a previous mod to show.
1070 if ($position > 0) {
1071 $prevmod = $mods[$modids[$position - 1]];
1074 // Check if we have a next mod to show.
1075 if ($position < ($nummods - 1)) {
1076 $nextmod = $mods[$modids[$position + 1]];
1079 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
1080 $renderer = $this->page->get_renderer('core', 'course');
1081 return $renderer->render($activitynav);
1085 * The standard tags (typically script tags that are not needed earlier) that
1086 * should be output after everything else. Designed to be called in theme layout.php files.
1088 * @return string HTML fragment.
1090 public function standard_end_of_body_html() {
1091 global $CFG;
1093 // This function is normally called from a layout.php file in {@link core_renderer::header()}
1094 // but some of the content won't be known until later, so we return a placeholder
1095 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
1096 $output = '';
1097 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
1098 $output .= "\n".$CFG->additionalhtmlfooter;
1100 $output .= $this->unique_end_html_token;
1101 return $output;
1105 * The standard HTML that should be output just before the <footer> tag.
1106 * Designed to be called in theme layout.php files.
1108 * @return string HTML fragment.
1110 public function standard_after_main_region_html() {
1111 global $CFG;
1113 // Ensure that the callback exists prior to cache purge.
1114 // This is a critical page path.
1115 // TODO MDL-81134 Remove after LTS+1.
1116 require_once(__DIR__ . '/classes/hook/output/after_standard_main_region_html_generation.php');
1118 $hook = new after_standard_main_region_html_generation($this);
1120 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlbottomofbody)) {
1121 $hook->add_html("\n");
1122 $hook->add_html($CFG->additionalhtmlbottomofbody);
1125 $hook->process_legacy_callbacks();
1126 di::get(hook_manager::class)->dispatch($hook);
1128 return $hook->get_output();
1132 * Return the standard string that says whether you are logged in (and switched
1133 * roles/logged in as another user).
1134 * @param bool $withlinks if false, then don't include any links in the HTML produced.
1135 * If not set, the default is the nologinlinks option from the theme config.php file,
1136 * and if that is not set, then links are included.
1137 * @return string HTML fragment.
1139 public function login_info($withlinks = null) {
1140 global $USER, $CFG, $DB, $SESSION;
1142 if (during_initial_install()) {
1143 return '';
1146 if (is_null($withlinks)) {
1147 $withlinks = empty($this->page->layout_options['nologinlinks']);
1150 $course = $this->page->course;
1151 if (\core\session\manager::is_loggedinas()) {
1152 $realuser = \core\session\manager::get_realuser();
1153 $fullname = fullname($realuser);
1154 if ($withlinks) {
1155 $loginastitle = get_string('loginas');
1156 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
1157 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
1158 } else {
1159 $realuserinfo = " [$fullname] ";
1161 } else {
1162 $realuserinfo = '';
1165 $loginpage = $this->is_login_page();
1166 $loginurl = get_login_url();
1168 if (empty($course->id)) {
1169 // $course->id is not defined during installation
1170 return '';
1171 } else if (isloggedin()) {
1172 $context = context_course::instance($course->id);
1174 $fullname = fullname($USER);
1175 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
1176 if ($withlinks) {
1177 $linktitle = get_string('viewprofile');
1178 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
1179 } else {
1180 $username = $fullname;
1182 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
1183 if ($withlinks) {
1184 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1185 } else {
1186 $username .= " from {$idprovider->name}";
1189 if (isguestuser()) {
1190 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1191 if (!$loginpage && $withlinks) {
1192 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1194 } else if (is_role_switched($course->id)) { // Has switched roles
1195 $rolename = '';
1196 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1197 $rolename = ': '.role_get_name($role, $context);
1199 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1200 if ($withlinks) {
1201 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1202 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1204 } else {
1205 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1206 if ($withlinks) {
1207 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1210 } else {
1211 $loggedinas = get_string('loggedinnot', 'moodle');
1212 if (!$loginpage && $withlinks) {
1213 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1217 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1219 if (isset($SESSION->justloggedin)) {
1220 unset($SESSION->justloggedin);
1221 if (!isguestuser()) {
1222 // Include this file only when required.
1223 require_once($CFG->dirroot . '/user/lib.php');
1224 if (($count = user_count_login_failures($USER)) && !empty($CFG->displayloginfailures)) {
1225 $loggedinas .= '<div class="loginfailures">';
1226 $a = new stdClass();
1227 $a->attempts = $count;
1228 $loggedinas .= get_string('failedloginattempts', '', $a);
1229 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1230 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1231 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1233 $loggedinas .= '</div>';
1238 return $loggedinas;
1242 * Check whether the current page is a login page.
1244 * @since Moodle 2.9
1245 * @return bool
1247 protected function is_login_page() {
1248 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1249 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1250 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1251 return in_array(
1252 $this->page->url->out_as_local_url(false, array()),
1253 array(
1254 '/login/index.php',
1255 '/login/forgot_password.php',
1261 * Return the 'back' link that normally appears in the footer.
1263 * @return string HTML fragment.
1265 public function home_link() {
1266 global $CFG, $SITE;
1268 if ($this->page->pagetype == 'site-index') {
1269 // Special case for site home page - please do not remove
1270 return '<div class="sitelink">' .
1271 '<a title="Moodle" class="d-inline-block aalink" href="http://moodle.org/">' .
1272 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1274 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1275 // Special case for during install/upgrade.
1276 return '<div class="sitelink">'.
1277 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1278 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1280 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1281 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1282 get_string('home') . '</a></div>';
1284 } else {
1285 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1286 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1291 * Redirects the user by any means possible given the current state
1293 * This function should not be called directly, it should always be called using
1294 * the redirect function in lib/weblib.php
1296 * The redirect function should really only be called before page output has started
1297 * however it will allow itself to be called during the state STATE_IN_BODY
1299 * @param string $encodedurl The URL to send to encoded if required
1300 * @param string $message The message to display to the user if any
1301 * @param int $delay The delay before redirecting a user, if $message has been
1302 * set this is a requirement and defaults to 3, set to 0 no delay
1303 * @param boolean $debugdisableredirect this redirect has been disabled for
1304 * debugging purposes. Display a message that explains, and don't
1305 * trigger the redirect.
1306 * @param string $messagetype The type of notification to show the message in.
1307 * See constants on \core\output\notification.
1308 * @return string The HTML to display to the user before dying, may contain
1309 * meta refresh, javascript refresh, and may have set header redirects
1311 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1312 $messagetype = \core\output\notification::NOTIFY_INFO) {
1313 global $CFG;
1314 $url = str_replace('&amp;', '&', $encodedurl);
1316 switch ($this->page->state) {
1317 case moodle_page::STATE_BEFORE_HEADER :
1318 // No output yet it is safe to delivery the full arsenal of redirect methods
1319 if (!$debugdisableredirect) {
1320 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1321 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1322 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1324 $output = $this->header();
1325 break;
1326 case moodle_page::STATE_PRINTING_HEADER :
1327 // We should hopefully never get here
1328 throw new coding_exception('You cannot redirect while printing the page header');
1329 break;
1330 case moodle_page::STATE_IN_BODY :
1331 // We really shouldn't be here but we can deal with this
1332 debugging("You should really redirect before you start page output");
1333 if (!$debugdisableredirect) {
1334 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1336 $output = $this->opencontainers->pop_all_but_last();
1337 break;
1338 case moodle_page::STATE_DONE :
1339 // Too late to be calling redirect now
1340 throw new coding_exception('You cannot redirect after the entire page has been generated');
1341 break;
1343 $output .= $this->notification($message, $messagetype);
1344 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1345 if ($debugdisableredirect) {
1346 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1348 $output .= $this->footer();
1349 return $output;
1353 * Start output by sending the HTTP headers, and printing the HTML <head>
1354 * and the start of the <body>.
1356 * To control what is printed, you should set properties on $PAGE.
1358 * @return string HTML that you must output this, preferably immediately.
1360 public function header() {
1361 global $USER, $CFG, $SESSION;
1363 // Ensure that the callback exists prior to cache purge.
1364 // This is a critical page path.
1365 // TODO MDL-81134 Remove after LTS+1.
1366 require_once(__DIR__ . '/classes/hook/output/before_http_headers.php');
1368 $hook = new before_http_headers($this);
1369 $hook->process_legacy_callbacks();
1370 di::get(hook_manager::class)->dispatch($hook);
1372 if (\core\session\manager::is_loggedinas()) {
1373 $this->page->add_body_class('userloggedinas');
1376 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1377 require_once($CFG->dirroot . '/user/lib.php');
1378 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1379 if ($count = user_count_login_failures($USER, false)) {
1380 $this->page->add_body_class('loginfailures');
1384 // If the user is logged in, and we're not in initial install,
1385 // check to see if the user is role-switched and add the appropriate
1386 // CSS class to the body element.
1387 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1388 $this->page->add_body_class('userswitchedrole');
1391 // Give themes a chance to init/alter the page object.
1392 $this->page->theme->init_page($this->page);
1394 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1396 // Find the appropriate page layout file, based on $this->page->pagelayout.
1397 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1398 // Render the layout using the layout file.
1399 $rendered = $this->render_page_layout($layoutfile);
1401 // Slice the rendered output into header and footer.
1402 $cutpos = strpos($rendered, $this->unique_main_content_token);
1403 if ($cutpos === false) {
1404 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1405 $token = self::MAIN_CONTENT_TOKEN;
1406 } else {
1407 $token = $this->unique_main_content_token;
1410 if ($cutpos === false) {
1411 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.');
1414 $header = substr($rendered, 0, $cutpos);
1415 $footer = substr($rendered, $cutpos + strlen($token));
1417 if (empty($this->contenttype)) {
1418 debugging('The page layout file did not call $OUTPUT->doctype()');
1419 $header = $this->doctype() . $header;
1422 // If this theme version is below 2.4 release and this is a course view page
1423 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1424 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1425 // check if course content header/footer have not been output during render of theme layout
1426 $coursecontentheader = $this->course_content_header(true);
1427 $coursecontentfooter = $this->course_content_footer(true);
1428 if (!empty($coursecontentheader)) {
1429 // display debug message and add header and footer right above and below main content
1430 // Please note that course header and footer (to be displayed above and below the whole page)
1431 // are not displayed in this case at all.
1432 // Besides the content header and footer are not displayed on any other course page
1433 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);
1434 $header .= $coursecontentheader;
1435 $footer = $coursecontentfooter. $footer;
1439 send_headers($this->contenttype, $this->page->cacheable);
1441 $this->opencontainers->push('header/footer', $footer);
1442 $this->page->set_state(moodle_page::STATE_IN_BODY);
1444 // If an activity record has been set, activity_header will handle this.
1445 if (!$this->page->cm || !empty($this->page->layout_options['noactivityheader'])) {
1446 $header .= $this->skip_link_target('maincontent');
1448 return $header;
1452 * Renders and outputs the page layout file.
1454 * This is done by preparing the normal globals available to a script, and
1455 * then including the layout file provided by the current theme for the
1456 * requested layout.
1458 * @param string $layoutfile The name of the layout file
1459 * @return string HTML code
1461 protected function render_page_layout($layoutfile) {
1462 global $CFG, $SITE, $USER;
1463 // The next lines are a bit tricky. The point is, here we are in a method
1464 // of a renderer class, and this object may, or may not, be the same as
1465 // the global $OUTPUT object. When rendering the page layout file, we want to use
1466 // this object. However, people writing Moodle code expect the current
1467 // renderer to be called $OUTPUT, not $this, so define a variable called
1468 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1469 $OUTPUT = $this;
1470 $PAGE = $this->page;
1471 $COURSE = $this->page->course;
1473 ob_start();
1474 include($layoutfile);
1475 $rendered = ob_get_contents();
1476 ob_end_clean();
1477 return $rendered;
1481 * Outputs the page's footer
1483 * @return string HTML fragment
1485 public function footer() {
1486 global $CFG, $DB, $PERF;
1488 // Ensure that the callback exists prior to cache purge.
1489 // This is a critical page path.
1490 // TODO MDL-81134 Remove after LTS+1.
1491 require_once(__DIR__ . '/classes/hook/output/before_footer_html_generation.php');
1493 $hook = new before_footer_html_generation($this);
1494 $hook->process_legacy_callbacks();
1495 di::get(hook_manager::class)->dispatch($hook);
1496 $hook->add_html($this->container_end_all(true));
1497 $output = $hook->get_output();
1499 $footer = $this->opencontainers->pop('header/footer');
1501 if (debugging() and $DB and $DB->is_transaction_started()) {
1502 // TODO: MDL-20625 print warning - transaction will be rolled back
1505 // Provide some performance info if required
1506 $performanceinfo = '';
1507 if (MDL_PERF || (!empty($CFG->perfdebug) && $CFG->perfdebug > 7)) {
1508 if (MDL_PERFTOFOOT || debugging() || (!empty($CFG->perfdebug) && $CFG->perfdebug > 7)) {
1509 if (NO_OUTPUT_BUFFERING) {
1510 // If the output buffer was off then we render a placeholder and stream the
1511 // performance debugging into it at the very end in the shutdown handler.
1512 $PERF->perfdebugdeferred = true;
1513 $performanceinfo .= html_writer::tag('div',
1514 get_string('perfdebugdeferred', 'admin'),
1516 'id' => 'perfdebugfooter',
1517 'style' => 'min-height: 30em',
1519 } else {
1520 $perf = get_performance_info();
1521 $performanceinfo = $perf['html'];
1526 // We always want performance data when running a performance test, even if the user is redirected to another page.
1527 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1528 $footer = $this->unique_performance_info_token . $footer;
1530 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1532 // Only show notifications when the current page has a context id.
1533 if (!empty($this->page->context->id)) {
1534 $this->page->requires->js_call_amd('core/notification', 'init', array(
1535 $this->page->context->id,
1536 \core\notification::fetch_as_array($this)
1539 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1541 $this->page->set_state(moodle_page::STATE_DONE);
1543 // Here we remove the closing body and html tags and store them to be added back
1544 // in the shutdown handler so we can have valid html with streaming script tags
1545 // which are rendered after the visible footer.
1546 $tags = '';
1547 preg_match('#\<\/body>#i', $footer, $matches);
1548 $tags .= $matches[0];
1549 $footer = str_replace($matches[0], '', $footer);
1551 preg_match('#\<\/html>#i', $footer, $matches);
1552 $tags .= $matches[0];
1553 $footer = str_replace($matches[0], '', $footer);
1555 $CFG->closingtags = $tags;
1557 return $output . $footer;
1561 * Close all but the last open container. This is useful in places like error
1562 * handling, where you want to close all the open containers (apart from <body>)
1563 * before outputting the error message.
1565 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1566 * developer debug warning if it isn't.
1567 * @return string the HTML required to close any open containers inside <body>.
1569 public function container_end_all($shouldbenone = false) {
1570 return $this->opencontainers->pop_all_but_last($shouldbenone);
1574 * Returns course-specific information to be output immediately above content on any course page
1575 * (for the current course)
1577 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1578 * @return string
1580 public function course_content_header($onlyifnotcalledbefore = false) {
1581 global $CFG;
1582 static $functioncalled = false;
1583 if ($functioncalled && $onlyifnotcalledbefore) {
1584 // we have already output the content header
1585 return '';
1588 // Output any session notification.
1589 $notifications = \core\notification::fetch();
1591 $bodynotifications = '';
1592 foreach ($notifications as $notification) {
1593 $bodynotifications .= $this->render_from_template(
1594 $notification->get_template_name(),
1595 $notification->export_for_template($this)
1599 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1601 if ($this->page->course->id == SITEID) {
1602 // return immediately and do not include /course/lib.php if not necessary
1603 return $output;
1606 require_once($CFG->dirroot.'/course/lib.php');
1607 $functioncalled = true;
1608 $courseformat = course_get_format($this->page->course);
1609 if (($obj = $courseformat->course_content_header()) !== null) {
1610 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1612 return $output;
1616 * Returns course-specific information to be output immediately below content on any course page
1617 * (for the current course)
1619 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1620 * @return string
1622 public function course_content_footer($onlyifnotcalledbefore = false) {
1623 global $CFG;
1624 if ($this->page->course->id == SITEID) {
1625 // return immediately and do not include /course/lib.php if not necessary
1626 return '';
1628 static $functioncalled = false;
1629 if ($functioncalled && $onlyifnotcalledbefore) {
1630 // we have already output the content footer
1631 return '';
1633 $functioncalled = true;
1634 require_once($CFG->dirroot.'/course/lib.php');
1635 $courseformat = course_get_format($this->page->course);
1636 if (($obj = $courseformat->course_content_footer()) !== null) {
1637 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1639 return '';
1643 * Returns course-specific information to be output on any course page in the header area
1644 * (for the current course)
1646 * @return string
1648 public function course_header() {
1649 global $CFG;
1650 if ($this->page->course->id == SITEID) {
1651 // return immediately and do not include /course/lib.php if not necessary
1652 return '';
1654 require_once($CFG->dirroot.'/course/lib.php');
1655 $courseformat = course_get_format($this->page->course);
1656 if (($obj = $courseformat->course_header()) !== null) {
1657 return $courseformat->get_renderer($this->page)->render($obj);
1659 return '';
1663 * Returns course-specific information to be output on any course page in the footer area
1664 * (for the current course)
1666 * @return string
1668 public function course_footer() {
1669 global $CFG;
1670 if ($this->page->course->id == SITEID) {
1671 // return immediately and do not include /course/lib.php if not necessary
1672 return '';
1674 require_once($CFG->dirroot.'/course/lib.php');
1675 $courseformat = course_get_format($this->page->course);
1676 if (($obj = $courseformat->course_footer()) !== null) {
1677 return $courseformat->get_renderer($this->page)->render($obj);
1679 return '';
1683 * Get the course pattern datauri to show on a course card.
1685 * The datauri is an encoded svg that can be passed as a url.
1686 * @param int $id Id to use when generating the pattern
1687 * @return string datauri
1689 public function get_generated_image_for_id($id) {
1690 $color = $this->get_generated_color_for_id($id);
1691 $pattern = new \core_geopattern();
1692 $pattern->setColor($color);
1693 $pattern->patternbyid($id);
1694 return $pattern->datauri();
1698 * Get the course pattern image URL.
1700 * @param context_course $context course context object
1701 * @return string URL of the course pattern image in SVG format
1703 public function get_generated_url_for_course(context_course $context): string {
1704 return moodle_url::make_pluginfile_url($context->id, 'course', 'generated', null, '/', 'course.svg')->out();
1708 * Get the course pattern in SVG format to show on a course card.
1710 * @param int $id id to use when generating the pattern
1711 * @return string SVG file contents
1713 public function get_generated_svg_for_id(int $id): string {
1714 $color = $this->get_generated_color_for_id($id);
1715 $pattern = new \core_geopattern();
1716 $pattern->setColor($color);
1717 $pattern->patternbyid($id);
1718 return $pattern->toSVG();
1722 * Get the course color to show on a course card.
1724 * @param int $id Id to use when generating the color.
1725 * @return string hex color code.
1727 public function get_generated_color_for_id($id) {
1728 $colornumbers = range(1, 10);
1729 $basecolors = [];
1730 foreach ($colornumbers as $number) {
1731 $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1734 $color = $basecolors[$id % 10];
1735 return $color;
1739 * Returns lang menu or '', this method also checks forcing of languages in courses.
1741 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1743 * @return string The lang menu HTML or empty string
1745 public function lang_menu() {
1746 $languagemenu = new \core\output\language_menu($this->page);
1747 $data = $languagemenu->export_for_single_select($this);
1748 if ($data) {
1749 return $this->render_from_template('core/single_select', $data);
1751 return '';
1755 * Output the row of editing icons for a block, as defined by the controls array.
1757 * @param array $controls an array like {@link block_contents::$controls}.
1758 * @param string $blockid The ID given to the block.
1759 * @return string HTML fragment.
1761 public function block_controls($actions, $blockid = null) {
1762 if (empty($actions)) {
1763 return '';
1765 $menu = new action_menu($actions);
1766 if ($blockid !== null) {
1767 $menu->set_owner_selector('#'.$blockid);
1769 $menu->attributes['class'] .= ' block-control-actions commands';
1770 return $this->render($menu);
1774 * Returns the HTML for a basic textarea field.
1776 * @param string $name Name to use for the textarea element
1777 * @param string $id The id to use fort he textarea element
1778 * @param string $value Initial content to display in the textarea
1779 * @param int $rows Number of rows to display
1780 * @param int $cols Number of columns to display
1781 * @return string the HTML to display
1783 public function print_textarea($name, $id, $value, $rows, $cols) {
1784 editors_head_setup();
1785 $editor = editors_get_preferred_editor(FORMAT_HTML);
1786 $editor->set_text($value);
1787 $editor->use_editor($id, []);
1789 $context = [
1790 'id' => $id,
1791 'name' => $name,
1792 'value' => $value,
1793 'rows' => $rows,
1794 'cols' => $cols
1797 return $this->render_from_template('core_form/editor_textarea', $context);
1801 * Renders an action menu component.
1803 * @param action_menu $menu
1804 * @return string HTML
1806 public function render_action_menu(action_menu $menu) {
1808 // We don't want the class icon there!
1809 foreach ($menu->get_secondary_actions() as $action) {
1810 if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1811 $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1815 if ($menu->is_empty()) {
1816 return '';
1818 $context = $menu->export_for_template($this);
1820 return $this->render_from_template('core/action_menu', $context);
1824 * Renders a full check API result including summary and details
1826 * @param core\check\check $check the check that was run to get details from
1827 * @param core\check\result $result the result of a check
1828 * @param bool $includedetails if true, details are included as well
1829 * @return string rendered html
1831 protected function render_check_full_result(core\check\check $check, core\check\result $result, bool $includedetails): string {
1832 // Initially render just badge itself.
1833 $renderedresult = $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1835 // Add summary.
1836 $renderedresult .= ' ' . $result->get_summary();
1838 // Wrap in notificaiton.
1839 $notificationmap = [
1840 \core\check\result::NA => \core\output\notification::NOTIFY_INFO,
1841 \core\check\result::OK => \core\output\notification::NOTIFY_SUCCESS,
1842 \core\check\result::INFO => \core\output\notification::NOTIFY_INFO,
1843 \core\check\result::UNKNOWN => \core\output\notification::NOTIFY_WARNING,
1844 \core\check\result::WARNING => \core\output\notification::NOTIFY_WARNING,
1845 \core\check\result::ERROR => \core\output\notification::NOTIFY_ERROR,
1846 \core\check\result::CRITICAL => \core\output\notification::NOTIFY_ERROR,
1849 // Get type, or default to error.
1850 $notificationtype = $notificationmap[$result->get_status()] ?? \core\output\notification::NOTIFY_ERROR;
1851 $renderedresult = $this->notification($renderedresult, $notificationtype, false);
1853 // If adding details, add on new line.
1854 if ($includedetails) {
1855 $renderedresult .= $result->get_details();
1858 // Add the action link.
1859 $renderedresult .= $this->render_action_link($check->get_action_link());
1861 return $renderedresult;
1865 * Renders a full check API result including summary and details
1867 * @param core\check\check $check the check that was run to get details from
1868 * @param core\check\result $result the result of a check
1869 * @param bool $includedetails if details should be included
1870 * @return string HTML fragment
1872 public function check_full_result(core\check\check $check, core\check\result $result, bool $includedetails = false) {
1873 return $this->render_check_full_result($check, $result, $includedetails);
1877 * Renders a Check API result
1879 * @param core\check\result $result
1880 * @return string HTML fragment
1882 protected function render_check_result(core\check\result $result) {
1883 return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1887 * Renders a Check API result
1889 * @param core\check\result $result
1890 * @return string HTML fragment
1892 public function check_result(core\check\result $result) {
1893 return $this->render_check_result($result);
1897 * Renders an action_menu_link item.
1899 * @param action_menu_link $action
1900 * @return string HTML fragment
1902 protected function render_action_menu_link(action_menu_link $action) {
1903 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1907 * Renders a primary action_menu_filler item.
1909 * @param action_menu_filler $action
1910 * @return string HTML fragment
1912 protected function render_action_menu_filler(action_menu_filler $action) {
1913 return html_writer::span('&nbsp;', 'filler');
1917 * Renders a primary action_menu_link item.
1919 * @param action_menu_link_primary $action
1920 * @return string HTML fragment
1922 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1923 return $this->render_action_menu_link($action);
1927 * Renders a secondary action_menu_link item.
1929 * @param action_menu_link_secondary $action
1930 * @return string HTML fragment
1932 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1933 return $this->render_action_menu_link($action);
1937 * Prints a nice side block with an optional header.
1939 * @param block_contents $bc HTML for the content
1940 * @param string $region the region the block is appearing in.
1941 * @return string the HTML to be output.
1943 public function block(block_contents $bc, $region) {
1944 $bc = clone($bc); // Avoid messing up the object passed in.
1945 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1946 $bc->collapsible = block_contents::NOT_HIDEABLE;
1949 $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1950 $context = new stdClass();
1951 $context->skipid = $bc->skipid;
1952 $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
1953 $context->dockable = $bc->dockable;
1954 $context->id = $id;
1955 $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1956 $context->skiptitle = strip_tags($bc->title);
1957 $context->showskiplink = !empty($context->skiptitle);
1958 $context->arialabel = $bc->arialabel;
1959 $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
1960 $context->class = $bc->attributes['class'];
1961 $context->type = $bc->attributes['data-block'];
1962 $context->title = $bc->title;
1963 $context->content = $bc->content;
1964 $context->annotation = $bc->annotation;
1965 $context->footer = $bc->footer;
1966 $context->hascontrols = !empty($bc->controls);
1967 if ($context->hascontrols) {
1968 $context->controls = $this->block_controls($bc->controls, $id);
1971 return $this->render_from_template('core/block', $context);
1975 * Render the contents of a block_list.
1977 * @param array $icons the icon for each item.
1978 * @param array $items the content of each item.
1979 * @return string HTML
1981 public function list_block_contents($icons, $items) {
1982 $row = 0;
1983 $lis = array();
1984 foreach ($items as $key => $string) {
1985 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1986 if (!empty($icons[$key])) { //test if the content has an assigned icon
1987 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1989 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1990 $item .= html_writer::end_tag('li');
1991 $lis[] = $item;
1992 $row = 1 - $row; // Flip even/odd.
1994 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1998 * Output all the blocks in a particular region.
2000 * @param string $region the name of a region on this page.
2001 * @param boolean $fakeblocksonly Output fake block only.
2002 * @return string the HTML to be output.
2004 public function blocks_for_region($region, $fakeblocksonly = false) {
2005 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
2006 $lastblock = null;
2007 $zones = array();
2008 foreach ($blockcontents as $bc) {
2009 if ($bc instanceof block_contents) {
2010 $zones[] = $bc->title;
2013 $output = '';
2015 foreach ($blockcontents as $bc) {
2016 if ($bc instanceof block_contents) {
2017 if ($fakeblocksonly && !$bc->is_fake()) {
2018 // Skip rendering real blocks if we only want to show fake blocks.
2019 continue;
2021 $output .= $this->block($bc, $region);
2022 $lastblock = $bc->title;
2023 } else if ($bc instanceof block_move_target) {
2024 if (!$fakeblocksonly) {
2025 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
2027 } else {
2028 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
2031 return $output;
2035 * Output a place where the block that is currently being moved can be dropped.
2037 * @param block_move_target $target with the necessary details.
2038 * @param array $zones array of areas where the block can be moved to
2039 * @param string $previous the block located before the area currently being rendered.
2040 * @param string $region the name of the region
2041 * @return string the HTML to be output.
2043 public function block_move_target($target, $zones, $previous, $region) {
2044 if ($previous == null) {
2045 if (empty($zones)) {
2046 // There are no zones, probably because there are no blocks.
2047 $regions = $this->page->theme->get_all_block_regions();
2048 $position = get_string('moveblockinregion', 'block', $regions[$region]);
2049 } else {
2050 $position = get_string('moveblockbefore', 'block', $zones[0]);
2052 } else {
2053 $position = get_string('moveblockafter', 'block', $previous);
2055 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
2059 * Renders a special html link with attached action
2061 * Theme developers: DO NOT OVERRIDE! Please override function
2062 * {@link core_renderer::render_action_link()} instead.
2064 * @param string|moodle_url $url
2065 * @param string $text HTML fragment
2066 * @param component_action $action
2067 * @param array $attributes associative array of html link attributes + disabled
2068 * @param pix_icon optional pix icon to render with the link
2069 * @return string HTML fragment
2071 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
2072 if (!($url instanceof moodle_url)) {
2073 $url = new moodle_url($url);
2075 $link = new action_link($url, $text, $action, $attributes, $icon);
2077 return $this->render($link);
2081 * Renders an action_link object.
2083 * The provided link is renderer and the HTML returned. At the same time the
2084 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
2086 * @param action_link $link
2087 * @return string HTML fragment
2089 protected function render_action_link(action_link $link) {
2090 return $this->render_from_template('core/action_link', $link->export_for_template($this));
2094 * Renders an action_icon.
2096 * This function uses the {@link core_renderer::action_link()} method for the
2097 * most part. What it does different is prepare the icon as HTML and use it
2098 * as the link text.
2100 * Theme developers: If you want to change how action links and/or icons are rendered,
2101 * consider overriding function {@link core_renderer::render_action_link()} and
2102 * {@link core_renderer::render_pix_icon()}.
2104 * @param string|moodle_url $url A string URL or moodel_url
2105 * @param pix_icon $pixicon
2106 * @param component_action $action
2107 * @param array $attributes associative array of html link attributes + disabled
2108 * @param bool $linktext show title next to image in link
2109 * @return string HTML fragment
2111 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
2112 if (!($url instanceof moodle_url)) {
2113 $url = new moodle_url($url);
2115 $attributes = (array)$attributes;
2117 if (empty($attributes['class'])) {
2118 // let ppl override the class via $options
2119 $attributes['class'] = 'action-icon';
2122 if ($linktext) {
2123 $text = $pixicon->attributes['alt'];
2124 // Set the icon as a decorative image if we're displaying the action text.
2125 // Otherwise, the action name will be read twice by assistive technologies.
2126 $pixicon->attributes['alt'] = '';
2127 $pixicon->attributes['title'] = '';
2128 $pixicon->attributes['aria-hidden'] = 'true';
2129 } else {
2130 $text = '';
2133 $icon = $this->render($pixicon);
2135 return $this->action_link($url, $text.$icon, $action, $attributes);
2139 * Print a message along with button choices for Continue/Cancel
2141 * If a string or moodle_url is given instead of a single_button, method defaults to post.
2143 * @param string $message The question to ask the user
2144 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
2145 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
2146 * @param array $displayoptions optional extra display options
2147 * @return string HTML fragment
2149 public function confirm($message, $continue, $cancel, array $displayoptions = []) {
2151 // Check existing displayoptions.
2152 $displayoptions['confirmtitle'] = $displayoptions['confirmtitle'] ?? get_string('confirm');
2153 $displayoptions['continuestr'] = $displayoptions['continuestr'] ?? get_string('continue');
2154 $displayoptions['cancelstr'] = $displayoptions['cancelstr'] ?? get_string('cancel');
2156 if ($continue instanceof single_button) {
2157 // Continue button should be primary if set to secondary type as it is the fefault.
2158 if ($continue->type === single_button::BUTTON_SECONDARY) {
2159 $continue->type = single_button::BUTTON_PRIMARY;
2161 } else if (is_string($continue)) {
2162 $continue = new single_button(new moodle_url($continue), $displayoptions['continuestr'], 'post',
2163 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
2164 } else if ($continue instanceof moodle_url) {
2165 $continue = new single_button($continue, $displayoptions['continuestr'], 'post',
2166 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
2167 } else {
2168 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2171 if ($cancel instanceof single_button) {
2172 // ok
2173 } else if (is_string($cancel)) {
2174 $cancel = new single_button(new moodle_url($cancel), $displayoptions['cancelstr'], 'get');
2175 } else if ($cancel instanceof moodle_url) {
2176 $cancel = new single_button($cancel, $displayoptions['cancelstr'], 'get');
2177 } else {
2178 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2181 $attributes = [
2182 'role'=>'alertdialog',
2183 'aria-labelledby'=>'modal-header',
2184 'aria-describedby'=>'modal-body',
2185 'aria-modal'=>'true'
2188 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
2189 $output .= $this->box_start('modal-content', 'modal-content');
2190 $output .= $this->box_start('modal-header px-3', 'modal-header');
2191 $output .= html_writer::tag('h4', $displayoptions['confirmtitle']);
2192 $output .= $this->box_end();
2193 $attributes = [
2194 'role'=>'alert',
2195 'data-aria-autofocus'=>'true'
2197 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
2198 $output .= html_writer::tag('p', $message);
2199 $output .= $this->box_end();
2200 $output .= $this->box_start('modal-footer', 'modal-footer');
2201 $output .= html_writer::tag('div', $this->render($cancel) . $this->render($continue), ['class' => 'buttons']);
2202 $output .= $this->box_end();
2203 $output .= $this->box_end();
2204 $output .= $this->box_end();
2205 return $output;
2209 * Returns a form with a single button.
2211 * Theme developers: DO NOT OVERRIDE! Please override function
2212 * {@link core_renderer::render_single_button()} instead.
2214 * @param string|moodle_url $url
2215 * @param string $label button text
2216 * @param string $method get or post submit method
2217 * @param array $options associative array {disabled, title, etc.}
2218 * @return string HTML fragment
2220 public function single_button($url, $label, $method='post', array $options=null) {
2221 if (!($url instanceof moodle_url)) {
2222 $url = new moodle_url($url);
2224 $button = new single_button($url, $label, $method);
2226 foreach ((array)$options as $key=>$value) {
2227 if (property_exists($button, $key)) {
2228 $button->$key = $value;
2229 } else {
2230 $button->set_attribute($key, $value);
2234 return $this->render($button);
2238 * Renders a single button widget.
2240 * This will return HTML to display a form containing a single button.
2242 * @param single_button $button
2243 * @return string HTML fragment
2245 protected function render_single_button(single_button $button) {
2246 return $this->render_from_template('core/single_button', $button->export_for_template($this));
2250 * Returns a form with a single select widget.
2252 * Theme developers: DO NOT OVERRIDE! Please override function
2253 * {@link core_renderer::render_single_select()} instead.
2255 * @param moodle_url $url form action target, includes hidden fields
2256 * @param string $name name of selection field - the changing parameter in url
2257 * @param array $options list of options
2258 * @param string $selected selected element
2259 * @param array $nothing
2260 * @param string $formid
2261 * @param array $attributes other attributes for the single select
2262 * @return string HTML fragment
2264 public function single_select($url, $name, array $options, $selected = '',
2265 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2266 if (!($url instanceof moodle_url)) {
2267 $url = new moodle_url($url);
2269 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2271 if (array_key_exists('label', $attributes)) {
2272 $select->set_label($attributes['label']);
2273 unset($attributes['label']);
2275 $select->attributes = $attributes;
2277 return $this->render($select);
2281 * Returns a dataformat selection and download form
2283 * @param string $label A text label
2284 * @param moodle_url|string $base The download page url
2285 * @param string $name The query param which will hold the type of the download
2286 * @param array $params Extra params sent to the download page
2287 * @return string HTML fragment
2289 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2291 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2292 $options = array();
2293 foreach ($formats as $format) {
2294 if ($format->is_enabled()) {
2295 $options[] = array(
2296 'value' => $format->name,
2297 'label' => get_string('dataformat', $format->component),
2301 $hiddenparams = array();
2302 foreach ($params as $key => $value) {
2303 $hiddenparams[] = array(
2304 'name' => $key,
2305 'value' => $value,
2308 $data = array(
2309 'label' => $label,
2310 'base' => $base,
2311 'name' => $name,
2312 'params' => $hiddenparams,
2313 'options' => $options,
2314 'sesskey' => sesskey(),
2315 'submit' => get_string('download'),
2318 return $this->render_from_template('core/dataformat_selector', $data);
2323 * Internal implementation of single_select rendering
2325 * @param single_select $select
2326 * @return string HTML fragment
2328 protected function render_single_select(single_select $select) {
2329 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2333 * Returns a form with a url select widget.
2335 * Theme developers: DO NOT OVERRIDE! Please override function
2336 * {@link core_renderer::render_url_select()} instead.
2338 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2339 * @param string $selected selected element
2340 * @param array $nothing
2341 * @param string $formid
2342 * @return string HTML fragment
2344 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2345 $select = new url_select($urls, $selected, $nothing, $formid);
2346 return $this->render($select);
2350 * Internal implementation of url_select rendering
2352 * @param url_select $select
2353 * @return string HTML fragment
2355 protected function render_url_select(url_select $select) {
2356 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2360 * Returns a string containing a link to the user documentation.
2361 * Also contains an icon by default. Shown to teachers and admin only.
2363 * @param string $path The page link after doc root and language, no leading slash.
2364 * @param string $text The text to be displayed for the link
2365 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2366 * @param array $attributes htm attributes
2367 * @return string
2369 public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
2370 global $CFG;
2372 $icon = $this->pix_icon('book', '', 'moodle', array('class' => 'iconhelp icon-pre'));
2374 $attributes['href'] = new moodle_url(get_docs_url($path));
2375 $newwindowicon = '';
2376 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2377 $attributes['target'] = '_blank';
2378 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle',
2379 ['class' => 'fa fa-externallink fa-fw']);
2382 return html_writer::tag('a', $icon . $text . $newwindowicon, $attributes);
2386 * Return HTML for an image_icon.
2388 * Theme developers: DO NOT OVERRIDE! Please override function
2389 * {@link core_renderer::render_image_icon()} instead.
2391 * @param string $pix short pix name
2392 * @param string $alt mandatory alt attribute
2393 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2394 * @param array $attributes htm attributes
2395 * @return string HTML fragment
2397 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2398 $icon = new image_icon($pix, $alt, $component, $attributes);
2399 return $this->render($icon);
2403 * Renders a pix_icon widget and returns the HTML to display it.
2405 * @param image_icon $icon
2406 * @return string HTML fragment
2408 protected function render_image_icon(image_icon $icon) {
2409 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2410 return $system->render_pix_icon($this, $icon);
2414 * Return HTML for a pix_icon.
2416 * Theme developers: DO NOT OVERRIDE! Please override function
2417 * {@link core_renderer::render_pix_icon()} instead.
2419 * @param string $pix short pix name
2420 * @param string $alt mandatory alt attribute
2421 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2422 * @param array $attributes htm lattributes
2423 * @return string HTML fragment
2425 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2426 $icon = new pix_icon($pix, $alt, $component, $attributes);
2427 return $this->render($icon);
2431 * Renders a pix_icon widget and returns the HTML to display it.
2433 * @param pix_icon $icon
2434 * @return string HTML fragment
2436 protected function render_pix_icon(pix_icon $icon) {
2437 $system = \core\output\icon_system::instance();
2438 return $system->render_pix_icon($this, $icon);
2442 * Return HTML to display an emoticon icon.
2444 * @param pix_emoticon $emoticon
2445 * @return string HTML fragment
2447 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2448 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2449 return $system->render_pix_icon($this, $emoticon);
2453 * Produces the html that represents this rating in the UI
2455 * @param rating $rating the page object on which this rating will appear
2456 * @return string
2458 function render_rating(rating $rating) {
2459 global $CFG, $USER;
2461 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2462 return null;//ratings are turned off
2465 $ratingmanager = new rating_manager();
2466 // Initialise the JavaScript so ratings can be done by AJAX.
2467 $ratingmanager->initialise_rating_javascript($this->page);
2469 $strrate = get_string("rate", "rating");
2470 $ratinghtml = ''; //the string we'll return
2472 // permissions check - can they view the aggregate?
2473 if ($rating->user_can_view_aggregate()) {
2475 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2476 $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2477 $aggregatestr = $rating->get_aggregate_string();
2479 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2480 if ($rating->count > 0) {
2481 $countstr = "({$rating->count})";
2482 } else {
2483 $countstr = '-';
2485 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2487 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2489 $nonpopuplink = $rating->get_view_ratings_url();
2490 $popuplink = $rating->get_view_ratings_url(true);
2492 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2493 $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
2496 $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
2499 $formstart = null;
2500 // if the item doesn't belong to the current user, the user has permission to rate
2501 // and we're within the assessable period
2502 if ($rating->user_can_rate()) {
2504 $rateurl = $rating->get_rate_url();
2505 $inputs = $rateurl->params();
2507 //start the rating form
2508 $formattrs = array(
2509 'id' => "postrating{$rating->itemid}",
2510 'class' => 'postratingform',
2511 'method' => 'post',
2512 'action' => $rateurl->out_omit_querystring()
2514 $formstart = html_writer::start_tag('form', $formattrs);
2515 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2517 // add the hidden inputs
2518 foreach ($inputs as $name => $value) {
2519 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2520 $formstart .= html_writer::empty_tag('input', $attributes);
2523 if (empty($ratinghtml)) {
2524 $ratinghtml .= $strrate.': ';
2526 $ratinghtml = $formstart.$ratinghtml;
2528 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2529 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2530 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2531 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2533 //output submit button
2534 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2536 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2537 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2539 if (!$rating->settings->scale->isnumeric) {
2540 // If a global scale, try to find current course ID from the context
2541 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2542 $courseid = $coursecontext->instanceid;
2543 } else {
2544 $courseid = $rating->settings->scale->courseid;
2546 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2548 $ratinghtml .= html_writer::end_tag('span');
2549 $ratinghtml .= html_writer::end_tag('div');
2550 $ratinghtml .= html_writer::end_tag('form');
2553 return $ratinghtml;
2557 * Centered heading with attached help button (same title text)
2558 * and optional icon attached.
2560 * @param string $text A heading text
2561 * @param string $helpidentifier The keyword that defines a help page
2562 * @param string $component component name
2563 * @param string|moodle_url $icon
2564 * @param string $iconalt icon alt text
2565 * @param int $level The level of importance of the heading. Defaulting to 2
2566 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2567 * @return string HTML fragment
2569 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2570 $image = '';
2571 if ($icon) {
2572 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2575 $help = '';
2576 if ($helpidentifier) {
2577 $help = $this->help_icon($helpidentifier, $component);
2580 return $this->heading($image.$text.$help, $level, $classnames);
2584 * Returns HTML to display a help icon.
2586 * @deprecated since Moodle 2.0
2588 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2589 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2593 * Returns HTML to display a help icon.
2595 * Theme developers: DO NOT OVERRIDE! Please override function
2596 * {@link core_renderer::render_help_icon()} instead.
2598 * @param string $identifier The keyword that defines a help page
2599 * @param string $component component name
2600 * @param string|bool $linktext true means use $title as link text, string means link text value
2601 * @param string|object|array|int $a An object, string or number that can be used
2602 * within translation strings
2603 * @return string HTML fragment
2605 public function help_icon($identifier, $component = 'moodle', $linktext = '', $a = null) {
2606 $icon = new help_icon($identifier, $component, $a);
2607 $icon->diag_strings();
2608 if ($linktext === true) {
2609 $icon->linktext = get_string($icon->identifier, $icon->component, $a);
2610 } else if (!empty($linktext)) {
2611 $icon->linktext = $linktext;
2613 return $this->render($icon);
2617 * Implementation of user image rendering.
2619 * @param help_icon $helpicon A help icon instance
2620 * @return string HTML fragment
2622 protected function render_help_icon(help_icon $helpicon) {
2623 $context = $helpicon->export_for_template($this);
2624 return $this->render_from_template('core/help_icon', $context);
2628 * Returns HTML to display a scale help icon.
2630 * @param int $courseid
2631 * @param stdClass $scale instance
2632 * @return string HTML fragment
2634 public function help_icon_scale($courseid, stdClass $scale) {
2635 global $CFG;
2637 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2639 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2641 $scaleid = abs($scale->id);
2643 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2644 $action = new popup_action('click', $link, 'ratingscale');
2646 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2650 * Creates and returns a spacer image with optional line break.
2652 * @param array $attributes Any HTML attributes to add to the spaced.
2653 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2654 * laxy do it with CSS which is a much better solution.
2655 * @return string HTML fragment
2657 public function spacer(array $attributes = null, $br = false) {
2658 $attributes = (array)$attributes;
2659 if (empty($attributes['width'])) {
2660 $attributes['width'] = 1;
2662 if (empty($attributes['height'])) {
2663 $attributes['height'] = 1;
2665 $attributes['class'] = 'spacer';
2667 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2669 if (!empty($br)) {
2670 $output .= '<br />';
2673 return $output;
2677 * Returns HTML to display the specified user's avatar.
2679 * User avatar may be obtained in two ways:
2680 * <pre>
2681 * // Option 1: (shortcut for simple cases, preferred way)
2682 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2683 * $OUTPUT->user_picture($user, array('popup'=>true));
2685 * // Option 2:
2686 * $userpic = new user_picture($user);
2687 * // Set properties of $userpic
2688 * $userpic->popup = true;
2689 * $OUTPUT->render($userpic);
2690 * </pre>
2692 * Theme developers: DO NOT OVERRIDE! Please override function
2693 * {@link core_renderer::render_user_picture()} instead.
2695 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2696 * If any of these are missing, the database is queried. Avoid this
2697 * if at all possible, particularly for reports. It is very bad for performance.
2698 * @param array $options associative array with user picture options, used only if not a user_picture object,
2699 * options are:
2700 * - courseid=$this->page->course->id (course id of user profile in link)
2701 * - size=35 (size of image)
2702 * - link=true (make image clickable - the link leads to user profile)
2703 * - popup=false (open in popup)
2704 * - alttext=true (add image alt attribute)
2705 * - class = image class attribute (default 'userpicture')
2706 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2707 * - includefullname=false (whether to include the user's full name together with the user picture)
2708 * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2709 * @return string HTML fragment
2711 public function user_picture(stdClass $user, array $options = null) {
2712 $userpicture = new user_picture($user);
2713 foreach ((array)$options as $key=>$value) {
2714 if (property_exists($userpicture, $key)) {
2715 $userpicture->$key = $value;
2718 return $this->render($userpicture);
2722 * Internal implementation of user image rendering.
2724 * @param user_picture $userpicture
2725 * @return string
2727 protected function render_user_picture(user_picture $userpicture) {
2728 global $CFG;
2730 $user = $userpicture->user;
2731 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
2733 $alt = '';
2734 if ($userpicture->alttext) {
2735 if (!empty($user->imagealt)) {
2736 $alt = trim($user->imagealt);
2740 // If the user picture is being rendered as a link but without the full name, an empty alt text for the user picture
2741 // would mean that the link displayed will not have any discernible text. This becomes an accessibility issue,
2742 // especially to screen reader users. Use the user's full name by default for the user picture's alt-text if this is
2743 // the case.
2744 if ($userpicture->link && !$userpicture->includefullname && empty($alt)) {
2745 $alt = fullname($user);
2748 if (empty($userpicture->size)) {
2749 $size = 35;
2750 } else if ($userpicture->size === true or $userpicture->size == 1) {
2751 $size = 100;
2752 } else {
2753 $size = $userpicture->size;
2756 $class = $userpicture->class;
2758 if ($user->picture == 0) {
2759 $class .= ' defaultuserpic';
2762 $src = $userpicture->get_url($this->page, $this);
2764 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2765 if (!$userpicture->visibletoscreenreaders) {
2766 $alt = '';
2768 $attributes['alt'] = $alt;
2770 if (!empty($alt)) {
2771 $attributes['title'] = $alt;
2774 // Get the image html output first, auto generated based on initials if one isn't already set.
2775 if ($user->picture == 0 && empty($CFG->enablegravatar) && !defined('BEHAT_SITE_RUNNING')) {
2776 $initials = \core_user::get_initials($user);
2777 $fullname = fullname($userpicture->user, $canviewfullnames);
2778 // Don't modify in corner cases where neither the firstname nor the lastname appears.
2779 $output = html_writer::tag(
2780 'span', $initials,
2782 'class' => 'userinitials size-' . $size,
2783 'title' => $fullname,
2784 'aria-label' => $fullname,
2785 'role' => 'img',
2788 } else {
2789 $output = html_writer::empty_tag('img', $attributes);
2792 // Show fullname together with the picture when desired.
2793 if ($userpicture->includefullname) {
2794 $output .= fullname($userpicture->user, $canviewfullnames);
2797 if (empty($userpicture->courseid)) {
2798 $courseid = $this->page->course->id;
2799 } else {
2800 $courseid = $userpicture->courseid;
2802 if ($courseid == SITEID) {
2803 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2804 } else {
2805 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2808 // Then wrap it in link if needed. Also we don't wrap it in link if the link redirects to itself.
2809 if (!$userpicture->link ||
2810 ($this->page->has_set_url() && $this->page->url == $url)) { // Protect against unset page->url.
2811 return $output;
2814 $attributes = array('href' => $url, 'class' => 'd-inline-block aabtn');
2815 if (!$userpicture->visibletoscreenreaders) {
2816 $attributes['tabindex'] = '-1';
2817 $attributes['aria-hidden'] = 'true';
2820 if ($userpicture->popup) {
2821 $id = html_writer::random_id('userpicture');
2822 $attributes['id'] = $id;
2823 $this->add_action_handler(new popup_action('click', $url), $id);
2826 return html_writer::tag('a', $output, $attributes);
2830 * @deprecated since Moodle 4.3
2832 public function htmllize_file_tree() {
2833 throw new coding_exception('This function is deprecated and no longer relevant.');
2837 * Returns HTML to display the file picker
2839 * <pre>
2840 * $OUTPUT->file_picker($options);
2841 * </pre>
2843 * Theme developers: DO NOT OVERRIDE! Please override function
2844 * {@link core_renderer::render_file_picker()} instead.
2846 * @param stdClass $options file manager options
2847 * options are:
2848 * maxbytes=>-1,
2849 * itemid=>0,
2850 * client_id=>uniqid(),
2851 * acepted_types=>'*',
2852 * return_types=>FILE_INTERNAL,
2853 * context=>current page context
2854 * @return string HTML fragment
2856 public function file_picker($options) {
2857 $fp = new file_picker($options);
2858 return $this->render($fp);
2862 * Internal implementation of file picker rendering.
2864 * @param file_picker $fp
2865 * @return string
2867 public function render_file_picker(file_picker $fp) {
2868 $options = $fp->options;
2869 $client_id = $options->client_id;
2870 $strsaved = get_string('filesaved', 'repository');
2871 $straddfile = get_string('openpicker', 'repository');
2872 $strloading = get_string('loading', 'repository');
2873 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2874 $strdroptoupload = get_string('droptoupload', 'moodle');
2875 $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
2877 $currentfile = $options->currentfile;
2878 if (empty($currentfile)) {
2879 $currentfile = '';
2880 } else {
2881 $currentfile .= ' - ';
2883 if ($options->maxbytes) {
2884 $size = $options->maxbytes;
2885 } else {
2886 $size = get_max_upload_file_size();
2888 if ($size == -1) {
2889 $maxsize = '';
2890 } else {
2891 $maxsize = get_string('maxfilesize', 'moodle', display_size($size, 0));
2893 if ($options->buttonname) {
2894 $buttonname = ' name="' . $options->buttonname . '"';
2895 } else {
2896 $buttonname = '';
2898 $html = <<<EOD
2899 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2900 $iconprogress
2901 </div>
2902 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2903 <div>
2904 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2905 <span> $maxsize </span>
2906 </div>
2907 EOD;
2908 if ($options->env != 'url') {
2909 $html .= <<<EOD
2910 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2911 <div class="filepicker-filename">
2912 <div class="filepicker-container">$currentfile
2913 <div class="dndupload-message">$strdndenabled <br/>
2914 <div class="dndupload-arrow d-flex"><i class="fa fa-arrow-circle-o-down fa-3x m-auto"></i></div>
2915 </div>
2916 </div>
2917 <div class="dndupload-progressbars"></div>
2918 </div>
2919 <div>
2920 <div class="dndupload-target">{$strdroptoupload}<br/>
2921 <div class="dndupload-arrow d-flex"><i class="fa fa-arrow-circle-o-down fa-3x m-auto"></i></div>
2922 </div>
2923 </div>
2924 </div>
2925 EOD;
2927 $html .= '</div>';
2928 return $html;
2932 * @deprecated since Moodle 3.2
2934 public function update_module_button() {
2935 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2936 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2937 'Themes can choose to display the link in the buttons row consistently for all module types.');
2941 * Returns HTML to display a "Turn editing on/off" button in a form.
2943 * @param moodle_url $url The URL + params to send through when clicking the button
2944 * @param string $method
2945 * @return ?string HTML the button
2947 public function edit_button(moodle_url $url, string $method = 'post') {
2949 if ($this->page->theme->haseditswitch == true) {
2950 return;
2952 $url->param('sesskey', sesskey());
2953 if ($this->page->user_is_editing()) {
2954 $url->param('edit', 'off');
2955 $editstring = get_string('turneditingoff');
2956 } else {
2957 $url->param('edit', 'on');
2958 $editstring = get_string('turneditingon');
2961 return $this->single_button($url, $editstring, $method);
2965 * Create a navbar switch for toggling editing mode.
2967 * @return ?string Html containing the edit switch
2969 public function edit_switch() {
2970 if ($this->page->user_allowed_editing()) {
2972 $temp = (object) [
2973 'legacyseturl' => (new moodle_url('/editmode.php'))->out(false),
2974 'pagecontextid' => $this->page->context->id,
2975 'pageurl' => $this->page->url,
2976 'sesskey' => sesskey(),
2978 if ($this->page->user_is_editing()) {
2979 $temp->checked = true;
2981 return $this->render_from_template('core/editswitch', $temp);
2986 * Returns HTML to display a simple button to close a window
2988 * @param string $text The lang string for the button's label (already output from get_string())
2989 * @return string html fragment
2991 public function close_window_button($text='') {
2992 if (empty($text)) {
2993 $text = get_string('closewindow');
2995 $button = new single_button(new moodle_url('#'), $text, 'get');
2996 $button->add_action(new component_action('click', 'close_window'));
2998 return $this->container($this->render($button), 'closewindow');
3002 * Output an error message. By default wraps the error message in <span class="error">.
3003 * If the error message is blank, nothing is output.
3005 * @param string $message the error message.
3006 * @return string the HTML to output.
3008 public function error_text($message) {
3009 if (empty($message)) {
3010 return '';
3012 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
3013 return html_writer::tag('span', $message, array('class' => 'error'));
3017 * Do not call this function directly.
3019 * To terminate the current script with a fatal error, throw an exception.
3020 * Doing this will then call this function to display the error, before terminating the execution.
3022 * @param string $message The message to output
3023 * @param string $moreinfourl URL where more info can be found about the error
3024 * @param string $link Link for the Continue button
3025 * @param array $backtrace The execution backtrace
3026 * @param string $debuginfo Debugging information
3027 * @return string the HTML to output.
3029 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
3030 global $CFG;
3032 $output = '';
3033 $obbuffer = '';
3035 if ($this->has_started()) {
3036 // we can not always recover properly here, we have problems with output buffering,
3037 // html tables, etc.
3038 $output .= $this->opencontainers->pop_all_but_last();
3040 } else {
3041 // It is really bad if library code throws exception when output buffering is on,
3042 // because the buffered text would be printed before our start of page.
3043 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
3044 error_reporting(0); // disable notices from gzip compression, etc.
3045 while (ob_get_level() > 0) {
3046 $buff = ob_get_clean();
3047 if ($buff === false) {
3048 break;
3050 $obbuffer .= $buff;
3052 error_reporting($CFG->debug);
3054 // Output not yet started.
3055 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
3056 if (empty($_SERVER['HTTP_RANGE'])) {
3057 @header($protocol . ' 404 Not Found');
3058 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
3059 // Coax iOS 10 into sending the session cookie.
3060 @header($protocol . ' 403 Forbidden');
3061 } else {
3062 // Must stop byteserving attempts somehow,
3063 // this is weird but Chrome PDF viewer can be stopped only with 407!
3064 @header($protocol . ' 407 Proxy Authentication Required');
3067 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
3068 $this->page->set_url('/'); // no url
3069 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
3070 $this->page->set_title(get_string('error'));
3071 $this->page->set_heading($this->page->course->fullname);
3072 // No need to display the activity header when encountering an error.
3073 $this->page->activityheader->disable();
3074 $output .= $this->header();
3077 $message = '<p class="errormessage">' . s($message) . '</p>'.
3078 '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
3079 get_string('moreinformation') . '</a></p>';
3080 if (empty($CFG->rolesactive)) {
3081 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
3082 //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.
3084 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
3086 if ($CFG->debugdeveloper) {
3087 $labelsep = get_string('labelsep', 'langconfig');
3088 if (!empty($debuginfo)) {
3089 $debuginfo = s($debuginfo); // removes all nasty JS
3090 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
3091 $label = get_string('debuginfo', 'debug') . $labelsep;
3092 $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
3094 if (!empty($backtrace)) {
3095 $label = get_string('stacktrace', 'debug') . $labelsep;
3096 $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
3098 if ($obbuffer !== '' ) {
3099 $label = get_string('outputbuffer', 'debug') . $labelsep;
3100 $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
3104 if (empty($CFG->rolesactive)) {
3105 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
3106 } else if (!empty($link)) {
3107 $output .= $this->continue_button($link);
3110 $output .= $this->footer();
3112 // Padding to encourage IE to display our error page, rather than its own.
3113 $output .= str_repeat(' ', 512);
3115 return $output;
3119 * Output a notification (that is, a status message about something that has just happened).
3121 * Note: \core\notification::add() may be more suitable for your usage.
3123 * @param string $message The message to print out.
3124 * @param ?string $type The type of notification. See constants on \core\output\notification.
3125 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
3126 * @return string the HTML to output.
3128 public function notification($message, $type = null, $closebutton = true) {
3129 $typemappings = [
3130 // Valid types.
3131 'success' => \core\output\notification::NOTIFY_SUCCESS,
3132 'info' => \core\output\notification::NOTIFY_INFO,
3133 'warning' => \core\output\notification::NOTIFY_WARNING,
3134 'error' => \core\output\notification::NOTIFY_ERROR,
3136 // Legacy types mapped to current types.
3137 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
3138 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
3139 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
3140 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
3141 'notifymessage' => \core\output\notification::NOTIFY_INFO,
3142 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
3143 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
3146 $extraclasses = [];
3148 if ($type) {
3149 if (strpos($type, ' ') === false) {
3150 // No spaces in the list of classes, therefore no need to loop over and determine the class.
3151 if (isset($typemappings[$type])) {
3152 $type = $typemappings[$type];
3153 } else {
3154 // The value provided did not match a known type. It must be an extra class.
3155 $extraclasses = [$type];
3157 } else {
3158 // Identify what type of notification this is.
3159 $classarray = explode(' ', self::prepare_classes($type));
3161 // Separate out the type of notification from the extra classes.
3162 foreach ($classarray as $class) {
3163 if (isset($typemappings[$class])) {
3164 $type = $typemappings[$class];
3165 } else {
3166 $extraclasses[] = $class;
3172 $notification = new \core\output\notification($message, $type, $closebutton);
3173 if (count($extraclasses)) {
3174 $notification->set_extra_classes($extraclasses);
3177 // Return the rendered template.
3178 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3182 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3184 public function notify_problem() {
3185 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
3186 'please use \core\notification::add(), or \core\output\notification as required.');
3190 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3192 public function notify_success() {
3193 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
3194 'please use \core\notification::add(), or \core\output\notification as required.');
3198 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3200 public function notify_message() {
3201 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
3202 'please use \core\notification::add(), or \core\output\notification as required.');
3206 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3208 public function notify_redirect() {
3209 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
3210 'please use \core\notification::add(), or \core\output\notification as required.');
3214 * Render a notification (that is, a status message about something that has
3215 * just happened).
3217 * @param \core\output\notification $notification the notification to print out
3218 * @return string the HTML to output.
3220 protected function render_notification(\core\output\notification $notification) {
3221 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3225 * Returns HTML to display a continue button that goes to a particular URL.
3227 * @param string|moodle_url $url The url the button goes to.
3228 * @return string the HTML to output.
3230 public function continue_button($url) {
3231 if (!($url instanceof moodle_url)) {
3232 $url = new moodle_url($url);
3234 $button = new single_button($url, get_string('continue'), 'get', single_button::BUTTON_PRIMARY);
3235 $button->class = 'continuebutton';
3237 return $this->render($button);
3241 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
3243 * Theme developers: DO NOT OVERRIDE! Please override function
3244 * {@link core_renderer::render_paging_bar()} instead.
3246 * @param int $totalcount The total number of entries available to be paged through
3247 * @param int $page The page you are currently viewing
3248 * @param int $perpage The number of entries that should be shown per page
3249 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3250 * @param string $pagevar name of page parameter that holds the page number
3251 * @return string the HTML to output.
3253 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3254 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3255 return $this->render($pb);
3259 * Returns HTML to display the paging bar.
3261 * @param paging_bar $pagingbar
3262 * @return string the HTML to output.
3264 protected function render_paging_bar(paging_bar $pagingbar) {
3265 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3266 $pagingbar->maxdisplay = 10;
3267 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3271 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3273 * @param string $current the currently selected letter.
3274 * @param string $class class name to add to this initial bar.
3275 * @param string $title the name to put in front of this initial bar.
3276 * @param string $urlvar URL parameter name for this initial.
3277 * @param string $url URL object.
3278 * @param array $alpha of letters in the alphabet.
3279 * @param bool $minirender Return a trimmed down view of the initials bar.
3280 * @return string the HTML to output.
3282 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null, bool $minirender = false) {
3283 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha, $minirender);
3284 return $this->render($ib);
3288 * Internal implementation of initials bar rendering.
3290 * @param initials_bar $initialsbar
3291 * @return string
3293 protected function render_initials_bar(initials_bar $initialsbar) {
3294 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3298 * Output the place a skip link goes to.
3300 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3301 * @return string the HTML to output.
3303 public function skip_link_target($id = null) {
3304 return html_writer::span('', '', array('id' => $id));
3308 * Outputs a heading
3310 * @param string $text The text of the heading
3311 * @param int $level The level of importance of the heading. Defaulting to 2
3312 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3313 * @param string $id An optional ID
3314 * @return string the HTML to output.
3316 public function heading($text, $level = 2, $classes = null, $id = null) {
3317 $level = (integer) $level;
3318 if ($level < 1 or $level > 6) {
3319 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3321 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3325 * Outputs a box.
3327 * @param string $contents The contents of the box
3328 * @param string $classes A space-separated list of CSS classes
3329 * @param string $id An optional ID
3330 * @param array $attributes An array of other attributes to give the box.
3331 * @return string the HTML to output.
3333 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3334 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3338 * Outputs the opening section of a box.
3340 * @param string $classes A space-separated list of CSS classes
3341 * @param string $id An optional ID
3342 * @param array $attributes An array of other attributes to give the box.
3343 * @return string the HTML to output.
3345 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3346 $this->opencontainers->push('box', html_writer::end_tag('div'));
3347 $attributes['id'] = $id;
3348 $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes);
3349 return html_writer::start_tag('div', $attributes);
3353 * Outputs the closing section of a box.
3355 * @return string the HTML to output.
3357 public function box_end() {
3358 return $this->opencontainers->pop('box');
3362 * Outputs a paragraph.
3364 * @param string $contents The contents of the paragraph
3365 * @param string|null $classes A space-separated list of CSS classes
3366 * @param string|null $id An optional ID
3367 * @return string the HTML to output.
3369 public function paragraph(string $contents, ?string $classes = null, ?string $id = null): string {
3370 return html_writer::tag(
3371 'p',
3372 $contents,
3373 ['id' => $id, 'class' => renderer_base::prepare_classes($classes)]
3378 * Outputs a screen reader only inline text.
3380 * @param string $contents The contents of the paragraph
3381 * @return string the HTML to output.
3383 public function sr_text(string $contents): string {
3384 return html_writer::tag(
3385 'span',
3386 $contents,
3387 ['class' => 'sr-only']
3388 ) . ' ';
3392 * Outputs a container.
3394 * @param string $contents The contents of the box
3395 * @param string $classes A space-separated list of CSS classes
3396 * @param string $id An optional ID
3397 * @param array $attributes Optional other attributes as array
3398 * @return string the HTML to output.
3400 public function container($contents, $classes = null, $id = null, $attributes = []) {
3401 return $this->container_start($classes, $id, $attributes) . $contents . $this->container_end();
3405 * Outputs the opening section of a container.
3407 * @param string $classes A space-separated list of CSS classes
3408 * @param string $id An optional ID
3409 * @param array $attributes Optional other attributes as array
3410 * @return string the HTML to output.
3412 public function container_start($classes = null, $id = null, $attributes = []) {
3413 $this->opencontainers->push('container', html_writer::end_tag('div'));
3414 $attributes = array_merge(['id' => $id, 'class' => renderer_base::prepare_classes($classes)], $attributes);
3415 return html_writer::start_tag('div', $attributes);
3419 * Outputs the closing section of a container.
3421 * @return string the HTML to output.
3423 public function container_end() {
3424 return $this->opencontainers->pop('container');
3428 * Make nested HTML lists out of the items
3430 * The resulting list will look something like this:
3432 * <pre>
3433 * <<ul>>
3434 * <<li>><div class='tree_item parent'>(item contents)</div>
3435 * <<ul>
3436 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3437 * <</ul>>
3438 * <</li>>
3439 * <</ul>>
3440 * </pre>
3442 * @param array $items
3443 * @param array $attrs html attributes passed to the top ofs the list
3444 * @return string HTML
3446 public function tree_block_contents($items, $attrs = array()) {
3447 // exit if empty, we don't want an empty ul element
3448 if (empty($items)) {
3449 return '';
3451 // array of nested li elements
3452 $lis = array();
3453 foreach ($items as $item) {
3454 // this applies to the li item which contains all child lists too
3455 $content = $item->content($this);
3456 $liclasses = array($item->get_css_type());
3457 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3458 $liclasses[] = 'collapsed';
3460 if ($item->isactive === true) {
3461 $liclasses[] = 'current_branch';
3463 $liattr = array('class'=>join(' ',$liclasses));
3464 // class attribute on the div item which only contains the item content
3465 $divclasses = array('tree_item');
3466 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3467 $divclasses[] = 'branch';
3468 } else {
3469 $divclasses[] = 'leaf';
3471 if (!empty($item->classes) && count($item->classes)>0) {
3472 $divclasses[] = join(' ', $item->classes);
3474 $divattr = array('class'=>join(' ', $divclasses));
3475 if (!empty($item->id)) {
3476 $divattr['id'] = $item->id;
3478 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3479 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3480 $content = html_writer::empty_tag('hr') . $content;
3482 $content = html_writer::tag('li', $content, $liattr);
3483 $lis[] = $content;
3485 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3489 * Returns a search box.
3491 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3492 * @return string HTML with the search form hidden by default.
3494 public function search_box($id = false) {
3495 global $CFG;
3497 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3498 // result in an extra included file for each site, even the ones where global search
3499 // is disabled.
3500 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3501 return '';
3504 $data = [
3505 'action' => new moodle_url('/search/index.php'),
3506 'hiddenfields' => (object) ['name' => 'context', 'value' => $this->page->context->id],
3507 'inputname' => 'q',
3508 'searchstring' => get_string('search'),
3510 return $this->render_from_template('core/search_input_navbar', $data);
3514 * Allow plugins to provide some content to be rendered in the navbar.
3515 * The plugin must define a PLUGIN_render_navbar_output function that returns
3516 * the HTML they wish to add to the navbar.
3518 * @return string HTML for the navbar
3520 public function navbar_plugin_output() {
3521 $output = '';
3523 // Give subsystems an opportunity to inject extra html content. The callback
3524 // must always return a string containing valid html.
3525 foreach (\core_component::get_core_subsystems() as $name => $path) {
3526 if ($path) {
3527 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3531 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3532 foreach ($pluginsfunction as $plugintype => $plugins) {
3533 foreach ($plugins as $pluginfunction) {
3534 $output .= $pluginfunction($this);
3539 return $output;
3543 * Construct a user menu, returning HTML that can be echoed out by a
3544 * layout file.
3546 * @param stdClass $user A user object, usually $USER.
3547 * @param bool $withlinks true if a dropdown should be built.
3548 * @return string HTML fragment.
3550 public function user_menu($user = null, $withlinks = null) {
3551 global $USER, $CFG;
3552 require_once($CFG->dirroot . '/user/lib.php');
3554 if (is_null($user)) {
3555 $user = $USER;
3558 // Note: this behaviour is intended to match that of core_renderer::login_info,
3559 // but should not be considered to be good practice; layout options are
3560 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3561 if (is_null($withlinks)) {
3562 $withlinks = empty($this->page->layout_options['nologinlinks']);
3565 // Add a class for when $withlinks is false.
3566 $usermenuclasses = 'usermenu';
3567 if (!$withlinks) {
3568 $usermenuclasses .= ' withoutlinks';
3571 $returnstr = "";
3573 // If during initial install, return the empty return string.
3574 if (during_initial_install()) {
3575 return $returnstr;
3578 $loginpage = $this->is_login_page();
3579 $loginurl = get_login_url();
3581 // Get some navigation opts.
3582 $opts = user_get_user_navigation_info($user, $this->page);
3584 if (!empty($opts->unauthenticateduser)) {
3585 $returnstr = get_string($opts->unauthenticateduser['content'], 'moodle');
3586 // If not logged in, show the typical not-logged-in string.
3587 if (!$loginpage && (!$opts->unauthenticateduser['guest'] || $withlinks)) {
3588 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3591 return html_writer::div(
3592 html_writer::span(
3593 $returnstr,
3594 'login nav-link'
3596 $usermenuclasses
3600 $avatarclasses = "avatars";
3601 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3602 $usertextcontents = $opts->metadata['userfullname'];
3604 // Other user.
3605 if (!empty($opts->metadata['asotheruser'])) {
3606 $avatarcontents .= html_writer::span(
3607 $opts->metadata['realuseravatar'],
3608 'avatar realuser'
3610 $usertextcontents = $opts->metadata['realuserfullname'];
3611 $usertextcontents .= html_writer::tag(
3612 'span',
3613 get_string(
3614 'loggedinas',
3615 'moodle',
3616 html_writer::span(
3617 $opts->metadata['userfullname'],
3618 'value'
3621 array('class' => 'meta viewingas')
3625 // Role.
3626 if (!empty($opts->metadata['asotherrole'])) {
3627 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3628 $usertextcontents .= html_writer::span(
3629 $opts->metadata['rolename'],
3630 'meta role role-' . $role
3634 // User login failures.
3635 if (!empty($opts->metadata['userloginfail'])) {
3636 $usertextcontents .= html_writer::span(
3637 $opts->metadata['userloginfail'],
3638 'meta loginfailures'
3642 // MNet.
3643 if (!empty($opts->metadata['asmnetuser'])) {
3644 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3645 $usertextcontents .= html_writer::span(
3646 $opts->metadata['mnetidprovidername'],
3647 'meta mnet mnet-' . $mnet
3651 $returnstr .= html_writer::span(
3652 html_writer::span($usertextcontents, 'usertext mr-1') .
3653 html_writer::span($avatarcontents, $avatarclasses),
3654 'userbutton'
3657 // Create a divider (well, a filler).
3658 $divider = new action_menu_filler();
3659 $divider->primary = false;
3661 $am = new action_menu();
3662 $am->set_menu_trigger(
3663 $returnstr,
3664 'nav-link'
3666 $am->set_action_label(get_string('usermenu'));
3667 $am->set_nowrap_on_items();
3668 if ($withlinks) {
3669 $navitemcount = count($opts->navitems);
3670 $idx = 0;
3671 foreach ($opts->navitems as $key => $value) {
3673 switch ($value->itemtype) {
3674 case 'divider':
3675 // If the nav item is a divider, add one and skip link processing.
3676 $am->add($divider);
3677 break;
3679 case 'invalid':
3680 // Silently skip invalid entries (should we post a notification?).
3681 break;
3683 case 'link':
3684 // Process this as a link item.
3685 $pix = null;
3686 if (isset($value->pix) && !empty($value->pix)) {
3687 $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
3688 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3689 $value->title = html_writer::img(
3690 $value->imgsrc,
3691 $value->title,
3692 array('class' => 'iconsmall')
3693 ) . $value->title;
3696 $al = new action_menu_link_secondary(
3697 $value->url,
3698 $pix,
3699 $value->title,
3700 array('class' => 'icon')
3702 if (!empty($value->titleidentifier)) {
3703 $al->attributes['data-title'] = $value->titleidentifier;
3705 $am->add($al);
3706 break;
3709 $idx++;
3711 // Add dividers after the first item and before the last item.
3712 if ($idx == 1 || $idx == $navitemcount - 1) {
3713 $am->add($divider);
3718 return html_writer::div(
3719 $this->render($am),
3720 $usermenuclasses
3725 * Secure layout login info.
3727 * @return string
3729 public function secure_layout_login_info() {
3730 if (get_config('core', 'logininfoinsecurelayout')) {
3731 return $this->login_info(false);
3732 } else {
3733 return '';
3738 * Returns the language menu in the secure layout.
3740 * No custom menu items are passed though, such that it will render only the language selection.
3742 * @return string
3744 public function secure_layout_language_menu() {
3745 if (get_config('core', 'langmenuinsecurelayout')) {
3746 $custommenu = new custom_menu('', current_language());
3747 return $this->render_custom_menu($custommenu);
3748 } else {
3749 return '';
3754 * This renders the navbar.
3755 * Uses bootstrap compatible html.
3757 public function navbar() {
3758 return $this->render_from_template('core/navbar', $this->page->navbar);
3762 * Renders a breadcrumb navigation node object.
3764 * @param breadcrumb_navigation_node $item The navigation node to render.
3765 * @return string HTML fragment
3767 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3769 if ($item->action instanceof moodle_url) {
3770 $content = $item->get_content();
3771 $title = $item->get_title();
3772 $attributes = array();
3773 $attributes['itemprop'] = 'url';
3774 if ($title !== '') {
3775 $attributes['title'] = $title;
3777 if ($item->hidden) {
3778 $attributes['class'] = 'dimmed_text';
3780 if ($item->is_last()) {
3781 $attributes['aria-current'] = 'page';
3783 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3784 $content = html_writer::link($item->action, $content, $attributes);
3786 $attributes = array();
3787 $attributes['itemscope'] = '';
3788 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3789 $content = html_writer::tag('span', $content, $attributes);
3791 } else {
3792 $content = $this->render_navigation_node($item);
3794 return $content;
3798 * Renders a navigation node object.
3800 * @param navigation_node $item The navigation node to render.
3801 * @return string HTML fragment
3803 protected function render_navigation_node(navigation_node $item) {
3804 $content = $item->get_content();
3805 $title = $item->get_title();
3806 if ($item->icon instanceof renderable && !$item->hideicon) {
3807 $icon = $this->render($item->icon);
3808 $content = $icon.$content; // use CSS for spacing of icons
3810 if ($item->helpbutton !== null) {
3811 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3813 if ($content === '') {
3814 return '';
3816 if ($item->action instanceof action_link) {
3817 $link = $item->action;
3818 if ($item->hidden) {
3819 $link->add_class('dimmed');
3821 if (!empty($content)) {
3822 // Providing there is content we will use that for the link content.
3823 $link->text = $content;
3825 $content = $this->render($link);
3826 } else if ($item->action instanceof moodle_url) {
3827 $attributes = array();
3828 if ($title !== '') {
3829 $attributes['title'] = $title;
3831 if ($item->hidden) {
3832 $attributes['class'] = 'dimmed_text';
3834 $content = html_writer::link($item->action, $content, $attributes);
3836 } else if (is_string($item->action) || empty($item->action)) {
3837 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3838 if ($title !== '') {
3839 $attributes['title'] = $title;
3841 if ($item->hidden) {
3842 $attributes['class'] = 'dimmed_text';
3844 $content = html_writer::tag('span', $content, $attributes);
3846 return $content;
3850 * Accessibility: Right arrow-like character is
3851 * used in the breadcrumb trail, course navigation menu
3852 * (previous/next activity), calendar, and search forum block.
3853 * If the theme does not set characters, appropriate defaults
3854 * are set automatically. Please DO NOT
3855 * use &lt; &gt; &raquo; - these are confusing for blind users.
3857 * @return string
3859 public function rarrow() {
3860 return $this->page->theme->rarrow;
3864 * Accessibility: Left arrow-like character is
3865 * used in the breadcrumb trail, course navigation menu
3866 * (previous/next activity), calendar, and search forum block.
3867 * If the theme does not set characters, appropriate defaults
3868 * are set automatically. Please DO NOT
3869 * use &lt; &gt; &raquo; - these are confusing for blind users.
3871 * @return string
3873 public function larrow() {
3874 return $this->page->theme->larrow;
3878 * Accessibility: Up arrow-like character is used in
3879 * the book heirarchical navigation.
3880 * If the theme does not set characters, appropriate defaults
3881 * are set automatically. Please DO NOT
3882 * use ^ - this is confusing for blind users.
3884 * @return string
3886 public function uarrow() {
3887 return $this->page->theme->uarrow;
3891 * Accessibility: Down arrow-like character.
3892 * If the theme does not set characters, appropriate defaults
3893 * are set automatically.
3895 * @return string
3897 public function darrow() {
3898 return $this->page->theme->darrow;
3902 * Returns the custom menu if one has been set
3904 * A custom menu can be configured by browsing to a theme's settings page
3905 * and then configuring the custommenu config setting as described.
3907 * Theme developers: DO NOT OVERRIDE! Please override function
3908 * {@link core_renderer::render_custom_menu()} instead.
3910 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3911 * @return string
3913 public function custom_menu($custommenuitems = '') {
3914 global $CFG;
3916 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3917 $custommenuitems = $CFG->custommenuitems;
3919 $custommenu = new custom_menu($custommenuitems, current_language());
3920 return $this->render_custom_menu($custommenu);
3924 * We want to show the custom menus as a list of links in the footer on small screens.
3925 * Just return the menu object exported so we can render it differently.
3927 public function custom_menu_flat() {
3928 global $CFG;
3929 $custommenuitems = '';
3931 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3932 $custommenuitems = $CFG->custommenuitems;
3934 $custommenu = new custom_menu($custommenuitems, current_language());
3935 $langs = get_string_manager()->get_list_of_translations();
3936 $haslangmenu = $this->lang_menu() != '';
3938 if ($haslangmenu) {
3939 $strlang = get_string('language');
3940 $currentlang = current_language();
3941 if (isset($langs[$currentlang])) {
3942 $currentlang = $langs[$currentlang];
3943 } else {
3944 $currentlang = $strlang;
3946 $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3947 foreach ($langs as $langtype => $langname) {
3948 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3952 return $custommenu->export_for_template($this);
3956 * Renders a custom menu object (located in outputcomponents.php)
3958 * The custom menu this method produces makes use of the YUI3 menunav widget
3959 * and requires very specific html elements and classes.
3961 * @staticvar int $menucount
3962 * @param custom_menu $menu
3963 * @return string
3965 protected function render_custom_menu(custom_menu $menu) {
3966 global $CFG;
3968 $langs = get_string_manager()->get_list_of_translations();
3969 $haslangmenu = $this->lang_menu() != '';
3971 if (!$menu->has_children() && !$haslangmenu) {
3972 return '';
3975 if ($haslangmenu) {
3976 $strlang = get_string('language');
3977 $currentlang = current_language();
3978 if (isset($langs[$currentlang])) {
3979 $currentlangstr = $langs[$currentlang];
3980 } else {
3981 $currentlangstr = $strlang;
3983 $this->language = $menu->add($currentlangstr, new moodle_url('#'), $strlang, 10000);
3984 foreach ($langs as $langtype => $langname) {
3985 $attributes = [];
3986 // Set the lang attribute for languages different from the page's current language.
3987 if ($langtype !== $currentlang) {
3988 $attributes[] = [
3989 'key' => 'lang',
3990 'value' => get_html_lang_attribute_value($langtype),
3993 $this->language->add($langname, new moodle_url($this->page->url, ['lang' => $langtype]), null, null, $attributes);
3997 $content = '';
3998 foreach ($menu->get_children() as $item) {
3999 $context = $item->export_for_template($this);
4000 $content .= $this->render_from_template('core/custom_menu_item', $context);
4003 return $content;
4007 * Renders a custom menu node as part of a submenu
4009 * The custom menu this method produces makes use of the YUI3 menunav widget
4010 * and requires very specific html elements and classes.
4012 * @see core:renderer::render_custom_menu()
4014 * @staticvar int $submenucount
4015 * @param custom_menu_item $menunode
4016 * @return string
4018 protected function render_custom_menu_item(custom_menu_item $menunode) {
4019 // Required to ensure we get unique trackable id's
4020 static $submenucount = 0;
4021 if ($menunode->has_children()) {
4022 // If the child has menus render it as a sub menu
4023 $submenucount++;
4024 $content = html_writer::start_tag('li');
4025 if ($menunode->get_url() !== null) {
4026 $url = $menunode->get_url();
4027 } else {
4028 $url = '#cm_submenu_'.$submenucount;
4030 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
4031 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
4032 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
4033 $content .= html_writer::start_tag('ul');
4034 foreach ($menunode->get_children() as $menunode) {
4035 $content .= $this->render_custom_menu_item($menunode);
4037 $content .= html_writer::end_tag('ul');
4038 $content .= html_writer::end_tag('div');
4039 $content .= html_writer::end_tag('div');
4040 $content .= html_writer::end_tag('li');
4041 } else {
4042 // The node doesn't have children so produce a final menuitem.
4043 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
4044 $content = '';
4045 if (preg_match("/^#+$/", $menunode->get_text())) {
4047 // This is a divider.
4048 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
4049 } else {
4050 $content = html_writer::start_tag(
4051 'li',
4052 array(
4053 'class' => 'yui3-menuitem'
4056 if ($menunode->get_url() !== null) {
4057 $url = $menunode->get_url();
4058 } else {
4059 $url = '#';
4061 $content .= html_writer::link(
4062 $url,
4063 $menunode->get_text(),
4064 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
4067 $content .= html_writer::end_tag('li');
4069 // Return the sub menu
4070 return $content;
4074 * Renders theme links for switching between default and other themes.
4076 * @return string
4078 protected function theme_switch_links() {
4080 $actualdevice = core_useragent::get_device_type();
4081 $currentdevice = $this->page->devicetypeinuse;
4082 $switched = ($actualdevice != $currentdevice);
4084 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
4085 // The user is using the a default device and hasn't switched so don't shown the switch
4086 // device links.
4087 return '';
4090 if ($switched) {
4091 $linktext = get_string('switchdevicerecommended');
4092 $devicetype = $actualdevice;
4093 } else {
4094 $linktext = get_string('switchdevicedefault');
4095 $devicetype = 'default';
4097 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
4099 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
4100 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
4101 $content .= html_writer::end_tag('div');
4103 return $content;
4107 * Renders tabs
4109 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
4111 * Theme developers: In order to change how tabs are displayed please override functions
4112 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
4114 * @param array $tabs array of tabs, each of them may have it's own ->subtree
4115 * @param string|null $selected which tab to mark as selected, all parent tabs will
4116 * automatically be marked as activated
4117 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
4118 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
4119 * @return string
4121 final public function tabtree($tabs, $selected = null, $inactive = null) {
4122 return $this->render(new tabtree($tabs, $selected, $inactive));
4126 * Renders tabtree
4128 * @param tabtree $tabtree
4129 * @return string
4131 protected function render_tabtree(tabtree $tabtree) {
4132 if (empty($tabtree->subtree)) {
4133 return '';
4135 $data = $tabtree->export_for_template($this);
4136 return $this->render_from_template('core/tabtree', $data);
4140 * Renders tabobject (part of tabtree)
4142 * This function is called from {@link core_renderer::render_tabtree()}
4143 * and also it calls itself when printing the $tabobject subtree recursively.
4145 * Property $tabobject->level indicates the number of row of tabs.
4147 * @param tabobject $tabobject
4148 * @return string HTML fragment
4150 protected function render_tabobject(tabobject $tabobject) {
4151 $str = '';
4153 // Print name of the current tab.
4154 if ($tabobject instanceof tabtree) {
4155 // No name for tabtree root.
4156 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
4157 // Tab name without a link. The <a> tag is used for styling.
4158 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
4159 } else {
4160 // Tab name with a link.
4161 if (!($tabobject->link instanceof moodle_url)) {
4162 // backward compartibility when link was passed as quoted string
4163 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
4164 } else {
4165 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
4169 if (empty($tabobject->subtree)) {
4170 if ($tabobject->selected) {
4171 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
4173 return $str;
4176 // Print subtree.
4177 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
4178 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
4179 $cnt = 0;
4180 foreach ($tabobject->subtree as $tab) {
4181 $liclass = '';
4182 if (!$cnt) {
4183 $liclass .= ' first';
4185 if ($cnt == count($tabobject->subtree) - 1) {
4186 $liclass .= ' last';
4188 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
4189 $liclass .= ' onerow';
4192 if ($tab->selected) {
4193 $liclass .= ' here selected';
4194 } else if ($tab->activated) {
4195 $liclass .= ' here active';
4198 // This will recursively call function render_tabobject() for each item in subtree.
4199 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
4200 $cnt++;
4202 $str .= html_writer::end_tag('ul');
4205 return $str;
4209 * Get the HTML for blocks in the given region.
4211 * @since Moodle 2.5.1 2.6
4212 * @param string $region The region to get HTML for.
4213 * @param array $classes Wrapping tag classes.
4214 * @param string $tag Wrapping tag.
4215 * @param boolean $fakeblocksonly Include fake blocks only.
4216 * @return string HTML.
4218 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
4219 $displayregion = $this->page->apply_theme_region_manipulations($region);
4220 $classes = (array)$classes;
4221 $classes[] = 'block-region';
4222 $attributes = array(
4223 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
4224 'class' => join(' ', $classes),
4225 'data-blockregion' => $displayregion,
4226 'data-droptarget' => '1'
4228 if ($this->page->blocks->region_has_content($displayregion, $this)) {
4229 $content = html_writer::tag('h2', get_string('blocks'), ['class' => 'sr-only']) .
4230 $this->blocks_for_region($displayregion, $fakeblocksonly);
4231 } else {
4232 $content = html_writer::tag('h2', get_string('blocks'), ['class' => 'sr-only']);
4234 return html_writer::tag($tag, $content, $attributes);
4238 * Renders a custom block region.
4240 * Use this method if you want to add an additional block region to the content of the page.
4241 * Please note this should only be used in special situations.
4242 * We want to leave the theme is control where ever possible!
4244 * This method must use the same method that the theme uses within its layout file.
4245 * As such it asks the theme what method it is using.
4246 * It can be one of two values, blocks or blocks_for_region (deprecated).
4248 * @param string $regionname The name of the custom region to add.
4249 * @return string HTML for the block region.
4251 public function custom_block_region($regionname) {
4252 if ($this->page->theme->get_block_render_method() === 'blocks') {
4253 return $this->blocks($regionname);
4254 } else {
4255 return $this->blocks_for_region($regionname);
4260 * Returns the CSS classes to apply to the body tag.
4262 * @since Moodle 2.5.1 2.6
4263 * @param array $additionalclasses Any additional classes to apply.
4264 * @return string
4266 public function body_css_classes(array $additionalclasses = array()) {
4267 return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses);
4271 * The ID attribute to apply to the body tag.
4273 * @since Moodle 2.5.1 2.6
4274 * @return string
4276 public function body_id() {
4277 return $this->page->bodyid;
4281 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4283 * @since Moodle 2.5.1 2.6
4284 * @param string|array $additionalclasses Any additional classes to give the body tag,
4285 * @return string
4287 public function body_attributes($additionalclasses = array()) {
4288 if (!is_array($additionalclasses)) {
4289 $additionalclasses = explode(' ', $additionalclasses);
4291 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4295 * Gets HTML for the page heading.
4297 * @since Moodle 2.5.1 2.6
4298 * @param string $tag The tag to encase the heading in. h1 by default.
4299 * @return string HTML.
4301 public function page_heading($tag = 'h1') {
4302 return html_writer::tag($tag, $this->page->heading);
4306 * Gets the HTML for the page heading button.
4308 * @since Moodle 2.5.1 2.6
4309 * @return string HTML.
4311 public function page_heading_button() {
4312 return $this->page->button;
4316 * Returns the Moodle docs link to use for this page.
4318 * @since Moodle 2.5.1 2.6
4319 * @param string $text
4320 * @return string
4322 public function page_doc_link($text = null) {
4323 if ($text === null) {
4324 $text = get_string('moodledocslink');
4326 $path = page_get_doc_link_path($this->page);
4327 if (!$path) {
4328 return '';
4330 return $this->doc_link($path, $text);
4334 * Returns the HTML for the site support email link
4336 * @param array $customattribs Array of custom attributes for the support email anchor tag.
4337 * @param bool $embed Set to true if you want to embed the link in other inline content.
4338 * @return string The html code for the support email link.
4340 public function supportemail(array $customattribs = [], bool $embed = false): string {
4341 global $CFG;
4343 // Do not provide a link to contact site support if it is unavailable to this user. This would be where the site has
4344 // disabled support, or limited it to authenticated users and the current user is a guest or not logged in.
4345 if (!isset($CFG->supportavailability) ||
4346 $CFG->supportavailability == CONTACT_SUPPORT_DISABLED ||
4347 ($CFG->supportavailability == CONTACT_SUPPORT_AUTHENTICATED && (!isloggedin() || isguestuser()))) {
4348 return '';
4351 $label = get_string('contactsitesupport', 'admin');
4352 $icon = $this->pix_icon('t/email', '');
4354 if (!$embed) {
4355 $content = $icon . $label;
4356 } else {
4357 $content = $label;
4360 if (!empty($CFG->supportpage)) {
4361 $attributes = ['href' => $CFG->supportpage, 'target' => 'blank'];
4362 $content .= $this->pix_icon('i/externallink', '', 'moodle', ['class' => 'ml-1']);
4363 } else {
4364 $attributes = ['href' => $CFG->wwwroot . '/user/contactsitesupport.php'];
4367 $attributes += $customattribs;
4369 return html_writer::tag('a', $content, $attributes);
4373 * Returns the services and support link for the help pop-up.
4375 * @return string
4377 public function services_support_link(): string {
4378 global $CFG;
4380 if (during_initial_install() ||
4381 (isset($CFG->showservicesandsupportcontent) && $CFG->showservicesandsupportcontent == false) ||
4382 !is_siteadmin()) {
4383 return '';
4386 $liferingicon = $this->pix_icon('t/life-ring', '', 'moodle', ['class' => 'fa fa-life-ring']);
4387 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle', ['class' => 'ml-1']);
4388 $link = !empty($CFG->servicespage)
4389 ? $CFG->servicespage
4390 : 'https://moodle.com/help/?utm_source=CTA-banner&utm_medium=platform&utm_campaign=name~Moodle4+cat~lms+mp~no';
4391 $content = $liferingicon . get_string('moodleservicesandsupport') . $newwindowicon;
4393 return html_writer::tag('a', $content, ['target' => '_blank', 'href' => $link]);
4397 * Helper function to decide whether to show the help popover header or not.
4399 * @return bool
4401 public function has_popover_links(): bool {
4402 return !empty($this->services_support_link()) || !empty($this->page_doc_link()) || !empty($this->supportemail());
4406 * Helper function to decide whether to show the communication link or not.
4408 * @return bool
4410 public function has_communication_links(): bool {
4411 if (during_initial_install() || !core_communication\api::is_available()) {
4412 return false;
4414 return !empty($this->communication_link());
4418 * Returns the communication link, complete with html.
4420 * @return string
4422 public function communication_link(): string {
4423 $link = $this->communication_url() ?? '';
4424 $commicon = $this->pix_icon('t/messages-o', '', 'moodle', ['class' => 'fa fa-comments']);
4425 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle', ['class' => 'ml-1']);
4426 $content = $commicon . get_string('communicationroomlink', 'course') . $newwindowicon;
4427 $html = html_writer::tag('a', $content, ['target' => '_blank', 'href' => $link]);
4429 return !empty($link) ? $html : '';
4433 * Returns the communication url for a given instance if it exists.
4435 * @return string
4437 public function communication_url(): string {
4438 global $COURSE;
4439 return \core_communication\helper::get_course_communication_url($COURSE);
4443 * Returns the page heading menu.
4445 * @since Moodle 2.5.1 2.6
4446 * @return string HTML.
4448 public function page_heading_menu() {
4449 return $this->page->headingmenu;
4453 * Returns the title to use on the page.
4455 * @since Moodle 2.5.1 2.6
4456 * @return string
4458 public function page_title() {
4459 return $this->page->title;
4463 * Returns the moodle_url for the favicon.
4465 * @since Moodle 2.5.1 2.6
4466 * @return moodle_url The moodle_url for the favicon
4468 public function favicon() {
4469 $logo = null;
4470 if (!during_initial_install()) {
4471 $logo = get_config('core_admin', 'favicon');
4473 if (empty($logo)) {
4474 return $this->image_url('favicon', 'theme');
4477 // Use $CFG->themerev to prevent browser caching when the file changes.
4478 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'favicon', '64x64/',
4479 theme_get_revision(), $logo);
4483 * Renders preferences groups.
4485 * @param preferences_groups $renderable The renderable
4486 * @return string The output.
4488 public function render_preferences_groups(preferences_groups $renderable) {
4489 return $this->render_from_template('core/preferences_groups', $renderable);
4493 * Renders preferences group.
4495 * @param preferences_group $renderable The renderable
4496 * @return string The output.
4498 public function render_preferences_group(preferences_group $renderable) {
4499 $html = '';
4500 $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4501 $html .= $this->heading($renderable->title, 3);
4502 $html .= html_writer::start_tag('ul');
4503 foreach ($renderable->nodes as $node) {
4504 if ($node->has_children()) {
4505 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4507 $html .= html_writer::tag('li', $this->render($node));
4509 $html .= html_writer::end_tag('ul');
4510 $html .= html_writer::end_tag('div');
4511 return $html;
4514 public function context_header($headerinfo = null, $headinglevel = 1) {
4515 global $DB, $USER, $CFG, $SITE;
4516 require_once($CFG->dirroot . '/user/lib.php');
4517 $context = $this->page->context;
4518 $heading = null;
4519 $imagedata = null;
4520 $subheader = null;
4521 $userbuttons = null;
4523 // Make sure to use the heading if it has been set.
4524 if (isset($headerinfo['heading'])) {
4525 $heading = $headerinfo['heading'];
4526 } else {
4527 $heading = $this->page->heading;
4530 // The user context currently has images and buttons. Other contexts may follow.
4531 if ((isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) && $this->page->pagetype !== 'my-index') {
4532 if (isset($headerinfo['user'])) {
4533 $user = $headerinfo['user'];
4534 } else {
4535 // Look up the user information if it is not supplied.
4536 $user = $DB->get_record('user', array('id' => $context->instanceid));
4539 // If the user context is set, then use that for capability checks.
4540 if (isset($headerinfo['usercontext'])) {
4541 $context = $headerinfo['usercontext'];
4544 // Only provide user information if the user is the current user, or a user which the current user can view.
4545 // When checking user_can_view_profile(), either:
4546 // If the page context is course, check the course context (from the page object) or;
4547 // If page context is NOT course, then check across all courses.
4548 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4550 if (user_can_view_profile($user, $course)) {
4551 // Use the user's full name if the heading isn't set.
4552 if (empty($heading)) {
4553 $heading = fullname($user);
4556 $imagedata = $this->user_picture($user, array('size' => 100));
4558 // Check to see if we should be displaying a message button.
4559 if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
4560 $userbuttons = array(
4561 'messages' => array(
4562 'buttontype' => 'message',
4563 'title' => get_string('message', 'message'),
4564 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4565 'image' => 'message',
4566 'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
4567 'page' => $this->page
4571 if ($USER->id != $user->id) {
4572 $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4573 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4574 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4575 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4576 $userbuttons['togglecontact'] = array(
4577 'buttontype' => 'togglecontact',
4578 'title' => get_string($contacttitle, 'message'),
4579 'url' => new moodle_url('/message/index.php', array(
4580 'user1' => $USER->id,
4581 'user2' => $user->id,
4582 $contacturlaction => $user->id,
4583 'sesskey' => sesskey())
4585 'image' => $contactimage,
4586 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4587 'page' => $this->page
4591 } else {
4592 $heading = null;
4597 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4598 return $this->render_context_header($contextheader);
4602 * Renders the skip links for the page.
4604 * @param array $links List of skip links.
4605 * @return string HTML for the skip links.
4607 public function render_skip_links($links) {
4608 $context = [ 'links' => []];
4610 foreach ($links as $url => $text) {
4611 $context['links'][] = [ 'url' => $url, 'text' => $text];
4614 return $this->render_from_template('core/skip_links', $context);
4618 * Renders the header bar.
4620 * @param context_header $contextheader Header bar object.
4621 * @return string HTML for the header bar.
4623 protected function render_context_header(context_header $contextheader) {
4625 // Generate the heading first and before everything else as we might have to do an early return.
4626 if (!isset($contextheader->heading)) {
4627 $heading = $this->heading($this->page->heading, $contextheader->headinglevel);
4628 } else {
4629 $heading = $this->heading($contextheader->heading, $contextheader->headinglevel);
4632 $showheader = empty($this->page->layout_options['nocontextheader']);
4633 if (!$showheader) {
4634 // Return the heading wrapped in an sr-only element so it is only visible to screen-readers.
4635 return html_writer::div($heading, 'sr-only');
4638 // All the html stuff goes here.
4639 $html = html_writer::start_div('page-context-header');
4641 // Image data.
4642 if (isset($contextheader->imagedata)) {
4643 // Header specific image.
4644 $html .= html_writer::div($contextheader->imagedata, 'page-header-image icon-size-7');
4647 // Headings.
4648 if (isset($contextheader->prefix)) {
4649 $prefix = html_writer::div($contextheader->prefix, 'text-muted');
4650 $heading = $prefix . $heading;
4652 $html .= html_writer::tag('div', $heading, array('class' => 'page-header-headings'));
4654 // Buttons.
4655 if (isset($contextheader->additionalbuttons)) {
4656 $html .= html_writer::start_div('btn-group header-button-group');
4657 foreach ($contextheader->additionalbuttons as $button) {
4658 if (!isset($button->page)) {
4659 // Include js for messaging.
4660 if ($button['buttontype'] === 'togglecontact') {
4661 \core_message\helper::togglecontact_requirejs();
4663 if ($button['buttontype'] === 'message') {
4664 \core_message\helper::messageuser_requirejs();
4666 $image = $this->pix_icon($button['formattedimage'], '', 'moodle', array(
4667 'class' => 'iconsmall',
4669 $image .= html_writer::span($button['title'], 'header-button-title');
4670 } else {
4671 $image = html_writer::empty_tag('img', array(
4672 'src' => $button['formattedimage'],
4673 'alt' => $button['title'],
4676 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4678 $html .= html_writer::end_div();
4680 $html .= html_writer::end_div();
4682 return $html;
4686 * Wrapper for header elements.
4688 * @return string HTML to display the main header.
4690 public function full_header() {
4691 $pagetype = $this->page->pagetype;
4692 $homepage = get_home_page();
4693 $homepagetype = null;
4694 // Add a special case since /my/courses is a part of the /my subsystem.
4695 if ($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES) {
4696 $homepagetype = 'my-index';
4697 } else if ($homepage == HOMEPAGE_SITE) {
4698 $homepagetype = 'site-index';
4700 if ($this->page->include_region_main_settings_in_header_actions() &&
4701 !$this->page->blocks->is_block_present('settings')) {
4702 // Only include the region main settings if the page has requested it and it doesn't already have
4703 // the settings block on it. The region main settings are included in the settings block and
4704 // duplicating the content causes behat failures.
4705 $this->page->add_header_action(html_writer::div(
4706 $this->region_main_settings_menu(),
4707 'd-print-none',
4708 ['id' => 'region-main-settings-menu']
4712 $header = new stdClass();
4713 $header->settingsmenu = $this->context_header_settings_menu();
4714 $header->contextheader = $this->context_header();
4715 $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
4716 $header->navbar = $this->navbar();
4717 $header->pageheadingbutton = $this->page_heading_button();
4718 $header->courseheader = $this->course_header();
4719 $header->headeractions = $this->page->get_header_actions();
4720 if (!empty($pagetype) && !empty($homepagetype) && $pagetype == $homepagetype) {
4721 $header->welcomemessage = \core_user::welcome_message();
4723 return $this->render_from_template('core/full_header', $header);
4727 * This is an optional menu that can be added to a layout by a theme. It contains the
4728 * menu for the course administration, only on the course main page.
4730 * @return string
4732 public function context_header_settings_menu() {
4733 $context = $this->page->context;
4734 $menu = new action_menu();
4736 $items = $this->page->navbar->get_items();
4737 $currentnode = end($items);
4739 $showcoursemenu = false;
4740 $showfrontpagemenu = false;
4741 $showusermenu = false;
4743 // We are on the course home page.
4744 if (($context->contextlevel == CONTEXT_COURSE) &&
4745 !empty($currentnode) &&
4746 ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
4747 $showcoursemenu = true;
4750 $courseformat = course_get_format($this->page->course);
4751 // This is a single activity course format, always show the course menu on the activity main page.
4752 if ($context->contextlevel == CONTEXT_MODULE &&
4753 !$courseformat->has_view_page()) {
4755 $this->page->navigation->initialise();
4756 $activenode = $this->page->navigation->find_active_node();
4757 // If the settings menu has been forced then show the menu.
4758 if ($this->page->is_settings_menu_forced()) {
4759 $showcoursemenu = true;
4760 } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
4761 $activenode->type == navigation_node::TYPE_RESOURCE)) {
4763 // We only want to show the menu on the first page of the activity. This means
4764 // the breadcrumb has no additional nodes.
4765 if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
4766 $showcoursemenu = true;
4771 // This is the site front page.
4772 if ($context->contextlevel == CONTEXT_COURSE &&
4773 !empty($currentnode) &&
4774 $currentnode->key === 'home') {
4775 $showfrontpagemenu = true;
4778 // This is the user profile page.
4779 if ($context->contextlevel == CONTEXT_USER &&
4780 !empty($currentnode) &&
4781 ($currentnode->key === 'myprofile')) {
4782 $showusermenu = true;
4785 if ($showfrontpagemenu) {
4786 $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
4787 if ($settingsnode) {
4788 // Build an action menu based on the visible nodes from this navigation tree.
4789 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4791 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4792 if ($skipped) {
4793 $text = get_string('morenavigationlinks');
4794 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4795 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4796 $menu->add_secondary_action($link);
4799 } else if ($showcoursemenu) {
4800 $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
4801 if ($settingsnode) {
4802 // Build an action menu based on the visible nodes from this navigation tree.
4803 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4805 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4806 if ($skipped) {
4807 $text = get_string('morenavigationlinks');
4808 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4809 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4810 $menu->add_secondary_action($link);
4813 } else if ($showusermenu) {
4814 // Get the course admin node from the settings navigation.
4815 $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
4816 if ($settingsnode) {
4817 // Build an action menu based on the visible nodes from this navigation tree.
4818 $this->build_action_menu_from_navigation($menu, $settingsnode);
4822 return $this->render($menu);
4826 * Take a node in the nav tree and make an action menu out of it.
4827 * The links are injected in the action menu.
4829 * @param action_menu $menu
4830 * @param navigation_node $node
4831 * @param boolean $indent
4832 * @param boolean $onlytopleafnodes
4833 * @return boolean nodesskipped - True if nodes were skipped in building the menu
4835 protected function build_action_menu_from_navigation(action_menu $menu,
4836 navigation_node $node,
4837 $indent = false,
4838 $onlytopleafnodes = false) {
4839 $skipped = false;
4840 // Build an action menu based on the visible nodes from this navigation tree.
4841 foreach ($node->children as $menuitem) {
4842 if ($menuitem->display) {
4843 if ($onlytopleafnodes && $menuitem->children->count()) {
4844 $skipped = true;
4845 continue;
4847 if ($menuitem->action) {
4848 if ($menuitem->action instanceof action_link) {
4849 $link = $menuitem->action;
4850 // Give preference to setting icon over action icon.
4851 if (!empty($menuitem->icon)) {
4852 $link->icon = $menuitem->icon;
4854 } else {
4855 $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
4857 } else {
4858 if ($onlytopleafnodes) {
4859 $skipped = true;
4860 continue;
4862 $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
4864 if ($indent) {
4865 $link->add_class('ml-4');
4867 if (!empty($menuitem->classes)) {
4868 $link->add_class(implode(" ", $menuitem->classes));
4871 $menu->add_secondary_action($link);
4872 $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
4875 return $skipped;
4879 * This is an optional menu that can be added to a layout by a theme. It contains the
4880 * menu for the most specific thing from the settings block. E.g. Module administration.
4882 * @return string
4884 public function region_main_settings_menu() {
4885 $context = $this->page->context;
4886 $menu = new action_menu();
4888 if ($context->contextlevel == CONTEXT_MODULE) {
4890 $this->page->navigation->initialise();
4891 $node = $this->page->navigation->find_active_node();
4892 $buildmenu = false;
4893 // If the settings menu has been forced then show the menu.
4894 if ($this->page->is_settings_menu_forced()) {
4895 $buildmenu = true;
4896 } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
4897 $node->type == navigation_node::TYPE_RESOURCE)) {
4899 $items = $this->page->navbar->get_items();
4900 $navbarnode = end($items);
4901 // We only want to show the menu on the first page of the activity. This means
4902 // the breadcrumb has no additional nodes.
4903 if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
4904 $buildmenu = true;
4907 if ($buildmenu) {
4908 // Get the course admin node from the settings navigation.
4909 $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
4910 if ($node) {
4911 // Build an action menu based on the visible nodes from this navigation tree.
4912 $this->build_action_menu_from_navigation($menu, $node);
4916 } else if ($context->contextlevel == CONTEXT_COURSECAT) {
4917 // For course category context, show category settings menu, if we're on the course category page.
4918 if ($this->page->pagetype === 'course-index-category') {
4919 $node = $this->page->settingsnav->find('categorysettings', navigation_node::TYPE_CONTAINER);
4920 if ($node) {
4921 // Build an action menu based on the visible nodes from this navigation tree.
4922 $this->build_action_menu_from_navigation($menu, $node);
4926 } else {
4927 $items = $this->page->navbar->get_items();
4928 $navbarnode = end($items);
4930 if ($navbarnode && ($navbarnode->key === 'participants')) {
4931 $node = $this->page->settingsnav->find('users', navigation_node::TYPE_CONTAINER);
4932 if ($node) {
4933 // Build an action menu based on the visible nodes from this navigation tree.
4934 $this->build_action_menu_from_navigation($menu, $node);
4939 return $this->render($menu);
4943 * Displays the list of tags associated with an entry
4945 * @param array $tags list of instances of core_tag or stdClass
4946 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4947 * to use default, set to '' (empty string) to omit the label completely
4948 * @param string $classes additional classes for the enclosing div element
4949 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4950 * will be appended to the end, JS will toggle the rest of the tags
4951 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4952 * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
4953 * @return string
4955 public function tag_list($tags, $label = null, $classes = '', $limit = 10,
4956 $pagecontext = null, $accesshidelabel = false) {
4957 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
4958 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4962 * Renders element for inline editing of any value
4964 * @param \core\output\inplace_editable $element
4965 * @return string
4967 public function render_inplace_editable(\core\output\inplace_editable $element) {
4968 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4972 * Renders a bar chart.
4974 * @param \core\chart_bar $chart The chart.
4975 * @return string
4977 public function render_chart_bar(\core\chart_bar $chart) {
4978 return $this->render_chart($chart);
4982 * Renders a line chart.
4984 * @param \core\chart_line $chart The chart.
4985 * @return string
4987 public function render_chart_line(\core\chart_line $chart) {
4988 return $this->render_chart($chart);
4992 * Renders a pie chart.
4994 * @param \core\chart_pie $chart The chart.
4995 * @return string
4997 public function render_chart_pie(\core\chart_pie $chart) {
4998 return $this->render_chart($chart);
5002 * Renders a chart.
5004 * @param \core\chart_base $chart The chart.
5005 * @param bool $withtable Whether to include a data table with the chart.
5006 * @return string
5008 public function render_chart(\core\chart_base $chart, $withtable = true) {
5009 $chartdata = json_encode($chart);
5010 return $this->render_from_template('core/chart', (object) [
5011 'chartdata' => $chartdata,
5012 'withtable' => $withtable
5017 * Renders the login form.
5019 * @param \core_auth\output\login $form The renderable.
5020 * @return string
5022 public function render_login(\core_auth\output\login $form) {
5023 global $CFG, $SITE;
5025 $context = $form->export_for_template($this);
5027 $context->errorformatted = $this->error_text($context->error);
5028 $url = $this->get_logo_url();
5029 if ($url) {
5030 $url = $url->out(false);
5032 $context->logourl = $url;
5033 $context->sitename = format_string($SITE->fullname, true,
5034 ['context' => context_course::instance(SITEID), "escape" => false]);
5036 return $this->render_from_template('core/loginform', $context);
5040 * Renders an mform element from a template.
5042 * @param HTML_QuickForm_element $element element
5043 * @param bool $required if input is required field
5044 * @param bool $advanced if input is an advanced field
5045 * @param string $error error message to display
5046 * @param bool $ingroup True if this element is rendered as part of a group
5047 * @return mixed string|bool
5049 public function mform_element($element, $required, $advanced, $error, $ingroup) {
5050 $templatename = 'core_form/element-' . $element->getType();
5051 if ($ingroup) {
5052 $templatename .= "-inline";
5054 try {
5055 // We call this to generate a file not found exception if there is no template.
5056 // We don't want to call export_for_template if there is no template.
5057 core\output\mustache_template_finder::get_template_filepath($templatename);
5059 if ($element instanceof templatable) {
5060 $elementcontext = $element->export_for_template($this);
5062 $helpbutton = '';
5063 if (method_exists($element, 'getHelpButton')) {
5064 $helpbutton = $element->getHelpButton();
5066 $label = $element->getLabel();
5067 $text = '';
5068 if (method_exists($element, 'getText')) {
5069 // There currently exists code that adds a form element with an empty label.
5070 // If this is the case then set the label to the description.
5071 if (empty($label)) {
5072 $label = $element->getText();
5073 } else {
5074 $text = $element->getText();
5078 // Generate the form element wrapper ids and names to pass to the template.
5079 // This differs between group and non-group elements.
5080 if ($element->getType() === 'group') {
5081 // Group element.
5082 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
5083 $elementcontext['wrapperid'] = $elementcontext['id'];
5085 // Ensure group elements pass through the group name as the element name.
5086 $elementcontext['name'] = $elementcontext['groupname'];
5087 } else {
5088 // Non grouped element.
5089 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
5090 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
5093 $context = array(
5094 'element' => $elementcontext,
5095 'label' => $label,
5096 'text' => $text,
5097 'required' => $required,
5098 'advanced' => $advanced,
5099 'helpbutton' => $helpbutton,
5100 'error' => $error
5102 return $this->render_from_template($templatename, $context);
5104 } catch (Exception $e) {
5105 // No template for this element.
5106 return false;
5111 * Render the login signup form into a nice template for the theme.
5113 * @param moodleform $form
5114 * @return string
5116 public function render_login_signup_form($form) {
5117 global $SITE;
5119 $context = $form->export_for_template($this);
5120 $url = $this->get_logo_url();
5121 if ($url) {
5122 $url = $url->out(false);
5124 $context['logourl'] = $url;
5125 $context['sitename'] = format_string($SITE->fullname, true,
5126 ['context' => context_course::instance(SITEID), "escape" => false]);
5128 return $this->render_from_template('core/signup_form_layout', $context);
5132 * Render the verify age and location page into a nice template for the theme.
5134 * @param \core_auth\output\verify_age_location_page $page The renderable
5135 * @return string
5137 protected function render_verify_age_location_page($page) {
5138 $context = $page->export_for_template($this);
5140 return $this->render_from_template('core/auth_verify_age_location_page', $context);
5144 * Render the digital minor contact information page into a nice template for the theme.
5146 * @param \core_auth\output\digital_minor_page $page The renderable
5147 * @return string
5149 protected function render_digital_minor_page($page) {
5150 $context = $page->export_for_template($this);
5152 return $this->render_from_template('core/auth_digital_minor_page', $context);
5156 * Renders a progress bar.
5158 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
5160 * @param progress_bar $bar The bar.
5161 * @return string HTML fragment
5163 public function render_progress_bar(progress_bar $bar) {
5164 $data = $bar->export_for_template($this);
5165 return $this->render_from_template('core/progress_bar', $data);
5169 * Renders an update to a progress bar.
5171 * Note: This does not cleanly map to a renderable class and should
5172 * never be used directly.
5174 * @param string $id
5175 * @param float $percent
5176 * @param string $msg Message
5177 * @param string $estimate time remaining message
5178 * @return string ascii fragment
5180 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate): string {
5181 return html_writer::script(js_writer::function_call('updateProgressBar', [
5182 $id,
5183 round($percent, 1),
5184 $msg,
5185 $estimate,
5186 ]));
5190 * Renders element for a toggle-all checkbox.
5192 * @param \core\output\checkbox_toggleall $element
5193 * @return string
5195 public function render_checkbox_toggleall(\core\output\checkbox_toggleall $element) {
5196 return $this->render_from_template($element->get_template(), $element->export_for_template($this));
5200 * Renders the tertiary nav for the participants page
5202 * @param object $course The course we are operating within
5203 * @param string|null $renderedbuttons Any additional buttons/content to be displayed in line with the nav
5204 * @return string
5206 public function render_participants_tertiary_nav(object $course, ?string $renderedbuttons = null) {
5207 $actionbar = new \core\output\participants_action_bar($course, $this->page, $renderedbuttons);
5208 $content = $this->render_from_template('core_course/participants_actionbar', $actionbar->export_for_template($this));
5209 return $content ?: "";
5213 * Renders release information in the footer popup
5214 * @return ?string Moodle release info.
5216 public function moodle_release() {
5217 global $CFG;
5218 if (!during_initial_install() && is_siteadmin()) {
5219 return $CFG->release;
5224 * Generate the add block button when editing mode is turned on and the user can edit blocks.
5226 * @param string $region where new blocks should be added.
5227 * @return string html for the add block button.
5229 public function addblockbutton($region = ''): string {
5230 $addblockbutton = '';
5231 $regions = $this->page->blocks->get_regions();
5232 if (count($regions) == 0) {
5233 return '';
5235 if (isset($this->page->theme->addblockposition) &&
5236 $this->page->user_is_editing() &&
5237 $this->page->user_can_edit_blocks() &&
5238 $this->page->pagelayout !== 'mycourses'
5240 $params = ['bui_addblock' => '', 'sesskey' => sesskey()];
5241 if (!empty($region)) {
5242 $params['bui_blockregion'] = $region;
5244 $url = new moodle_url($this->page->url, $params);
5245 $addblockbutton = $this->render_from_template('core/add_block_button',
5247 'link' => $url->out(false),
5248 'escapedlink' => "?{$url->get_query_string(false)}",
5249 'pagehash' => $this->page->get_edited_page_hash(),
5250 'blockregion' => $region,
5251 // The following parameters are not used since Moodle 4.2 but are
5252 // still passed for backward-compatibility.
5253 'pageType' => $this->page->pagetype,
5254 'pageLayout' => $this->page->pagelayout,
5255 'subPage' => $this->page->subpage,
5259 return $addblockbutton;
5263 * Prepares an element for streaming output
5265 * This must be used with NO_OUTPUT_BUFFERING set to true. After using this method
5266 * any subsequent prints or echos to STDOUT result in the outputted content magically
5267 * being appended inside that element rather than where the current html would be
5268 * normally. This enables pages which take some time to render incremental content to
5269 * first output a fully formed html page, including the footer, and to then stream
5270 * into an element such as the main content div. This fixes a class of page layout
5271 * bugs and reduces layout shift issues and was inspired by Facebook BigPipe.
5273 * Some use cases such as a simple page which loads content via ajax could be swapped
5274 * to this method wich saves another http request and its network latency resulting
5275 * in both lower server load and better front end performance.
5277 * You should consider giving the element you stream into a minimum height to further
5278 * reduce layout shift as the content initally streams into the element.
5280 * You can safely finish the output without closing the streamed element. You can also
5281 * call this method again to swap the target of the streaming to a new element as
5282 * often as you want.
5284 * https://www.youtube.com/watch?v=LLRig4s1_yA&t=1022s
5285 * Watch this video segment to explain how and why this 'One Weird Trick' works.
5287 * @param string $selector where new content should be appended
5288 * @param string $element which contains the streamed content
5289 * @return string html to be written
5291 public function select_element_for_append(string $selector = '#region-main [role=main]', string $element = 'div') {
5293 if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) {
5294 throw new coding_exception('select_element_for_append used in a non-CLI script without setting NO_OUTPUT_BUFFERING.',
5295 DEBUG_DEVELOPER);
5298 // We are already streaming into this element so don't change anything.
5299 if ($this->currentselector === $selector && $this->currentelement === $element) {
5300 return;
5303 // If we have a streaming element close it before starting a new one.
5304 $html = $this->close_element_for_append();
5306 $this->currentselector = $selector;
5307 $this->currentelement = $element;
5309 // Create an unclosed element for the streamed content to append into.
5310 $id = uniqid();
5311 $html .= html_writer::start_tag($element, ['id' => $id]);
5312 $html .= html_writer::tag('script', "document.querySelector('$selector').append(document.getElementById('$id'))");
5313 $html .= "\n";
5314 return $html;
5318 * This closes any opened stream elements
5320 * @return string html to be written
5322 public function close_element_for_append() {
5323 $html = '';
5324 if ($this->currentselector !== '') {
5325 $html .= html_writer::end_tag($this->currentelement);
5326 $html .= "\n";
5327 $this->currentelement = '';
5329 return $html;
5333 * A companion method to select_element_for_append
5335 * This must be used with NO_OUTPUT_BUFFERING set to true.
5337 * This is similar but instead of appending into the element it replaces
5338 * the content in the element. Depending on the 3rd argument it can replace
5339 * the innerHTML or the outerHTML which can be useful to completely remove
5340 * the element if needed.
5342 * @param string $selector where new content should be replaced
5343 * @param string $html A chunk of well formed html
5344 * @param bool $outer Wether it replaces the innerHTML or the outerHTML
5345 * @return string html to be written
5347 public function select_element_for_replace(string $selector, string $html, bool $outer = false) {
5349 if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) {
5350 throw new coding_exception('select_element_for_replace used in a non-CLI script without setting NO_OUTPUT_BUFFERING.',
5351 DEBUG_DEVELOPER);
5354 // Escape html for use inside a javascript string.
5355 $html = addslashes_js($html);
5356 $property = $outer ? 'outerHTML' : 'innerHTML';
5357 $output = html_writer::tag('script', "document.querySelector('$selector').$property = '$html';");
5358 $output .= "\n";
5359 return $output;
5364 * A renderer that generates output for command-line scripts.
5366 * The implementation of this renderer is probably incomplete.
5368 * @copyright 2009 Tim Hunt
5369 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5370 * @since Moodle 2.0
5371 * @package core
5372 * @category output
5374 class core_renderer_cli extends core_renderer {
5377 * @var array $progressmaximums stores the largest percentage for a progress bar.
5378 * @return string ascii fragment
5380 private $progressmaximums = [];
5383 * Returns the page header.
5385 * @return string HTML fragment
5387 public function header() {
5388 return $this->page->heading . "\n";
5392 * Renders a Check API result
5394 * To aid in CLI consistency this status is NOT translated and the visual
5395 * width is always exactly 10 chars.
5397 * @param core\check\result $result
5398 * @return string HTML fragment
5400 protected function render_check_result(core\check\result $result) {
5401 $status = $result->get_status();
5403 $labels = [
5404 core\check\result::NA => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' NA ',
5405 core\check\result::OK => ' ' . cli_ansi_format('<colour:green>') . ' OK ',
5406 core\check\result::INFO => ' ' . cli_ansi_format('<colour:blue>' ) . ' INFO ',
5407 core\check\result::UNKNOWN => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' UNKNOWN ',
5408 core\check\result::WARNING => ' ' . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
5409 core\check\result::ERROR => ' ' . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
5410 core\check\result::CRITICAL => '' . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
5412 $string = $labels[$status] . cli_ansi_format('<colour:normal>');
5413 return $string;
5417 * Renders a Check API result
5419 * @param core\check\result $result
5420 * @return string fragment
5422 public function check_result(core\check\result $result) {
5423 return $this->render_check_result($result);
5427 * Renders a progress bar.
5429 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
5431 * @param progress_bar $bar The bar.
5432 * @return string ascii fragment
5434 public function render_progress_bar(progress_bar $bar) {
5435 global $CFG;
5437 $size = 55; // The width of the progress bar in chars.
5438 $ascii = "\n";
5440 if (stream_isatty(STDOUT)) {
5441 require_once($CFG->libdir.'/clilib.php');
5443 $ascii .= "[" . str_repeat(' ', $size) . "] 0% \n";
5444 return cli_ansi_format($ascii);
5447 $this->progressmaximums[$bar->get_id()] = 0;
5448 $ascii .= '[';
5449 return $ascii;
5453 * Renders an update to a progress bar.
5455 * Note: This does not cleanly map to a renderable class and should
5456 * never be used directly.
5458 * @param string $id
5459 * @param float $percent
5460 * @param string $msg Message
5461 * @param string $estimate time remaining message
5462 * @return string ascii fragment
5464 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate): string {
5465 $size = 55; // The width of the progress bar in chars.
5466 $ascii = '';
5468 // If we are rendering to a terminal then we can safely use ansii codes
5469 // to move the cursor and redraw the complete progress bar each time
5470 // it is updated.
5471 if (stream_isatty(STDOUT)) {
5472 $colour = $percent == 100 ? 'green' : 'blue';
5474 $done = $percent * $size * 0.01;
5475 $whole = floor($done);
5476 $bar = "<colour:$colour>";
5477 $bar .= str_repeat('█', $whole);
5479 if ($whole < $size) {
5480 // By using unicode chars for partial blocks we can have higher
5481 // precision progress bar.
5482 $fraction = floor(($done - $whole) * 8);
5483 $bar .= core_text::substr(' ▏▎▍▌▋▊▉', $fraction, 1);
5485 // Fill the rest of the empty bar.
5486 $bar .= str_repeat(' ', $size - $whole - 1);
5489 $bar .= '<colour:normal>';
5491 if ($estimate) {
5492 $estimate = "- $estimate";
5495 $ascii .= '<cursor:up>';
5496 $ascii .= '<cursor:up>';
5497 $ascii .= sprintf("[$bar] %3.1f%% %-22s\n", $percent, $estimate);
5498 $ascii .= sprintf("%-80s\n", $msg);
5499 return cli_ansi_format($ascii);
5502 // If we are not rendering to a tty, ie when piped to another command
5503 // or on windows we need to progressively render the progress bar
5504 // which can only ever go forwards.
5505 $done = round($percent * $size * 0.01);
5506 $delta = max(0, $done - $this->progressmaximums[$id]);
5508 $ascii .= str_repeat('#', $delta);
5509 if ($percent >= 100 && $delta > 0) {
5510 $ascii .= sprintf("] %3.1f%%\n$msg\n", $percent);
5512 $this->progressmaximums[$id] += $delta;
5513 return $ascii;
5517 * Returns a template fragment representing a Heading.
5519 * @param string $text The text of the heading
5520 * @param int $level The level of importance of the heading
5521 * @param string $classes A space-separated list of CSS classes
5522 * @param string $id An optional ID
5523 * @return string A template fragment for a heading
5525 public function heading($text, $level = 2, $classes = 'main', $id = null) {
5526 $text .= "\n";
5527 switch ($level) {
5528 case 1:
5529 return '=>' . $text;
5530 case 2:
5531 return '-->' . $text;
5532 default:
5533 return $text;
5538 * Returns a template fragment representing a fatal error.
5540 * @param string $message The message to output
5541 * @param string $moreinfourl URL where more info can be found about the error
5542 * @param string $link Link for the Continue button
5543 * @param array $backtrace The execution backtrace
5544 * @param string $debuginfo Debugging information
5545 * @return string A template fragment for a fatal error
5547 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5548 global $CFG;
5550 $output = "!!! $message !!!\n";
5552 if ($CFG->debugdeveloper) {
5553 if (!empty($debuginfo)) {
5554 $output .= $this->notification($debuginfo, 'notifytiny');
5556 if (!empty($backtrace)) {
5557 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
5561 return $output;
5565 * Returns a template fragment representing a notification.
5567 * @param string $message The message to print out.
5568 * @param string $type The type of notification. See constants on \core\output\notification.
5569 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5570 * @return string A template fragment for a notification
5572 public function notification($message, $type = null, $closebutton = true) {
5573 $message = clean_text($message);
5574 if ($type === 'notifysuccess' || $type === 'success') {
5575 return "++ $message ++\n";
5577 return "!! $message !!\n";
5581 * There is no footer for a cli request, however we must override the
5582 * footer method to prevent the default footer.
5584 public function footer() {}
5587 * Render a notification (that is, a status message about something that has
5588 * just happened).
5590 * @param \core\output\notification $notification the notification to print out
5591 * @return string plain text output
5593 public function render_notification(\core\output\notification $notification) {
5594 return $this->notification($notification->get_message(), $notification->get_message_type());
5600 * A renderer that generates output for ajax scripts.
5602 * This renderer prevents accidental sends back only json
5603 * encoded error messages, all other output is ignored.
5605 * @copyright 2010 Petr Skoda
5606 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5607 * @since Moodle 2.0
5608 * @package core
5609 * @category output
5611 class core_renderer_ajax extends core_renderer {
5614 * Returns a template fragment representing a fatal error.
5616 * @param string $message The message to output
5617 * @param string $moreinfourl URL where more info can be found about the error
5618 * @param string $link Link for the Continue button
5619 * @param array $backtrace The execution backtrace
5620 * @param string $debuginfo Debugging information
5621 * @return string A template fragment for a fatal error
5623 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5624 global $CFG;
5626 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
5628 $e = new stdClass();
5629 $e->error = $message;
5630 $e->errorcode = $errorcode;
5631 $e->stacktrace = NULL;
5632 $e->debuginfo = NULL;
5633 $e->reproductionlink = NULL;
5634 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
5635 $link = (string) $link;
5636 if ($link) {
5637 $e->reproductionlink = $link;
5639 if (!empty($debuginfo)) {
5640 $e->debuginfo = $debuginfo;
5642 if (!empty($backtrace)) {
5643 $e->stacktrace = format_backtrace($backtrace, true);
5646 $this->header();
5647 return json_encode($e);
5651 * Used to display a notification.
5652 * For the AJAX notifications are discarded.
5654 * @param string $message The message to print out.
5655 * @param string $type The type of notification. See constants on \core\output\notification.
5656 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5658 public function notification($message, $type = null, $closebutton = true) {
5662 * Used to display a redirection message.
5663 * AJAX redirections should not occur and as such redirection messages
5664 * are discarded.
5666 * @param moodle_url|string $encodedurl
5667 * @param string $message
5668 * @param int $delay
5669 * @param bool $debugdisableredirect
5670 * @param string $messagetype The type of notification to show the message in.
5671 * See constants on \core\output\notification.
5673 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
5674 $messagetype = \core\output\notification::NOTIFY_INFO) {}
5677 * Prepares the start of an AJAX output.
5679 public function header() {
5680 // unfortunately YUI iframe upload does not support application/json
5681 if (!empty($_FILES)) {
5682 @header('Content-type: text/plain; charset=utf-8');
5683 if (!core_useragent::supports_json_contenttype()) {
5684 @header('X-Content-Type-Options: nosniff');
5686 } else if (!core_useragent::supports_json_contenttype()) {
5687 @header('Content-type: text/plain; charset=utf-8');
5688 @header('X-Content-Type-Options: nosniff');
5689 } else {
5690 @header('Content-type: application/json; charset=utf-8');
5693 // Headers to make it not cacheable and json
5694 @header('Cache-Control: no-store, no-cache, must-revalidate');
5695 @header('Cache-Control: post-check=0, pre-check=0', false);
5696 @header('Pragma: no-cache');
5697 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
5698 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
5699 @header('Accept-Ranges: none');
5703 * There is no footer for an AJAX request, however we must override the
5704 * footer method to prevent the default footer.
5706 public function footer() {}
5709 * No need for headers in an AJAX request... this should never happen.
5710 * @param string $text
5711 * @param int $level
5712 * @param string $classes
5713 * @param string $id
5715 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
5721 * The maintenance renderer.
5723 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
5724 * is running a maintenance related task.
5725 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
5727 * @since Moodle 2.6
5728 * @package core
5729 * @category output
5730 * @copyright 2013 Sam Hemelryk
5731 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5733 class core_renderer_maintenance extends core_renderer {
5736 * Initialises the renderer instance.
5738 * @param moodle_page $page
5739 * @param string $target
5740 * @throws coding_exception
5742 public function __construct(moodle_page $page, $target) {
5743 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
5744 throw new coding_exception('Invalid request for the maintenance renderer.');
5746 parent::__construct($page, $target);
5750 * Does nothing. The maintenance renderer cannot produce blocks.
5752 * @param block_contents $bc
5753 * @param string $region
5754 * @return string
5756 public function block(block_contents $bc, $region) {
5757 return '';
5761 * Does nothing. The maintenance renderer cannot produce blocks.
5763 * @param string $region
5764 * @param array $classes
5765 * @param string $tag
5766 * @param boolean $fakeblocksonly
5767 * @return string
5769 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
5770 return '';
5774 * Does nothing. The maintenance renderer cannot produce blocks.
5776 * @param string $region
5777 * @param boolean $fakeblocksonly Output fake block only.
5778 * @return string
5780 public function blocks_for_region($region, $fakeblocksonly = false) {
5781 return '';
5785 * Does nothing. The maintenance renderer cannot produce a course content header.
5787 * @param bool $onlyifnotcalledbefore
5788 * @return string
5790 public function course_content_header($onlyifnotcalledbefore = false) {
5791 return '';
5795 * Does nothing. The maintenance renderer cannot produce a course content footer.
5797 * @param bool $onlyifnotcalledbefore
5798 * @return string
5800 public function course_content_footer($onlyifnotcalledbefore = false) {
5801 return '';
5805 * Does nothing. The maintenance renderer cannot produce a course header.
5807 * @return string
5809 public function course_header() {
5810 return '';
5814 * Does nothing. The maintenance renderer cannot produce a course footer.
5816 * @return string
5818 public function course_footer() {
5819 return '';
5823 * Does nothing. The maintenance renderer cannot produce a custom menu.
5825 * @param string $custommenuitems
5826 * @return string
5828 public function custom_menu($custommenuitems = '') {
5829 return '';
5833 * Does nothing. The maintenance renderer cannot produce a file picker.
5835 * @param array $options
5836 * @return string
5838 public function file_picker($options) {
5839 return '';
5843 * Overridden confirm message for upgrades.
5845 * @param string $message The question to ask the user
5846 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5847 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5848 * @param array $displayoptions optional extra display options
5849 * @return string HTML fragment
5851 public function confirm($message, $continue, $cancel, array $displayoptions = []) {
5852 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5853 // from any previous version of Moodle).
5854 if ($continue instanceof single_button) {
5855 $continue->type = single_button::BUTTON_PRIMARY;
5856 } else if (is_string($continue)) {
5857 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post',
5858 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
5859 } else if ($continue instanceof moodle_url) {
5860 $continue = new single_button($continue, get_string('continue'), 'post',
5861 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
5862 } else {
5863 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5864 ' (string/moodle_url) or a single_button instance.');
5867 if ($cancel instanceof single_button) {
5868 $output = '';
5869 } else if (is_string($cancel)) {
5870 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5871 } else if ($cancel instanceof moodle_url) {
5872 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5873 } else {
5874 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5875 ' (string/moodle_url) or a single_button instance.');
5878 $output = $this->box_start('generalbox', 'notice');
5879 $output .= html_writer::tag('h4', get_string('confirm'));
5880 $output .= html_writer::tag('p', $message);
5881 $output .= html_writer::tag('div', $this->render($cancel) . $this->render($continue), ['class' => 'buttons']);
5882 $output .= $this->box_end();
5883 return $output;
5887 * Does nothing. The maintenance renderer does not support JS.
5889 * @param block_contents $bc
5891 public function init_block_hider_js(block_contents $bc) {
5892 // Does nothing.
5896 * Does nothing. The maintenance renderer cannot produce language menus.
5898 * @return string
5900 public function lang_menu() {
5901 return '';
5905 * Does nothing. The maintenance renderer has no need for login information.
5907 * @param mixed $withlinks
5908 * @return string
5910 public function login_info($withlinks = null) {
5911 return '';
5915 * Secure login info.
5917 * @return string
5919 public function secure_login_info() {
5920 return $this->login_info(false);
5924 * Does nothing. The maintenance renderer cannot produce user pictures.
5926 * @param stdClass $user
5927 * @param array $options
5928 * @return string
5930 public function user_picture(stdClass $user, array $options = null) {
5931 return '';