MDL-71669 editor_atto: Fire custom event when toggling button highlight
[moodle.git] / lib / outputrenderers.php
blob4c093c428e1c2165a626a67b73d7a028453eef21
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 defined('MOODLE_INTERNAL') || die();
40 /**
41 * Simple base class for Moodle renderers.
43 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
45 * Also has methods to facilitate generating HTML output.
47 * @copyright 2009 Tim Hunt
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 * @since Moodle 2.0
50 * @package core
51 * @category output
53 class renderer_base {
54 /**
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
59 /**
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
62 protected $page;
64 /**
65 * @var string The requested rendering target.
67 protected $target;
69 /**
70 * @var Mustache_Engine $mustache The mustache template compiler
72 private $mustache;
74 /**
75 * Return an instance of the mustache class.
77 * @since 2.9
78 * @return Mustache_Engine
80 protected function get_mustache() {
81 global $CFG;
83 if ($this->mustache === null) {
84 require_once("{$CFG->libdir}/filelib.php");
86 $themename = $this->page->theme->name;
87 $themerev = theme_get_revision();
89 // Create new localcache directory.
90 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
92 // Remove old localcache directories.
93 $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR);
94 foreach ($mustachecachedirs as $localcachedir) {
95 $cachedrev = [];
96 preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
97 $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
98 if ($cachedrev > 0 && $cachedrev < $themerev) {
99 fulldelete($localcachedir);
103 $loader = new \core\output\mustache_filesystem_loader();
104 $stringhelper = new \core\output\mustache_string_helper();
105 $quotehelper = new \core\output\mustache_quote_helper();
106 $jshelper = new \core\output\mustache_javascript_helper($this->page);
107 $pixhelper = new \core\output\mustache_pix_helper($this);
108 $shortentexthelper = new \core\output\mustache_shorten_text_helper();
109 $userdatehelper = new \core\output\mustache_user_date_helper();
111 // We only expose the variables that are exposed to JS templates.
112 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
114 $helpers = array('config' => $safeconfig,
115 'str' => array($stringhelper, 'str'),
116 'quote' => array($quotehelper, 'quote'),
117 'js' => array($jshelper, 'help'),
118 'pix' => array($pixhelper, 'pix'),
119 'shortentext' => array($shortentexthelper, 'shorten'),
120 'userdate' => array($userdatehelper, 'transform'),
123 $this->mustache = new \core\output\mustache_engine(array(
124 'cache' => $cachedir,
125 'escape' => 's',
126 'loader' => $loader,
127 'helpers' => $helpers,
128 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS],
129 // Don't allow the JavaScript helper to be executed from within another
130 // helper. If it's allowed it can be used by users to inject malicious
131 // JS into the page.
132 'disallowednestedhelpers' => ['js']));
136 return $this->mustache;
141 * Constructor
143 * The constructor takes two arguments. The first is the page that the renderer
144 * has been created to assist with, and the second is the target.
145 * The target is an additional identifier that can be used to load different
146 * renderers for different options.
148 * @param moodle_page $page the page we are doing output for.
149 * @param string $target one of rendering target constants
151 public function __construct(moodle_page $page, $target) {
152 $this->opencontainers = $page->opencontainers;
153 $this->page = $page;
154 $this->target = $target;
158 * Renders a template by name with the given context.
160 * The provided data needs to be array/stdClass made up of only simple types.
161 * Simple types are array,stdClass,bool,int,float,string
163 * @since 2.9
164 * @param array|stdClass $context Context containing data for the template.
165 * @return string|boolean
167 public function render_from_template($templatename, $context) {
168 static $templatecache = array();
169 $mustache = $this->get_mustache();
171 try {
172 // Grab a copy of the existing helper to be restored later.
173 $uniqidhelper = $mustache->getHelper('uniqid');
174 } catch (Mustache_Exception_UnknownHelperException $e) {
175 // Helper doesn't exist.
176 $uniqidhelper = null;
179 // Provide 1 random value that will not change within a template
180 // but will be different from template to template. This is useful for
181 // e.g. aria attributes that only work with id attributes and must be
182 // unique in a page.
183 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
184 if (isset($templatecache[$templatename])) {
185 $template = $templatecache[$templatename];
186 } else {
187 try {
188 $template = $mustache->loadTemplate($templatename);
189 $templatecache[$templatename] = $template;
190 } catch (Mustache_Exception_UnknownTemplateException $e) {
191 throw new moodle_exception('Unknown template: ' . $templatename);
195 $renderedtemplate = trim($template->render($context));
197 // If we had an existing uniqid helper then we need to restore it to allow
198 // handle nested calls of render_from_template.
199 if ($uniqidhelper) {
200 $mustache->addHelper('uniqid', $uniqidhelper);
203 return $renderedtemplate;
208 * Returns rendered widget.
210 * The provided widget needs to be an object that extends the renderable
211 * interface.
212 * If will then be rendered by a method based upon the classname for the widget.
213 * For instance a widget of class `crazywidget` will be rendered by a protected
214 * render_crazywidget method of this renderer.
215 * If no render_crazywidget method exists and crazywidget implements templatable,
216 * look for the 'crazywidget' template in the same component and render that.
218 * @param renderable $widget instance with renderable interface
219 * @return string
221 public function render(renderable $widget) {
222 $classparts = explode('\\', get_class($widget));
223 // Strip namespaces.
224 $classname = array_pop($classparts);
225 // Remove _renderable suffixes
226 $classname = preg_replace('/_renderable$/', '', $classname);
228 $rendermethod = 'render_'.$classname;
229 if (method_exists($this, $rendermethod)) {
230 return $this->$rendermethod($widget);
232 if ($widget instanceof templatable) {
233 $component = array_shift($classparts);
234 if (!$component) {
235 $component = 'core';
237 $template = $component . '/' . $classname;
238 $context = $widget->export_for_template($this);
239 return $this->render_from_template($template, $context);
241 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
245 * Adds a JS action for the element with the provided id.
247 * This method adds a JS event for the provided component action to the page
248 * and then returns the id that the event has been attached to.
249 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
251 * @param component_action $action
252 * @param string $id
253 * @return string id of element, either original submitted or random new if not supplied
255 public function add_action_handler(component_action $action, $id = null) {
256 if (!$id) {
257 $id = html_writer::random_id($action->event);
259 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
260 return $id;
264 * Returns true is output has already started, and false if not.
266 * @return boolean true if the header has been printed.
268 public function has_started() {
269 return $this->page->state >= moodle_page::STATE_IN_BODY;
273 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
275 * @param mixed $classes Space-separated string or array of classes
276 * @return string HTML class attribute value
278 public static function prepare_classes($classes) {
279 if (is_array($classes)) {
280 return implode(' ', array_unique($classes));
282 return $classes;
286 * Return the direct URL for an image from the pix folder.
288 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
290 * @deprecated since Moodle 3.3
291 * @param string $imagename the name of the icon.
292 * @param string $component specification of one plugin like in get_string()
293 * @return moodle_url
295 public function pix_url($imagename, $component = 'moodle') {
296 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
297 return $this->page->theme->image_url($imagename, $component);
301 * Return the moodle_url for an image.
303 * The exact image location and extension is determined
304 * automatically by searching for gif|png|jpg|jpeg, please
305 * note there can not be diferent images with the different
306 * extension. The imagename is for historical reasons
307 * a relative path name, it may be changed later for core
308 * images. It is recommended to not use subdirectories
309 * in plugin and theme pix directories.
311 * There are three types of images:
312 * 1/ theme images - stored in theme/mytheme/pix/,
313 * use component 'theme'
314 * 2/ core images - stored in /pix/,
315 * overridden via theme/mytheme/pix_core/
316 * 3/ plugin images - stored in mod/mymodule/pix,
317 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
318 * example: image_url('comment', 'mod_glossary')
320 * @param string $imagename the pathname of the image
321 * @param string $component full plugin name (aka component) or 'theme'
322 * @return moodle_url
324 public function image_url($imagename, $component = 'moodle') {
325 return $this->page->theme->image_url($imagename, $component);
329 * Return the site's logo URL, if any.
331 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
332 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
333 * @return moodle_url|false
335 public function get_logo_url($maxwidth = null, $maxheight = 200) {
336 global $CFG;
337 $logo = get_config('core_admin', 'logo');
338 if (empty($logo)) {
339 return false;
342 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
343 // It's not worth the overhead of detecting and serving 2 different images based on the device.
345 // Hide the requested size in the file path.
346 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
348 // Use $CFG->themerev to prevent browser caching when the file changes.
349 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
350 theme_get_revision(), $logo);
354 * Return the site's compact logo URL, if any.
356 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
357 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
358 * @return moodle_url|false
360 public function get_compact_logo_url($maxwidth = 300, $maxheight = 300) {
361 global $CFG;
362 $logo = get_config('core_admin', 'logocompact');
363 if (empty($logo)) {
364 return false;
367 // Hide the requested size in the file path.
368 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
370 // Use $CFG->themerev to prevent browser caching when the file changes.
371 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
372 theme_get_revision(), $logo);
376 * Whether we should display the logo in the navbar.
378 * We will when there are no main logos, and we have compact logo.
380 * @return bool
382 public function should_display_navbar_logo() {
383 $logo = $this->get_compact_logo_url();
384 return !empty($logo) && !$this->should_display_main_logo();
388 * Whether we should display the main logo.
390 * @param int $headinglevel The heading level we want to check against.
391 * @return bool
393 public function should_display_main_logo($headinglevel = 1) {
395 // Only render the logo if we're on the front page or login page and the we have a logo.
396 $logo = $this->get_logo_url();
397 if ($headinglevel == 1 && !empty($logo)) {
398 if ($this->page->pagelayout == 'frontpage' || $this->page->pagelayout == 'login') {
399 return true;
403 return false;
410 * Basis for all plugin renderers.
412 * @copyright Petr Skoda (skodak)
413 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
414 * @since Moodle 2.0
415 * @package core
416 * @category output
418 class plugin_renderer_base extends renderer_base {
421 * @var renderer_base|core_renderer A reference to the current renderer.
422 * The renderer provided here will be determined by the page but will in 90%
423 * of cases by the {@link core_renderer}
425 protected $output;
428 * Constructor method, calls the parent constructor
430 * @param moodle_page $page
431 * @param string $target one of rendering target constants
433 public function __construct(moodle_page $page, $target) {
434 if (empty($target) && $page->pagelayout === 'maintenance') {
435 // If the page is using the maintenance layout then we're going to force the target to maintenance.
436 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
437 // unavailable for this page layout.
438 $target = RENDERER_TARGET_MAINTENANCE;
440 $this->output = $page->get_renderer('core', null, $target);
441 parent::__construct($page, $target);
445 * Renders the provided widget and returns the HTML to display it.
447 * @param renderable $widget instance with renderable interface
448 * @return string
450 public function render(renderable $widget) {
451 $classname = get_class($widget);
452 // Strip namespaces.
453 $classname = preg_replace('/^.*\\\/', '', $classname);
454 // Keep a copy at this point, we may need to look for a deprecated method.
455 $deprecatedmethod = 'render_'.$classname;
456 // Remove _renderable suffixes
457 $classname = preg_replace('/_renderable$/', '', $classname);
459 $rendermethod = 'render_'.$classname;
460 if (method_exists($this, $rendermethod)) {
461 return $this->$rendermethod($widget);
463 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
464 // This is exactly where we don't want to be.
465 // If you have arrived here you have a renderable component within your plugin that has the name
466 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
467 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
468 // and the _renderable suffix now gets removed when looking for a render method.
469 // You need to change your renderers render_blah_renderable to render_blah.
470 // Until you do this it will not be possible for a theme to override the renderer to override your method.
471 // Please do it ASAP.
472 static $debugged = array();
473 if (!isset($debugged[$deprecatedmethod])) {
474 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
475 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
476 $debugged[$deprecatedmethod] = true;
478 return $this->$deprecatedmethod($widget);
480 // pass to core renderer if method not found here
481 return $this->output->render($widget);
485 * Magic method used to pass calls otherwise meant for the standard renderer
486 * to it to ensure we don't go causing unnecessary grief.
488 * @param string $method
489 * @param array $arguments
490 * @return mixed
492 public function __call($method, $arguments) {
493 if (method_exists('renderer_base', $method)) {
494 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
496 if (method_exists($this->output, $method)) {
497 return call_user_func_array(array($this->output, $method), $arguments);
498 } else {
499 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
506 * The standard implementation of the core_renderer interface.
508 * @copyright 2009 Tim Hunt
509 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
510 * @since Moodle 2.0
511 * @package core
512 * @category output
514 class core_renderer extends renderer_base {
516 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
517 * in layout files instead.
518 * @deprecated
519 * @var string used in {@link core_renderer::header()}.
521 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
524 * @var string Used to pass information from {@link core_renderer::doctype()} to
525 * {@link core_renderer::standard_head_html()}.
527 protected $contenttype;
530 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
531 * with {@link core_renderer::header()}.
533 protected $metarefreshtag = '';
536 * @var string Unique token for the closing HTML
538 protected $unique_end_html_token;
541 * @var string Unique token for performance information
543 protected $unique_performance_info_token;
546 * @var string Unique token for the main content.
548 protected $unique_main_content_token;
550 /** @var custom_menu_item language The language menu if created */
551 protected $language = null;
554 * Constructor
556 * @param moodle_page $page the page we are doing output for.
557 * @param string $target one of rendering target constants
559 public function __construct(moodle_page $page, $target) {
560 $this->opencontainers = $page->opencontainers;
561 $this->page = $page;
562 $this->target = $target;
564 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
565 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
566 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
570 * Get the DOCTYPE declaration that should be used with this page. Designed to
571 * be called in theme layout.php files.
573 * @return string the DOCTYPE declaration that should be used.
575 public function doctype() {
576 if ($this->page->theme->doctype === 'html5') {
577 $this->contenttype = 'text/html; charset=utf-8';
578 return "<!DOCTYPE html>\n";
580 } else if ($this->page->theme->doctype === 'xhtml5') {
581 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
582 return "<!DOCTYPE html>\n";
584 } else {
585 // legacy xhtml 1.0
586 $this->contenttype = 'text/html; charset=utf-8';
587 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
592 * The attributes that should be added to the <html> tag. Designed to
593 * be called in theme layout.php files.
595 * @return string HTML fragment.
597 public function htmlattributes() {
598 $return = get_html_lang(true);
599 $attributes = array();
600 if ($this->page->theme->doctype !== 'html5') {
601 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
604 // Give plugins an opportunity to add things like xml namespaces to the html element.
605 // This function should return an array of html attribute names => values.
606 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
607 foreach ($pluginswithfunction as $plugins) {
608 foreach ($plugins as $function) {
609 $newattrs = $function();
610 unset($newattrs['dir']);
611 unset($newattrs['lang']);
612 unset($newattrs['xmlns']);
613 unset($newattrs['xml:lang']);
614 $attributes += $newattrs;
618 foreach ($attributes as $key => $val) {
619 $val = s($val);
620 $return .= " $key=\"$val\"";
623 return $return;
627 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
628 * that should be included in the <head> tag. Designed to be called in theme
629 * layout.php files.
631 * @return string HTML fragment.
633 public function standard_head_html() {
634 global $CFG, $SESSION, $SITE;
636 // Before we output any content, we need to ensure that certain
637 // page components are set up.
639 // Blocks must be set up early as they may require javascript which
640 // has to be included in the page header before output is created.
641 foreach ($this->page->blocks->get_regions() as $region) {
642 $this->page->blocks->ensure_content_created($region, $this);
645 $output = '';
647 // Give plugins an opportunity to add any head elements. The callback
648 // must always return a string containing valid html head content.
649 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
650 foreach ($pluginswithfunction as $plugins) {
651 foreach ($plugins as $function) {
652 $output .= $function();
656 // Allow a url_rewrite plugin to setup any dynamic head content.
657 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
658 $class = $CFG->urlrewriteclass;
659 $output .= $class::html_head_setup();
662 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
663 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
664 // This is only set by the {@link redirect()} method
665 $output .= $this->metarefreshtag;
667 // Check if a periodic refresh delay has been set and make sure we arn't
668 // already meta refreshing
669 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
670 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
673 // Set up help link popups for all links with the helptooltip class
674 $this->page->requires->js_init_call('M.util.help_popups.setup');
676 $focus = $this->page->focuscontrol;
677 if (!empty($focus)) {
678 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
679 // This is a horrifically bad way to handle focus but it is passed in
680 // through messy formslib::moodleform
681 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
682 } else if (strpos($focus, '.')!==false) {
683 // Old style of focus, bad way to do it
684 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);
685 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
686 } else {
687 // Focus element with given id
688 $this->page->requires->js_function_call('focuscontrol', array($focus));
692 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
693 // any other custom CSS can not be overridden via themes and is highly discouraged
694 $urls = $this->page->theme->css_urls($this->page);
695 foreach ($urls as $url) {
696 $this->page->requires->css_theme($url);
699 // Get the theme javascript head and footer
700 if ($jsurl = $this->page->theme->javascript_url(true)) {
701 $this->page->requires->js($jsurl, true);
703 if ($jsurl = $this->page->theme->javascript_url(false)) {
704 $this->page->requires->js($jsurl);
707 // Get any HTML from the page_requirements_manager.
708 $output .= $this->page->requires->get_head_code($this->page, $this);
710 // List alternate versions.
711 foreach ($this->page->alternateversions as $type => $alt) {
712 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
713 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
716 // Add noindex tag if relevant page and setting applied.
717 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
718 $loginpages = array('login-index', 'login-signup');
719 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
720 if (!isset($CFG->additionalhtmlhead)) {
721 $CFG->additionalhtmlhead = '';
723 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
726 if (!empty($CFG->additionalhtmlhead)) {
727 $output .= "\n".$CFG->additionalhtmlhead;
730 if ($this->page->pagelayout == 'frontpage') {
731 $summary = s(strip_tags(format_text($SITE->summary, FORMAT_HTML)));
732 if (!empty($summary)) {
733 $output .= "<meta name=\"description\" content=\"$summary\" />\n";
737 return $output;
741 * The standard tags (typically skip links) that should be output just inside
742 * the start of the <body> tag. Designed to be called in theme layout.php files.
744 * @return string HTML fragment.
746 public function standard_top_of_body_html() {
747 global $CFG;
748 $output = $this->page->requires->get_top_of_body_code($this);
749 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
750 $output .= "\n".$CFG->additionalhtmltopofbody;
753 // Give subsystems an opportunity to inject extra html content. The callback
754 // must always return a string containing valid html.
755 foreach (\core_component::get_core_subsystems() as $name => $path) {
756 if ($path) {
757 $output .= component_callback($name, 'before_standard_top_of_body_html', [], '');
761 // Give plugins an opportunity to inject extra html content. The callback
762 // must always return a string containing valid html.
763 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
764 foreach ($pluginswithfunction as $plugins) {
765 foreach ($plugins as $function) {
766 $output .= $function();
770 $output .= $this->maintenance_warning();
772 return $output;
776 * Scheduled maintenance warning message.
778 * Note: This is a nasty hack to display maintenance notice, this should be moved
779 * to some general notification area once we have it.
781 * @return string
783 public function maintenance_warning() {
784 global $CFG;
786 $output = '';
787 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
788 $timeleft = $CFG->maintenance_later - time();
789 // If timeleft less than 30 sec, set the class on block to error to highlight.
790 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
791 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-3 alert');
792 $a = new stdClass();
793 $a->hour = (int)($timeleft / 3600);
794 $a->min = (int)(($timeleft / 60) % 60);
795 $a->sec = (int)($timeleft % 60);
796 if ($a->hour > 0) {
797 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
798 } else {
799 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
802 $output .= $this->box_end();
803 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
804 array(array('timeleftinsec' => $timeleft)));
805 $this->page->requires->strings_for_js(
806 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
807 'admin');
809 return $output;
813 * The standard tags (typically performance information and validation links,
814 * if we are in developer debug mode) that should be output in the footer area
815 * of the page. Designed to be called in theme layout.php files.
817 * @return string HTML fragment.
819 public function standard_footer_html() {
820 global $CFG, $SCRIPT;
822 $output = '';
823 if (during_initial_install()) {
824 // Debugging info can not work before install is finished,
825 // in any case we do not want any links during installation!
826 return $output;
829 // Give plugins an opportunity to add any footer elements.
830 // The callback must always return a string containing valid html footer content.
831 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
832 foreach ($pluginswithfunction as $plugins) {
833 foreach ($plugins as $function) {
834 $output .= $function();
838 if (core_userfeedback::can_give_feedback()) {
839 $output .= html_writer::div(
840 $this->render_from_template('core/userfeedback_footer_link', ['url' => core_userfeedback::make_link()->out(false)])
844 // This function is normally called from a layout.php file in {@link core_renderer::header()}
845 // but some of the content won't be known until later, so we return a placeholder
846 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
847 $output .= $this->unique_performance_info_token;
848 if ($this->page->devicetypeinuse == 'legacy') {
849 // The legacy theme is in use print the notification
850 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
853 // Get links to switch device types (only shown for users not on a default device)
854 $output .= $this->theme_switch_links();
856 if (!empty($CFG->debugpageinfo)) {
857 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
858 $this->page->debug_summary()) . '</div>';
860 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
861 // Add link to profiling report if necessary
862 if (function_exists('profiling_is_running') && profiling_is_running()) {
863 $txt = get_string('profiledscript', 'admin');
864 $title = get_string('profiledscriptview', 'admin');
865 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
866 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
867 $output .= '<div class="profilingfooter">' . $link . '</div>';
869 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
870 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
871 $output .= '<div class="purgecaches">' .
872 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
874 if (!empty($CFG->debugvalidators)) {
875 // NOTE: this is not a nice hack, $this->page->url is not always accurate and
876 // $FULLME neither, it is not a bug if it fails. --skodak.
877 $output .= '<div class="validators"><ul class="list-unstyled ml-1">
878 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
879 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
880 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&amp;warnp2n3e=1&amp;url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
881 </ul></div>';
883 return $output;
887 * Returns standard main content placeholder.
888 * Designed to be called in theme layout.php files.
890 * @return string HTML fragment.
892 public function main_content() {
893 // This is here because it is the only place we can inject the "main" role over the entire main content area
894 // without requiring all theme's to manually do it, and without creating yet another thing people need to
895 // remember in the theme.
896 // This is an unfortunate hack. DO NO EVER add anything more here.
897 // DO NOT add classes.
898 // DO NOT add an id.
899 return '<div role="main">'.$this->unique_main_content_token.'</div>';
903 * Returns standard navigation between activities in a course.
905 * @return string the navigation HTML.
907 public function activity_navigation() {
908 // First we should check if we want to add navigation.
909 $context = $this->page->context;
910 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
911 || $context->contextlevel != CONTEXT_MODULE) {
912 return '';
915 // If the activity is in stealth mode, show no links.
916 if ($this->page->cm->is_stealth()) {
917 return '';
920 // Get a list of all the activities in the course.
921 $course = $this->page->cm->get_course();
922 $modules = get_fast_modinfo($course->id)->get_cms();
924 // Put the modules into an array in order by the position they are shown in the course.
925 $mods = [];
926 $activitylist = [];
927 foreach ($modules as $module) {
928 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
929 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
930 continue;
932 $mods[$module->id] = $module;
934 // No need to add the current module to the list for the activity dropdown menu.
935 if ($module->id == $this->page->cm->id) {
936 continue;
938 // Module name.
939 $modname = $module->get_formatted_name();
940 // Display the hidden text if necessary.
941 if (!$module->visible) {
942 $modname .= ' ' . get_string('hiddenwithbrackets');
944 // Module URL.
945 $linkurl = new moodle_url($module->url, array('forceview' => 1));
946 // Add module URL (as key) and name (as value) to the activity list array.
947 $activitylist[$linkurl->out(false)] = $modname;
950 $nummods = count($mods);
952 // If there is only one mod then do nothing.
953 if ($nummods == 1) {
954 return '';
957 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
958 $modids = array_keys($mods);
960 // Get the position in the array of the course module we are viewing.
961 $position = array_search($this->page->cm->id, $modids);
963 $prevmod = null;
964 $nextmod = null;
966 // Check if we have a previous mod to show.
967 if ($position > 0) {
968 $prevmod = $mods[$modids[$position - 1]];
971 // Check if we have a next mod to show.
972 if ($position < ($nummods - 1)) {
973 $nextmod = $mods[$modids[$position + 1]];
976 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
977 $renderer = $this->page->get_renderer('core', 'course');
978 return $renderer->render($activitynav);
982 * The standard tags (typically script tags that are not needed earlier) that
983 * should be output after everything else. Designed to be called in theme layout.php files.
985 * @return string HTML fragment.
987 public function standard_end_of_body_html() {
988 global $CFG;
990 // This function is normally called from a layout.php file in {@link core_renderer::header()}
991 // but some of the content won't be known until later, so we return a placeholder
992 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
993 $output = '';
994 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
995 $output .= "\n".$CFG->additionalhtmlfooter;
997 $output .= $this->unique_end_html_token;
998 return $output;
1002 * The standard HTML that should be output just before the <footer> tag.
1003 * Designed to be called in theme layout.php files.
1005 * @return string HTML fragment.
1007 public function standard_after_main_region_html() {
1008 global $CFG;
1009 $output = '';
1010 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlbottomofbody)) {
1011 $output .= "\n".$CFG->additionalhtmlbottomofbody;
1014 // Give subsystems an opportunity to inject extra html content. The callback
1015 // must always return a string containing valid html.
1016 foreach (\core_component::get_core_subsystems() as $name => $path) {
1017 if ($path) {
1018 $output .= component_callback($name, 'standard_after_main_region_html', [], '');
1022 // Give plugins an opportunity to inject extra html content. The callback
1023 // must always return a string containing valid html.
1024 $pluginswithfunction = get_plugins_with_function('standard_after_main_region_html', 'lib.php');
1025 foreach ($pluginswithfunction as $plugins) {
1026 foreach ($plugins as $function) {
1027 $output .= $function();
1031 return $output;
1035 * Return the standard string that says whether you are logged in (and switched
1036 * roles/logged in as another user).
1037 * @param bool $withlinks if false, then don't include any links in the HTML produced.
1038 * If not set, the default is the nologinlinks option from the theme config.php file,
1039 * and if that is not set, then links are included.
1040 * @return string HTML fragment.
1042 public function login_info($withlinks = null) {
1043 global $USER, $CFG, $DB, $SESSION;
1045 if (during_initial_install()) {
1046 return '';
1049 if (is_null($withlinks)) {
1050 $withlinks = empty($this->page->layout_options['nologinlinks']);
1053 $course = $this->page->course;
1054 if (\core\session\manager::is_loggedinas()) {
1055 $realuser = \core\session\manager::get_realuser();
1056 $fullname = fullname($realuser);
1057 if ($withlinks) {
1058 $loginastitle = get_string('loginas');
1059 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
1060 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
1061 } else {
1062 $realuserinfo = " [$fullname] ";
1064 } else {
1065 $realuserinfo = '';
1068 $loginpage = $this->is_login_page();
1069 $loginurl = get_login_url();
1071 if (empty($course->id)) {
1072 // $course->id is not defined during installation
1073 return '';
1074 } else if (isloggedin()) {
1075 $context = context_course::instance($course->id);
1077 $fullname = fullname($USER);
1078 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
1079 if ($withlinks) {
1080 $linktitle = get_string('viewprofile');
1081 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
1082 } else {
1083 $username = $fullname;
1085 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
1086 if ($withlinks) {
1087 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1088 } else {
1089 $username .= " from {$idprovider->name}";
1092 if (isguestuser()) {
1093 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1094 if (!$loginpage && $withlinks) {
1095 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1097 } else if (is_role_switched($course->id)) { // Has switched roles
1098 $rolename = '';
1099 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1100 $rolename = ': '.role_get_name($role, $context);
1102 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1103 if ($withlinks) {
1104 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1105 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1107 } else {
1108 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1109 if ($withlinks) {
1110 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1113 } else {
1114 $loggedinas = get_string('loggedinnot', 'moodle');
1115 if (!$loginpage && $withlinks) {
1116 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1120 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1122 if (isset($SESSION->justloggedin)) {
1123 unset($SESSION->justloggedin);
1124 if (!empty($CFG->displayloginfailures)) {
1125 if (!isguestuser()) {
1126 // Include this file only when required.
1127 require_once($CFG->dirroot . '/user/lib.php');
1128 if ($count = user_count_login_failures($USER)) {
1129 $loggedinas .= '<div class="loginfailures">';
1130 $a = new stdClass();
1131 $a->attempts = $count;
1132 $loggedinas .= get_string('failedloginattempts', '', $a);
1133 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1134 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1135 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1137 $loggedinas .= '</div>';
1143 return $loggedinas;
1147 * Check whether the current page is a login page.
1149 * @since Moodle 2.9
1150 * @return bool
1152 protected function is_login_page() {
1153 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1154 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1155 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1156 return in_array(
1157 $this->page->url->out_as_local_url(false, array()),
1158 array(
1159 '/login/index.php',
1160 '/login/forgot_password.php',
1166 * Return the 'back' link that normally appears in the footer.
1168 * @return string HTML fragment.
1170 public function home_link() {
1171 global $CFG, $SITE;
1173 if ($this->page->pagetype == 'site-index') {
1174 // Special case for site home page - please do not remove
1175 return '<div class="sitelink">' .
1176 '<a title="Moodle" class="d-inline-block aalink" href="http://moodle.org/">' .
1177 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1179 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1180 // Special case for during install/upgrade.
1181 return '<div class="sitelink">'.
1182 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1183 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1185 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1186 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1187 get_string('home') . '</a></div>';
1189 } else {
1190 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1191 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1196 * Redirects the user by any means possible given the current state
1198 * This function should not be called directly, it should always be called using
1199 * the redirect function in lib/weblib.php
1201 * The redirect function should really only be called before page output has started
1202 * however it will allow itself to be called during the state STATE_IN_BODY
1204 * @param string $encodedurl The URL to send to encoded if required
1205 * @param string $message The message to display to the user if any
1206 * @param int $delay The delay before redirecting a user, if $message has been
1207 * set this is a requirement and defaults to 3, set to 0 no delay
1208 * @param boolean $debugdisableredirect this redirect has been disabled for
1209 * debugging purposes. Display a message that explains, and don't
1210 * trigger the redirect.
1211 * @param string $messagetype The type of notification to show the message in.
1212 * See constants on \core\output\notification.
1213 * @return string The HTML to display to the user before dying, may contain
1214 * meta refresh, javascript refresh, and may have set header redirects
1216 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1217 $messagetype = \core\output\notification::NOTIFY_INFO) {
1218 global $CFG;
1219 $url = str_replace('&amp;', '&', $encodedurl);
1221 switch ($this->page->state) {
1222 case moodle_page::STATE_BEFORE_HEADER :
1223 // No output yet it is safe to delivery the full arsenal of redirect methods
1224 if (!$debugdisableredirect) {
1225 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1226 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1227 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1229 $output = $this->header();
1230 break;
1231 case moodle_page::STATE_PRINTING_HEADER :
1232 // We should hopefully never get here
1233 throw new coding_exception('You cannot redirect while printing the page header');
1234 break;
1235 case moodle_page::STATE_IN_BODY :
1236 // We really shouldn't be here but we can deal with this
1237 debugging("You should really redirect before you start page output");
1238 if (!$debugdisableredirect) {
1239 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1241 $output = $this->opencontainers->pop_all_but_last();
1242 break;
1243 case moodle_page::STATE_DONE :
1244 // Too late to be calling redirect now
1245 throw new coding_exception('You cannot redirect after the entire page has been generated');
1246 break;
1248 $output .= $this->notification($message, $messagetype);
1249 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1250 if ($debugdisableredirect) {
1251 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1253 $output .= $this->footer();
1254 return $output;
1258 * Start output by sending the HTTP headers, and printing the HTML <head>
1259 * and the start of the <body>.
1261 * To control what is printed, you should set properties on $PAGE.
1263 * @return string HTML that you must output this, preferably immediately.
1265 public function header() {
1266 global $USER, $CFG, $SESSION;
1268 // Give plugins an opportunity touch things before the http headers are sent
1269 // such as adding additional headers. The return value is ignored.
1270 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1271 foreach ($pluginswithfunction as $plugins) {
1272 foreach ($plugins as $function) {
1273 $function();
1277 if (\core\session\manager::is_loggedinas()) {
1278 $this->page->add_body_class('userloggedinas');
1281 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1282 require_once($CFG->dirroot . '/user/lib.php');
1283 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1284 if ($count = user_count_login_failures($USER, false)) {
1285 $this->page->add_body_class('loginfailures');
1289 // If the user is logged in, and we're not in initial install,
1290 // check to see if the user is role-switched and add the appropriate
1291 // CSS class to the body element.
1292 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1293 $this->page->add_body_class('userswitchedrole');
1296 // Give themes a chance to init/alter the page object.
1297 $this->page->theme->init_page($this->page);
1299 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1301 // Find the appropriate page layout file, based on $this->page->pagelayout.
1302 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1303 // Render the layout using the layout file.
1304 $rendered = $this->render_page_layout($layoutfile);
1306 // Slice the rendered output into header and footer.
1307 $cutpos = strpos($rendered, $this->unique_main_content_token);
1308 if ($cutpos === false) {
1309 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1310 $token = self::MAIN_CONTENT_TOKEN;
1311 } else {
1312 $token = $this->unique_main_content_token;
1315 if ($cutpos === false) {
1316 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.');
1318 $header = substr($rendered, 0, $cutpos);
1319 $footer = substr($rendered, $cutpos + strlen($token));
1321 if (empty($this->contenttype)) {
1322 debugging('The page layout file did not call $OUTPUT->doctype()');
1323 $header = $this->doctype() . $header;
1326 // If this theme version is below 2.4 release and this is a course view page
1327 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1328 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1329 // check if course content header/footer have not been output during render of theme layout
1330 $coursecontentheader = $this->course_content_header(true);
1331 $coursecontentfooter = $this->course_content_footer(true);
1332 if (!empty($coursecontentheader)) {
1333 // display debug message and add header and footer right above and below main content
1334 // Please note that course header and footer (to be displayed above and below the whole page)
1335 // are not displayed in this case at all.
1336 // Besides the content header and footer are not displayed on any other course page
1337 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);
1338 $header .= $coursecontentheader;
1339 $footer = $coursecontentfooter. $footer;
1343 send_headers($this->contenttype, $this->page->cacheable);
1345 $this->opencontainers->push('header/footer', $footer);
1346 $this->page->set_state(moodle_page::STATE_IN_BODY);
1348 return $header . $this->skip_link_target('maincontent');
1352 * Renders and outputs the page layout file.
1354 * This is done by preparing the normal globals available to a script, and
1355 * then including the layout file provided by the current theme for the
1356 * requested layout.
1358 * @param string $layoutfile The name of the layout file
1359 * @return string HTML code
1361 protected function render_page_layout($layoutfile) {
1362 global $CFG, $SITE, $USER;
1363 // The next lines are a bit tricky. The point is, here we are in a method
1364 // of a renderer class, and this object may, or may not, be the same as
1365 // the global $OUTPUT object. When rendering the page layout file, we want to use
1366 // this object. However, people writing Moodle code expect the current
1367 // renderer to be called $OUTPUT, not $this, so define a variable called
1368 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1369 $OUTPUT = $this;
1370 $PAGE = $this->page;
1371 $COURSE = $this->page->course;
1373 ob_start();
1374 include($layoutfile);
1375 $rendered = ob_get_contents();
1376 ob_end_clean();
1377 return $rendered;
1381 * Outputs the page's footer
1383 * @return string HTML fragment
1385 public function footer() {
1386 global $CFG, $DB;
1388 $output = '';
1390 // Give plugins an opportunity to touch the page before JS is finalized.
1391 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1392 foreach ($pluginswithfunction as $plugins) {
1393 foreach ($plugins as $function) {
1394 $extrafooter = $function();
1395 if (is_string($extrafooter)) {
1396 $output .= $extrafooter;
1401 $output .= $this->container_end_all(true);
1403 $footer = $this->opencontainers->pop('header/footer');
1405 if (debugging() and $DB and $DB->is_transaction_started()) {
1406 // TODO: MDL-20625 print warning - transaction will be rolled back
1409 // Provide some performance info if required
1410 $performanceinfo = '';
1411 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1412 $perf = get_performance_info();
1413 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1414 $performanceinfo = $perf['html'];
1418 // We always want performance data when running a performance test, even if the user is redirected to another page.
1419 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1420 $footer = $this->unique_performance_info_token . $footer;
1422 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1424 // Only show notifications when the current page has a context id.
1425 if (!empty($this->page->context->id)) {
1426 $this->page->requires->js_call_amd('core/notification', 'init', array(
1427 $this->page->context->id,
1428 \core\notification::fetch_as_array($this)
1431 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1433 $this->page->set_state(moodle_page::STATE_DONE);
1435 return $output . $footer;
1439 * Close all but the last open container. This is useful in places like error
1440 * handling, where you want to close all the open containers (apart from <body>)
1441 * before outputting the error message.
1443 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1444 * developer debug warning if it isn't.
1445 * @return string the HTML required to close any open containers inside <body>.
1447 public function container_end_all($shouldbenone = false) {
1448 return $this->opencontainers->pop_all_but_last($shouldbenone);
1452 * Returns course-specific information to be output immediately above content on any course page
1453 * (for the current course)
1455 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1456 * @return string
1458 public function course_content_header($onlyifnotcalledbefore = false) {
1459 global $CFG;
1460 static $functioncalled = false;
1461 if ($functioncalled && $onlyifnotcalledbefore) {
1462 // we have already output the content header
1463 return '';
1466 // Output any session notification.
1467 $notifications = \core\notification::fetch();
1469 $bodynotifications = '';
1470 foreach ($notifications as $notification) {
1471 $bodynotifications .= $this->render_from_template(
1472 $notification->get_template_name(),
1473 $notification->export_for_template($this)
1477 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1479 if ($this->page->course->id == SITEID) {
1480 // return immediately and do not include /course/lib.php if not necessary
1481 return $output;
1484 require_once($CFG->dirroot.'/course/lib.php');
1485 $functioncalled = true;
1486 $courseformat = course_get_format($this->page->course);
1487 if (($obj = $courseformat->course_content_header()) !== null) {
1488 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1490 return $output;
1494 * Returns course-specific information to be output immediately below content on any course page
1495 * (for the current course)
1497 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1498 * @return string
1500 public function course_content_footer($onlyifnotcalledbefore = false) {
1501 global $CFG;
1502 if ($this->page->course->id == SITEID) {
1503 // return immediately and do not include /course/lib.php if not necessary
1504 return '';
1506 static $functioncalled = false;
1507 if ($functioncalled && $onlyifnotcalledbefore) {
1508 // we have already output the content footer
1509 return '';
1511 $functioncalled = true;
1512 require_once($CFG->dirroot.'/course/lib.php');
1513 $courseformat = course_get_format($this->page->course);
1514 if (($obj = $courseformat->course_content_footer()) !== null) {
1515 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1517 return '';
1521 * Returns course-specific information to be output on any course page in the header area
1522 * (for the current course)
1524 * @return string
1526 public function course_header() {
1527 global $CFG;
1528 if ($this->page->course->id == SITEID) {
1529 // return immediately and do not include /course/lib.php if not necessary
1530 return '';
1532 require_once($CFG->dirroot.'/course/lib.php');
1533 $courseformat = course_get_format($this->page->course);
1534 if (($obj = $courseformat->course_header()) !== null) {
1535 return $courseformat->get_renderer($this->page)->render($obj);
1537 return '';
1541 * Returns course-specific information to be output on any course page in the footer area
1542 * (for the current course)
1544 * @return string
1546 public function course_footer() {
1547 global $CFG;
1548 if ($this->page->course->id == SITEID) {
1549 // return immediately and do not include /course/lib.php if not necessary
1550 return '';
1552 require_once($CFG->dirroot.'/course/lib.php');
1553 $courseformat = course_get_format($this->page->course);
1554 if (($obj = $courseformat->course_footer()) !== null) {
1555 return $courseformat->get_renderer($this->page)->render($obj);
1557 return '';
1561 * Get the course pattern datauri to show on a course card.
1563 * The datauri is an encoded svg that can be passed as a url.
1564 * @param int $id Id to use when generating the pattern
1565 * @return string datauri
1567 public function get_generated_image_for_id($id) {
1568 $color = $this->get_generated_color_for_id($id);
1569 $pattern = new \core_geopattern();
1570 $pattern->setColor($color);
1571 $pattern->patternbyid($id);
1572 return $pattern->datauri();
1576 * Get the course color to show on a course card.
1578 * @param int $id Id to use when generating the color.
1579 * @return string hex color code.
1581 public function get_generated_color_for_id($id) {
1582 $colornumbers = range(1, 10);
1583 $basecolors = [];
1584 foreach ($colornumbers as $number) {
1585 $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1588 $color = $basecolors[$id % 10];
1589 return $color;
1593 * Returns lang menu or '', this method also checks forcing of languages in courses.
1595 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1597 * @return string The lang menu HTML or empty string
1599 public function lang_menu() {
1600 global $CFG;
1602 if (empty($CFG->langmenu)) {
1603 return '';
1606 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1607 // do not show lang menu if language forced
1608 return '';
1611 $currlang = current_language();
1612 $langs = get_string_manager()->get_list_of_translations();
1614 if (count($langs) < 2) {
1615 return '';
1618 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1619 $s->label = get_accesshide(get_string('language'));
1620 $s->class = 'langmenu';
1621 return $this->render($s);
1625 * Output the row of editing icons for a block, as defined by the controls array.
1627 * @param array $controls an array like {@link block_contents::$controls}.
1628 * @param string $blockid The ID given to the block.
1629 * @return string HTML fragment.
1631 public function block_controls($actions, $blockid = null) {
1632 global $CFG;
1633 if (empty($actions)) {
1634 return '';
1636 $menu = new action_menu($actions);
1637 if ($blockid !== null) {
1638 $menu->set_owner_selector('#'.$blockid);
1640 $menu->set_constraint('.block-region');
1641 $menu->attributes['class'] .= ' block-control-actions commands';
1642 return $this->render($menu);
1646 * Returns the HTML for a basic textarea field.
1648 * @param string $name Name to use for the textarea element
1649 * @param string $id The id to use fort he textarea element
1650 * @param string $value Initial content to display in the textarea
1651 * @param int $rows Number of rows to display
1652 * @param int $cols Number of columns to display
1653 * @return string the HTML to display
1655 public function print_textarea($name, $id, $value, $rows, $cols) {
1656 editors_head_setup();
1657 $editor = editors_get_preferred_editor(FORMAT_HTML);
1658 $editor->set_text($value);
1659 $editor->use_editor($id, []);
1661 $context = [
1662 'id' => $id,
1663 'name' => $name,
1664 'value' => $value,
1665 'rows' => $rows,
1666 'cols' => $cols
1669 return $this->render_from_template('core_form/editor_textarea', $context);
1673 * Renders an action menu component.
1675 * @param action_menu $menu
1676 * @return string HTML
1678 public function render_action_menu(action_menu $menu) {
1680 // We don't want the class icon there!
1681 foreach ($menu->get_secondary_actions() as $action) {
1682 if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1683 $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1687 if ($menu->is_empty()) {
1688 return '';
1690 $context = $menu->export_for_template($this);
1692 return $this->render_from_template('core/action_menu', $context);
1696 * Renders a Check API result
1698 * @param result $result
1699 * @return string HTML fragment
1701 protected function render_check_result(core\check\result $result) {
1702 return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1706 * Renders a Check API result
1708 * @param result $result
1709 * @return string HTML fragment
1711 public function check_result(core\check\result $result) {
1712 return $this->render_check_result($result);
1716 * Renders an action_menu_link item.
1718 * @param action_menu_link $action
1719 * @return string HTML fragment
1721 protected function render_action_menu_link(action_menu_link $action) {
1722 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1726 * Renders a primary action_menu_filler item.
1728 * @param action_menu_link_filler $action
1729 * @return string HTML fragment
1731 protected function render_action_menu_filler(action_menu_filler $action) {
1732 return html_writer::span('&nbsp;', 'filler');
1736 * Renders a primary action_menu_link item.
1738 * @param action_menu_link_primary $action
1739 * @return string HTML fragment
1741 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1742 return $this->render_action_menu_link($action);
1746 * Renders a secondary action_menu_link item.
1748 * @param action_menu_link_secondary $action
1749 * @return string HTML fragment
1751 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1752 return $this->render_action_menu_link($action);
1756 * Prints a nice side block with an optional header.
1758 * @param block_contents $bc HTML for the content
1759 * @param string $region the region the block is appearing in.
1760 * @return string the HTML to be output.
1762 public function block(block_contents $bc, $region) {
1763 $bc = clone($bc); // Avoid messing up the object passed in.
1764 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1765 $bc->collapsible = block_contents::NOT_HIDEABLE;
1768 $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1769 $context = new stdClass();
1770 $context->skipid = $bc->skipid;
1771 $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
1772 $context->dockable = $bc->dockable;
1773 $context->id = $id;
1774 $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1775 $context->skiptitle = strip_tags($bc->title);
1776 $context->showskiplink = !empty($context->skiptitle);
1777 $context->arialabel = $bc->arialabel;
1778 $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
1779 $context->class = $bc->attributes['class'];
1780 $context->type = $bc->attributes['data-block'];
1781 $context->title = $bc->title;
1782 $context->content = $bc->content;
1783 $context->annotation = $bc->annotation;
1784 $context->footer = $bc->footer;
1785 $context->hascontrols = !empty($bc->controls);
1786 if ($context->hascontrols) {
1787 $context->controls = $this->block_controls($bc->controls, $id);
1790 return $this->render_from_template('core/block', $context);
1794 * Render the contents of a block_list.
1796 * @param array $icons the icon for each item.
1797 * @param array $items the content of each item.
1798 * @return string HTML
1800 public function list_block_contents($icons, $items) {
1801 $row = 0;
1802 $lis = array();
1803 foreach ($items as $key => $string) {
1804 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1805 if (!empty($icons[$key])) { //test if the content has an assigned icon
1806 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1808 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1809 $item .= html_writer::end_tag('li');
1810 $lis[] = $item;
1811 $row = 1 - $row; // Flip even/odd.
1813 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1817 * Output all the blocks in a particular region.
1819 * @param string $region the name of a region on this page.
1820 * @return string the HTML to be output.
1822 public function blocks_for_region($region) {
1823 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1824 $lastblock = null;
1825 $zones = array();
1826 foreach ($blockcontents as $bc) {
1827 if ($bc instanceof block_contents) {
1828 $zones[] = $bc->title;
1831 $output = '';
1833 foreach ($blockcontents as $bc) {
1834 if ($bc instanceof block_contents) {
1835 $output .= $this->block($bc, $region);
1836 $lastblock = $bc->title;
1837 } else if ($bc instanceof block_move_target) {
1838 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1839 } else {
1840 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1843 return $output;
1847 * Output a place where the block that is currently being moved can be dropped.
1849 * @param block_move_target $target with the necessary details.
1850 * @param array $zones array of areas where the block can be moved to
1851 * @param string $previous the block located before the area currently being rendered.
1852 * @param string $region the name of the region
1853 * @return string the HTML to be output.
1855 public function block_move_target($target, $zones, $previous, $region) {
1856 if ($previous == null) {
1857 if (empty($zones)) {
1858 // There are no zones, probably because there are no blocks.
1859 $regions = $this->page->theme->get_all_block_regions();
1860 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1861 } else {
1862 $position = get_string('moveblockbefore', 'block', $zones[0]);
1864 } else {
1865 $position = get_string('moveblockafter', 'block', $previous);
1867 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1871 * Renders a special html link with attached action
1873 * Theme developers: DO NOT OVERRIDE! Please override function
1874 * {@link core_renderer::render_action_link()} instead.
1876 * @param string|moodle_url $url
1877 * @param string $text HTML fragment
1878 * @param component_action $action
1879 * @param array $attributes associative array of html link attributes + disabled
1880 * @param pix_icon optional pix icon to render with the link
1881 * @return string HTML fragment
1883 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1884 if (!($url instanceof moodle_url)) {
1885 $url = new moodle_url($url);
1887 $link = new action_link($url, $text, $action, $attributes, $icon);
1889 return $this->render($link);
1893 * Renders an action_link object.
1895 * The provided link is renderer and the HTML returned. At the same time the
1896 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1898 * @param action_link $link
1899 * @return string HTML fragment
1901 protected function render_action_link(action_link $link) {
1902 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1906 * Renders an action_icon.
1908 * This function uses the {@link core_renderer::action_link()} method for the
1909 * most part. What it does different is prepare the icon as HTML and use it
1910 * as the link text.
1912 * Theme developers: If you want to change how action links and/or icons are rendered,
1913 * consider overriding function {@link core_renderer::render_action_link()} and
1914 * {@link core_renderer::render_pix_icon()}.
1916 * @param string|moodle_url $url A string URL or moodel_url
1917 * @param pix_icon $pixicon
1918 * @param component_action $action
1919 * @param array $attributes associative array of html link attributes + disabled
1920 * @param bool $linktext show title next to image in link
1921 * @return string HTML fragment
1923 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1924 if (!($url instanceof moodle_url)) {
1925 $url = new moodle_url($url);
1927 $attributes = (array)$attributes;
1929 if (empty($attributes['class'])) {
1930 // let ppl override the class via $options
1931 $attributes['class'] = 'action-icon';
1934 $icon = $this->render($pixicon);
1936 if ($linktext) {
1937 $text = $pixicon->attributes['alt'];
1938 } else {
1939 $text = '';
1942 return $this->action_link($url, $text.$icon, $action, $attributes);
1946 * Print a message along with button choices for Continue/Cancel
1948 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1950 * @param string $message The question to ask the user
1951 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1952 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1953 * @return string HTML fragment
1955 public function confirm($message, $continue, $cancel) {
1956 if ($continue instanceof single_button) {
1957 // ok
1958 $continue->primary = true;
1959 } else if (is_string($continue)) {
1960 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1961 } else if ($continue instanceof moodle_url) {
1962 $continue = new single_button($continue, get_string('continue'), 'post', true);
1963 } else {
1964 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1967 if ($cancel instanceof single_button) {
1968 // ok
1969 } else if (is_string($cancel)) {
1970 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1971 } else if ($cancel instanceof moodle_url) {
1972 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1973 } else {
1974 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1977 $attributes = [
1978 'role'=>'alertdialog',
1979 'aria-labelledby'=>'modal-header',
1980 'aria-describedby'=>'modal-body',
1981 'aria-modal'=>'true'
1984 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
1985 $output .= $this->box_start('modal-content', 'modal-content');
1986 $output .= $this->box_start('modal-header px-3', 'modal-header');
1987 $output .= html_writer::tag('h4', get_string('confirm'));
1988 $output .= $this->box_end();
1989 $attributes = [
1990 'role'=>'alert',
1991 'data-aria-autofocus'=>'true'
1993 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
1994 $output .= html_writer::tag('p', $message);
1995 $output .= $this->box_end();
1996 $output .= $this->box_start('modal-footer', 'modal-footer');
1997 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1998 $output .= $this->box_end();
1999 $output .= $this->box_end();
2000 $output .= $this->box_end();
2001 return $output;
2005 * Returns a form with a single button.
2007 * Theme developers: DO NOT OVERRIDE! Please override function
2008 * {@link core_renderer::render_single_button()} instead.
2010 * @param string|moodle_url $url
2011 * @param string $label button text
2012 * @param string $method get or post submit method
2013 * @param array $options associative array {disabled, title, etc.}
2014 * @return string HTML fragment
2016 public function single_button($url, $label, $method='post', array $options=null) {
2017 if (!($url instanceof moodle_url)) {
2018 $url = new moodle_url($url);
2020 $button = new single_button($url, $label, $method);
2022 foreach ((array)$options as $key=>$value) {
2023 if (property_exists($button, $key)) {
2024 $button->$key = $value;
2025 } else {
2026 $button->set_attribute($key, $value);
2030 return $this->render($button);
2034 * Renders a single button widget.
2036 * This will return HTML to display a form containing a single button.
2038 * @param single_button $button
2039 * @return string HTML fragment
2041 protected function render_single_button(single_button $button) {
2042 return $this->render_from_template('core/single_button', $button->export_for_template($this));
2046 * Returns a form with a single select widget.
2048 * Theme developers: DO NOT OVERRIDE! Please override function
2049 * {@link core_renderer::render_single_select()} instead.
2051 * @param moodle_url $url form action target, includes hidden fields
2052 * @param string $name name of selection field - the changing parameter in url
2053 * @param array $options list of options
2054 * @param string $selected selected element
2055 * @param array $nothing
2056 * @param string $formid
2057 * @param array $attributes other attributes for the single select
2058 * @return string HTML fragment
2060 public function single_select($url, $name, array $options, $selected = '',
2061 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2062 if (!($url instanceof moodle_url)) {
2063 $url = new moodle_url($url);
2065 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2067 if (array_key_exists('label', $attributes)) {
2068 $select->set_label($attributes['label']);
2069 unset($attributes['label']);
2071 $select->attributes = $attributes;
2073 return $this->render($select);
2077 * Returns a dataformat selection and download form
2079 * @param string $label A text label
2080 * @param moodle_url|string $base The download page url
2081 * @param string $name The query param which will hold the type of the download
2082 * @param array $params Extra params sent to the download page
2083 * @return string HTML fragment
2085 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2087 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2088 $options = array();
2089 foreach ($formats as $format) {
2090 if ($format->is_enabled()) {
2091 $options[] = array(
2092 'value' => $format->name,
2093 'label' => get_string('dataformat', $format->component),
2097 $hiddenparams = array();
2098 foreach ($params as $key => $value) {
2099 $hiddenparams[] = array(
2100 'name' => $key,
2101 'value' => $value,
2104 $data = array(
2105 'label' => $label,
2106 'base' => $base,
2107 'name' => $name,
2108 'params' => $hiddenparams,
2109 'options' => $options,
2110 'sesskey' => sesskey(),
2111 'submit' => get_string('download'),
2114 return $this->render_from_template('core/dataformat_selector', $data);
2119 * Internal implementation of single_select rendering
2121 * @param single_select $select
2122 * @return string HTML fragment
2124 protected function render_single_select(single_select $select) {
2125 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2129 * Returns a form with a url select widget.
2131 * Theme developers: DO NOT OVERRIDE! Please override function
2132 * {@link core_renderer::render_url_select()} instead.
2134 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2135 * @param string $selected selected element
2136 * @param array $nothing
2137 * @param string $formid
2138 * @return string HTML fragment
2140 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2141 $select = new url_select($urls, $selected, $nothing, $formid);
2142 return $this->render($select);
2146 * Internal implementation of url_select rendering
2148 * @param url_select $select
2149 * @return string HTML fragment
2151 protected function render_url_select(url_select $select) {
2152 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2156 * Returns a string containing a link to the user documentation.
2157 * Also contains an icon by default. Shown to teachers and admin only.
2159 * @param string $path The page link after doc root and language, no leading slash.
2160 * @param string $text The text to be displayed for the link
2161 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2162 * @param array $attributes htm attributes
2163 * @return string
2165 public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
2166 global $CFG;
2168 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2170 $attributes['href'] = new moodle_url(get_docs_url($path));
2171 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2172 $attributes['class'] = 'helplinkpopup';
2175 return html_writer::tag('a', $icon.$text, $attributes);
2179 * Return HTML for an image_icon.
2181 * Theme developers: DO NOT OVERRIDE! Please override function
2182 * {@link core_renderer::render_image_icon()} instead.
2184 * @param string $pix short pix name
2185 * @param string $alt mandatory alt attribute
2186 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2187 * @param array $attributes htm attributes
2188 * @return string HTML fragment
2190 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2191 $icon = new image_icon($pix, $alt, $component, $attributes);
2192 return $this->render($icon);
2196 * Renders a pix_icon widget and returns the HTML to display it.
2198 * @param image_icon $icon
2199 * @return string HTML fragment
2201 protected function render_image_icon(image_icon $icon) {
2202 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2203 return $system->render_pix_icon($this, $icon);
2207 * Return HTML for a pix_icon.
2209 * Theme developers: DO NOT OVERRIDE! Please override function
2210 * {@link core_renderer::render_pix_icon()} instead.
2212 * @param string $pix short pix name
2213 * @param string $alt mandatory alt attribute
2214 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2215 * @param array $attributes htm lattributes
2216 * @return string HTML fragment
2218 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2219 $icon = new pix_icon($pix, $alt, $component, $attributes);
2220 return $this->render($icon);
2224 * Renders a pix_icon widget and returns the HTML to display it.
2226 * @param pix_icon $icon
2227 * @return string HTML fragment
2229 protected function render_pix_icon(pix_icon $icon) {
2230 $system = \core\output\icon_system::instance();
2231 return $system->render_pix_icon($this, $icon);
2235 * Return HTML to display an emoticon icon.
2237 * @param pix_emoticon $emoticon
2238 * @return string HTML fragment
2240 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2241 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2242 return $system->render_pix_icon($this, $emoticon);
2246 * Produces the html that represents this rating in the UI
2248 * @param rating $rating the page object on which this rating will appear
2249 * @return string
2251 function render_rating(rating $rating) {
2252 global $CFG, $USER;
2254 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2255 return null;//ratings are turned off
2258 $ratingmanager = new rating_manager();
2259 // Initialise the JavaScript so ratings can be done by AJAX.
2260 $ratingmanager->initialise_rating_javascript($this->page);
2262 $strrate = get_string("rate", "rating");
2263 $ratinghtml = ''; //the string we'll return
2265 // permissions check - can they view the aggregate?
2266 if ($rating->user_can_view_aggregate()) {
2268 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2269 $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2270 $aggregatestr = $rating->get_aggregate_string();
2272 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2273 if ($rating->count > 0) {
2274 $countstr = "({$rating->count})";
2275 } else {
2276 $countstr = '-';
2278 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2280 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2282 $nonpopuplink = $rating->get_view_ratings_url();
2283 $popuplink = $rating->get_view_ratings_url(true);
2285 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2286 $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
2289 $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
2292 $formstart = null;
2293 // if the item doesn't belong to the current user, the user has permission to rate
2294 // and we're within the assessable period
2295 if ($rating->user_can_rate()) {
2297 $rateurl = $rating->get_rate_url();
2298 $inputs = $rateurl->params();
2300 //start the rating form
2301 $formattrs = array(
2302 'id' => "postrating{$rating->itemid}",
2303 'class' => 'postratingform',
2304 'method' => 'post',
2305 'action' => $rateurl->out_omit_querystring()
2307 $formstart = html_writer::start_tag('form', $formattrs);
2308 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2310 // add the hidden inputs
2311 foreach ($inputs as $name => $value) {
2312 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2313 $formstart .= html_writer::empty_tag('input', $attributes);
2316 if (empty($ratinghtml)) {
2317 $ratinghtml .= $strrate.': ';
2319 $ratinghtml = $formstart.$ratinghtml;
2321 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2322 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2323 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2324 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2326 //output submit button
2327 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2329 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2330 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2332 if (!$rating->settings->scale->isnumeric) {
2333 // If a global scale, try to find current course ID from the context
2334 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2335 $courseid = $coursecontext->instanceid;
2336 } else {
2337 $courseid = $rating->settings->scale->courseid;
2339 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2341 $ratinghtml .= html_writer::end_tag('span');
2342 $ratinghtml .= html_writer::end_tag('div');
2343 $ratinghtml .= html_writer::end_tag('form');
2346 return $ratinghtml;
2350 * Centered heading with attached help button (same title text)
2351 * and optional icon attached.
2353 * @param string $text A heading text
2354 * @param string $helpidentifier The keyword that defines a help page
2355 * @param string $component component name
2356 * @param string|moodle_url $icon
2357 * @param string $iconalt icon alt text
2358 * @param int $level The level of importance of the heading. Defaulting to 2
2359 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2360 * @return string HTML fragment
2362 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2363 $image = '';
2364 if ($icon) {
2365 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2368 $help = '';
2369 if ($helpidentifier) {
2370 $help = $this->help_icon($helpidentifier, $component);
2373 return $this->heading($image.$text.$help, $level, $classnames);
2377 * Returns HTML to display a help icon.
2379 * @deprecated since Moodle 2.0
2381 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2382 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2386 * Returns HTML to display a help icon.
2388 * Theme developers: DO NOT OVERRIDE! Please override function
2389 * {@link core_renderer::render_help_icon()} instead.
2391 * @param string $identifier The keyword that defines a help page
2392 * @param string $component component name
2393 * @param string|bool $linktext true means use $title as link text, string means link text value
2394 * @return string HTML fragment
2396 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2397 $icon = new help_icon($identifier, $component);
2398 $icon->diag_strings();
2399 if ($linktext === true) {
2400 $icon->linktext = get_string($icon->identifier, $icon->component);
2401 } else if (!empty($linktext)) {
2402 $icon->linktext = $linktext;
2404 return $this->render($icon);
2408 * Implementation of user image rendering.
2410 * @param help_icon $helpicon A help icon instance
2411 * @return string HTML fragment
2413 protected function render_help_icon(help_icon $helpicon) {
2414 $context = $helpicon->export_for_template($this);
2415 return $this->render_from_template('core/help_icon', $context);
2419 * Returns HTML to display a scale help icon.
2421 * @param int $courseid
2422 * @param stdClass $scale instance
2423 * @return string HTML fragment
2425 public function help_icon_scale($courseid, stdClass $scale) {
2426 global $CFG;
2428 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2430 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2432 $scaleid = abs($scale->id);
2434 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2435 $action = new popup_action('click', $link, 'ratingscale');
2437 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2441 * Creates and returns a spacer image with optional line break.
2443 * @param array $attributes Any HTML attributes to add to the spaced.
2444 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2445 * laxy do it with CSS which is a much better solution.
2446 * @return string HTML fragment
2448 public function spacer(array $attributes = null, $br = false) {
2449 $attributes = (array)$attributes;
2450 if (empty($attributes['width'])) {
2451 $attributes['width'] = 1;
2453 if (empty($attributes['height'])) {
2454 $attributes['height'] = 1;
2456 $attributes['class'] = 'spacer';
2458 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2460 if (!empty($br)) {
2461 $output .= '<br />';
2464 return $output;
2468 * Returns HTML to display the specified user's avatar.
2470 * User avatar may be obtained in two ways:
2471 * <pre>
2472 * // Option 1: (shortcut for simple cases, preferred way)
2473 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2474 * $OUTPUT->user_picture($user, array('popup'=>true));
2476 * // Option 2:
2477 * $userpic = new user_picture($user);
2478 * // Set properties of $userpic
2479 * $userpic->popup = true;
2480 * $OUTPUT->render($userpic);
2481 * </pre>
2483 * Theme developers: DO NOT OVERRIDE! Please override function
2484 * {@link core_renderer::render_user_picture()} instead.
2486 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2487 * If any of these are missing, the database is queried. Avoid this
2488 * if at all possible, particularly for reports. It is very bad for performance.
2489 * @param array $options associative array with user picture options, used only if not a user_picture object,
2490 * options are:
2491 * - courseid=$this->page->course->id (course id of user profile in link)
2492 * - size=35 (size of image)
2493 * - link=true (make image clickable - the link leads to user profile)
2494 * - popup=false (open in popup)
2495 * - alttext=true (add image alt attribute)
2496 * - class = image class attribute (default 'userpicture')
2497 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2498 * - includefullname=false (whether to include the user's full name together with the user picture)
2499 * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2500 * @return string HTML fragment
2502 public function user_picture(stdClass $user, array $options = null) {
2503 $userpicture = new user_picture($user);
2504 foreach ((array)$options as $key=>$value) {
2505 if (property_exists($userpicture, $key)) {
2506 $userpicture->$key = $value;
2509 return $this->render($userpicture);
2513 * Internal implementation of user image rendering.
2515 * @param user_picture $userpicture
2516 * @return string
2518 protected function render_user_picture(user_picture $userpicture) {
2519 $user = $userpicture->user;
2520 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
2522 if ($userpicture->alttext) {
2523 if (!empty($user->imagealt)) {
2524 $alt = $user->imagealt;
2525 } else {
2526 $alt = get_string('pictureof', '', fullname($user, $canviewfullnames));
2528 } else {
2529 $alt = '';
2532 if (empty($userpicture->size)) {
2533 $size = 35;
2534 } else if ($userpicture->size === true or $userpicture->size == 1) {
2535 $size = 100;
2536 } else {
2537 $size = $userpicture->size;
2540 $class = $userpicture->class;
2542 if ($user->picture == 0) {
2543 $class .= ' defaultuserpic';
2546 $src = $userpicture->get_url($this->page, $this);
2548 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2549 if (!$userpicture->visibletoscreenreaders) {
2550 $alt = '';
2552 $attributes['alt'] = $alt;
2554 if (!empty($alt)) {
2555 $attributes['title'] = $alt;
2558 // get the image html output fisrt
2559 $output = html_writer::empty_tag('img', $attributes);
2561 // Show fullname together with the picture when desired.
2562 if ($userpicture->includefullname) {
2563 $output .= fullname($userpicture->user, $canviewfullnames);
2566 // then wrap it in link if needed
2567 if (!$userpicture->link) {
2568 return $output;
2571 if (empty($userpicture->courseid)) {
2572 $courseid = $this->page->course->id;
2573 } else {
2574 $courseid = $userpicture->courseid;
2577 if ($courseid == SITEID) {
2578 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2579 } else {
2580 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2583 $attributes = array('href' => $url, 'class' => 'd-inline-block aabtn');
2584 if (!$userpicture->visibletoscreenreaders) {
2585 $attributes['tabindex'] = '-1';
2586 $attributes['aria-hidden'] = 'true';
2589 if ($userpicture->popup) {
2590 $id = html_writer::random_id('userpicture');
2591 $attributes['id'] = $id;
2592 $this->add_action_handler(new popup_action('click', $url), $id);
2595 return html_writer::tag('a', $output, $attributes);
2599 * Internal implementation of file tree viewer items rendering.
2601 * @param array $dir
2602 * @return string
2604 public function htmllize_file_tree($dir) {
2605 if (empty($dir['subdirs']) and empty($dir['files'])) {
2606 return '';
2608 $result = '<ul>';
2609 foreach ($dir['subdirs'] as $subdir) {
2610 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2612 foreach ($dir['files'] as $file) {
2613 $filename = $file->get_filename();
2614 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2616 $result .= '</ul>';
2618 return $result;
2622 * Returns HTML to display the file picker
2624 * <pre>
2625 * $OUTPUT->file_picker($options);
2626 * </pre>
2628 * Theme developers: DO NOT OVERRIDE! Please override function
2629 * {@link core_renderer::render_file_picker()} instead.
2631 * @param array $options associative array with file manager options
2632 * options are:
2633 * maxbytes=>-1,
2634 * itemid=>0,
2635 * client_id=>uniqid(),
2636 * acepted_types=>'*',
2637 * return_types=>FILE_INTERNAL,
2638 * context=>current page context
2639 * @return string HTML fragment
2641 public function file_picker($options) {
2642 $fp = new file_picker($options);
2643 return $this->render($fp);
2647 * Internal implementation of file picker rendering.
2649 * @param file_picker $fp
2650 * @return string
2652 public function render_file_picker(file_picker $fp) {
2653 $options = $fp->options;
2654 $client_id = $options->client_id;
2655 $strsaved = get_string('filesaved', 'repository');
2656 $straddfile = get_string('openpicker', 'repository');
2657 $strloading = get_string('loading', 'repository');
2658 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2659 $strdroptoupload = get_string('droptoupload', 'moodle');
2660 $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
2662 $currentfile = $options->currentfile;
2663 if (empty($currentfile)) {
2664 $currentfile = '';
2665 } else {
2666 $currentfile .= ' - ';
2668 if ($options->maxbytes) {
2669 $size = $options->maxbytes;
2670 } else {
2671 $size = get_max_upload_file_size();
2673 if ($size == -1) {
2674 $maxsize = '';
2675 } else {
2676 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2678 if ($options->buttonname) {
2679 $buttonname = ' name="' . $options->buttonname . '"';
2680 } else {
2681 $buttonname = '';
2683 $html = <<<EOD
2684 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2685 $iconprogress
2686 </div>
2687 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2688 <div>
2689 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2690 <span> $maxsize </span>
2691 </div>
2692 EOD;
2693 if ($options->env != 'url') {
2694 $html .= <<<EOD
2695 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2696 <div class="filepicker-filename">
2697 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2698 <div class="dndupload-progressbars"></div>
2699 </div>
2700 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2701 </div>
2702 EOD;
2704 $html .= '</div>';
2705 return $html;
2709 * @deprecated since Moodle 3.2
2711 public function update_module_button() {
2712 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2713 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2714 'Themes can choose to display the link in the buttons row consistently for all module types.');
2718 * Returns HTML to display a "Turn editing on/off" button in a form.
2720 * @param moodle_url $url The URL + params to send through when clicking the button
2721 * @return string HTML the button
2723 public function edit_button(moodle_url $url) {
2725 $url->param('sesskey', sesskey());
2726 if ($this->page->user_is_editing()) {
2727 $url->param('edit', 'off');
2728 $editstring = get_string('turneditingoff');
2729 } else {
2730 $url->param('edit', 'on');
2731 $editstring = get_string('turneditingon');
2734 return $this->single_button($url, $editstring);
2738 * Returns HTML to display a simple button to close a window
2740 * @param string $text The lang string for the button's label (already output from get_string())
2741 * @return string html fragment
2743 public function close_window_button($text='') {
2744 if (empty($text)) {
2745 $text = get_string('closewindow');
2747 $button = new single_button(new moodle_url('#'), $text, 'get');
2748 $button->add_action(new component_action('click', 'close_window'));
2750 return $this->container($this->render($button), 'closewindow');
2754 * Output an error message. By default wraps the error message in <span class="error">.
2755 * If the error message is blank, nothing is output.
2757 * @param string $message the error message.
2758 * @return string the HTML to output.
2760 public function error_text($message) {
2761 if (empty($message)) {
2762 return '';
2764 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2765 return html_writer::tag('span', $message, array('class' => 'error'));
2769 * Do not call this function directly.
2771 * To terminate the current script with a fatal error, call the {@link print_error}
2772 * function, or throw an exception. Doing either of those things will then call this
2773 * function to display the error, before terminating the execution.
2775 * @param string $message The message to output
2776 * @param string $moreinfourl URL where more info can be found about the error
2777 * @param string $link Link for the Continue button
2778 * @param array $backtrace The execution backtrace
2779 * @param string $debuginfo Debugging information
2780 * @return string the HTML to output.
2782 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2783 global $CFG;
2785 $output = '';
2786 $obbuffer = '';
2788 if ($this->has_started()) {
2789 // we can not always recover properly here, we have problems with output buffering,
2790 // html tables, etc.
2791 $output .= $this->opencontainers->pop_all_but_last();
2793 } else {
2794 // It is really bad if library code throws exception when output buffering is on,
2795 // because the buffered text would be printed before our start of page.
2796 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2797 error_reporting(0); // disable notices from gzip compression, etc.
2798 while (ob_get_level() > 0) {
2799 $buff = ob_get_clean();
2800 if ($buff === false) {
2801 break;
2803 $obbuffer .= $buff;
2805 error_reporting($CFG->debug);
2807 // Output not yet started.
2808 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2809 if (empty($_SERVER['HTTP_RANGE'])) {
2810 @header($protocol . ' 404 Not Found');
2811 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2812 // Coax iOS 10 into sending the session cookie.
2813 @header($protocol . ' 403 Forbidden');
2814 } else {
2815 // Must stop byteserving attempts somehow,
2816 // this is weird but Chrome PDF viewer can be stopped only with 407!
2817 @header($protocol . ' 407 Proxy Authentication Required');
2820 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2821 $this->page->set_url('/'); // no url
2822 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2823 $this->page->set_title(get_string('error'));
2824 $this->page->set_heading($this->page->course->fullname);
2825 $output .= $this->header();
2828 $message = '<p class="errormessage">' . s($message) . '</p>'.
2829 '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
2830 get_string('moreinformation') . '</a></p>';
2831 if (empty($CFG->rolesactive)) {
2832 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2833 //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.
2835 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2837 if ($CFG->debugdeveloper) {
2838 $labelsep = get_string('labelsep', 'langconfig');
2839 if (!empty($debuginfo)) {
2840 $debuginfo = s($debuginfo); // removes all nasty JS
2841 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2842 $label = get_string('debuginfo', 'debug') . $labelsep;
2843 $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
2845 if (!empty($backtrace)) {
2846 $label = get_string('stacktrace', 'debug') . $labelsep;
2847 $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
2849 if ($obbuffer !== '' ) {
2850 $label = get_string('outputbuffer', 'debug') . $labelsep;
2851 $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
2855 if (empty($CFG->rolesactive)) {
2856 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2857 } else if (!empty($link)) {
2858 $output .= $this->continue_button($link);
2861 $output .= $this->footer();
2863 // Padding to encourage IE to display our error page, rather than its own.
2864 $output .= str_repeat(' ', 512);
2866 return $output;
2870 * Output a notification (that is, a status message about something that has just happened).
2872 * Note: \core\notification::add() may be more suitable for your usage.
2874 * @param string $message The message to print out.
2875 * @param string $type The type of notification. See constants on \core\output\notification.
2876 * @return string the HTML to output.
2878 public function notification($message, $type = null) {
2879 $typemappings = [
2880 // Valid types.
2881 'success' => \core\output\notification::NOTIFY_SUCCESS,
2882 'info' => \core\output\notification::NOTIFY_INFO,
2883 'warning' => \core\output\notification::NOTIFY_WARNING,
2884 'error' => \core\output\notification::NOTIFY_ERROR,
2886 // Legacy types mapped to current types.
2887 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2888 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2889 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2890 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2891 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2892 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2893 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2896 $extraclasses = [];
2898 if ($type) {
2899 if (strpos($type, ' ') === false) {
2900 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2901 if (isset($typemappings[$type])) {
2902 $type = $typemappings[$type];
2903 } else {
2904 // The value provided did not match a known type. It must be an extra class.
2905 $extraclasses = [$type];
2907 } else {
2908 // Identify what type of notification this is.
2909 $classarray = explode(' ', self::prepare_classes($type));
2911 // Separate out the type of notification from the extra classes.
2912 foreach ($classarray as $class) {
2913 if (isset($typemappings[$class])) {
2914 $type = $typemappings[$class];
2915 } else {
2916 $extraclasses[] = $class;
2922 $notification = new \core\output\notification($message, $type);
2923 if (count($extraclasses)) {
2924 $notification->set_extra_classes($extraclasses);
2927 // Return the rendered template.
2928 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2932 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2934 public function notify_problem() {
2935 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
2936 'please use \core\notification::add(), or \core\output\notification as required.');
2940 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2942 public function notify_success() {
2943 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
2944 'please use \core\notification::add(), or \core\output\notification as required.');
2948 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2950 public function notify_message() {
2951 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
2952 'please use \core\notification::add(), or \core\output\notification as required.');
2956 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2958 public function notify_redirect() {
2959 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
2960 'please use \core\notification::add(), or \core\output\notification as required.');
2964 * Render a notification (that is, a status message about something that has
2965 * just happened).
2967 * @param \core\output\notification $notification the notification to print out
2968 * @return string the HTML to output.
2970 protected function render_notification(\core\output\notification $notification) {
2971 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2975 * Returns HTML to display a continue button that goes to a particular URL.
2977 * @param string|moodle_url $url The url the button goes to.
2978 * @return string the HTML to output.
2980 public function continue_button($url) {
2981 if (!($url instanceof moodle_url)) {
2982 $url = new moodle_url($url);
2984 $button = new single_button($url, get_string('continue'), 'get', true);
2985 $button->class = 'continuebutton';
2987 return $this->render($button);
2991 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2993 * Theme developers: DO NOT OVERRIDE! Please override function
2994 * {@link core_renderer::render_paging_bar()} instead.
2996 * @param int $totalcount The total number of entries available to be paged through
2997 * @param int $page The page you are currently viewing
2998 * @param int $perpage The number of entries that should be shown per page
2999 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3000 * @param string $pagevar name of page parameter that holds the page number
3001 * @return string the HTML to output.
3003 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3004 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3005 return $this->render($pb);
3009 * Returns HTML to display the paging bar.
3011 * @param paging_bar $pagingbar
3012 * @return string the HTML to output.
3014 protected function render_paging_bar(paging_bar $pagingbar) {
3015 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3016 $pagingbar->maxdisplay = 10;
3017 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3021 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3023 * @param string $current the currently selected letter.
3024 * @param string $class class name to add to this initial bar.
3025 * @param string $title the name to put in front of this initial bar.
3026 * @param string $urlvar URL parameter name for this initial.
3027 * @param string $url URL object.
3028 * @param array $alpha of letters in the alphabet.
3029 * @return string the HTML to output.
3031 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3032 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3033 return $this->render($ib);
3037 * Internal implementation of initials bar rendering.
3039 * @param initials_bar $initialsbar
3040 * @return string
3042 protected function render_initials_bar(initials_bar $initialsbar) {
3043 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3047 * Output the place a skip link goes to.
3049 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3050 * @return string the HTML to output.
3052 public function skip_link_target($id = null) {
3053 return html_writer::span('', '', array('id' => $id));
3057 * Outputs a heading
3059 * @param string $text The text of the heading
3060 * @param int $level The level of importance of the heading. Defaulting to 2
3061 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3062 * @param string $id An optional ID
3063 * @return string the HTML to output.
3065 public function heading($text, $level = 2, $classes = null, $id = null) {
3066 $level = (integer) $level;
3067 if ($level < 1 or $level > 6) {
3068 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3070 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3074 * Outputs a box.
3076 * @param string $contents The contents of the box
3077 * @param string $classes A space-separated list of CSS classes
3078 * @param string $id An optional ID
3079 * @param array $attributes An array of other attributes to give the box.
3080 * @return string the HTML to output.
3082 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3083 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3087 * Outputs the opening section of a box.
3089 * @param string $classes A space-separated list of CSS classes
3090 * @param string $id An optional ID
3091 * @param array $attributes An array of other attributes to give the box.
3092 * @return string the HTML to output.
3094 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3095 $this->opencontainers->push('box', html_writer::end_tag('div'));
3096 $attributes['id'] = $id;
3097 $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes);
3098 return html_writer::start_tag('div', $attributes);
3102 * Outputs the closing section of a box.
3104 * @return string the HTML to output.
3106 public function box_end() {
3107 return $this->opencontainers->pop('box');
3111 * Outputs a container.
3113 * @param string $contents The contents of the box
3114 * @param string $classes A space-separated list of CSS classes
3115 * @param string $id An optional ID
3116 * @return string the HTML to output.
3118 public function container($contents, $classes = null, $id = null) {
3119 return $this->container_start($classes, $id) . $contents . $this->container_end();
3123 * Outputs the opening section of a container.
3125 * @param string $classes A space-separated list of CSS classes
3126 * @param string $id An optional ID
3127 * @return string the HTML to output.
3129 public function container_start($classes = null, $id = null) {
3130 $this->opencontainers->push('container', html_writer::end_tag('div'));
3131 return html_writer::start_tag('div', array('id' => $id,
3132 'class' => renderer_base::prepare_classes($classes)));
3136 * Outputs the closing section of a container.
3138 * @return string the HTML to output.
3140 public function container_end() {
3141 return $this->opencontainers->pop('container');
3145 * Make nested HTML lists out of the items
3147 * The resulting list will look something like this:
3149 * <pre>
3150 * <<ul>>
3151 * <<li>><div class='tree_item parent'>(item contents)</div>
3152 * <<ul>
3153 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3154 * <</ul>>
3155 * <</li>>
3156 * <</ul>>
3157 * </pre>
3159 * @param array $items
3160 * @param array $attrs html attributes passed to the top ofs the list
3161 * @return string HTML
3163 public function tree_block_contents($items, $attrs = array()) {
3164 // exit if empty, we don't want an empty ul element
3165 if (empty($items)) {
3166 return '';
3168 // array of nested li elements
3169 $lis = array();
3170 foreach ($items as $item) {
3171 // this applies to the li item which contains all child lists too
3172 $content = $item->content($this);
3173 $liclasses = array($item->get_css_type());
3174 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3175 $liclasses[] = 'collapsed';
3177 if ($item->isactive === true) {
3178 $liclasses[] = 'current_branch';
3180 $liattr = array('class'=>join(' ',$liclasses));
3181 // class attribute on the div item which only contains the item content
3182 $divclasses = array('tree_item');
3183 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3184 $divclasses[] = 'branch';
3185 } else {
3186 $divclasses[] = 'leaf';
3188 if (!empty($item->classes) && count($item->classes)>0) {
3189 $divclasses[] = join(' ', $item->classes);
3191 $divattr = array('class'=>join(' ', $divclasses));
3192 if (!empty($item->id)) {
3193 $divattr['id'] = $item->id;
3195 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3196 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3197 $content = html_writer::empty_tag('hr') . $content;
3199 $content = html_writer::tag('li', $content, $liattr);
3200 $lis[] = $content;
3202 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3206 * Returns a search box.
3208 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3209 * @return string HTML with the search form hidden by default.
3211 public function search_box($id = false) {
3212 global $CFG;
3214 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3215 // result in an extra included file for each site, even the ones where global search
3216 // is disabled.
3217 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3218 return '';
3221 $data = [
3222 'action' => new moodle_url('/search/index.php'),
3223 'hiddenfields' => (object) ['name' => 'context', 'value' => $this->page->context->id],
3224 'inputname' => 'q',
3225 'searchstring' => get_string('search'),
3227 return $this->render_from_template('core/search_input_navbar', $data);
3231 * Allow plugins to provide some content to be rendered in the navbar.
3232 * The plugin must define a PLUGIN_render_navbar_output function that returns
3233 * the HTML they wish to add to the navbar.
3235 * @return string HTML for the navbar
3237 public function navbar_plugin_output() {
3238 $output = '';
3240 // Give subsystems an opportunity to inject extra html content. The callback
3241 // must always return a string containing valid html.
3242 foreach (\core_component::get_core_subsystems() as $name => $path) {
3243 if ($path) {
3244 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3248 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3249 foreach ($pluginsfunction as $plugintype => $plugins) {
3250 foreach ($plugins as $pluginfunction) {
3251 $output .= $pluginfunction($this);
3256 return $output;
3260 * Construct a user menu, returning HTML that can be echoed out by a
3261 * layout file.
3263 * @param stdClass $user A user object, usually $USER.
3264 * @param bool $withlinks true if a dropdown should be built.
3265 * @return string HTML fragment.
3267 public function user_menu($user = null, $withlinks = null) {
3268 global $USER, $CFG;
3269 require_once($CFG->dirroot . '/user/lib.php');
3271 if (is_null($user)) {
3272 $user = $USER;
3275 // Note: this behaviour is intended to match that of core_renderer::login_info,
3276 // but should not be considered to be good practice; layout options are
3277 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3278 if (is_null($withlinks)) {
3279 $withlinks = empty($this->page->layout_options['nologinlinks']);
3282 // Add a class for when $withlinks is false.
3283 $usermenuclasses = 'usermenu';
3284 if (!$withlinks) {
3285 $usermenuclasses .= ' withoutlinks';
3288 $returnstr = "";
3290 // If during initial install, return the empty return string.
3291 if (during_initial_install()) {
3292 return $returnstr;
3295 $loginpage = $this->is_login_page();
3296 $loginurl = get_login_url();
3297 // If not logged in, show the typical not-logged-in string.
3298 if (!isloggedin()) {
3299 $returnstr = get_string('loggedinnot', 'moodle');
3300 if (!$loginpage) {
3301 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3303 return html_writer::div(
3304 html_writer::span(
3305 $returnstr,
3306 'login'
3308 $usermenuclasses
3313 // If logged in as a guest user, show a string to that effect.
3314 if (isguestuser()) {
3315 $returnstr = get_string('loggedinasguest');
3316 if (!$loginpage && $withlinks) {
3317 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3320 return html_writer::div(
3321 html_writer::span(
3322 $returnstr,
3323 'login'
3325 $usermenuclasses
3329 // Get some navigation opts.
3330 $opts = user_get_user_navigation_info($user, $this->page);
3332 $avatarclasses = "avatars";
3333 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3334 $usertextcontents = $opts->metadata['userfullname'];
3336 // Other user.
3337 if (!empty($opts->metadata['asotheruser'])) {
3338 $avatarcontents .= html_writer::span(
3339 $opts->metadata['realuseravatar'],
3340 'avatar realuser'
3342 $usertextcontents = $opts->metadata['realuserfullname'];
3343 $usertextcontents .= html_writer::tag(
3344 'span',
3345 get_string(
3346 'loggedinas',
3347 'moodle',
3348 html_writer::span(
3349 $opts->metadata['userfullname'],
3350 'value'
3353 array('class' => 'meta viewingas')
3357 // Role.
3358 if (!empty($opts->metadata['asotherrole'])) {
3359 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3360 $usertextcontents .= html_writer::span(
3361 $opts->metadata['rolename'],
3362 'meta role role-' . $role
3366 // User login failures.
3367 if (!empty($opts->metadata['userloginfail'])) {
3368 $usertextcontents .= html_writer::span(
3369 $opts->metadata['userloginfail'],
3370 'meta loginfailures'
3374 // MNet.
3375 if (!empty($opts->metadata['asmnetuser'])) {
3376 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3377 $usertextcontents .= html_writer::span(
3378 $opts->metadata['mnetidprovidername'],
3379 'meta mnet mnet-' . $mnet
3383 $returnstr .= html_writer::span(
3384 html_writer::span($usertextcontents, 'usertext mr-1') .
3385 html_writer::span($avatarcontents, $avatarclasses),
3386 'userbutton'
3389 // Create a divider (well, a filler).
3390 $divider = new action_menu_filler();
3391 $divider->primary = false;
3393 $am = new action_menu();
3394 $am->set_menu_trigger(
3395 $returnstr
3397 $am->set_action_label(get_string('usermenu'));
3398 $am->set_alignment(action_menu::TR, action_menu::BR);
3399 $am->set_nowrap_on_items();
3400 if ($withlinks) {
3401 $navitemcount = count($opts->navitems);
3402 $idx = 0;
3403 foreach ($opts->navitems as $key => $value) {
3405 switch ($value->itemtype) {
3406 case 'divider':
3407 // If the nav item is a divider, add one and skip link processing.
3408 $am->add($divider);
3409 break;
3411 case 'invalid':
3412 // Silently skip invalid entries (should we post a notification?).
3413 break;
3415 case 'link':
3416 // Process this as a link item.
3417 $pix = null;
3418 if (isset($value->pix) && !empty($value->pix)) {
3419 $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
3420 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3421 $value->title = html_writer::img(
3422 $value->imgsrc,
3423 $value->title,
3424 array('class' => 'iconsmall')
3425 ) . $value->title;
3428 $al = new action_menu_link_secondary(
3429 $value->url,
3430 $pix,
3431 $value->title,
3432 array('class' => 'icon')
3434 if (!empty($value->titleidentifier)) {
3435 $al->attributes['data-title'] = $value->titleidentifier;
3437 $am->add($al);
3438 break;
3441 $idx++;
3443 // Add dividers after the first item and before the last item.
3444 if ($idx == 1 || $idx == $navitemcount - 1) {
3445 $am->add($divider);
3450 return html_writer::div(
3451 $this->render($am),
3452 $usermenuclasses
3457 * Secure layout login info.
3459 * @return string
3461 public function secure_layout_login_info() {
3462 if (get_config('core', 'logininfoinsecurelayout')) {
3463 return $this->login_info(false);
3464 } else {
3465 return '';
3470 * Returns the language menu in the secure layout.
3472 * No custom menu items are passed though, such that it will render only the language selection.
3474 * @return string
3476 public function secure_layout_language_menu() {
3477 if (get_config('core', 'langmenuinsecurelayout')) {
3478 $custommenu = new custom_menu('', current_language());
3479 return $this->render_custom_menu($custommenu);
3480 } else {
3481 return '';
3486 * This renders the navbar.
3487 * Uses bootstrap compatible html.
3489 public function navbar() {
3490 return $this->render_from_template('core/navbar', $this->page->navbar);
3494 * Renders a breadcrumb navigation node object.
3496 * @param breadcrumb_navigation_node $item The navigation node to render.
3497 * @return string HTML fragment
3499 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3501 if ($item->action instanceof moodle_url) {
3502 $content = $item->get_content();
3503 $title = $item->get_title();
3504 $attributes = array();
3505 $attributes['itemprop'] = 'url';
3506 if ($title !== '') {
3507 $attributes['title'] = $title;
3509 if ($item->hidden) {
3510 $attributes['class'] = 'dimmed_text';
3512 if ($item->is_last()) {
3513 $attributes['aria-current'] = 'page';
3515 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3516 $content = html_writer::link($item->action, $content, $attributes);
3518 $attributes = array();
3519 $attributes['itemscope'] = '';
3520 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3521 $content = html_writer::tag('span', $content, $attributes);
3523 } else {
3524 $content = $this->render_navigation_node($item);
3526 return $content;
3530 * Renders a navigation node object.
3532 * @param navigation_node $item The navigation node to render.
3533 * @return string HTML fragment
3535 protected function render_navigation_node(navigation_node $item) {
3536 $content = $item->get_content();
3537 $title = $item->get_title();
3538 if ($item->icon instanceof renderable && !$item->hideicon) {
3539 $icon = $this->render($item->icon);
3540 $content = $icon.$content; // use CSS for spacing of icons
3542 if ($item->helpbutton !== null) {
3543 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3545 if ($content === '') {
3546 return '';
3548 if ($item->action instanceof action_link) {
3549 $link = $item->action;
3550 if ($item->hidden) {
3551 $link->add_class('dimmed');
3553 if (!empty($content)) {
3554 // Providing there is content we will use that for the link content.
3555 $link->text = $content;
3557 $content = $this->render($link);
3558 } else if ($item->action instanceof moodle_url) {
3559 $attributes = array();
3560 if ($title !== '') {
3561 $attributes['title'] = $title;
3563 if ($item->hidden) {
3564 $attributes['class'] = 'dimmed_text';
3566 $content = html_writer::link($item->action, $content, $attributes);
3568 } else if (is_string($item->action) || empty($item->action)) {
3569 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3570 if ($title !== '') {
3571 $attributes['title'] = $title;
3573 if ($item->hidden) {
3574 $attributes['class'] = 'dimmed_text';
3576 $content = html_writer::tag('span', $content, $attributes);
3578 return $content;
3582 * Accessibility: Right arrow-like character is
3583 * used in the breadcrumb trail, course navigation menu
3584 * (previous/next activity), calendar, and search forum block.
3585 * If the theme does not set characters, appropriate defaults
3586 * are set automatically. Please DO NOT
3587 * use &lt; &gt; &raquo; - these are confusing for blind users.
3589 * @return string
3591 public function rarrow() {
3592 return $this->page->theme->rarrow;
3596 * Accessibility: Left arrow-like character is
3597 * used in the breadcrumb trail, course navigation menu
3598 * (previous/next activity), calendar, and search forum block.
3599 * If the theme does not set characters, appropriate defaults
3600 * are set automatically. Please DO NOT
3601 * use &lt; &gt; &raquo; - these are confusing for blind users.
3603 * @return string
3605 public function larrow() {
3606 return $this->page->theme->larrow;
3610 * Accessibility: Up arrow-like character is used in
3611 * the book heirarchical navigation.
3612 * If the theme does not set characters, appropriate defaults
3613 * are set automatically. Please DO NOT
3614 * use ^ - this is confusing for blind users.
3616 * @return string
3618 public function uarrow() {
3619 return $this->page->theme->uarrow;
3623 * Accessibility: Down arrow-like character.
3624 * If the theme does not set characters, appropriate defaults
3625 * are set automatically.
3627 * @return string
3629 public function darrow() {
3630 return $this->page->theme->darrow;
3634 * Returns the custom menu if one has been set
3636 * A custom menu can be configured by browsing to
3637 * Settings: Administration > Appearance > Themes > Theme settings
3638 * and then configuring the custommenu config setting as described.
3640 * Theme developers: DO NOT OVERRIDE! Please override function
3641 * {@link core_renderer::render_custom_menu()} instead.
3643 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3644 * @return string
3646 public function custom_menu($custommenuitems = '') {
3647 global $CFG;
3649 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3650 $custommenuitems = $CFG->custommenuitems;
3652 $custommenu = new custom_menu($custommenuitems, current_language());
3653 return $this->render_custom_menu($custommenu);
3657 * We want to show the custom menus as a list of links in the footer on small screens.
3658 * Just return the menu object exported so we can render it differently.
3660 public function custom_menu_flat() {
3661 global $CFG;
3662 $custommenuitems = '';
3664 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3665 $custommenuitems = $CFG->custommenuitems;
3667 $custommenu = new custom_menu($custommenuitems, current_language());
3668 $langs = get_string_manager()->get_list_of_translations();
3669 $haslangmenu = $this->lang_menu() != '';
3671 if ($haslangmenu) {
3672 $strlang = get_string('language');
3673 $currentlang = current_language();
3674 if (isset($langs[$currentlang])) {
3675 $currentlang = $langs[$currentlang];
3676 } else {
3677 $currentlang = $strlang;
3679 $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3680 foreach ($langs as $langtype => $langname) {
3681 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3685 return $custommenu->export_for_template($this);
3689 * Renders a custom menu object (located in outputcomponents.php)
3691 * The custom menu this method produces makes use of the YUI3 menunav widget
3692 * and requires very specific html elements and classes.
3694 * @staticvar int $menucount
3695 * @param custom_menu $menu
3696 * @return string
3698 protected function render_custom_menu(custom_menu $menu) {
3699 global $CFG;
3701 $langs = get_string_manager()->get_list_of_translations();
3702 $haslangmenu = $this->lang_menu() != '';
3704 if (!$menu->has_children() && !$haslangmenu) {
3705 return '';
3708 if ($haslangmenu) {
3709 $strlang = get_string('language');
3710 $currentlang = current_language();
3711 if (isset($langs[$currentlang])) {
3712 $currentlang = $langs[$currentlang];
3713 } else {
3714 $currentlang = $strlang;
3716 $this->language = $menu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3717 foreach ($langs as $langtype => $langname) {
3718 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3722 $content = '';
3723 foreach ($menu->get_children() as $item) {
3724 $context = $item->export_for_template($this);
3725 $content .= $this->render_from_template('core/custom_menu_item', $context);
3728 return $content;
3732 * Renders a custom menu node as part of a submenu
3734 * The custom menu this method produces makes use of the YUI3 menunav widget
3735 * and requires very specific html elements and classes.
3737 * @see core:renderer::render_custom_menu()
3739 * @staticvar int $submenucount
3740 * @param custom_menu_item $menunode
3741 * @return string
3743 protected function render_custom_menu_item(custom_menu_item $menunode) {
3744 // Required to ensure we get unique trackable id's
3745 static $submenucount = 0;
3746 if ($menunode->has_children()) {
3747 // If the child has menus render it as a sub menu
3748 $submenucount++;
3749 $content = html_writer::start_tag('li');
3750 if ($menunode->get_url() !== null) {
3751 $url = $menunode->get_url();
3752 } else {
3753 $url = '#cm_submenu_'.$submenucount;
3755 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3756 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3757 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3758 $content .= html_writer::start_tag('ul');
3759 foreach ($menunode->get_children() as $menunode) {
3760 $content .= $this->render_custom_menu_item($menunode);
3762 $content .= html_writer::end_tag('ul');
3763 $content .= html_writer::end_tag('div');
3764 $content .= html_writer::end_tag('div');
3765 $content .= html_writer::end_tag('li');
3766 } else {
3767 // The node doesn't have children so produce a final menuitem.
3768 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3769 $content = '';
3770 if (preg_match("/^#+$/", $menunode->get_text())) {
3772 // This is a divider.
3773 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3774 } else {
3775 $content = html_writer::start_tag(
3776 'li',
3777 array(
3778 'class' => 'yui3-menuitem'
3781 if ($menunode->get_url() !== null) {
3782 $url = $menunode->get_url();
3783 } else {
3784 $url = '#';
3786 $content .= html_writer::link(
3787 $url,
3788 $menunode->get_text(),
3789 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3792 $content .= html_writer::end_tag('li');
3794 // Return the sub menu
3795 return $content;
3799 * Renders theme links for switching between default and other themes.
3801 * @return string
3803 protected function theme_switch_links() {
3805 $actualdevice = core_useragent::get_device_type();
3806 $currentdevice = $this->page->devicetypeinuse;
3807 $switched = ($actualdevice != $currentdevice);
3809 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3810 // The user is using the a default device and hasn't switched so don't shown the switch
3811 // device links.
3812 return '';
3815 if ($switched) {
3816 $linktext = get_string('switchdevicerecommended');
3817 $devicetype = $actualdevice;
3818 } else {
3819 $linktext = get_string('switchdevicedefault');
3820 $devicetype = 'default';
3822 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3824 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3825 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3826 $content .= html_writer::end_tag('div');
3828 return $content;
3832 * Renders tabs
3834 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3836 * Theme developers: In order to change how tabs are displayed please override functions
3837 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3839 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3840 * @param string|null $selected which tab to mark as selected, all parent tabs will
3841 * automatically be marked as activated
3842 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3843 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3844 * @return string
3846 public final function tabtree($tabs, $selected = null, $inactive = null) {
3847 return $this->render(new tabtree($tabs, $selected, $inactive));
3851 * Renders tabtree
3853 * @param tabtree $tabtree
3854 * @return string
3856 protected function render_tabtree(tabtree $tabtree) {
3857 if (empty($tabtree->subtree)) {
3858 return '';
3860 $data = $tabtree->export_for_template($this);
3861 return $this->render_from_template('core/tabtree', $data);
3865 * Renders tabobject (part of tabtree)
3867 * This function is called from {@link core_renderer::render_tabtree()}
3868 * and also it calls itself when printing the $tabobject subtree recursively.
3870 * Property $tabobject->level indicates the number of row of tabs.
3872 * @param tabobject $tabobject
3873 * @return string HTML fragment
3875 protected function render_tabobject(tabobject $tabobject) {
3876 $str = '';
3878 // Print name of the current tab.
3879 if ($tabobject instanceof tabtree) {
3880 // No name for tabtree root.
3881 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3882 // Tab name without a link. The <a> tag is used for styling.
3883 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3884 } else {
3885 // Tab name with a link.
3886 if (!($tabobject->link instanceof moodle_url)) {
3887 // backward compartibility when link was passed as quoted string
3888 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3889 } else {
3890 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3894 if (empty($tabobject->subtree)) {
3895 if ($tabobject->selected) {
3896 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3898 return $str;
3901 // Print subtree.
3902 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
3903 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3904 $cnt = 0;
3905 foreach ($tabobject->subtree as $tab) {
3906 $liclass = '';
3907 if (!$cnt) {
3908 $liclass .= ' first';
3910 if ($cnt == count($tabobject->subtree) - 1) {
3911 $liclass .= ' last';
3913 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3914 $liclass .= ' onerow';
3917 if ($tab->selected) {
3918 $liclass .= ' here selected';
3919 } else if ($tab->activated) {
3920 $liclass .= ' here active';
3923 // This will recursively call function render_tabobject() for each item in subtree.
3924 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3925 $cnt++;
3927 $str .= html_writer::end_tag('ul');
3930 return $str;
3934 * Get the HTML for blocks in the given region.
3936 * @since Moodle 2.5.1 2.6
3937 * @param string $region The region to get HTML for.
3938 * @return string HTML.
3940 public function blocks($region, $classes = array(), $tag = 'aside') {
3941 $displayregion = $this->page->apply_theme_region_manipulations($region);
3942 $classes = (array)$classes;
3943 $classes[] = 'block-region';
3944 $attributes = array(
3945 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3946 'class' => join(' ', $classes),
3947 'data-blockregion' => $displayregion,
3948 'data-droptarget' => '1'
3950 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3951 $content = $this->blocks_for_region($displayregion);
3952 } else {
3953 $content = '';
3955 return html_writer::tag($tag, $content, $attributes);
3959 * Renders a custom block region.
3961 * Use this method if you want to add an additional block region to the content of the page.
3962 * Please note this should only be used in special situations.
3963 * We want to leave the theme is control where ever possible!
3965 * This method must use the same method that the theme uses within its layout file.
3966 * As such it asks the theme what method it is using.
3967 * It can be one of two values, blocks or blocks_for_region (deprecated).
3969 * @param string $regionname The name of the custom region to add.
3970 * @return string HTML for the block region.
3972 public function custom_block_region($regionname) {
3973 if ($this->page->theme->get_block_render_method() === 'blocks') {
3974 return $this->blocks($regionname);
3975 } else {
3976 return $this->blocks_for_region($regionname);
3981 * Returns the CSS classes to apply to the body tag.
3983 * @since Moodle 2.5.1 2.6
3984 * @param array $additionalclasses Any additional classes to apply.
3985 * @return string
3987 public function body_css_classes(array $additionalclasses = array()) {
3988 return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses);
3992 * The ID attribute to apply to the body tag.
3994 * @since Moodle 2.5.1 2.6
3995 * @return string
3997 public function body_id() {
3998 return $this->page->bodyid;
4002 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4004 * @since Moodle 2.5.1 2.6
4005 * @param string|array $additionalclasses Any additional classes to give the body tag,
4006 * @return string
4008 public function body_attributes($additionalclasses = array()) {
4009 if (!is_array($additionalclasses)) {
4010 $additionalclasses = explode(' ', $additionalclasses);
4012 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4016 * Gets HTML for the page heading.
4018 * @since Moodle 2.5.1 2.6
4019 * @param string $tag The tag to encase the heading in. h1 by default.
4020 * @return string HTML.
4022 public function page_heading($tag = 'h1') {
4023 return html_writer::tag($tag, $this->page->heading);
4027 * Gets the HTML for the page heading button.
4029 * @since Moodle 2.5.1 2.6
4030 * @return string HTML.
4032 public function page_heading_button() {
4033 return $this->page->button;
4037 * Returns the Moodle docs link to use for this page.
4039 * @since Moodle 2.5.1 2.6
4040 * @param string $text
4041 * @return string
4043 public function page_doc_link($text = null) {
4044 if ($text === null) {
4045 $text = get_string('moodledocslink');
4047 $path = page_get_doc_link_path($this->page);
4048 if (!$path) {
4049 return '';
4051 return $this->doc_link($path, $text);
4055 * Returns the page heading menu.
4057 * @since Moodle 2.5.1 2.6
4058 * @return string HTML.
4060 public function page_heading_menu() {
4061 return $this->page->headingmenu;
4065 * Returns the title to use on the page.
4067 * @since Moodle 2.5.1 2.6
4068 * @return string
4070 public function page_title() {
4071 return $this->page->title;
4075 * Returns the moodle_url for the favicon.
4077 * @since Moodle 2.5.1 2.6
4078 * @return moodle_url The moodle_url for the favicon
4080 public function favicon() {
4081 return $this->image_url('favicon', 'theme');
4085 * Renders preferences groups.
4087 * @param preferences_groups $renderable The renderable
4088 * @return string The output.
4090 public function render_preferences_groups(preferences_groups $renderable) {
4091 return $this->render_from_template('core/preferences_groups', $renderable);
4095 * Renders preferences group.
4097 * @param preferences_group $renderable The renderable
4098 * @return string The output.
4100 public function render_preferences_group(preferences_group $renderable) {
4101 $html = '';
4102 $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4103 $html .= $this->heading($renderable->title, 3);
4104 $html .= html_writer::start_tag('ul');
4105 foreach ($renderable->nodes as $node) {
4106 if ($node->has_children()) {
4107 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4109 $html .= html_writer::tag('li', $this->render($node));
4111 $html .= html_writer::end_tag('ul');
4112 $html .= html_writer::end_tag('div');
4113 return $html;
4116 public function context_header($headerinfo = null, $headinglevel = 1) {
4117 global $DB, $USER, $CFG, $SITE;
4118 require_once($CFG->dirroot . '/user/lib.php');
4119 $context = $this->page->context;
4120 $heading = null;
4121 $imagedata = null;
4122 $subheader = null;
4123 $userbuttons = null;
4125 // Make sure to use the heading if it has been set.
4126 if (isset($headerinfo['heading'])) {
4127 $heading = $headerinfo['heading'];
4128 } else {
4129 $heading = $this->page->heading;
4132 // The user context currently has images and buttons. Other contexts may follow.
4133 if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
4134 if (isset($headerinfo['user'])) {
4135 $user = $headerinfo['user'];
4136 } else {
4137 // Look up the user information if it is not supplied.
4138 $user = $DB->get_record('user', array('id' => $context->instanceid));
4141 // If the user context is set, then use that for capability checks.
4142 if (isset($headerinfo['usercontext'])) {
4143 $context = $headerinfo['usercontext'];
4146 // Only provide user information if the user is the current user, or a user which the current user can view.
4147 // When checking user_can_view_profile(), either:
4148 // If the page context is course, check the course context (from the page object) or;
4149 // If page context is NOT course, then check across all courses.
4150 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4152 if (user_can_view_profile($user, $course)) {
4153 // Use the user's full name if the heading isn't set.
4154 if (empty($heading)) {
4155 $heading = fullname($user);
4158 $imagedata = $this->user_picture($user, array('size' => 100));
4160 // Check to see if we should be displaying a message button.
4161 if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
4162 $userbuttons = array(
4163 'messages' => array(
4164 'buttontype' => 'message',
4165 'title' => get_string('message', 'message'),
4166 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4167 'image' => 'message',
4168 'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
4169 'page' => $this->page
4173 if ($USER->id != $user->id) {
4174 $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4175 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4176 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4177 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4178 $userbuttons['togglecontact'] = array(
4179 'buttontype' => 'togglecontact',
4180 'title' => get_string($contacttitle, 'message'),
4181 'url' => new moodle_url('/message/index.php', array(
4182 'user1' => $USER->id,
4183 'user2' => $user->id,
4184 $contacturlaction => $user->id,
4185 'sesskey' => sesskey())
4187 'image' => $contactimage,
4188 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4189 'page' => $this->page
4193 $this->page->requires->string_for_js('changesmadereallygoaway', 'moodle');
4195 } else {
4196 $heading = null;
4200 if ($this->should_display_main_logo($headinglevel)) {
4201 $sitename = format_string($SITE->fullname, true, ['context' => context_course::instance(SITEID)]);
4202 // Logo.
4203 $html = html_writer::div(
4204 html_writer::empty_tag('img', [
4205 'src' => $this->get_logo_url(null, 150),
4206 'alt' => get_string('logoof', '', $sitename),
4207 'class' => 'img-fluid'
4209 'logo'
4211 // Heading.
4212 if (!isset($heading)) {
4213 $html .= $this->heading($this->page->heading, $headinglevel, 'sr-only');
4214 } else {
4215 $html .= $this->heading($heading, $headinglevel, 'sr-only');
4217 return $html;
4220 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4221 return $this->render_context_header($contextheader);
4225 * Renders the skip links for the page.
4227 * @param array $links List of skip links.
4228 * @return string HTML for the skip links.
4230 public function render_skip_links($links) {
4231 $context = [ 'links' => []];
4233 foreach ($links as $url => $text) {
4234 $context['links'][] = [ 'url' => $url, 'text' => $text];
4237 return $this->render_from_template('core/skip_links', $context);
4241 * Renders the header bar.
4243 * @param context_header $contextheader Header bar object.
4244 * @return string HTML for the header bar.
4246 protected function render_context_header(context_header $contextheader) {
4248 // Generate the heading first and before everything else as we might have to do an early return.
4249 if (!isset($contextheader->heading)) {
4250 $heading = $this->heading($this->page->heading, $contextheader->headinglevel);
4251 } else {
4252 $heading = $this->heading($contextheader->heading, $contextheader->headinglevel);
4255 $showheader = empty($this->page->layout_options['nocontextheader']);
4256 if (!$showheader) {
4257 // Return the heading wrapped in an sr-only element so it is only visible to screen-readers.
4258 return html_writer::div($heading, 'sr-only');
4261 // All the html stuff goes here.
4262 $html = html_writer::start_div('page-context-header');
4264 // Image data.
4265 if (isset($contextheader->imagedata)) {
4266 // Header specific image.
4267 $html .= html_writer::div($contextheader->imagedata, 'page-header-image');
4270 // Headings.
4271 $html .= html_writer::tag('div', $heading, array('class' => 'page-header-headings'));
4273 // Buttons.
4274 if (isset($contextheader->additionalbuttons)) {
4275 $html .= html_writer::start_div('btn-group header-button-group');
4276 foreach ($contextheader->additionalbuttons as $button) {
4277 if (!isset($button->page)) {
4278 // Include js for messaging.
4279 if ($button['buttontype'] === 'togglecontact') {
4280 \core_message\helper::togglecontact_requirejs();
4282 if ($button['buttontype'] === 'message') {
4283 \core_message\helper::messageuser_requirejs();
4285 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4286 'class' => 'iconsmall',
4287 'role' => 'presentation'
4289 $image .= html_writer::span($button['title'], 'header-button-title');
4290 } else {
4291 $image = html_writer::empty_tag('img', array(
4292 'src' => $button['formattedimage'],
4293 'role' => 'presentation'
4296 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4298 $html .= html_writer::end_div();
4300 $html .= html_writer::end_div();
4302 return $html;
4306 * Wrapper for header elements.
4308 * @return string HTML to display the main header.
4310 public function full_header() {
4312 if ($this->page->include_region_main_settings_in_header_actions() &&
4313 !$this->page->blocks->is_block_present('settings')) {
4314 // Only include the region main settings if the page has requested it and it doesn't already have
4315 // the settings block on it. The region main settings are included in the settings block and
4316 // duplicating the content causes behat failures.
4317 $this->page->add_header_action(html_writer::div(
4318 $this->region_main_settings_menu(),
4319 'd-print-none',
4320 ['id' => 'region-main-settings-menu']
4324 $header = new stdClass();
4325 $header->settingsmenu = $this->context_header_settings_menu();
4326 $header->contextheader = $this->context_header();
4327 $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
4328 $header->navbar = $this->navbar();
4329 $header->pageheadingbutton = $this->page_heading_button();
4330 $header->courseheader = $this->course_header();
4331 $header->headeractions = $this->page->get_header_actions();
4332 return $this->render_from_template('core/full_header', $header);
4336 * This is an optional menu that can be added to a layout by a theme. It contains the
4337 * menu for the course administration, only on the course main page.
4339 * @return string
4341 public function context_header_settings_menu() {
4342 $context = $this->page->context;
4343 $menu = new action_menu();
4345 $items = $this->page->navbar->get_items();
4346 $currentnode = end($items);
4348 $showcoursemenu = false;
4349 $showfrontpagemenu = false;
4350 $showusermenu = false;
4352 // We are on the course home page.
4353 if (($context->contextlevel == CONTEXT_COURSE) &&
4354 !empty($currentnode) &&
4355 ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
4356 $showcoursemenu = true;
4359 $courseformat = course_get_format($this->page->course);
4360 // This is a single activity course format, always show the course menu on the activity main page.
4361 if ($context->contextlevel == CONTEXT_MODULE &&
4362 !$courseformat->has_view_page()) {
4364 $this->page->navigation->initialise();
4365 $activenode = $this->page->navigation->find_active_node();
4366 // If the settings menu has been forced then show the menu.
4367 if ($this->page->is_settings_menu_forced()) {
4368 $showcoursemenu = true;
4369 } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
4370 $activenode->type == navigation_node::TYPE_RESOURCE)) {
4372 // We only want to show the menu on the first page of the activity. This means
4373 // the breadcrumb has no additional nodes.
4374 if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
4375 $showcoursemenu = true;
4380 // This is the site front page.
4381 if ($context->contextlevel == CONTEXT_COURSE &&
4382 !empty($currentnode) &&
4383 $currentnode->key === 'home') {
4384 $showfrontpagemenu = true;
4387 // This is the user profile page.
4388 if ($context->contextlevel == CONTEXT_USER &&
4389 !empty($currentnode) &&
4390 ($currentnode->key === 'myprofile')) {
4391 $showusermenu = true;
4394 if ($showfrontpagemenu) {
4395 $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
4396 if ($settingsnode) {
4397 // Build an action menu based on the visible nodes from this navigation tree.
4398 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4400 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4401 if ($skipped) {
4402 $text = get_string('morenavigationlinks');
4403 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4404 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4405 $menu->add_secondary_action($link);
4408 } else if ($showcoursemenu) {
4409 $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
4410 if ($settingsnode) {
4411 // Build an action menu based on the visible nodes from this navigation tree.
4412 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4414 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4415 if ($skipped) {
4416 $text = get_string('morenavigationlinks');
4417 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4418 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4419 $menu->add_secondary_action($link);
4422 } else if ($showusermenu) {
4423 // Get the course admin node from the settings navigation.
4424 $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
4425 if ($settingsnode) {
4426 // Build an action menu based on the visible nodes from this navigation tree.
4427 $this->build_action_menu_from_navigation($menu, $settingsnode);
4431 return $this->render($menu);
4435 * Take a node in the nav tree and make an action menu out of it.
4436 * The links are injected in the action menu.
4438 * @param action_menu $menu
4439 * @param navigation_node $node
4440 * @param boolean $indent
4441 * @param boolean $onlytopleafnodes
4442 * @return boolean nodesskipped - True if nodes were skipped in building the menu
4444 protected function build_action_menu_from_navigation(action_menu $menu,
4445 navigation_node $node,
4446 $indent = false,
4447 $onlytopleafnodes = false) {
4448 $skipped = false;
4449 // Build an action menu based on the visible nodes from this navigation tree.
4450 foreach ($node->children as $menuitem) {
4451 if ($menuitem->display) {
4452 if ($onlytopleafnodes && $menuitem->children->count()) {
4453 $skipped = true;
4454 continue;
4456 if ($menuitem->action) {
4457 if ($menuitem->action instanceof action_link) {
4458 $link = $menuitem->action;
4459 // Give preference to setting icon over action icon.
4460 if (!empty($menuitem->icon)) {
4461 $link->icon = $menuitem->icon;
4463 } else {
4464 $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
4466 } else {
4467 if ($onlytopleafnodes) {
4468 $skipped = true;
4469 continue;
4471 $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
4473 if ($indent) {
4474 $link->add_class('ml-4');
4476 if (!empty($menuitem->classes)) {
4477 $link->add_class(implode(" ", $menuitem->classes));
4480 $menu->add_secondary_action($link);
4481 $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
4484 return $skipped;
4488 * This is an optional menu that can be added to a layout by a theme. It contains the
4489 * menu for the most specific thing from the settings block. E.g. Module administration.
4491 * @return string
4493 public function region_main_settings_menu() {
4494 $context = $this->page->context;
4495 $menu = new action_menu();
4497 if ($context->contextlevel == CONTEXT_MODULE) {
4499 $this->page->navigation->initialise();
4500 $node = $this->page->navigation->find_active_node();
4501 $buildmenu = false;
4502 // If the settings menu has been forced then show the menu.
4503 if ($this->page->is_settings_menu_forced()) {
4504 $buildmenu = true;
4505 } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
4506 $node->type == navigation_node::TYPE_RESOURCE)) {
4508 $items = $this->page->navbar->get_items();
4509 $navbarnode = end($items);
4510 // We only want to show the menu on the first page of the activity. This means
4511 // the breadcrumb has no additional nodes.
4512 if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
4513 $buildmenu = true;
4516 if ($buildmenu) {
4517 // Get the course admin node from the settings navigation.
4518 $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
4519 if ($node) {
4520 // Build an action menu based on the visible nodes from this navigation tree.
4521 $this->build_action_menu_from_navigation($menu, $node);
4525 } else if ($context->contextlevel == CONTEXT_COURSECAT) {
4526 // For course category context, show category settings menu, if we're on the course category page.
4527 if ($this->page->pagetype === 'course-index-category') {
4528 $node = $this->page->settingsnav->find('categorysettings', navigation_node::TYPE_CONTAINER);
4529 if ($node) {
4530 // Build an action menu based on the visible nodes from this navigation tree.
4531 $this->build_action_menu_from_navigation($menu, $node);
4535 } else {
4536 $items = $this->page->navbar->get_items();
4537 $navbarnode = end($items);
4539 if ($navbarnode && ($navbarnode->key === 'participants')) {
4540 $node = $this->page->settingsnav->find('users', navigation_node::TYPE_CONTAINER);
4541 if ($node) {
4542 // Build an action menu based on the visible nodes from this navigation tree.
4543 $this->build_action_menu_from_navigation($menu, $node);
4548 return $this->render($menu);
4552 * Displays the list of tags associated with an entry
4554 * @param array $tags list of instances of core_tag or stdClass
4555 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4556 * to use default, set to '' (empty string) to omit the label completely
4557 * @param string $classes additional classes for the enclosing div element
4558 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4559 * will be appended to the end, JS will toggle the rest of the tags
4560 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4561 * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
4562 * @return string
4564 public function tag_list($tags, $label = null, $classes = '', $limit = 10,
4565 $pagecontext = null, $accesshidelabel = false) {
4566 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
4567 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4571 * Renders element for inline editing of any value
4573 * @param \core\output\inplace_editable $element
4574 * @return string
4576 public function render_inplace_editable(\core\output\inplace_editable $element) {
4577 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4581 * Renders a bar chart.
4583 * @param \core\chart_bar $chart The chart.
4584 * @return string.
4586 public function render_chart_bar(\core\chart_bar $chart) {
4587 return $this->render_chart($chart);
4591 * Renders a line chart.
4593 * @param \core\chart_line $chart The chart.
4594 * @return string.
4596 public function render_chart_line(\core\chart_line $chart) {
4597 return $this->render_chart($chart);
4601 * Renders a pie chart.
4603 * @param \core\chart_pie $chart The chart.
4604 * @return string.
4606 public function render_chart_pie(\core\chart_pie $chart) {
4607 return $this->render_chart($chart);
4611 * Renders a chart.
4613 * @param \core\chart_base $chart The chart.
4614 * @param bool $withtable Whether to include a data table with the chart.
4615 * @return string.
4617 public function render_chart(\core\chart_base $chart, $withtable = true) {
4618 $chartdata = json_encode($chart);
4619 return $this->render_from_template('core/chart', (object) [
4620 'chartdata' => $chartdata,
4621 'withtable' => $withtable
4626 * Renders the login form.
4628 * @param \core_auth\output\login $form The renderable.
4629 * @return string
4631 public function render_login(\core_auth\output\login $form) {
4632 global $CFG, $SITE;
4634 $context = $form->export_for_template($this);
4636 // Override because rendering is not supported in template yet.
4637 if ($CFG->rememberusername == 0) {
4638 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabledonlysession');
4639 } else {
4640 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
4642 $context->errorformatted = $this->error_text($context->error);
4643 $url = $this->get_logo_url();
4644 if ($url) {
4645 $url = $url->out(false);
4647 $context->logourl = $url;
4648 $context->sitename = format_string($SITE->fullname, true,
4649 ['context' => context_course::instance(SITEID), "escape" => false]);
4651 return $this->render_from_template('core/loginform', $context);
4655 * Renders an mform element from a template.
4657 * @param HTML_QuickForm_element $element element
4658 * @param bool $required if input is required field
4659 * @param bool $advanced if input is an advanced field
4660 * @param string $error error message to display
4661 * @param bool $ingroup True if this element is rendered as part of a group
4662 * @return mixed string|bool
4664 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4665 $templatename = 'core_form/element-' . $element->getType();
4666 if ($ingroup) {
4667 $templatename .= "-inline";
4669 try {
4670 // We call this to generate a file not found exception if there is no template.
4671 // We don't want to call export_for_template if there is no template.
4672 core\output\mustache_template_finder::get_template_filepath($templatename);
4674 if ($element instanceof templatable) {
4675 $elementcontext = $element->export_for_template($this);
4677 $helpbutton = '';
4678 if (method_exists($element, 'getHelpButton')) {
4679 $helpbutton = $element->getHelpButton();
4681 $label = $element->getLabel();
4682 $text = '';
4683 if (method_exists($element, 'getText')) {
4684 // There currently exists code that adds a form element with an empty label.
4685 // If this is the case then set the label to the description.
4686 if (empty($label)) {
4687 $label = $element->getText();
4688 } else {
4689 $text = $element->getText();
4693 // Generate the form element wrapper ids and names to pass to the template.
4694 // This differs between group and non-group elements.
4695 if ($element->getType() === 'group') {
4696 // Group element.
4697 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
4698 $elementcontext['wrapperid'] = $elementcontext['id'];
4700 // Ensure group elements pass through the group name as the element name.
4701 $elementcontext['name'] = $elementcontext['groupname'];
4702 } else {
4703 // Non grouped element.
4704 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
4705 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
4708 $context = array(
4709 'element' => $elementcontext,
4710 'label' => $label,
4711 'text' => $text,
4712 'required' => $required,
4713 'advanced' => $advanced,
4714 'helpbutton' => $helpbutton,
4715 'error' => $error
4717 return $this->render_from_template($templatename, $context);
4719 } catch (Exception $e) {
4720 // No template for this element.
4721 return false;
4726 * Render the login signup form into a nice template for the theme.
4728 * @param mform $form
4729 * @return string
4731 public function render_login_signup_form($form) {
4732 global $SITE;
4734 $context = $form->export_for_template($this);
4735 $url = $this->get_logo_url();
4736 if ($url) {
4737 $url = $url->out(false);
4739 $context['logourl'] = $url;
4740 $context['sitename'] = format_string($SITE->fullname, true,
4741 ['context' => context_course::instance(SITEID), "escape" => false]);
4743 return $this->render_from_template('core/signup_form_layout', $context);
4747 * Render the verify age and location page into a nice template for the theme.
4749 * @param \core_auth\output\verify_age_location_page $page The renderable
4750 * @return string
4752 protected function render_verify_age_location_page($page) {
4753 $context = $page->export_for_template($this);
4755 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4759 * Render the digital minor contact information page into a nice template for the theme.
4761 * @param \core_auth\output\digital_minor_page $page The renderable
4762 * @return string
4764 protected function render_digital_minor_page($page) {
4765 $context = $page->export_for_template($this);
4767 return $this->render_from_template('core/auth_digital_minor_page', $context);
4771 * Renders a progress bar.
4773 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4775 * @param progress_bar $bar The bar.
4776 * @return string HTML fragment
4778 public function render_progress_bar(progress_bar $bar) {
4779 $data = $bar->export_for_template($this);
4780 return $this->render_from_template('core/progress_bar', $data);
4784 * Renders element for a toggle-all checkbox.
4786 * @param \core\output\checkbox_toggleall $element
4787 * @return string
4789 public function render_checkbox_toggleall(\core\output\checkbox_toggleall $element) {
4790 return $this->render_from_template($element->get_template(), $element->export_for_template($this));
4795 * A renderer that generates output for command-line scripts.
4797 * The implementation of this renderer is probably incomplete.
4799 * @copyright 2009 Tim Hunt
4800 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4801 * @since Moodle 2.0
4802 * @package core
4803 * @category output
4805 class core_renderer_cli extends core_renderer {
4808 * Returns the page header.
4810 * @return string HTML fragment
4812 public function header() {
4813 return $this->page->heading . "\n";
4817 * Renders a Check API result
4819 * To aid in CLI consistency this status is NOT translated and the visual
4820 * width is always exactly 10 chars.
4822 * @param result $result
4823 * @return string HTML fragment
4825 protected function render_check_result(core\check\result $result) {
4826 $status = $result->get_status();
4828 $labels = [
4829 core\check\result::NA => ' ' . cli_ansi_format('<colour:gray>' ) . ' NA ',
4830 core\check\result::OK => ' ' . cli_ansi_format('<colour:green>') . ' OK ',
4831 core\check\result::INFO => ' ' . cli_ansi_format('<colour:blue>' ) . ' INFO ',
4832 core\check\result::UNKNOWN => ' ' . cli_ansi_format('<colour:grey>' ) . ' UNKNOWN ',
4833 core\check\result::WARNING => ' ' . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
4834 core\check\result::ERROR => ' ' . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
4835 core\check\result::CRITICAL => '' . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
4837 $string = $labels[$status] . cli_ansi_format('<colour:normal>');
4838 return $string;
4842 * Renders a Check API result
4844 * @param result $result
4845 * @return string fragment
4847 public function check_result(core\check\result $result) {
4848 return $this->render_check_result($result);
4852 * Returns a template fragment representing a Heading.
4854 * @param string $text The text of the heading
4855 * @param int $level The level of importance of the heading
4856 * @param string $classes A space-separated list of CSS classes
4857 * @param string $id An optional ID
4858 * @return string A template fragment for a heading
4860 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4861 $text .= "\n";
4862 switch ($level) {
4863 case 1:
4864 return '=>' . $text;
4865 case 2:
4866 return '-->' . $text;
4867 default:
4868 return $text;
4873 * Returns a template fragment representing a fatal error.
4875 * @param string $message The message to output
4876 * @param string $moreinfourl URL where more info can be found about the error
4877 * @param string $link Link for the Continue button
4878 * @param array $backtrace The execution backtrace
4879 * @param string $debuginfo Debugging information
4880 * @return string A template fragment for a fatal error
4882 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4883 global $CFG;
4885 $output = "!!! $message !!!\n";
4887 if ($CFG->debugdeveloper) {
4888 if (!empty($debuginfo)) {
4889 $output .= $this->notification($debuginfo, 'notifytiny');
4891 if (!empty($backtrace)) {
4892 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
4896 return $output;
4900 * Returns a template fragment representing a notification.
4902 * @param string $message The message to print out.
4903 * @param string $type The type of notification. See constants on \core\output\notification.
4904 * @return string A template fragment for a notification
4906 public function notification($message, $type = null) {
4907 $message = clean_text($message);
4908 if ($type === 'notifysuccess' || $type === 'success') {
4909 return "++ $message ++\n";
4911 return "!! $message !!\n";
4915 * There is no footer for a cli request, however we must override the
4916 * footer method to prevent the default footer.
4918 public function footer() {}
4921 * Render a notification (that is, a status message about something that has
4922 * just happened).
4924 * @param \core\output\notification $notification the notification to print out
4925 * @return string plain text output
4927 public function render_notification(\core\output\notification $notification) {
4928 return $this->notification($notification->get_message(), $notification->get_message_type());
4934 * A renderer that generates output for ajax scripts.
4936 * This renderer prevents accidental sends back only json
4937 * encoded error messages, all other output is ignored.
4939 * @copyright 2010 Petr Skoda
4940 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4941 * @since Moodle 2.0
4942 * @package core
4943 * @category output
4945 class core_renderer_ajax extends core_renderer {
4948 * Returns a template fragment representing a fatal error.
4950 * @param string $message The message to output
4951 * @param string $moreinfourl URL where more info can be found about the error
4952 * @param string $link Link for the Continue button
4953 * @param array $backtrace The execution backtrace
4954 * @param string $debuginfo Debugging information
4955 * @return string A template fragment for a fatal error
4957 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4958 global $CFG;
4960 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
4962 $e = new stdClass();
4963 $e->error = $message;
4964 $e->errorcode = $errorcode;
4965 $e->stacktrace = NULL;
4966 $e->debuginfo = NULL;
4967 $e->reproductionlink = NULL;
4968 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
4969 $link = (string) $link;
4970 if ($link) {
4971 $e->reproductionlink = $link;
4973 if (!empty($debuginfo)) {
4974 $e->debuginfo = $debuginfo;
4976 if (!empty($backtrace)) {
4977 $e->stacktrace = format_backtrace($backtrace, true);
4980 $this->header();
4981 return json_encode($e);
4985 * Used to display a notification.
4986 * For the AJAX notifications are discarded.
4988 * @param string $message The message to print out.
4989 * @param string $type The type of notification. See constants on \core\output\notification.
4991 public function notification($message, $type = null) {}
4994 * Used to display a redirection message.
4995 * AJAX redirections should not occur and as such redirection messages
4996 * are discarded.
4998 * @param moodle_url|string $encodedurl
4999 * @param string $message
5000 * @param int $delay
5001 * @param bool $debugdisableredirect
5002 * @param string $messagetype The type of notification to show the message in.
5003 * See constants on \core\output\notification.
5005 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
5006 $messagetype = \core\output\notification::NOTIFY_INFO) {}
5009 * Prepares the start of an AJAX output.
5011 public function header() {
5012 // unfortunately YUI iframe upload does not support application/json
5013 if (!empty($_FILES)) {
5014 @header('Content-type: text/plain; charset=utf-8');
5015 if (!core_useragent::supports_json_contenttype()) {
5016 @header('X-Content-Type-Options: nosniff');
5018 } else if (!core_useragent::supports_json_contenttype()) {
5019 @header('Content-type: text/plain; charset=utf-8');
5020 @header('X-Content-Type-Options: nosniff');
5021 } else {
5022 @header('Content-type: application/json; charset=utf-8');
5025 // Headers to make it not cacheable and json
5026 @header('Cache-Control: no-store, no-cache, must-revalidate');
5027 @header('Cache-Control: post-check=0, pre-check=0', false);
5028 @header('Pragma: no-cache');
5029 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
5030 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
5031 @header('Accept-Ranges: none');
5035 * There is no footer for an AJAX request, however we must override the
5036 * footer method to prevent the default footer.
5038 public function footer() {}
5041 * No need for headers in an AJAX request... this should never happen.
5042 * @param string $text
5043 * @param int $level
5044 * @param string $classes
5045 * @param string $id
5047 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
5053 * The maintenance renderer.
5055 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
5056 * is running a maintenance related task.
5057 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
5059 * @since Moodle 2.6
5060 * @package core
5061 * @category output
5062 * @copyright 2013 Sam Hemelryk
5063 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5065 class core_renderer_maintenance extends core_renderer {
5068 * Initialises the renderer instance.
5070 * @param moodle_page $page
5071 * @param string $target
5072 * @throws coding_exception
5074 public function __construct(moodle_page $page, $target) {
5075 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
5076 throw new coding_exception('Invalid request for the maintenance renderer.');
5078 parent::__construct($page, $target);
5082 * Does nothing. The maintenance renderer cannot produce blocks.
5084 * @param block_contents $bc
5085 * @param string $region
5086 * @return string
5088 public function block(block_contents $bc, $region) {
5089 return '';
5093 * Does nothing. The maintenance renderer cannot produce blocks.
5095 * @param string $region
5096 * @param array $classes
5097 * @param string $tag
5098 * @return string
5100 public function blocks($region, $classes = array(), $tag = 'aside') {
5101 return '';
5105 * Does nothing. The maintenance renderer cannot produce blocks.
5107 * @param string $region
5108 * @return string
5110 public function blocks_for_region($region) {
5111 return '';
5115 * Does nothing. The maintenance renderer cannot produce a course content header.
5117 * @param bool $onlyifnotcalledbefore
5118 * @return string
5120 public function course_content_header($onlyifnotcalledbefore = false) {
5121 return '';
5125 * Does nothing. The maintenance renderer cannot produce a course content footer.
5127 * @param bool $onlyifnotcalledbefore
5128 * @return string
5130 public function course_content_footer($onlyifnotcalledbefore = false) {
5131 return '';
5135 * Does nothing. The maintenance renderer cannot produce a course header.
5137 * @return string
5139 public function course_header() {
5140 return '';
5144 * Does nothing. The maintenance renderer cannot produce a course footer.
5146 * @return string
5148 public function course_footer() {
5149 return '';
5153 * Does nothing. The maintenance renderer cannot produce a custom menu.
5155 * @param string $custommenuitems
5156 * @return string
5158 public function custom_menu($custommenuitems = '') {
5159 return '';
5163 * Does nothing. The maintenance renderer cannot produce a file picker.
5165 * @param array $options
5166 * @return string
5168 public function file_picker($options) {
5169 return '';
5173 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
5175 * @param array $dir
5176 * @return string
5178 public function htmllize_file_tree($dir) {
5179 return '';
5184 * Overridden confirm message for upgrades.
5186 * @param string $message The question to ask the user
5187 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5188 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5189 * @return string HTML fragment
5191 public function confirm($message, $continue, $cancel) {
5192 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5193 // from any previous version of Moodle).
5194 if ($continue instanceof single_button) {
5195 $continue->primary = true;
5196 } else if (is_string($continue)) {
5197 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
5198 } else if ($continue instanceof moodle_url) {
5199 $continue = new single_button($continue, get_string('continue'), 'post', true);
5200 } else {
5201 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5202 ' (string/moodle_url) or a single_button instance.');
5205 if ($cancel instanceof single_button) {
5206 $output = '';
5207 } else if (is_string($cancel)) {
5208 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5209 } else if ($cancel instanceof moodle_url) {
5210 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5211 } else {
5212 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5213 ' (string/moodle_url) or a single_button instance.');
5216 $output = $this->box_start('generalbox', 'notice');
5217 $output .= html_writer::tag('h4', get_string('confirm'));
5218 $output .= html_writer::tag('p', $message);
5219 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
5220 $output .= $this->box_end();
5221 return $output;
5225 * Does nothing. The maintenance renderer does not support JS.
5227 * @param block_contents $bc
5229 public function init_block_hider_js(block_contents $bc) {
5230 // Does nothing.
5234 * Does nothing. The maintenance renderer cannot produce language menus.
5236 * @return string
5238 public function lang_menu() {
5239 return '';
5243 * Does nothing. The maintenance renderer has no need for login information.
5245 * @param null $withlinks
5246 * @return string
5248 public function login_info($withlinks = null) {
5249 return '';
5253 * Secure login info.
5255 * @return string
5257 public function secure_login_info() {
5258 return $this->login_info(false);
5262 * Does nothing. The maintenance renderer cannot produce user pictures.
5264 * @param stdClass $user
5265 * @param array $options
5266 * @return string
5268 public function user_picture(stdClass $user, array $options = null) {
5269 return '';