Merge branch 'MDL-79938-main' of https://github.com/sammarshallou/moodle
[moodle.git] / lib / outputrenderers.php
blob3cef72177a2a7442170dbe6df29d42c85caf9d97
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 try {
185 // Grab a copy of the existing helper to be restored later.
186 $uniqidhelper = $mustache->getHelper('uniqid');
187 } catch (Mustache_Exception_UnknownHelperException $e) {
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.
705 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
706 foreach ($pluginswithfunction as $plugins) {
707 foreach ($plugins as $function) {
708 $output .= $function();
712 // Allow a url_rewrite plugin to setup any dynamic head content.
713 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
714 $class = $CFG->urlrewriteclass;
715 $output .= $class::html_head_setup();
718 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
719 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
720 // This is only set by the {@link redirect()} method
721 $output .= $this->metarefreshtag;
723 // Check if a periodic refresh delay has been set and make sure we arn't
724 // already meta refreshing
725 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
726 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
729 // Set up help link popups for all links with the helptooltip class
730 $this->page->requires->js_init_call('M.util.help_popups.setup');
732 $focus = $this->page->focuscontrol;
733 if (!empty($focus)) {
734 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
735 // This is a horrifically bad way to handle focus but it is passed in
736 // through messy formslib::moodleform
737 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
738 } else if (strpos($focus, '.')!==false) {
739 // Old style of focus, bad way to do it
740 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);
741 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
742 } else {
743 // Focus element with given id
744 $this->page->requires->js_function_call('focuscontrol', array($focus));
748 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
749 // any other custom CSS can not be overridden via themes and is highly discouraged
750 $urls = $this->page->theme->css_urls($this->page);
751 foreach ($urls as $url) {
752 $this->page->requires->css_theme($url);
755 // Get the theme javascript head and footer
756 if ($jsurl = $this->page->theme->javascript_url(true)) {
757 $this->page->requires->js($jsurl, true);
759 if ($jsurl = $this->page->theme->javascript_url(false)) {
760 $this->page->requires->js($jsurl);
763 // Get any HTML from the page_requirements_manager.
764 $output .= $this->page->requires->get_head_code($this->page, $this);
766 // List alternate versions.
767 foreach ($this->page->alternateversions as $type => $alt) {
768 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
769 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
772 // Add noindex tag if relevant page and setting applied.
773 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
774 $loginpages = array('login-index', 'login-signup');
775 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
776 if (!isset($CFG->additionalhtmlhead)) {
777 $CFG->additionalhtmlhead = '';
779 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
782 if (!empty($CFG->additionalhtmlhead)) {
783 $output .= "\n".$CFG->additionalhtmlhead;
786 if ($this->page->pagelayout == 'frontpage') {
787 $summary = s(strip_tags(format_text($SITE->summary, FORMAT_HTML)));
788 if (!empty($summary)) {
789 $output .= "<meta name=\"description\" content=\"$summary\" />\n";
793 return $output;
797 * The standard tags (typically skip links) that should be output just inside
798 * the start of the <body> tag. Designed to be called in theme layout.php files.
800 * @return string HTML fragment.
802 public function standard_top_of_body_html() {
803 global $CFG;
804 $output = $this->page->requires->get_top_of_body_code($this);
805 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
806 $output .= "\n".$CFG->additionalhtmltopofbody;
809 // Give subsystems an opportunity to inject extra html content. The callback
810 // must always return a string containing valid html.
811 foreach (\core_component::get_core_subsystems() as $name => $path) {
812 if ($path) {
813 $output .= component_callback($name, 'before_standard_top_of_body_html', [], '');
817 // Give plugins an opportunity to inject extra html content. The callback
818 // must always return a string containing valid html.
819 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
820 foreach ($pluginswithfunction as $plugins) {
821 foreach ($plugins as $function) {
822 $output .= $function();
826 $output .= $this->maintenance_warning();
828 return $output;
832 * Scheduled maintenance warning message.
834 * Note: This is a nasty hack to display maintenance notice, this should be moved
835 * to some general notification area once we have it.
837 * @return string
839 public function maintenance_warning() {
840 global $CFG;
842 $output = '';
843 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
844 $timeleft = $CFG->maintenance_later - time();
845 // If timeleft less than 30 sec, set the class on block to error to highlight.
846 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
847 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-3 alert');
848 $a = new stdClass();
849 $a->hour = (int)($timeleft / 3600);
850 $a->min = (int)(floor($timeleft / 60) % 60);
851 $a->sec = (int)($timeleft % 60);
852 if ($a->hour > 0) {
853 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
854 } else {
855 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
858 $output .= $this->box_end();
859 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
860 array(array('timeleftinsec' => $timeleft)));
861 $this->page->requires->strings_for_js(
862 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
863 'admin');
865 return $output;
869 * content that should be output in the footer area
870 * of the page. Designed to be called in theme layout.php files.
872 * @return string HTML fragment.
874 public function standard_footer_html() {
875 global $CFG;
877 $output = '';
878 if (during_initial_install()) {
879 // Debugging info can not work before install is finished,
880 // in any case we do not want any links during installation!
881 return $output;
884 // Give plugins an opportunity to add any footer elements.
885 // The callback must always return a string containing valid html footer content.
886 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
887 foreach ($pluginswithfunction as $plugins) {
888 foreach ($plugins as $function) {
889 $output .= $function();
893 if (core_userfeedback::can_give_feedback()) {
894 $output .= html_writer::div(
895 $this->render_from_template('core/userfeedback_footer_link', ['url' => core_userfeedback::make_link()->out(false)])
899 if ($this->page->devicetypeinuse == 'legacy') {
900 // The legacy theme is in use print the notification
901 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
904 // Get links to switch device types (only shown for users not on a default device)
905 $output .= $this->theme_switch_links();
907 return $output;
911 * Performance information and validation links for debugging.
913 * @return string HTML fragment.
915 public function debug_footer_html() {
916 global $CFG, $SCRIPT;
917 $output = '';
919 if (during_initial_install()) {
920 // Debugging info can not work before install is finished.
921 return $output;
924 // This function is normally called from a layout.php file
925 // but some of the content won't be known until later, so we return a placeholder
926 // for now. This will be replaced with the real content in the footer.
927 $output .= $this->unique_performance_info_token;
929 if (!empty($CFG->debugpageinfo)) {
930 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
931 $this->page->debug_summary()) . '</div>';
933 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
935 // Add link to profiling report if necessary
936 if (function_exists('profiling_is_running') && profiling_is_running()) {
937 $txt = get_string('profiledscript', 'admin');
938 $title = get_string('profiledscriptview', 'admin');
939 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
940 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
941 $output .= '<div class="profilingfooter">' . $link . '</div>';
943 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
944 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
945 $output .= '<div class="purgecaches">' .
946 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
948 // Reactive module debug panel.
949 $output .= $this->render_from_template('core/local/reactive/debugpanel', []);
951 if (!empty($CFG->debugvalidators)) {
952 $siteurl = qualified_me();
953 $nuurl = new moodle_url('https://validator.w3.org/nu/', ['doc' => $siteurl, 'showsource' => 'yes']);
954 $waveurl = new moodle_url('https://wave.webaim.org/report#/' . urlencode($siteurl));
955 $validatorlinks = [
956 html_writer::link($nuurl, get_string('validatehtml')),
957 html_writer::link($waveurl, get_string('wcagcheck'))
959 $validatorlinkslist = html_writer::alist($validatorlinks, ['class' => 'list-unstyled ml-1']);
960 $output .= html_writer::div($validatorlinkslist, 'validators');
962 return $output;
966 * Returns standard main content placeholder.
967 * Designed to be called in theme layout.php files.
969 * @return string HTML fragment.
971 public function main_content() {
972 // This is here because it is the only place we can inject the "main" role over the entire main content area
973 // without requiring all theme's to manually do it, and without creating yet another thing people need to
974 // remember in the theme.
975 // This is an unfortunate hack. DO NO EVER add anything more here.
976 // DO NOT add classes.
977 // DO NOT add an id.
978 return '<div role="main">'.$this->unique_main_content_token.'</div>';
982 * Returns information about an activity.
984 * @deprecated since Moodle 4.3 MDL-78744
985 * @todo MDL-78926 This method will be deleted in Moodle 4.7
986 * @param cm_info $cminfo The course module information.
987 * @param cm_completion_details $completiondetails The completion details for this activity module.
988 * @param array $activitydates The dates for this activity module.
989 * @return string the activity information HTML.
990 * @throws coding_exception
992 public function activity_information(cm_info $cminfo, cm_completion_details $completiondetails, array $activitydates): string {
993 debugging('activity_information method is deprecated.', DEBUG_DEVELOPER);
994 if (!$completiondetails->has_completion() && empty($activitydates)) {
995 // No need to render the activity information when there's no completion info and activity dates to show.
996 return '';
998 $activityinfo = new activity_information($cminfo, $completiondetails, $activitydates);
999 $renderer = $this->page->get_renderer('core', 'course');
1000 return $renderer->render($activityinfo);
1004 * Returns standard navigation between activities in a course.
1006 * @return string the navigation HTML.
1008 public function activity_navigation() {
1009 // First we should check if we want to add navigation.
1010 $context = $this->page->context;
1011 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
1012 || $context->contextlevel != CONTEXT_MODULE) {
1013 return '';
1016 // If the activity is in stealth mode, show no links.
1017 if ($this->page->cm->is_stealth()) {
1018 return '';
1021 $course = $this->page->cm->get_course();
1022 $courseformat = course_get_format($course);
1024 // If the theme implements course index and the current course format uses course index and the current
1025 // page layout is not 'frametop' (this layout does not support course index), show no links.
1026 if ($this->page->theme->usescourseindex && $courseformat->uses_course_index() &&
1027 $this->page->pagelayout !== 'frametop') {
1028 return '';
1031 // Get a list of all the activities in the course.
1032 $modules = get_fast_modinfo($course->id)->get_cms();
1034 // Put the modules into an array in order by the position they are shown in the course.
1035 $mods = [];
1036 $activitylist = [];
1037 foreach ($modules as $module) {
1038 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
1039 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
1040 continue;
1042 $mods[$module->id] = $module;
1044 // No need to add the current module to the list for the activity dropdown menu.
1045 if ($module->id == $this->page->cm->id) {
1046 continue;
1048 // Module name.
1049 $modname = $module->get_formatted_name();
1050 // Display the hidden text if necessary.
1051 if (!$module->visible) {
1052 $modname .= ' ' . get_string('hiddenwithbrackets');
1054 // Module URL.
1055 $linkurl = new moodle_url($module->url, array('forceview' => 1));
1056 // Add module URL (as key) and name (as value) to the activity list array.
1057 $activitylist[$linkurl->out(false)] = $modname;
1060 $nummods = count($mods);
1062 // If there is only one mod then do nothing.
1063 if ($nummods == 1) {
1064 return '';
1067 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
1068 $modids = array_keys($mods);
1070 // Get the position in the array of the course module we are viewing.
1071 $position = array_search($this->page->cm->id, $modids);
1073 $prevmod = null;
1074 $nextmod = null;
1076 // Check if we have a previous mod to show.
1077 if ($position > 0) {
1078 $prevmod = $mods[$modids[$position - 1]];
1081 // Check if we have a next mod to show.
1082 if ($position < ($nummods - 1)) {
1083 $nextmod = $mods[$modids[$position + 1]];
1086 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
1087 $renderer = $this->page->get_renderer('core', 'course');
1088 return $renderer->render($activitynav);
1092 * The standard tags (typically script tags that are not needed earlier) that
1093 * should be output after everything else. Designed to be called in theme layout.php files.
1095 * @return string HTML fragment.
1097 public function standard_end_of_body_html() {
1098 global $CFG;
1100 // This function is normally called from a layout.php file in {@link core_renderer::header()}
1101 // but some of the content won't be known until later, so we return a placeholder
1102 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
1103 $output = '';
1104 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
1105 $output .= "\n".$CFG->additionalhtmlfooter;
1107 $output .= $this->unique_end_html_token;
1108 return $output;
1112 * The standard HTML that should be output just before the <footer> tag.
1113 * Designed to be called in theme layout.php files.
1115 * @return string HTML fragment.
1117 public function standard_after_main_region_html() {
1118 global $CFG;
1119 $output = '';
1120 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlbottomofbody)) {
1121 $output .= "\n".$CFG->additionalhtmlbottomofbody;
1124 // Give subsystems an opportunity to inject extra html content. The callback
1125 // must always return a string containing valid html.
1126 foreach (\core_component::get_core_subsystems() as $name => $path) {
1127 if ($path) {
1128 $output .= component_callback($name, 'standard_after_main_region_html', [], '');
1132 // Give plugins an opportunity to inject extra html content. The callback
1133 // must always return a string containing valid html.
1134 $pluginswithfunction = get_plugins_with_function('standard_after_main_region_html', 'lib.php');
1135 foreach ($pluginswithfunction as $plugins) {
1136 foreach ($plugins as $function) {
1137 $output .= $function();
1141 return $output;
1145 * Return the standard string that says whether you are logged in (and switched
1146 * roles/logged in as another user).
1147 * @param bool $withlinks if false, then don't include any links in the HTML produced.
1148 * If not set, the default is the nologinlinks option from the theme config.php file,
1149 * and if that is not set, then links are included.
1150 * @return string HTML fragment.
1152 public function login_info($withlinks = null) {
1153 global $USER, $CFG, $DB, $SESSION;
1155 if (during_initial_install()) {
1156 return '';
1159 if (is_null($withlinks)) {
1160 $withlinks = empty($this->page->layout_options['nologinlinks']);
1163 $course = $this->page->course;
1164 if (\core\session\manager::is_loggedinas()) {
1165 $realuser = \core\session\manager::get_realuser();
1166 $fullname = fullname($realuser);
1167 if ($withlinks) {
1168 $loginastitle = get_string('loginas');
1169 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
1170 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
1171 } else {
1172 $realuserinfo = " [$fullname] ";
1174 } else {
1175 $realuserinfo = '';
1178 $loginpage = $this->is_login_page();
1179 $loginurl = get_login_url();
1181 if (empty($course->id)) {
1182 // $course->id is not defined during installation
1183 return '';
1184 } else if (isloggedin()) {
1185 $context = context_course::instance($course->id);
1187 $fullname = fullname($USER);
1188 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
1189 if ($withlinks) {
1190 $linktitle = get_string('viewprofile');
1191 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
1192 } else {
1193 $username = $fullname;
1195 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
1196 if ($withlinks) {
1197 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1198 } else {
1199 $username .= " from {$idprovider->name}";
1202 if (isguestuser()) {
1203 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1204 if (!$loginpage && $withlinks) {
1205 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1207 } else if (is_role_switched($course->id)) { // Has switched roles
1208 $rolename = '';
1209 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1210 $rolename = ': '.role_get_name($role, $context);
1212 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1213 if ($withlinks) {
1214 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1215 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1217 } else {
1218 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1219 if ($withlinks) {
1220 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1223 } else {
1224 $loggedinas = get_string('loggedinnot', 'moodle');
1225 if (!$loginpage && $withlinks) {
1226 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1230 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1232 if (isset($SESSION->justloggedin)) {
1233 unset($SESSION->justloggedin);
1234 if (!isguestuser()) {
1235 // Include this file only when required.
1236 require_once($CFG->dirroot . '/user/lib.php');
1237 if (($count = user_count_login_failures($USER)) && !empty($CFG->displayloginfailures)) {
1238 $loggedinas .= '<div class="loginfailures">';
1239 $a = new stdClass();
1240 $a->attempts = $count;
1241 $loggedinas .= get_string('failedloginattempts', '', $a);
1242 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1243 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1244 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1246 $loggedinas .= '</div>';
1251 return $loggedinas;
1255 * Check whether the current page is a login page.
1257 * @since Moodle 2.9
1258 * @return bool
1260 protected function is_login_page() {
1261 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1262 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1263 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1264 return in_array(
1265 $this->page->url->out_as_local_url(false, array()),
1266 array(
1267 '/login/index.php',
1268 '/login/forgot_password.php',
1274 * Return the 'back' link that normally appears in the footer.
1276 * @return string HTML fragment.
1278 public function home_link() {
1279 global $CFG, $SITE;
1281 if ($this->page->pagetype == 'site-index') {
1282 // Special case for site home page - please do not remove
1283 return '<div class="sitelink">' .
1284 '<a title="Moodle" class="d-inline-block aalink" href="http://moodle.org/">' .
1285 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1287 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1288 // Special case for during install/upgrade.
1289 return '<div class="sitelink">'.
1290 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1291 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1293 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1294 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1295 get_string('home') . '</a></div>';
1297 } else {
1298 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1299 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1304 * Redirects the user by any means possible given the current state
1306 * This function should not be called directly, it should always be called using
1307 * the redirect function in lib/weblib.php
1309 * The redirect function should really only be called before page output has started
1310 * however it will allow itself to be called during the state STATE_IN_BODY
1312 * @param string $encodedurl The URL to send to encoded if required
1313 * @param string $message The message to display to the user if any
1314 * @param int $delay The delay before redirecting a user, if $message has been
1315 * set this is a requirement and defaults to 3, set to 0 no delay
1316 * @param boolean $debugdisableredirect this redirect has been disabled for
1317 * debugging purposes. Display a message that explains, and don't
1318 * trigger the redirect.
1319 * @param string $messagetype The type of notification to show the message in.
1320 * See constants on \core\output\notification.
1321 * @return string The HTML to display to the user before dying, may contain
1322 * meta refresh, javascript refresh, and may have set header redirects
1324 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1325 $messagetype = \core\output\notification::NOTIFY_INFO) {
1326 global $CFG;
1327 $url = str_replace('&amp;', '&', $encodedurl);
1329 switch ($this->page->state) {
1330 case moodle_page::STATE_BEFORE_HEADER :
1331 // No output yet it is safe to delivery the full arsenal of redirect methods
1332 if (!$debugdisableredirect) {
1333 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1334 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1335 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1337 $output = $this->header();
1338 break;
1339 case moodle_page::STATE_PRINTING_HEADER :
1340 // We should hopefully never get here
1341 throw new coding_exception('You cannot redirect while printing the page header');
1342 break;
1343 case moodle_page::STATE_IN_BODY :
1344 // We really shouldn't be here but we can deal with this
1345 debugging("You should really redirect before you start page output");
1346 if (!$debugdisableredirect) {
1347 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1349 $output = $this->opencontainers->pop_all_but_last();
1350 break;
1351 case moodle_page::STATE_DONE :
1352 // Too late to be calling redirect now
1353 throw new coding_exception('You cannot redirect after the entire page has been generated');
1354 break;
1356 $output .= $this->notification($message, $messagetype);
1357 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1358 if ($debugdisableredirect) {
1359 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1361 $output .= $this->footer();
1362 return $output;
1366 * Start output by sending the HTTP headers, and printing the HTML <head>
1367 * and the start of the <body>.
1369 * To control what is printed, you should set properties on $PAGE.
1371 * @return string HTML that you must output this, preferably immediately.
1373 public function header() {
1374 global $USER, $CFG, $SESSION;
1376 // Give plugins an opportunity touch things before the http headers are sent
1377 // such as adding additional headers. The return value is ignored.
1378 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1379 foreach ($pluginswithfunction as $plugins) {
1380 foreach ($plugins as $function) {
1381 $function();
1385 if (\core\session\manager::is_loggedinas()) {
1386 $this->page->add_body_class('userloggedinas');
1389 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1390 require_once($CFG->dirroot . '/user/lib.php');
1391 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1392 if ($count = user_count_login_failures($USER, false)) {
1393 $this->page->add_body_class('loginfailures');
1397 // If the user is logged in, and we're not in initial install,
1398 // check to see if the user is role-switched and add the appropriate
1399 // CSS class to the body element.
1400 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1401 $this->page->add_body_class('userswitchedrole');
1404 // Give themes a chance to init/alter the page object.
1405 $this->page->theme->init_page($this->page);
1407 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1409 // Find the appropriate page layout file, based on $this->page->pagelayout.
1410 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1411 // Render the layout using the layout file.
1412 $rendered = $this->render_page_layout($layoutfile);
1414 // Slice the rendered output into header and footer.
1415 $cutpos = strpos($rendered, $this->unique_main_content_token);
1416 if ($cutpos === false) {
1417 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1418 $token = self::MAIN_CONTENT_TOKEN;
1419 } else {
1420 $token = $this->unique_main_content_token;
1423 if ($cutpos === false) {
1424 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.');
1426 $header = substr($rendered, 0, $cutpos);
1427 $footer = substr($rendered, $cutpos + strlen($token));
1429 if (empty($this->contenttype)) {
1430 debugging('The page layout file did not call $OUTPUT->doctype()');
1431 $header = $this->doctype() . $header;
1434 // If this theme version is below 2.4 release and this is a course view page
1435 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1436 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1437 // check if course content header/footer have not been output during render of theme layout
1438 $coursecontentheader = $this->course_content_header(true);
1439 $coursecontentfooter = $this->course_content_footer(true);
1440 if (!empty($coursecontentheader)) {
1441 // display debug message and add header and footer right above and below main content
1442 // Please note that course header and footer (to be displayed above and below the whole page)
1443 // are not displayed in this case at all.
1444 // Besides the content header and footer are not displayed on any other course page
1445 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);
1446 $header .= $coursecontentheader;
1447 $footer = $coursecontentfooter. $footer;
1451 send_headers($this->contenttype, $this->page->cacheable);
1453 $this->opencontainers->push('header/footer', $footer);
1454 $this->page->set_state(moodle_page::STATE_IN_BODY);
1456 // If an activity record has been set, activity_header will handle this.
1457 if (!$this->page->cm || !empty($this->page->layout_options['noactivityheader'])) {
1458 $header .= $this->skip_link_target('maincontent');
1460 return $header;
1464 * Renders and outputs the page layout file.
1466 * This is done by preparing the normal globals available to a script, and
1467 * then including the layout file provided by the current theme for the
1468 * requested layout.
1470 * @param string $layoutfile The name of the layout file
1471 * @return string HTML code
1473 protected function render_page_layout($layoutfile) {
1474 global $CFG, $SITE, $USER;
1475 // The next lines are a bit tricky. The point is, here we are in a method
1476 // of a renderer class, and this object may, or may not, be the same as
1477 // the global $OUTPUT object. When rendering the page layout file, we want to use
1478 // this object. However, people writing Moodle code expect the current
1479 // renderer to be called $OUTPUT, not $this, so define a variable called
1480 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1481 $OUTPUT = $this;
1482 $PAGE = $this->page;
1483 $COURSE = $this->page->course;
1485 ob_start();
1486 include($layoutfile);
1487 $rendered = ob_get_contents();
1488 ob_end_clean();
1489 return $rendered;
1493 * Outputs the page's footer
1495 * @return string HTML fragment
1497 public function footer() {
1498 global $CFG, $DB, $PERF;
1500 $output = '';
1502 // Give plugins an opportunity to touch the page before JS is finalized.
1503 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1504 foreach ($pluginswithfunction as $plugins) {
1505 foreach ($plugins as $function) {
1506 $extrafooter = $function();
1507 if (is_string($extrafooter)) {
1508 $output .= $extrafooter;
1513 $output .= $this->container_end_all(true);
1515 $footer = $this->opencontainers->pop('header/footer');
1517 if (debugging() and $DB and $DB->is_transaction_started()) {
1518 // TODO: MDL-20625 print warning - transaction will be rolled back
1521 // Provide some performance info if required
1522 $performanceinfo = '';
1523 if (MDL_PERF || (!empty($CFG->perfdebug) && $CFG->perfdebug > 7)) {
1524 if (MDL_PERFTOFOOT || debugging() || (!empty($CFG->perfdebug) && $CFG->perfdebug > 7)) {
1525 if (NO_OUTPUT_BUFFERING) {
1526 // If the output buffer was off then we render a placeholder and stream the
1527 // performance debugging into it at the very end in the shutdown handler.
1528 $PERF->perfdebugdeferred = true;
1529 $performanceinfo .= html_writer::tag('div',
1530 get_string('perfdebugdeferred', 'admin'),
1532 'id' => 'perfdebugfooter',
1533 'style' => 'min-height: 30em',
1535 } else {
1536 $perf = get_performance_info();
1537 $performanceinfo = $perf['html'];
1542 // We always want performance data when running a performance test, even if the user is redirected to another page.
1543 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1544 $footer = $this->unique_performance_info_token . $footer;
1546 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1548 // Only show notifications when the current page has a context id.
1549 if (!empty($this->page->context->id)) {
1550 $this->page->requires->js_call_amd('core/notification', 'init', array(
1551 $this->page->context->id,
1552 \core\notification::fetch_as_array($this)
1555 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1557 $this->page->set_state(moodle_page::STATE_DONE);
1559 // Here we remove the closing body and html tags and store them to be added back
1560 // in the shutdown handler so we can have valid html with streaming script tags
1561 // which are rendered after the visible footer.
1562 $tags = '';
1563 preg_match('#\<\/body>#i', $footer, $matches);
1564 $tags .= $matches[0];
1565 $footer = str_replace($matches[0], '', $footer);
1567 preg_match('#\<\/html>#i', $footer, $matches);
1568 $tags .= $matches[0];
1569 $footer = str_replace($matches[0], '', $footer);
1571 $CFG->closingtags = $tags;
1573 return $output . $footer;
1577 * Close all but the last open container. This is useful in places like error
1578 * handling, where you want to close all the open containers (apart from <body>)
1579 * before outputting the error message.
1581 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1582 * developer debug warning if it isn't.
1583 * @return string the HTML required to close any open containers inside <body>.
1585 public function container_end_all($shouldbenone = false) {
1586 return $this->opencontainers->pop_all_but_last($shouldbenone);
1590 * Returns course-specific information to be output immediately above content on any course page
1591 * (for the current course)
1593 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1594 * @return string
1596 public function course_content_header($onlyifnotcalledbefore = false) {
1597 global $CFG;
1598 static $functioncalled = false;
1599 if ($functioncalled && $onlyifnotcalledbefore) {
1600 // we have already output the content header
1601 return '';
1604 // Output any session notification.
1605 $notifications = \core\notification::fetch();
1607 $bodynotifications = '';
1608 foreach ($notifications as $notification) {
1609 $bodynotifications .= $this->render_from_template(
1610 $notification->get_template_name(),
1611 $notification->export_for_template($this)
1615 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1617 if ($this->page->course->id == SITEID) {
1618 // return immediately and do not include /course/lib.php if not necessary
1619 return $output;
1622 require_once($CFG->dirroot.'/course/lib.php');
1623 $functioncalled = true;
1624 $courseformat = course_get_format($this->page->course);
1625 if (($obj = $courseformat->course_content_header()) !== null) {
1626 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1628 return $output;
1632 * Returns course-specific information to be output immediately below content on any course page
1633 * (for the current course)
1635 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1636 * @return string
1638 public function course_content_footer($onlyifnotcalledbefore = false) {
1639 global $CFG;
1640 if ($this->page->course->id == SITEID) {
1641 // return immediately and do not include /course/lib.php if not necessary
1642 return '';
1644 static $functioncalled = false;
1645 if ($functioncalled && $onlyifnotcalledbefore) {
1646 // we have already output the content footer
1647 return '';
1649 $functioncalled = true;
1650 require_once($CFG->dirroot.'/course/lib.php');
1651 $courseformat = course_get_format($this->page->course);
1652 if (($obj = $courseformat->course_content_footer()) !== null) {
1653 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1655 return '';
1659 * Returns course-specific information to be output on any course page in the header area
1660 * (for the current course)
1662 * @return string
1664 public function course_header() {
1665 global $CFG;
1666 if ($this->page->course->id == SITEID) {
1667 // return immediately and do not include /course/lib.php if not necessary
1668 return '';
1670 require_once($CFG->dirroot.'/course/lib.php');
1671 $courseformat = course_get_format($this->page->course);
1672 if (($obj = $courseformat->course_header()) !== null) {
1673 return $courseformat->get_renderer($this->page)->render($obj);
1675 return '';
1679 * Returns course-specific information to be output on any course page in the footer area
1680 * (for the current course)
1682 * @return string
1684 public function course_footer() {
1685 global $CFG;
1686 if ($this->page->course->id == SITEID) {
1687 // return immediately and do not include /course/lib.php if not necessary
1688 return '';
1690 require_once($CFG->dirroot.'/course/lib.php');
1691 $courseformat = course_get_format($this->page->course);
1692 if (($obj = $courseformat->course_footer()) !== null) {
1693 return $courseformat->get_renderer($this->page)->render($obj);
1695 return '';
1699 * Get the course pattern datauri to show on a course card.
1701 * The datauri is an encoded svg that can be passed as a url.
1702 * @param int $id Id to use when generating the pattern
1703 * @return string datauri
1705 public function get_generated_image_for_id($id) {
1706 $color = $this->get_generated_color_for_id($id);
1707 $pattern = new \core_geopattern();
1708 $pattern->setColor($color);
1709 $pattern->patternbyid($id);
1710 return $pattern->datauri();
1714 * Get the course pattern image URL.
1716 * @param context_course $context course context object
1717 * @return string URL of the course pattern image in SVG format
1719 public function get_generated_url_for_course(context_course $context): string {
1720 return moodle_url::make_pluginfile_url($context->id, 'course', 'generated', null, '/', 'course.svg')->out();
1724 * Get the course pattern in SVG format to show on a course card.
1726 * @param int $id id to use when generating the pattern
1727 * @return string SVG file contents
1729 public function get_generated_svg_for_id(int $id): string {
1730 $color = $this->get_generated_color_for_id($id);
1731 $pattern = new \core_geopattern();
1732 $pattern->setColor($color);
1733 $pattern->patternbyid($id);
1734 return $pattern->toSVG();
1738 * Get the course color to show on a course card.
1740 * @param int $id Id to use when generating the color.
1741 * @return string hex color code.
1743 public function get_generated_color_for_id($id) {
1744 $colornumbers = range(1, 10);
1745 $basecolors = [];
1746 foreach ($colornumbers as $number) {
1747 $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1750 $color = $basecolors[$id % 10];
1751 return $color;
1755 * Returns lang menu or '', this method also checks forcing of languages in courses.
1757 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1759 * @return string The lang menu HTML or empty string
1761 public function lang_menu() {
1762 $languagemenu = new \core\output\language_menu($this->page);
1763 $data = $languagemenu->export_for_single_select($this);
1764 if ($data) {
1765 return $this->render_from_template('core/single_select', $data);
1767 return '';
1771 * Output the row of editing icons for a block, as defined by the controls array.
1773 * @param array $controls an array like {@link block_contents::$controls}.
1774 * @param string $blockid The ID given to the block.
1775 * @return string HTML fragment.
1777 public function block_controls($actions, $blockid = null) {
1778 if (empty($actions)) {
1779 return '';
1781 $menu = new action_menu($actions);
1782 if ($blockid !== null) {
1783 $menu->set_owner_selector('#'.$blockid);
1785 $menu->attributes['class'] .= ' block-control-actions commands';
1786 return $this->render($menu);
1790 * Returns the HTML for a basic textarea field.
1792 * @param string $name Name to use for the textarea element
1793 * @param string $id The id to use fort he textarea element
1794 * @param string $value Initial content to display in the textarea
1795 * @param int $rows Number of rows to display
1796 * @param int $cols Number of columns to display
1797 * @return string the HTML to display
1799 public function print_textarea($name, $id, $value, $rows, $cols) {
1800 editors_head_setup();
1801 $editor = editors_get_preferred_editor(FORMAT_HTML);
1802 $editor->set_text($value);
1803 $editor->use_editor($id, []);
1805 $context = [
1806 'id' => $id,
1807 'name' => $name,
1808 'value' => $value,
1809 'rows' => $rows,
1810 'cols' => $cols
1813 return $this->render_from_template('core_form/editor_textarea', $context);
1817 * Renders an action menu component.
1819 * @param action_menu $menu
1820 * @return string HTML
1822 public function render_action_menu(action_menu $menu) {
1824 // We don't want the class icon there!
1825 foreach ($menu->get_secondary_actions() as $action) {
1826 if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1827 $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1831 if ($menu->is_empty()) {
1832 return '';
1834 $context = $menu->export_for_template($this);
1836 return $this->render_from_template('core/action_menu', $context);
1840 * Renders a full check API result including summary and details
1842 * @param core\check\check $check the check that was run to get details from
1843 * @param core\check\result $result the result of a check
1844 * @param bool $includedetails if true, details are included as well
1845 * @return string rendered html
1847 protected function render_check_full_result(core\check\check $check, core\check\result $result, bool $includedetails): string {
1848 // Initially render just badge itself.
1849 $renderedresult = $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1851 // Add summary.
1852 $renderedresult .= ' ' . $result->get_summary();
1854 // Wrap in notificaiton.
1855 $notificationmap = [
1856 \core\check\result::NA => \core\output\notification::NOTIFY_INFO,
1857 \core\check\result::OK => \core\output\notification::NOTIFY_SUCCESS,
1858 \core\check\result::INFO => \core\output\notification::NOTIFY_INFO,
1859 \core\check\result::UNKNOWN => \core\output\notification::NOTIFY_WARNING,
1860 \core\check\result::WARNING => \core\output\notification::NOTIFY_WARNING,
1861 \core\check\result::ERROR => \core\output\notification::NOTIFY_ERROR,
1862 \core\check\result::CRITICAL => \core\output\notification::NOTIFY_ERROR,
1865 // Get type, or default to error.
1866 $notificationtype = $notificationmap[$result->get_status()] ?? \core\output\notification::NOTIFY_ERROR;
1867 $renderedresult = $this->notification($renderedresult, $notificationtype, false);
1869 // If adding details, add on new line.
1870 if ($includedetails) {
1871 $renderedresult .= $result->get_details();
1874 // Add the action link.
1875 $renderedresult .= $this->render_action_link($check->get_action_link());
1877 return $renderedresult;
1881 * Renders a full check API result including summary and details
1883 * @param core\check\check $check the check that was run to get details from
1884 * @param core\check\result $result the result of a check
1885 * @param bool $includedetails if details should be included
1886 * @return string HTML fragment
1888 public function check_full_result(core\check\check $check, core\check\result $result, bool $includedetails = false) {
1889 return $this->render_check_full_result($check, $result, $includedetails);
1893 * Renders a Check API result
1895 * @param core\check\result $result
1896 * @return string HTML fragment
1898 protected function render_check_result(core\check\result $result) {
1899 return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1903 * Renders a Check API result
1905 * @param core\check\result $result
1906 * @return string HTML fragment
1908 public function check_result(core\check\result $result) {
1909 return $this->render_check_result($result);
1913 * Renders an action_menu_link item.
1915 * @param action_menu_link $action
1916 * @return string HTML fragment
1918 protected function render_action_menu_link(action_menu_link $action) {
1919 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1923 * Renders a primary action_menu_filler item.
1925 * @param action_menu_link_filler $action
1926 * @return string HTML fragment
1928 protected function render_action_menu_filler(action_menu_filler $action) {
1929 return html_writer::span('&nbsp;', 'filler');
1933 * Renders a primary action_menu_link item.
1935 * @param action_menu_link_primary $action
1936 * @return string HTML fragment
1938 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1939 return $this->render_action_menu_link($action);
1943 * Renders a secondary action_menu_link item.
1945 * @param action_menu_link_secondary $action
1946 * @return string HTML fragment
1948 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1949 return $this->render_action_menu_link($action);
1953 * Prints a nice side block with an optional header.
1955 * @param block_contents $bc HTML for the content
1956 * @param string $region the region the block is appearing in.
1957 * @return string the HTML to be output.
1959 public function block(block_contents $bc, $region) {
1960 $bc = clone($bc); // Avoid messing up the object passed in.
1961 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1962 $bc->collapsible = block_contents::NOT_HIDEABLE;
1965 $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1966 $context = new stdClass();
1967 $context->skipid = $bc->skipid;
1968 $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
1969 $context->dockable = $bc->dockable;
1970 $context->id = $id;
1971 $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1972 $context->skiptitle = strip_tags($bc->title);
1973 $context->showskiplink = !empty($context->skiptitle);
1974 $context->arialabel = $bc->arialabel;
1975 $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
1976 $context->class = $bc->attributes['class'];
1977 $context->type = $bc->attributes['data-block'];
1978 $context->title = $bc->title;
1979 $context->content = $bc->content;
1980 $context->annotation = $bc->annotation;
1981 $context->footer = $bc->footer;
1982 $context->hascontrols = !empty($bc->controls);
1983 if ($context->hascontrols) {
1984 $context->controls = $this->block_controls($bc->controls, $id);
1987 return $this->render_from_template('core/block', $context);
1991 * Render the contents of a block_list.
1993 * @param array $icons the icon for each item.
1994 * @param array $items the content of each item.
1995 * @return string HTML
1997 public function list_block_contents($icons, $items) {
1998 $row = 0;
1999 $lis = array();
2000 foreach ($items as $key => $string) {
2001 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
2002 if (!empty($icons[$key])) { //test if the content has an assigned icon
2003 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
2005 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
2006 $item .= html_writer::end_tag('li');
2007 $lis[] = $item;
2008 $row = 1 - $row; // Flip even/odd.
2010 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
2014 * Output all the blocks in a particular region.
2016 * @param string $region the name of a region on this page.
2017 * @param boolean $fakeblocksonly Output fake block only.
2018 * @return string the HTML to be output.
2020 public function blocks_for_region($region, $fakeblocksonly = false) {
2021 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
2022 $lastblock = null;
2023 $zones = array();
2024 foreach ($blockcontents as $bc) {
2025 if ($bc instanceof block_contents) {
2026 $zones[] = $bc->title;
2029 $output = '';
2031 foreach ($blockcontents as $bc) {
2032 if ($bc instanceof block_contents) {
2033 if ($fakeblocksonly && !$bc->is_fake()) {
2034 // Skip rendering real blocks if we only want to show fake blocks.
2035 continue;
2037 $output .= $this->block($bc, $region);
2038 $lastblock = $bc->title;
2039 } else if ($bc instanceof block_move_target) {
2040 if (!$fakeblocksonly) {
2041 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
2043 } else {
2044 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
2047 return $output;
2051 * Output a place where the block that is currently being moved can be dropped.
2053 * @param block_move_target $target with the necessary details.
2054 * @param array $zones array of areas where the block can be moved to
2055 * @param string $previous the block located before the area currently being rendered.
2056 * @param string $region the name of the region
2057 * @return string the HTML to be output.
2059 public function block_move_target($target, $zones, $previous, $region) {
2060 if ($previous == null) {
2061 if (empty($zones)) {
2062 // There are no zones, probably because there are no blocks.
2063 $regions = $this->page->theme->get_all_block_regions();
2064 $position = get_string('moveblockinregion', 'block', $regions[$region]);
2065 } else {
2066 $position = get_string('moveblockbefore', 'block', $zones[0]);
2068 } else {
2069 $position = get_string('moveblockafter', 'block', $previous);
2071 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
2075 * Renders a special html link with attached action
2077 * Theme developers: DO NOT OVERRIDE! Please override function
2078 * {@link core_renderer::render_action_link()} instead.
2080 * @param string|moodle_url $url
2081 * @param string $text HTML fragment
2082 * @param component_action $action
2083 * @param array $attributes associative array of html link attributes + disabled
2084 * @param pix_icon optional pix icon to render with the link
2085 * @return string HTML fragment
2087 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
2088 if (!($url instanceof moodle_url)) {
2089 $url = new moodle_url($url);
2091 $link = new action_link($url, $text, $action, $attributes, $icon);
2093 return $this->render($link);
2097 * Renders an action_link object.
2099 * The provided link is renderer and the HTML returned. At the same time the
2100 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
2102 * @param action_link $link
2103 * @return string HTML fragment
2105 protected function render_action_link(action_link $link) {
2106 return $this->render_from_template('core/action_link', $link->export_for_template($this));
2110 * Renders an action_icon.
2112 * This function uses the {@link core_renderer::action_link()} method for the
2113 * most part. What it does different is prepare the icon as HTML and use it
2114 * as the link text.
2116 * Theme developers: If you want to change how action links and/or icons are rendered,
2117 * consider overriding function {@link core_renderer::render_action_link()} and
2118 * {@link core_renderer::render_pix_icon()}.
2120 * @param string|moodle_url $url A string URL or moodel_url
2121 * @param pix_icon $pixicon
2122 * @param component_action $action
2123 * @param array $attributes associative array of html link attributes + disabled
2124 * @param bool $linktext show title next to image in link
2125 * @return string HTML fragment
2127 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
2128 if (!($url instanceof moodle_url)) {
2129 $url = new moodle_url($url);
2131 $attributes = (array)$attributes;
2133 if (empty($attributes['class'])) {
2134 // let ppl override the class via $options
2135 $attributes['class'] = 'action-icon';
2138 $icon = $this->render($pixicon);
2140 if ($linktext) {
2141 $text = $pixicon->attributes['alt'];
2142 } else {
2143 $text = '';
2146 return $this->action_link($url, $text.$icon, $action, $attributes);
2150 * Print a message along with button choices for Continue/Cancel
2152 * If a string or moodle_url is given instead of a single_button, method defaults to post.
2154 * @param string $message The question to ask the user
2155 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
2156 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
2157 * @param array $displayoptions optional extra display options
2158 * @return string HTML fragment
2160 public function confirm($message, $continue, $cancel, array $displayoptions = []) {
2162 // Check existing displayoptions.
2163 $displayoptions['confirmtitle'] = $displayoptions['confirmtitle'] ?? get_string('confirm');
2164 $displayoptions['continuestr'] = $displayoptions['continuestr'] ?? get_string('continue');
2165 $displayoptions['cancelstr'] = $displayoptions['cancelstr'] ?? get_string('cancel');
2167 if ($continue instanceof single_button) {
2168 // Continue button should be primary if set to secondary type as it is the fefault.
2169 if ($continue->type === single_button::BUTTON_SECONDARY) {
2170 $continue->type = single_button::BUTTON_PRIMARY;
2172 } else if (is_string($continue)) {
2173 $continue = new single_button(new moodle_url($continue), $displayoptions['continuestr'], 'post',
2174 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
2175 } else if ($continue instanceof moodle_url) {
2176 $continue = new single_button($continue, $displayoptions['continuestr'], 'post',
2177 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
2178 } else {
2179 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2182 if ($cancel instanceof single_button) {
2183 // ok
2184 } else if (is_string($cancel)) {
2185 $cancel = new single_button(new moodle_url($cancel), $displayoptions['cancelstr'], 'get');
2186 } else if ($cancel instanceof moodle_url) {
2187 $cancel = new single_button($cancel, $displayoptions['cancelstr'], 'get');
2188 } else {
2189 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2192 $attributes = [
2193 'role'=>'alertdialog',
2194 'aria-labelledby'=>'modal-header',
2195 'aria-describedby'=>'modal-body',
2196 'aria-modal'=>'true'
2199 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
2200 $output .= $this->box_start('modal-content', 'modal-content');
2201 $output .= $this->box_start('modal-header px-3', 'modal-header');
2202 $output .= html_writer::tag('h4', $displayoptions['confirmtitle']);
2203 $output .= $this->box_end();
2204 $attributes = [
2205 'role'=>'alert',
2206 'data-aria-autofocus'=>'true'
2208 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
2209 $output .= html_writer::tag('p', $message);
2210 $output .= $this->box_end();
2211 $output .= $this->box_start('modal-footer', 'modal-footer');
2212 $output .= html_writer::tag('div', $this->render($cancel) . $this->render($continue), ['class' => 'buttons']);
2213 $output .= $this->box_end();
2214 $output .= $this->box_end();
2215 $output .= $this->box_end();
2216 return $output;
2220 * Returns a form with a single button.
2222 * Theme developers: DO NOT OVERRIDE! Please override function
2223 * {@link core_renderer::render_single_button()} instead.
2225 * @param string|moodle_url $url
2226 * @param string $label button text
2227 * @param string $method get or post submit method
2228 * @param array $options associative array {disabled, title, etc.}
2229 * @return string HTML fragment
2231 public function single_button($url, $label, $method='post', array $options=null) {
2232 if (!($url instanceof moodle_url)) {
2233 $url = new moodle_url($url);
2235 $button = new single_button($url, $label, $method);
2237 foreach ((array)$options as $key=>$value) {
2238 if (property_exists($button, $key)) {
2239 $button->$key = $value;
2240 } else {
2241 $button->set_attribute($key, $value);
2245 return $this->render($button);
2249 * Renders a single button widget.
2251 * This will return HTML to display a form containing a single button.
2253 * @param single_button $button
2254 * @return string HTML fragment
2256 protected function render_single_button(single_button $button) {
2257 return $this->render_from_template('core/single_button', $button->export_for_template($this));
2261 * Returns a form with a single select widget.
2263 * Theme developers: DO NOT OVERRIDE! Please override function
2264 * {@link core_renderer::render_single_select()} instead.
2266 * @param moodle_url $url form action target, includes hidden fields
2267 * @param string $name name of selection field - the changing parameter in url
2268 * @param array $options list of options
2269 * @param string $selected selected element
2270 * @param array $nothing
2271 * @param string $formid
2272 * @param array $attributes other attributes for the single select
2273 * @return string HTML fragment
2275 public function single_select($url, $name, array $options, $selected = '',
2276 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2277 if (!($url instanceof moodle_url)) {
2278 $url = new moodle_url($url);
2280 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2282 if (array_key_exists('label', $attributes)) {
2283 $select->set_label($attributes['label']);
2284 unset($attributes['label']);
2286 $select->attributes = $attributes;
2288 return $this->render($select);
2292 * Returns a dataformat selection and download form
2294 * @param string $label A text label
2295 * @param moodle_url|string $base The download page url
2296 * @param string $name The query param which will hold the type of the download
2297 * @param array $params Extra params sent to the download page
2298 * @return string HTML fragment
2300 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2302 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2303 $options = array();
2304 foreach ($formats as $format) {
2305 if ($format->is_enabled()) {
2306 $options[] = array(
2307 'value' => $format->name,
2308 'label' => get_string('dataformat', $format->component),
2312 $hiddenparams = array();
2313 foreach ($params as $key => $value) {
2314 $hiddenparams[] = array(
2315 'name' => $key,
2316 'value' => $value,
2319 $data = array(
2320 'label' => $label,
2321 'base' => $base,
2322 'name' => $name,
2323 'params' => $hiddenparams,
2324 'options' => $options,
2325 'sesskey' => sesskey(),
2326 'submit' => get_string('download'),
2329 return $this->render_from_template('core/dataformat_selector', $data);
2334 * Internal implementation of single_select rendering
2336 * @param single_select $select
2337 * @return string HTML fragment
2339 protected function render_single_select(single_select $select) {
2340 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2344 * Returns a form with a url select widget.
2346 * Theme developers: DO NOT OVERRIDE! Please override function
2347 * {@link core_renderer::render_url_select()} instead.
2349 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2350 * @param string $selected selected element
2351 * @param array $nothing
2352 * @param string $formid
2353 * @return string HTML fragment
2355 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2356 $select = new url_select($urls, $selected, $nothing, $formid);
2357 return $this->render($select);
2361 * Internal implementation of url_select rendering
2363 * @param url_select $select
2364 * @return string HTML fragment
2366 protected function render_url_select(url_select $select) {
2367 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2371 * Returns a string containing a link to the user documentation.
2372 * Also contains an icon by default. Shown to teachers and admin only.
2374 * @param string $path The page link after doc root and language, no leading slash.
2375 * @param string $text The text to be displayed for the link
2376 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2377 * @param array $attributes htm attributes
2378 * @return string
2380 public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
2381 global $CFG;
2383 $icon = $this->pix_icon('book', '', 'moodle', array('class' => 'iconhelp icon-pre', 'role' => 'presentation'));
2385 $attributes['href'] = new moodle_url(get_docs_url($path));
2386 $newwindowicon = '';
2387 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2388 $attributes['target'] = '_blank';
2389 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle',
2390 ['class' => 'fa fa-externallink fa-fw']);
2393 return html_writer::tag('a', $icon . $text . $newwindowicon, $attributes);
2397 * Return HTML for an image_icon.
2399 * Theme developers: DO NOT OVERRIDE! Please override function
2400 * {@link core_renderer::render_image_icon()} instead.
2402 * @param string $pix short pix name
2403 * @param string $alt mandatory alt attribute
2404 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2405 * @param array $attributes htm attributes
2406 * @return string HTML fragment
2408 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2409 $icon = new image_icon($pix, $alt, $component, $attributes);
2410 return $this->render($icon);
2414 * Renders a pix_icon widget and returns the HTML to display it.
2416 * @param image_icon $icon
2417 * @return string HTML fragment
2419 protected function render_image_icon(image_icon $icon) {
2420 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2421 return $system->render_pix_icon($this, $icon);
2425 * Return HTML for a pix_icon.
2427 * Theme developers: DO NOT OVERRIDE! Please override function
2428 * {@link core_renderer::render_pix_icon()} instead.
2430 * @param string $pix short pix name
2431 * @param string $alt mandatory alt attribute
2432 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2433 * @param array $attributes htm lattributes
2434 * @return string HTML fragment
2436 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2437 $icon = new pix_icon($pix, $alt, $component, $attributes);
2438 return $this->render($icon);
2442 * Renders a pix_icon widget and returns the HTML to display it.
2444 * @param pix_icon $icon
2445 * @return string HTML fragment
2447 protected function render_pix_icon(pix_icon $icon) {
2448 $system = \core\output\icon_system::instance();
2449 return $system->render_pix_icon($this, $icon);
2453 * Return HTML to display an emoticon icon.
2455 * @param pix_emoticon $emoticon
2456 * @return string HTML fragment
2458 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2459 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2460 return $system->render_pix_icon($this, $emoticon);
2464 * Produces the html that represents this rating in the UI
2466 * @param rating $rating the page object on which this rating will appear
2467 * @return string
2469 function render_rating(rating $rating) {
2470 global $CFG, $USER;
2472 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2473 return null;//ratings are turned off
2476 $ratingmanager = new rating_manager();
2477 // Initialise the JavaScript so ratings can be done by AJAX.
2478 $ratingmanager->initialise_rating_javascript($this->page);
2480 $strrate = get_string("rate", "rating");
2481 $ratinghtml = ''; //the string we'll return
2483 // permissions check - can they view the aggregate?
2484 if ($rating->user_can_view_aggregate()) {
2486 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2487 $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2488 $aggregatestr = $rating->get_aggregate_string();
2490 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2491 if ($rating->count > 0) {
2492 $countstr = "({$rating->count})";
2493 } else {
2494 $countstr = '-';
2496 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2498 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2500 $nonpopuplink = $rating->get_view_ratings_url();
2501 $popuplink = $rating->get_view_ratings_url(true);
2503 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2504 $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
2507 $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
2510 $formstart = null;
2511 // if the item doesn't belong to the current user, the user has permission to rate
2512 // and we're within the assessable period
2513 if ($rating->user_can_rate()) {
2515 $rateurl = $rating->get_rate_url();
2516 $inputs = $rateurl->params();
2518 //start the rating form
2519 $formattrs = array(
2520 'id' => "postrating{$rating->itemid}",
2521 'class' => 'postratingform',
2522 'method' => 'post',
2523 'action' => $rateurl->out_omit_querystring()
2525 $formstart = html_writer::start_tag('form', $formattrs);
2526 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2528 // add the hidden inputs
2529 foreach ($inputs as $name => $value) {
2530 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2531 $formstart .= html_writer::empty_tag('input', $attributes);
2534 if (empty($ratinghtml)) {
2535 $ratinghtml .= $strrate.': ';
2537 $ratinghtml = $formstart.$ratinghtml;
2539 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2540 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2541 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2542 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2544 //output submit button
2545 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2547 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2548 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2550 if (!$rating->settings->scale->isnumeric) {
2551 // If a global scale, try to find current course ID from the context
2552 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2553 $courseid = $coursecontext->instanceid;
2554 } else {
2555 $courseid = $rating->settings->scale->courseid;
2557 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2559 $ratinghtml .= html_writer::end_tag('span');
2560 $ratinghtml .= html_writer::end_tag('div');
2561 $ratinghtml .= html_writer::end_tag('form');
2564 return $ratinghtml;
2568 * Centered heading with attached help button (same title text)
2569 * and optional icon attached.
2571 * @param string $text A heading text
2572 * @param string $helpidentifier The keyword that defines a help page
2573 * @param string $component component name
2574 * @param string|moodle_url $icon
2575 * @param string $iconalt icon alt text
2576 * @param int $level The level of importance of the heading. Defaulting to 2
2577 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2578 * @return string HTML fragment
2580 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2581 $image = '';
2582 if ($icon) {
2583 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2586 $help = '';
2587 if ($helpidentifier) {
2588 $help = $this->help_icon($helpidentifier, $component);
2591 return $this->heading($image.$text.$help, $level, $classnames);
2595 * Returns HTML to display a help icon.
2597 * @deprecated since Moodle 2.0
2599 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2600 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2604 * Returns HTML to display a help icon.
2606 * Theme developers: DO NOT OVERRIDE! Please override function
2607 * {@link core_renderer::render_help_icon()} instead.
2609 * @param string $identifier The keyword that defines a help page
2610 * @param string $component component name
2611 * @param string|bool $linktext true means use $title as link text, string means link text value
2612 * @param string|object|array|int $a An object, string or number that can be used
2613 * within translation strings
2614 * @return string HTML fragment
2616 public function help_icon($identifier, $component = 'moodle', $linktext = '', $a = null) {
2617 $icon = new help_icon($identifier, $component, $a);
2618 $icon->diag_strings();
2619 if ($linktext === true) {
2620 $icon->linktext = get_string($icon->identifier, $icon->component, $a);
2621 } else if (!empty($linktext)) {
2622 $icon->linktext = $linktext;
2624 return $this->render($icon);
2628 * Implementation of user image rendering.
2630 * @param help_icon $helpicon A help icon instance
2631 * @return string HTML fragment
2633 protected function render_help_icon(help_icon $helpicon) {
2634 $context = $helpicon->export_for_template($this);
2635 return $this->render_from_template('core/help_icon', $context);
2639 * Returns HTML to display a scale help icon.
2641 * @param int $courseid
2642 * @param stdClass $scale instance
2643 * @return string HTML fragment
2645 public function help_icon_scale($courseid, stdClass $scale) {
2646 global $CFG;
2648 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2650 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2652 $scaleid = abs($scale->id);
2654 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2655 $action = new popup_action('click', $link, 'ratingscale');
2657 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2661 * Creates and returns a spacer image with optional line break.
2663 * @param array $attributes Any HTML attributes to add to the spaced.
2664 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2665 * laxy do it with CSS which is a much better solution.
2666 * @return string HTML fragment
2668 public function spacer(array $attributes = null, $br = false) {
2669 $attributes = (array)$attributes;
2670 if (empty($attributes['width'])) {
2671 $attributes['width'] = 1;
2673 if (empty($attributes['height'])) {
2674 $attributes['height'] = 1;
2676 $attributes['class'] = 'spacer';
2678 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2680 if (!empty($br)) {
2681 $output .= '<br />';
2684 return $output;
2688 * Returns HTML to display the specified user's avatar.
2690 * User avatar may be obtained in two ways:
2691 * <pre>
2692 * // Option 1: (shortcut for simple cases, preferred way)
2693 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2694 * $OUTPUT->user_picture($user, array('popup'=>true));
2696 * // Option 2:
2697 * $userpic = new user_picture($user);
2698 * // Set properties of $userpic
2699 * $userpic->popup = true;
2700 * $OUTPUT->render($userpic);
2701 * </pre>
2703 * Theme developers: DO NOT OVERRIDE! Please override function
2704 * {@link core_renderer::render_user_picture()} instead.
2706 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2707 * If any of these are missing, the database is queried. Avoid this
2708 * if at all possible, particularly for reports. It is very bad for performance.
2709 * @param array $options associative array with user picture options, used only if not a user_picture object,
2710 * options are:
2711 * - courseid=$this->page->course->id (course id of user profile in link)
2712 * - size=35 (size of image)
2713 * - link=true (make image clickable - the link leads to user profile)
2714 * - popup=false (open in popup)
2715 * - alttext=true (add image alt attribute)
2716 * - class = image class attribute (default 'userpicture')
2717 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2718 * - includefullname=false (whether to include the user's full name together with the user picture)
2719 * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2720 * @return string HTML fragment
2722 public function user_picture(stdClass $user, array $options = null) {
2723 $userpicture = new user_picture($user);
2724 foreach ((array)$options as $key=>$value) {
2725 if (property_exists($userpicture, $key)) {
2726 $userpicture->$key = $value;
2729 return $this->render($userpicture);
2733 * Internal implementation of user image rendering.
2735 * @param user_picture $userpicture
2736 * @return string
2738 protected function render_user_picture(user_picture $userpicture) {
2739 global $CFG;
2741 $user = $userpicture->user;
2742 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
2744 $alt = '';
2745 if ($userpicture->alttext) {
2746 if (!empty($user->imagealt)) {
2747 $alt = trim($user->imagealt);
2751 // If the user picture is being rendered as a link but without the full name, an empty alt text for the user picture
2752 // would mean that the link displayed will not have any discernible text. This becomes an accessibility issue,
2753 // especially to screen reader users. Use the user's full name by default for the user picture's alt-text if this is
2754 // the case.
2755 if ($userpicture->link && !$userpicture->includefullname && empty($alt)) {
2756 $alt = fullname($user);
2759 if (empty($userpicture->size)) {
2760 $size = 35;
2761 } else if ($userpicture->size === true or $userpicture->size == 1) {
2762 $size = 100;
2763 } else {
2764 $size = $userpicture->size;
2767 $class = $userpicture->class;
2769 if ($user->picture == 0) {
2770 $class .= ' defaultuserpic';
2773 $src = $userpicture->get_url($this->page, $this);
2775 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2776 if (!$userpicture->visibletoscreenreaders) {
2777 $alt = '';
2779 $attributes['alt'] = $alt;
2781 if (!empty($alt)) {
2782 $attributes['title'] = $alt;
2785 // Get the image html output first, auto generated based on initials if one isn't already set.
2786 if ($user->picture == 0 && empty($CFG->enablegravatar) && !defined('BEHAT_SITE_RUNNING')) {
2787 $initials = \core_user::get_initials($user);
2788 // Don't modify in corner cases where neither the firstname nor the lastname appears.
2789 $output = html_writer::tag(
2790 'span', $initials,
2791 ['class' => 'userinitials size-' . $size]
2793 } else {
2794 $output = html_writer::empty_tag('img', $attributes);
2797 // Show fullname together with the picture when desired.
2798 if ($userpicture->includefullname) {
2799 $output .= fullname($userpicture->user, $canviewfullnames);
2802 if (empty($userpicture->courseid)) {
2803 $courseid = $this->page->course->id;
2804 } else {
2805 $courseid = $userpicture->courseid;
2807 if ($courseid == SITEID) {
2808 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2809 } else {
2810 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2813 // Then wrap it in link if needed. Also we don't wrap it in link if the link redirects to itself.
2814 if (!$userpicture->link ||
2815 ($this->page->has_set_url() && $this->page->url == $url)) { // Protect against unset page->url.
2816 return $output;
2819 $attributes = array('href' => $url, 'class' => 'd-inline-block aabtn');
2820 if (!$userpicture->visibletoscreenreaders) {
2821 $attributes['tabindex'] = '-1';
2822 $attributes['aria-hidden'] = 'true';
2825 if ($userpicture->popup) {
2826 $id = html_writer::random_id('userpicture');
2827 $attributes['id'] = $id;
2828 $this->add_action_handler(new popup_action('click', $url), $id);
2831 return html_writer::tag('a', $output, $attributes);
2835 * @deprecated since Moodle 4.3
2837 public function htmllize_file_tree() {
2838 throw new coding_exception('This function is deprecated and no longer relevant.');
2842 * Returns HTML to display the file picker
2844 * <pre>
2845 * $OUTPUT->file_picker($options);
2846 * </pre>
2848 * Theme developers: DO NOT OVERRIDE! Please override function
2849 * {@link core_renderer::render_file_picker()} instead.
2851 * @param stdClass $options file manager options
2852 * options are:
2853 * maxbytes=>-1,
2854 * itemid=>0,
2855 * client_id=>uniqid(),
2856 * acepted_types=>'*',
2857 * return_types=>FILE_INTERNAL,
2858 * context=>current page context
2859 * @return string HTML fragment
2861 public function file_picker($options) {
2862 $fp = new file_picker($options);
2863 return $this->render($fp);
2867 * Internal implementation of file picker rendering.
2869 * @param file_picker $fp
2870 * @return string
2872 public function render_file_picker(file_picker $fp) {
2873 $options = $fp->options;
2874 $client_id = $options->client_id;
2875 $strsaved = get_string('filesaved', 'repository');
2876 $straddfile = get_string('openpicker', 'repository');
2877 $strloading = get_string('loading', 'repository');
2878 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2879 $strdroptoupload = get_string('droptoupload', 'moodle');
2880 $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
2882 $currentfile = $options->currentfile;
2883 if (empty($currentfile)) {
2884 $currentfile = '';
2885 } else {
2886 $currentfile .= ' - ';
2888 if ($options->maxbytes) {
2889 $size = $options->maxbytes;
2890 } else {
2891 $size = get_max_upload_file_size();
2893 if ($size == -1) {
2894 $maxsize = '';
2895 } else {
2896 $maxsize = get_string('maxfilesize', 'moodle', display_size($size, 0));
2898 if ($options->buttonname) {
2899 $buttonname = ' name="' . $options->buttonname . '"';
2900 } else {
2901 $buttonname = '';
2903 $html = <<<EOD
2904 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2905 $iconprogress
2906 </div>
2907 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2908 <div>
2909 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2910 <span> $maxsize </span>
2911 </div>
2912 EOD;
2913 if ($options->env != 'url') {
2914 $html .= <<<EOD
2915 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2916 <div class="filepicker-filename">
2917 <div class="filepicker-container">$currentfile
2918 <div class="dndupload-message">$strdndenabled <br/>
2919 <div class="dndupload-arrow d-flex"><i class="fa fa-arrow-circle-o-down fa-3x m-auto"></i></div>
2920 </div>
2921 </div>
2922 <div class="dndupload-progressbars"></div>
2923 </div>
2924 <div>
2925 <div class="dndupload-target">{$strdroptoupload}<br/>
2926 <div class="dndupload-arrow d-flex"><i class="fa fa-arrow-circle-o-down fa-3x m-auto"></i></div>
2927 </div>
2928 </div>
2929 </div>
2930 EOD;
2932 $html .= '</div>';
2933 return $html;
2937 * @deprecated since Moodle 3.2
2939 public function update_module_button() {
2940 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2941 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2942 'Themes can choose to display the link in the buttons row consistently for all module types.');
2946 * Returns HTML to display a "Turn editing on/off" button in a form.
2948 * @param moodle_url $url The URL + params to send through when clicking the button
2949 * @param string $method
2950 * @return string HTML the button
2952 public function edit_button(moodle_url $url, string $method = 'post') {
2954 if ($this->page->theme->haseditswitch == true) {
2955 return;
2957 $url->param('sesskey', sesskey());
2958 if ($this->page->user_is_editing()) {
2959 $url->param('edit', 'off');
2960 $editstring = get_string('turneditingoff');
2961 } else {
2962 $url->param('edit', 'on');
2963 $editstring = get_string('turneditingon');
2966 return $this->single_button($url, $editstring, $method);
2970 * Create a navbar switch for toggling editing mode.
2972 * @return string Html containing the edit switch
2974 public function edit_switch() {
2975 if ($this->page->user_allowed_editing()) {
2977 $temp = (object) [
2978 'legacyseturl' => (new moodle_url('/editmode.php'))->out(false),
2979 'pagecontextid' => $this->page->context->id,
2980 'pageurl' => $this->page->url,
2981 'sesskey' => sesskey(),
2983 if ($this->page->user_is_editing()) {
2984 $temp->checked = true;
2986 return $this->render_from_template('core/editswitch', $temp);
2991 * Returns HTML to display a simple button to close a window
2993 * @param string $text The lang string for the button's label (already output from get_string())
2994 * @return string html fragment
2996 public function close_window_button($text='') {
2997 if (empty($text)) {
2998 $text = get_string('closewindow');
3000 $button = new single_button(new moodle_url('#'), $text, 'get');
3001 $button->add_action(new component_action('click', 'close_window'));
3003 return $this->container($this->render($button), 'closewindow');
3007 * Output an error message. By default wraps the error message in <span class="error">.
3008 * If the error message is blank, nothing is output.
3010 * @param string $message the error message.
3011 * @return string the HTML to output.
3013 public function error_text($message) {
3014 if (empty($message)) {
3015 return '';
3017 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
3018 return html_writer::tag('span', $message, array('class' => 'error'));
3022 * Do not call this function directly.
3024 * To terminate the current script with a fatal error, throw an exception.
3025 * Doing this will then call this function to display the error, before terminating the execution.
3027 * @param string $message The message to output
3028 * @param string $moreinfourl URL where more info can be found about the error
3029 * @param string $link Link for the Continue button
3030 * @param array $backtrace The execution backtrace
3031 * @param string $debuginfo Debugging information
3032 * @return string the HTML to output.
3034 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
3035 global $CFG;
3037 $output = '';
3038 $obbuffer = '';
3040 if ($this->has_started()) {
3041 // we can not always recover properly here, we have problems with output buffering,
3042 // html tables, etc.
3043 $output .= $this->opencontainers->pop_all_but_last();
3045 } else {
3046 // It is really bad if library code throws exception when output buffering is on,
3047 // because the buffered text would be printed before our start of page.
3048 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
3049 error_reporting(0); // disable notices from gzip compression, etc.
3050 while (ob_get_level() > 0) {
3051 $buff = ob_get_clean();
3052 if ($buff === false) {
3053 break;
3055 $obbuffer .= $buff;
3057 error_reporting($CFG->debug);
3059 // Output not yet started.
3060 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
3061 if (empty($_SERVER['HTTP_RANGE'])) {
3062 @header($protocol . ' 404 Not Found');
3063 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
3064 // Coax iOS 10 into sending the session cookie.
3065 @header($protocol . ' 403 Forbidden');
3066 } else {
3067 // Must stop byteserving attempts somehow,
3068 // this is weird but Chrome PDF viewer can be stopped only with 407!
3069 @header($protocol . ' 407 Proxy Authentication Required');
3072 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
3073 $this->page->set_url('/'); // no url
3074 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
3075 $this->page->set_title(get_string('error'));
3076 $this->page->set_heading($this->page->course->fullname);
3077 // No need to display the activity header when encountering an error.
3078 $this->page->activityheader->disable();
3079 $output .= $this->header();
3082 $message = '<p class="errormessage">' . s($message) . '</p>'.
3083 '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
3084 get_string('moreinformation') . '</a></p>';
3085 if (empty($CFG->rolesactive)) {
3086 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
3087 //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.
3089 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
3091 if ($CFG->debugdeveloper) {
3092 $labelsep = get_string('labelsep', 'langconfig');
3093 if (!empty($debuginfo)) {
3094 $debuginfo = s($debuginfo); // removes all nasty JS
3095 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
3096 $label = get_string('debuginfo', 'debug') . $labelsep;
3097 $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
3099 if (!empty($backtrace)) {
3100 $label = get_string('stacktrace', 'debug') . $labelsep;
3101 $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
3103 if ($obbuffer !== '' ) {
3104 $label = get_string('outputbuffer', 'debug') . $labelsep;
3105 $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
3109 if (empty($CFG->rolesactive)) {
3110 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
3111 } else if (!empty($link)) {
3112 $output .= $this->continue_button($link);
3115 $output .= $this->footer();
3117 // Padding to encourage IE to display our error page, rather than its own.
3118 $output .= str_repeat(' ', 512);
3120 return $output;
3124 * Output a notification (that is, a status message about something that has just happened).
3126 * Note: \core\notification::add() may be more suitable for your usage.
3128 * @param string $message The message to print out.
3129 * @param ?string $type The type of notification. See constants on \core\output\notification.
3130 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
3131 * @return string the HTML to output.
3133 public function notification($message, $type = null, $closebutton = true) {
3134 $typemappings = [
3135 // Valid types.
3136 'success' => \core\output\notification::NOTIFY_SUCCESS,
3137 'info' => \core\output\notification::NOTIFY_INFO,
3138 'warning' => \core\output\notification::NOTIFY_WARNING,
3139 'error' => \core\output\notification::NOTIFY_ERROR,
3141 // Legacy types mapped to current types.
3142 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
3143 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
3144 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
3145 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
3146 'notifymessage' => \core\output\notification::NOTIFY_INFO,
3147 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
3148 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
3151 $extraclasses = [];
3153 if ($type) {
3154 if (strpos($type, ' ') === false) {
3155 // No spaces in the list of classes, therefore no need to loop over and determine the class.
3156 if (isset($typemappings[$type])) {
3157 $type = $typemappings[$type];
3158 } else {
3159 // The value provided did not match a known type. It must be an extra class.
3160 $extraclasses = [$type];
3162 } else {
3163 // Identify what type of notification this is.
3164 $classarray = explode(' ', self::prepare_classes($type));
3166 // Separate out the type of notification from the extra classes.
3167 foreach ($classarray as $class) {
3168 if (isset($typemappings[$class])) {
3169 $type = $typemappings[$class];
3170 } else {
3171 $extraclasses[] = $class;
3177 $notification = new \core\output\notification($message, $type, $closebutton);
3178 if (count($extraclasses)) {
3179 $notification->set_extra_classes($extraclasses);
3182 // Return the rendered template.
3183 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3187 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3189 public function notify_problem() {
3190 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
3191 'please use \core\notification::add(), or \core\output\notification as required.');
3195 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3197 public function notify_success() {
3198 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
3199 'please use \core\notification::add(), or \core\output\notification as required.');
3203 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3205 public function notify_message() {
3206 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
3207 'please use \core\notification::add(), or \core\output\notification as required.');
3211 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3213 public function notify_redirect() {
3214 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
3215 'please use \core\notification::add(), or \core\output\notification as required.');
3219 * Render a notification (that is, a status message about something that has
3220 * just happened).
3222 * @param \core\output\notification $notification the notification to print out
3223 * @return string the HTML to output.
3225 protected function render_notification(\core\output\notification $notification) {
3226 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3230 * Returns HTML to display a continue button that goes to a particular URL.
3232 * @param string|moodle_url $url The url the button goes to.
3233 * @return string the HTML to output.
3235 public function continue_button($url) {
3236 if (!($url instanceof moodle_url)) {
3237 $url = new moodle_url($url);
3239 $button = new single_button($url, get_string('continue'), 'get', single_button::BUTTON_PRIMARY);
3240 $button->class = 'continuebutton';
3242 return $this->render($button);
3246 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
3248 * Theme developers: DO NOT OVERRIDE! Please override function
3249 * {@link core_renderer::render_paging_bar()} instead.
3251 * @param int $totalcount The total number of entries available to be paged through
3252 * @param int $page The page you are currently viewing
3253 * @param int $perpage The number of entries that should be shown per page
3254 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3255 * @param string $pagevar name of page parameter that holds the page number
3256 * @return string the HTML to output.
3258 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3259 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3260 return $this->render($pb);
3264 * Returns HTML to display the paging bar.
3266 * @param paging_bar $pagingbar
3267 * @return string the HTML to output.
3269 protected function render_paging_bar(paging_bar $pagingbar) {
3270 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3271 $pagingbar->maxdisplay = 10;
3272 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3276 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3278 * @param string $current the currently selected letter.
3279 * @param string $class class name to add to this initial bar.
3280 * @param string $title the name to put in front of this initial bar.
3281 * @param string $urlvar URL parameter name for this initial.
3282 * @param string $url URL object.
3283 * @param array $alpha of letters in the alphabet.
3284 * @param bool $minirender Return a trimmed down view of the initials bar.
3285 * @return string the HTML to output.
3287 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null, bool $minirender = false) {
3288 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha, $minirender);
3289 return $this->render($ib);
3293 * Internal implementation of initials bar rendering.
3295 * @param initials_bar $initialsbar
3296 * @return string
3298 protected function render_initials_bar(initials_bar $initialsbar) {
3299 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3303 * Output the place a skip link goes to.
3305 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3306 * @return string the HTML to output.
3308 public function skip_link_target($id = null) {
3309 return html_writer::span('', '', array('id' => $id));
3313 * Outputs a heading
3315 * @param string $text The text of the heading
3316 * @param int $level The level of importance of the heading. Defaulting to 2
3317 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3318 * @param string $id An optional ID
3319 * @return string the HTML to output.
3321 public function heading($text, $level = 2, $classes = null, $id = null) {
3322 $level = (integer) $level;
3323 if ($level < 1 or $level > 6) {
3324 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3326 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3330 * Outputs a box.
3332 * @param string $contents The contents of the box
3333 * @param string $classes A space-separated list of CSS classes
3334 * @param string $id An optional ID
3335 * @param array $attributes An array of other attributes to give the box.
3336 * @return string the HTML to output.
3338 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3339 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3343 * Outputs the opening section of a box.
3345 * @param string $classes A space-separated list of CSS classes
3346 * @param string $id An optional ID
3347 * @param array $attributes An array of other attributes to give the box.
3348 * @return string the HTML to output.
3350 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3351 $this->opencontainers->push('box', html_writer::end_tag('div'));
3352 $attributes['id'] = $id;
3353 $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes);
3354 return html_writer::start_tag('div', $attributes);
3358 * Outputs the closing section of a box.
3360 * @return string the HTML to output.
3362 public function box_end() {
3363 return $this->opencontainers->pop('box');
3367 * Outputs a paragraph.
3369 * @param string $contents The contents of the paragraph
3370 * @param string|null $classes A space-separated list of CSS classes
3371 * @param string|null $id An optional ID
3372 * @return string the HTML to output.
3374 public function paragraph(string $contents, ?string $classes = null, ?string $id = null): string {
3375 return html_writer::tag(
3376 'p',
3377 $contents,
3378 ['id' => $id, 'class' => renderer_base::prepare_classes($classes)]
3383 * Outputs a screen reader only inline text.
3385 * @param string $contents The contents of the paragraph
3386 * @return string the HTML to output.
3388 public function sr_text(string $contents): string {
3389 return html_writer::tag(
3390 'span',
3391 $contents,
3392 ['class' => 'sr-only']
3393 ) . ' ';
3397 * Outputs a container.
3399 * @param string $contents The contents of the box
3400 * @param string $classes A space-separated list of CSS classes
3401 * @param string $id An optional ID
3402 * @return string the HTML to output.
3404 public function container($contents, $classes = null, $id = null) {
3405 return $this->container_start($classes, $id) . $contents . $this->container_end();
3409 * Outputs the opening section of a container.
3411 * @param string $classes A space-separated list of CSS classes
3412 * @param string $id An optional ID
3413 * @return string the HTML to output.
3415 public function container_start($classes = null, $id = null) {
3416 $this->opencontainers->push('container', html_writer::end_tag('div'));
3417 return html_writer::start_tag('div', array('id' => $id,
3418 'class' => renderer_base::prepare_classes($classes)));
3422 * Outputs the closing section of a container.
3424 * @return string the HTML to output.
3426 public function container_end() {
3427 return $this->opencontainers->pop('container');
3431 * Make nested HTML lists out of the items
3433 * The resulting list will look something like this:
3435 * <pre>
3436 * <<ul>>
3437 * <<li>><div class='tree_item parent'>(item contents)</div>
3438 * <<ul>
3439 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3440 * <</ul>>
3441 * <</li>>
3442 * <</ul>>
3443 * </pre>
3445 * @param array $items
3446 * @param array $attrs html attributes passed to the top ofs the list
3447 * @return string HTML
3449 public function tree_block_contents($items, $attrs = array()) {
3450 // exit if empty, we don't want an empty ul element
3451 if (empty($items)) {
3452 return '';
3454 // array of nested li elements
3455 $lis = array();
3456 foreach ($items as $item) {
3457 // this applies to the li item which contains all child lists too
3458 $content = $item->content($this);
3459 $liclasses = array($item->get_css_type());
3460 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3461 $liclasses[] = 'collapsed';
3463 if ($item->isactive === true) {
3464 $liclasses[] = 'current_branch';
3466 $liattr = array('class'=>join(' ',$liclasses));
3467 // class attribute on the div item which only contains the item content
3468 $divclasses = array('tree_item');
3469 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3470 $divclasses[] = 'branch';
3471 } else {
3472 $divclasses[] = 'leaf';
3474 if (!empty($item->classes) && count($item->classes)>0) {
3475 $divclasses[] = join(' ', $item->classes);
3477 $divattr = array('class'=>join(' ', $divclasses));
3478 if (!empty($item->id)) {
3479 $divattr['id'] = $item->id;
3481 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3482 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3483 $content = html_writer::empty_tag('hr') . $content;
3485 $content = html_writer::tag('li', $content, $liattr);
3486 $lis[] = $content;
3488 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3492 * Returns a search box.
3494 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3495 * @return string HTML with the search form hidden by default.
3497 public function search_box($id = false) {
3498 global $CFG;
3500 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3501 // result in an extra included file for each site, even the ones where global search
3502 // is disabled.
3503 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3504 return '';
3507 $data = [
3508 'action' => new moodle_url('/search/index.php'),
3509 'hiddenfields' => (object) ['name' => 'context', 'value' => $this->page->context->id],
3510 'inputname' => 'q',
3511 'searchstring' => get_string('search'),
3513 return $this->render_from_template('core/search_input_navbar', $data);
3517 * Allow plugins to provide some content to be rendered in the navbar.
3518 * The plugin must define a PLUGIN_render_navbar_output function that returns
3519 * the HTML they wish to add to the navbar.
3521 * @return string HTML for the navbar
3523 public function navbar_plugin_output() {
3524 $output = '';
3526 // Give subsystems an opportunity to inject extra html content. The callback
3527 // must always return a string containing valid html.
3528 foreach (\core_component::get_core_subsystems() as $name => $path) {
3529 if ($path) {
3530 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3534 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3535 foreach ($pluginsfunction as $plugintype => $plugins) {
3536 foreach ($plugins as $pluginfunction) {
3537 $output .= $pluginfunction($this);
3542 return $output;
3546 * Construct a user menu, returning HTML that can be echoed out by a
3547 * layout file.
3549 * @param stdClass $user A user object, usually $USER.
3550 * @param bool $withlinks true if a dropdown should be built.
3551 * @return string HTML fragment.
3553 public function user_menu($user = null, $withlinks = null) {
3554 global $USER, $CFG;
3555 require_once($CFG->dirroot . '/user/lib.php');
3557 if (is_null($user)) {
3558 $user = $USER;
3561 // Note: this behaviour is intended to match that of core_renderer::login_info,
3562 // but should not be considered to be good practice; layout options are
3563 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3564 if (is_null($withlinks)) {
3565 $withlinks = empty($this->page->layout_options['nologinlinks']);
3568 // Add a class for when $withlinks is false.
3569 $usermenuclasses = 'usermenu';
3570 if (!$withlinks) {
3571 $usermenuclasses .= ' withoutlinks';
3574 $returnstr = "";
3576 // If during initial install, return the empty return string.
3577 if (during_initial_install()) {
3578 return $returnstr;
3581 $loginpage = $this->is_login_page();
3582 $loginurl = get_login_url();
3584 // Get some navigation opts.
3585 $opts = user_get_user_navigation_info($user, $this->page);
3587 if (!empty($opts->unauthenticateduser)) {
3588 $returnstr = get_string($opts->unauthenticateduser['content'], 'moodle');
3589 // If not logged in, show the typical not-logged-in string.
3590 if (!$loginpage && (!$opts->unauthenticateduser['guest'] || $withlinks)) {
3591 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3594 return html_writer::div(
3595 html_writer::span(
3596 $returnstr,
3597 'login nav-link'
3599 $usermenuclasses
3603 $avatarclasses = "avatars";
3604 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3605 $usertextcontents = $opts->metadata['userfullname'];
3607 // Other user.
3608 if (!empty($opts->metadata['asotheruser'])) {
3609 $avatarcontents .= html_writer::span(
3610 $opts->metadata['realuseravatar'],
3611 'avatar realuser'
3613 $usertextcontents = $opts->metadata['realuserfullname'];
3614 $usertextcontents .= html_writer::tag(
3615 'span',
3616 get_string(
3617 'loggedinas',
3618 'moodle',
3619 html_writer::span(
3620 $opts->metadata['userfullname'],
3621 'value'
3624 array('class' => 'meta viewingas')
3628 // Role.
3629 if (!empty($opts->metadata['asotherrole'])) {
3630 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3631 $usertextcontents .= html_writer::span(
3632 $opts->metadata['rolename'],
3633 'meta role role-' . $role
3637 // User login failures.
3638 if (!empty($opts->metadata['userloginfail'])) {
3639 $usertextcontents .= html_writer::span(
3640 $opts->metadata['userloginfail'],
3641 'meta loginfailures'
3645 // MNet.
3646 if (!empty($opts->metadata['asmnetuser'])) {
3647 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3648 $usertextcontents .= html_writer::span(
3649 $opts->metadata['mnetidprovidername'],
3650 'meta mnet mnet-' . $mnet
3654 $returnstr .= html_writer::span(
3655 html_writer::span($usertextcontents, 'usertext mr-1') .
3656 html_writer::span($avatarcontents, $avatarclasses),
3657 'userbutton'
3660 // Create a divider (well, a filler).
3661 $divider = new action_menu_filler();
3662 $divider->primary = false;
3664 $am = new action_menu();
3665 $am->set_menu_trigger(
3666 $returnstr,
3667 'nav-link'
3669 $am->set_action_label(get_string('usermenu'));
3670 $am->set_nowrap_on_items();
3671 if ($withlinks) {
3672 $navitemcount = count($opts->navitems);
3673 $idx = 0;
3674 foreach ($opts->navitems as $key => $value) {
3676 switch ($value->itemtype) {
3677 case 'divider':
3678 // If the nav item is a divider, add one and skip link processing.
3679 $am->add($divider);
3680 break;
3682 case 'invalid':
3683 // Silently skip invalid entries (should we post a notification?).
3684 break;
3686 case 'link':
3687 // Process this as a link item.
3688 $pix = null;
3689 if (isset($value->pix) && !empty($value->pix)) {
3690 $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
3691 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3692 $value->title = html_writer::img(
3693 $value->imgsrc,
3694 $value->title,
3695 array('class' => 'iconsmall')
3696 ) . $value->title;
3699 $al = new action_menu_link_secondary(
3700 $value->url,
3701 $pix,
3702 $value->title,
3703 array('class' => 'icon')
3705 if (!empty($value->titleidentifier)) {
3706 $al->attributes['data-title'] = $value->titleidentifier;
3708 $am->add($al);
3709 break;
3712 $idx++;
3714 // Add dividers after the first item and before the last item.
3715 if ($idx == 1 || $idx == $navitemcount - 1) {
3716 $am->add($divider);
3721 return html_writer::div(
3722 $this->render($am),
3723 $usermenuclasses
3728 * Secure layout login info.
3730 * @return string
3732 public function secure_layout_login_info() {
3733 if (get_config('core', 'logininfoinsecurelayout')) {
3734 return $this->login_info(false);
3735 } else {
3736 return '';
3741 * Returns the language menu in the secure layout.
3743 * No custom menu items are passed though, such that it will render only the language selection.
3745 * @return string
3747 public function secure_layout_language_menu() {
3748 if (get_config('core', 'langmenuinsecurelayout')) {
3749 $custommenu = new custom_menu('', current_language());
3750 return $this->render_custom_menu($custommenu);
3751 } else {
3752 return '';
3757 * This renders the navbar.
3758 * Uses bootstrap compatible html.
3760 public function navbar() {
3761 return $this->render_from_template('core/navbar', $this->page->navbar);
3765 * Renders a breadcrumb navigation node object.
3767 * @param breadcrumb_navigation_node $item The navigation node to render.
3768 * @return string HTML fragment
3770 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3772 if ($item->action instanceof moodle_url) {
3773 $content = $item->get_content();
3774 $title = $item->get_title();
3775 $attributes = array();
3776 $attributes['itemprop'] = 'url';
3777 if ($title !== '') {
3778 $attributes['title'] = $title;
3780 if ($item->hidden) {
3781 $attributes['class'] = 'dimmed_text';
3783 if ($item->is_last()) {
3784 $attributes['aria-current'] = 'page';
3786 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3787 $content = html_writer::link($item->action, $content, $attributes);
3789 $attributes = array();
3790 $attributes['itemscope'] = '';
3791 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3792 $content = html_writer::tag('span', $content, $attributes);
3794 } else {
3795 $content = $this->render_navigation_node($item);
3797 return $content;
3801 * Renders a navigation node object.
3803 * @param navigation_node $item The navigation node to render.
3804 * @return string HTML fragment
3806 protected function render_navigation_node(navigation_node $item) {
3807 $content = $item->get_content();
3808 $title = $item->get_title();
3809 if ($item->icon instanceof renderable && !$item->hideicon) {
3810 $icon = $this->render($item->icon);
3811 $content = $icon.$content; // use CSS for spacing of icons
3813 if ($item->helpbutton !== null) {
3814 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3816 if ($content === '') {
3817 return '';
3819 if ($item->action instanceof action_link) {
3820 $link = $item->action;
3821 if ($item->hidden) {
3822 $link->add_class('dimmed');
3824 if (!empty($content)) {
3825 // Providing there is content we will use that for the link content.
3826 $link->text = $content;
3828 $content = $this->render($link);
3829 } else if ($item->action instanceof moodle_url) {
3830 $attributes = array();
3831 if ($title !== '') {
3832 $attributes['title'] = $title;
3834 if ($item->hidden) {
3835 $attributes['class'] = 'dimmed_text';
3837 $content = html_writer::link($item->action, $content, $attributes);
3839 } else if (is_string($item->action) || empty($item->action)) {
3840 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3841 if ($title !== '') {
3842 $attributes['title'] = $title;
3844 if ($item->hidden) {
3845 $attributes['class'] = 'dimmed_text';
3847 $content = html_writer::tag('span', $content, $attributes);
3849 return $content;
3853 * Accessibility: Right arrow-like character is
3854 * used in the breadcrumb trail, course navigation menu
3855 * (previous/next activity), calendar, and search forum block.
3856 * If the theme does not set characters, appropriate defaults
3857 * are set automatically. Please DO NOT
3858 * use &lt; &gt; &raquo; - these are confusing for blind users.
3860 * @return string
3862 public function rarrow() {
3863 return $this->page->theme->rarrow;
3867 * Accessibility: Left arrow-like character is
3868 * used in the breadcrumb trail, course navigation menu
3869 * (previous/next activity), calendar, and search forum block.
3870 * If the theme does not set characters, appropriate defaults
3871 * are set automatically. Please DO NOT
3872 * use &lt; &gt; &raquo; - these are confusing for blind users.
3874 * @return string
3876 public function larrow() {
3877 return $this->page->theme->larrow;
3881 * Accessibility: Up arrow-like character is used in
3882 * the book heirarchical navigation.
3883 * If the theme does not set characters, appropriate defaults
3884 * are set automatically. Please DO NOT
3885 * use ^ - this is confusing for blind users.
3887 * @return string
3889 public function uarrow() {
3890 return $this->page->theme->uarrow;
3894 * Accessibility: Down arrow-like character.
3895 * If the theme does not set characters, appropriate defaults
3896 * are set automatically.
3898 * @return string
3900 public function darrow() {
3901 return $this->page->theme->darrow;
3905 * Returns the custom menu if one has been set
3907 * A custom menu can be configured by browsing to a theme's settings page
3908 * and then configuring the custommenu config setting as described.
3910 * Theme developers: DO NOT OVERRIDE! Please override function
3911 * {@link core_renderer::render_custom_menu()} instead.
3913 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3914 * @return string
3916 public function custom_menu($custommenuitems = '') {
3917 global $CFG;
3919 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3920 $custommenuitems = $CFG->custommenuitems;
3922 $custommenu = new custom_menu($custommenuitems, current_language());
3923 return $this->render_custom_menu($custommenu);
3927 * We want to show the custom menus as a list of links in the footer on small screens.
3928 * Just return the menu object exported so we can render it differently.
3930 public function custom_menu_flat() {
3931 global $CFG;
3932 $custommenuitems = '';
3934 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3935 $custommenuitems = $CFG->custommenuitems;
3937 $custommenu = new custom_menu($custommenuitems, current_language());
3938 $langs = get_string_manager()->get_list_of_translations();
3939 $haslangmenu = $this->lang_menu() != '';
3941 if ($haslangmenu) {
3942 $strlang = get_string('language');
3943 $currentlang = current_language();
3944 if (isset($langs[$currentlang])) {
3945 $currentlang = $langs[$currentlang];
3946 } else {
3947 $currentlang = $strlang;
3949 $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3950 foreach ($langs as $langtype => $langname) {
3951 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3955 return $custommenu->export_for_template($this);
3959 * Renders a custom menu object (located in outputcomponents.php)
3961 * The custom menu this method produces makes use of the YUI3 menunav widget
3962 * and requires very specific html elements and classes.
3964 * @staticvar int $menucount
3965 * @param custom_menu $menu
3966 * @return string
3968 protected function render_custom_menu(custom_menu $menu) {
3969 global $CFG;
3971 $langs = get_string_manager()->get_list_of_translations();
3972 $haslangmenu = $this->lang_menu() != '';
3974 if (!$menu->has_children() && !$haslangmenu) {
3975 return '';
3978 if ($haslangmenu) {
3979 $strlang = get_string('language');
3980 $currentlang = current_language();
3981 if (isset($langs[$currentlang])) {
3982 $currentlangstr = $langs[$currentlang];
3983 } else {
3984 $currentlangstr = $strlang;
3986 $this->language = $menu->add($currentlangstr, new moodle_url('#'), $strlang, 10000);
3987 foreach ($langs as $langtype => $langname) {
3988 $attributes = [];
3989 // Set the lang attribute for languages different from the page's current language.
3990 if ($langtype !== $currentlang) {
3991 $attributes[] = [
3992 'key' => 'lang',
3993 'value' => get_html_lang_attribute_value($langtype),
3996 $this->language->add($langname, new moodle_url($this->page->url, ['lang' => $langtype]), null, null, $attributes);
4000 $content = '';
4001 foreach ($menu->get_children() as $item) {
4002 $context = $item->export_for_template($this);
4003 $content .= $this->render_from_template('core/custom_menu_item', $context);
4006 return $content;
4010 * Renders a custom menu node as part of a submenu
4012 * The custom menu this method produces makes use of the YUI3 menunav widget
4013 * and requires very specific html elements and classes.
4015 * @see core:renderer::render_custom_menu()
4017 * @staticvar int $submenucount
4018 * @param custom_menu_item $menunode
4019 * @return string
4021 protected function render_custom_menu_item(custom_menu_item $menunode) {
4022 // Required to ensure we get unique trackable id's
4023 static $submenucount = 0;
4024 if ($menunode->has_children()) {
4025 // If the child has menus render it as a sub menu
4026 $submenucount++;
4027 $content = html_writer::start_tag('li');
4028 if ($menunode->get_url() !== null) {
4029 $url = $menunode->get_url();
4030 } else {
4031 $url = '#cm_submenu_'.$submenucount;
4033 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
4034 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
4035 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
4036 $content .= html_writer::start_tag('ul');
4037 foreach ($menunode->get_children() as $menunode) {
4038 $content .= $this->render_custom_menu_item($menunode);
4040 $content .= html_writer::end_tag('ul');
4041 $content .= html_writer::end_tag('div');
4042 $content .= html_writer::end_tag('div');
4043 $content .= html_writer::end_tag('li');
4044 } else {
4045 // The node doesn't have children so produce a final menuitem.
4046 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
4047 $content = '';
4048 if (preg_match("/^#+$/", $menunode->get_text())) {
4050 // This is a divider.
4051 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
4052 } else {
4053 $content = html_writer::start_tag(
4054 'li',
4055 array(
4056 'class' => 'yui3-menuitem'
4059 if ($menunode->get_url() !== null) {
4060 $url = $menunode->get_url();
4061 } else {
4062 $url = '#';
4064 $content .= html_writer::link(
4065 $url,
4066 $menunode->get_text(),
4067 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
4070 $content .= html_writer::end_tag('li');
4072 // Return the sub menu
4073 return $content;
4077 * Renders theme links for switching between default and other themes.
4079 * @return string
4081 protected function theme_switch_links() {
4083 $actualdevice = core_useragent::get_device_type();
4084 $currentdevice = $this->page->devicetypeinuse;
4085 $switched = ($actualdevice != $currentdevice);
4087 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
4088 // The user is using the a default device and hasn't switched so don't shown the switch
4089 // device links.
4090 return '';
4093 if ($switched) {
4094 $linktext = get_string('switchdevicerecommended');
4095 $devicetype = $actualdevice;
4096 } else {
4097 $linktext = get_string('switchdevicedefault');
4098 $devicetype = 'default';
4100 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
4102 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
4103 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
4104 $content .= html_writer::end_tag('div');
4106 return $content;
4110 * Renders tabs
4112 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
4114 * Theme developers: In order to change how tabs are displayed please override functions
4115 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
4117 * @param array $tabs array of tabs, each of them may have it's own ->subtree
4118 * @param string|null $selected which tab to mark as selected, all parent tabs will
4119 * automatically be marked as activated
4120 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
4121 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
4122 * @return string
4124 public final function tabtree($tabs, $selected = null, $inactive = null) {
4125 return $this->render(new tabtree($tabs, $selected, $inactive));
4129 * Renders tabtree
4131 * @param tabtree $tabtree
4132 * @return string
4134 protected function render_tabtree(tabtree $tabtree) {
4135 if (empty($tabtree->subtree)) {
4136 return '';
4138 $data = $tabtree->export_for_template($this);
4139 return $this->render_from_template('core/tabtree', $data);
4143 * Renders tabobject (part of tabtree)
4145 * This function is called from {@link core_renderer::render_tabtree()}
4146 * and also it calls itself when printing the $tabobject subtree recursively.
4148 * Property $tabobject->level indicates the number of row of tabs.
4150 * @param tabobject $tabobject
4151 * @return string HTML fragment
4153 protected function render_tabobject(tabobject $tabobject) {
4154 $str = '';
4156 // Print name of the current tab.
4157 if ($tabobject instanceof tabtree) {
4158 // No name for tabtree root.
4159 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
4160 // Tab name without a link. The <a> tag is used for styling.
4161 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
4162 } else {
4163 // Tab name with a link.
4164 if (!($tabobject->link instanceof moodle_url)) {
4165 // backward compartibility when link was passed as quoted string
4166 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
4167 } else {
4168 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
4172 if (empty($tabobject->subtree)) {
4173 if ($tabobject->selected) {
4174 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
4176 return $str;
4179 // Print subtree.
4180 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
4181 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
4182 $cnt = 0;
4183 foreach ($tabobject->subtree as $tab) {
4184 $liclass = '';
4185 if (!$cnt) {
4186 $liclass .= ' first';
4188 if ($cnt == count($tabobject->subtree) - 1) {
4189 $liclass .= ' last';
4191 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
4192 $liclass .= ' onerow';
4195 if ($tab->selected) {
4196 $liclass .= ' here selected';
4197 } else if ($tab->activated) {
4198 $liclass .= ' here active';
4201 // This will recursively call function render_tabobject() for each item in subtree.
4202 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
4203 $cnt++;
4205 $str .= html_writer::end_tag('ul');
4208 return $str;
4212 * Get the HTML for blocks in the given region.
4214 * @since Moodle 2.5.1 2.6
4215 * @param string $region The region to get HTML for.
4216 * @param array $classes Wrapping tag classes.
4217 * @param string $tag Wrapping tag.
4218 * @param boolean $fakeblocksonly Include fake blocks only.
4219 * @return string HTML.
4221 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
4222 $displayregion = $this->page->apply_theme_region_manipulations($region);
4223 $classes = (array)$classes;
4224 $classes[] = 'block-region';
4225 $attributes = array(
4226 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
4227 'class' => join(' ', $classes),
4228 'data-blockregion' => $displayregion,
4229 'data-droptarget' => '1'
4231 if ($this->page->blocks->region_has_content($displayregion, $this)) {
4232 $content = $this->blocks_for_region($displayregion, $fakeblocksonly);
4233 } else {
4234 $content = '';
4236 return html_writer::tag($tag, $content, $attributes);
4240 * Renders a custom block region.
4242 * Use this method if you want to add an additional block region to the content of the page.
4243 * Please note this should only be used in special situations.
4244 * We want to leave the theme is control where ever possible!
4246 * This method must use the same method that the theme uses within its layout file.
4247 * As such it asks the theme what method it is using.
4248 * It can be one of two values, blocks or blocks_for_region (deprecated).
4250 * @param string $regionname The name of the custom region to add.
4251 * @return string HTML for the block region.
4253 public function custom_block_region($regionname) {
4254 if ($this->page->theme->get_block_render_method() === 'blocks') {
4255 return $this->blocks($regionname);
4256 } else {
4257 return $this->blocks_for_region($regionname);
4262 * Returns the CSS classes to apply to the body tag.
4264 * @since Moodle 2.5.1 2.6
4265 * @param array $additionalclasses Any additional classes to apply.
4266 * @return string
4268 public function body_css_classes(array $additionalclasses = array()) {
4269 return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses);
4273 * The ID attribute to apply to the body tag.
4275 * @since Moodle 2.5.1 2.6
4276 * @return string
4278 public function body_id() {
4279 return $this->page->bodyid;
4283 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4285 * @since Moodle 2.5.1 2.6
4286 * @param string|array $additionalclasses Any additional classes to give the body tag,
4287 * @return string
4289 public function body_attributes($additionalclasses = array()) {
4290 if (!is_array($additionalclasses)) {
4291 $additionalclasses = explode(' ', $additionalclasses);
4293 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4297 * Gets HTML for the page heading.
4299 * @since Moodle 2.5.1 2.6
4300 * @param string $tag The tag to encase the heading in. h1 by default.
4301 * @return string HTML.
4303 public function page_heading($tag = 'h1') {
4304 return html_writer::tag($tag, $this->page->heading);
4308 * Gets the HTML for the page heading button.
4310 * @since Moodle 2.5.1 2.6
4311 * @return string HTML.
4313 public function page_heading_button() {
4314 return $this->page->button;
4318 * Returns the Moodle docs link to use for this page.
4320 * @since Moodle 2.5.1 2.6
4321 * @param string $text
4322 * @return string
4324 public function page_doc_link($text = null) {
4325 if ($text === null) {
4326 $text = get_string('moodledocslink');
4328 $path = page_get_doc_link_path($this->page);
4329 if (!$path) {
4330 return '';
4332 return $this->doc_link($path, $text);
4336 * Returns the HTML for the site support email link
4338 * @param array $customattribs Array of custom attributes for the support email anchor tag.
4339 * @param bool $embed Set to true if you want to embed the link in other inline content.
4340 * @return string The html code for the support email link.
4342 public function supportemail(array $customattribs = [], bool $embed = false): string {
4343 global $CFG;
4345 // Do not provide a link to contact site support if it is unavailable to this user. This would be where the site has
4346 // disabled support, or limited it to authenticated users and the current user is a guest or not logged in.
4347 if (!isset($CFG->supportavailability) ||
4348 $CFG->supportavailability == CONTACT_SUPPORT_DISABLED ||
4349 ($CFG->supportavailability == CONTACT_SUPPORT_AUTHENTICATED && (!isloggedin() || isguestuser()))) {
4350 return '';
4353 $label = get_string('contactsitesupport', 'admin');
4354 $icon = $this->pix_icon('t/email', '');
4356 if (!$embed) {
4357 $content = $icon . $label;
4358 } else {
4359 $content = $label;
4362 if (!empty($CFG->supportpage)) {
4363 $attributes = ['href' => $CFG->supportpage, 'target' => 'blank'];
4364 $content .= $this->pix_icon('i/externallink', '', 'moodle', ['class' => 'ml-1']);
4365 } else {
4366 $attributes = ['href' => $CFG->wwwroot . '/user/contactsitesupport.php'];
4369 $attributes += $customattribs;
4371 return html_writer::tag('a', $content, $attributes);
4375 * Returns the services and support link for the help pop-up.
4377 * @return string
4379 public function services_support_link(): string {
4380 global $CFG;
4382 if (during_initial_install() ||
4383 (isset($CFG->showservicesandsupportcontent) && $CFG->showservicesandsupportcontent == false) ||
4384 !is_siteadmin()) {
4385 return '';
4388 $liferingicon = $this->pix_icon('t/life-ring', '', 'moodle', ['class' => 'fa fa-life-ring']);
4389 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle', ['class' => 'ml-1']);
4390 $link = !empty($CFG->servicespage)
4391 ? $CFG->servicespage
4392 : 'https://moodle.com/help/?utm_source=CTA-banner&utm_medium=platform&utm_campaign=name~Moodle4+cat~lms+mp~no';
4393 $content = $liferingicon . get_string('moodleservicesandsupport') . $newwindowicon;
4395 return html_writer::tag('a', $content, ['target' => '_blank', 'href' => $link]);
4399 * Helper function to decide whether to show the help popover header or not.
4401 * @return bool
4403 public function has_popover_links(): bool {
4404 return !empty($this->services_support_link()) || !empty($this->page_doc_link()) || !empty($this->supportemail());
4408 * Helper function to decide whether to show the communication link or not.
4410 * @return bool
4412 public function has_communication_links(): bool {
4413 if (during_initial_install() || !core_communication\api::is_available()) {
4414 return false;
4416 return !empty($this->communication_link());
4420 * Returns the communication link, complete with html.
4422 * @return string
4424 public function communication_link(): string {
4425 $link = $this->communication_url() ?? '';
4426 $commicon = $this->pix_icon('t/messages-o', '', 'moodle', ['class' => 'fa fa-comments']);
4427 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle', ['class' => 'ml-1']);
4428 $content = $commicon . get_string('communicationroomlink', 'course') . $newwindowicon;
4429 $html = html_writer::tag('a', $content, ['target' => '_blank', 'href' => $link]);
4431 return !empty($link) ? $html : '';
4435 * Returns the communication url for a given instance if it exists.
4437 * @return string
4439 public function communication_url(): string {
4440 global $COURSE;
4441 $url = '';
4442 if ($COURSE->id !== SITEID) {
4443 $comm = \core_communication\api::load_by_instance(
4444 context: \core\context\course::instance($COURSE->id),
4445 component: 'core_course',
4446 instancetype: 'coursecommunication',
4447 instanceid: $COURSE->id,
4449 $url = $comm->get_communication_room_url();
4452 return !empty($url) ? $url : '';
4456 * Returns the page heading menu.
4458 * @since Moodle 2.5.1 2.6
4459 * @return string HTML.
4461 public function page_heading_menu() {
4462 return $this->page->headingmenu;
4466 * Returns the title to use on the page.
4468 * @since Moodle 2.5.1 2.6
4469 * @return string
4471 public function page_title() {
4472 return $this->page->title;
4476 * Returns the moodle_url for the favicon.
4478 * @since Moodle 2.5.1 2.6
4479 * @return moodle_url The moodle_url for the favicon
4481 public function favicon() {
4482 $logo = null;
4483 if (!during_initial_install()) {
4484 $logo = get_config('core_admin', 'favicon');
4486 if (empty($logo)) {
4487 return $this->image_url('favicon', 'theme');
4490 // Use $CFG->themerev to prevent browser caching when the file changes.
4491 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'favicon', '64x64/',
4492 theme_get_revision(), $logo);
4496 * Renders preferences groups.
4498 * @param preferences_groups $renderable The renderable
4499 * @return string The output.
4501 public function render_preferences_groups(preferences_groups $renderable) {
4502 return $this->render_from_template('core/preferences_groups', $renderable);
4506 * Renders preferences group.
4508 * @param preferences_group $renderable The renderable
4509 * @return string The output.
4511 public function render_preferences_group(preferences_group $renderable) {
4512 $html = '';
4513 $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4514 $html .= $this->heading($renderable->title, 3);
4515 $html .= html_writer::start_tag('ul');
4516 foreach ($renderable->nodes as $node) {
4517 if ($node->has_children()) {
4518 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4520 $html .= html_writer::tag('li', $this->render($node));
4522 $html .= html_writer::end_tag('ul');
4523 $html .= html_writer::end_tag('div');
4524 return $html;
4527 public function context_header($headerinfo = null, $headinglevel = 1) {
4528 global $DB, $USER, $CFG, $SITE;
4529 require_once($CFG->dirroot . '/user/lib.php');
4530 $context = $this->page->context;
4531 $heading = null;
4532 $imagedata = null;
4533 $subheader = null;
4534 $userbuttons = null;
4536 // Make sure to use the heading if it has been set.
4537 if (isset($headerinfo['heading'])) {
4538 $heading = $headerinfo['heading'];
4539 } else {
4540 $heading = $this->page->heading;
4543 // The user context currently has images and buttons. Other contexts may follow.
4544 if ((isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) && $this->page->pagetype !== 'my-index') {
4545 if (isset($headerinfo['user'])) {
4546 $user = $headerinfo['user'];
4547 } else {
4548 // Look up the user information if it is not supplied.
4549 $user = $DB->get_record('user', array('id' => $context->instanceid));
4552 // If the user context is set, then use that for capability checks.
4553 if (isset($headerinfo['usercontext'])) {
4554 $context = $headerinfo['usercontext'];
4557 // Only provide user information if the user is the current user, or a user which the current user can view.
4558 // When checking user_can_view_profile(), either:
4559 // If the page context is course, check the course context (from the page object) or;
4560 // If page context is NOT course, then check across all courses.
4561 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4563 if (user_can_view_profile($user, $course)) {
4564 // Use the user's full name if the heading isn't set.
4565 if (empty($heading)) {
4566 $heading = fullname($user);
4569 $imagedata = $this->user_picture($user, array('size' => 100));
4571 // Check to see if we should be displaying a message button.
4572 if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
4573 $userbuttons = array(
4574 'messages' => array(
4575 'buttontype' => 'message',
4576 'title' => get_string('message', 'message'),
4577 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4578 'image' => 'message',
4579 'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
4580 'page' => $this->page
4584 if ($USER->id != $user->id) {
4585 $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4586 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4587 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4588 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4589 $userbuttons['togglecontact'] = array(
4590 'buttontype' => 'togglecontact',
4591 'title' => get_string($contacttitle, 'message'),
4592 'url' => new moodle_url('/message/index.php', array(
4593 'user1' => $USER->id,
4594 'user2' => $user->id,
4595 $contacturlaction => $user->id,
4596 'sesskey' => sesskey())
4598 'image' => $contactimage,
4599 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4600 'page' => $this->page
4604 } else {
4605 $heading = null;
4610 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4611 return $this->render_context_header($contextheader);
4615 * Renders the skip links for the page.
4617 * @param array $links List of skip links.
4618 * @return string HTML for the skip links.
4620 public function render_skip_links($links) {
4621 $context = [ 'links' => []];
4623 foreach ($links as $url => $text) {
4624 $context['links'][] = [ 'url' => $url, 'text' => $text];
4627 return $this->render_from_template('core/skip_links', $context);
4631 * Renders the header bar.
4633 * @param context_header $contextheader Header bar object.
4634 * @return string HTML for the header bar.
4636 protected function render_context_header(context_header $contextheader) {
4638 // Generate the heading first and before everything else as we might have to do an early return.
4639 if (!isset($contextheader->heading)) {
4640 $heading = $this->heading($this->page->heading, $contextheader->headinglevel);
4641 } else {
4642 $heading = $this->heading($contextheader->heading, $contextheader->headinglevel);
4645 $showheader = empty($this->page->layout_options['nocontextheader']);
4646 if (!$showheader) {
4647 // Return the heading wrapped in an sr-only element so it is only visible to screen-readers.
4648 return html_writer::div($heading, 'sr-only');
4651 // All the html stuff goes here.
4652 $html = html_writer::start_div('page-context-header');
4654 // Image data.
4655 if (isset($contextheader->imagedata)) {
4656 // Header specific image.
4657 $html .= html_writer::div($contextheader->imagedata, 'page-header-image icon-size-7');
4660 // Headings.
4661 if (isset($contextheader->prefix)) {
4662 $prefix = html_writer::div($contextheader->prefix, 'text-muted');
4663 $heading = $prefix . $heading;
4665 $html .= html_writer::tag('div', $heading, array('class' => 'page-header-headings'));
4667 // Buttons.
4668 if (isset($contextheader->additionalbuttons)) {
4669 $html .= html_writer::start_div('btn-group header-button-group');
4670 foreach ($contextheader->additionalbuttons as $button) {
4671 if (!isset($button->page)) {
4672 // Include js for messaging.
4673 if ($button['buttontype'] === 'togglecontact') {
4674 \core_message\helper::togglecontact_requirejs();
4676 if ($button['buttontype'] === 'message') {
4677 \core_message\helper::messageuser_requirejs();
4679 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4680 'class' => 'iconsmall',
4681 'role' => 'presentation'
4683 $image .= html_writer::span($button['title'], 'header-button-title');
4684 } else {
4685 $image = html_writer::empty_tag('img', array(
4686 'src' => $button['formattedimage'],
4687 'role' => 'presentation'
4690 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4692 $html .= html_writer::end_div();
4694 $html .= html_writer::end_div();
4696 return $html;
4700 * Wrapper for header elements.
4702 * @return string HTML to display the main header.
4704 public function full_header() {
4705 $pagetype = $this->page->pagetype;
4706 $homepage = get_home_page();
4707 $homepagetype = null;
4708 // Add a special case since /my/courses is a part of the /my subsystem.
4709 if ($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES) {
4710 $homepagetype = 'my-index';
4711 } else if ($homepage == HOMEPAGE_SITE) {
4712 $homepagetype = 'site-index';
4714 if ($this->page->include_region_main_settings_in_header_actions() &&
4715 !$this->page->blocks->is_block_present('settings')) {
4716 // Only include the region main settings if the page has requested it and it doesn't already have
4717 // the settings block on it. The region main settings are included in the settings block and
4718 // duplicating the content causes behat failures.
4719 $this->page->add_header_action(html_writer::div(
4720 $this->region_main_settings_menu(),
4721 'd-print-none',
4722 ['id' => 'region-main-settings-menu']
4726 $header = new stdClass();
4727 $header->settingsmenu = $this->context_header_settings_menu();
4728 $header->contextheader = $this->context_header();
4729 $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
4730 $header->navbar = $this->navbar();
4731 $header->pageheadingbutton = $this->page_heading_button();
4732 $header->courseheader = $this->course_header();
4733 $header->headeractions = $this->page->get_header_actions();
4734 if (!empty($pagetype) && !empty($homepagetype) && $pagetype == $homepagetype) {
4735 $header->welcomemessage = \core_user::welcome_message();
4737 return $this->render_from_template('core/full_header', $header);
4741 * This is an optional menu that can be added to a layout by a theme. It contains the
4742 * menu for the course administration, only on the course main page.
4744 * @return string
4746 public function context_header_settings_menu() {
4747 $context = $this->page->context;
4748 $menu = new action_menu();
4750 $items = $this->page->navbar->get_items();
4751 $currentnode = end($items);
4753 $showcoursemenu = false;
4754 $showfrontpagemenu = false;
4755 $showusermenu = false;
4757 // We are on the course home page.
4758 if (($context->contextlevel == CONTEXT_COURSE) &&
4759 !empty($currentnode) &&
4760 ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
4761 $showcoursemenu = true;
4764 $courseformat = course_get_format($this->page->course);
4765 // This is a single activity course format, always show the course menu on the activity main page.
4766 if ($context->contextlevel == CONTEXT_MODULE &&
4767 !$courseformat->has_view_page()) {
4769 $this->page->navigation->initialise();
4770 $activenode = $this->page->navigation->find_active_node();
4771 // If the settings menu has been forced then show the menu.
4772 if ($this->page->is_settings_menu_forced()) {
4773 $showcoursemenu = true;
4774 } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
4775 $activenode->type == navigation_node::TYPE_RESOURCE)) {
4777 // We only want to show the menu on the first page of the activity. This means
4778 // the breadcrumb has no additional nodes.
4779 if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
4780 $showcoursemenu = true;
4785 // This is the site front page.
4786 if ($context->contextlevel == CONTEXT_COURSE &&
4787 !empty($currentnode) &&
4788 $currentnode->key === 'home') {
4789 $showfrontpagemenu = true;
4792 // This is the user profile page.
4793 if ($context->contextlevel == CONTEXT_USER &&
4794 !empty($currentnode) &&
4795 ($currentnode->key === 'myprofile')) {
4796 $showusermenu = true;
4799 if ($showfrontpagemenu) {
4800 $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
4801 if ($settingsnode) {
4802 // Build an action menu based on the visible nodes from this navigation tree.
4803 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4805 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4806 if ($skipped) {
4807 $text = get_string('morenavigationlinks');
4808 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4809 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4810 $menu->add_secondary_action($link);
4813 } else if ($showcoursemenu) {
4814 $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
4815 if ($settingsnode) {
4816 // Build an action menu based on the visible nodes from this navigation tree.
4817 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4819 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4820 if ($skipped) {
4821 $text = get_string('morenavigationlinks');
4822 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4823 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4824 $menu->add_secondary_action($link);
4827 } else if ($showusermenu) {
4828 // Get the course admin node from the settings navigation.
4829 $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
4830 if ($settingsnode) {
4831 // Build an action menu based on the visible nodes from this navigation tree.
4832 $this->build_action_menu_from_navigation($menu, $settingsnode);
4836 return $this->render($menu);
4840 * Take a node in the nav tree and make an action menu out of it.
4841 * The links are injected in the action menu.
4843 * @param action_menu $menu
4844 * @param navigation_node $node
4845 * @param boolean $indent
4846 * @param boolean $onlytopleafnodes
4847 * @return boolean nodesskipped - True if nodes were skipped in building the menu
4849 protected function build_action_menu_from_navigation(action_menu $menu,
4850 navigation_node $node,
4851 $indent = false,
4852 $onlytopleafnodes = false) {
4853 $skipped = false;
4854 // Build an action menu based on the visible nodes from this navigation tree.
4855 foreach ($node->children as $menuitem) {
4856 if ($menuitem->display) {
4857 if ($onlytopleafnodes && $menuitem->children->count()) {
4858 $skipped = true;
4859 continue;
4861 if ($menuitem->action) {
4862 if ($menuitem->action instanceof action_link) {
4863 $link = $menuitem->action;
4864 // Give preference to setting icon over action icon.
4865 if (!empty($menuitem->icon)) {
4866 $link->icon = $menuitem->icon;
4868 } else {
4869 $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
4871 } else {
4872 if ($onlytopleafnodes) {
4873 $skipped = true;
4874 continue;
4876 $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
4878 if ($indent) {
4879 $link->add_class('ml-4');
4881 if (!empty($menuitem->classes)) {
4882 $link->add_class(implode(" ", $menuitem->classes));
4885 $menu->add_secondary_action($link);
4886 $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
4889 return $skipped;
4893 * This is an optional menu that can be added to a layout by a theme. It contains the
4894 * menu for the most specific thing from the settings block. E.g. Module administration.
4896 * @return string
4898 public function region_main_settings_menu() {
4899 $context = $this->page->context;
4900 $menu = new action_menu();
4902 if ($context->contextlevel == CONTEXT_MODULE) {
4904 $this->page->navigation->initialise();
4905 $node = $this->page->navigation->find_active_node();
4906 $buildmenu = false;
4907 // If the settings menu has been forced then show the menu.
4908 if ($this->page->is_settings_menu_forced()) {
4909 $buildmenu = true;
4910 } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
4911 $node->type == navigation_node::TYPE_RESOURCE)) {
4913 $items = $this->page->navbar->get_items();
4914 $navbarnode = end($items);
4915 // We only want to show the menu on the first page of the activity. This means
4916 // the breadcrumb has no additional nodes.
4917 if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
4918 $buildmenu = true;
4921 if ($buildmenu) {
4922 // Get the course admin node from the settings navigation.
4923 $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
4924 if ($node) {
4925 // Build an action menu based on the visible nodes from this navigation tree.
4926 $this->build_action_menu_from_navigation($menu, $node);
4930 } else if ($context->contextlevel == CONTEXT_COURSECAT) {
4931 // For course category context, show category settings menu, if we're on the course category page.
4932 if ($this->page->pagetype === 'course-index-category') {
4933 $node = $this->page->settingsnav->find('categorysettings', navigation_node::TYPE_CONTAINER);
4934 if ($node) {
4935 // Build an action menu based on the visible nodes from this navigation tree.
4936 $this->build_action_menu_from_navigation($menu, $node);
4940 } else {
4941 $items = $this->page->navbar->get_items();
4942 $navbarnode = end($items);
4944 if ($navbarnode && ($navbarnode->key === 'participants')) {
4945 $node = $this->page->settingsnav->find('users', navigation_node::TYPE_CONTAINER);
4946 if ($node) {
4947 // Build an action menu based on the visible nodes from this navigation tree.
4948 $this->build_action_menu_from_navigation($menu, $node);
4953 return $this->render($menu);
4957 * Displays the list of tags associated with an entry
4959 * @param array $tags list of instances of core_tag or stdClass
4960 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4961 * to use default, set to '' (empty string) to omit the label completely
4962 * @param string $classes additional classes for the enclosing div element
4963 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4964 * will be appended to the end, JS will toggle the rest of the tags
4965 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4966 * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
4967 * @return string
4969 public function tag_list($tags, $label = null, $classes = '', $limit = 10,
4970 $pagecontext = null, $accesshidelabel = false) {
4971 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
4972 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4976 * Renders element for inline editing of any value
4978 * @param \core\output\inplace_editable $element
4979 * @return string
4981 public function render_inplace_editable(\core\output\inplace_editable $element) {
4982 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4986 * Renders a bar chart.
4988 * @param \core\chart_bar $chart The chart.
4989 * @return string
4991 public function render_chart_bar(\core\chart_bar $chart) {
4992 return $this->render_chart($chart);
4996 * Renders a line chart.
4998 * @param \core\chart_line $chart The chart.
4999 * @return string
5001 public function render_chart_line(\core\chart_line $chart) {
5002 return $this->render_chart($chart);
5006 * Renders a pie chart.
5008 * @param \core\chart_pie $chart The chart.
5009 * @return string
5011 public function render_chart_pie(\core\chart_pie $chart) {
5012 return $this->render_chart($chart);
5016 * Renders a chart.
5018 * @param \core\chart_base $chart The chart.
5019 * @param bool $withtable Whether to include a data table with the chart.
5020 * @return string
5022 public function render_chart(\core\chart_base $chart, $withtable = true) {
5023 $chartdata = json_encode($chart);
5024 return $this->render_from_template('core/chart', (object) [
5025 'chartdata' => $chartdata,
5026 'withtable' => $withtable
5031 * Renders the login form.
5033 * @param \core_auth\output\login $form The renderable.
5034 * @return string
5036 public function render_login(\core_auth\output\login $form) {
5037 global $CFG, $SITE;
5039 $context = $form->export_for_template($this);
5041 $context->errorformatted = $this->error_text($context->error);
5042 $url = $this->get_logo_url();
5043 if ($url) {
5044 $url = $url->out(false);
5046 $context->logourl = $url;
5047 $context->sitename = format_string($SITE->fullname, true,
5048 ['context' => context_course::instance(SITEID), "escape" => false]);
5050 return $this->render_from_template('core/loginform', $context);
5054 * Renders an mform element from a template.
5056 * @param HTML_QuickForm_element $element element
5057 * @param bool $required if input is required field
5058 * @param bool $advanced if input is an advanced field
5059 * @param string $error error message to display
5060 * @param bool $ingroup True if this element is rendered as part of a group
5061 * @return mixed string|bool
5063 public function mform_element($element, $required, $advanced, $error, $ingroup) {
5064 $templatename = 'core_form/element-' . $element->getType();
5065 if ($ingroup) {
5066 $templatename .= "-inline";
5068 try {
5069 // We call this to generate a file not found exception if there is no template.
5070 // We don't want to call export_for_template if there is no template.
5071 core\output\mustache_template_finder::get_template_filepath($templatename);
5073 if ($element instanceof templatable) {
5074 $elementcontext = $element->export_for_template($this);
5076 $helpbutton = '';
5077 if (method_exists($element, 'getHelpButton')) {
5078 $helpbutton = $element->getHelpButton();
5080 $label = $element->getLabel();
5081 $text = '';
5082 if (method_exists($element, 'getText')) {
5083 // There currently exists code that adds a form element with an empty label.
5084 // If this is the case then set the label to the description.
5085 if (empty($label)) {
5086 $label = $element->getText();
5087 } else {
5088 $text = $element->getText();
5092 // Generate the form element wrapper ids and names to pass to the template.
5093 // This differs between group and non-group elements.
5094 if ($element->getType() === 'group') {
5095 // Group element.
5096 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
5097 $elementcontext['wrapperid'] = $elementcontext['id'];
5099 // Ensure group elements pass through the group name as the element name.
5100 $elementcontext['name'] = $elementcontext['groupname'];
5101 } else {
5102 // Non grouped element.
5103 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
5104 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
5107 $context = array(
5108 'element' => $elementcontext,
5109 'label' => $label,
5110 'text' => $text,
5111 'required' => $required,
5112 'advanced' => $advanced,
5113 'helpbutton' => $helpbutton,
5114 'error' => $error
5116 return $this->render_from_template($templatename, $context);
5118 } catch (Exception $e) {
5119 // No template for this element.
5120 return false;
5125 * Render the login signup form into a nice template for the theme.
5127 * @param mform $form
5128 * @return string
5130 public function render_login_signup_form($form) {
5131 global $SITE;
5133 $context = $form->export_for_template($this);
5134 $url = $this->get_logo_url();
5135 if ($url) {
5136 $url = $url->out(false);
5138 $context['logourl'] = $url;
5139 $context['sitename'] = format_string($SITE->fullname, true,
5140 ['context' => context_course::instance(SITEID), "escape" => false]);
5142 return $this->render_from_template('core/signup_form_layout', $context);
5146 * Render the verify age and location page into a nice template for the theme.
5148 * @param \core_auth\output\verify_age_location_page $page The renderable
5149 * @return string
5151 protected function render_verify_age_location_page($page) {
5152 $context = $page->export_for_template($this);
5154 return $this->render_from_template('core/auth_verify_age_location_page', $context);
5158 * Render the digital minor contact information page into a nice template for the theme.
5160 * @param \core_auth\output\digital_minor_page $page The renderable
5161 * @return string
5163 protected function render_digital_minor_page($page) {
5164 $context = $page->export_for_template($this);
5166 return $this->render_from_template('core/auth_digital_minor_page', $context);
5170 * Renders a progress bar.
5172 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
5174 * @param progress_bar $bar The bar.
5175 * @return string HTML fragment
5177 public function render_progress_bar(progress_bar $bar) {
5178 $data = $bar->export_for_template($this);
5179 return $this->render_from_template('core/progress_bar', $data);
5183 * Renders an update to a progress bar.
5185 * Note: This does not cleanly map to a renderable class and should
5186 * never be used directly.
5188 * @param string $id
5189 * @param float $percent
5190 * @param string $msg Message
5191 * @param string $estimate time remaining message
5192 * @return string ascii fragment
5194 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
5195 return html_writer::script(js_writer::function_call('updateProgressBar', [$id, $percent, $msg, $estimate]));
5199 * Renders element for a toggle-all checkbox.
5201 * @param \core\output\checkbox_toggleall $element
5202 * @return string
5204 public function render_checkbox_toggleall(\core\output\checkbox_toggleall $element) {
5205 return $this->render_from_template($element->get_template(), $element->export_for_template($this));
5209 * Renders the tertiary nav for the participants page
5211 * @param object $course The course we are operating within
5212 * @param string|null $renderedbuttons Any additional buttons/content to be displayed in line with the nav
5213 * @return string
5215 public function render_participants_tertiary_nav(object $course, ?string $renderedbuttons = null) {
5216 $actionbar = new \core\output\participants_action_bar($course, $this->page, $renderedbuttons);
5217 $content = $this->render_from_template('core_course/participants_actionbar', $actionbar->export_for_template($this));
5218 return $content ?: "";
5222 * Renders release information in the footer popup
5223 * @return string Moodle release info.
5225 public function moodle_release() {
5226 global $CFG;
5227 if (!during_initial_install() && is_siteadmin()) {
5228 return $CFG->release;
5233 * Generate the add block button when editing mode is turned on and the user can edit blocks.
5235 * @param string $region where new blocks should be added.
5236 * @return string html for the add block button.
5238 public function addblockbutton($region = ''): string {
5239 $addblockbutton = '';
5240 $regions = $this->page->blocks->get_regions();
5241 if (count($regions) == 0) {
5242 return '';
5244 if (isset($this->page->theme->addblockposition) &&
5245 $this->page->user_is_editing() &&
5246 $this->page->user_can_edit_blocks() &&
5247 $this->page->pagelayout !== 'mycourses'
5249 $params = ['bui_addblock' => '', 'sesskey' => sesskey()];
5250 if (!empty($region)) {
5251 $params['bui_blockregion'] = $region;
5253 $url = new moodle_url($this->page->url, $params);
5254 $addblockbutton = $this->render_from_template('core/add_block_button',
5256 'link' => $url->out(false),
5257 'escapedlink' => "?{$url->get_query_string(false)}",
5258 'pagehash' => $this->page->get_edited_page_hash(),
5259 'blockregion' => $region,
5260 // The following parameters are not used since Moodle 4.2 but are
5261 // still passed for backward-compatibility.
5262 'pageType' => $this->page->pagetype,
5263 'pageLayout' => $this->page->pagelayout,
5264 'subPage' => $this->page->subpage,
5268 return $addblockbutton;
5272 * Prepares an element for streaming output
5274 * This must be used with NO_OUTPUT_BUFFERING set to true. After using this method
5275 * any subsequent prints or echos to STDOUT result in the outputted content magically
5276 * being appended inside that element rather than where the current html would be
5277 * normally. This enables pages which take some time to render incremental content to
5278 * first output a fully formed html page, including the footer, and to then stream
5279 * into an element such as the main content div. This fixes a class of page layout
5280 * bugs and reduces layout shift issues and was inspired by Facebook BigPipe.
5282 * Some use cases such as a simple page which loads content via ajax could be swapped
5283 * to this method wich saves another http request and its network latency resulting
5284 * in both lower server load and better front end performance.
5286 * You should consider giving the element you stream into a minimum height to further
5287 * reduce layout shift as the content initally streams into the element.
5289 * You can safely finish the output without closing the streamed element. You can also
5290 * call this method again to swap the target of the streaming to a new element as
5291 * often as you want.
5293 * https://www.youtube.com/watch?v=LLRig4s1_yA&t=1022s
5294 * Watch this video segment to explain how and why this 'One Weird Trick' works.
5296 * @param string $selector where new content should be appended
5297 * @param string $element which contains the streamed content
5298 * @return string html to be written
5300 public function select_element_for_append(string $selector = '#region-main [role=main]', string $element = 'div') {
5302 if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) {
5303 throw new coding_exception('select_element_for_append used in a non-CLI script without setting NO_OUTPUT_BUFFERING.',
5304 DEBUG_DEVELOPER);
5307 // We are already streaming into this element so don't change anything.
5308 if ($this->currentselector === $selector && $this->currentelement === $element) {
5309 return;
5312 // If we have a streaming element close it before starting a new one.
5313 $html = $this->close_element_for_append();
5315 $this->currentselector = $selector;
5316 $this->currentelement = $element;
5318 // Create an unclosed element for the streamed content to append into.
5319 $id = uniqid();
5320 $html .= html_writer::start_tag($element, ['id' => $id]);
5321 $html .= html_writer::tag('script', "document.querySelector('$selector').append(document.getElementById('$id'))");
5322 $html .= "\n";
5323 return $html;
5327 * This closes any opened stream elements
5329 * @return string html to be written
5331 public function close_element_for_append() {
5332 $html = '';
5333 if ($this->currentselector !== '') {
5334 $html .= html_writer::end_tag($this->currentelement);
5335 $html .= "\n";
5336 $this->currentelement = '';
5338 return $html;
5342 * A companion method to select_element_for_append
5344 * This must be used with NO_OUTPUT_BUFFERING set to true.
5346 * This is similar but instead of appending into the element it replaces
5347 * the content in the element. Depending on the 3rd argument it can replace
5348 * the innerHTML or the outerHTML which can be useful to completely remove
5349 * the element if needed.
5351 * @param string $selector where new content should be replaced
5352 * @param string $html A chunk of well formed html
5353 * @param bool $outer Wether it replaces the innerHTML or the outerHTML
5354 * @return string html to be written
5356 public function select_element_for_replace(string $selector, string $html, bool $outer = false) {
5358 if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) {
5359 throw new coding_exception('select_element_for_replace used in a non-CLI script without setting NO_OUTPUT_BUFFERING.',
5360 DEBUG_DEVELOPER);
5363 // Escape html for use inside a javascript string.
5364 $html = addslashes_js($html);
5365 $property = $outer ? 'outerHTML' : 'innerHTML';
5366 $output = html_writer::tag('script', "document.querySelector('$selector').$property = '$html';");
5367 $output .= "\n";
5368 return $output;
5373 * A renderer that generates output for command-line scripts.
5375 * The implementation of this renderer is probably incomplete.
5377 * @copyright 2009 Tim Hunt
5378 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5379 * @since Moodle 2.0
5380 * @package core
5381 * @category output
5383 class core_renderer_cli extends core_renderer {
5386 * @var array $progressmaximums stores the largest percentage for a progress bar.
5387 * @return string ascii fragment
5389 private $progressmaximums = [];
5392 * Returns the page header.
5394 * @return string HTML fragment
5396 public function header() {
5397 return $this->page->heading . "\n";
5401 * Renders a Check API result
5403 * To aid in CLI consistency this status is NOT translated and the visual
5404 * width is always exactly 10 chars.
5406 * @param core\check\result $result
5407 * @return string HTML fragment
5409 protected function render_check_result(core\check\result $result) {
5410 $status = $result->get_status();
5412 $labels = [
5413 core\check\result::NA => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' NA ',
5414 core\check\result::OK => ' ' . cli_ansi_format('<colour:green>') . ' OK ',
5415 core\check\result::INFO => ' ' . cli_ansi_format('<colour:blue>' ) . ' INFO ',
5416 core\check\result::UNKNOWN => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' UNKNOWN ',
5417 core\check\result::WARNING => ' ' . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
5418 core\check\result::ERROR => ' ' . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
5419 core\check\result::CRITICAL => '' . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
5421 $string = $labels[$status] . cli_ansi_format('<colour:normal>');
5422 return $string;
5426 * Renders a Check API result
5428 * @param result $result
5429 * @return string fragment
5431 public function check_result(core\check\result $result) {
5432 return $this->render_check_result($result);
5436 * Renders a progress bar.
5438 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
5440 * @param progress_bar $bar The bar.
5441 * @return string ascii fragment
5443 public function render_progress_bar(progress_bar $bar) {
5444 global $CFG;
5446 $size = 55; // The width of the progress bar in chars.
5447 $ascii = "\n";
5449 if (stream_isatty(STDOUT)) {
5450 require_once($CFG->libdir.'/clilib.php');
5452 $ascii .= "[" . str_repeat(' ', $size) . "] 0% \n";
5453 return cli_ansi_format($ascii);
5456 $this->progressmaximums[$bar->get_id()] = 0;
5457 $ascii .= '[';
5458 return $ascii;
5462 * Renders an update to a progress bar.
5464 * Note: This does not cleanly map to a renderable class and should
5465 * never be used directly.
5467 * @param string $id
5468 * @param float $percent
5469 * @param string $msg Message
5470 * @param string $estimate time remaining message
5471 * @return string ascii fragment
5473 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
5474 $size = 55; // The width of the progress bar in chars.
5475 $ascii = '';
5477 // If we are rendering to a terminal then we can safely use ansii codes
5478 // to move the cursor and redraw the complete progress bar each time
5479 // it is updated.
5480 if (stream_isatty(STDOUT)) {
5481 $colour = $percent == 100 ? 'green' : 'blue';
5483 $done = $percent * $size * 0.01;
5484 $whole = floor($done);
5485 $bar = "<colour:$colour>";
5486 $bar .= str_repeat('█', $whole);
5488 if ($whole < $size) {
5489 // By using unicode chars for partial blocks we can have higher
5490 // precision progress bar.
5491 $fraction = floor(($done - $whole) * 8);
5492 $bar .= core_text::substr(' ▏▎▍▌▋▊▉', $fraction, 1);
5494 // Fill the rest of the empty bar.
5495 $bar .= str_repeat(' ', $size - $whole - 1);
5498 $bar .= '<colour:normal>';
5500 if ($estimate) {
5501 $estimate = "- $estimate";
5504 $ascii .= '<cursor:up>';
5505 $ascii .= '<cursor:up>';
5506 $ascii .= sprintf("[$bar] %3.1f%% %-22s\n", $percent, $estimate);
5507 $ascii .= sprintf("%-80s\n", $msg);
5508 return cli_ansi_format($ascii);
5511 // If we are not rendering to a tty, ie when piped to another command
5512 // or on windows we need to progressively render the progress bar
5513 // which can only ever go forwards.
5514 $done = round($percent * $size * 0.01);
5515 $delta = max(0, $done - $this->progressmaximums[$id]);
5517 $ascii .= str_repeat('#', $delta);
5518 if ($percent >= 100 && $delta > 0) {
5519 $ascii .= sprintf("] %3.1f%%\n$msg\n", $percent);
5521 $this->progressmaximums[$id] += $delta;
5522 return $ascii;
5526 * Returns a template fragment representing a Heading.
5528 * @param string $text The text of the heading
5529 * @param int $level The level of importance of the heading
5530 * @param string $classes A space-separated list of CSS classes
5531 * @param string $id An optional ID
5532 * @return string A template fragment for a heading
5534 public function heading($text, $level = 2, $classes = 'main', $id = null) {
5535 $text .= "\n";
5536 switch ($level) {
5537 case 1:
5538 return '=>' . $text;
5539 case 2:
5540 return '-->' . $text;
5541 default:
5542 return $text;
5547 * Returns a template fragment representing a fatal error.
5549 * @param string $message The message to output
5550 * @param string $moreinfourl URL where more info can be found about the error
5551 * @param string $link Link for the Continue button
5552 * @param array $backtrace The execution backtrace
5553 * @param string $debuginfo Debugging information
5554 * @return string A template fragment for a fatal error
5556 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5557 global $CFG;
5559 $output = "!!! $message !!!\n";
5561 if ($CFG->debugdeveloper) {
5562 if (!empty($debuginfo)) {
5563 $output .= $this->notification($debuginfo, 'notifytiny');
5565 if (!empty($backtrace)) {
5566 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
5570 return $output;
5574 * Returns a template fragment representing a notification.
5576 * @param string $message The message to print out.
5577 * @param string $type The type of notification. See constants on \core\output\notification.
5578 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5579 * @return string A template fragment for a notification
5581 public function notification($message, $type = null, $closebutton = true) {
5582 $message = clean_text($message);
5583 if ($type === 'notifysuccess' || $type === 'success') {
5584 return "++ $message ++\n";
5586 return "!! $message !!\n";
5590 * There is no footer for a cli request, however we must override the
5591 * footer method to prevent the default footer.
5593 public function footer() {}
5596 * Render a notification (that is, a status message about something that has
5597 * just happened).
5599 * @param \core\output\notification $notification the notification to print out
5600 * @return string plain text output
5602 public function render_notification(\core\output\notification $notification) {
5603 return $this->notification($notification->get_message(), $notification->get_message_type());
5609 * A renderer that generates output for ajax scripts.
5611 * This renderer prevents accidental sends back only json
5612 * encoded error messages, all other output is ignored.
5614 * @copyright 2010 Petr Skoda
5615 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5616 * @since Moodle 2.0
5617 * @package core
5618 * @category output
5620 class core_renderer_ajax extends core_renderer {
5623 * Returns a template fragment representing a fatal error.
5625 * @param string $message The message to output
5626 * @param string $moreinfourl URL where more info can be found about the error
5627 * @param string $link Link for the Continue button
5628 * @param array $backtrace The execution backtrace
5629 * @param string $debuginfo Debugging information
5630 * @return string A template fragment for a fatal error
5632 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5633 global $CFG;
5635 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
5637 $e = new stdClass();
5638 $e->error = $message;
5639 $e->errorcode = $errorcode;
5640 $e->stacktrace = NULL;
5641 $e->debuginfo = NULL;
5642 $e->reproductionlink = NULL;
5643 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
5644 $link = (string) $link;
5645 if ($link) {
5646 $e->reproductionlink = $link;
5648 if (!empty($debuginfo)) {
5649 $e->debuginfo = $debuginfo;
5651 if (!empty($backtrace)) {
5652 $e->stacktrace = format_backtrace($backtrace, true);
5655 $this->header();
5656 return json_encode($e);
5660 * Used to display a notification.
5661 * For the AJAX notifications are discarded.
5663 * @param string $message The message to print out.
5664 * @param string $type The type of notification. See constants on \core\output\notification.
5665 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5667 public function notification($message, $type = null, $closebutton = true) {
5671 * Used to display a redirection message.
5672 * AJAX redirections should not occur and as such redirection messages
5673 * are discarded.
5675 * @param moodle_url|string $encodedurl
5676 * @param string $message
5677 * @param int $delay
5678 * @param bool $debugdisableredirect
5679 * @param string $messagetype The type of notification to show the message in.
5680 * See constants on \core\output\notification.
5682 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
5683 $messagetype = \core\output\notification::NOTIFY_INFO) {}
5686 * Prepares the start of an AJAX output.
5688 public function header() {
5689 // unfortunately YUI iframe upload does not support application/json
5690 if (!empty($_FILES)) {
5691 @header('Content-type: text/plain; charset=utf-8');
5692 if (!core_useragent::supports_json_contenttype()) {
5693 @header('X-Content-Type-Options: nosniff');
5695 } else if (!core_useragent::supports_json_contenttype()) {
5696 @header('Content-type: text/plain; charset=utf-8');
5697 @header('X-Content-Type-Options: nosniff');
5698 } else {
5699 @header('Content-type: application/json; charset=utf-8');
5702 // Headers to make it not cacheable and json
5703 @header('Cache-Control: no-store, no-cache, must-revalidate');
5704 @header('Cache-Control: post-check=0, pre-check=0', false);
5705 @header('Pragma: no-cache');
5706 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
5707 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
5708 @header('Accept-Ranges: none');
5712 * There is no footer for an AJAX request, however we must override the
5713 * footer method to prevent the default footer.
5715 public function footer() {}
5718 * No need for headers in an AJAX request... this should never happen.
5719 * @param string $text
5720 * @param int $level
5721 * @param string $classes
5722 * @param string $id
5724 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
5730 * The maintenance renderer.
5732 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
5733 * is running a maintenance related task.
5734 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
5736 * @since Moodle 2.6
5737 * @package core
5738 * @category output
5739 * @copyright 2013 Sam Hemelryk
5740 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5742 class core_renderer_maintenance extends core_renderer {
5745 * Initialises the renderer instance.
5747 * @param moodle_page $page
5748 * @param string $target
5749 * @throws coding_exception
5751 public function __construct(moodle_page $page, $target) {
5752 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
5753 throw new coding_exception('Invalid request for the maintenance renderer.');
5755 parent::__construct($page, $target);
5759 * Does nothing. The maintenance renderer cannot produce blocks.
5761 * @param block_contents $bc
5762 * @param string $region
5763 * @return string
5765 public function block(block_contents $bc, $region) {
5766 return '';
5770 * Does nothing. The maintenance renderer cannot produce blocks.
5772 * @param string $region
5773 * @param array $classes
5774 * @param string $tag
5775 * @param boolean $fakeblocksonly
5776 * @return string
5778 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
5779 return '';
5783 * Does nothing. The maintenance renderer cannot produce blocks.
5785 * @param string $region
5786 * @param boolean $fakeblocksonly Output fake block only.
5787 * @return string
5789 public function blocks_for_region($region, $fakeblocksonly = false) {
5790 return '';
5794 * Does nothing. The maintenance renderer cannot produce a course content header.
5796 * @param bool $onlyifnotcalledbefore
5797 * @return string
5799 public function course_content_header($onlyifnotcalledbefore = false) {
5800 return '';
5804 * Does nothing. The maintenance renderer cannot produce a course content footer.
5806 * @param bool $onlyifnotcalledbefore
5807 * @return string
5809 public function course_content_footer($onlyifnotcalledbefore = false) {
5810 return '';
5814 * Does nothing. The maintenance renderer cannot produce a course header.
5816 * @return string
5818 public function course_header() {
5819 return '';
5823 * Does nothing. The maintenance renderer cannot produce a course footer.
5825 * @return string
5827 public function course_footer() {
5828 return '';
5832 * Does nothing. The maintenance renderer cannot produce a custom menu.
5834 * @param string $custommenuitems
5835 * @return string
5837 public function custom_menu($custommenuitems = '') {
5838 return '';
5842 * Does nothing. The maintenance renderer cannot produce a file picker.
5844 * @param array $options
5845 * @return string
5847 public function file_picker($options) {
5848 return '';
5852 * Overridden confirm message for upgrades.
5854 * @param string $message The question to ask the user
5855 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5856 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5857 * @param array $displayoptions optional extra display options
5858 * @return string HTML fragment
5860 public function confirm($message, $continue, $cancel, array $displayoptions = []) {
5861 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5862 // from any previous version of Moodle).
5863 if ($continue instanceof single_button) {
5864 $continue->type = single_button::BUTTON_PRIMARY;
5865 } else if (is_string($continue)) {
5866 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post',
5867 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
5868 } else if ($continue instanceof moodle_url) {
5869 $continue = new single_button($continue, get_string('continue'), 'post',
5870 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
5871 } else {
5872 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5873 ' (string/moodle_url) or a single_button instance.');
5876 if ($cancel instanceof single_button) {
5877 $output = '';
5878 } else if (is_string($cancel)) {
5879 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5880 } else if ($cancel instanceof moodle_url) {
5881 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5882 } else {
5883 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5884 ' (string/moodle_url) or a single_button instance.');
5887 $output = $this->box_start('generalbox', 'notice');
5888 $output .= html_writer::tag('h4', get_string('confirm'));
5889 $output .= html_writer::tag('p', $message);
5890 $output .= html_writer::tag('div', $this->render($cancel) . $this->render($continue), ['class' => 'buttons']);
5891 $output .= $this->box_end();
5892 return $output;
5896 * Does nothing. The maintenance renderer does not support JS.
5898 * @param block_contents $bc
5900 public function init_block_hider_js(block_contents $bc) {
5901 // Does nothing.
5905 * Does nothing. The maintenance renderer cannot produce language menus.
5907 * @return string
5909 public function lang_menu() {
5910 return '';
5914 * Does nothing. The maintenance renderer has no need for login information.
5916 * @param null $withlinks
5917 * @return string
5919 public function login_info($withlinks = null) {
5920 return '';
5924 * Secure login info.
5926 * @return string
5928 public function secure_login_info() {
5929 return $this->login_info(false);
5933 * Does nothing. The maintenance renderer cannot produce user pictures.
5935 * @param stdClass $user
5936 * @param array $options
5937 * @return string
5939 public function user_picture(stdClass $user, array $options = null) {
5940 return '';