MDL-81144 core: Convert add_htmlattributes to hook
[moodle.git] / lib / outputrenderers.php
blob062c8a867071a70dc653541cbabde0ac766da04f
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\before_standard_footer_html_generation;
41 use core\hook\output\before_standard_top_of_body_html_generation;
42 use core\output\named_templatable;
43 use core_completion\cm_completion_details;
44 use core_course\output\activity_information;
46 defined('MOODLE_INTERNAL') || die();
48 /**
49 * Simple base class for Moodle renderers.
51 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
53 * Also has methods to facilitate generating HTML output.
55 * @copyright 2009 Tim Hunt
56 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
57 * @since Moodle 2.0
58 * @package core
59 * @category output
61 class renderer_base {
62 /**
63 * @var xhtml_container_stack The xhtml_container_stack to use.
65 protected $opencontainers;
67 /**
68 * @var moodle_page The Moodle page the renderer has been created to assist with.
70 protected $page;
72 /**
73 * @var string The requested rendering target.
75 protected $target;
77 /**
78 * @var Mustache_Engine $mustache The mustache template compiler
80 private $mustache;
82 /**
83 * @var array $templatecache The mustache template cache.
85 protected $templatecache = [];
87 /**
88 * Return an instance of the mustache class.
90 * @since 2.9
91 * @return Mustache_Engine
93 protected function get_mustache() {
94 global $CFG;
96 if ($this->mustache === null) {
97 require_once("{$CFG->libdir}/filelib.php");
99 $themename = $this->page->theme->name;
100 $themerev = theme_get_revision();
102 // Create new localcache directory.
103 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
105 // Remove old localcache directories.
106 $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR);
107 foreach ($mustachecachedirs as $localcachedir) {
108 $cachedrev = [];
109 preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
110 $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
111 if ($cachedrev > 0 && $cachedrev < $themerev) {
112 fulldelete($localcachedir);
116 $loader = new \core\output\mustache_filesystem_loader();
117 $stringhelper = new \core\output\mustache_string_helper();
118 $cleanstringhelper = new \core\output\mustache_clean_string_helper();
119 $quotehelper = new \core\output\mustache_quote_helper();
120 $jshelper = new \core\output\mustache_javascript_helper($this->page);
121 $pixhelper = new \core\output\mustache_pix_helper($this);
122 $shortentexthelper = new \core\output\mustache_shorten_text_helper();
123 $userdatehelper = new \core\output\mustache_user_date_helper();
125 // We only expose the variables that are exposed to JS templates.
126 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
128 $helpers = array('config' => $safeconfig,
129 'str' => array($stringhelper, 'str'),
130 'cleanstr' => array($cleanstringhelper, 'cleanstr'),
131 'quote' => array($quotehelper, 'quote'),
132 'js' => array($jshelper, 'help'),
133 'pix' => array($pixhelper, 'pix'),
134 'shortentext' => array($shortentexthelper, 'shorten'),
135 'userdate' => array($userdatehelper, 'transform'),
138 $this->mustache = new \core\output\mustache_engine(array(
139 'cache' => $cachedir,
140 'escape' => 's',
141 'loader' => $loader,
142 'helpers' => $helpers,
143 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS],
144 // Don't allow the JavaScript helper to be executed from within another
145 // helper. If it's allowed it can be used by users to inject malicious
146 // JS into the page.
147 'disallowednestedhelpers' => ['js'],
148 // Disable lambda rendering - content in helpers is already rendered, no need to render it again.
149 'disable_lambda_rendering' => true,
154 return $this->mustache;
159 * Constructor
161 * The constructor takes two arguments. The first is the page that the renderer
162 * has been created to assist with, and the second is the target.
163 * The target is an additional identifier that can be used to load different
164 * renderers for different options.
166 * @param moodle_page $page the page we are doing output for.
167 * @param string $target one of rendering target constants
169 public function __construct(moodle_page $page, $target) {
170 $this->opencontainers = $page->opencontainers;
171 $this->page = $page;
172 $this->target = $target;
176 * Renders a template by name with the given context.
178 * The provided data needs to be array/stdClass made up of only simple types.
179 * Simple types are array,stdClass,bool,int,float,string
181 * @since 2.9
182 * @param array|stdClass $context Context containing data for the template.
183 * @return string|boolean
185 public function render_from_template($templatename, $context) {
186 $mustache = $this->get_mustache();
188 if ($mustache->hasHelper('uniqid')) {
189 // Grab a copy of the existing helper to be restored later.
190 $uniqidhelper = $mustache->getHelper('uniqid');
191 } else {
192 // Helper doesn't exist.
193 $uniqidhelper = null;
196 // Provide 1 random value that will not change within a template
197 // but will be different from template to template. This is useful for
198 // e.g. aria attributes that only work with id attributes and must be
199 // unique in a page.
200 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
201 if (isset($this->templatecache[$templatename])) {
202 $template = $this->templatecache[$templatename];
203 } else {
204 try {
205 $template = $mustache->loadTemplate($templatename);
206 $this->templatecache[$templatename] = $template;
207 } catch (Mustache_Exception_UnknownTemplateException $e) {
208 throw new moodle_exception('Unknown template: ' . $templatename);
212 $renderedtemplate = trim($template->render($context));
214 // If we had an existing uniqid helper then we need to restore it to allow
215 // handle nested calls of render_from_template.
216 if ($uniqidhelper) {
217 $mustache->addHelper('uniqid', $uniqidhelper);
220 return $renderedtemplate;
225 * Returns rendered widget.
227 * The provided widget needs to be an object that extends the renderable
228 * interface.
229 * If will then be rendered by a method based upon the classname for the widget.
230 * For instance a widget of class `crazywidget` will be rendered by a protected
231 * render_crazywidget method of this renderer.
232 * If no render_crazywidget method exists and crazywidget implements templatable,
233 * look for the 'crazywidget' template in the same component and render that.
235 * @param renderable $widget instance with renderable interface
236 * @return string
238 public function render(renderable $widget) {
239 $classparts = explode('\\', get_class($widget));
240 // Strip namespaces.
241 $classname = array_pop($classparts);
242 // Remove _renderable suffixes.
243 $classname = preg_replace('/_renderable$/', '', $classname);
245 $rendermethod = "render_{$classname}";
246 if (method_exists($this, $rendermethod)) {
247 // Call the render_[widget_name] function.
248 // Note: This has a higher priority than the named_templatable to allow the theme to override the template.
249 return $this->$rendermethod($widget);
252 if ($widget instanceof named_templatable) {
253 // This is a named templatable.
254 // Fetch the template name from the get_template_name function instead.
255 // Note: This has higher priority than the guessed template name.
256 return $this->render_from_template(
257 $widget->get_template_name($this),
258 $widget->export_for_template($this)
262 if ($widget instanceof templatable) {
263 // Guess the templat ename based on the class name.
264 // Note: There's no benefit to moving this aboved the named_templatable and this approach is more costly.
265 $component = array_shift($classparts);
266 if (!$component) {
267 $component = 'core';
269 $template = $component . '/' . $classname;
270 $context = $widget->export_for_template($this);
271 return $this->render_from_template($template, $context);
273 throw new coding_exception("Can not render widget, renderer method ('{$rendermethod}') not found.");
277 * Adds a JS action for the element with the provided id.
279 * This method adds a JS event for the provided component action to the page
280 * and then returns the id that the event has been attached to.
281 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
283 * @param component_action $action
284 * @param string $id
285 * @return string id of element, either original submitted or random new if not supplied
287 public function add_action_handler(component_action $action, $id = null) {
288 if (!$id) {
289 $id = html_writer::random_id($action->event);
291 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
292 return $id;
296 * Returns true is output has already started, and false if not.
298 * @return boolean true if the header has been printed.
300 public function has_started() {
301 return $this->page->state >= moodle_page::STATE_IN_BODY;
305 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
307 * @param mixed $classes Space-separated string or array of classes
308 * @return string HTML class attribute value
310 public static function prepare_classes($classes) {
311 if (is_array($classes)) {
312 return implode(' ', array_unique($classes));
314 return $classes;
318 * Return the direct URL for an image from the pix folder.
320 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
322 * @deprecated since Moodle 3.3
323 * @param string $imagename the name of the icon.
324 * @param string $component specification of one plugin like in get_string()
325 * @return moodle_url
327 public function pix_url($imagename, $component = 'moodle') {
328 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
329 return $this->page->theme->image_url($imagename, $component);
333 * Return the moodle_url for an image.
335 * The exact image location and extension is determined
336 * automatically by searching for gif|png|jpg|jpeg, please
337 * note there can not be diferent images with the different
338 * extension. The imagename is for historical reasons
339 * a relative path name, it may be changed later for core
340 * images. It is recommended to not use subdirectories
341 * in plugin and theme pix directories.
343 * There are three types of images:
344 * 1/ theme images - stored in theme/mytheme/pix/,
345 * use component 'theme'
346 * 2/ core images - stored in /pix/,
347 * overridden via theme/mytheme/pix_core/
348 * 3/ plugin images - stored in mod/mymodule/pix,
349 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
350 * example: image_url('comment', 'mod_glossary')
352 * @param string $imagename the pathname of the image
353 * @param string $component full plugin name (aka component) or 'theme'
354 * @return moodle_url
356 public function image_url($imagename, $component = 'moodle') {
357 return $this->page->theme->image_url($imagename, $component);
361 * Return the site's logo URL, if any.
363 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
364 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
365 * @return moodle_url|false
367 public function get_logo_url($maxwidth = null, $maxheight = 200) {
368 global $CFG;
369 $logo = get_config('core_admin', 'logo');
370 if (empty($logo)) {
371 return false;
374 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
375 // It's not worth the overhead of detecting and serving 2 different images based on the device.
377 // Hide the requested size in the file path.
378 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
380 // Use $CFG->themerev to prevent browser caching when the file changes.
381 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
382 theme_get_revision(), $logo);
386 * Return the site's compact logo URL, if any.
388 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
389 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
390 * @return moodle_url|false
392 public function get_compact_logo_url($maxwidth = 300, $maxheight = 300) {
393 global $CFG;
394 $logo = get_config('core_admin', 'logocompact');
395 if (empty($logo)) {
396 return false;
399 // Hide the requested size in the file path.
400 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
402 // Use $CFG->themerev to prevent browser caching when the file changes.
403 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
404 theme_get_revision(), $logo);
408 * Whether we should display the logo in the navbar.
410 * We will when there are no main logos, and we have compact logo.
412 * @return bool
414 public function should_display_navbar_logo() {
415 $logo = $this->get_compact_logo_url();
416 return !empty($logo);
420 * Whether we should display the main logo.
421 * @deprecated since Moodle 4.0
422 * @todo final deprecation. To be removed in Moodle 4.4 MDL-73165.
423 * @param int $headinglevel The heading level we want to check against.
424 * @return bool
426 public function should_display_main_logo($headinglevel = 1) {
427 debugging('should_display_main_logo() is deprecated and will be removed in Moodle 4.4.', DEBUG_DEVELOPER);
428 // Only render the logo if we're on the front page or login page and the we have a logo.
429 $logo = $this->get_logo_url();
430 if ($headinglevel == 1 && !empty($logo)) {
431 if ($this->page->pagelayout == 'frontpage' || $this->page->pagelayout == 'login') {
432 return true;
436 return false;
443 * Basis for all plugin renderers.
445 * @copyright Petr Skoda (skodak)
446 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
447 * @since Moodle 2.0
448 * @package core
449 * @category output
451 class plugin_renderer_base extends renderer_base {
454 * @var renderer_base|core_renderer A reference to the current renderer.
455 * The renderer provided here will be determined by the page but will in 90%
456 * of cases by the {@link core_renderer}
458 protected $output;
461 * Constructor method, calls the parent constructor
463 * @param moodle_page $page
464 * @param string $target one of rendering target constants
466 public function __construct(moodle_page $page, $target) {
467 if (empty($target) && $page->pagelayout === 'maintenance') {
468 // If the page is using the maintenance layout then we're going to force the target to maintenance.
469 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
470 // unavailable for this page layout.
471 $target = RENDERER_TARGET_MAINTENANCE;
473 $this->output = $page->get_renderer('core', null, $target);
474 parent::__construct($page, $target);
478 * Renders the provided widget and returns the HTML to display it.
480 * @param renderable $widget instance with renderable interface
481 * @return string
483 public function render(renderable $widget) {
484 $classname = get_class($widget);
486 // Strip namespaces.
487 $classname = preg_replace('/^.*\\\/', '', $classname);
489 // Keep a copy at this point, we may need to look for a deprecated method.
490 $deprecatedmethod = "render_{$classname}";
492 // Remove _renderable suffixes.
493 $classname = preg_replace('/_renderable$/', '', $classname);
494 $rendermethod = "render_{$classname}";
496 if (method_exists($this, $rendermethod)) {
497 // Call the render_[widget_name] function.
498 // Note: This has a higher priority than the named_templatable to allow the theme to override the template.
499 return $this->$rendermethod($widget);
502 if ($widget instanceof named_templatable) {
503 // This is a named templatable.
504 // Fetch the template name from the get_template_name function instead.
505 // Note: This has higher priority than the deprecated method which is not overridable by themes anyway.
506 return $this->render_from_template(
507 $widget->get_template_name($this),
508 $widget->export_for_template($this)
512 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
513 // This is exactly where we don't want to be.
514 // If you have arrived here you have a renderable component within your plugin that has the name
515 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
516 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
517 // and the _renderable suffix now gets removed when looking for a render method.
518 // You need to change your renderers render_blah_renderable to render_blah.
519 // Until you do this it will not be possible for a theme to override the renderer to override your method.
520 // Please do it ASAP.
521 static $debugged = [];
522 if (!isset($debugged[$deprecatedmethod])) {
523 debugging(sprintf(
524 'Deprecated call. Please rename your renderables render method from %s to %s.',
525 $deprecatedmethod,
526 $rendermethod
527 ), DEBUG_DEVELOPER);
528 $debugged[$deprecatedmethod] = true;
530 return $this->$deprecatedmethod($widget);
533 // Pass to core renderer if method not found here.
534 // Note: this is not a parent. This is _new_ renderer which respects the requested format, and output type.
535 return $this->output->render($widget);
539 * Magic method used to pass calls otherwise meant for the standard renderer
540 * to it to ensure we don't go causing unnecessary grief.
542 * @param string $method
543 * @param array $arguments
544 * @return mixed
546 public function __call($method, $arguments) {
547 if (method_exists('renderer_base', $method)) {
548 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
550 if (method_exists($this->output, $method)) {
551 return call_user_func_array(array($this->output, $method), $arguments);
552 } else {
553 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
560 * The standard implementation of the core_renderer interface.
562 * @copyright 2009 Tim Hunt
563 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
564 * @since Moodle 2.0
565 * @package core
566 * @category output
568 class core_renderer extends renderer_base {
570 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
571 * in layout files instead.
572 * @deprecated
573 * @var string used in {@link core_renderer::header()}.
575 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
578 * @var string Used to pass information from {@link core_renderer::doctype()} to
579 * {@link core_renderer::standard_head_html()}.
581 protected $contenttype;
584 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
585 * with {@link core_renderer::header()}.
587 protected $metarefreshtag = '';
590 * @var string Unique token for the closing HTML
592 protected $unique_end_html_token;
595 * @var string Unique token for performance information
597 protected $unique_performance_info_token;
600 * @var string Unique token for the main content.
602 protected $unique_main_content_token;
604 /** @var custom_menu_item language The language menu if created */
605 protected $language = null;
607 /** @var string The current selector for an element being streamed into */
608 protected $currentselector = '';
610 /** @var string The current element tag which is being streamed into */
611 protected $currentelement = '';
614 * Constructor
616 * @param moodle_page $page the page we are doing output for.
617 * @param string $target one of rendering target constants
619 public function __construct(moodle_page $page, $target) {
620 $this->opencontainers = $page->opencontainers;
621 $this->page = $page;
622 $this->target = $target;
624 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
625 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
626 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
630 * Get the DOCTYPE declaration that should be used with this page. Designed to
631 * be called in theme layout.php files.
633 * @return string the DOCTYPE declaration that should be used.
635 public function doctype() {
636 if ($this->page->theme->doctype === 'html5') {
637 $this->contenttype = 'text/html; charset=utf-8';
638 return "<!DOCTYPE html>\n";
640 } else if ($this->page->theme->doctype === 'xhtml5') {
641 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
642 return "<!DOCTYPE html>\n";
644 } else {
645 // legacy xhtml 1.0
646 $this->contenttype = 'text/html; charset=utf-8';
647 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
652 * The attributes that should be added to the <html> tag. Designed to
653 * be called in theme layout.php files.
655 * @return string HTML fragment.
657 public function htmlattributes() {
658 $return = get_html_lang(true);
660 // Ensure that the callback exists prior to cache purge.
661 // This is a critical page path.
662 // TODO MDL-81134 Remove after LTS+1.
663 require_once(__DIR__ . '/classes/hook/output/before_html_attributes.php');
665 $hook = new before_html_attributes($this);
667 if ($this->page->theme->doctype !== 'html5') {
668 $hook->add_attribute('xmlns', 'http://www.w3.org/1999/xhtml');
671 di::get(hook_manager::class)->dispatch($hook);
672 $hook->process_legacy_callbacks();
674 foreach ($hook->get_attributes() as $key => $val) {
675 $val = s($val);
676 $return .= " $key=\"$val\"";
679 return $return;
683 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
684 * that should be included in the <head> tag. Designed to be called in theme
685 * layout.php files.
687 * @return string HTML fragment.
689 public function standard_head_html() {
690 global $CFG, $SESSION, $SITE;
692 // Before we output any content, we need to ensure that certain
693 // page components are set up.
695 // Blocks must be set up early as they may require javascript which
696 // has to be included in the page header before output is created.
697 foreach ($this->page->blocks->get_regions() as $region) {
698 $this->page->blocks->ensure_content_created($region, $this);
701 // Give plugins an opportunity to add any head elements. The callback
702 // must always return a string containing valid html head content.
704 $hook = new \core\hook\output\before_standard_head_html_generation($this);
705 di::get(hook_manager::class)->dispatch($hook);
706 $hook->process_legacy_callbacks();
708 // Allow a url_rewrite plugin to setup any dynamic head content.
709 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
710 $class = $CFG->urlrewriteclass;
711 $hook->add_html($class::html_head_setup());
714 $hook->add_html('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n");
715 $hook->add_html('<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n");
716 // This is only set by the {@link redirect()} method
717 $hook->add_html($this->metarefreshtag);
719 // Check if a periodic refresh delay has been set and make sure we arn't
720 // already meta refreshing
721 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
722 $hook->add_html(
723 html_writer::empty_tag('meta', [
724 'http-equiv' => 'refresh',
725 'content' => $this->page->periodicrefreshdelay . ';url='.$this->page->url->out(),
730 $output = $hook->get_output();
732 // Set up help link popups for all links with the helptooltip class
733 $this->page->requires->js_init_call('M.util.help_popups.setup');
735 $focus = $this->page->focuscontrol;
736 if (!empty($focus)) {
737 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
738 // This is a horrifically bad way to handle focus but it is passed in
739 // through messy formslib::moodleform
740 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
741 } else if (strpos($focus, '.')!==false) {
742 // Old style of focus, bad way to do it
743 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);
744 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
745 } else {
746 // Focus element with given id
747 $this->page->requires->js_function_call('focuscontrol', array($focus));
751 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
752 // any other custom CSS can not be overridden via themes and is highly discouraged
753 $urls = $this->page->theme->css_urls($this->page);
754 foreach ($urls as $url) {
755 $this->page->requires->css_theme($url);
758 // Get the theme javascript head and footer
759 if ($jsurl = $this->page->theme->javascript_url(true)) {
760 $this->page->requires->js($jsurl, true);
762 if ($jsurl = $this->page->theme->javascript_url(false)) {
763 $this->page->requires->js($jsurl);
766 // Get any HTML from the page_requirements_manager.
767 $output .= $this->page->requires->get_head_code($this->page, $this);
769 // List alternate versions.
770 foreach ($this->page->alternateversions as $type => $alt) {
771 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
772 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
775 // Add noindex tag if relevant page and setting applied.
776 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
777 $loginpages = array('login-index', 'login-signup');
778 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
779 if (!isset($CFG->additionalhtmlhead)) {
780 $CFG->additionalhtmlhead = '';
782 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
785 if (!empty($CFG->additionalhtmlhead)) {
786 $output .= "\n".$CFG->additionalhtmlhead;
789 if ($this->page->pagelayout == 'frontpage') {
790 $summary = s(strip_tags(format_text($SITE->summary, FORMAT_HTML)));
791 if (!empty($summary)) {
792 $output .= "<meta name=\"description\" content=\"$summary\" />\n";
796 return $output;
800 * The standard tags (typically skip links) that should be output just inside
801 * the start of the <body> tag. Designed to be called in theme layout.php files.
803 * @return string HTML fragment.
805 public function standard_top_of_body_html() {
806 global $CFG;
807 $output = $this->page->requires->get_top_of_body_code($this);
808 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
809 $output .= "\n".$CFG->additionalhtmltopofbody;
812 // Ensure that the callback exists prior to cache purge.
813 // This is a critical page path.
814 // TODO MDL-81134 Remove after LTS+1.
815 require_once(__DIR__ . '/classes/hook/output/before_standard_top_of_body_html_generation.php');
817 // Allow components to add content to the top of the body.
818 $hook = new before_standard_top_of_body_html_generation($this, $output);
819 di::get(hook_manager::class)->dispatch($hook);
820 $hook->process_legacy_callbacks();
821 $output = $hook->get_output();
823 $output .= $this->maintenance_warning();
825 return $output;
829 * Scheduled maintenance warning message.
831 * Note: This is a nasty hack to display maintenance notice, this should be moved
832 * to some general notification area once we have it.
834 * @return string
836 public function maintenance_warning() {
837 global $CFG;
839 $output = '';
840 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
841 $timeleft = $CFG->maintenance_later - time();
842 // If timeleft less than 30 sec, set the class on block to error to highlight.
843 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
844 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-3 alert');
845 $a = new stdClass();
846 $a->hour = (int)($timeleft / 3600);
847 $a->min = (int)(floor($timeleft / 60) % 60);
848 $a->sec = (int)($timeleft % 60);
849 if ($a->hour > 0) {
850 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
851 } else {
852 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
855 $output .= $this->box_end();
856 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
857 array(array('timeleftinsec' => $timeleft)));
858 $this->page->requires->strings_for_js(
859 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
860 'admin');
862 return $output;
866 * content that should be output in the footer area
867 * of the page. Designed to be called in theme layout.php files.
869 * @return string HTML fragment.
871 public function standard_footer_html() {
872 if (during_initial_install()) {
873 // Debugging info can not work before install is finished,
874 // in any case we do not want any links during installation!
875 return '';
878 // Ensure that the callback exists prior to cache purge.
879 // This is a critical page path.
880 // TODO MDL-81134 Remove after LTS+1.
881 require_once(__DIR__ . '/classes/hook/output/before_standard_footer_html_generation.php');
883 $hook = new before_standard_footer_html_generation($this);
884 di::get(hook_manager::class)->dispatch($hook);
885 $hook->process_legacy_callbacks();
886 $output = $hook->get_output();
888 if ($this->page->devicetypeinuse == 'legacy') {
889 // The legacy theme is in use print the notification
890 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
893 // Get links to switch device types (only shown for users not on a default device)
894 $output .= $this->theme_switch_links();
896 return $output;
900 * Performance information and validation links for debugging.
902 * @return string HTML fragment.
904 public function debug_footer_html() {
905 global $CFG, $SCRIPT;
906 $output = '';
908 if (during_initial_install()) {
909 // Debugging info can not work before install is finished.
910 return $output;
913 // This function is normally called from a layout.php file
914 // but some of the content won't be known until later, so we return a placeholder
915 // for now. This will be replaced with the real content in the footer.
916 $output .= $this->unique_performance_info_token;
918 if (!empty($CFG->debugpageinfo)) {
919 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
920 $this->page->debug_summary()) . '</div>';
922 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
924 // Add link to profiling report if necessary
925 if (function_exists('profiling_is_running') && profiling_is_running()) {
926 $txt = get_string('profiledscript', 'admin');
927 $title = get_string('profiledscriptview', 'admin');
928 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
929 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
930 $output .= '<div class="profilingfooter">' . $link . '</div>';
932 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
933 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
934 $output .= '<div class="purgecaches">' .
935 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
937 // Reactive module debug panel.
938 $output .= $this->render_from_template('core/local/reactive/debugpanel', []);
940 if (!empty($CFG->debugvalidators)) {
941 $siteurl = qualified_me();
942 $nuurl = new moodle_url('https://validator.w3.org/nu/', ['doc' => $siteurl, 'showsource' => 'yes']);
943 $waveurl = new moodle_url('https://wave.webaim.org/report#/' . urlencode($siteurl));
944 $validatorlinks = [
945 html_writer::link($nuurl, get_string('validatehtml')),
946 html_writer::link($waveurl, get_string('wcagcheck'))
948 $validatorlinkslist = html_writer::alist($validatorlinks, ['class' => 'list-unstyled ml-1']);
949 $output .= html_writer::div($validatorlinkslist, 'validators');
951 return $output;
955 * Returns standard main content placeholder.
956 * Designed to be called in theme layout.php files.
958 * @return string HTML fragment.
960 public function main_content() {
961 // This is here because it is the only place we can inject the "main" role over the entire main content area
962 // without requiring all theme's to manually do it, and without creating yet another thing people need to
963 // remember in the theme.
964 // This is an unfortunate hack. DO NO EVER add anything more here.
965 // DO NOT add classes.
966 // DO NOT add an id.
967 return '<div role="main">'.$this->unique_main_content_token.'</div>';
971 * Returns information about an activity.
973 * @deprecated since Moodle 4.3 MDL-78744
974 * @todo MDL-78926 This method will be deleted in Moodle 4.7
975 * @param cm_info $cminfo The course module information.
976 * @param cm_completion_details $completiondetails The completion details for this activity module.
977 * @param array $activitydates The dates for this activity module.
978 * @return string the activity information HTML.
979 * @throws coding_exception
981 public function activity_information(cm_info $cminfo, cm_completion_details $completiondetails, array $activitydates): string {
982 debugging('activity_information method is deprecated.', DEBUG_DEVELOPER);
983 if (!$completiondetails->has_completion() && empty($activitydates)) {
984 // No need to render the activity information when there's no completion info and activity dates to show.
985 return '';
987 $activityinfo = new activity_information($cminfo, $completiondetails, $activitydates);
988 $renderer = $this->page->get_renderer('core', 'course');
989 return $renderer->render($activityinfo);
993 * Returns standard navigation between activities in a course.
995 * @return string the navigation HTML.
997 public function activity_navigation() {
998 // First we should check if we want to add navigation.
999 $context = $this->page->context;
1000 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
1001 || $context->contextlevel != CONTEXT_MODULE) {
1002 return '';
1005 // If the activity is in stealth mode, show no links.
1006 if ($this->page->cm->is_stealth()) {
1007 return '';
1010 $course = $this->page->cm->get_course();
1011 $courseformat = course_get_format($course);
1013 // If the theme implements course index and the current course format uses course index and the current
1014 // page layout is not 'frametop' (this layout does not support course index), show no links.
1015 if ($this->page->theme->usescourseindex && $courseformat->uses_course_index() &&
1016 $this->page->pagelayout !== 'frametop') {
1017 return '';
1020 // Get a list of all the activities in the course.
1021 $modules = get_fast_modinfo($course->id)->get_cms();
1023 // Put the modules into an array in order by the position they are shown in the course.
1024 $mods = [];
1025 $activitylist = [];
1026 foreach ($modules as $module) {
1027 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
1028 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
1029 continue;
1031 $mods[$module->id] = $module;
1033 // No need to add the current module to the list for the activity dropdown menu.
1034 if ($module->id == $this->page->cm->id) {
1035 continue;
1037 // Module name.
1038 $modname = $module->get_formatted_name();
1039 // Display the hidden text if necessary.
1040 if (!$module->visible) {
1041 $modname .= ' ' . get_string('hiddenwithbrackets');
1043 // Module URL.
1044 $linkurl = new moodle_url($module->url, array('forceview' => 1));
1045 // Add module URL (as key) and name (as value) to the activity list array.
1046 $activitylist[$linkurl->out(false)] = $modname;
1049 $nummods = count($mods);
1051 // If there is only one mod then do nothing.
1052 if ($nummods == 1) {
1053 return '';
1056 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
1057 $modids = array_keys($mods);
1059 // Get the position in the array of the course module we are viewing.
1060 $position = array_search($this->page->cm->id, $modids);
1062 $prevmod = null;
1063 $nextmod = null;
1065 // Check if we have a previous mod to show.
1066 if ($position > 0) {
1067 $prevmod = $mods[$modids[$position - 1]];
1070 // Check if we have a next mod to show.
1071 if ($position < ($nummods - 1)) {
1072 $nextmod = $mods[$modids[$position + 1]];
1075 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
1076 $renderer = $this->page->get_renderer('core', 'course');
1077 return $renderer->render($activitynav);
1081 * The standard tags (typically script tags that are not needed earlier) that
1082 * should be output after everything else. Designed to be called in theme layout.php files.
1084 * @return string HTML fragment.
1086 public function standard_end_of_body_html() {
1087 global $CFG;
1089 // This function is normally called from a layout.php file in {@link core_renderer::header()}
1090 // but some of the content won't be known until later, so we return a placeholder
1091 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
1092 $output = '';
1093 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
1094 $output .= "\n".$CFG->additionalhtmlfooter;
1096 $output .= $this->unique_end_html_token;
1097 return $output;
1101 * The standard HTML that should be output just before the <footer> tag.
1102 * Designed to be called in theme layout.php files.
1104 * @return string HTML fragment.
1106 public function standard_after_main_region_html() {
1107 global $CFG;
1108 $output = '';
1109 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlbottomofbody)) {
1110 $output .= "\n".$CFG->additionalhtmlbottomofbody;
1113 // Give subsystems an opportunity to inject extra html content. The callback
1114 // must always return a string containing valid html.
1115 foreach (\core_component::get_core_subsystems() as $name => $path) {
1116 if ($path) {
1117 $output .= component_callback($name, 'standard_after_main_region_html', [], '');
1121 // Give plugins an opportunity to inject extra html content. The callback
1122 // must always return a string containing valid html.
1123 $pluginswithfunction = get_plugins_with_function('standard_after_main_region_html', 'lib.php');
1124 foreach ($pluginswithfunction as $plugins) {
1125 foreach ($plugins as $function) {
1126 $output .= $function();
1130 return $output;
1134 * Return the standard string that says whether you are logged in (and switched
1135 * roles/logged in as another user).
1136 * @param bool $withlinks if false, then don't include any links in the HTML produced.
1137 * If not set, the default is the nologinlinks option from the theme config.php file,
1138 * and if that is not set, then links are included.
1139 * @return string HTML fragment.
1141 public function login_info($withlinks = null) {
1142 global $USER, $CFG, $DB, $SESSION;
1144 if (during_initial_install()) {
1145 return '';
1148 if (is_null($withlinks)) {
1149 $withlinks = empty($this->page->layout_options['nologinlinks']);
1152 $course = $this->page->course;
1153 if (\core\session\manager::is_loggedinas()) {
1154 $realuser = \core\session\manager::get_realuser();
1155 $fullname = fullname($realuser);
1156 if ($withlinks) {
1157 $loginastitle = get_string('loginas');
1158 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
1159 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
1160 } else {
1161 $realuserinfo = " [$fullname] ";
1163 } else {
1164 $realuserinfo = '';
1167 $loginpage = $this->is_login_page();
1168 $loginurl = get_login_url();
1170 if (empty($course->id)) {
1171 // $course->id is not defined during installation
1172 return '';
1173 } else if (isloggedin()) {
1174 $context = context_course::instance($course->id);
1176 $fullname = fullname($USER);
1177 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
1178 if ($withlinks) {
1179 $linktitle = get_string('viewprofile');
1180 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
1181 } else {
1182 $username = $fullname;
1184 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
1185 if ($withlinks) {
1186 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1187 } else {
1188 $username .= " from {$idprovider->name}";
1191 if (isguestuser()) {
1192 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1193 if (!$loginpage && $withlinks) {
1194 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1196 } else if (is_role_switched($course->id)) { // Has switched roles
1197 $rolename = '';
1198 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1199 $rolename = ': '.role_get_name($role, $context);
1201 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1202 if ($withlinks) {
1203 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1204 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1206 } else {
1207 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1208 if ($withlinks) {
1209 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1212 } else {
1213 $loggedinas = get_string('loggedinnot', 'moodle');
1214 if (!$loginpage && $withlinks) {
1215 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1219 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1221 if (isset($SESSION->justloggedin)) {
1222 unset($SESSION->justloggedin);
1223 if (!isguestuser()) {
1224 // Include this file only when required.
1225 require_once($CFG->dirroot . '/user/lib.php');
1226 if (($count = user_count_login_failures($USER)) && !empty($CFG->displayloginfailures)) {
1227 $loggedinas .= '<div class="loginfailures">';
1228 $a = new stdClass();
1229 $a->attempts = $count;
1230 $loggedinas .= get_string('failedloginattempts', '', $a);
1231 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1232 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1233 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1235 $loggedinas .= '</div>';
1240 return $loggedinas;
1244 * Check whether the current page is a login page.
1246 * @since Moodle 2.9
1247 * @return bool
1249 protected function is_login_page() {
1250 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1251 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1252 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1253 return in_array(
1254 $this->page->url->out_as_local_url(false, array()),
1255 array(
1256 '/login/index.php',
1257 '/login/forgot_password.php',
1263 * Return the 'back' link that normally appears in the footer.
1265 * @return string HTML fragment.
1267 public function home_link() {
1268 global $CFG, $SITE;
1270 if ($this->page->pagetype == 'site-index') {
1271 // Special case for site home page - please do not remove
1272 return '<div class="sitelink">' .
1273 '<a title="Moodle" class="d-inline-block aalink" href="http://moodle.org/">' .
1274 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1276 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1277 // Special case for during install/upgrade.
1278 return '<div class="sitelink">'.
1279 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1280 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1282 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1283 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1284 get_string('home') . '</a></div>';
1286 } else {
1287 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1288 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1293 * Redirects the user by any means possible given the current state
1295 * This function should not be called directly, it should always be called using
1296 * the redirect function in lib/weblib.php
1298 * The redirect function should really only be called before page output has started
1299 * however it will allow itself to be called during the state STATE_IN_BODY
1301 * @param string $encodedurl The URL to send to encoded if required
1302 * @param string $message The message to display to the user if any
1303 * @param int $delay The delay before redirecting a user, if $message has been
1304 * set this is a requirement and defaults to 3, set to 0 no delay
1305 * @param boolean $debugdisableredirect this redirect has been disabled for
1306 * debugging purposes. Display a message that explains, and don't
1307 * trigger the redirect.
1308 * @param string $messagetype The type of notification to show the message in.
1309 * See constants on \core\output\notification.
1310 * @return string The HTML to display to the user before dying, may contain
1311 * meta refresh, javascript refresh, and may have set header redirects
1313 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1314 $messagetype = \core\output\notification::NOTIFY_INFO) {
1315 global $CFG;
1316 $url = str_replace('&amp;', '&', $encodedurl);
1318 switch ($this->page->state) {
1319 case moodle_page::STATE_BEFORE_HEADER :
1320 // No output yet it is safe to delivery the full arsenal of redirect methods
1321 if (!$debugdisableredirect) {
1322 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1323 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1324 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1326 $output = $this->header();
1327 break;
1328 case moodle_page::STATE_PRINTING_HEADER :
1329 // We should hopefully never get here
1330 throw new coding_exception('You cannot redirect while printing the page header');
1331 break;
1332 case moodle_page::STATE_IN_BODY :
1333 // We really shouldn't be here but we can deal with this
1334 debugging("You should really redirect before you start page output");
1335 if (!$debugdisableredirect) {
1336 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1338 $output = $this->opencontainers->pop_all_but_last();
1339 break;
1340 case moodle_page::STATE_DONE :
1341 // Too late to be calling redirect now
1342 throw new coding_exception('You cannot redirect after the entire page has been generated');
1343 break;
1345 $output .= $this->notification($message, $messagetype);
1346 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1347 if ($debugdisableredirect) {
1348 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1350 $output .= $this->footer();
1351 return $output;
1355 * Start output by sending the HTTP headers, and printing the HTML <head>
1356 * and the start of the <body>.
1358 * To control what is printed, you should set properties on $PAGE.
1360 * @return string HTML that you must output this, preferably immediately.
1362 public function header() {
1363 global $USER, $CFG, $SESSION;
1365 // Give plugins an opportunity touch things before the http headers are sent
1366 // such as adding additional headers. The return value is ignored.
1367 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1368 foreach ($pluginswithfunction as $plugins) {
1369 foreach ($plugins as $function) {
1370 $function();
1374 if (\core\session\manager::is_loggedinas()) {
1375 $this->page->add_body_class('userloggedinas');
1378 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1379 require_once($CFG->dirroot . '/user/lib.php');
1380 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1381 if ($count = user_count_login_failures($USER, false)) {
1382 $this->page->add_body_class('loginfailures');
1386 // If the user is logged in, and we're not in initial install,
1387 // check to see if the user is role-switched and add the appropriate
1388 // CSS class to the body element.
1389 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1390 $this->page->add_body_class('userswitchedrole');
1393 // Give themes a chance to init/alter the page object.
1394 $this->page->theme->init_page($this->page);
1396 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1398 // Find the appropriate page layout file, based on $this->page->pagelayout.
1399 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1400 // Render the layout using the layout file.
1401 $rendered = $this->render_page_layout($layoutfile);
1403 // Slice the rendered output into header and footer.
1404 $cutpos = strpos($rendered, $this->unique_main_content_token);
1405 if ($cutpos === false) {
1406 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1407 $token = self::MAIN_CONTENT_TOKEN;
1408 } else {
1409 $token = $this->unique_main_content_token;
1412 if ($cutpos === false) {
1413 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.');
1415 $header = substr($rendered, 0, $cutpos);
1416 $footer = substr($rendered, $cutpos + strlen($token));
1418 if (empty($this->contenttype)) {
1419 debugging('The page layout file did not call $OUTPUT->doctype()');
1420 $header = $this->doctype() . $header;
1423 // If this theme version is below 2.4 release and this is a course view page
1424 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1425 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1426 // check if course content header/footer have not been output during render of theme layout
1427 $coursecontentheader = $this->course_content_header(true);
1428 $coursecontentfooter = $this->course_content_footer(true);
1429 if (!empty($coursecontentheader)) {
1430 // display debug message and add header and footer right above and below main content
1431 // Please note that course header and footer (to be displayed above and below the whole page)
1432 // are not displayed in this case at all.
1433 // Besides the content header and footer are not displayed on any other course page
1434 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);
1435 $header .= $coursecontentheader;
1436 $footer = $coursecontentfooter. $footer;
1440 send_headers($this->contenttype, $this->page->cacheable);
1442 $this->opencontainers->push('header/footer', $footer);
1443 $this->page->set_state(moodle_page::STATE_IN_BODY);
1445 // If an activity record has been set, activity_header will handle this.
1446 if (!$this->page->cm || !empty($this->page->layout_options['noactivityheader'])) {
1447 $header .= $this->skip_link_target('maincontent');
1449 return $header;
1453 * Renders and outputs the page layout file.
1455 * This is done by preparing the normal globals available to a script, and
1456 * then including the layout file provided by the current theme for the
1457 * requested layout.
1459 * @param string $layoutfile The name of the layout file
1460 * @return string HTML code
1462 protected function render_page_layout($layoutfile) {
1463 global $CFG, $SITE, $USER;
1464 // The next lines are a bit tricky. The point is, here we are in a method
1465 // of a renderer class, and this object may, or may not, be the same as
1466 // the global $OUTPUT object. When rendering the page layout file, we want to use
1467 // this object. However, people writing Moodle code expect the current
1468 // renderer to be called $OUTPUT, not $this, so define a variable called
1469 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1470 $OUTPUT = $this;
1471 $PAGE = $this->page;
1472 $COURSE = $this->page->course;
1474 ob_start();
1475 include($layoutfile);
1476 $rendered = ob_get_contents();
1477 ob_end_clean();
1478 return $rendered;
1482 * Outputs the page's footer
1484 * @return string HTML fragment
1486 public function footer() {
1487 global $CFG, $DB, $PERF;
1489 $output = '';
1491 // Give plugins an opportunity to touch the page before JS is finalized.
1492 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1493 foreach ($pluginswithfunction as $plugins) {
1494 foreach ($plugins as $function) {
1495 $extrafooter = $function();
1496 if (is_string($extrafooter)) {
1497 $output .= $extrafooter;
1502 $output .= $this->container_end_all(true);
1504 $footer = $this->opencontainers->pop('header/footer');
1506 if (debugging() and $DB and $DB->is_transaction_started()) {
1507 // TODO: MDL-20625 print warning - transaction will be rolled back
1510 // Provide some performance info if required
1511 $performanceinfo = '';
1512 if (MDL_PERF || (!empty($CFG->perfdebug) && $CFG->perfdebug > 7)) {
1513 if (MDL_PERFTOFOOT || debugging() || (!empty($CFG->perfdebug) && $CFG->perfdebug > 7)) {
1514 if (NO_OUTPUT_BUFFERING) {
1515 // If the output buffer was off then we render a placeholder and stream the
1516 // performance debugging into it at the very end in the shutdown handler.
1517 $PERF->perfdebugdeferred = true;
1518 $performanceinfo .= html_writer::tag('div',
1519 get_string('perfdebugdeferred', 'admin'),
1521 'id' => 'perfdebugfooter',
1522 'style' => 'min-height: 30em',
1524 } else {
1525 $perf = get_performance_info();
1526 $performanceinfo = $perf['html'];
1531 // We always want performance data when running a performance test, even if the user is redirected to another page.
1532 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1533 $footer = $this->unique_performance_info_token . $footer;
1535 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1537 // Only show notifications when the current page has a context id.
1538 if (!empty($this->page->context->id)) {
1539 $this->page->requires->js_call_amd('core/notification', 'init', array(
1540 $this->page->context->id,
1541 \core\notification::fetch_as_array($this)
1544 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1546 $this->page->set_state(moodle_page::STATE_DONE);
1548 // Here we remove the closing body and html tags and store them to be added back
1549 // in the shutdown handler so we can have valid html with streaming script tags
1550 // which are rendered after the visible footer.
1551 $tags = '';
1552 preg_match('#\<\/body>#i', $footer, $matches);
1553 $tags .= $matches[0];
1554 $footer = str_replace($matches[0], '', $footer);
1556 preg_match('#\<\/html>#i', $footer, $matches);
1557 $tags .= $matches[0];
1558 $footer = str_replace($matches[0], '', $footer);
1560 $CFG->closingtags = $tags;
1562 return $output . $footer;
1566 * Close all but the last open container. This is useful in places like error
1567 * handling, where you want to close all the open containers (apart from <body>)
1568 * before outputting the error message.
1570 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1571 * developer debug warning if it isn't.
1572 * @return string the HTML required to close any open containers inside <body>.
1574 public function container_end_all($shouldbenone = false) {
1575 return $this->opencontainers->pop_all_but_last($shouldbenone);
1579 * Returns course-specific information to be output immediately above content on any course page
1580 * (for the current course)
1582 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1583 * @return string
1585 public function course_content_header($onlyifnotcalledbefore = false) {
1586 global $CFG;
1587 static $functioncalled = false;
1588 if ($functioncalled && $onlyifnotcalledbefore) {
1589 // we have already output the content header
1590 return '';
1593 // Output any session notification.
1594 $notifications = \core\notification::fetch();
1596 $bodynotifications = '';
1597 foreach ($notifications as $notification) {
1598 $bodynotifications .= $this->render_from_template(
1599 $notification->get_template_name(),
1600 $notification->export_for_template($this)
1604 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1606 if ($this->page->course->id == SITEID) {
1607 // return immediately and do not include /course/lib.php if not necessary
1608 return $output;
1611 require_once($CFG->dirroot.'/course/lib.php');
1612 $functioncalled = true;
1613 $courseformat = course_get_format($this->page->course);
1614 if (($obj = $courseformat->course_content_header()) !== null) {
1615 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1617 return $output;
1621 * Returns course-specific information to be output immediately below content on any course page
1622 * (for the current course)
1624 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1625 * @return string
1627 public function course_content_footer($onlyifnotcalledbefore = false) {
1628 global $CFG;
1629 if ($this->page->course->id == SITEID) {
1630 // return immediately and do not include /course/lib.php if not necessary
1631 return '';
1633 static $functioncalled = false;
1634 if ($functioncalled && $onlyifnotcalledbefore) {
1635 // we have already output the content footer
1636 return '';
1638 $functioncalled = true;
1639 require_once($CFG->dirroot.'/course/lib.php');
1640 $courseformat = course_get_format($this->page->course);
1641 if (($obj = $courseformat->course_content_footer()) !== null) {
1642 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1644 return '';
1648 * Returns course-specific information to be output on any course page in the header area
1649 * (for the current course)
1651 * @return string
1653 public function course_header() {
1654 global $CFG;
1655 if ($this->page->course->id == SITEID) {
1656 // return immediately and do not include /course/lib.php if not necessary
1657 return '';
1659 require_once($CFG->dirroot.'/course/lib.php');
1660 $courseformat = course_get_format($this->page->course);
1661 if (($obj = $courseformat->course_header()) !== null) {
1662 return $courseformat->get_renderer($this->page)->render($obj);
1664 return '';
1668 * Returns course-specific information to be output on any course page in the footer area
1669 * (for the current course)
1671 * @return string
1673 public function course_footer() {
1674 global $CFG;
1675 if ($this->page->course->id == SITEID) {
1676 // return immediately and do not include /course/lib.php if not necessary
1677 return '';
1679 require_once($CFG->dirroot.'/course/lib.php');
1680 $courseformat = course_get_format($this->page->course);
1681 if (($obj = $courseformat->course_footer()) !== null) {
1682 return $courseformat->get_renderer($this->page)->render($obj);
1684 return '';
1688 * Get the course pattern datauri to show on a course card.
1690 * The datauri is an encoded svg that can be passed as a url.
1691 * @param int $id Id to use when generating the pattern
1692 * @return string datauri
1694 public function get_generated_image_for_id($id) {
1695 $color = $this->get_generated_color_for_id($id);
1696 $pattern = new \core_geopattern();
1697 $pattern->setColor($color);
1698 $pattern->patternbyid($id);
1699 return $pattern->datauri();
1703 * Get the course pattern image URL.
1705 * @param context_course $context course context object
1706 * @return string URL of the course pattern image in SVG format
1708 public function get_generated_url_for_course(context_course $context): string {
1709 return moodle_url::make_pluginfile_url($context->id, 'course', 'generated', null, '/', 'course.svg')->out();
1713 * Get the course pattern in SVG format to show on a course card.
1715 * @param int $id id to use when generating the pattern
1716 * @return string SVG file contents
1718 public function get_generated_svg_for_id(int $id): string {
1719 $color = $this->get_generated_color_for_id($id);
1720 $pattern = new \core_geopattern();
1721 $pattern->setColor($color);
1722 $pattern->patternbyid($id);
1723 return $pattern->toSVG();
1727 * Get the course color to show on a course card.
1729 * @param int $id Id to use when generating the color.
1730 * @return string hex color code.
1732 public function get_generated_color_for_id($id) {
1733 $colornumbers = range(1, 10);
1734 $basecolors = [];
1735 foreach ($colornumbers as $number) {
1736 $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1739 $color = $basecolors[$id % 10];
1740 return $color;
1744 * Returns lang menu or '', this method also checks forcing of languages in courses.
1746 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1748 * @return string The lang menu HTML or empty string
1750 public function lang_menu() {
1751 $languagemenu = new \core\output\language_menu($this->page);
1752 $data = $languagemenu->export_for_single_select($this);
1753 if ($data) {
1754 return $this->render_from_template('core/single_select', $data);
1756 return '';
1760 * Output the row of editing icons for a block, as defined by the controls array.
1762 * @param array $controls an array like {@link block_contents::$controls}.
1763 * @param string $blockid The ID given to the block.
1764 * @return string HTML fragment.
1766 public function block_controls($actions, $blockid = null) {
1767 if (empty($actions)) {
1768 return '';
1770 $menu = new action_menu($actions);
1771 if ($blockid !== null) {
1772 $menu->set_owner_selector('#'.$blockid);
1774 $menu->attributes['class'] .= ' block-control-actions commands';
1775 return $this->render($menu);
1779 * Returns the HTML for a basic textarea field.
1781 * @param string $name Name to use for the textarea element
1782 * @param string $id The id to use fort he textarea element
1783 * @param string $value Initial content to display in the textarea
1784 * @param int $rows Number of rows to display
1785 * @param int $cols Number of columns to display
1786 * @return string the HTML to display
1788 public function print_textarea($name, $id, $value, $rows, $cols) {
1789 editors_head_setup();
1790 $editor = editors_get_preferred_editor(FORMAT_HTML);
1791 $editor->set_text($value);
1792 $editor->use_editor($id, []);
1794 $context = [
1795 'id' => $id,
1796 'name' => $name,
1797 'value' => $value,
1798 'rows' => $rows,
1799 'cols' => $cols
1802 return $this->render_from_template('core_form/editor_textarea', $context);
1806 * Renders an action menu component.
1808 * @param action_menu $menu
1809 * @return string HTML
1811 public function render_action_menu(action_menu $menu) {
1813 // We don't want the class icon there!
1814 foreach ($menu->get_secondary_actions() as $action) {
1815 if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1816 $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1820 if ($menu->is_empty()) {
1821 return '';
1823 $context = $menu->export_for_template($this);
1825 return $this->render_from_template('core/action_menu', $context);
1829 * Renders a full check API result including summary and details
1831 * @param core\check\check $check the check that was run to get details from
1832 * @param core\check\result $result the result of a check
1833 * @param bool $includedetails if true, details are included as well
1834 * @return string rendered html
1836 protected function render_check_full_result(core\check\check $check, core\check\result $result, bool $includedetails): string {
1837 // Initially render just badge itself.
1838 $renderedresult = $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1840 // Add summary.
1841 $renderedresult .= ' ' . $result->get_summary();
1843 // Wrap in notificaiton.
1844 $notificationmap = [
1845 \core\check\result::NA => \core\output\notification::NOTIFY_INFO,
1846 \core\check\result::OK => \core\output\notification::NOTIFY_SUCCESS,
1847 \core\check\result::INFO => \core\output\notification::NOTIFY_INFO,
1848 \core\check\result::UNKNOWN => \core\output\notification::NOTIFY_WARNING,
1849 \core\check\result::WARNING => \core\output\notification::NOTIFY_WARNING,
1850 \core\check\result::ERROR => \core\output\notification::NOTIFY_ERROR,
1851 \core\check\result::CRITICAL => \core\output\notification::NOTIFY_ERROR,
1854 // Get type, or default to error.
1855 $notificationtype = $notificationmap[$result->get_status()] ?? \core\output\notification::NOTIFY_ERROR;
1856 $renderedresult = $this->notification($renderedresult, $notificationtype, false);
1858 // If adding details, add on new line.
1859 if ($includedetails) {
1860 $renderedresult .= $result->get_details();
1863 // Add the action link.
1864 $renderedresult .= $this->render_action_link($check->get_action_link());
1866 return $renderedresult;
1870 * Renders a full check API result including summary and details
1872 * @param core\check\check $check the check that was run to get details from
1873 * @param core\check\result $result the result of a check
1874 * @param bool $includedetails if details should be included
1875 * @return string HTML fragment
1877 public function check_full_result(core\check\check $check, core\check\result $result, bool $includedetails = false) {
1878 return $this->render_check_full_result($check, $result, $includedetails);
1882 * Renders a Check API result
1884 * @param core\check\result $result
1885 * @return string HTML fragment
1887 protected function render_check_result(core\check\result $result) {
1888 return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1892 * Renders a Check API result
1894 * @param core\check\result $result
1895 * @return string HTML fragment
1897 public function check_result(core\check\result $result) {
1898 return $this->render_check_result($result);
1902 * Renders an action_menu_link item.
1904 * @param action_menu_link $action
1905 * @return string HTML fragment
1907 protected function render_action_menu_link(action_menu_link $action) {
1908 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1912 * Renders a primary action_menu_filler item.
1914 * @param action_menu_link_filler $action
1915 * @return string HTML fragment
1917 protected function render_action_menu_filler(action_menu_filler $action) {
1918 return html_writer::span('&nbsp;', 'filler');
1922 * Renders a primary action_menu_link item.
1924 * @param action_menu_link_primary $action
1925 * @return string HTML fragment
1927 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1928 return $this->render_action_menu_link($action);
1932 * Renders a secondary action_menu_link item.
1934 * @param action_menu_link_secondary $action
1935 * @return string HTML fragment
1937 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1938 return $this->render_action_menu_link($action);
1942 * Prints a nice side block with an optional header.
1944 * @param block_contents $bc HTML for the content
1945 * @param string $region the region the block is appearing in.
1946 * @return string the HTML to be output.
1948 public function block(block_contents $bc, $region) {
1949 $bc = clone($bc); // Avoid messing up the object passed in.
1950 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1951 $bc->collapsible = block_contents::NOT_HIDEABLE;
1954 $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1955 $context = new stdClass();
1956 $context->skipid = $bc->skipid;
1957 $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
1958 $context->dockable = $bc->dockable;
1959 $context->id = $id;
1960 $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1961 $context->skiptitle = strip_tags($bc->title);
1962 $context->showskiplink = !empty($context->skiptitle);
1963 $context->arialabel = $bc->arialabel;
1964 $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
1965 $context->class = $bc->attributes['class'];
1966 $context->type = $bc->attributes['data-block'];
1967 $context->title = $bc->title;
1968 $context->content = $bc->content;
1969 $context->annotation = $bc->annotation;
1970 $context->footer = $bc->footer;
1971 $context->hascontrols = !empty($bc->controls);
1972 if ($context->hascontrols) {
1973 $context->controls = $this->block_controls($bc->controls, $id);
1976 return $this->render_from_template('core/block', $context);
1980 * Render the contents of a block_list.
1982 * @param array $icons the icon for each item.
1983 * @param array $items the content of each item.
1984 * @return string HTML
1986 public function list_block_contents($icons, $items) {
1987 $row = 0;
1988 $lis = array();
1989 foreach ($items as $key => $string) {
1990 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1991 if (!empty($icons[$key])) { //test if the content has an assigned icon
1992 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1994 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1995 $item .= html_writer::end_tag('li');
1996 $lis[] = $item;
1997 $row = 1 - $row; // Flip even/odd.
1999 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
2003 * Output all the blocks in a particular region.
2005 * @param string $region the name of a region on this page.
2006 * @param boolean $fakeblocksonly Output fake block only.
2007 * @return string the HTML to be output.
2009 public function blocks_for_region($region, $fakeblocksonly = false) {
2010 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
2011 $lastblock = null;
2012 $zones = array();
2013 foreach ($blockcontents as $bc) {
2014 if ($bc instanceof block_contents) {
2015 $zones[] = $bc->title;
2018 $output = '';
2020 foreach ($blockcontents as $bc) {
2021 if ($bc instanceof block_contents) {
2022 if ($fakeblocksonly && !$bc->is_fake()) {
2023 // Skip rendering real blocks if we only want to show fake blocks.
2024 continue;
2026 $output .= $this->block($bc, $region);
2027 $lastblock = $bc->title;
2028 } else if ($bc instanceof block_move_target) {
2029 if (!$fakeblocksonly) {
2030 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
2032 } else {
2033 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
2036 return $output;
2040 * Output a place where the block that is currently being moved can be dropped.
2042 * @param block_move_target $target with the necessary details.
2043 * @param array $zones array of areas where the block can be moved to
2044 * @param string $previous the block located before the area currently being rendered.
2045 * @param string $region the name of the region
2046 * @return string the HTML to be output.
2048 public function block_move_target($target, $zones, $previous, $region) {
2049 if ($previous == null) {
2050 if (empty($zones)) {
2051 // There are no zones, probably because there are no blocks.
2052 $regions = $this->page->theme->get_all_block_regions();
2053 $position = get_string('moveblockinregion', 'block', $regions[$region]);
2054 } else {
2055 $position = get_string('moveblockbefore', 'block', $zones[0]);
2057 } else {
2058 $position = get_string('moveblockafter', 'block', $previous);
2060 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
2064 * Renders a special html link with attached action
2066 * Theme developers: DO NOT OVERRIDE! Please override function
2067 * {@link core_renderer::render_action_link()} instead.
2069 * @param string|moodle_url $url
2070 * @param string $text HTML fragment
2071 * @param component_action $action
2072 * @param array $attributes associative array of html link attributes + disabled
2073 * @param pix_icon optional pix icon to render with the link
2074 * @return string HTML fragment
2076 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
2077 if (!($url instanceof moodle_url)) {
2078 $url = new moodle_url($url);
2080 $link = new action_link($url, $text, $action, $attributes, $icon);
2082 return $this->render($link);
2086 * Renders an action_link object.
2088 * The provided link is renderer and the HTML returned. At the same time the
2089 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
2091 * @param action_link $link
2092 * @return string HTML fragment
2094 protected function render_action_link(action_link $link) {
2095 return $this->render_from_template('core/action_link', $link->export_for_template($this));
2099 * Renders an action_icon.
2101 * This function uses the {@link core_renderer::action_link()} method for the
2102 * most part. What it does different is prepare the icon as HTML and use it
2103 * as the link text.
2105 * Theme developers: If you want to change how action links and/or icons are rendered,
2106 * consider overriding function {@link core_renderer::render_action_link()} and
2107 * {@link core_renderer::render_pix_icon()}.
2109 * @param string|moodle_url $url A string URL or moodel_url
2110 * @param pix_icon $pixicon
2111 * @param component_action $action
2112 * @param array $attributes associative array of html link attributes + disabled
2113 * @param bool $linktext show title next to image in link
2114 * @return string HTML fragment
2116 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
2117 if (!($url instanceof moodle_url)) {
2118 $url = new moodle_url($url);
2120 $attributes = (array)$attributes;
2122 if (empty($attributes['class'])) {
2123 // let ppl override the class via $options
2124 $attributes['class'] = 'action-icon';
2127 $icon = $this->render($pixicon);
2129 if ($linktext) {
2130 $text = $pixicon->attributes['alt'];
2131 } else {
2132 $text = '';
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', 'role' => 'presentation'));
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'], $button['title'], 'moodle', array(
4667 'class' => 'iconsmall',
4668 'role' => 'presentation'
4670 $image .= html_writer::span($button['title'], 'header-button-title');
4671 } else {
4672 $image = html_writer::empty_tag('img', array(
4673 'src' => $button['formattedimage'],
4674 'role' => 'presentation'
4677 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4679 $html .= html_writer::end_div();
4681 $html .= html_writer::end_div();
4683 return $html;
4687 * Wrapper for header elements.
4689 * @return string HTML to display the main header.
4691 public function full_header() {
4692 $pagetype = $this->page->pagetype;
4693 $homepage = get_home_page();
4694 $homepagetype = null;
4695 // Add a special case since /my/courses is a part of the /my subsystem.
4696 if ($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES) {
4697 $homepagetype = 'my-index';
4698 } else if ($homepage == HOMEPAGE_SITE) {
4699 $homepagetype = 'site-index';
4701 if ($this->page->include_region_main_settings_in_header_actions() &&
4702 !$this->page->blocks->is_block_present('settings')) {
4703 // Only include the region main settings if the page has requested it and it doesn't already have
4704 // the settings block on it. The region main settings are included in the settings block and
4705 // duplicating the content causes behat failures.
4706 $this->page->add_header_action(html_writer::div(
4707 $this->region_main_settings_menu(),
4708 'd-print-none',
4709 ['id' => 'region-main-settings-menu']
4713 $header = new stdClass();
4714 $header->settingsmenu = $this->context_header_settings_menu();
4715 $header->contextheader = $this->context_header();
4716 $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
4717 $header->navbar = $this->navbar();
4718 $header->pageheadingbutton = $this->page_heading_button();
4719 $header->courseheader = $this->course_header();
4720 $header->headeractions = $this->page->get_header_actions();
4721 if (!empty($pagetype) && !empty($homepagetype) && $pagetype == $homepagetype) {
4722 $header->welcomemessage = \core_user::welcome_message();
4724 return $this->render_from_template('core/full_header', $header);
4728 * This is an optional menu that can be added to a layout by a theme. It contains the
4729 * menu for the course administration, only on the course main page.
4731 * @return string
4733 public function context_header_settings_menu() {
4734 $context = $this->page->context;
4735 $menu = new action_menu();
4737 $items = $this->page->navbar->get_items();
4738 $currentnode = end($items);
4740 $showcoursemenu = false;
4741 $showfrontpagemenu = false;
4742 $showusermenu = false;
4744 // We are on the course home page.
4745 if (($context->contextlevel == CONTEXT_COURSE) &&
4746 !empty($currentnode) &&
4747 ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
4748 $showcoursemenu = true;
4751 $courseformat = course_get_format($this->page->course);
4752 // This is a single activity course format, always show the course menu on the activity main page.
4753 if ($context->contextlevel == CONTEXT_MODULE &&
4754 !$courseformat->has_view_page()) {
4756 $this->page->navigation->initialise();
4757 $activenode = $this->page->navigation->find_active_node();
4758 // If the settings menu has been forced then show the menu.
4759 if ($this->page->is_settings_menu_forced()) {
4760 $showcoursemenu = true;
4761 } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
4762 $activenode->type == navigation_node::TYPE_RESOURCE)) {
4764 // We only want to show the menu on the first page of the activity. This means
4765 // the breadcrumb has no additional nodes.
4766 if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
4767 $showcoursemenu = true;
4772 // This is the site front page.
4773 if ($context->contextlevel == CONTEXT_COURSE &&
4774 !empty($currentnode) &&
4775 $currentnode->key === 'home') {
4776 $showfrontpagemenu = true;
4779 // This is the user profile page.
4780 if ($context->contextlevel == CONTEXT_USER &&
4781 !empty($currentnode) &&
4782 ($currentnode->key === 'myprofile')) {
4783 $showusermenu = true;
4786 if ($showfrontpagemenu) {
4787 $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
4788 if ($settingsnode) {
4789 // Build an action menu based on the visible nodes from this navigation tree.
4790 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4792 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4793 if ($skipped) {
4794 $text = get_string('morenavigationlinks');
4795 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4796 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4797 $menu->add_secondary_action($link);
4800 } else if ($showcoursemenu) {
4801 $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
4802 if ($settingsnode) {
4803 // Build an action menu based on the visible nodes from this navigation tree.
4804 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4806 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4807 if ($skipped) {
4808 $text = get_string('morenavigationlinks');
4809 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4810 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4811 $menu->add_secondary_action($link);
4814 } else if ($showusermenu) {
4815 // Get the course admin node from the settings navigation.
4816 $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
4817 if ($settingsnode) {
4818 // Build an action menu based on the visible nodes from this navigation tree.
4819 $this->build_action_menu_from_navigation($menu, $settingsnode);
4823 return $this->render($menu);
4827 * Take a node in the nav tree and make an action menu out of it.
4828 * The links are injected in the action menu.
4830 * @param action_menu $menu
4831 * @param navigation_node $node
4832 * @param boolean $indent
4833 * @param boolean $onlytopleafnodes
4834 * @return boolean nodesskipped - True if nodes were skipped in building the menu
4836 protected function build_action_menu_from_navigation(action_menu $menu,
4837 navigation_node $node,
4838 $indent = false,
4839 $onlytopleafnodes = false) {
4840 $skipped = false;
4841 // Build an action menu based on the visible nodes from this navigation tree.
4842 foreach ($node->children as $menuitem) {
4843 if ($menuitem->display) {
4844 if ($onlytopleafnodes && $menuitem->children->count()) {
4845 $skipped = true;
4846 continue;
4848 if ($menuitem->action) {
4849 if ($menuitem->action instanceof action_link) {
4850 $link = $menuitem->action;
4851 // Give preference to setting icon over action icon.
4852 if (!empty($menuitem->icon)) {
4853 $link->icon = $menuitem->icon;
4855 } else {
4856 $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
4858 } else {
4859 if ($onlytopleafnodes) {
4860 $skipped = true;
4861 continue;
4863 $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
4865 if ($indent) {
4866 $link->add_class('ml-4');
4868 if (!empty($menuitem->classes)) {
4869 $link->add_class(implode(" ", $menuitem->classes));
4872 $menu->add_secondary_action($link);
4873 $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
4876 return $skipped;
4880 * This is an optional menu that can be added to a layout by a theme. It contains the
4881 * menu for the most specific thing from the settings block. E.g. Module administration.
4883 * @return string
4885 public function region_main_settings_menu() {
4886 $context = $this->page->context;
4887 $menu = new action_menu();
4889 if ($context->contextlevel == CONTEXT_MODULE) {
4891 $this->page->navigation->initialise();
4892 $node = $this->page->navigation->find_active_node();
4893 $buildmenu = false;
4894 // If the settings menu has been forced then show the menu.
4895 if ($this->page->is_settings_menu_forced()) {
4896 $buildmenu = true;
4897 } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
4898 $node->type == navigation_node::TYPE_RESOURCE)) {
4900 $items = $this->page->navbar->get_items();
4901 $navbarnode = end($items);
4902 // We only want to show the menu on the first page of the activity. This means
4903 // the breadcrumb has no additional nodes.
4904 if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
4905 $buildmenu = true;
4908 if ($buildmenu) {
4909 // Get the course admin node from the settings navigation.
4910 $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
4911 if ($node) {
4912 // Build an action menu based on the visible nodes from this navigation tree.
4913 $this->build_action_menu_from_navigation($menu, $node);
4917 } else if ($context->contextlevel == CONTEXT_COURSECAT) {
4918 // For course category context, show category settings menu, if we're on the course category page.
4919 if ($this->page->pagetype === 'course-index-category') {
4920 $node = $this->page->settingsnav->find('categorysettings', navigation_node::TYPE_CONTAINER);
4921 if ($node) {
4922 // Build an action menu based on the visible nodes from this navigation tree.
4923 $this->build_action_menu_from_navigation($menu, $node);
4927 } else {
4928 $items = $this->page->navbar->get_items();
4929 $navbarnode = end($items);
4931 if ($navbarnode && ($navbarnode->key === 'participants')) {
4932 $node = $this->page->settingsnav->find('users', navigation_node::TYPE_CONTAINER);
4933 if ($node) {
4934 // Build an action menu based on the visible nodes from this navigation tree.
4935 $this->build_action_menu_from_navigation($menu, $node);
4940 return $this->render($menu);
4944 * Displays the list of tags associated with an entry
4946 * @param array $tags list of instances of core_tag or stdClass
4947 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4948 * to use default, set to '' (empty string) to omit the label completely
4949 * @param string $classes additional classes for the enclosing div element
4950 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4951 * will be appended to the end, JS will toggle the rest of the tags
4952 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4953 * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
4954 * @return string
4956 public function tag_list($tags, $label = null, $classes = '', $limit = 10,
4957 $pagecontext = null, $accesshidelabel = false) {
4958 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
4959 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4963 * Renders element for inline editing of any value
4965 * @param \core\output\inplace_editable $element
4966 * @return string
4968 public function render_inplace_editable(\core\output\inplace_editable $element) {
4969 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4973 * Renders a bar chart.
4975 * @param \core\chart_bar $chart The chart.
4976 * @return string
4978 public function render_chart_bar(\core\chart_bar $chart) {
4979 return $this->render_chart($chart);
4983 * Renders a line chart.
4985 * @param \core\chart_line $chart The chart.
4986 * @return string
4988 public function render_chart_line(\core\chart_line $chart) {
4989 return $this->render_chart($chart);
4993 * Renders a pie chart.
4995 * @param \core\chart_pie $chart The chart.
4996 * @return string
4998 public function render_chart_pie(\core\chart_pie $chart) {
4999 return $this->render_chart($chart);
5003 * Renders a chart.
5005 * @param \core\chart_base $chart The chart.
5006 * @param bool $withtable Whether to include a data table with the chart.
5007 * @return string
5009 public function render_chart(\core\chart_base $chart, $withtable = true) {
5010 $chartdata = json_encode($chart);
5011 return $this->render_from_template('core/chart', (object) [
5012 'chartdata' => $chartdata,
5013 'withtable' => $withtable
5018 * Renders the login form.
5020 * @param \core_auth\output\login $form The renderable.
5021 * @return string
5023 public function render_login(\core_auth\output\login $form) {
5024 global $CFG, $SITE;
5026 $context = $form->export_for_template($this);
5028 $context->errorformatted = $this->error_text($context->error);
5029 $url = $this->get_logo_url();
5030 if ($url) {
5031 $url = $url->out(false);
5033 $context->logourl = $url;
5034 $context->sitename = format_string($SITE->fullname, true,
5035 ['context' => context_course::instance(SITEID), "escape" => false]);
5037 return $this->render_from_template('core/loginform', $context);
5041 * Renders an mform element from a template.
5043 * @param HTML_QuickForm_element $element element
5044 * @param bool $required if input is required field
5045 * @param bool $advanced if input is an advanced field
5046 * @param string $error error message to display
5047 * @param bool $ingroup True if this element is rendered as part of a group
5048 * @return mixed string|bool
5050 public function mform_element($element, $required, $advanced, $error, $ingroup) {
5051 $templatename = 'core_form/element-' . $element->getType();
5052 if ($ingroup) {
5053 $templatename .= "-inline";
5055 try {
5056 // We call this to generate a file not found exception if there is no template.
5057 // We don't want to call export_for_template if there is no template.
5058 core\output\mustache_template_finder::get_template_filepath($templatename);
5060 if ($element instanceof templatable) {
5061 $elementcontext = $element->export_for_template($this);
5063 $helpbutton = '';
5064 if (method_exists($element, 'getHelpButton')) {
5065 $helpbutton = $element->getHelpButton();
5067 $label = $element->getLabel();
5068 $text = '';
5069 if (method_exists($element, 'getText')) {
5070 // There currently exists code that adds a form element with an empty label.
5071 // If this is the case then set the label to the description.
5072 if (empty($label)) {
5073 $label = $element->getText();
5074 } else {
5075 $text = $element->getText();
5079 // Generate the form element wrapper ids and names to pass to the template.
5080 // This differs between group and non-group elements.
5081 if ($element->getType() === 'group') {
5082 // Group element.
5083 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
5084 $elementcontext['wrapperid'] = $elementcontext['id'];
5086 // Ensure group elements pass through the group name as the element name.
5087 $elementcontext['name'] = $elementcontext['groupname'];
5088 } else {
5089 // Non grouped element.
5090 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
5091 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
5094 $context = array(
5095 'element' => $elementcontext,
5096 'label' => $label,
5097 'text' => $text,
5098 'required' => $required,
5099 'advanced' => $advanced,
5100 'helpbutton' => $helpbutton,
5101 'error' => $error
5103 return $this->render_from_template($templatename, $context);
5105 } catch (Exception $e) {
5106 // No template for this element.
5107 return false;
5112 * Render the login signup form into a nice template for the theme.
5114 * @param mform $form
5115 * @return string
5117 public function render_login_signup_form($form) {
5118 global $SITE;
5120 $context = $form->export_for_template($this);
5121 $url = $this->get_logo_url();
5122 if ($url) {
5123 $url = $url->out(false);
5125 $context['logourl'] = $url;
5126 $context['sitename'] = format_string($SITE->fullname, true,
5127 ['context' => context_course::instance(SITEID), "escape" => false]);
5129 return $this->render_from_template('core/signup_form_layout', $context);
5133 * Render the verify age and location page into a nice template for the theme.
5135 * @param \core_auth\output\verify_age_location_page $page The renderable
5136 * @return string
5138 protected function render_verify_age_location_page($page) {
5139 $context = $page->export_for_template($this);
5141 return $this->render_from_template('core/auth_verify_age_location_page', $context);
5145 * Render the digital minor contact information page into a nice template for the theme.
5147 * @param \core_auth\output\digital_minor_page $page The renderable
5148 * @return string
5150 protected function render_digital_minor_page($page) {
5151 $context = $page->export_for_template($this);
5153 return $this->render_from_template('core/auth_digital_minor_page', $context);
5157 * Renders a progress bar.
5159 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
5161 * @param progress_bar $bar The bar.
5162 * @return string HTML fragment
5164 public function render_progress_bar(progress_bar $bar) {
5165 $data = $bar->export_for_template($this);
5166 return $this->render_from_template('core/progress_bar', $data);
5170 * Renders an update to a progress bar.
5172 * Note: This does not cleanly map to a renderable class and should
5173 * never be used directly.
5175 * @param string $id
5176 * @param float $percent
5177 * @param string $msg Message
5178 * @param string $estimate time remaining message
5179 * @return string ascii fragment
5181 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate): string {
5182 return html_writer::script(js_writer::function_call('updateProgressBar', [
5183 $id,
5184 round($percent, 1),
5185 $msg,
5186 $estimate,
5187 ]));
5191 * Renders element for a toggle-all checkbox.
5193 * @param \core\output\checkbox_toggleall $element
5194 * @return string
5196 public function render_checkbox_toggleall(\core\output\checkbox_toggleall $element) {
5197 return $this->render_from_template($element->get_template(), $element->export_for_template($this));
5201 * Renders the tertiary nav for the participants page
5203 * @param object $course The course we are operating within
5204 * @param string|null $renderedbuttons Any additional buttons/content to be displayed in line with the nav
5205 * @return string
5207 public function render_participants_tertiary_nav(object $course, ?string $renderedbuttons = null) {
5208 $actionbar = new \core\output\participants_action_bar($course, $this->page, $renderedbuttons);
5209 $content = $this->render_from_template('core_course/participants_actionbar', $actionbar->export_for_template($this));
5210 return $content ?: "";
5214 * Renders release information in the footer popup
5215 * @return string Moodle release info.
5217 public function moodle_release() {
5218 global $CFG;
5219 if (!during_initial_install() && is_siteadmin()) {
5220 return $CFG->release;
5225 * Generate the add block button when editing mode is turned on and the user can edit blocks.
5227 * @param string $region where new blocks should be added.
5228 * @return string html for the add block button.
5230 public function addblockbutton($region = ''): string {
5231 $addblockbutton = '';
5232 $regions = $this->page->blocks->get_regions();
5233 if (count($regions) == 0) {
5234 return '';
5236 if (isset($this->page->theme->addblockposition) &&
5237 $this->page->user_is_editing() &&
5238 $this->page->user_can_edit_blocks() &&
5239 $this->page->pagelayout !== 'mycourses'
5241 $params = ['bui_addblock' => '', 'sesskey' => sesskey()];
5242 if (!empty($region)) {
5243 $params['bui_blockregion'] = $region;
5245 $url = new moodle_url($this->page->url, $params);
5246 $addblockbutton = $this->render_from_template('core/add_block_button',
5248 'link' => $url->out(false),
5249 'escapedlink' => "?{$url->get_query_string(false)}",
5250 'pagehash' => $this->page->get_edited_page_hash(),
5251 'blockregion' => $region,
5252 // The following parameters are not used since Moodle 4.2 but are
5253 // still passed for backward-compatibility.
5254 'pageType' => $this->page->pagetype,
5255 'pageLayout' => $this->page->pagelayout,
5256 'subPage' => $this->page->subpage,
5260 return $addblockbutton;
5264 * Prepares an element for streaming output
5266 * This must be used with NO_OUTPUT_BUFFERING set to true. After using this method
5267 * any subsequent prints or echos to STDOUT result in the outputted content magically
5268 * being appended inside that element rather than where the current html would be
5269 * normally. This enables pages which take some time to render incremental content to
5270 * first output a fully formed html page, including the footer, and to then stream
5271 * into an element such as the main content div. This fixes a class of page layout
5272 * bugs and reduces layout shift issues and was inspired by Facebook BigPipe.
5274 * Some use cases such as a simple page which loads content via ajax could be swapped
5275 * to this method wich saves another http request and its network latency resulting
5276 * in both lower server load and better front end performance.
5278 * You should consider giving the element you stream into a minimum height to further
5279 * reduce layout shift as the content initally streams into the element.
5281 * You can safely finish the output without closing the streamed element. You can also
5282 * call this method again to swap the target of the streaming to a new element as
5283 * often as you want.
5285 * https://www.youtube.com/watch?v=LLRig4s1_yA&t=1022s
5286 * Watch this video segment to explain how and why this 'One Weird Trick' works.
5288 * @param string $selector where new content should be appended
5289 * @param string $element which contains the streamed content
5290 * @return string html to be written
5292 public function select_element_for_append(string $selector = '#region-main [role=main]', string $element = 'div') {
5294 if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) {
5295 throw new coding_exception('select_element_for_append used in a non-CLI script without setting NO_OUTPUT_BUFFERING.',
5296 DEBUG_DEVELOPER);
5299 // We are already streaming into this element so don't change anything.
5300 if ($this->currentselector === $selector && $this->currentelement === $element) {
5301 return;
5304 // If we have a streaming element close it before starting a new one.
5305 $html = $this->close_element_for_append();
5307 $this->currentselector = $selector;
5308 $this->currentelement = $element;
5310 // Create an unclosed element for the streamed content to append into.
5311 $id = uniqid();
5312 $html .= html_writer::start_tag($element, ['id' => $id]);
5313 $html .= html_writer::tag('script', "document.querySelector('$selector').append(document.getElementById('$id'))");
5314 $html .= "\n";
5315 return $html;
5319 * This closes any opened stream elements
5321 * @return string html to be written
5323 public function close_element_for_append() {
5324 $html = '';
5325 if ($this->currentselector !== '') {
5326 $html .= html_writer::end_tag($this->currentelement);
5327 $html .= "\n";
5328 $this->currentelement = '';
5330 return $html;
5334 * A companion method to select_element_for_append
5336 * This must be used with NO_OUTPUT_BUFFERING set to true.
5338 * This is similar but instead of appending into the element it replaces
5339 * the content in the element. Depending on the 3rd argument it can replace
5340 * the innerHTML or the outerHTML which can be useful to completely remove
5341 * the element if needed.
5343 * @param string $selector where new content should be replaced
5344 * @param string $html A chunk of well formed html
5345 * @param bool $outer Wether it replaces the innerHTML or the outerHTML
5346 * @return string html to be written
5348 public function select_element_for_replace(string $selector, string $html, bool $outer = false) {
5350 if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) {
5351 throw new coding_exception('select_element_for_replace used in a non-CLI script without setting NO_OUTPUT_BUFFERING.',
5352 DEBUG_DEVELOPER);
5355 // Escape html for use inside a javascript string.
5356 $html = addslashes_js($html);
5357 $property = $outer ? 'outerHTML' : 'innerHTML';
5358 $output = html_writer::tag('script', "document.querySelector('$selector').$property = '$html';");
5359 $output .= "\n";
5360 return $output;
5365 * A renderer that generates output for command-line scripts.
5367 * The implementation of this renderer is probably incomplete.
5369 * @copyright 2009 Tim Hunt
5370 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5371 * @since Moodle 2.0
5372 * @package core
5373 * @category output
5375 class core_renderer_cli extends core_renderer {
5378 * @var array $progressmaximums stores the largest percentage for a progress bar.
5379 * @return string ascii fragment
5381 private $progressmaximums = [];
5384 * Returns the page header.
5386 * @return string HTML fragment
5388 public function header() {
5389 return $this->page->heading . "\n";
5393 * Renders a Check API result
5395 * To aid in CLI consistency this status is NOT translated and the visual
5396 * width is always exactly 10 chars.
5398 * @param core\check\result $result
5399 * @return string HTML fragment
5401 protected function render_check_result(core\check\result $result) {
5402 $status = $result->get_status();
5404 $labels = [
5405 core\check\result::NA => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' NA ',
5406 core\check\result::OK => ' ' . cli_ansi_format('<colour:green>') . ' OK ',
5407 core\check\result::INFO => ' ' . cli_ansi_format('<colour:blue>' ) . ' INFO ',
5408 core\check\result::UNKNOWN => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' UNKNOWN ',
5409 core\check\result::WARNING => ' ' . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
5410 core\check\result::ERROR => ' ' . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
5411 core\check\result::CRITICAL => '' . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
5413 $string = $labels[$status] . cli_ansi_format('<colour:normal>');
5414 return $string;
5418 * Renders a Check API result
5420 * @param result $result
5421 * @return string fragment
5423 public function check_result(core\check\result $result) {
5424 return $this->render_check_result($result);
5428 * Renders a progress bar.
5430 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
5432 * @param progress_bar $bar The bar.
5433 * @return string ascii fragment
5435 public function render_progress_bar(progress_bar $bar) {
5436 global $CFG;
5438 $size = 55; // The width of the progress bar in chars.
5439 $ascii = "\n";
5441 if (stream_isatty(STDOUT)) {
5442 require_once($CFG->libdir.'/clilib.php');
5444 $ascii .= "[" . str_repeat(' ', $size) . "] 0% \n";
5445 return cli_ansi_format($ascii);
5448 $this->progressmaximums[$bar->get_id()] = 0;
5449 $ascii .= '[';
5450 return $ascii;
5454 * Renders an update to a progress bar.
5456 * Note: This does not cleanly map to a renderable class and should
5457 * never be used directly.
5459 * @param string $id
5460 * @param float $percent
5461 * @param string $msg Message
5462 * @param string $estimate time remaining message
5463 * @return string ascii fragment
5465 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate): string {
5466 $size = 55; // The width of the progress bar in chars.
5467 $ascii = '';
5469 // If we are rendering to a terminal then we can safely use ansii codes
5470 // to move the cursor and redraw the complete progress bar each time
5471 // it is updated.
5472 if (stream_isatty(STDOUT)) {
5473 $colour = $percent == 100 ? 'green' : 'blue';
5475 $done = $percent * $size * 0.01;
5476 $whole = floor($done);
5477 $bar = "<colour:$colour>";
5478 $bar .= str_repeat('█', $whole);
5480 if ($whole < $size) {
5481 // By using unicode chars for partial blocks we can have higher
5482 // precision progress bar.
5483 $fraction = floor(($done - $whole) * 8);
5484 $bar .= core_text::substr(' ▏▎▍▌▋▊▉', $fraction, 1);
5486 // Fill the rest of the empty bar.
5487 $bar .= str_repeat(' ', $size - $whole - 1);
5490 $bar .= '<colour:normal>';
5492 if ($estimate) {
5493 $estimate = "- $estimate";
5496 $ascii .= '<cursor:up>';
5497 $ascii .= '<cursor:up>';
5498 $ascii .= sprintf("[$bar] %3.1f%% %-22s\n", $percent, $estimate);
5499 $ascii .= sprintf("%-80s\n", $msg);
5500 return cli_ansi_format($ascii);
5503 // If we are not rendering to a tty, ie when piped to another command
5504 // or on windows we need to progressively render the progress bar
5505 // which can only ever go forwards.
5506 $done = round($percent * $size * 0.01);
5507 $delta = max(0, $done - $this->progressmaximums[$id]);
5509 $ascii .= str_repeat('#', $delta);
5510 if ($percent >= 100 && $delta > 0) {
5511 $ascii .= sprintf("] %3.1f%%\n$msg\n", $percent);
5513 $this->progressmaximums[$id] += $delta;
5514 return $ascii;
5518 * Returns a template fragment representing a Heading.
5520 * @param string $text The text of the heading
5521 * @param int $level The level of importance of the heading
5522 * @param string $classes A space-separated list of CSS classes
5523 * @param string $id An optional ID
5524 * @return string A template fragment for a heading
5526 public function heading($text, $level = 2, $classes = 'main', $id = null) {
5527 $text .= "\n";
5528 switch ($level) {
5529 case 1:
5530 return '=>' . $text;
5531 case 2:
5532 return '-->' . $text;
5533 default:
5534 return $text;
5539 * Returns a template fragment representing a fatal error.
5541 * @param string $message The message to output
5542 * @param string $moreinfourl URL where more info can be found about the error
5543 * @param string $link Link for the Continue button
5544 * @param array $backtrace The execution backtrace
5545 * @param string $debuginfo Debugging information
5546 * @return string A template fragment for a fatal error
5548 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5549 global $CFG;
5551 $output = "!!! $message !!!\n";
5553 if ($CFG->debugdeveloper) {
5554 if (!empty($debuginfo)) {
5555 $output .= $this->notification($debuginfo, 'notifytiny');
5557 if (!empty($backtrace)) {
5558 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
5562 return $output;
5566 * Returns a template fragment representing a notification.
5568 * @param string $message The message to print out.
5569 * @param string $type The type of notification. See constants on \core\output\notification.
5570 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5571 * @return string A template fragment for a notification
5573 public function notification($message, $type = null, $closebutton = true) {
5574 $message = clean_text($message);
5575 if ($type === 'notifysuccess' || $type === 'success') {
5576 return "++ $message ++\n";
5578 return "!! $message !!\n";
5582 * There is no footer for a cli request, however we must override the
5583 * footer method to prevent the default footer.
5585 public function footer() {}
5588 * Render a notification (that is, a status message about something that has
5589 * just happened).
5591 * @param \core\output\notification $notification the notification to print out
5592 * @return string plain text output
5594 public function render_notification(\core\output\notification $notification) {
5595 return $this->notification($notification->get_message(), $notification->get_message_type());
5601 * A renderer that generates output for ajax scripts.
5603 * This renderer prevents accidental sends back only json
5604 * encoded error messages, all other output is ignored.
5606 * @copyright 2010 Petr Skoda
5607 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5608 * @since Moodle 2.0
5609 * @package core
5610 * @category output
5612 class core_renderer_ajax extends core_renderer {
5615 * Returns a template fragment representing a fatal error.
5617 * @param string $message The message to output
5618 * @param string $moreinfourl URL where more info can be found about the error
5619 * @param string $link Link for the Continue button
5620 * @param array $backtrace The execution backtrace
5621 * @param string $debuginfo Debugging information
5622 * @return string A template fragment for a fatal error
5624 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5625 global $CFG;
5627 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
5629 $e = new stdClass();
5630 $e->error = $message;
5631 $e->errorcode = $errorcode;
5632 $e->stacktrace = NULL;
5633 $e->debuginfo = NULL;
5634 $e->reproductionlink = NULL;
5635 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
5636 $link = (string) $link;
5637 if ($link) {
5638 $e->reproductionlink = $link;
5640 if (!empty($debuginfo)) {
5641 $e->debuginfo = $debuginfo;
5643 if (!empty($backtrace)) {
5644 $e->stacktrace = format_backtrace($backtrace, true);
5647 $this->header();
5648 return json_encode($e);
5652 * Used to display a notification.
5653 * For the AJAX notifications are discarded.
5655 * @param string $message The message to print out.
5656 * @param string $type The type of notification. See constants on \core\output\notification.
5657 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5659 public function notification($message, $type = null, $closebutton = true) {
5663 * Used to display a redirection message.
5664 * AJAX redirections should not occur and as such redirection messages
5665 * are discarded.
5667 * @param moodle_url|string $encodedurl
5668 * @param string $message
5669 * @param int $delay
5670 * @param bool $debugdisableredirect
5671 * @param string $messagetype The type of notification to show the message in.
5672 * See constants on \core\output\notification.
5674 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
5675 $messagetype = \core\output\notification::NOTIFY_INFO) {}
5678 * Prepares the start of an AJAX output.
5680 public function header() {
5681 // unfortunately YUI iframe upload does not support application/json
5682 if (!empty($_FILES)) {
5683 @header('Content-type: text/plain; charset=utf-8');
5684 if (!core_useragent::supports_json_contenttype()) {
5685 @header('X-Content-Type-Options: nosniff');
5687 } else if (!core_useragent::supports_json_contenttype()) {
5688 @header('Content-type: text/plain; charset=utf-8');
5689 @header('X-Content-Type-Options: nosniff');
5690 } else {
5691 @header('Content-type: application/json; charset=utf-8');
5694 // Headers to make it not cacheable and json
5695 @header('Cache-Control: no-store, no-cache, must-revalidate');
5696 @header('Cache-Control: post-check=0, pre-check=0', false);
5697 @header('Pragma: no-cache');
5698 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
5699 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
5700 @header('Accept-Ranges: none');
5704 * There is no footer for an AJAX request, however we must override the
5705 * footer method to prevent the default footer.
5707 public function footer() {}
5710 * No need for headers in an AJAX request... this should never happen.
5711 * @param string $text
5712 * @param int $level
5713 * @param string $classes
5714 * @param string $id
5716 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
5722 * The maintenance renderer.
5724 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
5725 * is running a maintenance related task.
5726 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
5728 * @since Moodle 2.6
5729 * @package core
5730 * @category output
5731 * @copyright 2013 Sam Hemelryk
5732 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5734 class core_renderer_maintenance extends core_renderer {
5737 * Initialises the renderer instance.
5739 * @param moodle_page $page
5740 * @param string $target
5741 * @throws coding_exception
5743 public function __construct(moodle_page $page, $target) {
5744 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
5745 throw new coding_exception('Invalid request for the maintenance renderer.');
5747 parent::__construct($page, $target);
5751 * Does nothing. The maintenance renderer cannot produce blocks.
5753 * @param block_contents $bc
5754 * @param string $region
5755 * @return string
5757 public function block(block_contents $bc, $region) {
5758 return '';
5762 * Does nothing. The maintenance renderer cannot produce blocks.
5764 * @param string $region
5765 * @param array $classes
5766 * @param string $tag
5767 * @param boolean $fakeblocksonly
5768 * @return string
5770 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
5771 return '';
5775 * Does nothing. The maintenance renderer cannot produce blocks.
5777 * @param string $region
5778 * @param boolean $fakeblocksonly Output fake block only.
5779 * @return string
5781 public function blocks_for_region($region, $fakeblocksonly = false) {
5782 return '';
5786 * Does nothing. The maintenance renderer cannot produce a course content header.
5788 * @param bool $onlyifnotcalledbefore
5789 * @return string
5791 public function course_content_header($onlyifnotcalledbefore = false) {
5792 return '';
5796 * Does nothing. The maintenance renderer cannot produce a course content footer.
5798 * @param bool $onlyifnotcalledbefore
5799 * @return string
5801 public function course_content_footer($onlyifnotcalledbefore = false) {
5802 return '';
5806 * Does nothing. The maintenance renderer cannot produce a course header.
5808 * @return string
5810 public function course_header() {
5811 return '';
5815 * Does nothing. The maintenance renderer cannot produce a course footer.
5817 * @return string
5819 public function course_footer() {
5820 return '';
5824 * Does nothing. The maintenance renderer cannot produce a custom menu.
5826 * @param string $custommenuitems
5827 * @return string
5829 public function custom_menu($custommenuitems = '') {
5830 return '';
5834 * Does nothing. The maintenance renderer cannot produce a file picker.
5836 * @param array $options
5837 * @return string
5839 public function file_picker($options) {
5840 return '';
5844 * Overridden confirm message for upgrades.
5846 * @param string $message The question to ask the user
5847 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5848 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5849 * @param array $displayoptions optional extra display options
5850 * @return string HTML fragment
5852 public function confirm($message, $continue, $cancel, array $displayoptions = []) {
5853 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5854 // from any previous version of Moodle).
5855 if ($continue instanceof single_button) {
5856 $continue->type = single_button::BUTTON_PRIMARY;
5857 } else if (is_string($continue)) {
5858 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post',
5859 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
5860 } else if ($continue instanceof moodle_url) {
5861 $continue = new single_button($continue, get_string('continue'), 'post',
5862 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
5863 } else {
5864 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5865 ' (string/moodle_url) or a single_button instance.');
5868 if ($cancel instanceof single_button) {
5869 $output = '';
5870 } else if (is_string($cancel)) {
5871 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5872 } else if ($cancel instanceof moodle_url) {
5873 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5874 } else {
5875 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5876 ' (string/moodle_url) or a single_button instance.');
5879 $output = $this->box_start('generalbox', 'notice');
5880 $output .= html_writer::tag('h4', get_string('confirm'));
5881 $output .= html_writer::tag('p', $message);
5882 $output .= html_writer::tag('div', $this->render($cancel) . $this->render($continue), ['class' => 'buttons']);
5883 $output .= $this->box_end();
5884 return $output;
5888 * Does nothing. The maintenance renderer does not support JS.
5890 * @param block_contents $bc
5892 public function init_block_hider_js(block_contents $bc) {
5893 // Does nothing.
5897 * Does nothing. The maintenance renderer cannot produce language menus.
5899 * @return string
5901 public function lang_menu() {
5902 return '';
5906 * Does nothing. The maintenance renderer has no need for login information.
5908 * @param null $withlinks
5909 * @return string
5911 public function login_info($withlinks = null) {
5912 return '';
5916 * Secure login info.
5918 * @return string
5920 public function secure_login_info() {
5921 return $this->login_info(false);
5925 * Does nothing. The maintenance renderer cannot produce user pictures.
5927 * @param stdClass $user
5928 * @param array $options
5929 * @return string
5931 public function user_picture(stdClass $user, array $options = null) {
5932 return '';