Merge branch 'MDL-79927' of https://github.com/paulholden/moodle
[moodle.git] / lib / outputrenderers.php
blob3c50d69c7407696b064925d00eef879b8e05a88c
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\output\named_templatable;
39 use core_completion\cm_completion_details;
40 use core_course\output\activity_information;
42 defined('MOODLE_INTERNAL') || die();
44 /**
45 * Simple base class for Moodle renderers.
47 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
49 * Also has methods to facilitate generating HTML output.
51 * @copyright 2009 Tim Hunt
52 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 * @since Moodle 2.0
54 * @package core
55 * @category output
57 class renderer_base {
58 /**
59 * @var xhtml_container_stack The xhtml_container_stack to use.
61 protected $opencontainers;
63 /**
64 * @var moodle_page The Moodle page the renderer has been created to assist with.
66 protected $page;
68 /**
69 * @var string The requested rendering target.
71 protected $target;
73 /**
74 * @var Mustache_Engine $mustache The mustache template compiler
76 private $mustache;
78 /**
79 * @var array $templatecache The mustache template cache.
81 protected $templatecache = [];
83 /**
84 * Return an instance of the mustache class.
86 * @since 2.9
87 * @return Mustache_Engine
89 protected function get_mustache() {
90 global $CFG;
92 if ($this->mustache === null) {
93 require_once("{$CFG->libdir}/filelib.php");
95 $themename = $this->page->theme->name;
96 $themerev = theme_get_revision();
98 // Create new localcache directory.
99 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
101 // Remove old localcache directories.
102 $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR);
103 foreach ($mustachecachedirs as $localcachedir) {
104 $cachedrev = [];
105 preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
106 $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
107 if ($cachedrev > 0 && $cachedrev < $themerev) {
108 fulldelete($localcachedir);
112 $loader = new \core\output\mustache_filesystem_loader();
113 $stringhelper = new \core\output\mustache_string_helper();
114 $cleanstringhelper = new \core\output\mustache_clean_string_helper();
115 $quotehelper = new \core\output\mustache_quote_helper();
116 $jshelper = new \core\output\mustache_javascript_helper($this->page);
117 $pixhelper = new \core\output\mustache_pix_helper($this);
118 $shortentexthelper = new \core\output\mustache_shorten_text_helper();
119 $userdatehelper = new \core\output\mustache_user_date_helper();
121 // We only expose the variables that are exposed to JS templates.
122 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
124 $helpers = array('config' => $safeconfig,
125 'str' => array($stringhelper, 'str'),
126 'cleanstr' => array($cleanstringhelper, 'cleanstr'),
127 'quote' => array($quotehelper, 'quote'),
128 'js' => array($jshelper, 'help'),
129 'pix' => array($pixhelper, 'pix'),
130 'shortentext' => array($shortentexthelper, 'shorten'),
131 'userdate' => array($userdatehelper, 'transform'),
134 $this->mustache = new \core\output\mustache_engine(array(
135 'cache' => $cachedir,
136 'escape' => 's',
137 'loader' => $loader,
138 'helpers' => $helpers,
139 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS],
140 // Don't allow the JavaScript helper to be executed from within another
141 // helper. If it's allowed it can be used by users to inject malicious
142 // JS into the page.
143 'disallowednestedhelpers' => ['js'],
144 // Disable lambda rendering - content in helpers is already rendered, no need to render it again.
145 'disable_lambda_rendering' => true,
150 return $this->mustache;
155 * Constructor
157 * The constructor takes two arguments. The first is the page that the renderer
158 * has been created to assist with, and the second is the target.
159 * The target is an additional identifier that can be used to load different
160 * renderers for different options.
162 * @param moodle_page $page the page we are doing output for.
163 * @param string $target one of rendering target constants
165 public function __construct(moodle_page $page, $target) {
166 $this->opencontainers = $page->opencontainers;
167 $this->page = $page;
168 $this->target = $target;
172 * Renders a template by name with the given context.
174 * The provided data needs to be array/stdClass made up of only simple types.
175 * Simple types are array,stdClass,bool,int,float,string
177 * @since 2.9
178 * @param array|stdClass $context Context containing data for the template.
179 * @return string|boolean
181 public function render_from_template($templatename, $context) {
182 $mustache = $this->get_mustache();
184 if ($mustache->hasHelper('uniqid')) {
185 // Grab a copy of the existing helper to be restored later.
186 $uniqidhelper = $mustache->getHelper('uniqid');
187 } else {
188 // Helper doesn't exist.
189 $uniqidhelper = null;
192 // Provide 1 random value that will not change within a template
193 // but will be different from template to template. This is useful for
194 // e.g. aria attributes that only work with id attributes and must be
195 // unique in a page.
196 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
197 if (isset($this->templatecache[$templatename])) {
198 $template = $this->templatecache[$templatename];
199 } else {
200 try {
201 $template = $mustache->loadTemplate($templatename);
202 $this->templatecache[$templatename] = $template;
203 } catch (Mustache_Exception_UnknownTemplateException $e) {
204 throw new moodle_exception('Unknown template: ' . $templatename);
208 $renderedtemplate = trim($template->render($context));
210 // If we had an existing uniqid helper then we need to restore it to allow
211 // handle nested calls of render_from_template.
212 if ($uniqidhelper) {
213 $mustache->addHelper('uniqid', $uniqidhelper);
216 return $renderedtemplate;
221 * Returns rendered widget.
223 * The provided widget needs to be an object that extends the renderable
224 * interface.
225 * If will then be rendered by a method based upon the classname for the widget.
226 * For instance a widget of class `crazywidget` will be rendered by a protected
227 * render_crazywidget method of this renderer.
228 * If no render_crazywidget method exists and crazywidget implements templatable,
229 * look for the 'crazywidget' template in the same component and render that.
231 * @param renderable $widget instance with renderable interface
232 * @return string
234 public function render(renderable $widget) {
235 $classparts = explode('\\', get_class($widget));
236 // Strip namespaces.
237 $classname = array_pop($classparts);
238 // Remove _renderable suffixes.
239 $classname = preg_replace('/_renderable$/', '', $classname);
241 $rendermethod = "render_{$classname}";
242 if (method_exists($this, $rendermethod)) {
243 // Call the render_[widget_name] function.
244 // Note: This has a higher priority than the named_templatable to allow the theme to override the template.
245 return $this->$rendermethod($widget);
248 if ($widget instanceof named_templatable) {
249 // This is a named templatable.
250 // Fetch the template name from the get_template_name function instead.
251 // Note: This has higher priority than the guessed template name.
252 return $this->render_from_template(
253 $widget->get_template_name($this),
254 $widget->export_for_template($this)
258 if ($widget instanceof templatable) {
259 // Guess the templat ename based on the class name.
260 // Note: There's no benefit to moving this aboved the named_templatable and this approach is more costly.
261 $component = array_shift($classparts);
262 if (!$component) {
263 $component = 'core';
265 $template = $component . '/' . $classname;
266 $context = $widget->export_for_template($this);
267 return $this->render_from_template($template, $context);
269 throw new coding_exception("Can not render widget, renderer method ('{$rendermethod}') not found.");
273 * Adds a JS action for the element with the provided id.
275 * This method adds a JS event for the provided component action to the page
276 * and then returns the id that the event has been attached to.
277 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
279 * @param component_action $action
280 * @param string $id
281 * @return string id of element, either original submitted or random new if not supplied
283 public function add_action_handler(component_action $action, $id = null) {
284 if (!$id) {
285 $id = html_writer::random_id($action->event);
287 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
288 return $id;
292 * Returns true is output has already started, and false if not.
294 * @return boolean true if the header has been printed.
296 public function has_started() {
297 return $this->page->state >= moodle_page::STATE_IN_BODY;
301 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
303 * @param mixed $classes Space-separated string or array of classes
304 * @return string HTML class attribute value
306 public static function prepare_classes($classes) {
307 if (is_array($classes)) {
308 return implode(' ', array_unique($classes));
310 return $classes;
314 * Return the direct URL for an image from the pix folder.
316 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
318 * @deprecated since Moodle 3.3
319 * @param string $imagename the name of the icon.
320 * @param string $component specification of one plugin like in get_string()
321 * @return moodle_url
323 public function pix_url($imagename, $component = 'moodle') {
324 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
325 return $this->page->theme->image_url($imagename, $component);
329 * Return the moodle_url for an image.
331 * The exact image location and extension is determined
332 * automatically by searching for gif|png|jpg|jpeg, please
333 * note there can not be diferent images with the different
334 * extension. The imagename is for historical reasons
335 * a relative path name, it may be changed later for core
336 * images. It is recommended to not use subdirectories
337 * in plugin and theme pix directories.
339 * There are three types of images:
340 * 1/ theme images - stored in theme/mytheme/pix/,
341 * use component 'theme'
342 * 2/ core images - stored in /pix/,
343 * overridden via theme/mytheme/pix_core/
344 * 3/ plugin images - stored in mod/mymodule/pix,
345 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
346 * example: image_url('comment', 'mod_glossary')
348 * @param string $imagename the pathname of the image
349 * @param string $component full plugin name (aka component) or 'theme'
350 * @return moodle_url
352 public function image_url($imagename, $component = 'moodle') {
353 return $this->page->theme->image_url($imagename, $component);
357 * Return the site's logo URL, if any.
359 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
360 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
361 * @return moodle_url|false
363 public function get_logo_url($maxwidth = null, $maxheight = 200) {
364 global $CFG;
365 $logo = get_config('core_admin', 'logo');
366 if (empty($logo)) {
367 return false;
370 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
371 // It's not worth the overhead of detecting and serving 2 different images based on the device.
373 // Hide the requested size in the file path.
374 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
376 // Use $CFG->themerev to prevent browser caching when the file changes.
377 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
378 theme_get_revision(), $logo);
382 * Return the site's compact logo URL, if any.
384 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
385 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
386 * @return moodle_url|false
388 public function get_compact_logo_url($maxwidth = 300, $maxheight = 300) {
389 global $CFG;
390 $logo = get_config('core_admin', 'logocompact');
391 if (empty($logo)) {
392 return false;
395 // Hide the requested size in the file path.
396 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
398 // Use $CFG->themerev to prevent browser caching when the file changes.
399 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
400 theme_get_revision(), $logo);
404 * Whether we should display the logo in the navbar.
406 * We will when there are no main logos, and we have compact logo.
408 * @return bool
410 public function should_display_navbar_logo() {
411 $logo = $this->get_compact_logo_url();
412 return !empty($logo);
416 * Whether we should display the main logo.
417 * @deprecated since Moodle 4.0
418 * @todo final deprecation. To be removed in Moodle 4.4 MDL-73165.
419 * @param int $headinglevel The heading level we want to check against.
420 * @return bool
422 public function should_display_main_logo($headinglevel = 1) {
423 debugging('should_display_main_logo() is deprecated and will be removed in Moodle 4.4.', DEBUG_DEVELOPER);
424 // Only render the logo if we're on the front page or login page and the we have a logo.
425 $logo = $this->get_logo_url();
426 if ($headinglevel == 1 && !empty($logo)) {
427 if ($this->page->pagelayout == 'frontpage' || $this->page->pagelayout == 'login') {
428 return true;
432 return false;
439 * Basis for all plugin renderers.
441 * @copyright Petr Skoda (skodak)
442 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
443 * @since Moodle 2.0
444 * @package core
445 * @category output
447 class plugin_renderer_base extends renderer_base {
450 * @var renderer_base|core_renderer A reference to the current renderer.
451 * The renderer provided here will be determined by the page but will in 90%
452 * of cases by the {@link core_renderer}
454 protected $output;
457 * Constructor method, calls the parent constructor
459 * @param moodle_page $page
460 * @param string $target one of rendering target constants
462 public function __construct(moodle_page $page, $target) {
463 if (empty($target) && $page->pagelayout === 'maintenance') {
464 // If the page is using the maintenance layout then we're going to force the target to maintenance.
465 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
466 // unavailable for this page layout.
467 $target = RENDERER_TARGET_MAINTENANCE;
469 $this->output = $page->get_renderer('core', null, $target);
470 parent::__construct($page, $target);
474 * Renders the provided widget and returns the HTML to display it.
476 * @param renderable $widget instance with renderable interface
477 * @return string
479 public function render(renderable $widget) {
480 $classname = get_class($widget);
482 // Strip namespaces.
483 $classname = preg_replace('/^.*\\\/', '', $classname);
485 // Keep a copy at this point, we may need to look for a deprecated method.
486 $deprecatedmethod = "render_{$classname}";
488 // Remove _renderable suffixes.
489 $classname = preg_replace('/_renderable$/', '', $classname);
490 $rendermethod = "render_{$classname}";
492 if (method_exists($this, $rendermethod)) {
493 // Call the render_[widget_name] function.
494 // Note: This has a higher priority than the named_templatable to allow the theme to override the template.
495 return $this->$rendermethod($widget);
498 if ($widget instanceof named_templatable) {
499 // This is a named templatable.
500 // Fetch the template name from the get_template_name function instead.
501 // Note: This has higher priority than the deprecated method which is not overridable by themes anyway.
502 return $this->render_from_template(
503 $widget->get_template_name($this),
504 $widget->export_for_template($this)
508 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
509 // This is exactly where we don't want to be.
510 // If you have arrived here you have a renderable component within your plugin that has the name
511 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
512 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
513 // and the _renderable suffix now gets removed when looking for a render method.
514 // You need to change your renderers render_blah_renderable to render_blah.
515 // Until you do this it will not be possible for a theme to override the renderer to override your method.
516 // Please do it ASAP.
517 static $debugged = [];
518 if (!isset($debugged[$deprecatedmethod])) {
519 debugging(sprintf(
520 'Deprecated call. Please rename your renderables render method from %s to %s.',
521 $deprecatedmethod,
522 $rendermethod
523 ), DEBUG_DEVELOPER);
524 $debugged[$deprecatedmethod] = true;
526 return $this->$deprecatedmethod($widget);
529 // Pass to core renderer if method not found here.
530 // Note: this is not a parent. This is _new_ renderer which respects the requested format, and output type.
531 return $this->output->render($widget);
535 * Magic method used to pass calls otherwise meant for the standard renderer
536 * to it to ensure we don't go causing unnecessary grief.
538 * @param string $method
539 * @param array $arguments
540 * @return mixed
542 public function __call($method, $arguments) {
543 if (method_exists('renderer_base', $method)) {
544 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
546 if (method_exists($this->output, $method)) {
547 return call_user_func_array(array($this->output, $method), $arguments);
548 } else {
549 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
556 * The standard implementation of the core_renderer interface.
558 * @copyright 2009 Tim Hunt
559 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
560 * @since Moodle 2.0
561 * @package core
562 * @category output
564 class core_renderer extends renderer_base {
566 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
567 * in layout files instead.
568 * @deprecated
569 * @var string used in {@link core_renderer::header()}.
571 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
574 * @var string Used to pass information from {@link core_renderer::doctype()} to
575 * {@link core_renderer::standard_head_html()}.
577 protected $contenttype;
580 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
581 * with {@link core_renderer::header()}.
583 protected $metarefreshtag = '';
586 * @var string Unique token for the closing HTML
588 protected $unique_end_html_token;
591 * @var string Unique token for performance information
593 protected $unique_performance_info_token;
596 * @var string Unique token for the main content.
598 protected $unique_main_content_token;
600 /** @var custom_menu_item language The language menu if created */
601 protected $language = null;
603 /** @var string The current selector for an element being streamed into */
604 protected $currentselector = '';
606 /** @var string The current element tag which is being streamed into */
607 protected $currentelement = '';
610 * Constructor
612 * @param moodle_page $page the page we are doing output for.
613 * @param string $target one of rendering target constants
615 public function __construct(moodle_page $page, $target) {
616 $this->opencontainers = $page->opencontainers;
617 $this->page = $page;
618 $this->target = $target;
620 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
621 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
622 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
626 * Get the DOCTYPE declaration that should be used with this page. Designed to
627 * be called in theme layout.php files.
629 * @return string the DOCTYPE declaration that should be used.
631 public function doctype() {
632 if ($this->page->theme->doctype === 'html5') {
633 $this->contenttype = 'text/html; charset=utf-8';
634 return "<!DOCTYPE html>\n";
636 } else if ($this->page->theme->doctype === 'xhtml5') {
637 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
638 return "<!DOCTYPE html>\n";
640 } else {
641 // legacy xhtml 1.0
642 $this->contenttype = 'text/html; charset=utf-8';
643 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
648 * The attributes that should be added to the <html> tag. Designed to
649 * be called in theme layout.php files.
651 * @return string HTML fragment.
653 public function htmlattributes() {
654 $return = get_html_lang(true);
655 $attributes = array();
656 if ($this->page->theme->doctype !== 'html5') {
657 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
660 // Give plugins an opportunity to add things like xml namespaces to the html element.
661 // This function should return an array of html attribute names => values.
662 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
663 foreach ($pluginswithfunction as $plugins) {
664 foreach ($plugins as $function) {
665 $newattrs = $function();
666 unset($newattrs['dir']);
667 unset($newattrs['lang']);
668 unset($newattrs['xmlns']);
669 unset($newattrs['xml:lang']);
670 $attributes += $newattrs;
674 foreach ($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 $output = '';
703 // Give plugins an opportunity to add any head elements. The callback
704 // must always return a string containing valid html head content.
706 $hook = new \core\hook\output\standard_head_html_prepend();
707 \core\hook\manager::get_instance()->dispatch($hook);
708 $hook->process_legacy_callbacks();
709 $output .= $hook->get_output();
711 // Allow a url_rewrite plugin to setup any dynamic head content.
712 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
713 $class = $CFG->urlrewriteclass;
714 $output .= $class::html_head_setup();
717 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
718 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
719 // This is only set by the {@link redirect()} method
720 $output .= $this->metarefreshtag;
722 // Check if a periodic refresh delay has been set and make sure we arn't
723 // already meta refreshing
724 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
725 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
728 // Set up help link popups for all links with the helptooltip class
729 $this->page->requires->js_init_call('M.util.help_popups.setup');
731 $focus = $this->page->focuscontrol;
732 if (!empty($focus)) {
733 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
734 // This is a horrifically bad way to handle focus but it is passed in
735 // through messy formslib::moodleform
736 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
737 } else if (strpos($focus, '.')!==false) {
738 // Old style of focus, bad way to do it
739 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);
740 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
741 } else {
742 // Focus element with given id
743 $this->page->requires->js_function_call('focuscontrol', array($focus));
747 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
748 // any other custom CSS can not be overridden via themes and is highly discouraged
749 $urls = $this->page->theme->css_urls($this->page);
750 foreach ($urls as $url) {
751 $this->page->requires->css_theme($url);
754 // Get the theme javascript head and footer
755 if ($jsurl = $this->page->theme->javascript_url(true)) {
756 $this->page->requires->js($jsurl, true);
758 if ($jsurl = $this->page->theme->javascript_url(false)) {
759 $this->page->requires->js($jsurl);
762 // Get any HTML from the page_requirements_manager.
763 $output .= $this->page->requires->get_head_code($this->page, $this);
765 // List alternate versions.
766 foreach ($this->page->alternateversions as $type => $alt) {
767 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
768 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
771 // Add noindex tag if relevant page and setting applied.
772 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
773 $loginpages = array('login-index', 'login-signup');
774 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
775 if (!isset($CFG->additionalhtmlhead)) {
776 $CFG->additionalhtmlhead = '';
778 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
781 if (!empty($CFG->additionalhtmlhead)) {
782 $output .= "\n".$CFG->additionalhtmlhead;
785 if ($this->page->pagelayout == 'frontpage') {
786 $summary = s(strip_tags(format_text($SITE->summary, FORMAT_HTML)));
787 if (!empty($summary)) {
788 $output .= "<meta name=\"description\" content=\"$summary\" />\n";
792 return $output;
796 * The standard tags (typically skip links) that should be output just inside
797 * the start of the <body> tag. Designed to be called in theme layout.php files.
799 * @return string HTML fragment.
801 public function standard_top_of_body_html() {
802 global $CFG;
803 $output = $this->page->requires->get_top_of_body_code($this);
804 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
805 $output .= "\n".$CFG->additionalhtmltopofbody;
808 // Give subsystems an opportunity to inject extra html content. The callback
809 // must always return a string containing valid html.
810 foreach (\core_component::get_core_subsystems() as $name => $path) {
811 if ($path) {
812 $output .= component_callback($name, 'before_standard_top_of_body_html', [], '');
816 // Give plugins an opportunity to inject extra html content. The callback
817 // must always return a string containing valid html.
818 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
819 foreach ($pluginswithfunction as $plugins) {
820 foreach ($plugins as $function) {
821 $output .= $function();
825 $output .= $this->maintenance_warning();
827 return $output;
831 * Scheduled maintenance warning message.
833 * Note: This is a nasty hack to display maintenance notice, this should be moved
834 * to some general notification area once we have it.
836 * @return string
838 public function maintenance_warning() {
839 global $CFG;
841 $output = '';
842 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
843 $timeleft = $CFG->maintenance_later - time();
844 // If timeleft less than 30 sec, set the class on block to error to highlight.
845 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
846 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-3 alert');
847 $a = new stdClass();
848 $a->hour = (int)($timeleft / 3600);
849 $a->min = (int)(floor($timeleft / 60) % 60);
850 $a->sec = (int)($timeleft % 60);
851 if ($a->hour > 0) {
852 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
853 } else {
854 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
857 $output .= $this->box_end();
858 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
859 array(array('timeleftinsec' => $timeleft)));
860 $this->page->requires->strings_for_js(
861 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
862 'admin');
864 return $output;
868 * content that should be output in the footer area
869 * of the page. Designed to be called in theme layout.php files.
871 * @return string HTML fragment.
873 public function standard_footer_html() {
874 global $CFG;
876 $output = '';
877 if (during_initial_install()) {
878 // Debugging info can not work before install is finished,
879 // in any case we do not want any links during installation!
880 return $output;
883 // Give plugins an opportunity to add any footer elements.
884 // The callback must always return a string containing valid html footer content.
885 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
886 foreach ($pluginswithfunction as $plugins) {
887 foreach ($plugins as $function) {
888 $output .= $function();
892 if (core_userfeedback::can_give_feedback()) {
893 $output .= html_writer::div(
894 $this->render_from_template('core/userfeedback_footer_link', ['url' => core_userfeedback::make_link()->out(false)])
898 if ($this->page->devicetypeinuse == 'legacy') {
899 // The legacy theme is in use print the notification
900 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
903 // Get links to switch device types (only shown for users not on a default device)
904 $output .= $this->theme_switch_links();
906 return $output;
910 * Performance information and validation links for debugging.
912 * @return string HTML fragment.
914 public function debug_footer_html() {
915 global $CFG, $SCRIPT;
916 $output = '';
918 if (during_initial_install()) {
919 // Debugging info can not work before install is finished.
920 return $output;
923 // This function is normally called from a layout.php file
924 // but some of the content won't be known until later, so we return a placeholder
925 // for now. This will be replaced with the real content in the footer.
926 $output .= $this->unique_performance_info_token;
928 if (!empty($CFG->debugpageinfo)) {
929 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
930 $this->page->debug_summary()) . '</div>';
932 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
934 // Add link to profiling report if necessary
935 if (function_exists('profiling_is_running') && profiling_is_running()) {
936 $txt = get_string('profiledscript', 'admin');
937 $title = get_string('profiledscriptview', 'admin');
938 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
939 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
940 $output .= '<div class="profilingfooter">' . $link . '</div>';
942 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
943 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
944 $output .= '<div class="purgecaches">' .
945 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
947 // Reactive module debug panel.
948 $output .= $this->render_from_template('core/local/reactive/debugpanel', []);
950 if (!empty($CFG->debugvalidators)) {
951 $siteurl = qualified_me();
952 $nuurl = new moodle_url('https://validator.w3.org/nu/', ['doc' => $siteurl, 'showsource' => 'yes']);
953 $waveurl = new moodle_url('https://wave.webaim.org/report#/' . urlencode($siteurl));
954 $validatorlinks = [
955 html_writer::link($nuurl, get_string('validatehtml')),
956 html_writer::link($waveurl, get_string('wcagcheck'))
958 $validatorlinkslist = html_writer::alist($validatorlinks, ['class' => 'list-unstyled ml-1']);
959 $output .= html_writer::div($validatorlinkslist, 'validators');
961 return $output;
965 * Returns standard main content placeholder.
966 * Designed to be called in theme layout.php files.
968 * @return string HTML fragment.
970 public function main_content() {
971 // This is here because it is the only place we can inject the "main" role over the entire main content area
972 // without requiring all theme's to manually do it, and without creating yet another thing people need to
973 // remember in the theme.
974 // This is an unfortunate hack. DO NO EVER add anything more here.
975 // DO NOT add classes.
976 // DO NOT add an id.
977 return '<div role="main">'.$this->unique_main_content_token.'</div>';
981 * Returns information about an activity.
983 * @deprecated since Moodle 4.3 MDL-78744
984 * @todo MDL-78926 This method will be deleted in Moodle 4.7
985 * @param cm_info $cminfo The course module information.
986 * @param cm_completion_details $completiondetails The completion details for this activity module.
987 * @param array $activitydates The dates for this activity module.
988 * @return string the activity information HTML.
989 * @throws coding_exception
991 public function activity_information(cm_info $cminfo, cm_completion_details $completiondetails, array $activitydates): string {
992 debugging('activity_information method is deprecated.', DEBUG_DEVELOPER);
993 if (!$completiondetails->has_completion() && empty($activitydates)) {
994 // No need to render the activity information when there's no completion info and activity dates to show.
995 return '';
997 $activityinfo = new activity_information($cminfo, $completiondetails, $activitydates);
998 $renderer = $this->page->get_renderer('core', 'course');
999 return $renderer->render($activityinfo);
1003 * Returns standard navigation between activities in a course.
1005 * @return string the navigation HTML.
1007 public function activity_navigation() {
1008 // First we should check if we want to add navigation.
1009 $context = $this->page->context;
1010 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
1011 || $context->contextlevel != CONTEXT_MODULE) {
1012 return '';
1015 // If the activity is in stealth mode, show no links.
1016 if ($this->page->cm->is_stealth()) {
1017 return '';
1020 $course = $this->page->cm->get_course();
1021 $courseformat = course_get_format($course);
1023 // If the theme implements course index and the current course format uses course index and the current
1024 // page layout is not 'frametop' (this layout does not support course index), show no links.
1025 if ($this->page->theme->usescourseindex && $courseformat->uses_course_index() &&
1026 $this->page->pagelayout !== 'frametop') {
1027 return '';
1030 // Get a list of all the activities in the course.
1031 $modules = get_fast_modinfo($course->id)->get_cms();
1033 // Put the modules into an array in order by the position they are shown in the course.
1034 $mods = [];
1035 $activitylist = [];
1036 foreach ($modules as $module) {
1037 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
1038 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
1039 continue;
1041 $mods[$module->id] = $module;
1043 // No need to add the current module to the list for the activity dropdown menu.
1044 if ($module->id == $this->page->cm->id) {
1045 continue;
1047 // Module name.
1048 $modname = $module->get_formatted_name();
1049 // Display the hidden text if necessary.
1050 if (!$module->visible) {
1051 $modname .= ' ' . get_string('hiddenwithbrackets');
1053 // Module URL.
1054 $linkurl = new moodle_url($module->url, array('forceview' => 1));
1055 // Add module URL (as key) and name (as value) to the activity list array.
1056 $activitylist[$linkurl->out(false)] = $modname;
1059 $nummods = count($mods);
1061 // If there is only one mod then do nothing.
1062 if ($nummods == 1) {
1063 return '';
1066 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
1067 $modids = array_keys($mods);
1069 // Get the position in the array of the course module we are viewing.
1070 $position = array_search($this->page->cm->id, $modids);
1072 $prevmod = null;
1073 $nextmod = null;
1075 // Check if we have a previous mod to show.
1076 if ($position > 0) {
1077 $prevmod = $mods[$modids[$position - 1]];
1080 // Check if we have a next mod to show.
1081 if ($position < ($nummods - 1)) {
1082 $nextmod = $mods[$modids[$position + 1]];
1085 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
1086 $renderer = $this->page->get_renderer('core', 'course');
1087 return $renderer->render($activitynav);
1091 * The standard tags (typically script tags that are not needed earlier) that
1092 * should be output after everything else. Designed to be called in theme layout.php files.
1094 * @return string HTML fragment.
1096 public function standard_end_of_body_html() {
1097 global $CFG;
1099 // This function is normally called from a layout.php file in {@link core_renderer::header()}
1100 // but some of the content won't be known until later, so we return a placeholder
1101 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
1102 $output = '';
1103 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
1104 $output .= "\n".$CFG->additionalhtmlfooter;
1106 $output .= $this->unique_end_html_token;
1107 return $output;
1111 * The standard HTML that should be output just before the <footer> tag.
1112 * Designed to be called in theme layout.php files.
1114 * @return string HTML fragment.
1116 public function standard_after_main_region_html() {
1117 global $CFG;
1118 $output = '';
1119 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlbottomofbody)) {
1120 $output .= "\n".$CFG->additionalhtmlbottomofbody;
1123 // Give subsystems an opportunity to inject extra html content. The callback
1124 // must always return a string containing valid html.
1125 foreach (\core_component::get_core_subsystems() as $name => $path) {
1126 if ($path) {
1127 $output .= component_callback($name, 'standard_after_main_region_html', [], '');
1131 // Give plugins an opportunity to inject extra html content. The callback
1132 // must always return a string containing valid html.
1133 $pluginswithfunction = get_plugins_with_function('standard_after_main_region_html', 'lib.php');
1134 foreach ($pluginswithfunction as $plugins) {
1135 foreach ($plugins as $function) {
1136 $output .= $function();
1140 return $output;
1144 * Return the standard string that says whether you are logged in (and switched
1145 * roles/logged in as another user).
1146 * @param bool $withlinks if false, then don't include any links in the HTML produced.
1147 * If not set, the default is the nologinlinks option from the theme config.php file,
1148 * and if that is not set, then links are included.
1149 * @return string HTML fragment.
1151 public function login_info($withlinks = null) {
1152 global $USER, $CFG, $DB, $SESSION;
1154 if (during_initial_install()) {
1155 return '';
1158 if (is_null($withlinks)) {
1159 $withlinks = empty($this->page->layout_options['nologinlinks']);
1162 $course = $this->page->course;
1163 if (\core\session\manager::is_loggedinas()) {
1164 $realuser = \core\session\manager::get_realuser();
1165 $fullname = fullname($realuser);
1166 if ($withlinks) {
1167 $loginastitle = get_string('loginas');
1168 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
1169 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
1170 } else {
1171 $realuserinfo = " [$fullname] ";
1173 } else {
1174 $realuserinfo = '';
1177 $loginpage = $this->is_login_page();
1178 $loginurl = get_login_url();
1180 if (empty($course->id)) {
1181 // $course->id is not defined during installation
1182 return '';
1183 } else if (isloggedin()) {
1184 $context = context_course::instance($course->id);
1186 $fullname = fullname($USER);
1187 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
1188 if ($withlinks) {
1189 $linktitle = get_string('viewprofile');
1190 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
1191 } else {
1192 $username = $fullname;
1194 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
1195 if ($withlinks) {
1196 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1197 } else {
1198 $username .= " from {$idprovider->name}";
1201 if (isguestuser()) {
1202 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1203 if (!$loginpage && $withlinks) {
1204 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1206 } else if (is_role_switched($course->id)) { // Has switched roles
1207 $rolename = '';
1208 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1209 $rolename = ': '.role_get_name($role, $context);
1211 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1212 if ($withlinks) {
1213 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1214 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1216 } else {
1217 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1218 if ($withlinks) {
1219 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1222 } else {
1223 $loggedinas = get_string('loggedinnot', 'moodle');
1224 if (!$loginpage && $withlinks) {
1225 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1229 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1231 if (isset($SESSION->justloggedin)) {
1232 unset($SESSION->justloggedin);
1233 if (!isguestuser()) {
1234 // Include this file only when required.
1235 require_once($CFG->dirroot . '/user/lib.php');
1236 if (($count = user_count_login_failures($USER)) && !empty($CFG->displayloginfailures)) {
1237 $loggedinas .= '<div class="loginfailures">';
1238 $a = new stdClass();
1239 $a->attempts = $count;
1240 $loggedinas .= get_string('failedloginattempts', '', $a);
1241 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1242 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1243 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1245 $loggedinas .= '</div>';
1250 return $loggedinas;
1254 * Check whether the current page is a login page.
1256 * @since Moodle 2.9
1257 * @return bool
1259 protected function is_login_page() {
1260 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1261 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1262 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1263 return in_array(
1264 $this->page->url->out_as_local_url(false, array()),
1265 array(
1266 '/login/index.php',
1267 '/login/forgot_password.php',
1273 * Return the 'back' link that normally appears in the footer.
1275 * @return string HTML fragment.
1277 public function home_link() {
1278 global $CFG, $SITE;
1280 if ($this->page->pagetype == 'site-index') {
1281 // Special case for site home page - please do not remove
1282 return '<div class="sitelink">' .
1283 '<a title="Moodle" class="d-inline-block aalink" href="http://moodle.org/">' .
1284 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1286 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1287 // Special case for during install/upgrade.
1288 return '<div class="sitelink">'.
1289 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1290 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1292 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1293 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1294 get_string('home') . '</a></div>';
1296 } else {
1297 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1298 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1303 * Redirects the user by any means possible given the current state
1305 * This function should not be called directly, it should always be called using
1306 * the redirect function in lib/weblib.php
1308 * The redirect function should really only be called before page output has started
1309 * however it will allow itself to be called during the state STATE_IN_BODY
1311 * @param string $encodedurl The URL to send to encoded if required
1312 * @param string $message The message to display to the user if any
1313 * @param int $delay The delay before redirecting a user, if $message has been
1314 * set this is a requirement and defaults to 3, set to 0 no delay
1315 * @param boolean $debugdisableredirect this redirect has been disabled for
1316 * debugging purposes. Display a message that explains, and don't
1317 * trigger the redirect.
1318 * @param string $messagetype The type of notification to show the message in.
1319 * See constants on \core\output\notification.
1320 * @return string The HTML to display to the user before dying, may contain
1321 * meta refresh, javascript refresh, and may have set header redirects
1323 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1324 $messagetype = \core\output\notification::NOTIFY_INFO) {
1325 global $CFG;
1326 $url = str_replace('&amp;', '&', $encodedurl);
1328 switch ($this->page->state) {
1329 case moodle_page::STATE_BEFORE_HEADER :
1330 // No output yet it is safe to delivery the full arsenal of redirect methods
1331 if (!$debugdisableredirect) {
1332 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1333 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1334 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1336 $output = $this->header();
1337 break;
1338 case moodle_page::STATE_PRINTING_HEADER :
1339 // We should hopefully never get here
1340 throw new coding_exception('You cannot redirect while printing the page header');
1341 break;
1342 case moodle_page::STATE_IN_BODY :
1343 // We really shouldn't be here but we can deal with this
1344 debugging("You should really redirect before you start page output");
1345 if (!$debugdisableredirect) {
1346 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1348 $output = $this->opencontainers->pop_all_but_last();
1349 break;
1350 case moodle_page::STATE_DONE :
1351 // Too late to be calling redirect now
1352 throw new coding_exception('You cannot redirect after the entire page has been generated');
1353 break;
1355 $output .= $this->notification($message, $messagetype);
1356 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1357 if ($debugdisableredirect) {
1358 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1360 $output .= $this->footer();
1361 return $output;
1365 * Start output by sending the HTTP headers, and printing the HTML <head>
1366 * and the start of the <body>.
1368 * To control what is printed, you should set properties on $PAGE.
1370 * @return string HTML that you must output this, preferably immediately.
1372 public function header() {
1373 global $USER, $CFG, $SESSION;
1375 // Give plugins an opportunity touch things before the http headers are sent
1376 // such as adding additional headers. The return value is ignored.
1377 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1378 foreach ($pluginswithfunction as $plugins) {
1379 foreach ($plugins as $function) {
1380 $function();
1384 if (\core\session\manager::is_loggedinas()) {
1385 $this->page->add_body_class('userloggedinas');
1388 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1389 require_once($CFG->dirroot . '/user/lib.php');
1390 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1391 if ($count = user_count_login_failures($USER, false)) {
1392 $this->page->add_body_class('loginfailures');
1396 // If the user is logged in, and we're not in initial install,
1397 // check to see if the user is role-switched and add the appropriate
1398 // CSS class to the body element.
1399 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1400 $this->page->add_body_class('userswitchedrole');
1403 // Give themes a chance to init/alter the page object.
1404 $this->page->theme->init_page($this->page);
1406 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1408 // Find the appropriate page layout file, based on $this->page->pagelayout.
1409 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1410 // Render the layout using the layout file.
1411 $rendered = $this->render_page_layout($layoutfile);
1413 // Slice the rendered output into header and footer.
1414 $cutpos = strpos($rendered, $this->unique_main_content_token);
1415 if ($cutpos === false) {
1416 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1417 $token = self::MAIN_CONTENT_TOKEN;
1418 } else {
1419 $token = $this->unique_main_content_token;
1422 if ($cutpos === false) {
1423 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.');
1425 $header = substr($rendered, 0, $cutpos);
1426 $footer = substr($rendered, $cutpos + strlen($token));
1428 if (empty($this->contenttype)) {
1429 debugging('The page layout file did not call $OUTPUT->doctype()');
1430 $header = $this->doctype() . $header;
1433 // If this theme version is below 2.4 release and this is a course view page
1434 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1435 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1436 // check if course content header/footer have not been output during render of theme layout
1437 $coursecontentheader = $this->course_content_header(true);
1438 $coursecontentfooter = $this->course_content_footer(true);
1439 if (!empty($coursecontentheader)) {
1440 // display debug message and add header and footer right above and below main content
1441 // Please note that course header and footer (to be displayed above and below the whole page)
1442 // are not displayed in this case at all.
1443 // Besides the content header and footer are not displayed on any other course page
1444 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);
1445 $header .= $coursecontentheader;
1446 $footer = $coursecontentfooter. $footer;
1450 send_headers($this->contenttype, $this->page->cacheable);
1452 $this->opencontainers->push('header/footer', $footer);
1453 $this->page->set_state(moodle_page::STATE_IN_BODY);
1455 // If an activity record has been set, activity_header will handle this.
1456 if (!$this->page->cm || !empty($this->page->layout_options['noactivityheader'])) {
1457 $header .= $this->skip_link_target('maincontent');
1459 return $header;
1463 * Renders and outputs the page layout file.
1465 * This is done by preparing the normal globals available to a script, and
1466 * then including the layout file provided by the current theme for the
1467 * requested layout.
1469 * @param string $layoutfile The name of the layout file
1470 * @return string HTML code
1472 protected function render_page_layout($layoutfile) {
1473 global $CFG, $SITE, $USER;
1474 // The next lines are a bit tricky. The point is, here we are in a method
1475 // of a renderer class, and this object may, or may not, be the same as
1476 // the global $OUTPUT object. When rendering the page layout file, we want to use
1477 // this object. However, people writing Moodle code expect the current
1478 // renderer to be called $OUTPUT, not $this, so define a variable called
1479 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1480 $OUTPUT = $this;
1481 $PAGE = $this->page;
1482 $COURSE = $this->page->course;
1484 ob_start();
1485 include($layoutfile);
1486 $rendered = ob_get_contents();
1487 ob_end_clean();
1488 return $rendered;
1492 * Outputs the page's footer
1494 * @return string HTML fragment
1496 public function footer() {
1497 global $CFG, $DB, $PERF;
1499 $output = '';
1501 // Give plugins an opportunity to touch the page before JS is finalized.
1502 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1503 foreach ($pluginswithfunction as $plugins) {
1504 foreach ($plugins as $function) {
1505 $extrafooter = $function();
1506 if (is_string($extrafooter)) {
1507 $output .= $extrafooter;
1512 $output .= $this->container_end_all(true);
1514 $footer = $this->opencontainers->pop('header/footer');
1516 if (debugging() and $DB and $DB->is_transaction_started()) {
1517 // TODO: MDL-20625 print warning - transaction will be rolled back
1520 // Provide some performance info if required
1521 $performanceinfo = '';
1522 if (MDL_PERF || (!empty($CFG->perfdebug) && $CFG->perfdebug > 7)) {
1523 if (MDL_PERFTOFOOT || debugging() || (!empty($CFG->perfdebug) && $CFG->perfdebug > 7)) {
1524 if (NO_OUTPUT_BUFFERING) {
1525 // If the output buffer was off then we render a placeholder and stream the
1526 // performance debugging into it at the very end in the shutdown handler.
1527 $PERF->perfdebugdeferred = true;
1528 $performanceinfo .= html_writer::tag('div',
1529 get_string('perfdebugdeferred', 'admin'),
1531 'id' => 'perfdebugfooter',
1532 'style' => 'min-height: 30em',
1534 } else {
1535 $perf = get_performance_info();
1536 $performanceinfo = $perf['html'];
1541 // We always want performance data when running a performance test, even if the user is redirected to another page.
1542 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1543 $footer = $this->unique_performance_info_token . $footer;
1545 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1547 // Only show notifications when the current page has a context id.
1548 if (!empty($this->page->context->id)) {
1549 $this->page->requires->js_call_amd('core/notification', 'init', array(
1550 $this->page->context->id,
1551 \core\notification::fetch_as_array($this)
1554 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1556 $this->page->set_state(moodle_page::STATE_DONE);
1558 // Here we remove the closing body and html tags and store them to be added back
1559 // in the shutdown handler so we can have valid html with streaming script tags
1560 // which are rendered after the visible footer.
1561 $tags = '';
1562 preg_match('#\<\/body>#i', $footer, $matches);
1563 $tags .= $matches[0];
1564 $footer = str_replace($matches[0], '', $footer);
1566 preg_match('#\<\/html>#i', $footer, $matches);
1567 $tags .= $matches[0];
1568 $footer = str_replace($matches[0], '', $footer);
1570 $CFG->closingtags = $tags;
1572 return $output . $footer;
1576 * Close all but the last open container. This is useful in places like error
1577 * handling, where you want to close all the open containers (apart from <body>)
1578 * before outputting the error message.
1580 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1581 * developer debug warning if it isn't.
1582 * @return string the HTML required to close any open containers inside <body>.
1584 public function container_end_all($shouldbenone = false) {
1585 return $this->opencontainers->pop_all_but_last($shouldbenone);
1589 * Returns course-specific information to be output immediately above content on any course page
1590 * (for the current course)
1592 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1593 * @return string
1595 public function course_content_header($onlyifnotcalledbefore = false) {
1596 global $CFG;
1597 static $functioncalled = false;
1598 if ($functioncalled && $onlyifnotcalledbefore) {
1599 // we have already output the content header
1600 return '';
1603 // Output any session notification.
1604 $notifications = \core\notification::fetch();
1606 $bodynotifications = '';
1607 foreach ($notifications as $notification) {
1608 $bodynotifications .= $this->render_from_template(
1609 $notification->get_template_name(),
1610 $notification->export_for_template($this)
1614 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1616 if ($this->page->course->id == SITEID) {
1617 // return immediately and do not include /course/lib.php if not necessary
1618 return $output;
1621 require_once($CFG->dirroot.'/course/lib.php');
1622 $functioncalled = true;
1623 $courseformat = course_get_format($this->page->course);
1624 if (($obj = $courseformat->course_content_header()) !== null) {
1625 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1627 return $output;
1631 * Returns course-specific information to be output immediately below content on any course page
1632 * (for the current course)
1634 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1635 * @return string
1637 public function course_content_footer($onlyifnotcalledbefore = false) {
1638 global $CFG;
1639 if ($this->page->course->id == SITEID) {
1640 // return immediately and do not include /course/lib.php if not necessary
1641 return '';
1643 static $functioncalled = false;
1644 if ($functioncalled && $onlyifnotcalledbefore) {
1645 // we have already output the content footer
1646 return '';
1648 $functioncalled = true;
1649 require_once($CFG->dirroot.'/course/lib.php');
1650 $courseformat = course_get_format($this->page->course);
1651 if (($obj = $courseformat->course_content_footer()) !== null) {
1652 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1654 return '';
1658 * Returns course-specific information to be output on any course page in the header area
1659 * (for the current course)
1661 * @return string
1663 public function course_header() {
1664 global $CFG;
1665 if ($this->page->course->id == SITEID) {
1666 // return immediately and do not include /course/lib.php if not necessary
1667 return '';
1669 require_once($CFG->dirroot.'/course/lib.php');
1670 $courseformat = course_get_format($this->page->course);
1671 if (($obj = $courseformat->course_header()) !== null) {
1672 return $courseformat->get_renderer($this->page)->render($obj);
1674 return '';
1678 * Returns course-specific information to be output on any course page in the footer area
1679 * (for the current course)
1681 * @return string
1683 public function course_footer() {
1684 global $CFG;
1685 if ($this->page->course->id == SITEID) {
1686 // return immediately and do not include /course/lib.php if not necessary
1687 return '';
1689 require_once($CFG->dirroot.'/course/lib.php');
1690 $courseformat = course_get_format($this->page->course);
1691 if (($obj = $courseformat->course_footer()) !== null) {
1692 return $courseformat->get_renderer($this->page)->render($obj);
1694 return '';
1698 * Get the course pattern datauri to show on a course card.
1700 * The datauri is an encoded svg that can be passed as a url.
1701 * @param int $id Id to use when generating the pattern
1702 * @return string datauri
1704 public function get_generated_image_for_id($id) {
1705 $color = $this->get_generated_color_for_id($id);
1706 $pattern = new \core_geopattern();
1707 $pattern->setColor($color);
1708 $pattern->patternbyid($id);
1709 return $pattern->datauri();
1713 * Get the course pattern image URL.
1715 * @param context_course $context course context object
1716 * @return string URL of the course pattern image in SVG format
1718 public function get_generated_url_for_course(context_course $context): string {
1719 return moodle_url::make_pluginfile_url($context->id, 'course', 'generated', null, '/', 'course.svg')->out();
1723 * Get the course pattern in SVG format to show on a course card.
1725 * @param int $id id to use when generating the pattern
1726 * @return string SVG file contents
1728 public function get_generated_svg_for_id(int $id): string {
1729 $color = $this->get_generated_color_for_id($id);
1730 $pattern = new \core_geopattern();
1731 $pattern->setColor($color);
1732 $pattern->patternbyid($id);
1733 return $pattern->toSVG();
1737 * Get the course color to show on a course card.
1739 * @param int $id Id to use when generating the color.
1740 * @return string hex color code.
1742 public function get_generated_color_for_id($id) {
1743 $colornumbers = range(1, 10);
1744 $basecolors = [];
1745 foreach ($colornumbers as $number) {
1746 $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1749 $color = $basecolors[$id % 10];
1750 return $color;
1754 * Returns lang menu or '', this method also checks forcing of languages in courses.
1756 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1758 * @return string The lang menu HTML or empty string
1760 public function lang_menu() {
1761 $languagemenu = new \core\output\language_menu($this->page);
1762 $data = $languagemenu->export_for_single_select($this);
1763 if ($data) {
1764 return $this->render_from_template('core/single_select', $data);
1766 return '';
1770 * Output the row of editing icons for a block, as defined by the controls array.
1772 * @param array $controls an array like {@link block_contents::$controls}.
1773 * @param string $blockid The ID given to the block.
1774 * @return string HTML fragment.
1776 public function block_controls($actions, $blockid = null) {
1777 if (empty($actions)) {
1778 return '';
1780 $menu = new action_menu($actions);
1781 if ($blockid !== null) {
1782 $menu->set_owner_selector('#'.$blockid);
1784 $menu->attributes['class'] .= ' block-control-actions commands';
1785 return $this->render($menu);
1789 * Returns the HTML for a basic textarea field.
1791 * @param string $name Name to use for the textarea element
1792 * @param string $id The id to use fort he textarea element
1793 * @param string $value Initial content to display in the textarea
1794 * @param int $rows Number of rows to display
1795 * @param int $cols Number of columns to display
1796 * @return string the HTML to display
1798 public function print_textarea($name, $id, $value, $rows, $cols) {
1799 editors_head_setup();
1800 $editor = editors_get_preferred_editor(FORMAT_HTML);
1801 $editor->set_text($value);
1802 $editor->use_editor($id, []);
1804 $context = [
1805 'id' => $id,
1806 'name' => $name,
1807 'value' => $value,
1808 'rows' => $rows,
1809 'cols' => $cols
1812 return $this->render_from_template('core_form/editor_textarea', $context);
1816 * Renders an action menu component.
1818 * @param action_menu $menu
1819 * @return string HTML
1821 public function render_action_menu(action_menu $menu) {
1823 // We don't want the class icon there!
1824 foreach ($menu->get_secondary_actions() as $action) {
1825 if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1826 $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1830 if ($menu->is_empty()) {
1831 return '';
1833 $context = $menu->export_for_template($this);
1835 return $this->render_from_template('core/action_menu', $context);
1839 * Renders a full check API result including summary and details
1841 * @param core\check\check $check the check that was run to get details from
1842 * @param core\check\result $result the result of a check
1843 * @param bool $includedetails if true, details are included as well
1844 * @return string rendered html
1846 protected function render_check_full_result(core\check\check $check, core\check\result $result, bool $includedetails): string {
1847 // Initially render just badge itself.
1848 $renderedresult = $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1850 // Add summary.
1851 $renderedresult .= ' ' . $result->get_summary();
1853 // Wrap in notificaiton.
1854 $notificationmap = [
1855 \core\check\result::NA => \core\output\notification::NOTIFY_INFO,
1856 \core\check\result::OK => \core\output\notification::NOTIFY_SUCCESS,
1857 \core\check\result::INFO => \core\output\notification::NOTIFY_INFO,
1858 \core\check\result::UNKNOWN => \core\output\notification::NOTIFY_WARNING,
1859 \core\check\result::WARNING => \core\output\notification::NOTIFY_WARNING,
1860 \core\check\result::ERROR => \core\output\notification::NOTIFY_ERROR,
1861 \core\check\result::CRITICAL => \core\output\notification::NOTIFY_ERROR,
1864 // Get type, or default to error.
1865 $notificationtype = $notificationmap[$result->get_status()] ?? \core\output\notification::NOTIFY_ERROR;
1866 $renderedresult = $this->notification($renderedresult, $notificationtype, false);
1868 // If adding details, add on new line.
1869 if ($includedetails) {
1870 $renderedresult .= $result->get_details();
1873 // Add the action link.
1874 $renderedresult .= $this->render_action_link($check->get_action_link());
1876 return $renderedresult;
1880 * Renders a full check API result including summary and details
1882 * @param core\check\check $check the check that was run to get details from
1883 * @param core\check\result $result the result of a check
1884 * @param bool $includedetails if details should be included
1885 * @return string HTML fragment
1887 public function check_full_result(core\check\check $check, core\check\result $result, bool $includedetails = false) {
1888 return $this->render_check_full_result($check, $result, $includedetails);
1892 * Renders a Check API result
1894 * @param core\check\result $result
1895 * @return string HTML fragment
1897 protected function render_check_result(core\check\result $result) {
1898 return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1902 * Renders a Check API result
1904 * @param core\check\result $result
1905 * @return string HTML fragment
1907 public function check_result(core\check\result $result) {
1908 return $this->render_check_result($result);
1912 * Renders an action_menu_link item.
1914 * @param action_menu_link $action
1915 * @return string HTML fragment
1917 protected function render_action_menu_link(action_menu_link $action) {
1918 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1922 * Renders a primary action_menu_filler item.
1924 * @param action_menu_link_filler $action
1925 * @return string HTML fragment
1927 protected function render_action_menu_filler(action_menu_filler $action) {
1928 return html_writer::span('&nbsp;', 'filler');
1932 * Renders a primary action_menu_link item.
1934 * @param action_menu_link_primary $action
1935 * @return string HTML fragment
1937 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1938 return $this->render_action_menu_link($action);
1942 * Renders a secondary action_menu_link item.
1944 * @param action_menu_link_secondary $action
1945 * @return string HTML fragment
1947 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1948 return $this->render_action_menu_link($action);
1952 * Prints a nice side block with an optional header.
1954 * @param block_contents $bc HTML for the content
1955 * @param string $region the region the block is appearing in.
1956 * @return string the HTML to be output.
1958 public function block(block_contents $bc, $region) {
1959 $bc = clone($bc); // Avoid messing up the object passed in.
1960 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1961 $bc->collapsible = block_contents::NOT_HIDEABLE;
1964 $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1965 $context = new stdClass();
1966 $context->skipid = $bc->skipid;
1967 $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
1968 $context->dockable = $bc->dockable;
1969 $context->id = $id;
1970 $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1971 $context->skiptitle = strip_tags($bc->title);
1972 $context->showskiplink = !empty($context->skiptitle);
1973 $context->arialabel = $bc->arialabel;
1974 $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
1975 $context->class = $bc->attributes['class'];
1976 $context->type = $bc->attributes['data-block'];
1977 $context->title = $bc->title;
1978 $context->content = $bc->content;
1979 $context->annotation = $bc->annotation;
1980 $context->footer = $bc->footer;
1981 $context->hascontrols = !empty($bc->controls);
1982 if ($context->hascontrols) {
1983 $context->controls = $this->block_controls($bc->controls, $id);
1986 return $this->render_from_template('core/block', $context);
1990 * Render the contents of a block_list.
1992 * @param array $icons the icon for each item.
1993 * @param array $items the content of each item.
1994 * @return string HTML
1996 public function list_block_contents($icons, $items) {
1997 $row = 0;
1998 $lis = array();
1999 foreach ($items as $key => $string) {
2000 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
2001 if (!empty($icons[$key])) { //test if the content has an assigned icon
2002 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
2004 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
2005 $item .= html_writer::end_tag('li');
2006 $lis[] = $item;
2007 $row = 1 - $row; // Flip even/odd.
2009 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
2013 * Output all the blocks in a particular region.
2015 * @param string $region the name of a region on this page.
2016 * @param boolean $fakeblocksonly Output fake block only.
2017 * @return string the HTML to be output.
2019 public function blocks_for_region($region, $fakeblocksonly = false) {
2020 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
2021 $lastblock = null;
2022 $zones = array();
2023 foreach ($blockcontents as $bc) {
2024 if ($bc instanceof block_contents) {
2025 $zones[] = $bc->title;
2028 $output = '';
2030 foreach ($blockcontents as $bc) {
2031 if ($bc instanceof block_contents) {
2032 if ($fakeblocksonly && !$bc->is_fake()) {
2033 // Skip rendering real blocks if we only want to show fake blocks.
2034 continue;
2036 $output .= $this->block($bc, $region);
2037 $lastblock = $bc->title;
2038 } else if ($bc instanceof block_move_target) {
2039 if (!$fakeblocksonly) {
2040 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
2042 } else {
2043 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
2046 return $output;
2050 * Output a place where the block that is currently being moved can be dropped.
2052 * @param block_move_target $target with the necessary details.
2053 * @param array $zones array of areas where the block can be moved to
2054 * @param string $previous the block located before the area currently being rendered.
2055 * @param string $region the name of the region
2056 * @return string the HTML to be output.
2058 public function block_move_target($target, $zones, $previous, $region) {
2059 if ($previous == null) {
2060 if (empty($zones)) {
2061 // There are no zones, probably because there are no blocks.
2062 $regions = $this->page->theme->get_all_block_regions();
2063 $position = get_string('moveblockinregion', 'block', $regions[$region]);
2064 } else {
2065 $position = get_string('moveblockbefore', 'block', $zones[0]);
2067 } else {
2068 $position = get_string('moveblockafter', 'block', $previous);
2070 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
2074 * Renders a special html link with attached action
2076 * Theme developers: DO NOT OVERRIDE! Please override function
2077 * {@link core_renderer::render_action_link()} instead.
2079 * @param string|moodle_url $url
2080 * @param string $text HTML fragment
2081 * @param component_action $action
2082 * @param array $attributes associative array of html link attributes + disabled
2083 * @param pix_icon optional pix icon to render with the link
2084 * @return string HTML fragment
2086 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
2087 if (!($url instanceof moodle_url)) {
2088 $url = new moodle_url($url);
2090 $link = new action_link($url, $text, $action, $attributes, $icon);
2092 return $this->render($link);
2096 * Renders an action_link object.
2098 * The provided link is renderer and the HTML returned. At the same time the
2099 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
2101 * @param action_link $link
2102 * @return string HTML fragment
2104 protected function render_action_link(action_link $link) {
2105 return $this->render_from_template('core/action_link', $link->export_for_template($this));
2109 * Renders an action_icon.
2111 * This function uses the {@link core_renderer::action_link()} method for the
2112 * most part. What it does different is prepare the icon as HTML and use it
2113 * as the link text.
2115 * Theme developers: If you want to change how action links and/or icons are rendered,
2116 * consider overriding function {@link core_renderer::render_action_link()} and
2117 * {@link core_renderer::render_pix_icon()}.
2119 * @param string|moodle_url $url A string URL or moodel_url
2120 * @param pix_icon $pixicon
2121 * @param component_action $action
2122 * @param array $attributes associative array of html link attributes + disabled
2123 * @param bool $linktext show title next to image in link
2124 * @return string HTML fragment
2126 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
2127 if (!($url instanceof moodle_url)) {
2128 $url = new moodle_url($url);
2130 $attributes = (array)$attributes;
2132 if (empty($attributes['class'])) {
2133 // let ppl override the class via $options
2134 $attributes['class'] = 'action-icon';
2137 $icon = $this->render($pixicon);
2139 if ($linktext) {
2140 $text = $pixicon->attributes['alt'];
2141 } else {
2142 $text = '';
2145 return $this->action_link($url, $text.$icon, $action, $attributes);
2149 * Print a message along with button choices for Continue/Cancel
2151 * If a string or moodle_url is given instead of a single_button, method defaults to post.
2153 * @param string $message The question to ask the user
2154 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
2155 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
2156 * @param array $displayoptions optional extra display options
2157 * @return string HTML fragment
2159 public function confirm($message, $continue, $cancel, array $displayoptions = []) {
2161 // Check existing displayoptions.
2162 $displayoptions['confirmtitle'] = $displayoptions['confirmtitle'] ?? get_string('confirm');
2163 $displayoptions['continuestr'] = $displayoptions['continuestr'] ?? get_string('continue');
2164 $displayoptions['cancelstr'] = $displayoptions['cancelstr'] ?? get_string('cancel');
2166 if ($continue instanceof single_button) {
2167 // Continue button should be primary if set to secondary type as it is the fefault.
2168 if ($continue->type === single_button::BUTTON_SECONDARY) {
2169 $continue->type = single_button::BUTTON_PRIMARY;
2171 } else if (is_string($continue)) {
2172 $continue = new single_button(new moodle_url($continue), $displayoptions['continuestr'], 'post',
2173 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
2174 } else if ($continue instanceof moodle_url) {
2175 $continue = new single_button($continue, $displayoptions['continuestr'], 'post',
2176 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
2177 } else {
2178 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2181 if ($cancel instanceof single_button) {
2182 // ok
2183 } else if (is_string($cancel)) {
2184 $cancel = new single_button(new moodle_url($cancel), $displayoptions['cancelstr'], 'get');
2185 } else if ($cancel instanceof moodle_url) {
2186 $cancel = new single_button($cancel, $displayoptions['cancelstr'], 'get');
2187 } else {
2188 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2191 $attributes = [
2192 'role'=>'alertdialog',
2193 'aria-labelledby'=>'modal-header',
2194 'aria-describedby'=>'modal-body',
2195 'aria-modal'=>'true'
2198 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
2199 $output .= $this->box_start('modal-content', 'modal-content');
2200 $output .= $this->box_start('modal-header px-3', 'modal-header');
2201 $output .= html_writer::tag('h4', $displayoptions['confirmtitle']);
2202 $output .= $this->box_end();
2203 $attributes = [
2204 'role'=>'alert',
2205 'data-aria-autofocus'=>'true'
2207 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
2208 $output .= html_writer::tag('p', $message);
2209 $output .= $this->box_end();
2210 $output .= $this->box_start('modal-footer', 'modal-footer');
2211 $output .= html_writer::tag('div', $this->render($cancel) . $this->render($continue), ['class' => 'buttons']);
2212 $output .= $this->box_end();
2213 $output .= $this->box_end();
2214 $output .= $this->box_end();
2215 return $output;
2219 * Returns a form with a single button.
2221 * Theme developers: DO NOT OVERRIDE! Please override function
2222 * {@link core_renderer::render_single_button()} instead.
2224 * @param string|moodle_url $url
2225 * @param string $label button text
2226 * @param string $method get or post submit method
2227 * @param array $options associative array {disabled, title, etc.}
2228 * @return string HTML fragment
2230 public function single_button($url, $label, $method='post', array $options=null) {
2231 if (!($url instanceof moodle_url)) {
2232 $url = new moodle_url($url);
2234 $button = new single_button($url, $label, $method);
2236 foreach ((array)$options as $key=>$value) {
2237 if (property_exists($button, $key)) {
2238 $button->$key = $value;
2239 } else {
2240 $button->set_attribute($key, $value);
2244 return $this->render($button);
2248 * Renders a single button widget.
2250 * This will return HTML to display a form containing a single button.
2252 * @param single_button $button
2253 * @return string HTML fragment
2255 protected function render_single_button(single_button $button) {
2256 return $this->render_from_template('core/single_button', $button->export_for_template($this));
2260 * Returns a form with a single select widget.
2262 * Theme developers: DO NOT OVERRIDE! Please override function
2263 * {@link core_renderer::render_single_select()} instead.
2265 * @param moodle_url $url form action target, includes hidden fields
2266 * @param string $name name of selection field - the changing parameter in url
2267 * @param array $options list of options
2268 * @param string $selected selected element
2269 * @param array $nothing
2270 * @param string $formid
2271 * @param array $attributes other attributes for the single select
2272 * @return string HTML fragment
2274 public function single_select($url, $name, array $options, $selected = '',
2275 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2276 if (!($url instanceof moodle_url)) {
2277 $url = new moodle_url($url);
2279 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2281 if (array_key_exists('label', $attributes)) {
2282 $select->set_label($attributes['label']);
2283 unset($attributes['label']);
2285 $select->attributes = $attributes;
2287 return $this->render($select);
2291 * Returns a dataformat selection and download form
2293 * @param string $label A text label
2294 * @param moodle_url|string $base The download page url
2295 * @param string $name The query param which will hold the type of the download
2296 * @param array $params Extra params sent to the download page
2297 * @return string HTML fragment
2299 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2301 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2302 $options = array();
2303 foreach ($formats as $format) {
2304 if ($format->is_enabled()) {
2305 $options[] = array(
2306 'value' => $format->name,
2307 'label' => get_string('dataformat', $format->component),
2311 $hiddenparams = array();
2312 foreach ($params as $key => $value) {
2313 $hiddenparams[] = array(
2314 'name' => $key,
2315 'value' => $value,
2318 $data = array(
2319 'label' => $label,
2320 'base' => $base,
2321 'name' => $name,
2322 'params' => $hiddenparams,
2323 'options' => $options,
2324 'sesskey' => sesskey(),
2325 'submit' => get_string('download'),
2328 return $this->render_from_template('core/dataformat_selector', $data);
2333 * Internal implementation of single_select rendering
2335 * @param single_select $select
2336 * @return string HTML fragment
2338 protected function render_single_select(single_select $select) {
2339 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2343 * Returns a form with a url select widget.
2345 * Theme developers: DO NOT OVERRIDE! Please override function
2346 * {@link core_renderer::render_url_select()} instead.
2348 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2349 * @param string $selected selected element
2350 * @param array $nothing
2351 * @param string $formid
2352 * @return string HTML fragment
2354 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2355 $select = new url_select($urls, $selected, $nothing, $formid);
2356 return $this->render($select);
2360 * Internal implementation of url_select rendering
2362 * @param url_select $select
2363 * @return string HTML fragment
2365 protected function render_url_select(url_select $select) {
2366 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2370 * Returns a string containing a link to the user documentation.
2371 * Also contains an icon by default. Shown to teachers and admin only.
2373 * @param string $path The page link after doc root and language, no leading slash.
2374 * @param string $text The text to be displayed for the link
2375 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2376 * @param array $attributes htm attributes
2377 * @return string
2379 public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
2380 global $CFG;
2382 $icon = $this->pix_icon('book', '', 'moodle', array('class' => 'iconhelp icon-pre', 'role' => 'presentation'));
2384 $attributes['href'] = new moodle_url(get_docs_url($path));
2385 $newwindowicon = '';
2386 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2387 $attributes['target'] = '_blank';
2388 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle',
2389 ['class' => 'fa fa-externallink fa-fw']);
2392 return html_writer::tag('a', $icon . $text . $newwindowicon, $attributes);
2396 * Return HTML for an image_icon.
2398 * Theme developers: DO NOT OVERRIDE! Please override function
2399 * {@link core_renderer::render_image_icon()} instead.
2401 * @param string $pix short pix name
2402 * @param string $alt mandatory alt attribute
2403 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2404 * @param array $attributes htm attributes
2405 * @return string HTML fragment
2407 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2408 $icon = new image_icon($pix, $alt, $component, $attributes);
2409 return $this->render($icon);
2413 * Renders a pix_icon widget and returns the HTML to display it.
2415 * @param image_icon $icon
2416 * @return string HTML fragment
2418 protected function render_image_icon(image_icon $icon) {
2419 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2420 return $system->render_pix_icon($this, $icon);
2424 * Return HTML for a pix_icon.
2426 * Theme developers: DO NOT OVERRIDE! Please override function
2427 * {@link core_renderer::render_pix_icon()} instead.
2429 * @param string $pix short pix name
2430 * @param string $alt mandatory alt attribute
2431 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2432 * @param array $attributes htm lattributes
2433 * @return string HTML fragment
2435 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2436 $icon = new pix_icon($pix, $alt, $component, $attributes);
2437 return $this->render($icon);
2441 * Renders a pix_icon widget and returns the HTML to display it.
2443 * @param pix_icon $icon
2444 * @return string HTML fragment
2446 protected function render_pix_icon(pix_icon $icon) {
2447 $system = \core\output\icon_system::instance();
2448 return $system->render_pix_icon($this, $icon);
2452 * Return HTML to display an emoticon icon.
2454 * @param pix_emoticon $emoticon
2455 * @return string HTML fragment
2457 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2458 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2459 return $system->render_pix_icon($this, $emoticon);
2463 * Produces the html that represents this rating in the UI
2465 * @param rating $rating the page object on which this rating will appear
2466 * @return string
2468 function render_rating(rating $rating) {
2469 global $CFG, $USER;
2471 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2472 return null;//ratings are turned off
2475 $ratingmanager = new rating_manager();
2476 // Initialise the JavaScript so ratings can be done by AJAX.
2477 $ratingmanager->initialise_rating_javascript($this->page);
2479 $strrate = get_string("rate", "rating");
2480 $ratinghtml = ''; //the string we'll return
2482 // permissions check - can they view the aggregate?
2483 if ($rating->user_can_view_aggregate()) {
2485 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2486 $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2487 $aggregatestr = $rating->get_aggregate_string();
2489 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2490 if ($rating->count > 0) {
2491 $countstr = "({$rating->count})";
2492 } else {
2493 $countstr = '-';
2495 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2497 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2499 $nonpopuplink = $rating->get_view_ratings_url();
2500 $popuplink = $rating->get_view_ratings_url(true);
2502 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2503 $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
2506 $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
2509 $formstart = null;
2510 // if the item doesn't belong to the current user, the user has permission to rate
2511 // and we're within the assessable period
2512 if ($rating->user_can_rate()) {
2514 $rateurl = $rating->get_rate_url();
2515 $inputs = $rateurl->params();
2517 //start the rating form
2518 $formattrs = array(
2519 'id' => "postrating{$rating->itemid}",
2520 'class' => 'postratingform',
2521 'method' => 'post',
2522 'action' => $rateurl->out_omit_querystring()
2524 $formstart = html_writer::start_tag('form', $formattrs);
2525 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2527 // add the hidden inputs
2528 foreach ($inputs as $name => $value) {
2529 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2530 $formstart .= html_writer::empty_tag('input', $attributes);
2533 if (empty($ratinghtml)) {
2534 $ratinghtml .= $strrate.': ';
2536 $ratinghtml = $formstart.$ratinghtml;
2538 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2539 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2540 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2541 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2543 //output submit button
2544 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2546 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2547 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2549 if (!$rating->settings->scale->isnumeric) {
2550 // If a global scale, try to find current course ID from the context
2551 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2552 $courseid = $coursecontext->instanceid;
2553 } else {
2554 $courseid = $rating->settings->scale->courseid;
2556 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2558 $ratinghtml .= html_writer::end_tag('span');
2559 $ratinghtml .= html_writer::end_tag('div');
2560 $ratinghtml .= html_writer::end_tag('form');
2563 return $ratinghtml;
2567 * Centered heading with attached help button (same title text)
2568 * and optional icon attached.
2570 * @param string $text A heading text
2571 * @param string $helpidentifier The keyword that defines a help page
2572 * @param string $component component name
2573 * @param string|moodle_url $icon
2574 * @param string $iconalt icon alt text
2575 * @param int $level The level of importance of the heading. Defaulting to 2
2576 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2577 * @return string HTML fragment
2579 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2580 $image = '';
2581 if ($icon) {
2582 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2585 $help = '';
2586 if ($helpidentifier) {
2587 $help = $this->help_icon($helpidentifier, $component);
2590 return $this->heading($image.$text.$help, $level, $classnames);
2594 * Returns HTML to display a help icon.
2596 * @deprecated since Moodle 2.0
2598 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2599 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2603 * Returns HTML to display a help icon.
2605 * Theme developers: DO NOT OVERRIDE! Please override function
2606 * {@link core_renderer::render_help_icon()} instead.
2608 * @param string $identifier The keyword that defines a help page
2609 * @param string $component component name
2610 * @param string|bool $linktext true means use $title as link text, string means link text value
2611 * @param string|object|array|int $a An object, string or number that can be used
2612 * within translation strings
2613 * @return string HTML fragment
2615 public function help_icon($identifier, $component = 'moodle', $linktext = '', $a = null) {
2616 $icon = new help_icon($identifier, $component, $a);
2617 $icon->diag_strings();
2618 if ($linktext === true) {
2619 $icon->linktext = get_string($icon->identifier, $icon->component, $a);
2620 } else if (!empty($linktext)) {
2621 $icon->linktext = $linktext;
2623 return $this->render($icon);
2627 * Implementation of user image rendering.
2629 * @param help_icon $helpicon A help icon instance
2630 * @return string HTML fragment
2632 protected function render_help_icon(help_icon $helpicon) {
2633 $context = $helpicon->export_for_template($this);
2634 return $this->render_from_template('core/help_icon', $context);
2638 * Returns HTML to display a scale help icon.
2640 * @param int $courseid
2641 * @param stdClass $scale instance
2642 * @return string HTML fragment
2644 public function help_icon_scale($courseid, stdClass $scale) {
2645 global $CFG;
2647 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2649 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2651 $scaleid = abs($scale->id);
2653 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2654 $action = new popup_action('click', $link, 'ratingscale');
2656 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2660 * Creates and returns a spacer image with optional line break.
2662 * @param array $attributes Any HTML attributes to add to the spaced.
2663 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2664 * laxy do it with CSS which is a much better solution.
2665 * @return string HTML fragment
2667 public function spacer(array $attributes = null, $br = false) {
2668 $attributes = (array)$attributes;
2669 if (empty($attributes['width'])) {
2670 $attributes['width'] = 1;
2672 if (empty($attributes['height'])) {
2673 $attributes['height'] = 1;
2675 $attributes['class'] = 'spacer';
2677 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2679 if (!empty($br)) {
2680 $output .= '<br />';
2683 return $output;
2687 * Returns HTML to display the specified user's avatar.
2689 * User avatar may be obtained in two ways:
2690 * <pre>
2691 * // Option 1: (shortcut for simple cases, preferred way)
2692 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2693 * $OUTPUT->user_picture($user, array('popup'=>true));
2695 * // Option 2:
2696 * $userpic = new user_picture($user);
2697 * // Set properties of $userpic
2698 * $userpic->popup = true;
2699 * $OUTPUT->render($userpic);
2700 * </pre>
2702 * Theme developers: DO NOT OVERRIDE! Please override function
2703 * {@link core_renderer::render_user_picture()} instead.
2705 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2706 * If any of these are missing, the database is queried. Avoid this
2707 * if at all possible, particularly for reports. It is very bad for performance.
2708 * @param array $options associative array with user picture options, used only if not a user_picture object,
2709 * options are:
2710 * - courseid=$this->page->course->id (course id of user profile in link)
2711 * - size=35 (size of image)
2712 * - link=true (make image clickable - the link leads to user profile)
2713 * - popup=false (open in popup)
2714 * - alttext=true (add image alt attribute)
2715 * - class = image class attribute (default 'userpicture')
2716 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2717 * - includefullname=false (whether to include the user's full name together with the user picture)
2718 * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2719 * @return string HTML fragment
2721 public function user_picture(stdClass $user, array $options = null) {
2722 $userpicture = new user_picture($user);
2723 foreach ((array)$options as $key=>$value) {
2724 if (property_exists($userpicture, $key)) {
2725 $userpicture->$key = $value;
2728 return $this->render($userpicture);
2732 * Internal implementation of user image rendering.
2734 * @param user_picture $userpicture
2735 * @return string
2737 protected function render_user_picture(user_picture $userpicture) {
2738 global $CFG;
2740 $user = $userpicture->user;
2741 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
2743 $alt = '';
2744 if ($userpicture->alttext) {
2745 if (!empty($user->imagealt)) {
2746 $alt = trim($user->imagealt);
2750 // If the user picture is being rendered as a link but without the full name, an empty alt text for the user picture
2751 // would mean that the link displayed will not have any discernible text. This becomes an accessibility issue,
2752 // especially to screen reader users. Use the user's full name by default for the user picture's alt-text if this is
2753 // the case.
2754 if ($userpicture->link && !$userpicture->includefullname && empty($alt)) {
2755 $alt = fullname($user);
2758 if (empty($userpicture->size)) {
2759 $size = 35;
2760 } else if ($userpicture->size === true or $userpicture->size == 1) {
2761 $size = 100;
2762 } else {
2763 $size = $userpicture->size;
2766 $class = $userpicture->class;
2768 if ($user->picture == 0) {
2769 $class .= ' defaultuserpic';
2772 $src = $userpicture->get_url($this->page, $this);
2774 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2775 if (!$userpicture->visibletoscreenreaders) {
2776 $alt = '';
2778 $attributes['alt'] = $alt;
2780 if (!empty($alt)) {
2781 $attributes['title'] = $alt;
2784 // Get the image html output first, auto generated based on initials if one isn't already set.
2785 if ($user->picture == 0 && empty($CFG->enablegravatar) && !defined('BEHAT_SITE_RUNNING')) {
2786 $initials = \core_user::get_initials($user);
2787 // Don't modify in corner cases where neither the firstname nor the lastname appears.
2788 $output = html_writer::tag(
2789 'span', $initials,
2790 ['class' => 'userinitials size-' . $size]
2792 } else {
2793 $output = html_writer::empty_tag('img', $attributes);
2796 // Show fullname together with the picture when desired.
2797 if ($userpicture->includefullname) {
2798 $output .= fullname($userpicture->user, $canviewfullnames);
2801 if (empty($userpicture->courseid)) {
2802 $courseid = $this->page->course->id;
2803 } else {
2804 $courseid = $userpicture->courseid;
2806 if ($courseid == SITEID) {
2807 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2808 } else {
2809 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2812 // Then wrap it in link if needed. Also we don't wrap it in link if the link redirects to itself.
2813 if (!$userpicture->link ||
2814 ($this->page->has_set_url() && $this->page->url == $url)) { // Protect against unset page->url.
2815 return $output;
2818 $attributes = array('href' => $url, 'class' => 'd-inline-block aabtn');
2819 if (!$userpicture->visibletoscreenreaders) {
2820 $attributes['tabindex'] = '-1';
2821 $attributes['aria-hidden'] = 'true';
2824 if ($userpicture->popup) {
2825 $id = html_writer::random_id('userpicture');
2826 $attributes['id'] = $id;
2827 $this->add_action_handler(new popup_action('click', $url), $id);
2830 return html_writer::tag('a', $output, $attributes);
2834 * @deprecated since Moodle 4.3
2836 public function htmllize_file_tree() {
2837 throw new coding_exception('This function is deprecated and no longer relevant.');
2841 * Returns HTML to display the file picker
2843 * <pre>
2844 * $OUTPUT->file_picker($options);
2845 * </pre>
2847 * Theme developers: DO NOT OVERRIDE! Please override function
2848 * {@link core_renderer::render_file_picker()} instead.
2850 * @param stdClass $options file manager options
2851 * options are:
2852 * maxbytes=>-1,
2853 * itemid=>0,
2854 * client_id=>uniqid(),
2855 * acepted_types=>'*',
2856 * return_types=>FILE_INTERNAL,
2857 * context=>current page context
2858 * @return string HTML fragment
2860 public function file_picker($options) {
2861 $fp = new file_picker($options);
2862 return $this->render($fp);
2866 * Internal implementation of file picker rendering.
2868 * @param file_picker $fp
2869 * @return string
2871 public function render_file_picker(file_picker $fp) {
2872 $options = $fp->options;
2873 $client_id = $options->client_id;
2874 $strsaved = get_string('filesaved', 'repository');
2875 $straddfile = get_string('openpicker', 'repository');
2876 $strloading = get_string('loading', 'repository');
2877 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2878 $strdroptoupload = get_string('droptoupload', 'moodle');
2879 $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
2881 $currentfile = $options->currentfile;
2882 if (empty($currentfile)) {
2883 $currentfile = '';
2884 } else {
2885 $currentfile .= ' - ';
2887 if ($options->maxbytes) {
2888 $size = $options->maxbytes;
2889 } else {
2890 $size = get_max_upload_file_size();
2892 if ($size == -1) {
2893 $maxsize = '';
2894 } else {
2895 $maxsize = get_string('maxfilesize', 'moodle', display_size($size, 0));
2897 if ($options->buttonname) {
2898 $buttonname = ' name="' . $options->buttonname . '"';
2899 } else {
2900 $buttonname = '';
2902 $html = <<<EOD
2903 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2904 $iconprogress
2905 </div>
2906 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2907 <div>
2908 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2909 <span> $maxsize </span>
2910 </div>
2911 EOD;
2912 if ($options->env != 'url') {
2913 $html .= <<<EOD
2914 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2915 <div class="filepicker-filename">
2916 <div class="filepicker-container">$currentfile
2917 <div class="dndupload-message">$strdndenabled <br/>
2918 <div class="dndupload-arrow d-flex"><i class="fa fa-arrow-circle-o-down fa-3x m-auto"></i></div>
2919 </div>
2920 </div>
2921 <div class="dndupload-progressbars"></div>
2922 </div>
2923 <div>
2924 <div class="dndupload-target">{$strdroptoupload}<br/>
2925 <div class="dndupload-arrow d-flex"><i class="fa fa-arrow-circle-o-down fa-3x m-auto"></i></div>
2926 </div>
2927 </div>
2928 </div>
2929 EOD;
2931 $html .= '</div>';
2932 return $html;
2936 * @deprecated since Moodle 3.2
2938 public function update_module_button() {
2939 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2940 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2941 'Themes can choose to display the link in the buttons row consistently for all module types.');
2945 * Returns HTML to display a "Turn editing on/off" button in a form.
2947 * @param moodle_url $url The URL + params to send through when clicking the button
2948 * @param string $method
2949 * @return string HTML the button
2951 public function edit_button(moodle_url $url, string $method = 'post') {
2953 if ($this->page->theme->haseditswitch == true) {
2954 return;
2956 $url->param('sesskey', sesskey());
2957 if ($this->page->user_is_editing()) {
2958 $url->param('edit', 'off');
2959 $editstring = get_string('turneditingoff');
2960 } else {
2961 $url->param('edit', 'on');
2962 $editstring = get_string('turneditingon');
2965 return $this->single_button($url, $editstring, $method);
2969 * Create a navbar switch for toggling editing mode.
2971 * @return string Html containing the edit switch
2973 public function edit_switch() {
2974 if ($this->page->user_allowed_editing()) {
2976 $temp = (object) [
2977 'legacyseturl' => (new moodle_url('/editmode.php'))->out(false),
2978 'pagecontextid' => $this->page->context->id,
2979 'pageurl' => $this->page->url,
2980 'sesskey' => sesskey(),
2982 if ($this->page->user_is_editing()) {
2983 $temp->checked = true;
2985 return $this->render_from_template('core/editswitch', $temp);
2990 * Returns HTML to display a simple button to close a window
2992 * @param string $text The lang string for the button's label (already output from get_string())
2993 * @return string html fragment
2995 public function close_window_button($text='') {
2996 if (empty($text)) {
2997 $text = get_string('closewindow');
2999 $button = new single_button(new moodle_url('#'), $text, 'get');
3000 $button->add_action(new component_action('click', 'close_window'));
3002 return $this->container($this->render($button), 'closewindow');
3006 * Output an error message. By default wraps the error message in <span class="error">.
3007 * If the error message is blank, nothing is output.
3009 * @param string $message the error message.
3010 * @return string the HTML to output.
3012 public function error_text($message) {
3013 if (empty($message)) {
3014 return '';
3016 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
3017 return html_writer::tag('span', $message, array('class' => 'error'));
3021 * Do not call this function directly.
3023 * To terminate the current script with a fatal error, throw an exception.
3024 * Doing this will then call this function to display the error, before terminating the execution.
3026 * @param string $message The message to output
3027 * @param string $moreinfourl URL where more info can be found about the error
3028 * @param string $link Link for the Continue button
3029 * @param array $backtrace The execution backtrace
3030 * @param string $debuginfo Debugging information
3031 * @return string the HTML to output.
3033 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
3034 global $CFG;
3036 $output = '';
3037 $obbuffer = '';
3039 if ($this->has_started()) {
3040 // we can not always recover properly here, we have problems with output buffering,
3041 // html tables, etc.
3042 $output .= $this->opencontainers->pop_all_but_last();
3044 } else {
3045 // It is really bad if library code throws exception when output buffering is on,
3046 // because the buffered text would be printed before our start of page.
3047 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
3048 error_reporting(0); // disable notices from gzip compression, etc.
3049 while (ob_get_level() > 0) {
3050 $buff = ob_get_clean();
3051 if ($buff === false) {
3052 break;
3054 $obbuffer .= $buff;
3056 error_reporting($CFG->debug);
3058 // Output not yet started.
3059 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
3060 if (empty($_SERVER['HTTP_RANGE'])) {
3061 @header($protocol . ' 404 Not Found');
3062 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
3063 // Coax iOS 10 into sending the session cookie.
3064 @header($protocol . ' 403 Forbidden');
3065 } else {
3066 // Must stop byteserving attempts somehow,
3067 // this is weird but Chrome PDF viewer can be stopped only with 407!
3068 @header($protocol . ' 407 Proxy Authentication Required');
3071 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
3072 $this->page->set_url('/'); // no url
3073 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
3074 $this->page->set_title(get_string('error'));
3075 $this->page->set_heading($this->page->course->fullname);
3076 // No need to display the activity header when encountering an error.
3077 $this->page->activityheader->disable();
3078 $output .= $this->header();
3081 $message = '<p class="errormessage">' . s($message) . '</p>'.
3082 '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
3083 get_string('moreinformation') . '</a></p>';
3084 if (empty($CFG->rolesactive)) {
3085 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
3086 //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.
3088 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
3090 if ($CFG->debugdeveloper) {
3091 $labelsep = get_string('labelsep', 'langconfig');
3092 if (!empty($debuginfo)) {
3093 $debuginfo = s($debuginfo); // removes all nasty JS
3094 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
3095 $label = get_string('debuginfo', 'debug') . $labelsep;
3096 $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
3098 if (!empty($backtrace)) {
3099 $label = get_string('stacktrace', 'debug') . $labelsep;
3100 $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
3102 if ($obbuffer !== '' ) {
3103 $label = get_string('outputbuffer', 'debug') . $labelsep;
3104 $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
3108 if (empty($CFG->rolesactive)) {
3109 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
3110 } else if (!empty($link)) {
3111 $output .= $this->continue_button($link);
3114 $output .= $this->footer();
3116 // Padding to encourage IE to display our error page, rather than its own.
3117 $output .= str_repeat(' ', 512);
3119 return $output;
3123 * Output a notification (that is, a status message about something that has just happened).
3125 * Note: \core\notification::add() may be more suitable for your usage.
3127 * @param string $message The message to print out.
3128 * @param ?string $type The type of notification. See constants on \core\output\notification.
3129 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
3130 * @return string the HTML to output.
3132 public function notification($message, $type = null, $closebutton = true) {
3133 $typemappings = [
3134 // Valid types.
3135 'success' => \core\output\notification::NOTIFY_SUCCESS,
3136 'info' => \core\output\notification::NOTIFY_INFO,
3137 'warning' => \core\output\notification::NOTIFY_WARNING,
3138 'error' => \core\output\notification::NOTIFY_ERROR,
3140 // Legacy types mapped to current types.
3141 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
3142 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
3143 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
3144 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
3145 'notifymessage' => \core\output\notification::NOTIFY_INFO,
3146 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
3147 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
3150 $extraclasses = [];
3152 if ($type) {
3153 if (strpos($type, ' ') === false) {
3154 // No spaces in the list of classes, therefore no need to loop over and determine the class.
3155 if (isset($typemappings[$type])) {
3156 $type = $typemappings[$type];
3157 } else {
3158 // The value provided did not match a known type. It must be an extra class.
3159 $extraclasses = [$type];
3161 } else {
3162 // Identify what type of notification this is.
3163 $classarray = explode(' ', self::prepare_classes($type));
3165 // Separate out the type of notification from the extra classes.
3166 foreach ($classarray as $class) {
3167 if (isset($typemappings[$class])) {
3168 $type = $typemappings[$class];
3169 } else {
3170 $extraclasses[] = $class;
3176 $notification = new \core\output\notification($message, $type, $closebutton);
3177 if (count($extraclasses)) {
3178 $notification->set_extra_classes($extraclasses);
3181 // Return the rendered template.
3182 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3186 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3188 public function notify_problem() {
3189 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
3190 'please use \core\notification::add(), or \core\output\notification as required.');
3194 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3196 public function notify_success() {
3197 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
3198 'please use \core\notification::add(), or \core\output\notification as required.');
3202 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3204 public function notify_message() {
3205 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
3206 'please use \core\notification::add(), or \core\output\notification as required.');
3210 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3212 public function notify_redirect() {
3213 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
3214 'please use \core\notification::add(), or \core\output\notification as required.');
3218 * Render a notification (that is, a status message about something that has
3219 * just happened).
3221 * @param \core\output\notification $notification the notification to print out
3222 * @return string the HTML to output.
3224 protected function render_notification(\core\output\notification $notification) {
3225 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3229 * Returns HTML to display a continue button that goes to a particular URL.
3231 * @param string|moodle_url $url The url the button goes to.
3232 * @return string the HTML to output.
3234 public function continue_button($url) {
3235 if (!($url instanceof moodle_url)) {
3236 $url = new moodle_url($url);
3238 $button = new single_button($url, get_string('continue'), 'get', single_button::BUTTON_PRIMARY);
3239 $button->class = 'continuebutton';
3241 return $this->render($button);
3245 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
3247 * Theme developers: DO NOT OVERRIDE! Please override function
3248 * {@link core_renderer::render_paging_bar()} instead.
3250 * @param int $totalcount The total number of entries available to be paged through
3251 * @param int $page The page you are currently viewing
3252 * @param int $perpage The number of entries that should be shown per page
3253 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3254 * @param string $pagevar name of page parameter that holds the page number
3255 * @return string the HTML to output.
3257 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3258 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3259 return $this->render($pb);
3263 * Returns HTML to display the paging bar.
3265 * @param paging_bar $pagingbar
3266 * @return string the HTML to output.
3268 protected function render_paging_bar(paging_bar $pagingbar) {
3269 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3270 $pagingbar->maxdisplay = 10;
3271 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3275 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3277 * @param string $current the currently selected letter.
3278 * @param string $class class name to add to this initial bar.
3279 * @param string $title the name to put in front of this initial bar.
3280 * @param string $urlvar URL parameter name for this initial.
3281 * @param string $url URL object.
3282 * @param array $alpha of letters in the alphabet.
3283 * @param bool $minirender Return a trimmed down view of the initials bar.
3284 * @return string the HTML to output.
3286 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null, bool $minirender = false) {
3287 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha, $minirender);
3288 return $this->render($ib);
3292 * Internal implementation of initials bar rendering.
3294 * @param initials_bar $initialsbar
3295 * @return string
3297 protected function render_initials_bar(initials_bar $initialsbar) {
3298 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3302 * Output the place a skip link goes to.
3304 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3305 * @return string the HTML to output.
3307 public function skip_link_target($id = null) {
3308 return html_writer::span('', '', array('id' => $id));
3312 * Outputs a heading
3314 * @param string $text The text of the heading
3315 * @param int $level The level of importance of the heading. Defaulting to 2
3316 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3317 * @param string $id An optional ID
3318 * @return string the HTML to output.
3320 public function heading($text, $level = 2, $classes = null, $id = null) {
3321 $level = (integer) $level;
3322 if ($level < 1 or $level > 6) {
3323 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3325 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3329 * Outputs a box.
3331 * @param string $contents The contents of the box
3332 * @param string $classes A space-separated list of CSS classes
3333 * @param string $id An optional ID
3334 * @param array $attributes An array of other attributes to give the box.
3335 * @return string the HTML to output.
3337 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3338 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3342 * Outputs the opening section of a box.
3344 * @param string $classes A space-separated list of CSS classes
3345 * @param string $id An optional ID
3346 * @param array $attributes An array of other attributes to give the box.
3347 * @return string the HTML to output.
3349 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3350 $this->opencontainers->push('box', html_writer::end_tag('div'));
3351 $attributes['id'] = $id;
3352 $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes);
3353 return html_writer::start_tag('div', $attributes);
3357 * Outputs the closing section of a box.
3359 * @return string the HTML to output.
3361 public function box_end() {
3362 return $this->opencontainers->pop('box');
3366 * Outputs a paragraph.
3368 * @param string $contents The contents of the paragraph
3369 * @param string|null $classes A space-separated list of CSS classes
3370 * @param string|null $id An optional ID
3371 * @return string the HTML to output.
3373 public function paragraph(string $contents, ?string $classes = null, ?string $id = null): string {
3374 return html_writer::tag(
3375 'p',
3376 $contents,
3377 ['id' => $id, 'class' => renderer_base::prepare_classes($classes)]
3382 * Outputs a screen reader only inline text.
3384 * @param string $contents The contents of the paragraph
3385 * @return string the HTML to output.
3387 public function sr_text(string $contents): string {
3388 return html_writer::tag(
3389 'span',
3390 $contents,
3391 ['class' => 'sr-only']
3392 ) . ' ';
3396 * Outputs a container.
3398 * @param string $contents The contents of the box
3399 * @param string $classes A space-separated list of CSS classes
3400 * @param string $id An optional ID
3401 * @return string the HTML to output.
3403 public function container($contents, $classes = null, $id = null) {
3404 return $this->container_start($classes, $id) . $contents . $this->container_end();
3408 * Outputs the opening section of a container.
3410 * @param string $classes A space-separated list of CSS classes
3411 * @param string $id An optional ID
3412 * @return string the HTML to output.
3414 public function container_start($classes = null, $id = null) {
3415 $this->opencontainers->push('container', html_writer::end_tag('div'));
3416 return html_writer::start_tag('div', array('id' => $id,
3417 'class' => renderer_base::prepare_classes($classes)));
3421 * Outputs the closing section of a container.
3423 * @return string the HTML to output.
3425 public function container_end() {
3426 return $this->opencontainers->pop('container');
3430 * Make nested HTML lists out of the items
3432 * The resulting list will look something like this:
3434 * <pre>
3435 * <<ul>>
3436 * <<li>><div class='tree_item parent'>(item contents)</div>
3437 * <<ul>
3438 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3439 * <</ul>>
3440 * <</li>>
3441 * <</ul>>
3442 * </pre>
3444 * @param array $items
3445 * @param array $attrs html attributes passed to the top ofs the list
3446 * @return string HTML
3448 public function tree_block_contents($items, $attrs = array()) {
3449 // exit if empty, we don't want an empty ul element
3450 if (empty($items)) {
3451 return '';
3453 // array of nested li elements
3454 $lis = array();
3455 foreach ($items as $item) {
3456 // this applies to the li item which contains all child lists too
3457 $content = $item->content($this);
3458 $liclasses = array($item->get_css_type());
3459 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3460 $liclasses[] = 'collapsed';
3462 if ($item->isactive === true) {
3463 $liclasses[] = 'current_branch';
3465 $liattr = array('class'=>join(' ',$liclasses));
3466 // class attribute on the div item which only contains the item content
3467 $divclasses = array('tree_item');
3468 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3469 $divclasses[] = 'branch';
3470 } else {
3471 $divclasses[] = 'leaf';
3473 if (!empty($item->classes) && count($item->classes)>0) {
3474 $divclasses[] = join(' ', $item->classes);
3476 $divattr = array('class'=>join(' ', $divclasses));
3477 if (!empty($item->id)) {
3478 $divattr['id'] = $item->id;
3480 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3481 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3482 $content = html_writer::empty_tag('hr') . $content;
3484 $content = html_writer::tag('li', $content, $liattr);
3485 $lis[] = $content;
3487 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3491 * Returns a search box.
3493 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3494 * @return string HTML with the search form hidden by default.
3496 public function search_box($id = false) {
3497 global $CFG;
3499 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3500 // result in an extra included file for each site, even the ones where global search
3501 // is disabled.
3502 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3503 return '';
3506 $data = [
3507 'action' => new moodle_url('/search/index.php'),
3508 'hiddenfields' => (object) ['name' => 'context', 'value' => $this->page->context->id],
3509 'inputname' => 'q',
3510 'searchstring' => get_string('search'),
3512 return $this->render_from_template('core/search_input_navbar', $data);
3516 * Allow plugins to provide some content to be rendered in the navbar.
3517 * The plugin must define a PLUGIN_render_navbar_output function that returns
3518 * the HTML they wish to add to the navbar.
3520 * @return string HTML for the navbar
3522 public function navbar_plugin_output() {
3523 $output = '';
3525 // Give subsystems an opportunity to inject extra html content. The callback
3526 // must always return a string containing valid html.
3527 foreach (\core_component::get_core_subsystems() as $name => $path) {
3528 if ($path) {
3529 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3533 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3534 foreach ($pluginsfunction as $plugintype => $plugins) {
3535 foreach ($plugins as $pluginfunction) {
3536 $output .= $pluginfunction($this);
3541 return $output;
3545 * Construct a user menu, returning HTML that can be echoed out by a
3546 * layout file.
3548 * @param stdClass $user A user object, usually $USER.
3549 * @param bool $withlinks true if a dropdown should be built.
3550 * @return string HTML fragment.
3552 public function user_menu($user = null, $withlinks = null) {
3553 global $USER, $CFG;
3554 require_once($CFG->dirroot . '/user/lib.php');
3556 if (is_null($user)) {
3557 $user = $USER;
3560 // Note: this behaviour is intended to match that of core_renderer::login_info,
3561 // but should not be considered to be good practice; layout options are
3562 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3563 if (is_null($withlinks)) {
3564 $withlinks = empty($this->page->layout_options['nologinlinks']);
3567 // Add a class for when $withlinks is false.
3568 $usermenuclasses = 'usermenu';
3569 if (!$withlinks) {
3570 $usermenuclasses .= ' withoutlinks';
3573 $returnstr = "";
3575 // If during initial install, return the empty return string.
3576 if (during_initial_install()) {
3577 return $returnstr;
3580 $loginpage = $this->is_login_page();
3581 $loginurl = get_login_url();
3583 // Get some navigation opts.
3584 $opts = user_get_user_navigation_info($user, $this->page);
3586 if (!empty($opts->unauthenticateduser)) {
3587 $returnstr = get_string($opts->unauthenticateduser['content'], 'moodle');
3588 // If not logged in, show the typical not-logged-in string.
3589 if (!$loginpage && (!$opts->unauthenticateduser['guest'] || $withlinks)) {
3590 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3593 return html_writer::div(
3594 html_writer::span(
3595 $returnstr,
3596 'login nav-link'
3598 $usermenuclasses
3602 $avatarclasses = "avatars";
3603 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3604 $usertextcontents = $opts->metadata['userfullname'];
3606 // Other user.
3607 if (!empty($opts->metadata['asotheruser'])) {
3608 $avatarcontents .= html_writer::span(
3609 $opts->metadata['realuseravatar'],
3610 'avatar realuser'
3612 $usertextcontents = $opts->metadata['realuserfullname'];
3613 $usertextcontents .= html_writer::tag(
3614 'span',
3615 get_string(
3616 'loggedinas',
3617 'moodle',
3618 html_writer::span(
3619 $opts->metadata['userfullname'],
3620 'value'
3623 array('class' => 'meta viewingas')
3627 // Role.
3628 if (!empty($opts->metadata['asotherrole'])) {
3629 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3630 $usertextcontents .= html_writer::span(
3631 $opts->metadata['rolename'],
3632 'meta role role-' . $role
3636 // User login failures.
3637 if (!empty($opts->metadata['userloginfail'])) {
3638 $usertextcontents .= html_writer::span(
3639 $opts->metadata['userloginfail'],
3640 'meta loginfailures'
3644 // MNet.
3645 if (!empty($opts->metadata['asmnetuser'])) {
3646 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3647 $usertextcontents .= html_writer::span(
3648 $opts->metadata['mnetidprovidername'],
3649 'meta mnet mnet-' . $mnet
3653 $returnstr .= html_writer::span(
3654 html_writer::span($usertextcontents, 'usertext mr-1') .
3655 html_writer::span($avatarcontents, $avatarclasses),
3656 'userbutton'
3659 // Create a divider (well, a filler).
3660 $divider = new action_menu_filler();
3661 $divider->primary = false;
3663 $am = new action_menu();
3664 $am->set_menu_trigger(
3665 $returnstr,
3666 'nav-link'
3668 $am->set_action_label(get_string('usermenu'));
3669 $am->set_nowrap_on_items();
3670 if ($withlinks) {
3671 $navitemcount = count($opts->navitems);
3672 $idx = 0;
3673 foreach ($opts->navitems as $key => $value) {
3675 switch ($value->itemtype) {
3676 case 'divider':
3677 // If the nav item is a divider, add one and skip link processing.
3678 $am->add($divider);
3679 break;
3681 case 'invalid':
3682 // Silently skip invalid entries (should we post a notification?).
3683 break;
3685 case 'link':
3686 // Process this as a link item.
3687 $pix = null;
3688 if (isset($value->pix) && !empty($value->pix)) {
3689 $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
3690 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3691 $value->title = html_writer::img(
3692 $value->imgsrc,
3693 $value->title,
3694 array('class' => 'iconsmall')
3695 ) . $value->title;
3698 $al = new action_menu_link_secondary(
3699 $value->url,
3700 $pix,
3701 $value->title,
3702 array('class' => 'icon')
3704 if (!empty($value->titleidentifier)) {
3705 $al->attributes['data-title'] = $value->titleidentifier;
3707 $am->add($al);
3708 break;
3711 $idx++;
3713 // Add dividers after the first item and before the last item.
3714 if ($idx == 1 || $idx == $navitemcount - 1) {
3715 $am->add($divider);
3720 return html_writer::div(
3721 $this->render($am),
3722 $usermenuclasses
3727 * Secure layout login info.
3729 * @return string
3731 public function secure_layout_login_info() {
3732 if (get_config('core', 'logininfoinsecurelayout')) {
3733 return $this->login_info(false);
3734 } else {
3735 return '';
3740 * Returns the language menu in the secure layout.
3742 * No custom menu items are passed though, such that it will render only the language selection.
3744 * @return string
3746 public function secure_layout_language_menu() {
3747 if (get_config('core', 'langmenuinsecurelayout')) {
3748 $custommenu = new custom_menu('', current_language());
3749 return $this->render_custom_menu($custommenu);
3750 } else {
3751 return '';
3756 * This renders the navbar.
3757 * Uses bootstrap compatible html.
3759 public function navbar() {
3760 return $this->render_from_template('core/navbar', $this->page->navbar);
3764 * Renders a breadcrumb navigation node object.
3766 * @param breadcrumb_navigation_node $item The navigation node to render.
3767 * @return string HTML fragment
3769 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3771 if ($item->action instanceof moodle_url) {
3772 $content = $item->get_content();
3773 $title = $item->get_title();
3774 $attributes = array();
3775 $attributes['itemprop'] = 'url';
3776 if ($title !== '') {
3777 $attributes['title'] = $title;
3779 if ($item->hidden) {
3780 $attributes['class'] = 'dimmed_text';
3782 if ($item->is_last()) {
3783 $attributes['aria-current'] = 'page';
3785 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3786 $content = html_writer::link($item->action, $content, $attributes);
3788 $attributes = array();
3789 $attributes['itemscope'] = '';
3790 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3791 $content = html_writer::tag('span', $content, $attributes);
3793 } else {
3794 $content = $this->render_navigation_node($item);
3796 return $content;
3800 * Renders a navigation node object.
3802 * @param navigation_node $item The navigation node to render.
3803 * @return string HTML fragment
3805 protected function render_navigation_node(navigation_node $item) {
3806 $content = $item->get_content();
3807 $title = $item->get_title();
3808 if ($item->icon instanceof renderable && !$item->hideicon) {
3809 $icon = $this->render($item->icon);
3810 $content = $icon.$content; // use CSS for spacing of icons
3812 if ($item->helpbutton !== null) {
3813 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3815 if ($content === '') {
3816 return '';
3818 if ($item->action instanceof action_link) {
3819 $link = $item->action;
3820 if ($item->hidden) {
3821 $link->add_class('dimmed');
3823 if (!empty($content)) {
3824 // Providing there is content we will use that for the link content.
3825 $link->text = $content;
3827 $content = $this->render($link);
3828 } else if ($item->action instanceof moodle_url) {
3829 $attributes = array();
3830 if ($title !== '') {
3831 $attributes['title'] = $title;
3833 if ($item->hidden) {
3834 $attributes['class'] = 'dimmed_text';
3836 $content = html_writer::link($item->action, $content, $attributes);
3838 } else if (is_string($item->action) || empty($item->action)) {
3839 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3840 if ($title !== '') {
3841 $attributes['title'] = $title;
3843 if ($item->hidden) {
3844 $attributes['class'] = 'dimmed_text';
3846 $content = html_writer::tag('span', $content, $attributes);
3848 return $content;
3852 * Accessibility: Right arrow-like character is
3853 * used in the breadcrumb trail, course navigation menu
3854 * (previous/next activity), calendar, and search forum block.
3855 * If the theme does not set characters, appropriate defaults
3856 * are set automatically. Please DO NOT
3857 * use &lt; &gt; &raquo; - these are confusing for blind users.
3859 * @return string
3861 public function rarrow() {
3862 return $this->page->theme->rarrow;
3866 * Accessibility: Left arrow-like character is
3867 * used in the breadcrumb trail, course navigation menu
3868 * (previous/next activity), calendar, and search forum block.
3869 * If the theme does not set characters, appropriate defaults
3870 * are set automatically. Please DO NOT
3871 * use &lt; &gt; &raquo; - these are confusing for blind users.
3873 * @return string
3875 public function larrow() {
3876 return $this->page->theme->larrow;
3880 * Accessibility: Up arrow-like character is used in
3881 * the book heirarchical navigation.
3882 * If the theme does not set characters, appropriate defaults
3883 * are set automatically. Please DO NOT
3884 * use ^ - this is confusing for blind users.
3886 * @return string
3888 public function uarrow() {
3889 return $this->page->theme->uarrow;
3893 * Accessibility: Down arrow-like character.
3894 * If the theme does not set characters, appropriate defaults
3895 * are set automatically.
3897 * @return string
3899 public function darrow() {
3900 return $this->page->theme->darrow;
3904 * Returns the custom menu if one has been set
3906 * A custom menu can be configured by browsing to a theme's settings page
3907 * and then configuring the custommenu config setting as described.
3909 * Theme developers: DO NOT OVERRIDE! Please override function
3910 * {@link core_renderer::render_custom_menu()} instead.
3912 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3913 * @return string
3915 public function custom_menu($custommenuitems = '') {
3916 global $CFG;
3918 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3919 $custommenuitems = $CFG->custommenuitems;
3921 $custommenu = new custom_menu($custommenuitems, current_language());
3922 return $this->render_custom_menu($custommenu);
3926 * We want to show the custom menus as a list of links in the footer on small screens.
3927 * Just return the menu object exported so we can render it differently.
3929 public function custom_menu_flat() {
3930 global $CFG;
3931 $custommenuitems = '';
3933 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3934 $custommenuitems = $CFG->custommenuitems;
3936 $custommenu = new custom_menu($custommenuitems, current_language());
3937 $langs = get_string_manager()->get_list_of_translations();
3938 $haslangmenu = $this->lang_menu() != '';
3940 if ($haslangmenu) {
3941 $strlang = get_string('language');
3942 $currentlang = current_language();
3943 if (isset($langs[$currentlang])) {
3944 $currentlang = $langs[$currentlang];
3945 } else {
3946 $currentlang = $strlang;
3948 $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3949 foreach ($langs as $langtype => $langname) {
3950 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3954 return $custommenu->export_for_template($this);
3958 * Renders a custom menu object (located in outputcomponents.php)
3960 * The custom menu this method produces makes use of the YUI3 menunav widget
3961 * and requires very specific html elements and classes.
3963 * @staticvar int $menucount
3964 * @param custom_menu $menu
3965 * @return string
3967 protected function render_custom_menu(custom_menu $menu) {
3968 global $CFG;
3970 $langs = get_string_manager()->get_list_of_translations();
3971 $haslangmenu = $this->lang_menu() != '';
3973 if (!$menu->has_children() && !$haslangmenu) {
3974 return '';
3977 if ($haslangmenu) {
3978 $strlang = get_string('language');
3979 $currentlang = current_language();
3980 if (isset($langs[$currentlang])) {
3981 $currentlangstr = $langs[$currentlang];
3982 } else {
3983 $currentlangstr = $strlang;
3985 $this->language = $menu->add($currentlangstr, new moodle_url('#'), $strlang, 10000);
3986 foreach ($langs as $langtype => $langname) {
3987 $attributes = [];
3988 // Set the lang attribute for languages different from the page's current language.
3989 if ($langtype !== $currentlang) {
3990 $attributes[] = [
3991 'key' => 'lang',
3992 'value' => get_html_lang_attribute_value($langtype),
3995 $this->language->add($langname, new moodle_url($this->page->url, ['lang' => $langtype]), null, null, $attributes);
3999 $content = '';
4000 foreach ($menu->get_children() as $item) {
4001 $context = $item->export_for_template($this);
4002 $content .= $this->render_from_template('core/custom_menu_item', $context);
4005 return $content;
4009 * Renders a custom menu node as part of a submenu
4011 * The custom menu this method produces makes use of the YUI3 menunav widget
4012 * and requires very specific html elements and classes.
4014 * @see core:renderer::render_custom_menu()
4016 * @staticvar int $submenucount
4017 * @param custom_menu_item $menunode
4018 * @return string
4020 protected function render_custom_menu_item(custom_menu_item $menunode) {
4021 // Required to ensure we get unique trackable id's
4022 static $submenucount = 0;
4023 if ($menunode->has_children()) {
4024 // If the child has menus render it as a sub menu
4025 $submenucount++;
4026 $content = html_writer::start_tag('li');
4027 if ($menunode->get_url() !== null) {
4028 $url = $menunode->get_url();
4029 } else {
4030 $url = '#cm_submenu_'.$submenucount;
4032 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
4033 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
4034 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
4035 $content .= html_writer::start_tag('ul');
4036 foreach ($menunode->get_children() as $menunode) {
4037 $content .= $this->render_custom_menu_item($menunode);
4039 $content .= html_writer::end_tag('ul');
4040 $content .= html_writer::end_tag('div');
4041 $content .= html_writer::end_tag('div');
4042 $content .= html_writer::end_tag('li');
4043 } else {
4044 // The node doesn't have children so produce a final menuitem.
4045 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
4046 $content = '';
4047 if (preg_match("/^#+$/", $menunode->get_text())) {
4049 // This is a divider.
4050 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
4051 } else {
4052 $content = html_writer::start_tag(
4053 'li',
4054 array(
4055 'class' => 'yui3-menuitem'
4058 if ($menunode->get_url() !== null) {
4059 $url = $menunode->get_url();
4060 } else {
4061 $url = '#';
4063 $content .= html_writer::link(
4064 $url,
4065 $menunode->get_text(),
4066 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
4069 $content .= html_writer::end_tag('li');
4071 // Return the sub menu
4072 return $content;
4076 * Renders theme links for switching between default and other themes.
4078 * @return string
4080 protected function theme_switch_links() {
4082 $actualdevice = core_useragent::get_device_type();
4083 $currentdevice = $this->page->devicetypeinuse;
4084 $switched = ($actualdevice != $currentdevice);
4086 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
4087 // The user is using the a default device and hasn't switched so don't shown the switch
4088 // device links.
4089 return '';
4092 if ($switched) {
4093 $linktext = get_string('switchdevicerecommended');
4094 $devicetype = $actualdevice;
4095 } else {
4096 $linktext = get_string('switchdevicedefault');
4097 $devicetype = 'default';
4099 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
4101 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
4102 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
4103 $content .= html_writer::end_tag('div');
4105 return $content;
4109 * Renders tabs
4111 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
4113 * Theme developers: In order to change how tabs are displayed please override functions
4114 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
4116 * @param array $tabs array of tabs, each of them may have it's own ->subtree
4117 * @param string|null $selected which tab to mark as selected, all parent tabs will
4118 * automatically be marked as activated
4119 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
4120 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
4121 * @return string
4123 public final function tabtree($tabs, $selected = null, $inactive = null) {
4124 return $this->render(new tabtree($tabs, $selected, $inactive));
4128 * Renders tabtree
4130 * @param tabtree $tabtree
4131 * @return string
4133 protected function render_tabtree(tabtree $tabtree) {
4134 if (empty($tabtree->subtree)) {
4135 return '';
4137 $data = $tabtree->export_for_template($this);
4138 return $this->render_from_template('core/tabtree', $data);
4142 * Renders tabobject (part of tabtree)
4144 * This function is called from {@link core_renderer::render_tabtree()}
4145 * and also it calls itself when printing the $tabobject subtree recursively.
4147 * Property $tabobject->level indicates the number of row of tabs.
4149 * @param tabobject $tabobject
4150 * @return string HTML fragment
4152 protected function render_tabobject(tabobject $tabobject) {
4153 $str = '';
4155 // Print name of the current tab.
4156 if ($tabobject instanceof tabtree) {
4157 // No name for tabtree root.
4158 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
4159 // Tab name without a link. The <a> tag is used for styling.
4160 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
4161 } else {
4162 // Tab name with a link.
4163 if (!($tabobject->link instanceof moodle_url)) {
4164 // backward compartibility when link was passed as quoted string
4165 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
4166 } else {
4167 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
4171 if (empty($tabobject->subtree)) {
4172 if ($tabobject->selected) {
4173 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
4175 return $str;
4178 // Print subtree.
4179 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
4180 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
4181 $cnt = 0;
4182 foreach ($tabobject->subtree as $tab) {
4183 $liclass = '';
4184 if (!$cnt) {
4185 $liclass .= ' first';
4187 if ($cnt == count($tabobject->subtree) - 1) {
4188 $liclass .= ' last';
4190 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
4191 $liclass .= ' onerow';
4194 if ($tab->selected) {
4195 $liclass .= ' here selected';
4196 } else if ($tab->activated) {
4197 $liclass .= ' here active';
4200 // This will recursively call function render_tabobject() for each item in subtree.
4201 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
4202 $cnt++;
4204 $str .= html_writer::end_tag('ul');
4207 return $str;
4211 * Get the HTML for blocks in the given region.
4213 * @since Moodle 2.5.1 2.6
4214 * @param string $region The region to get HTML for.
4215 * @param array $classes Wrapping tag classes.
4216 * @param string $tag Wrapping tag.
4217 * @param boolean $fakeblocksonly Include fake blocks only.
4218 * @return string HTML.
4220 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
4221 $displayregion = $this->page->apply_theme_region_manipulations($region);
4222 $classes = (array)$classes;
4223 $classes[] = 'block-region';
4224 $attributes = array(
4225 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
4226 'class' => join(' ', $classes),
4227 'data-blockregion' => $displayregion,
4228 'data-droptarget' => '1'
4230 if ($this->page->blocks->region_has_content($displayregion, $this)) {
4231 $content = $this->blocks_for_region($displayregion, $fakeblocksonly);
4232 } else {
4233 $content = '';
4235 return html_writer::tag($tag, $content, $attributes);
4239 * Renders a custom block region.
4241 * Use this method if you want to add an additional block region to the content of the page.
4242 * Please note this should only be used in special situations.
4243 * We want to leave the theme is control where ever possible!
4245 * This method must use the same method that the theme uses within its layout file.
4246 * As such it asks the theme what method it is using.
4247 * It can be one of two values, blocks or blocks_for_region (deprecated).
4249 * @param string $regionname The name of the custom region to add.
4250 * @return string HTML for the block region.
4252 public function custom_block_region($regionname) {
4253 if ($this->page->theme->get_block_render_method() === 'blocks') {
4254 return $this->blocks($regionname);
4255 } else {
4256 return $this->blocks_for_region($regionname);
4261 * Returns the CSS classes to apply to the body tag.
4263 * @since Moodle 2.5.1 2.6
4264 * @param array $additionalclasses Any additional classes to apply.
4265 * @return string
4267 public function body_css_classes(array $additionalclasses = array()) {
4268 return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses);
4272 * The ID attribute to apply to the body tag.
4274 * @since Moodle 2.5.1 2.6
4275 * @return string
4277 public function body_id() {
4278 return $this->page->bodyid;
4282 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4284 * @since Moodle 2.5.1 2.6
4285 * @param string|array $additionalclasses Any additional classes to give the body tag,
4286 * @return string
4288 public function body_attributes($additionalclasses = array()) {
4289 if (!is_array($additionalclasses)) {
4290 $additionalclasses = explode(' ', $additionalclasses);
4292 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4296 * Gets HTML for the page heading.
4298 * @since Moodle 2.5.1 2.6
4299 * @param string $tag The tag to encase the heading in. h1 by default.
4300 * @return string HTML.
4302 public function page_heading($tag = 'h1') {
4303 return html_writer::tag($tag, $this->page->heading);
4307 * Gets the HTML for the page heading button.
4309 * @since Moodle 2.5.1 2.6
4310 * @return string HTML.
4312 public function page_heading_button() {
4313 return $this->page->button;
4317 * Returns the Moodle docs link to use for this page.
4319 * @since Moodle 2.5.1 2.6
4320 * @param string $text
4321 * @return string
4323 public function page_doc_link($text = null) {
4324 if ($text === null) {
4325 $text = get_string('moodledocslink');
4327 $path = page_get_doc_link_path($this->page);
4328 if (!$path) {
4329 return '';
4331 return $this->doc_link($path, $text);
4335 * Returns the HTML for the site support email link
4337 * @param array $customattribs Array of custom attributes for the support email anchor tag.
4338 * @param bool $embed Set to true if you want to embed the link in other inline content.
4339 * @return string The html code for the support email link.
4341 public function supportemail(array $customattribs = [], bool $embed = false): string {
4342 global $CFG;
4344 // Do not provide a link to contact site support if it is unavailable to this user. This would be where the site has
4345 // disabled support, or limited it to authenticated users and the current user is a guest or not logged in.
4346 if (!isset($CFG->supportavailability) ||
4347 $CFG->supportavailability == CONTACT_SUPPORT_DISABLED ||
4348 ($CFG->supportavailability == CONTACT_SUPPORT_AUTHENTICATED && (!isloggedin() || isguestuser()))) {
4349 return '';
4352 $label = get_string('contactsitesupport', 'admin');
4353 $icon = $this->pix_icon('t/email', '');
4355 if (!$embed) {
4356 $content = $icon . $label;
4357 } else {
4358 $content = $label;
4361 if (!empty($CFG->supportpage)) {
4362 $attributes = ['href' => $CFG->supportpage, 'target' => 'blank'];
4363 $content .= $this->pix_icon('i/externallink', '', 'moodle', ['class' => 'ml-1']);
4364 } else {
4365 $attributes = ['href' => $CFG->wwwroot . '/user/contactsitesupport.php'];
4368 $attributes += $customattribs;
4370 return html_writer::tag('a', $content, $attributes);
4374 * Returns the services and support link for the help pop-up.
4376 * @return string
4378 public function services_support_link(): string {
4379 global $CFG;
4381 if (during_initial_install() ||
4382 (isset($CFG->showservicesandsupportcontent) && $CFG->showservicesandsupportcontent == false) ||
4383 !is_siteadmin()) {
4384 return '';
4387 $liferingicon = $this->pix_icon('t/life-ring', '', 'moodle', ['class' => 'fa fa-life-ring']);
4388 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle', ['class' => 'ml-1']);
4389 $link = !empty($CFG->servicespage)
4390 ? $CFG->servicespage
4391 : 'https://moodle.com/help/?utm_source=CTA-banner&utm_medium=platform&utm_campaign=name~Moodle4+cat~lms+mp~no';
4392 $content = $liferingicon . get_string('moodleservicesandsupport') . $newwindowicon;
4394 return html_writer::tag('a', $content, ['target' => '_blank', 'href' => $link]);
4398 * Helper function to decide whether to show the help popover header or not.
4400 * @return bool
4402 public function has_popover_links(): bool {
4403 return !empty($this->services_support_link()) || !empty($this->page_doc_link()) || !empty($this->supportemail());
4407 * Helper function to decide whether to show the communication link or not.
4409 * @return bool
4411 public function has_communication_links(): bool {
4412 if (during_initial_install() || !core_communication\api::is_available()) {
4413 return false;
4415 return !empty($this->communication_link());
4419 * Returns the communication link, complete with html.
4421 * @return string
4423 public function communication_link(): string {
4424 $link = $this->communication_url() ?? '';
4425 $commicon = $this->pix_icon('t/messages-o', '', 'moodle', ['class' => 'fa fa-comments']);
4426 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle', ['class' => 'ml-1']);
4427 $content = $commicon . get_string('communicationroomlink', 'course') . $newwindowicon;
4428 $html = html_writer::tag('a', $content, ['target' => '_blank', 'href' => $link]);
4430 return !empty($link) ? $html : '';
4434 * Returns the communication url for a given instance if it exists.
4436 * @return string
4438 public function communication_url(): string {
4439 global $COURSE;
4440 $url = '';
4441 if ($COURSE->id !== SITEID) {
4442 $comm = \core_communication\api::load_by_instance(
4443 context: \core\context\course::instance($COURSE->id),
4444 component: 'core_course',
4445 instancetype: 'coursecommunication',
4446 instanceid: $COURSE->id,
4448 $url = $comm->get_communication_room_url();
4451 return !empty($url) ? $url : '';
4455 * Returns the page heading menu.
4457 * @since Moodle 2.5.1 2.6
4458 * @return string HTML.
4460 public function page_heading_menu() {
4461 return $this->page->headingmenu;
4465 * Returns the title to use on the page.
4467 * @since Moodle 2.5.1 2.6
4468 * @return string
4470 public function page_title() {
4471 return $this->page->title;
4475 * Returns the moodle_url for the favicon.
4477 * @since Moodle 2.5.1 2.6
4478 * @return moodle_url The moodle_url for the favicon
4480 public function favicon() {
4481 $logo = null;
4482 if (!during_initial_install()) {
4483 $logo = get_config('core_admin', 'favicon');
4485 if (empty($logo)) {
4486 return $this->image_url('favicon', 'theme');
4489 // Use $CFG->themerev to prevent browser caching when the file changes.
4490 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'favicon', '64x64/',
4491 theme_get_revision(), $logo);
4495 * Renders preferences groups.
4497 * @param preferences_groups $renderable The renderable
4498 * @return string The output.
4500 public function render_preferences_groups(preferences_groups $renderable) {
4501 return $this->render_from_template('core/preferences_groups', $renderable);
4505 * Renders preferences group.
4507 * @param preferences_group $renderable The renderable
4508 * @return string The output.
4510 public function render_preferences_group(preferences_group $renderable) {
4511 $html = '';
4512 $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4513 $html .= $this->heading($renderable->title, 3);
4514 $html .= html_writer::start_tag('ul');
4515 foreach ($renderable->nodes as $node) {
4516 if ($node->has_children()) {
4517 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4519 $html .= html_writer::tag('li', $this->render($node));
4521 $html .= html_writer::end_tag('ul');
4522 $html .= html_writer::end_tag('div');
4523 return $html;
4526 public function context_header($headerinfo = null, $headinglevel = 1) {
4527 global $DB, $USER, $CFG, $SITE;
4528 require_once($CFG->dirroot . '/user/lib.php');
4529 $context = $this->page->context;
4530 $heading = null;
4531 $imagedata = null;
4532 $subheader = null;
4533 $userbuttons = null;
4535 // Make sure to use the heading if it has been set.
4536 if (isset($headerinfo['heading'])) {
4537 $heading = $headerinfo['heading'];
4538 } else {
4539 $heading = $this->page->heading;
4542 // The user context currently has images and buttons. Other contexts may follow.
4543 if ((isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) && $this->page->pagetype !== 'my-index') {
4544 if (isset($headerinfo['user'])) {
4545 $user = $headerinfo['user'];
4546 } else {
4547 // Look up the user information if it is not supplied.
4548 $user = $DB->get_record('user', array('id' => $context->instanceid));
4551 // If the user context is set, then use that for capability checks.
4552 if (isset($headerinfo['usercontext'])) {
4553 $context = $headerinfo['usercontext'];
4556 // Only provide user information if the user is the current user, or a user which the current user can view.
4557 // When checking user_can_view_profile(), either:
4558 // If the page context is course, check the course context (from the page object) or;
4559 // If page context is NOT course, then check across all courses.
4560 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4562 if (user_can_view_profile($user, $course)) {
4563 // Use the user's full name if the heading isn't set.
4564 if (empty($heading)) {
4565 $heading = fullname($user);
4568 $imagedata = $this->user_picture($user, array('size' => 100));
4570 // Check to see if we should be displaying a message button.
4571 if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
4572 $userbuttons = array(
4573 'messages' => array(
4574 'buttontype' => 'message',
4575 'title' => get_string('message', 'message'),
4576 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4577 'image' => 'message',
4578 'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
4579 'page' => $this->page
4583 if ($USER->id != $user->id) {
4584 $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4585 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4586 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4587 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4588 $userbuttons['togglecontact'] = array(
4589 'buttontype' => 'togglecontact',
4590 'title' => get_string($contacttitle, 'message'),
4591 'url' => new moodle_url('/message/index.php', array(
4592 'user1' => $USER->id,
4593 'user2' => $user->id,
4594 $contacturlaction => $user->id,
4595 'sesskey' => sesskey())
4597 'image' => $contactimage,
4598 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4599 'page' => $this->page
4603 } else {
4604 $heading = null;
4609 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4610 return $this->render_context_header($contextheader);
4614 * Renders the skip links for the page.
4616 * @param array $links List of skip links.
4617 * @return string HTML for the skip links.
4619 public function render_skip_links($links) {
4620 $context = [ 'links' => []];
4622 foreach ($links as $url => $text) {
4623 $context['links'][] = [ 'url' => $url, 'text' => $text];
4626 return $this->render_from_template('core/skip_links', $context);
4630 * Renders the header bar.
4632 * @param context_header $contextheader Header bar object.
4633 * @return string HTML for the header bar.
4635 protected function render_context_header(context_header $contextheader) {
4637 // Generate the heading first and before everything else as we might have to do an early return.
4638 if (!isset($contextheader->heading)) {
4639 $heading = $this->heading($this->page->heading, $contextheader->headinglevel);
4640 } else {
4641 $heading = $this->heading($contextheader->heading, $contextheader->headinglevel);
4644 $showheader = empty($this->page->layout_options['nocontextheader']);
4645 if (!$showheader) {
4646 // Return the heading wrapped in an sr-only element so it is only visible to screen-readers.
4647 return html_writer::div($heading, 'sr-only');
4650 // All the html stuff goes here.
4651 $html = html_writer::start_div('page-context-header');
4653 // Image data.
4654 if (isset($contextheader->imagedata)) {
4655 // Header specific image.
4656 $html .= html_writer::div($contextheader->imagedata, 'page-header-image icon-size-7');
4659 // Headings.
4660 if (isset($contextheader->prefix)) {
4661 $prefix = html_writer::div($contextheader->prefix, 'text-muted');
4662 $heading = $prefix . $heading;
4664 $html .= html_writer::tag('div', $heading, array('class' => 'page-header-headings'));
4666 // Buttons.
4667 if (isset($contextheader->additionalbuttons)) {
4668 $html .= html_writer::start_div('btn-group header-button-group');
4669 foreach ($contextheader->additionalbuttons as $button) {
4670 if (!isset($button->page)) {
4671 // Include js for messaging.
4672 if ($button['buttontype'] === 'togglecontact') {
4673 \core_message\helper::togglecontact_requirejs();
4675 if ($button['buttontype'] === 'message') {
4676 \core_message\helper::messageuser_requirejs();
4678 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4679 'class' => 'iconsmall',
4680 'role' => 'presentation'
4682 $image .= html_writer::span($button['title'], 'header-button-title');
4683 } else {
4684 $image = html_writer::empty_tag('img', array(
4685 'src' => $button['formattedimage'],
4686 'role' => 'presentation'
4689 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4691 $html .= html_writer::end_div();
4693 $html .= html_writer::end_div();
4695 return $html;
4699 * Wrapper for header elements.
4701 * @return string HTML to display the main header.
4703 public function full_header() {
4704 $pagetype = $this->page->pagetype;
4705 $homepage = get_home_page();
4706 $homepagetype = null;
4707 // Add a special case since /my/courses is a part of the /my subsystem.
4708 if ($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES) {
4709 $homepagetype = 'my-index';
4710 } else if ($homepage == HOMEPAGE_SITE) {
4711 $homepagetype = 'site-index';
4713 if ($this->page->include_region_main_settings_in_header_actions() &&
4714 !$this->page->blocks->is_block_present('settings')) {
4715 // Only include the region main settings if the page has requested it and it doesn't already have
4716 // the settings block on it. The region main settings are included in the settings block and
4717 // duplicating the content causes behat failures.
4718 $this->page->add_header_action(html_writer::div(
4719 $this->region_main_settings_menu(),
4720 'd-print-none',
4721 ['id' => 'region-main-settings-menu']
4725 $header = new stdClass();
4726 $header->settingsmenu = $this->context_header_settings_menu();
4727 $header->contextheader = $this->context_header();
4728 $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
4729 $header->navbar = $this->navbar();
4730 $header->pageheadingbutton = $this->page_heading_button();
4731 $header->courseheader = $this->course_header();
4732 $header->headeractions = $this->page->get_header_actions();
4733 if (!empty($pagetype) && !empty($homepagetype) && $pagetype == $homepagetype) {
4734 $header->welcomemessage = \core_user::welcome_message();
4736 return $this->render_from_template('core/full_header', $header);
4740 * This is an optional menu that can be added to a layout by a theme. It contains the
4741 * menu for the course administration, only on the course main page.
4743 * @return string
4745 public function context_header_settings_menu() {
4746 $context = $this->page->context;
4747 $menu = new action_menu();
4749 $items = $this->page->navbar->get_items();
4750 $currentnode = end($items);
4752 $showcoursemenu = false;
4753 $showfrontpagemenu = false;
4754 $showusermenu = false;
4756 // We are on the course home page.
4757 if (($context->contextlevel == CONTEXT_COURSE) &&
4758 !empty($currentnode) &&
4759 ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
4760 $showcoursemenu = true;
4763 $courseformat = course_get_format($this->page->course);
4764 // This is a single activity course format, always show the course menu on the activity main page.
4765 if ($context->contextlevel == CONTEXT_MODULE &&
4766 !$courseformat->has_view_page()) {
4768 $this->page->navigation->initialise();
4769 $activenode = $this->page->navigation->find_active_node();
4770 // If the settings menu has been forced then show the menu.
4771 if ($this->page->is_settings_menu_forced()) {
4772 $showcoursemenu = true;
4773 } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
4774 $activenode->type == navigation_node::TYPE_RESOURCE)) {
4776 // We only want to show the menu on the first page of the activity. This means
4777 // the breadcrumb has no additional nodes.
4778 if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
4779 $showcoursemenu = true;
4784 // This is the site front page.
4785 if ($context->contextlevel == CONTEXT_COURSE &&
4786 !empty($currentnode) &&
4787 $currentnode->key === 'home') {
4788 $showfrontpagemenu = true;
4791 // This is the user profile page.
4792 if ($context->contextlevel == CONTEXT_USER &&
4793 !empty($currentnode) &&
4794 ($currentnode->key === 'myprofile')) {
4795 $showusermenu = true;
4798 if ($showfrontpagemenu) {
4799 $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
4800 if ($settingsnode) {
4801 // Build an action menu based on the visible nodes from this navigation tree.
4802 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4804 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4805 if ($skipped) {
4806 $text = get_string('morenavigationlinks');
4807 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4808 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4809 $menu->add_secondary_action($link);
4812 } else if ($showcoursemenu) {
4813 $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
4814 if ($settingsnode) {
4815 // Build an action menu based on the visible nodes from this navigation tree.
4816 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4818 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4819 if ($skipped) {
4820 $text = get_string('morenavigationlinks');
4821 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4822 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4823 $menu->add_secondary_action($link);
4826 } else if ($showusermenu) {
4827 // Get the course admin node from the settings navigation.
4828 $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
4829 if ($settingsnode) {
4830 // Build an action menu based on the visible nodes from this navigation tree.
4831 $this->build_action_menu_from_navigation($menu, $settingsnode);
4835 return $this->render($menu);
4839 * Take a node in the nav tree and make an action menu out of it.
4840 * The links are injected in the action menu.
4842 * @param action_menu $menu
4843 * @param navigation_node $node
4844 * @param boolean $indent
4845 * @param boolean $onlytopleafnodes
4846 * @return boolean nodesskipped - True if nodes were skipped in building the menu
4848 protected function build_action_menu_from_navigation(action_menu $menu,
4849 navigation_node $node,
4850 $indent = false,
4851 $onlytopleafnodes = false) {
4852 $skipped = false;
4853 // Build an action menu based on the visible nodes from this navigation tree.
4854 foreach ($node->children as $menuitem) {
4855 if ($menuitem->display) {
4856 if ($onlytopleafnodes && $menuitem->children->count()) {
4857 $skipped = true;
4858 continue;
4860 if ($menuitem->action) {
4861 if ($menuitem->action instanceof action_link) {
4862 $link = $menuitem->action;
4863 // Give preference to setting icon over action icon.
4864 if (!empty($menuitem->icon)) {
4865 $link->icon = $menuitem->icon;
4867 } else {
4868 $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
4870 } else {
4871 if ($onlytopleafnodes) {
4872 $skipped = true;
4873 continue;
4875 $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
4877 if ($indent) {
4878 $link->add_class('ml-4');
4880 if (!empty($menuitem->classes)) {
4881 $link->add_class(implode(" ", $menuitem->classes));
4884 $menu->add_secondary_action($link);
4885 $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
4888 return $skipped;
4892 * This is an optional menu that can be added to a layout by a theme. It contains the
4893 * menu for the most specific thing from the settings block. E.g. Module administration.
4895 * @return string
4897 public function region_main_settings_menu() {
4898 $context = $this->page->context;
4899 $menu = new action_menu();
4901 if ($context->contextlevel == CONTEXT_MODULE) {
4903 $this->page->navigation->initialise();
4904 $node = $this->page->navigation->find_active_node();
4905 $buildmenu = false;
4906 // If the settings menu has been forced then show the menu.
4907 if ($this->page->is_settings_menu_forced()) {
4908 $buildmenu = true;
4909 } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
4910 $node->type == navigation_node::TYPE_RESOURCE)) {
4912 $items = $this->page->navbar->get_items();
4913 $navbarnode = end($items);
4914 // We only want to show the menu on the first page of the activity. This means
4915 // the breadcrumb has no additional nodes.
4916 if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
4917 $buildmenu = true;
4920 if ($buildmenu) {
4921 // Get the course admin node from the settings navigation.
4922 $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
4923 if ($node) {
4924 // Build an action menu based on the visible nodes from this navigation tree.
4925 $this->build_action_menu_from_navigation($menu, $node);
4929 } else if ($context->contextlevel == CONTEXT_COURSECAT) {
4930 // For course category context, show category settings menu, if we're on the course category page.
4931 if ($this->page->pagetype === 'course-index-category') {
4932 $node = $this->page->settingsnav->find('categorysettings', 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);
4939 } else {
4940 $items = $this->page->navbar->get_items();
4941 $navbarnode = end($items);
4943 if ($navbarnode && ($navbarnode->key === 'participants')) {
4944 $node = $this->page->settingsnav->find('users', navigation_node::TYPE_CONTAINER);
4945 if ($node) {
4946 // Build an action menu based on the visible nodes from this navigation tree.
4947 $this->build_action_menu_from_navigation($menu, $node);
4952 return $this->render($menu);
4956 * Displays the list of tags associated with an entry
4958 * @param array $tags list of instances of core_tag or stdClass
4959 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4960 * to use default, set to '' (empty string) to omit the label completely
4961 * @param string $classes additional classes for the enclosing div element
4962 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4963 * will be appended to the end, JS will toggle the rest of the tags
4964 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4965 * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
4966 * @return string
4968 public function tag_list($tags, $label = null, $classes = '', $limit = 10,
4969 $pagecontext = null, $accesshidelabel = false) {
4970 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
4971 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4975 * Renders element for inline editing of any value
4977 * @param \core\output\inplace_editable $element
4978 * @return string
4980 public function render_inplace_editable(\core\output\inplace_editable $element) {
4981 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4985 * Renders a bar chart.
4987 * @param \core\chart_bar $chart The chart.
4988 * @return string
4990 public function render_chart_bar(\core\chart_bar $chart) {
4991 return $this->render_chart($chart);
4995 * Renders a line chart.
4997 * @param \core\chart_line $chart The chart.
4998 * @return string
5000 public function render_chart_line(\core\chart_line $chart) {
5001 return $this->render_chart($chart);
5005 * Renders a pie chart.
5007 * @param \core\chart_pie $chart The chart.
5008 * @return string
5010 public function render_chart_pie(\core\chart_pie $chart) {
5011 return $this->render_chart($chart);
5015 * Renders a chart.
5017 * @param \core\chart_base $chart The chart.
5018 * @param bool $withtable Whether to include a data table with the chart.
5019 * @return string
5021 public function render_chart(\core\chart_base $chart, $withtable = true) {
5022 $chartdata = json_encode($chart);
5023 return $this->render_from_template('core/chart', (object) [
5024 'chartdata' => $chartdata,
5025 'withtable' => $withtable
5030 * Renders the login form.
5032 * @param \core_auth\output\login $form The renderable.
5033 * @return string
5035 public function render_login(\core_auth\output\login $form) {
5036 global $CFG, $SITE;
5038 $context = $form->export_for_template($this);
5040 $context->errorformatted = $this->error_text($context->error);
5041 $url = $this->get_logo_url();
5042 if ($url) {
5043 $url = $url->out(false);
5045 $context->logourl = $url;
5046 $context->sitename = format_string($SITE->fullname, true,
5047 ['context' => context_course::instance(SITEID), "escape" => false]);
5049 return $this->render_from_template('core/loginform', $context);
5053 * Renders an mform element from a template.
5055 * @param HTML_QuickForm_element $element element
5056 * @param bool $required if input is required field
5057 * @param bool $advanced if input is an advanced field
5058 * @param string $error error message to display
5059 * @param bool $ingroup True if this element is rendered as part of a group
5060 * @return mixed string|bool
5062 public function mform_element($element, $required, $advanced, $error, $ingroup) {
5063 $templatename = 'core_form/element-' . $element->getType();
5064 if ($ingroup) {
5065 $templatename .= "-inline";
5067 try {
5068 // We call this to generate a file not found exception if there is no template.
5069 // We don't want to call export_for_template if there is no template.
5070 core\output\mustache_template_finder::get_template_filepath($templatename);
5072 if ($element instanceof templatable) {
5073 $elementcontext = $element->export_for_template($this);
5075 $helpbutton = '';
5076 if (method_exists($element, 'getHelpButton')) {
5077 $helpbutton = $element->getHelpButton();
5079 $label = $element->getLabel();
5080 $text = '';
5081 if (method_exists($element, 'getText')) {
5082 // There currently exists code that adds a form element with an empty label.
5083 // If this is the case then set the label to the description.
5084 if (empty($label)) {
5085 $label = $element->getText();
5086 } else {
5087 $text = $element->getText();
5091 // Generate the form element wrapper ids and names to pass to the template.
5092 // This differs between group and non-group elements.
5093 if ($element->getType() === 'group') {
5094 // Group element.
5095 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
5096 $elementcontext['wrapperid'] = $elementcontext['id'];
5098 // Ensure group elements pass through the group name as the element name.
5099 $elementcontext['name'] = $elementcontext['groupname'];
5100 } else {
5101 // Non grouped element.
5102 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
5103 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
5106 $context = array(
5107 'element' => $elementcontext,
5108 'label' => $label,
5109 'text' => $text,
5110 'required' => $required,
5111 'advanced' => $advanced,
5112 'helpbutton' => $helpbutton,
5113 'error' => $error
5115 return $this->render_from_template($templatename, $context);
5117 } catch (Exception $e) {
5118 // No template for this element.
5119 return false;
5124 * Render the login signup form into a nice template for the theme.
5126 * @param mform $form
5127 * @return string
5129 public function render_login_signup_form($form) {
5130 global $SITE;
5132 $context = $form->export_for_template($this);
5133 $url = $this->get_logo_url();
5134 if ($url) {
5135 $url = $url->out(false);
5137 $context['logourl'] = $url;
5138 $context['sitename'] = format_string($SITE->fullname, true,
5139 ['context' => context_course::instance(SITEID), "escape" => false]);
5141 return $this->render_from_template('core/signup_form_layout', $context);
5145 * Render the verify age and location page into a nice template for the theme.
5147 * @param \core_auth\output\verify_age_location_page $page The renderable
5148 * @return string
5150 protected function render_verify_age_location_page($page) {
5151 $context = $page->export_for_template($this);
5153 return $this->render_from_template('core/auth_verify_age_location_page', $context);
5157 * Render the digital minor contact information page into a nice template for the theme.
5159 * @param \core_auth\output\digital_minor_page $page The renderable
5160 * @return string
5162 protected function render_digital_minor_page($page) {
5163 $context = $page->export_for_template($this);
5165 return $this->render_from_template('core/auth_digital_minor_page', $context);
5169 * Renders a progress bar.
5171 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
5173 * @param progress_bar $bar The bar.
5174 * @return string HTML fragment
5176 public function render_progress_bar(progress_bar $bar) {
5177 $data = $bar->export_for_template($this);
5178 return $this->render_from_template('core/progress_bar', $data);
5182 * Renders an update to a progress bar.
5184 * Note: This does not cleanly map to a renderable class and should
5185 * never be used directly.
5187 * @param string $id
5188 * @param float $percent
5189 * @param string $msg Message
5190 * @param string $estimate time remaining message
5191 * @return string ascii fragment
5193 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
5194 return html_writer::script(js_writer::function_call('updateProgressBar', [$id, $percent, $msg, $estimate]));
5198 * Renders element for a toggle-all checkbox.
5200 * @param \core\output\checkbox_toggleall $element
5201 * @return string
5203 public function render_checkbox_toggleall(\core\output\checkbox_toggleall $element) {
5204 return $this->render_from_template($element->get_template(), $element->export_for_template($this));
5208 * Renders the tertiary nav for the participants page
5210 * @param object $course The course we are operating within
5211 * @param string|null $renderedbuttons Any additional buttons/content to be displayed in line with the nav
5212 * @return string
5214 public function render_participants_tertiary_nav(object $course, ?string $renderedbuttons = null) {
5215 $actionbar = new \core\output\participants_action_bar($course, $this->page, $renderedbuttons);
5216 $content = $this->render_from_template('core_course/participants_actionbar', $actionbar->export_for_template($this));
5217 return $content ?: "";
5221 * Renders release information in the footer popup
5222 * @return string Moodle release info.
5224 public function moodle_release() {
5225 global $CFG;
5226 if (!during_initial_install() && is_siteadmin()) {
5227 return $CFG->release;
5232 * Generate the add block button when editing mode is turned on and the user can edit blocks.
5234 * @param string $region where new blocks should be added.
5235 * @return string html for the add block button.
5237 public function addblockbutton($region = ''): string {
5238 $addblockbutton = '';
5239 $regions = $this->page->blocks->get_regions();
5240 if (count($regions) == 0) {
5241 return '';
5243 if (isset($this->page->theme->addblockposition) &&
5244 $this->page->user_is_editing() &&
5245 $this->page->user_can_edit_blocks() &&
5246 $this->page->pagelayout !== 'mycourses'
5248 $params = ['bui_addblock' => '', 'sesskey' => sesskey()];
5249 if (!empty($region)) {
5250 $params['bui_blockregion'] = $region;
5252 $url = new moodle_url($this->page->url, $params);
5253 $addblockbutton = $this->render_from_template('core/add_block_button',
5255 'link' => $url->out(false),
5256 'escapedlink' => "?{$url->get_query_string(false)}",
5257 'pagehash' => $this->page->get_edited_page_hash(),
5258 'blockregion' => $region,
5259 // The following parameters are not used since Moodle 4.2 but are
5260 // still passed for backward-compatibility.
5261 'pageType' => $this->page->pagetype,
5262 'pageLayout' => $this->page->pagelayout,
5263 'subPage' => $this->page->subpage,
5267 return $addblockbutton;
5271 * Prepares an element for streaming output
5273 * This must be used with NO_OUTPUT_BUFFERING set to true. After using this method
5274 * any subsequent prints or echos to STDOUT result in the outputted content magically
5275 * being appended inside that element rather than where the current html would be
5276 * normally. This enables pages which take some time to render incremental content to
5277 * first output a fully formed html page, including the footer, and to then stream
5278 * into an element such as the main content div. This fixes a class of page layout
5279 * bugs and reduces layout shift issues and was inspired by Facebook BigPipe.
5281 * Some use cases such as a simple page which loads content via ajax could be swapped
5282 * to this method wich saves another http request and its network latency resulting
5283 * in both lower server load and better front end performance.
5285 * You should consider giving the element you stream into a minimum height to further
5286 * reduce layout shift as the content initally streams into the element.
5288 * You can safely finish the output without closing the streamed element. You can also
5289 * call this method again to swap the target of the streaming to a new element as
5290 * often as you want.
5292 * https://www.youtube.com/watch?v=LLRig4s1_yA&t=1022s
5293 * Watch this video segment to explain how and why this 'One Weird Trick' works.
5295 * @param string $selector where new content should be appended
5296 * @param string $element which contains the streamed content
5297 * @return string html to be written
5299 public function select_element_for_append(string $selector = '#region-main [role=main]', string $element = 'div') {
5301 if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) {
5302 throw new coding_exception('select_element_for_append used in a non-CLI script without setting NO_OUTPUT_BUFFERING.',
5303 DEBUG_DEVELOPER);
5306 // We are already streaming into this element so don't change anything.
5307 if ($this->currentselector === $selector && $this->currentelement === $element) {
5308 return;
5311 // If we have a streaming element close it before starting a new one.
5312 $html = $this->close_element_for_append();
5314 $this->currentselector = $selector;
5315 $this->currentelement = $element;
5317 // Create an unclosed element for the streamed content to append into.
5318 $id = uniqid();
5319 $html .= html_writer::start_tag($element, ['id' => $id]);
5320 $html .= html_writer::tag('script', "document.querySelector('$selector').append(document.getElementById('$id'))");
5321 $html .= "\n";
5322 return $html;
5326 * This closes any opened stream elements
5328 * @return string html to be written
5330 public function close_element_for_append() {
5331 $html = '';
5332 if ($this->currentselector !== '') {
5333 $html .= html_writer::end_tag($this->currentelement);
5334 $html .= "\n";
5335 $this->currentelement = '';
5337 return $html;
5341 * A companion method to select_element_for_append
5343 * This must be used with NO_OUTPUT_BUFFERING set to true.
5345 * This is similar but instead of appending into the element it replaces
5346 * the content in the element. Depending on the 3rd argument it can replace
5347 * the innerHTML or the outerHTML which can be useful to completely remove
5348 * the element if needed.
5350 * @param string $selector where new content should be replaced
5351 * @param string $html A chunk of well formed html
5352 * @param bool $outer Wether it replaces the innerHTML or the outerHTML
5353 * @return string html to be written
5355 public function select_element_for_replace(string $selector, string $html, bool $outer = false) {
5357 if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) {
5358 throw new coding_exception('select_element_for_replace used in a non-CLI script without setting NO_OUTPUT_BUFFERING.',
5359 DEBUG_DEVELOPER);
5362 // Escape html for use inside a javascript string.
5363 $html = addslashes_js($html);
5364 $property = $outer ? 'outerHTML' : 'innerHTML';
5365 $output = html_writer::tag('script', "document.querySelector('$selector').$property = '$html';");
5366 $output .= "\n";
5367 return $output;
5372 * A renderer that generates output for command-line scripts.
5374 * The implementation of this renderer is probably incomplete.
5376 * @copyright 2009 Tim Hunt
5377 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5378 * @since Moodle 2.0
5379 * @package core
5380 * @category output
5382 class core_renderer_cli extends core_renderer {
5385 * @var array $progressmaximums stores the largest percentage for a progress bar.
5386 * @return string ascii fragment
5388 private $progressmaximums = [];
5391 * Returns the page header.
5393 * @return string HTML fragment
5395 public function header() {
5396 return $this->page->heading . "\n";
5400 * Renders a Check API result
5402 * To aid in CLI consistency this status is NOT translated and the visual
5403 * width is always exactly 10 chars.
5405 * @param core\check\result $result
5406 * @return string HTML fragment
5408 protected function render_check_result(core\check\result $result) {
5409 $status = $result->get_status();
5411 $labels = [
5412 core\check\result::NA => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' NA ',
5413 core\check\result::OK => ' ' . cli_ansi_format('<colour:green>') . ' OK ',
5414 core\check\result::INFO => ' ' . cli_ansi_format('<colour:blue>' ) . ' INFO ',
5415 core\check\result::UNKNOWN => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' UNKNOWN ',
5416 core\check\result::WARNING => ' ' . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
5417 core\check\result::ERROR => ' ' . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
5418 core\check\result::CRITICAL => '' . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
5420 $string = $labels[$status] . cli_ansi_format('<colour:normal>');
5421 return $string;
5425 * Renders a Check API result
5427 * @param result $result
5428 * @return string fragment
5430 public function check_result(core\check\result $result) {
5431 return $this->render_check_result($result);
5435 * Renders a progress bar.
5437 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
5439 * @param progress_bar $bar The bar.
5440 * @return string ascii fragment
5442 public function render_progress_bar(progress_bar $bar) {
5443 global $CFG;
5445 $size = 55; // The width of the progress bar in chars.
5446 $ascii = "\n";
5448 if (stream_isatty(STDOUT)) {
5449 require_once($CFG->libdir.'/clilib.php');
5451 $ascii .= "[" . str_repeat(' ', $size) . "] 0% \n";
5452 return cli_ansi_format($ascii);
5455 $this->progressmaximums[$bar->get_id()] = 0;
5456 $ascii .= '[';
5457 return $ascii;
5461 * Renders an update to a progress bar.
5463 * Note: This does not cleanly map to a renderable class and should
5464 * never be used directly.
5466 * @param string $id
5467 * @param float $percent
5468 * @param string $msg Message
5469 * @param string $estimate time remaining message
5470 * @return string ascii fragment
5472 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
5473 $size = 55; // The width of the progress bar in chars.
5474 $ascii = '';
5476 // If we are rendering to a terminal then we can safely use ansii codes
5477 // to move the cursor and redraw the complete progress bar each time
5478 // it is updated.
5479 if (stream_isatty(STDOUT)) {
5480 $colour = $percent == 100 ? 'green' : 'blue';
5482 $done = $percent * $size * 0.01;
5483 $whole = floor($done);
5484 $bar = "<colour:$colour>";
5485 $bar .= str_repeat('█', $whole);
5487 if ($whole < $size) {
5488 // By using unicode chars for partial blocks we can have higher
5489 // precision progress bar.
5490 $fraction = floor(($done - $whole) * 8);
5491 $bar .= core_text::substr(' ▏▎▍▌▋▊▉', $fraction, 1);
5493 // Fill the rest of the empty bar.
5494 $bar .= str_repeat(' ', $size - $whole - 1);
5497 $bar .= '<colour:normal>';
5499 if ($estimate) {
5500 $estimate = "- $estimate";
5503 $ascii .= '<cursor:up>';
5504 $ascii .= '<cursor:up>';
5505 $ascii .= sprintf("[$bar] %3.1f%% %-22s\n", $percent, $estimate);
5506 $ascii .= sprintf("%-80s\n", $msg);
5507 return cli_ansi_format($ascii);
5510 // If we are not rendering to a tty, ie when piped to another command
5511 // or on windows we need to progressively render the progress bar
5512 // which can only ever go forwards.
5513 $done = round($percent * $size * 0.01);
5514 $delta = max(0, $done - $this->progressmaximums[$id]);
5516 $ascii .= str_repeat('#', $delta);
5517 if ($percent >= 100 && $delta > 0) {
5518 $ascii .= sprintf("] %3.1f%%\n$msg\n", $percent);
5520 $this->progressmaximums[$id] += $delta;
5521 return $ascii;
5525 * Returns a template fragment representing a Heading.
5527 * @param string $text The text of the heading
5528 * @param int $level The level of importance of the heading
5529 * @param string $classes A space-separated list of CSS classes
5530 * @param string $id An optional ID
5531 * @return string A template fragment for a heading
5533 public function heading($text, $level = 2, $classes = 'main', $id = null) {
5534 $text .= "\n";
5535 switch ($level) {
5536 case 1:
5537 return '=>' . $text;
5538 case 2:
5539 return '-->' . $text;
5540 default:
5541 return $text;
5546 * Returns a template fragment representing a fatal error.
5548 * @param string $message The message to output
5549 * @param string $moreinfourl URL where more info can be found about the error
5550 * @param string $link Link for the Continue button
5551 * @param array $backtrace The execution backtrace
5552 * @param string $debuginfo Debugging information
5553 * @return string A template fragment for a fatal error
5555 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5556 global $CFG;
5558 $output = "!!! $message !!!\n";
5560 if ($CFG->debugdeveloper) {
5561 if (!empty($debuginfo)) {
5562 $output .= $this->notification($debuginfo, 'notifytiny');
5564 if (!empty($backtrace)) {
5565 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
5569 return $output;
5573 * Returns a template fragment representing a notification.
5575 * @param string $message The message to print out.
5576 * @param string $type The type of notification. See constants on \core\output\notification.
5577 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5578 * @return string A template fragment for a notification
5580 public function notification($message, $type = null, $closebutton = true) {
5581 $message = clean_text($message);
5582 if ($type === 'notifysuccess' || $type === 'success') {
5583 return "++ $message ++\n";
5585 return "!! $message !!\n";
5589 * There is no footer for a cli request, however we must override the
5590 * footer method to prevent the default footer.
5592 public function footer() {}
5595 * Render a notification (that is, a status message about something that has
5596 * just happened).
5598 * @param \core\output\notification $notification the notification to print out
5599 * @return string plain text output
5601 public function render_notification(\core\output\notification $notification) {
5602 return $this->notification($notification->get_message(), $notification->get_message_type());
5608 * A renderer that generates output for ajax scripts.
5610 * This renderer prevents accidental sends back only json
5611 * encoded error messages, all other output is ignored.
5613 * @copyright 2010 Petr Skoda
5614 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5615 * @since Moodle 2.0
5616 * @package core
5617 * @category output
5619 class core_renderer_ajax extends core_renderer {
5622 * Returns a template fragment representing a fatal error.
5624 * @param string $message The message to output
5625 * @param string $moreinfourl URL where more info can be found about the error
5626 * @param string $link Link for the Continue button
5627 * @param array $backtrace The execution backtrace
5628 * @param string $debuginfo Debugging information
5629 * @return string A template fragment for a fatal error
5631 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5632 global $CFG;
5634 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
5636 $e = new stdClass();
5637 $e->error = $message;
5638 $e->errorcode = $errorcode;
5639 $e->stacktrace = NULL;
5640 $e->debuginfo = NULL;
5641 $e->reproductionlink = NULL;
5642 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
5643 $link = (string) $link;
5644 if ($link) {
5645 $e->reproductionlink = $link;
5647 if (!empty($debuginfo)) {
5648 $e->debuginfo = $debuginfo;
5650 if (!empty($backtrace)) {
5651 $e->stacktrace = format_backtrace($backtrace, true);
5654 $this->header();
5655 return json_encode($e);
5659 * Used to display a notification.
5660 * For the AJAX notifications are discarded.
5662 * @param string $message The message to print out.
5663 * @param string $type The type of notification. See constants on \core\output\notification.
5664 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5666 public function notification($message, $type = null, $closebutton = true) {
5670 * Used to display a redirection message.
5671 * AJAX redirections should not occur and as such redirection messages
5672 * are discarded.
5674 * @param moodle_url|string $encodedurl
5675 * @param string $message
5676 * @param int $delay
5677 * @param bool $debugdisableredirect
5678 * @param string $messagetype The type of notification to show the message in.
5679 * See constants on \core\output\notification.
5681 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
5682 $messagetype = \core\output\notification::NOTIFY_INFO) {}
5685 * Prepares the start of an AJAX output.
5687 public function header() {
5688 // unfortunately YUI iframe upload does not support application/json
5689 if (!empty($_FILES)) {
5690 @header('Content-type: text/plain; charset=utf-8');
5691 if (!core_useragent::supports_json_contenttype()) {
5692 @header('X-Content-Type-Options: nosniff');
5694 } else if (!core_useragent::supports_json_contenttype()) {
5695 @header('Content-type: text/plain; charset=utf-8');
5696 @header('X-Content-Type-Options: nosniff');
5697 } else {
5698 @header('Content-type: application/json; charset=utf-8');
5701 // Headers to make it not cacheable and json
5702 @header('Cache-Control: no-store, no-cache, must-revalidate');
5703 @header('Cache-Control: post-check=0, pre-check=0', false);
5704 @header('Pragma: no-cache');
5705 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
5706 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
5707 @header('Accept-Ranges: none');
5711 * There is no footer for an AJAX request, however we must override the
5712 * footer method to prevent the default footer.
5714 public function footer() {}
5717 * No need for headers in an AJAX request... this should never happen.
5718 * @param string $text
5719 * @param int $level
5720 * @param string $classes
5721 * @param string $id
5723 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
5729 * The maintenance renderer.
5731 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
5732 * is running a maintenance related task.
5733 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
5735 * @since Moodle 2.6
5736 * @package core
5737 * @category output
5738 * @copyright 2013 Sam Hemelryk
5739 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5741 class core_renderer_maintenance extends core_renderer {
5744 * Initialises the renderer instance.
5746 * @param moodle_page $page
5747 * @param string $target
5748 * @throws coding_exception
5750 public function __construct(moodle_page $page, $target) {
5751 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
5752 throw new coding_exception('Invalid request for the maintenance renderer.');
5754 parent::__construct($page, $target);
5758 * Does nothing. The maintenance renderer cannot produce blocks.
5760 * @param block_contents $bc
5761 * @param string $region
5762 * @return string
5764 public function block(block_contents $bc, $region) {
5765 return '';
5769 * Does nothing. The maintenance renderer cannot produce blocks.
5771 * @param string $region
5772 * @param array $classes
5773 * @param string $tag
5774 * @param boolean $fakeblocksonly
5775 * @return string
5777 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
5778 return '';
5782 * Does nothing. The maintenance renderer cannot produce blocks.
5784 * @param string $region
5785 * @param boolean $fakeblocksonly Output fake block only.
5786 * @return string
5788 public function blocks_for_region($region, $fakeblocksonly = false) {
5789 return '';
5793 * Does nothing. The maintenance renderer cannot produce a course content header.
5795 * @param bool $onlyifnotcalledbefore
5796 * @return string
5798 public function course_content_header($onlyifnotcalledbefore = false) {
5799 return '';
5803 * Does nothing. The maintenance renderer cannot produce a course content footer.
5805 * @param bool $onlyifnotcalledbefore
5806 * @return string
5808 public function course_content_footer($onlyifnotcalledbefore = false) {
5809 return '';
5813 * Does nothing. The maintenance renderer cannot produce a course header.
5815 * @return string
5817 public function course_header() {
5818 return '';
5822 * Does nothing. The maintenance renderer cannot produce a course footer.
5824 * @return string
5826 public function course_footer() {
5827 return '';
5831 * Does nothing. The maintenance renderer cannot produce a custom menu.
5833 * @param string $custommenuitems
5834 * @return string
5836 public function custom_menu($custommenuitems = '') {
5837 return '';
5841 * Does nothing. The maintenance renderer cannot produce a file picker.
5843 * @param array $options
5844 * @return string
5846 public function file_picker($options) {
5847 return '';
5851 * Overridden confirm message for upgrades.
5853 * @param string $message The question to ask the user
5854 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5855 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5856 * @param array $displayoptions optional extra display options
5857 * @return string HTML fragment
5859 public function confirm($message, $continue, $cancel, array $displayoptions = []) {
5860 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5861 // from any previous version of Moodle).
5862 if ($continue instanceof single_button) {
5863 $continue->type = single_button::BUTTON_PRIMARY;
5864 } else if (is_string($continue)) {
5865 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post',
5866 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
5867 } else if ($continue instanceof moodle_url) {
5868 $continue = new single_button($continue, get_string('continue'), 'post',
5869 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
5870 } else {
5871 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5872 ' (string/moodle_url) or a single_button instance.');
5875 if ($cancel instanceof single_button) {
5876 $output = '';
5877 } else if (is_string($cancel)) {
5878 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5879 } else if ($cancel instanceof moodle_url) {
5880 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5881 } else {
5882 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5883 ' (string/moodle_url) or a single_button instance.');
5886 $output = $this->box_start('generalbox', 'notice');
5887 $output .= html_writer::tag('h4', get_string('confirm'));
5888 $output .= html_writer::tag('p', $message);
5889 $output .= html_writer::tag('div', $this->render($cancel) . $this->render($continue), ['class' => 'buttons']);
5890 $output .= $this->box_end();
5891 return $output;
5895 * Does nothing. The maintenance renderer does not support JS.
5897 * @param block_contents $bc
5899 public function init_block_hider_js(block_contents $bc) {
5900 // Does nothing.
5904 * Does nothing. The maintenance renderer cannot produce language menus.
5906 * @return string
5908 public function lang_menu() {
5909 return '';
5913 * Does nothing. The maintenance renderer has no need for login information.
5915 * @param null $withlinks
5916 * @return string
5918 public function login_info($withlinks = null) {
5919 return '';
5923 * Secure login info.
5925 * @return string
5927 public function secure_login_info() {
5928 return $this->login_info(false);
5932 * Does nothing. The maintenance renderer cannot produce user pictures.
5934 * @param stdClass $user
5935 * @param array $options
5936 * @return string
5938 public function user_picture(stdClass $user, array $options = null) {
5939 return '';