Merge branch 'MDL-45849-selfenrol' of https://github.com/Peterburnett/moodle
[moodle.git] / lib / outputrenderers.php
blob8802a9e90ec7297054c873af0624e3ea4ec92824
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 'blacklistednestedhelpers' => ['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-a-1 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, true);
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, true);
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 // Give plugins an opportunity to touch the page before JS is finalized.
1389 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1390 foreach ($pluginswithfunction as $plugins) {
1391 foreach ($plugins as $function) {
1392 $function();
1396 $output = $this->container_end_all(true);
1398 $footer = $this->opencontainers->pop('header/footer');
1400 if (debugging() and $DB and $DB->is_transaction_started()) {
1401 // TODO: MDL-20625 print warning - transaction will be rolled back
1404 // Provide some performance info if required
1405 $performanceinfo = '';
1406 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1407 $perf = get_performance_info();
1408 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1409 $performanceinfo = $perf['html'];
1413 // We always want performance data when running a performance test, even if the user is redirected to another page.
1414 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1415 $footer = $this->unique_performance_info_token . $footer;
1417 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1419 // Only show notifications when the current page has a context id.
1420 if (!empty($this->page->context->id)) {
1421 $this->page->requires->js_call_amd('core/notification', 'init', array(
1422 $this->page->context->id,
1423 \core\notification::fetch_as_array($this),
1424 isloggedin()
1427 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1429 $this->page->set_state(moodle_page::STATE_DONE);
1431 return $output . $footer;
1435 * Close all but the last open container. This is useful in places like error
1436 * handling, where you want to close all the open containers (apart from <body>)
1437 * before outputting the error message.
1439 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1440 * developer debug warning if it isn't.
1441 * @return string the HTML required to close any open containers inside <body>.
1443 public function container_end_all($shouldbenone = false) {
1444 return $this->opencontainers->pop_all_but_last($shouldbenone);
1448 * Returns course-specific information to be output immediately above content on any course page
1449 * (for the current course)
1451 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1452 * @return string
1454 public function course_content_header($onlyifnotcalledbefore = false) {
1455 global $CFG;
1456 static $functioncalled = false;
1457 if ($functioncalled && $onlyifnotcalledbefore) {
1458 // we have already output the content header
1459 return '';
1462 // Output any session notification.
1463 $notifications = \core\notification::fetch();
1465 $bodynotifications = '';
1466 foreach ($notifications as $notification) {
1467 $bodynotifications .= $this->render_from_template(
1468 $notification->get_template_name(),
1469 $notification->export_for_template($this)
1473 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1475 if ($this->page->course->id == SITEID) {
1476 // return immediately and do not include /course/lib.php if not necessary
1477 return $output;
1480 require_once($CFG->dirroot.'/course/lib.php');
1481 $functioncalled = true;
1482 $courseformat = course_get_format($this->page->course);
1483 if (($obj = $courseformat->course_content_header()) !== null) {
1484 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1486 return $output;
1490 * Returns course-specific information to be output immediately below content on any course page
1491 * (for the current course)
1493 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1494 * @return string
1496 public function course_content_footer($onlyifnotcalledbefore = false) {
1497 global $CFG;
1498 if ($this->page->course->id == SITEID) {
1499 // return immediately and do not include /course/lib.php if not necessary
1500 return '';
1502 static $functioncalled = false;
1503 if ($functioncalled && $onlyifnotcalledbefore) {
1504 // we have already output the content footer
1505 return '';
1507 $functioncalled = true;
1508 require_once($CFG->dirroot.'/course/lib.php');
1509 $courseformat = course_get_format($this->page->course);
1510 if (($obj = $courseformat->course_content_footer()) !== null) {
1511 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1513 return '';
1517 * Returns course-specific information to be output on any course page in the header area
1518 * (for the current course)
1520 * @return string
1522 public function course_header() {
1523 global $CFG;
1524 if ($this->page->course->id == SITEID) {
1525 // return immediately and do not include /course/lib.php if not necessary
1526 return '';
1528 require_once($CFG->dirroot.'/course/lib.php');
1529 $courseformat = course_get_format($this->page->course);
1530 if (($obj = $courseformat->course_header()) !== null) {
1531 return $courseformat->get_renderer($this->page)->render($obj);
1533 return '';
1537 * Returns course-specific information to be output on any course page in the footer area
1538 * (for the current course)
1540 * @return string
1542 public function course_footer() {
1543 global $CFG;
1544 if ($this->page->course->id == SITEID) {
1545 // return immediately and do not include /course/lib.php if not necessary
1546 return '';
1548 require_once($CFG->dirroot.'/course/lib.php');
1549 $courseformat = course_get_format($this->page->course);
1550 if (($obj = $courseformat->course_footer()) !== null) {
1551 return $courseformat->get_renderer($this->page)->render($obj);
1553 return '';
1557 * Get the course pattern datauri to show on a course card.
1559 * The datauri is an encoded svg that can be passed as a url.
1560 * @param int $id Id to use when generating the pattern
1561 * @return string datauri
1563 public function get_generated_image_for_id($id) {
1564 $color = $this->get_generated_color_for_id($id);
1565 $pattern = new \core_geopattern();
1566 $pattern->setColor($color);
1567 $pattern->patternbyid($id);
1568 return $pattern->datauri();
1572 * Get the course color to show on a course card.
1574 * @param int $id Id to use when generating the color.
1575 * @return string hex color code.
1577 public function get_generated_color_for_id($id) {
1578 $colornumbers = range(1, 10);
1579 $basecolors = [];
1580 foreach ($colornumbers as $number) {
1581 $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1584 $color = $basecolors[$id % 10];
1585 return $color;
1589 * Returns lang menu or '', this method also checks forcing of languages in courses.
1591 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1593 * @return string The lang menu HTML or empty string
1595 public function lang_menu() {
1596 global $CFG;
1598 if (empty($CFG->langmenu)) {
1599 return '';
1602 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1603 // do not show lang menu if language forced
1604 return '';
1607 $currlang = current_language();
1608 $langs = get_string_manager()->get_list_of_translations();
1610 if (count($langs) < 2) {
1611 return '';
1614 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1615 $s->label = get_accesshide(get_string('language'));
1616 $s->class = 'langmenu';
1617 return $this->render($s);
1621 * Output the row of editing icons for a block, as defined by the controls array.
1623 * @param array $controls an array like {@link block_contents::$controls}.
1624 * @param string $blockid The ID given to the block.
1625 * @return string HTML fragment.
1627 public function block_controls($actions, $blockid = null) {
1628 global $CFG;
1629 if (empty($actions)) {
1630 return '';
1632 $menu = new action_menu($actions);
1633 if ($blockid !== null) {
1634 $menu->set_owner_selector('#'.$blockid);
1636 $menu->set_constraint('.block-region');
1637 $menu->attributes['class'] .= ' block-control-actions commands';
1638 return $this->render($menu);
1642 * Returns the HTML for a basic textarea field.
1644 * @param string $name Name to use for the textarea element
1645 * @param string $id The id to use fort he textarea element
1646 * @param string $value Initial content to display in the textarea
1647 * @param int $rows Number of rows to display
1648 * @param int $cols Number of columns to display
1649 * @return string the HTML to display
1651 public function print_textarea($name, $id, $value, $rows, $cols) {
1652 editors_head_setup();
1653 $editor = editors_get_preferred_editor(FORMAT_HTML);
1654 $editor->set_text($value);
1655 $editor->use_editor($id, []);
1657 $context = [
1658 'id' => $id,
1659 'name' => $name,
1660 'value' => $value,
1661 'rows' => $rows,
1662 'cols' => $cols
1665 return $this->render_from_template('core_form/editor_textarea', $context);
1669 * Renders an action menu component.
1671 * @param action_menu $menu
1672 * @return string HTML
1674 public function render_action_menu(action_menu $menu) {
1676 // We don't want the class icon there!
1677 foreach ($menu->get_secondary_actions() as $action) {
1678 if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1679 $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1683 if ($menu->is_empty()) {
1684 return '';
1686 $context = $menu->export_for_template($this);
1688 return $this->render_from_template('core/action_menu', $context);
1692 * Renders a Check API result
1694 * @param result $result
1695 * @return string HTML fragment
1697 protected function render_check_result(core\check\result $result) {
1698 return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1702 * Renders a Check API result
1704 * @param result $result
1705 * @return string HTML fragment
1707 public function check_result(core\check\result $result) {
1708 return $this->render_check_result($result);
1712 * Renders an action_menu_link item.
1714 * @param action_menu_link $action
1715 * @return string HTML fragment
1717 protected function render_action_menu_link(action_menu_link $action) {
1718 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1722 * Renders a primary action_menu_filler item.
1724 * @param action_menu_link_filler $action
1725 * @return string HTML fragment
1727 protected function render_action_menu_filler(action_menu_filler $action) {
1728 return html_writer::span('&nbsp;', 'filler');
1732 * Renders a primary action_menu_link item.
1734 * @param action_menu_link_primary $action
1735 * @return string HTML fragment
1737 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1738 return $this->render_action_menu_link($action);
1742 * Renders a secondary action_menu_link item.
1744 * @param action_menu_link_secondary $action
1745 * @return string HTML fragment
1747 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1748 return $this->render_action_menu_link($action);
1752 * Prints a nice side block with an optional header.
1754 * @param block_contents $bc HTML for the content
1755 * @param string $region the region the block is appearing in.
1756 * @return string the HTML to be output.
1758 public function block(block_contents $bc, $region) {
1759 $bc = clone($bc); // Avoid messing up the object passed in.
1760 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1761 $bc->collapsible = block_contents::NOT_HIDEABLE;
1764 $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1765 $context = new stdClass();
1766 $context->skipid = $bc->skipid;
1767 $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
1768 $context->dockable = $bc->dockable;
1769 $context->id = $id;
1770 $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1771 $context->skiptitle = strip_tags($bc->title);
1772 $context->showskiplink = !empty($context->skiptitle);
1773 $context->arialabel = $bc->arialabel;
1774 $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
1775 $context->class = $bc->attributes['class'];
1776 $context->type = $bc->attributes['data-block'];
1777 $context->title = $bc->title;
1778 $context->content = $bc->content;
1779 $context->annotation = $bc->annotation;
1780 $context->footer = $bc->footer;
1781 $context->hascontrols = !empty($bc->controls);
1782 if ($context->hascontrols) {
1783 $context->controls = $this->block_controls($bc->controls, $id);
1786 return $this->render_from_template('core/block', $context);
1790 * Render the contents of a block_list.
1792 * @param array $icons the icon for each item.
1793 * @param array $items the content of each item.
1794 * @return string HTML
1796 public function list_block_contents($icons, $items) {
1797 $row = 0;
1798 $lis = array();
1799 foreach ($items as $key => $string) {
1800 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1801 if (!empty($icons[$key])) { //test if the content has an assigned icon
1802 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1804 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1805 $item .= html_writer::end_tag('li');
1806 $lis[] = $item;
1807 $row = 1 - $row; // Flip even/odd.
1809 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1813 * Output all the blocks in a particular region.
1815 * @param string $region the name of a region on this page.
1816 * @return string the HTML to be output.
1818 public function blocks_for_region($region) {
1819 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1820 $blocks = $this->page->blocks->get_blocks_for_region($region);
1821 $lastblock = null;
1822 $zones = array();
1823 foreach ($blocks as $block) {
1824 $zones[] = $block->title;
1826 $output = '';
1828 foreach ($blockcontents as $bc) {
1829 if ($bc instanceof block_contents) {
1830 $output .= $this->block($bc, $region);
1831 $lastblock = $bc->title;
1832 } else if ($bc instanceof block_move_target) {
1833 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1834 } else {
1835 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1838 return $output;
1842 * Output a place where the block that is currently being moved can be dropped.
1844 * @param block_move_target $target with the necessary details.
1845 * @param array $zones array of areas where the block can be moved to
1846 * @param string $previous the block located before the area currently being rendered.
1847 * @param string $region the name of the region
1848 * @return string the HTML to be output.
1850 public function block_move_target($target, $zones, $previous, $region) {
1851 if ($previous == null) {
1852 if (empty($zones)) {
1853 // There are no zones, probably because there are no blocks.
1854 $regions = $this->page->theme->get_all_block_regions();
1855 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1856 } else {
1857 $position = get_string('moveblockbefore', 'block', $zones[0]);
1859 } else {
1860 $position = get_string('moveblockafter', 'block', $previous);
1862 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1866 * Renders a special html link with attached action
1868 * Theme developers: DO NOT OVERRIDE! Please override function
1869 * {@link core_renderer::render_action_link()} instead.
1871 * @param string|moodle_url $url
1872 * @param string $text HTML fragment
1873 * @param component_action $action
1874 * @param array $attributes associative array of html link attributes + disabled
1875 * @param pix_icon optional pix icon to render with the link
1876 * @return string HTML fragment
1878 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1879 if (!($url instanceof moodle_url)) {
1880 $url = new moodle_url($url);
1882 $link = new action_link($url, $text, $action, $attributes, $icon);
1884 return $this->render($link);
1888 * Renders an action_link object.
1890 * The provided link is renderer and the HTML returned. At the same time the
1891 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1893 * @param action_link $link
1894 * @return string HTML fragment
1896 protected function render_action_link(action_link $link) {
1897 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1901 * Renders an action_icon.
1903 * This function uses the {@link core_renderer::action_link()} method for the
1904 * most part. What it does different is prepare the icon as HTML and use it
1905 * as the link text.
1907 * Theme developers: If you want to change how action links and/or icons are rendered,
1908 * consider overriding function {@link core_renderer::render_action_link()} and
1909 * {@link core_renderer::render_pix_icon()}.
1911 * @param string|moodle_url $url A string URL or moodel_url
1912 * @param pix_icon $pixicon
1913 * @param component_action $action
1914 * @param array $attributes associative array of html link attributes + disabled
1915 * @param bool $linktext show title next to image in link
1916 * @return string HTML fragment
1918 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1919 if (!($url instanceof moodle_url)) {
1920 $url = new moodle_url($url);
1922 $attributes = (array)$attributes;
1924 if (empty($attributes['class'])) {
1925 // let ppl override the class via $options
1926 $attributes['class'] = 'action-icon';
1929 $icon = $this->render($pixicon);
1931 if ($linktext) {
1932 $text = $pixicon->attributes['alt'];
1933 } else {
1934 $text = '';
1937 return $this->action_link($url, $text.$icon, $action, $attributes);
1941 * Print a message along with button choices for Continue/Cancel
1943 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1945 * @param string $message The question to ask the user
1946 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1947 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1948 * @return string HTML fragment
1950 public function confirm($message, $continue, $cancel) {
1951 if ($continue instanceof single_button) {
1952 // ok
1953 $continue->primary = true;
1954 } else if (is_string($continue)) {
1955 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1956 } else if ($continue instanceof moodle_url) {
1957 $continue = new single_button($continue, get_string('continue'), 'post', true);
1958 } else {
1959 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1962 if ($cancel instanceof single_button) {
1963 // ok
1964 } else if (is_string($cancel)) {
1965 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1966 } else if ($cancel instanceof moodle_url) {
1967 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1968 } else {
1969 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1972 $attributes = [
1973 'role'=>'alertdialog',
1974 'aria-labelledby'=>'modal-header',
1975 'aria-describedby'=>'modal-body',
1976 'aria-modal'=>'true'
1979 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
1980 $output .= $this->box_start('modal-content', 'modal-content');
1981 $output .= $this->box_start('modal-header p-x-1', 'modal-header');
1982 $output .= html_writer::tag('h4', get_string('confirm'));
1983 $output .= $this->box_end();
1984 $attributes = [
1985 'role'=>'alert',
1986 'data-aria-autofocus'=>'true'
1988 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
1989 $output .= html_writer::tag('p', $message);
1990 $output .= $this->box_end();
1991 $output .= $this->box_start('modal-footer', 'modal-footer');
1992 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1993 $output .= $this->box_end();
1994 $output .= $this->box_end();
1995 $output .= $this->box_end();
1996 return $output;
2000 * Returns a form with a single button.
2002 * Theme developers: DO NOT OVERRIDE! Please override function
2003 * {@link core_renderer::render_single_button()} instead.
2005 * @param string|moodle_url $url
2006 * @param string $label button text
2007 * @param string $method get or post submit method
2008 * @param array $options associative array {disabled, title, etc.}
2009 * @return string HTML fragment
2011 public function single_button($url, $label, $method='post', array $options=null) {
2012 if (!($url instanceof moodle_url)) {
2013 $url = new moodle_url($url);
2015 $button = new single_button($url, $label, $method);
2017 foreach ((array)$options as $key=>$value) {
2018 if (property_exists($button, $key)) {
2019 $button->$key = $value;
2020 } else {
2021 $button->set_attribute($key, $value);
2025 return $this->render($button);
2029 * Renders a single button widget.
2031 * This will return HTML to display a form containing a single button.
2033 * @param single_button $button
2034 * @return string HTML fragment
2036 protected function render_single_button(single_button $button) {
2037 return $this->render_from_template('core/single_button', $button->export_for_template($this));
2041 * Returns a form with a single select widget.
2043 * Theme developers: DO NOT OVERRIDE! Please override function
2044 * {@link core_renderer::render_single_select()} instead.
2046 * @param moodle_url $url form action target, includes hidden fields
2047 * @param string $name name of selection field - the changing parameter in url
2048 * @param array $options list of options
2049 * @param string $selected selected element
2050 * @param array $nothing
2051 * @param string $formid
2052 * @param array $attributes other attributes for the single select
2053 * @return string HTML fragment
2055 public function single_select($url, $name, array $options, $selected = '',
2056 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2057 if (!($url instanceof moodle_url)) {
2058 $url = new moodle_url($url);
2060 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2062 if (array_key_exists('label', $attributes)) {
2063 $select->set_label($attributes['label']);
2064 unset($attributes['label']);
2066 $select->attributes = $attributes;
2068 return $this->render($select);
2072 * Returns a dataformat selection and download form
2074 * @param string $label A text label
2075 * @param moodle_url|string $base The download page url
2076 * @param string $name The query param which will hold the type of the download
2077 * @param array $params Extra params sent to the download page
2078 * @return string HTML fragment
2080 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2082 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2083 $options = array();
2084 foreach ($formats as $format) {
2085 if ($format->is_enabled()) {
2086 $options[] = array(
2087 'value' => $format->name,
2088 'label' => get_string('dataformat', $format->component),
2092 $hiddenparams = array();
2093 foreach ($params as $key => $value) {
2094 $hiddenparams[] = array(
2095 'name' => $key,
2096 'value' => $value,
2099 $data = array(
2100 'label' => $label,
2101 'base' => $base,
2102 'name' => $name,
2103 'params' => $hiddenparams,
2104 'options' => $options,
2105 'sesskey' => sesskey(),
2106 'submit' => get_string('download'),
2109 return $this->render_from_template('core/dataformat_selector', $data);
2114 * Internal implementation of single_select rendering
2116 * @param single_select $select
2117 * @return string HTML fragment
2119 protected function render_single_select(single_select $select) {
2120 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2124 * Returns a form with a url select widget.
2126 * Theme developers: DO NOT OVERRIDE! Please override function
2127 * {@link core_renderer::render_url_select()} instead.
2129 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2130 * @param string $selected selected element
2131 * @param array $nothing
2132 * @param string $formid
2133 * @return string HTML fragment
2135 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2136 $select = new url_select($urls, $selected, $nothing, $formid);
2137 return $this->render($select);
2141 * Internal implementation of url_select rendering
2143 * @param url_select $select
2144 * @return string HTML fragment
2146 protected function render_url_select(url_select $select) {
2147 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2151 * Returns a string containing a link to the user documentation.
2152 * Also contains an icon by default. Shown to teachers and admin only.
2154 * @param string $path The page link after doc root and language, no leading slash.
2155 * @param string $text The text to be displayed for the link
2156 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2157 * @param array $attributes htm attributes
2158 * @return string
2160 public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
2161 global $CFG;
2163 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2165 $attributes['href'] = new moodle_url(get_docs_url($path));
2166 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2167 $attributes['class'] = 'helplinkpopup';
2170 return html_writer::tag('a', $icon.$text, $attributes);
2174 * Return HTML for an image_icon.
2176 * Theme developers: DO NOT OVERRIDE! Please override function
2177 * {@link core_renderer::render_image_icon()} instead.
2179 * @param string $pix short pix name
2180 * @param string $alt mandatory alt attribute
2181 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2182 * @param array $attributes htm attributes
2183 * @return string HTML fragment
2185 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2186 $icon = new image_icon($pix, $alt, $component, $attributes);
2187 return $this->render($icon);
2191 * Renders a pix_icon widget and returns the HTML to display it.
2193 * @param image_icon $icon
2194 * @return string HTML fragment
2196 protected function render_image_icon(image_icon $icon) {
2197 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2198 return $system->render_pix_icon($this, $icon);
2202 * Return HTML for a pix_icon.
2204 * Theme developers: DO NOT OVERRIDE! Please override function
2205 * {@link core_renderer::render_pix_icon()} instead.
2207 * @param string $pix short pix name
2208 * @param string $alt mandatory alt attribute
2209 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2210 * @param array $attributes htm lattributes
2211 * @return string HTML fragment
2213 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2214 $icon = new pix_icon($pix, $alt, $component, $attributes);
2215 return $this->render($icon);
2219 * Renders a pix_icon widget and returns the HTML to display it.
2221 * @param pix_icon $icon
2222 * @return string HTML fragment
2224 protected function render_pix_icon(pix_icon $icon) {
2225 $system = \core\output\icon_system::instance();
2226 return $system->render_pix_icon($this, $icon);
2230 * Return HTML to display an emoticon icon.
2232 * @param pix_emoticon $emoticon
2233 * @return string HTML fragment
2235 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2236 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2237 return $system->render_pix_icon($this, $emoticon);
2241 * Produces the html that represents this rating in the UI
2243 * @param rating $rating the page object on which this rating will appear
2244 * @return string
2246 function render_rating(rating $rating) {
2247 global $CFG, $USER;
2249 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2250 return null;//ratings are turned off
2253 $ratingmanager = new rating_manager();
2254 // Initialise the JavaScript so ratings can be done by AJAX.
2255 $ratingmanager->initialise_rating_javascript($this->page);
2257 $strrate = get_string("rate", "rating");
2258 $ratinghtml = ''; //the string we'll return
2260 // permissions check - can they view the aggregate?
2261 if ($rating->user_can_view_aggregate()) {
2263 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2264 $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2265 $aggregatestr = $rating->get_aggregate_string();
2267 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2268 if ($rating->count > 0) {
2269 $countstr = "({$rating->count})";
2270 } else {
2271 $countstr = '-';
2273 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2275 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2277 $nonpopuplink = $rating->get_view_ratings_url();
2278 $popuplink = $rating->get_view_ratings_url(true);
2280 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2281 $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
2284 $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
2287 $formstart = null;
2288 // if the item doesn't belong to the current user, the user has permission to rate
2289 // and we're within the assessable period
2290 if ($rating->user_can_rate()) {
2292 $rateurl = $rating->get_rate_url();
2293 $inputs = $rateurl->params();
2295 //start the rating form
2296 $formattrs = array(
2297 'id' => "postrating{$rating->itemid}",
2298 'class' => 'postratingform',
2299 'method' => 'post',
2300 'action' => $rateurl->out_omit_querystring()
2302 $formstart = html_writer::start_tag('form', $formattrs);
2303 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2305 // add the hidden inputs
2306 foreach ($inputs as $name => $value) {
2307 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2308 $formstart .= html_writer::empty_tag('input', $attributes);
2311 if (empty($ratinghtml)) {
2312 $ratinghtml .= $strrate.': ';
2314 $ratinghtml = $formstart.$ratinghtml;
2316 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2317 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2318 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2319 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2321 //output submit button
2322 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2324 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2325 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2327 if (!$rating->settings->scale->isnumeric) {
2328 // If a global scale, try to find current course ID from the context
2329 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2330 $courseid = $coursecontext->instanceid;
2331 } else {
2332 $courseid = $rating->settings->scale->courseid;
2334 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2336 $ratinghtml .= html_writer::end_tag('span');
2337 $ratinghtml .= html_writer::end_tag('div');
2338 $ratinghtml .= html_writer::end_tag('form');
2341 return $ratinghtml;
2345 * Centered heading with attached help button (same title text)
2346 * and optional icon attached.
2348 * @param string $text A heading text
2349 * @param string $helpidentifier The keyword that defines a help page
2350 * @param string $component component name
2351 * @param string|moodle_url $icon
2352 * @param string $iconalt icon alt text
2353 * @param int $level The level of importance of the heading. Defaulting to 2
2354 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2355 * @return string HTML fragment
2357 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2358 $image = '';
2359 if ($icon) {
2360 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2363 $help = '';
2364 if ($helpidentifier) {
2365 $help = $this->help_icon($helpidentifier, $component);
2368 return $this->heading($image.$text.$help, $level, $classnames);
2372 * Returns HTML to display a help icon.
2374 * @deprecated since Moodle 2.0
2376 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2377 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2381 * Returns HTML to display a help icon.
2383 * Theme developers: DO NOT OVERRIDE! Please override function
2384 * {@link core_renderer::render_help_icon()} instead.
2386 * @param string $identifier The keyword that defines a help page
2387 * @param string $component component name
2388 * @param string|bool $linktext true means use $title as link text, string means link text value
2389 * @return string HTML fragment
2391 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2392 $icon = new help_icon($identifier, $component);
2393 $icon->diag_strings();
2394 if ($linktext === true) {
2395 $icon->linktext = get_string($icon->identifier, $icon->component);
2396 } else if (!empty($linktext)) {
2397 $icon->linktext = $linktext;
2399 return $this->render($icon);
2403 * Implementation of user image rendering.
2405 * @param help_icon $helpicon A help icon instance
2406 * @return string HTML fragment
2408 protected function render_help_icon(help_icon $helpicon) {
2409 $context = $helpicon->export_for_template($this);
2410 return $this->render_from_template('core/help_icon', $context);
2414 * Returns HTML to display a scale help icon.
2416 * @param int $courseid
2417 * @param stdClass $scale instance
2418 * @return string HTML fragment
2420 public function help_icon_scale($courseid, stdClass $scale) {
2421 global $CFG;
2423 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2425 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2427 $scaleid = abs($scale->id);
2429 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2430 $action = new popup_action('click', $link, 'ratingscale');
2432 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2436 * Creates and returns a spacer image with optional line break.
2438 * @param array $attributes Any HTML attributes to add to the spaced.
2439 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2440 * laxy do it with CSS which is a much better solution.
2441 * @return string HTML fragment
2443 public function spacer(array $attributes = null, $br = false) {
2444 $attributes = (array)$attributes;
2445 if (empty($attributes['width'])) {
2446 $attributes['width'] = 1;
2448 if (empty($attributes['height'])) {
2449 $attributes['height'] = 1;
2451 $attributes['class'] = 'spacer';
2453 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2455 if (!empty($br)) {
2456 $output .= '<br />';
2459 return $output;
2463 * Returns HTML to display the specified user's avatar.
2465 * User avatar may be obtained in two ways:
2466 * <pre>
2467 * // Option 1: (shortcut for simple cases, preferred way)
2468 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2469 * $OUTPUT->user_picture($user, array('popup'=>true));
2471 * // Option 2:
2472 * $userpic = new user_picture($user);
2473 * // Set properties of $userpic
2474 * $userpic->popup = true;
2475 * $OUTPUT->render($userpic);
2476 * </pre>
2478 * Theme developers: DO NOT OVERRIDE! Please override function
2479 * {@link core_renderer::render_user_picture()} instead.
2481 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2482 * If any of these are missing, the database is queried. Avoid this
2483 * if at all possible, particularly for reports. It is very bad for performance.
2484 * @param array $options associative array with user picture options, used only if not a user_picture object,
2485 * options are:
2486 * - courseid=$this->page->course->id (course id of user profile in link)
2487 * - size=35 (size of image)
2488 * - link=true (make image clickable - the link leads to user profile)
2489 * - popup=false (open in popup)
2490 * - alttext=true (add image alt attribute)
2491 * - class = image class attribute (default 'userpicture')
2492 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2493 * - includefullname=false (whether to include the user's full name together with the user picture)
2494 * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2495 * @return string HTML fragment
2497 public function user_picture(stdClass $user, array $options = null) {
2498 $userpicture = new user_picture($user);
2499 foreach ((array)$options as $key=>$value) {
2500 if (property_exists($userpicture, $key)) {
2501 $userpicture->$key = $value;
2504 return $this->render($userpicture);
2508 * Internal implementation of user image rendering.
2510 * @param user_picture $userpicture
2511 * @return string
2513 protected function render_user_picture(user_picture $userpicture) {
2514 global $CFG, $DB;
2516 $user = $userpicture->user;
2517 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
2519 if ($userpicture->alttext) {
2520 if (!empty($user->imagealt)) {
2521 $alt = $user->imagealt;
2522 } else {
2523 $alt = get_string('pictureof', '', fullname($user, $canviewfullnames));
2525 } else {
2526 $alt = '';
2529 if (empty($userpicture->size)) {
2530 $size = 35;
2531 } else if ($userpicture->size === true or $userpicture->size == 1) {
2532 $size = 100;
2533 } else {
2534 $size = $userpicture->size;
2537 $class = $userpicture->class;
2539 if ($user->picture == 0) {
2540 $class .= ' defaultuserpic';
2543 $src = $userpicture->get_url($this->page, $this);
2545 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2546 if (!$userpicture->visibletoscreenreaders) {
2547 $alt = '';
2548 $attributes['aria-hidden'] = 'true';
2551 if (!empty($alt)) {
2552 $attributes['alt'] = $alt;
2553 $attributes['title'] = $alt;
2556 // get the image html output fisrt
2557 $output = html_writer::empty_tag('img', $attributes);
2559 // Show fullname together with the picture when desired.
2560 if ($userpicture->includefullname) {
2561 $output .= fullname($userpicture->user, $canviewfullnames);
2564 // then wrap it in link if needed
2565 if (!$userpicture->link) {
2566 return $output;
2569 if (empty($userpicture->courseid)) {
2570 $courseid = $this->page->course->id;
2571 } else {
2572 $courseid = $userpicture->courseid;
2575 if ($courseid == SITEID) {
2576 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2577 } else {
2578 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2581 $attributes = array('href' => $url, 'class' => 'd-inline-block aabtn');
2582 if (!$userpicture->visibletoscreenreaders) {
2583 $attributes['tabindex'] = '-1';
2584 $attributes['aria-hidden'] = 'true';
2587 if ($userpicture->popup) {
2588 $id = html_writer::random_id('userpicture');
2589 $attributes['id'] = $id;
2590 $this->add_action_handler(new popup_action('click', $url), $id);
2593 return html_writer::tag('a', $output, $attributes);
2597 * Internal implementation of file tree viewer items rendering.
2599 * @param array $dir
2600 * @return string
2602 public function htmllize_file_tree($dir) {
2603 if (empty($dir['subdirs']) and empty($dir['files'])) {
2604 return '';
2606 $result = '<ul>';
2607 foreach ($dir['subdirs'] as $subdir) {
2608 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2610 foreach ($dir['files'] as $file) {
2611 $filename = $file->get_filename();
2612 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2614 $result .= '</ul>';
2616 return $result;
2620 * Returns HTML to display the file picker
2622 * <pre>
2623 * $OUTPUT->file_picker($options);
2624 * </pre>
2626 * Theme developers: DO NOT OVERRIDE! Please override function
2627 * {@link core_renderer::render_file_picker()} instead.
2629 * @param array $options associative array with file manager options
2630 * options are:
2631 * maxbytes=>-1,
2632 * itemid=>0,
2633 * client_id=>uniqid(),
2634 * acepted_types=>'*',
2635 * return_types=>FILE_INTERNAL,
2636 * context=>current page context
2637 * @return string HTML fragment
2639 public function file_picker($options) {
2640 $fp = new file_picker($options);
2641 return $this->render($fp);
2645 * Internal implementation of file picker rendering.
2647 * @param file_picker $fp
2648 * @return string
2650 public function render_file_picker(file_picker $fp) {
2651 $options = $fp->options;
2652 $client_id = $options->client_id;
2653 $strsaved = get_string('filesaved', 'repository');
2654 $straddfile = get_string('openpicker', 'repository');
2655 $strloading = get_string('loading', 'repository');
2656 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2657 $strdroptoupload = get_string('droptoupload', 'moodle');
2658 $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
2660 $currentfile = $options->currentfile;
2661 if (empty($currentfile)) {
2662 $currentfile = '';
2663 } else {
2664 $currentfile .= ' - ';
2666 if ($options->maxbytes) {
2667 $size = $options->maxbytes;
2668 } else {
2669 $size = get_max_upload_file_size();
2671 if ($size == -1) {
2672 $maxsize = '';
2673 } else {
2674 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2676 if ($options->buttonname) {
2677 $buttonname = ' name="' . $options->buttonname . '"';
2678 } else {
2679 $buttonname = '';
2681 $html = <<<EOD
2682 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2683 $iconprogress
2684 </div>
2685 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2686 <div>
2687 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2688 <span> $maxsize </span>
2689 </div>
2690 EOD;
2691 if ($options->env != 'url') {
2692 $html .= <<<EOD
2693 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist border" style="position: relative">
2694 <div class="filepicker-filename">
2695 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2696 <div class="dndupload-progressbars"></div>
2697 </div>
2698 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2699 </div>
2700 EOD;
2702 $html .= '</div>';
2703 return $html;
2707 * @deprecated since Moodle 3.2
2709 public function update_module_button() {
2710 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2711 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2712 'Themes can choose to display the link in the buttons row consistently for all module types.');
2716 * Returns HTML to display a "Turn editing on/off" button in a form.
2718 * @param moodle_url $url The URL + params to send through when clicking the button
2719 * @return string HTML the button
2721 public function edit_button(moodle_url $url) {
2723 $url->param('sesskey', sesskey());
2724 if ($this->page->user_is_editing()) {
2725 $url->param('edit', 'off');
2726 $editstring = get_string('turneditingoff');
2727 } else {
2728 $url->param('edit', 'on');
2729 $editstring = get_string('turneditingon');
2732 return $this->single_button($url, $editstring);
2736 * Returns HTML to display a simple button to close a window
2738 * @param string $text The lang string for the button's label (already output from get_string())
2739 * @return string html fragment
2741 public function close_window_button($text='') {
2742 if (empty($text)) {
2743 $text = get_string('closewindow');
2745 $button = new single_button(new moodle_url('#'), $text, 'get');
2746 $button->add_action(new component_action('click', 'close_window'));
2748 return $this->container($this->render($button), 'closewindow');
2752 * Output an error message. By default wraps the error message in <span class="error">.
2753 * If the error message is blank, nothing is output.
2755 * @param string $message the error message.
2756 * @return string the HTML to output.
2758 public function error_text($message) {
2759 if (empty($message)) {
2760 return '';
2762 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2763 return html_writer::tag('span', $message, array('class' => 'error'));
2767 * Do not call this function directly.
2769 * To terminate the current script with a fatal error, call the {@link print_error}
2770 * function, or throw an exception. Doing either of those things will then call this
2771 * function to display the error, before terminating the execution.
2773 * @param string $message The message to output
2774 * @param string $moreinfourl URL where more info can be found about the error
2775 * @param string $link Link for the Continue button
2776 * @param array $backtrace The execution backtrace
2777 * @param string $debuginfo Debugging information
2778 * @return string the HTML to output.
2780 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2781 global $CFG;
2783 $output = '';
2784 $obbuffer = '';
2786 if ($this->has_started()) {
2787 // we can not always recover properly here, we have problems with output buffering,
2788 // html tables, etc.
2789 $output .= $this->opencontainers->pop_all_but_last();
2791 } else {
2792 // It is really bad if library code throws exception when output buffering is on,
2793 // because the buffered text would be printed before our start of page.
2794 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2795 error_reporting(0); // disable notices from gzip compression, etc.
2796 while (ob_get_level() > 0) {
2797 $buff = ob_get_clean();
2798 if ($buff === false) {
2799 break;
2801 $obbuffer .= $buff;
2803 error_reporting($CFG->debug);
2805 // Output not yet started.
2806 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2807 if (empty($_SERVER['HTTP_RANGE'])) {
2808 @header($protocol . ' 404 Not Found');
2809 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2810 // Coax iOS 10 into sending the session cookie.
2811 @header($protocol . ' 403 Forbidden');
2812 } else {
2813 // Must stop byteserving attempts somehow,
2814 // this is weird but Chrome PDF viewer can be stopped only with 407!
2815 @header($protocol . ' 407 Proxy Authentication Required');
2818 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2819 $this->page->set_url('/'); // no url
2820 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2821 $this->page->set_title(get_string('error'));
2822 $this->page->set_heading($this->page->course->fullname);
2823 $output .= $this->header();
2826 $message = '<p class="errormessage">' . s($message) . '</p>'.
2827 '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
2828 get_string('moreinformation') . '</a></p>';
2829 if (empty($CFG->rolesactive)) {
2830 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2831 //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.
2833 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2835 if ($CFG->debugdeveloper) {
2836 $labelsep = get_string('labelsep', 'langconfig');
2837 if (!empty($debuginfo)) {
2838 $debuginfo = s($debuginfo); // removes all nasty JS
2839 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2840 $label = get_string('debuginfo', 'debug') . $labelsep;
2841 $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
2843 if (!empty($backtrace)) {
2844 $label = get_string('stacktrace', 'debug') . $labelsep;
2845 $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
2847 if ($obbuffer !== '' ) {
2848 $label = get_string('outputbuffer', 'debug') . $labelsep;
2849 $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
2853 if (empty($CFG->rolesactive)) {
2854 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2855 } else if (!empty($link)) {
2856 $output .= $this->continue_button($link);
2859 $output .= $this->footer();
2861 // Padding to encourage IE to display our error page, rather than its own.
2862 $output .= str_repeat(' ', 512);
2864 return $output;
2868 * Output a notification (that is, a status message about something that has just happened).
2870 * Note: \core\notification::add() may be more suitable for your usage.
2872 * @param string $message The message to print out.
2873 * @param string $type The type of notification. See constants on \core\output\notification.
2874 * @return string the HTML to output.
2876 public function notification($message, $type = null) {
2877 $typemappings = [
2878 // Valid types.
2879 'success' => \core\output\notification::NOTIFY_SUCCESS,
2880 'info' => \core\output\notification::NOTIFY_INFO,
2881 'warning' => \core\output\notification::NOTIFY_WARNING,
2882 'error' => \core\output\notification::NOTIFY_ERROR,
2884 // Legacy types mapped to current types.
2885 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2886 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2887 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2888 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2889 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2890 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2891 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2894 $extraclasses = [];
2896 if ($type) {
2897 if (strpos($type, ' ') === false) {
2898 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2899 if (isset($typemappings[$type])) {
2900 $type = $typemappings[$type];
2901 } else {
2902 // The value provided did not match a known type. It must be an extra class.
2903 $extraclasses = [$type];
2905 } else {
2906 // Identify what type of notification this is.
2907 $classarray = explode(' ', self::prepare_classes($type));
2909 // Separate out the type of notification from the extra classes.
2910 foreach ($classarray as $class) {
2911 if (isset($typemappings[$class])) {
2912 $type = $typemappings[$class];
2913 } else {
2914 $extraclasses[] = $class;
2920 $notification = new \core\output\notification($message, $type);
2921 if (count($extraclasses)) {
2922 $notification->set_extra_classes($extraclasses);
2925 // Return the rendered template.
2926 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2930 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2932 public function notify_problem() {
2933 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
2934 'please use \core\notification::add(), or \core\output\notification as required.');
2938 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2940 public function notify_success() {
2941 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
2942 'please use \core\notification::add(), or \core\output\notification as required.');
2946 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2948 public function notify_message() {
2949 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
2950 'please use \core\notification::add(), or \core\output\notification as required.');
2954 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2956 public function notify_redirect() {
2957 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
2958 'please use \core\notification::add(), or \core\output\notification as required.');
2962 * Render a notification (that is, a status message about something that has
2963 * just happened).
2965 * @param \core\output\notification $notification the notification to print out
2966 * @return string the HTML to output.
2968 protected function render_notification(\core\output\notification $notification) {
2969 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2973 * Returns HTML to display a continue button that goes to a particular URL.
2975 * @param string|moodle_url $url The url the button goes to.
2976 * @return string the HTML to output.
2978 public function continue_button($url) {
2979 if (!($url instanceof moodle_url)) {
2980 $url = new moodle_url($url);
2982 $button = new single_button($url, get_string('continue'), 'get', true);
2983 $button->class = 'continuebutton';
2985 return $this->render($button);
2989 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2991 * Theme developers: DO NOT OVERRIDE! Please override function
2992 * {@link core_renderer::render_paging_bar()} instead.
2994 * @param int $totalcount The total number of entries available to be paged through
2995 * @param int $page The page you are currently viewing
2996 * @param int $perpage The number of entries that should be shown per page
2997 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2998 * @param string $pagevar name of page parameter that holds the page number
2999 * @return string the HTML to output.
3001 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3002 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3003 return $this->render($pb);
3007 * Returns HTML to display the paging bar.
3009 * @param paging_bar $pagingbar
3010 * @return string the HTML to output.
3012 protected function render_paging_bar(paging_bar $pagingbar) {
3013 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3014 $pagingbar->maxdisplay = 10;
3015 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3019 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3021 * @param string $current the currently selected letter.
3022 * @param string $class class name to add to this initial bar.
3023 * @param string $title the name to put in front of this initial bar.
3024 * @param string $urlvar URL parameter name for this initial.
3025 * @param string $url URL object.
3026 * @param array $alpha of letters in the alphabet.
3027 * @return string the HTML to output.
3029 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3030 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3031 return $this->render($ib);
3035 * Internal implementation of initials bar rendering.
3037 * @param initials_bar $initialsbar
3038 * @return string
3040 protected function render_initials_bar(initials_bar $initialsbar) {
3041 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3045 * Output the place a skip link goes to.
3047 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3048 * @return string the HTML to output.
3050 public function skip_link_target($id = null) {
3051 return html_writer::span('', '', array('id' => $id));
3055 * Outputs a heading
3057 * @param string $text The text of the heading
3058 * @param int $level The level of importance of the heading. Defaulting to 2
3059 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3060 * @param string $id An optional ID
3061 * @return string the HTML to output.
3063 public function heading($text, $level = 2, $classes = null, $id = null) {
3064 $level = (integer) $level;
3065 if ($level < 1 or $level > 6) {
3066 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3068 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3072 * Outputs a box.
3074 * @param string $contents The contents of the box
3075 * @param string $classes A space-separated list of CSS classes
3076 * @param string $id An optional ID
3077 * @param array $attributes An array of other attributes to give the box.
3078 * @return string the HTML to output.
3080 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3081 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3085 * Outputs the opening section of a box.
3087 * @param string $classes A space-separated list of CSS classes
3088 * @param string $id An optional ID
3089 * @param array $attributes An array of other attributes to give the box.
3090 * @return string the HTML to output.
3092 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3093 $this->opencontainers->push('box', html_writer::end_tag('div'));
3094 $attributes['id'] = $id;
3095 $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes);
3096 return html_writer::start_tag('div', $attributes);
3100 * Outputs the closing section of a box.
3102 * @return string the HTML to output.
3104 public function box_end() {
3105 return $this->opencontainers->pop('box');
3109 * Outputs a container.
3111 * @param string $contents The contents of the box
3112 * @param string $classes A space-separated list of CSS classes
3113 * @param string $id An optional ID
3114 * @return string the HTML to output.
3116 public function container($contents, $classes = null, $id = null) {
3117 return $this->container_start($classes, $id) . $contents . $this->container_end();
3121 * Outputs the opening section of a container.
3123 * @param string $classes A space-separated list of CSS classes
3124 * @param string $id An optional ID
3125 * @return string the HTML to output.
3127 public function container_start($classes = null, $id = null) {
3128 $this->opencontainers->push('container', html_writer::end_tag('div'));
3129 return html_writer::start_tag('div', array('id' => $id,
3130 'class' => renderer_base::prepare_classes($classes)));
3134 * Outputs the closing section of a container.
3136 * @return string the HTML to output.
3138 public function container_end() {
3139 return $this->opencontainers->pop('container');
3143 * Make nested HTML lists out of the items
3145 * The resulting list will look something like this:
3147 * <pre>
3148 * <<ul>>
3149 * <<li>><div class='tree_item parent'>(item contents)</div>
3150 * <<ul>
3151 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3152 * <</ul>>
3153 * <</li>>
3154 * <</ul>>
3155 * </pre>
3157 * @param array $items
3158 * @param array $attrs html attributes passed to the top ofs the list
3159 * @return string HTML
3161 public function tree_block_contents($items, $attrs = array()) {
3162 // exit if empty, we don't want an empty ul element
3163 if (empty($items)) {
3164 return '';
3166 // array of nested li elements
3167 $lis = array();
3168 foreach ($items as $item) {
3169 // this applies to the li item which contains all child lists too
3170 $content = $item->content($this);
3171 $liclasses = array($item->get_css_type());
3172 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3173 $liclasses[] = 'collapsed';
3175 if ($item->isactive === true) {
3176 $liclasses[] = 'current_branch';
3178 $liattr = array('class'=>join(' ',$liclasses));
3179 // class attribute on the div item which only contains the item content
3180 $divclasses = array('tree_item');
3181 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3182 $divclasses[] = 'branch';
3183 } else {
3184 $divclasses[] = 'leaf';
3186 if (!empty($item->classes) && count($item->classes)>0) {
3187 $divclasses[] = join(' ', $item->classes);
3189 $divattr = array('class'=>join(' ', $divclasses));
3190 if (!empty($item->id)) {
3191 $divattr['id'] = $item->id;
3193 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3194 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3195 $content = html_writer::empty_tag('hr') . $content;
3197 $content = html_writer::tag('li', $content, $liattr);
3198 $lis[] = $content;
3200 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3204 * Returns a search box.
3206 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3207 * @return string HTML with the search form hidden by default.
3209 public function search_box($id = false) {
3210 global $CFG;
3212 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3213 // result in an extra included file for each site, even the ones where global search
3214 // is disabled.
3215 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3216 return '';
3219 if ($id == false) {
3220 $id = uniqid();
3221 } else {
3222 // Needs to be cleaned, we use it for the input id.
3223 $id = clean_param($id, PARAM_ALPHANUMEXT);
3226 // JS to animate the form.
3227 $this->page->requires->js_call_amd('core/search-input', 'init', array($id));
3229 $searchicon = html_writer::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
3230 array('role' => 'button', 'tabindex' => 0));
3231 $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot . '/search/index.php');
3232 $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
3233 'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id, 'class' => 'form-control');
3235 $contents = html_writer::tag('label', get_string('enteryoursearchquery', 'search'),
3236 array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer::empty_tag('input', $inputattrs);
3237 if ($this->page->context && $this->page->context->contextlevel !== CONTEXT_SYSTEM) {
3238 $contents .= html_writer::empty_tag('input', ['type' => 'hidden',
3239 'name' => 'context', 'value' => $this->page->context->id]);
3241 $searchinput = html_writer::tag('form', $contents, $formattrs);
3243 return html_writer::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper nav-link', 'id' => $id));
3247 * Allow plugins to provide some content to be rendered in the navbar.
3248 * The plugin must define a PLUGIN_render_navbar_output function that returns
3249 * the HTML they wish to add to the navbar.
3251 * @return string HTML for the navbar
3253 public function navbar_plugin_output() {
3254 $output = '';
3256 // Give subsystems an opportunity to inject extra html content. The callback
3257 // must always return a string containing valid html.
3258 foreach (\core_component::get_core_subsystems() as $name => $path) {
3259 if ($path) {
3260 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3264 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3265 foreach ($pluginsfunction as $plugintype => $plugins) {
3266 foreach ($plugins as $pluginfunction) {
3267 $output .= $pluginfunction($this);
3272 return $output;
3276 * Construct a user menu, returning HTML that can be echoed out by a
3277 * layout file.
3279 * @param stdClass $user A user object, usually $USER.
3280 * @param bool $withlinks true if a dropdown should be built.
3281 * @return string HTML fragment.
3283 public function user_menu($user = null, $withlinks = null) {
3284 global $USER, $CFG;
3285 require_once($CFG->dirroot . '/user/lib.php');
3287 if (is_null($user)) {
3288 $user = $USER;
3291 // Note: this behaviour is intended to match that of core_renderer::login_info,
3292 // but should not be considered to be good practice; layout options are
3293 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3294 if (is_null($withlinks)) {
3295 $withlinks = empty($this->page->layout_options['nologinlinks']);
3298 // Add a class for when $withlinks is false.
3299 $usermenuclasses = 'usermenu';
3300 if (!$withlinks) {
3301 $usermenuclasses .= ' withoutlinks';
3304 $returnstr = "";
3306 // If during initial install, return the empty return string.
3307 if (during_initial_install()) {
3308 return $returnstr;
3311 $loginpage = $this->is_login_page();
3312 $loginurl = get_login_url();
3313 // If not logged in, show the typical not-logged-in string.
3314 if (!isloggedin()) {
3315 $returnstr = get_string('loggedinnot', 'moodle');
3316 if (!$loginpage) {
3317 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3319 return html_writer::div(
3320 html_writer::span(
3321 $returnstr,
3322 'login'
3324 $usermenuclasses
3329 // If logged in as a guest user, show a string to that effect.
3330 if (isguestuser()) {
3331 $returnstr = get_string('loggedinasguest');
3332 if (!$loginpage && $withlinks) {
3333 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3336 return html_writer::div(
3337 html_writer::span(
3338 $returnstr,
3339 'login'
3341 $usermenuclasses
3345 // Get some navigation opts.
3346 $opts = user_get_user_navigation_info($user, $this->page);
3348 $avatarclasses = "avatars";
3349 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3350 $usertextcontents = $opts->metadata['userfullname'];
3352 // Other user.
3353 if (!empty($opts->metadata['asotheruser'])) {
3354 $avatarcontents .= html_writer::span(
3355 $opts->metadata['realuseravatar'],
3356 'avatar realuser'
3358 $usertextcontents = $opts->metadata['realuserfullname'];
3359 $usertextcontents .= html_writer::tag(
3360 'span',
3361 get_string(
3362 'loggedinas',
3363 'moodle',
3364 html_writer::span(
3365 $opts->metadata['userfullname'],
3366 'value'
3369 array('class' => 'meta viewingas')
3373 // Role.
3374 if (!empty($opts->metadata['asotherrole'])) {
3375 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3376 $usertextcontents .= html_writer::span(
3377 $opts->metadata['rolename'],
3378 'meta role role-' . $role
3382 // User login failures.
3383 if (!empty($opts->metadata['userloginfail'])) {
3384 $usertextcontents .= html_writer::span(
3385 $opts->metadata['userloginfail'],
3386 'meta loginfailures'
3390 // MNet.
3391 if (!empty($opts->metadata['asmnetuser'])) {
3392 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3393 $usertextcontents .= html_writer::span(
3394 $opts->metadata['mnetidprovidername'],
3395 'meta mnet mnet-' . $mnet
3399 $returnstr .= html_writer::span(
3400 html_writer::span($usertextcontents, 'usertext mr-1') .
3401 html_writer::span($avatarcontents, $avatarclasses),
3402 'userbutton'
3405 // Create a divider (well, a filler).
3406 $divider = new action_menu_filler();
3407 $divider->primary = false;
3409 $am = new action_menu();
3410 $am->set_menu_trigger(
3411 $returnstr
3413 $am->set_action_label(get_string('usermenu'));
3414 $am->set_alignment(action_menu::TR, action_menu::BR);
3415 $am->set_nowrap_on_items();
3416 if ($withlinks) {
3417 $navitemcount = count($opts->navitems);
3418 $idx = 0;
3419 foreach ($opts->navitems as $key => $value) {
3421 switch ($value->itemtype) {
3422 case 'divider':
3423 // If the nav item is a divider, add one and skip link processing.
3424 $am->add($divider);
3425 break;
3427 case 'invalid':
3428 // Silently skip invalid entries (should we post a notification?).
3429 break;
3431 case 'link':
3432 // Process this as a link item.
3433 $pix = null;
3434 if (isset($value->pix) && !empty($value->pix)) {
3435 $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
3436 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3437 $value->title = html_writer::img(
3438 $value->imgsrc,
3439 $value->title,
3440 array('class' => 'iconsmall')
3441 ) . $value->title;
3444 $al = new action_menu_link_secondary(
3445 $value->url,
3446 $pix,
3447 $value->title,
3448 array('class' => 'icon')
3450 if (!empty($value->titleidentifier)) {
3451 $al->attributes['data-title'] = $value->titleidentifier;
3453 $am->add($al);
3454 break;
3457 $idx++;
3459 // Add dividers after the first item and before the last item.
3460 if ($idx == 1 || $idx == $navitemcount - 1) {
3461 $am->add($divider);
3466 return html_writer::div(
3467 $this->render($am),
3468 $usermenuclasses
3473 * Secure layout login info.
3475 * @return string
3477 public function secure_layout_login_info() {
3478 if (get_config('core', 'logininfoinsecurelayout')) {
3479 return $this->login_info(false);
3480 } else {
3481 return '';
3486 * Returns the language menu in the secure layout.
3488 * No custom menu items are passed though, such that it will render only the language selection.
3490 * @return string
3492 public function secure_layout_language_menu() {
3493 if (get_config('core', 'langmenuinsecurelayout')) {
3494 $custommenu = new custom_menu('', current_language());
3495 return $this->render_custom_menu($custommenu);
3496 } else {
3497 return '';
3502 * This renders the navbar.
3503 * Uses bootstrap compatible html.
3505 public function navbar() {
3506 return $this->render_from_template('core/navbar', $this->page->navbar);
3510 * Renders a breadcrumb navigation node object.
3512 * @param breadcrumb_navigation_node $item The navigation node to render.
3513 * @return string HTML fragment
3515 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3517 if ($item->action instanceof moodle_url) {
3518 $content = $item->get_content();
3519 $title = $item->get_title();
3520 $attributes = array();
3521 $attributes['itemprop'] = 'url';
3522 if ($title !== '') {
3523 $attributes['title'] = $title;
3525 if ($item->hidden) {
3526 $attributes['class'] = 'dimmed_text';
3528 if ($item->is_last()) {
3529 $attributes['aria-current'] = 'page';
3531 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3532 $content = html_writer::link($item->action, $content, $attributes);
3534 $attributes = array();
3535 $attributes['itemscope'] = '';
3536 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3537 $content = html_writer::tag('span', $content, $attributes);
3539 } else {
3540 $content = $this->render_navigation_node($item);
3542 return $content;
3546 * Renders a navigation node object.
3548 * @param navigation_node $item The navigation node to render.
3549 * @return string HTML fragment
3551 protected function render_navigation_node(navigation_node $item) {
3552 $content = $item->get_content();
3553 $title = $item->get_title();
3554 if ($item->icon instanceof renderable && !$item->hideicon) {
3555 $icon = $this->render($item->icon);
3556 $content = $icon.$content; // use CSS for spacing of icons
3558 if ($item->helpbutton !== null) {
3559 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3561 if ($content === '') {
3562 return '';
3564 if ($item->action instanceof action_link) {
3565 $link = $item->action;
3566 if ($item->hidden) {
3567 $link->add_class('dimmed');
3569 if (!empty($content)) {
3570 // Providing there is content we will use that for the link content.
3571 $link->text = $content;
3573 $content = $this->render($link);
3574 } else if ($item->action instanceof moodle_url) {
3575 $attributes = array();
3576 if ($title !== '') {
3577 $attributes['title'] = $title;
3579 if ($item->hidden) {
3580 $attributes['class'] = 'dimmed_text';
3582 $content = html_writer::link($item->action, $content, $attributes);
3584 } else if (is_string($item->action) || empty($item->action)) {
3585 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3586 if ($title !== '') {
3587 $attributes['title'] = $title;
3589 if ($item->hidden) {
3590 $attributes['class'] = 'dimmed_text';
3592 $content = html_writer::tag('span', $content, $attributes);
3594 return $content;
3598 * Accessibility: Right arrow-like character is
3599 * used in the breadcrumb trail, course navigation menu
3600 * (previous/next activity), calendar, and search forum block.
3601 * If the theme does not set characters, appropriate defaults
3602 * are set automatically. Please DO NOT
3603 * use &lt; &gt; &raquo; - these are confusing for blind users.
3605 * @return string
3607 public function rarrow() {
3608 return $this->page->theme->rarrow;
3612 * Accessibility: Left arrow-like character is
3613 * used in the breadcrumb trail, course navigation menu
3614 * (previous/next activity), calendar, and search forum block.
3615 * If the theme does not set characters, appropriate defaults
3616 * are set automatically. Please DO NOT
3617 * use &lt; &gt; &raquo; - these are confusing for blind users.
3619 * @return string
3621 public function larrow() {
3622 return $this->page->theme->larrow;
3626 * Accessibility: Up arrow-like character is used in
3627 * the book heirarchical navigation.
3628 * If the theme does not set characters, appropriate defaults
3629 * are set automatically. Please DO NOT
3630 * use ^ - this is confusing for blind users.
3632 * @return string
3634 public function uarrow() {
3635 return $this->page->theme->uarrow;
3639 * Accessibility: Down arrow-like character.
3640 * If the theme does not set characters, appropriate defaults
3641 * are set automatically.
3643 * @return string
3645 public function darrow() {
3646 return $this->page->theme->darrow;
3650 * Returns the custom menu if one has been set
3652 * A custom menu can be configured by browsing to
3653 * Settings: Administration > Appearance > Themes > Theme settings
3654 * and then configuring the custommenu config setting as described.
3656 * Theme developers: DO NOT OVERRIDE! Please override function
3657 * {@link core_renderer::render_custom_menu()} instead.
3659 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3660 * @return string
3662 public function custom_menu($custommenuitems = '') {
3663 global $CFG;
3665 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3666 $custommenuitems = $CFG->custommenuitems;
3668 $custommenu = new custom_menu($custommenuitems, current_language());
3669 return $this->render_custom_menu($custommenu);
3673 * We want to show the custom menus as a list of links in the footer on small screens.
3674 * Just return the menu object exported so we can render it differently.
3676 public function custom_menu_flat() {
3677 global $CFG;
3678 $custommenuitems = '';
3680 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3681 $custommenuitems = $CFG->custommenuitems;
3683 $custommenu = new custom_menu($custommenuitems, current_language());
3684 $langs = get_string_manager()->get_list_of_translations();
3685 $haslangmenu = $this->lang_menu() != '';
3687 if ($haslangmenu) {
3688 $strlang = get_string('language');
3689 $currentlang = current_language();
3690 if (isset($langs[$currentlang])) {
3691 $currentlang = $langs[$currentlang];
3692 } else {
3693 $currentlang = $strlang;
3695 $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3696 foreach ($langs as $langtype => $langname) {
3697 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3701 return $custommenu->export_for_template($this);
3705 * Renders a custom menu object (located in outputcomponents.php)
3707 * The custom menu this method produces makes use of the YUI3 menunav widget
3708 * and requires very specific html elements and classes.
3710 * @staticvar int $menucount
3711 * @param custom_menu $menu
3712 * @return string
3714 protected function render_custom_menu(custom_menu $menu) {
3715 global $CFG;
3717 $langs = get_string_manager()->get_list_of_translations();
3718 $haslangmenu = $this->lang_menu() != '';
3720 if (!$menu->has_children() && !$haslangmenu) {
3721 return '';
3724 if ($haslangmenu) {
3725 $strlang = get_string('language');
3726 $currentlang = current_language();
3727 if (isset($langs[$currentlang])) {
3728 $currentlang = $langs[$currentlang];
3729 } else {
3730 $currentlang = $strlang;
3732 $this->language = $menu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3733 foreach ($langs as $langtype => $langname) {
3734 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3738 $content = '';
3739 foreach ($menu->get_children() as $item) {
3740 $context = $item->export_for_template($this);
3741 $content .= $this->render_from_template('core/custom_menu_item', $context);
3744 return $content;
3748 * Renders a custom menu node as part of a submenu
3750 * The custom menu this method produces makes use of the YUI3 menunav widget
3751 * and requires very specific html elements and classes.
3753 * @see core:renderer::render_custom_menu()
3755 * @staticvar int $submenucount
3756 * @param custom_menu_item $menunode
3757 * @return string
3759 protected function render_custom_menu_item(custom_menu_item $menunode) {
3760 // Required to ensure we get unique trackable id's
3761 static $submenucount = 0;
3762 if ($menunode->has_children()) {
3763 // If the child has menus render it as a sub menu
3764 $submenucount++;
3765 $content = html_writer::start_tag('li');
3766 if ($menunode->get_url() !== null) {
3767 $url = $menunode->get_url();
3768 } else {
3769 $url = '#cm_submenu_'.$submenucount;
3771 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3772 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3773 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3774 $content .= html_writer::start_tag('ul');
3775 foreach ($menunode->get_children() as $menunode) {
3776 $content .= $this->render_custom_menu_item($menunode);
3778 $content .= html_writer::end_tag('ul');
3779 $content .= html_writer::end_tag('div');
3780 $content .= html_writer::end_tag('div');
3781 $content .= html_writer::end_tag('li');
3782 } else {
3783 // The node doesn't have children so produce a final menuitem.
3784 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3785 $content = '';
3786 if (preg_match("/^#+$/", $menunode->get_text())) {
3788 // This is a divider.
3789 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3790 } else {
3791 $content = html_writer::start_tag(
3792 'li',
3793 array(
3794 'class' => 'yui3-menuitem'
3797 if ($menunode->get_url() !== null) {
3798 $url = $menunode->get_url();
3799 } else {
3800 $url = '#';
3802 $content .= html_writer::link(
3803 $url,
3804 $menunode->get_text(),
3805 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3808 $content .= html_writer::end_tag('li');
3810 // Return the sub menu
3811 return $content;
3815 * Renders theme links for switching between default and other themes.
3817 * @return string
3819 protected function theme_switch_links() {
3821 $actualdevice = core_useragent::get_device_type();
3822 $currentdevice = $this->page->devicetypeinuse;
3823 $switched = ($actualdevice != $currentdevice);
3825 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3826 // The user is using the a default device and hasn't switched so don't shown the switch
3827 // device links.
3828 return '';
3831 if ($switched) {
3832 $linktext = get_string('switchdevicerecommended');
3833 $devicetype = $actualdevice;
3834 } else {
3835 $linktext = get_string('switchdevicedefault');
3836 $devicetype = 'default';
3838 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3840 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3841 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3842 $content .= html_writer::end_tag('div');
3844 return $content;
3848 * Renders tabs
3850 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3852 * Theme developers: In order to change how tabs are displayed please override functions
3853 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3855 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3856 * @param string|null $selected which tab to mark as selected, all parent tabs will
3857 * automatically be marked as activated
3858 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3859 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3860 * @return string
3862 public final function tabtree($tabs, $selected = null, $inactive = null) {
3863 return $this->render(new tabtree($tabs, $selected, $inactive));
3867 * Renders tabtree
3869 * @param tabtree $tabtree
3870 * @return string
3872 protected function render_tabtree(tabtree $tabtree) {
3873 if (empty($tabtree->subtree)) {
3874 return '';
3876 $data = $tabtree->export_for_template($this);
3877 return $this->render_from_template('core/tabtree', $data);
3881 * Renders tabobject (part of tabtree)
3883 * This function is called from {@link core_renderer::render_tabtree()}
3884 * and also it calls itself when printing the $tabobject subtree recursively.
3886 * Property $tabobject->level indicates the number of row of tabs.
3888 * @param tabobject $tabobject
3889 * @return string HTML fragment
3891 protected function render_tabobject(tabobject $tabobject) {
3892 $str = '';
3894 // Print name of the current tab.
3895 if ($tabobject instanceof tabtree) {
3896 // No name for tabtree root.
3897 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3898 // Tab name without a link. The <a> tag is used for styling.
3899 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3900 } else {
3901 // Tab name with a link.
3902 if (!($tabobject->link instanceof moodle_url)) {
3903 // backward compartibility when link was passed as quoted string
3904 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3905 } else {
3906 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3910 if (empty($tabobject->subtree)) {
3911 if ($tabobject->selected) {
3912 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3914 return $str;
3917 // Print subtree.
3918 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
3919 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3920 $cnt = 0;
3921 foreach ($tabobject->subtree as $tab) {
3922 $liclass = '';
3923 if (!$cnt) {
3924 $liclass .= ' first';
3926 if ($cnt == count($tabobject->subtree) - 1) {
3927 $liclass .= ' last';
3929 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3930 $liclass .= ' onerow';
3933 if ($tab->selected) {
3934 $liclass .= ' here selected';
3935 } else if ($tab->activated) {
3936 $liclass .= ' here active';
3939 // This will recursively call function render_tabobject() for each item in subtree.
3940 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3941 $cnt++;
3943 $str .= html_writer::end_tag('ul');
3946 return $str;
3950 * Get the HTML for blocks in the given region.
3952 * @since Moodle 2.5.1 2.6
3953 * @param string $region The region to get HTML for.
3954 * @return string HTML.
3956 public function blocks($region, $classes = array(), $tag = 'aside') {
3957 $displayregion = $this->page->apply_theme_region_manipulations($region);
3958 $classes = (array)$classes;
3959 $classes[] = 'block-region';
3960 $attributes = array(
3961 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3962 'class' => join(' ', $classes),
3963 'data-blockregion' => $displayregion,
3964 'data-droptarget' => '1'
3966 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3967 $content = $this->blocks_for_region($displayregion);
3968 } else {
3969 $content = '';
3971 return html_writer::tag($tag, $content, $attributes);
3975 * Renders a custom block region.
3977 * Use this method if you want to add an additional block region to the content of the page.
3978 * Please note this should only be used in special situations.
3979 * We want to leave the theme is control where ever possible!
3981 * This method must use the same method that the theme uses within its layout file.
3982 * As such it asks the theme what method it is using.
3983 * It can be one of two values, blocks or blocks_for_region (deprecated).
3985 * @param string $regionname The name of the custom region to add.
3986 * @return string HTML for the block region.
3988 public function custom_block_region($regionname) {
3989 if ($this->page->theme->get_block_render_method() === 'blocks') {
3990 return $this->blocks($regionname);
3991 } else {
3992 return $this->blocks_for_region($regionname);
3997 * Returns the CSS classes to apply to the body tag.
3999 * @since Moodle 2.5.1 2.6
4000 * @param array $additionalclasses Any additional classes to apply.
4001 * @return string
4003 public function body_css_classes(array $additionalclasses = array()) {
4004 return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses);
4008 * The ID attribute to apply to the body tag.
4010 * @since Moodle 2.5.1 2.6
4011 * @return string
4013 public function body_id() {
4014 return $this->page->bodyid;
4018 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4020 * @since Moodle 2.5.1 2.6
4021 * @param string|array $additionalclasses Any additional classes to give the body tag,
4022 * @return string
4024 public function body_attributes($additionalclasses = array()) {
4025 if (!is_array($additionalclasses)) {
4026 $additionalclasses = explode(' ', $additionalclasses);
4028 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4032 * Gets HTML for the page heading.
4034 * @since Moodle 2.5.1 2.6
4035 * @param string $tag The tag to encase the heading in. h1 by default.
4036 * @return string HTML.
4038 public function page_heading($tag = 'h1') {
4039 return html_writer::tag($tag, $this->page->heading);
4043 * Gets the HTML for the page heading button.
4045 * @since Moodle 2.5.1 2.6
4046 * @return string HTML.
4048 public function page_heading_button() {
4049 return $this->page->button;
4053 * Returns the Moodle docs link to use for this page.
4055 * @since Moodle 2.5.1 2.6
4056 * @param string $text
4057 * @return string
4059 public function page_doc_link($text = null) {
4060 if ($text === null) {
4061 $text = get_string('moodledocslink');
4063 $path = page_get_doc_link_path($this->page);
4064 if (!$path) {
4065 return '';
4067 return $this->doc_link($path, $text);
4071 * Returns the page heading menu.
4073 * @since Moodle 2.5.1 2.6
4074 * @return string HTML.
4076 public function page_heading_menu() {
4077 return $this->page->headingmenu;
4081 * Returns the title to use on the page.
4083 * @since Moodle 2.5.1 2.6
4084 * @return string
4086 public function page_title() {
4087 return $this->page->title;
4091 * Returns the moodle_url for the favicon.
4093 * @since Moodle 2.5.1 2.6
4094 * @return moodle_url The moodle_url for the favicon
4096 public function favicon() {
4097 return $this->image_url('favicon', 'theme');
4101 * Renders preferences groups.
4103 * @param preferences_groups $renderable The renderable
4104 * @return string The output.
4106 public function render_preferences_groups(preferences_groups $renderable) {
4107 return $this->render_from_template('core/preferences_groups', $renderable);
4111 * Renders preferences group.
4113 * @param preferences_group $renderable The renderable
4114 * @return string The output.
4116 public function render_preferences_group(preferences_group $renderable) {
4117 $html = '';
4118 $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4119 $html .= $this->heading($renderable->title, 3);
4120 $html .= html_writer::start_tag('ul');
4121 foreach ($renderable->nodes as $node) {
4122 if ($node->has_children()) {
4123 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4125 $html .= html_writer::tag('li', $this->render($node));
4127 $html .= html_writer::end_tag('ul');
4128 $html .= html_writer::end_tag('div');
4129 return $html;
4132 public function context_header($headerinfo = null, $headinglevel = 1) {
4133 global $DB, $USER, $CFG, $SITE;
4134 require_once($CFG->dirroot . '/user/lib.php');
4135 $context = $this->page->context;
4136 $heading = null;
4137 $imagedata = null;
4138 $subheader = null;
4139 $userbuttons = null;
4141 if ($this->should_display_main_logo($headinglevel)) {
4142 $sitename = format_string($SITE->fullname, true, array('context' => context_course::instance(SITEID)));
4143 return html_writer::div(html_writer::empty_tag('img', [
4144 'src' => $this->get_logo_url(null, 150), 'alt' => $sitename, 'class' => 'img-fluid']), 'logo');
4147 // Make sure to use the heading if it has been set.
4148 if (isset($headerinfo['heading'])) {
4149 $heading = $headerinfo['heading'];
4152 // The user context currently has images and buttons. Other contexts may follow.
4153 if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
4154 if (isset($headerinfo['user'])) {
4155 $user = $headerinfo['user'];
4156 } else {
4157 // Look up the user information if it is not supplied.
4158 $user = $DB->get_record('user', array('id' => $context->instanceid));
4161 // If the user context is set, then use that for capability checks.
4162 if (isset($headerinfo['usercontext'])) {
4163 $context = $headerinfo['usercontext'];
4166 // Only provide user information if the user is the current user, or a user which the current user can view.
4167 // When checking user_can_view_profile(), either:
4168 // If the page context is course, check the course context (from the page object) or;
4169 // If page context is NOT course, then check across all courses.
4170 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4172 if (user_can_view_profile($user, $course)) {
4173 // Use the user's full name if the heading isn't set.
4174 if (!isset($heading)) {
4175 $heading = fullname($user);
4178 $imagedata = $this->user_picture($user, array('size' => 100));
4180 // Check to see if we should be displaying a message button.
4181 if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
4182 $userbuttons = array(
4183 'messages' => array(
4184 'buttontype' => 'message',
4185 'title' => get_string('message', 'message'),
4186 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4187 'image' => 'message',
4188 'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
4189 'page' => $this->page
4193 if ($USER->id != $user->id) {
4194 $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4195 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4196 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4197 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4198 $userbuttons['togglecontact'] = array(
4199 'buttontype' => 'togglecontact',
4200 'title' => get_string($contacttitle, 'message'),
4201 'url' => new moodle_url('/message/index.php', array(
4202 'user1' => $USER->id,
4203 'user2' => $user->id,
4204 $contacturlaction => $user->id,
4205 'sesskey' => sesskey())
4207 'image' => $contactimage,
4208 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4209 'page' => $this->page
4213 $this->page->requires->string_for_js('changesmadereallygoaway', 'moodle');
4215 } else {
4216 $heading = null;
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 $showheader = empty($this->page->layout_options['nocontextheader']);
4249 if (!$showheader) {
4250 return '';
4253 // All the html stuff goes here.
4254 $html = html_writer::start_div('page-context-header');
4256 // Image data.
4257 if (isset($contextheader->imagedata)) {
4258 // Header specific image.
4259 $html .= html_writer::div($contextheader->imagedata, 'page-header-image');
4262 // Headings.
4263 if (!isset($contextheader->heading)) {
4264 $headings = $this->heading($this->page->heading, $contextheader->headinglevel);
4265 } else {
4266 $headings = $this->heading($contextheader->heading, $contextheader->headinglevel);
4269 $html .= html_writer::tag('div', $headings, array('class' => 'page-header-headings'));
4271 // Buttons.
4272 if (isset($contextheader->additionalbuttons)) {
4273 $html .= html_writer::start_div('btn-group header-button-group');
4274 foreach ($contextheader->additionalbuttons as $button) {
4275 if (!isset($button->page)) {
4276 // Include js for messaging.
4277 if ($button['buttontype'] === 'togglecontact') {
4278 \core_message\helper::togglecontact_requirejs();
4280 if ($button['buttontype'] === 'message') {
4281 \core_message\helper::messageuser_requirejs();
4283 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4284 'class' => 'iconsmall',
4285 'role' => 'presentation'
4287 $image .= html_writer::span($button['title'], 'header-button-title');
4288 } else {
4289 $image = html_writer::empty_tag('img', array(
4290 'src' => $button['formattedimage'],
4291 'role' => 'presentation'
4294 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4296 $html .= html_writer::end_div();
4298 $html .= html_writer::end_div();
4300 return $html;
4304 * Wrapper for header elements.
4306 * @return string HTML to display the main header.
4308 public function full_header() {
4310 if ($this->page->include_region_main_settings_in_header_actions() &&
4311 !$this->page->blocks->is_block_present('settings')) {
4312 // Only include the region main settings if the page has requested it and it doesn't already have
4313 // the settings block on it. The region main settings are included in the settings block and
4314 // duplicating the content causes behat failures.
4315 $this->page->add_header_action(html_writer::div(
4316 $this->region_main_settings_menu(),
4317 'd-print-none',
4318 ['id' => 'region-main-settings-menu']
4322 $header = new stdClass();
4323 $header->settingsmenu = $this->context_header_settings_menu();
4324 $header->contextheader = $this->context_header();
4325 $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
4326 $header->navbar = $this->navbar();
4327 $header->pageheadingbutton = $this->page_heading_button();
4328 $header->courseheader = $this->course_header();
4329 $header->headeractions = $this->page->get_header_actions();
4330 return $this->render_from_template('core/full_header', $header);
4334 * This is an optional menu that can be added to a layout by a theme. It contains the
4335 * menu for the course administration, only on the course main page.
4337 * @return string
4339 public function context_header_settings_menu() {
4340 $context = $this->page->context;
4341 $menu = new action_menu();
4343 $items = $this->page->navbar->get_items();
4344 $currentnode = end($items);
4346 $showcoursemenu = false;
4347 $showfrontpagemenu = false;
4348 $showusermenu = false;
4350 // We are on the course home page.
4351 if (($context->contextlevel == CONTEXT_COURSE) &&
4352 !empty($currentnode) &&
4353 ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
4354 $showcoursemenu = true;
4357 $courseformat = course_get_format($this->page->course);
4358 // This is a single activity course format, always show the course menu on the activity main page.
4359 if ($context->contextlevel == CONTEXT_MODULE &&
4360 !$courseformat->has_view_page()) {
4362 $this->page->navigation->initialise();
4363 $activenode = $this->page->navigation->find_active_node();
4364 // If the settings menu has been forced then show the menu.
4365 if ($this->page->is_settings_menu_forced()) {
4366 $showcoursemenu = true;
4367 } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
4368 $activenode->type == navigation_node::TYPE_RESOURCE)) {
4370 // We only want to show the menu on the first page of the activity. This means
4371 // the breadcrumb has no additional nodes.
4372 if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
4373 $showcoursemenu = true;
4378 // This is the site front page.
4379 if ($context->contextlevel == CONTEXT_COURSE &&
4380 !empty($currentnode) &&
4381 $currentnode->key === 'home') {
4382 $showfrontpagemenu = true;
4385 // This is the user profile page.
4386 if ($context->contextlevel == CONTEXT_USER &&
4387 !empty($currentnode) &&
4388 ($currentnode->key === 'myprofile')) {
4389 $showusermenu = true;
4392 if ($showfrontpagemenu) {
4393 $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
4394 if ($settingsnode) {
4395 // Build an action menu based on the visible nodes from this navigation tree.
4396 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4398 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4399 if ($skipped) {
4400 $text = get_string('morenavigationlinks');
4401 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4402 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4403 $menu->add_secondary_action($link);
4406 } else if ($showcoursemenu) {
4407 $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
4408 if ($settingsnode) {
4409 // Build an action menu based on the visible nodes from this navigation tree.
4410 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4412 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4413 if ($skipped) {
4414 $text = get_string('morenavigationlinks');
4415 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4416 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4417 $menu->add_secondary_action($link);
4420 } else if ($showusermenu) {
4421 // Get the course admin node from the settings navigation.
4422 $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
4423 if ($settingsnode) {
4424 // Build an action menu based on the visible nodes from this navigation tree.
4425 $this->build_action_menu_from_navigation($menu, $settingsnode);
4429 return $this->render($menu);
4433 * Take a node in the nav tree and make an action menu out of it.
4434 * The links are injected in the action menu.
4436 * @param action_menu $menu
4437 * @param navigation_node $node
4438 * @param boolean $indent
4439 * @param boolean $onlytopleafnodes
4440 * @return boolean nodesskipped - True if nodes were skipped in building the menu
4442 protected function build_action_menu_from_navigation(action_menu $menu,
4443 navigation_node $node,
4444 $indent = false,
4445 $onlytopleafnodes = false) {
4446 $skipped = false;
4447 // Build an action menu based on the visible nodes from this navigation tree.
4448 foreach ($node->children as $menuitem) {
4449 if ($menuitem->display) {
4450 if ($onlytopleafnodes && $menuitem->children->count()) {
4451 $skipped = true;
4452 continue;
4454 if ($menuitem->action) {
4455 if ($menuitem->action instanceof action_link) {
4456 $link = $menuitem->action;
4457 // Give preference to setting icon over action icon.
4458 if (!empty($menuitem->icon)) {
4459 $link->icon = $menuitem->icon;
4461 } else {
4462 $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
4464 } else {
4465 if ($onlytopleafnodes) {
4466 $skipped = true;
4467 continue;
4469 $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
4471 if ($indent) {
4472 $link->add_class('ml-4');
4474 if (!empty($menuitem->classes)) {
4475 $link->add_class(implode(" ", $menuitem->classes));
4478 $menu->add_secondary_action($link);
4479 $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
4482 return $skipped;
4486 * This is an optional menu that can be added to a layout by a theme. It contains the
4487 * menu for the most specific thing from the settings block. E.g. Module administration.
4489 * @return string
4491 public function region_main_settings_menu() {
4492 $context = $this->page->context;
4493 $menu = new action_menu();
4495 if ($context->contextlevel == CONTEXT_MODULE) {
4497 $this->page->navigation->initialise();
4498 $node = $this->page->navigation->find_active_node();
4499 $buildmenu = false;
4500 // If the settings menu has been forced then show the menu.
4501 if ($this->page->is_settings_menu_forced()) {
4502 $buildmenu = true;
4503 } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
4504 $node->type == navigation_node::TYPE_RESOURCE)) {
4506 $items = $this->page->navbar->get_items();
4507 $navbarnode = end($items);
4508 // We only want to show the menu on the first page of the activity. This means
4509 // the breadcrumb has no additional nodes.
4510 if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
4511 $buildmenu = true;
4514 if ($buildmenu) {
4515 // Get the course admin node from the settings navigation.
4516 $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
4517 if ($node) {
4518 // Build an action menu based on the visible nodes from this navigation tree.
4519 $this->build_action_menu_from_navigation($menu, $node);
4523 } else if ($context->contextlevel == CONTEXT_COURSECAT) {
4524 // For course category context, show category settings menu, if we're on the course category page.
4525 if ($this->page->pagetype === 'course-index-category') {
4526 $node = $this->page->settingsnav->find('categorysettings', navigation_node::TYPE_CONTAINER);
4527 if ($node) {
4528 // Build an action menu based on the visible nodes from this navigation tree.
4529 $this->build_action_menu_from_navigation($menu, $node);
4533 } else {
4534 $items = $this->page->navbar->get_items();
4535 $navbarnode = end($items);
4537 if ($navbarnode && ($navbarnode->key === 'participants')) {
4538 $node = $this->page->settingsnav->find('users', navigation_node::TYPE_CONTAINER);
4539 if ($node) {
4540 // Build an action menu based on the visible nodes from this navigation tree.
4541 $this->build_action_menu_from_navigation($menu, $node);
4546 return $this->render($menu);
4550 * Displays the list of tags associated with an entry
4552 * @param array $tags list of instances of core_tag or stdClass
4553 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4554 * to use default, set to '' (empty string) to omit the label completely
4555 * @param string $classes additional classes for the enclosing div element
4556 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4557 * will be appended to the end, JS will toggle the rest of the tags
4558 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4559 * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
4560 * @return string
4562 public function tag_list($tags, $label = null, $classes = '', $limit = 10,
4563 $pagecontext = null, $accesshidelabel = false) {
4564 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
4565 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4569 * Renders element for inline editing of any value
4571 * @param \core\output\inplace_editable $element
4572 * @return string
4574 public function render_inplace_editable(\core\output\inplace_editable $element) {
4575 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4579 * Renders a bar chart.
4581 * @param \core\chart_bar $chart The chart.
4582 * @return string.
4584 public function render_chart_bar(\core\chart_bar $chart) {
4585 return $this->render_chart($chart);
4589 * Renders a line chart.
4591 * @param \core\chart_line $chart The chart.
4592 * @return string.
4594 public function render_chart_line(\core\chart_line $chart) {
4595 return $this->render_chart($chart);
4599 * Renders a pie chart.
4601 * @param \core\chart_pie $chart The chart.
4602 * @return string.
4604 public function render_chart_pie(\core\chart_pie $chart) {
4605 return $this->render_chart($chart);
4609 * Renders a chart.
4611 * @param \core\chart_base $chart The chart.
4612 * @param bool $withtable Whether to include a data table with the chart.
4613 * @return string.
4615 public function render_chart(\core\chart_base $chart, $withtable = true) {
4616 $chartdata = json_encode($chart);
4617 return $this->render_from_template('core/chart', (object) [
4618 'chartdata' => $chartdata,
4619 'withtable' => $withtable
4624 * Renders the login form.
4626 * @param \core_auth\output\login $form The renderable.
4627 * @return string
4629 public function render_login(\core_auth\output\login $form) {
4630 global $CFG, $SITE;
4632 $context = $form->export_for_template($this);
4634 // Override because rendering is not supported in template yet.
4635 if ($CFG->rememberusername == 0) {
4636 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabledonlysession');
4637 } else {
4638 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
4640 $context->errorformatted = $this->error_text($context->error);
4641 $url = $this->get_logo_url();
4642 if ($url) {
4643 $url = $url->out(false);
4645 $context->logourl = $url;
4646 $context->sitename = format_string($SITE->fullname, true,
4647 ['context' => context_course::instance(SITEID), "escape" => false]);
4649 return $this->render_from_template('core/loginform', $context);
4653 * Renders an mform element from a template.
4655 * @param HTML_QuickForm_element $element element
4656 * @param bool $required if input is required field
4657 * @param bool $advanced if input is an advanced field
4658 * @param string $error error message to display
4659 * @param bool $ingroup True if this element is rendered as part of a group
4660 * @return mixed string|bool
4662 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4663 $templatename = 'core_form/element-' . $element->getType();
4664 if ($ingroup) {
4665 $templatename .= "-inline";
4667 try {
4668 // We call this to generate a file not found exception if there is no template.
4669 // We don't want to call export_for_template if there is no template.
4670 core\output\mustache_template_finder::get_template_filepath($templatename);
4672 if ($element instanceof templatable) {
4673 $elementcontext = $element->export_for_template($this);
4675 $helpbutton = '';
4676 if (method_exists($element, 'getHelpButton')) {
4677 $helpbutton = $element->getHelpButton();
4679 $label = $element->getLabel();
4680 $text = '';
4681 if (method_exists($element, 'getText')) {
4682 // There currently exists code that adds a form element with an empty label.
4683 // If this is the case then set the label to the description.
4684 if (empty($label)) {
4685 $label = $element->getText();
4686 } else {
4687 $text = $element->getText();
4691 // Generate the form element wrapper ids and names to pass to the template.
4692 // This differs between group and non-group elements.
4693 if ($element->getType() === 'group') {
4694 // Group element.
4695 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
4696 $elementcontext['wrapperid'] = $elementcontext['id'];
4698 // Ensure group elements pass through the group name as the element name.
4699 $elementcontext['name'] = $elementcontext['groupname'];
4700 } else {
4701 // Non grouped element.
4702 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
4703 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
4706 $context = array(
4707 'element' => $elementcontext,
4708 'label' => $label,
4709 'text' => $text,
4710 'required' => $required,
4711 'advanced' => $advanced,
4712 'helpbutton' => $helpbutton,
4713 'error' => $error
4715 return $this->render_from_template($templatename, $context);
4717 } catch (Exception $e) {
4718 // No template for this element.
4719 return false;
4724 * Render the login signup form into a nice template for the theme.
4726 * @param mform $form
4727 * @return string
4729 public function render_login_signup_form($form) {
4730 global $SITE;
4732 $context = $form->export_for_template($this);
4733 $url = $this->get_logo_url();
4734 if ($url) {
4735 $url = $url->out(false);
4737 $context['logourl'] = $url;
4738 $context['sitename'] = format_string($SITE->fullname, true,
4739 ['context' => context_course::instance(SITEID), "escape" => false]);
4741 return $this->render_from_template('core/signup_form_layout', $context);
4745 * Render the verify age and location page into a nice template for the theme.
4747 * @param \core_auth\output\verify_age_location_page $page The renderable
4748 * @return string
4750 protected function render_verify_age_location_page($page) {
4751 $context = $page->export_for_template($this);
4753 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4757 * Render the digital minor contact information page into a nice template for the theme.
4759 * @param \core_auth\output\digital_minor_page $page The renderable
4760 * @return string
4762 protected function render_digital_minor_page($page) {
4763 $context = $page->export_for_template($this);
4765 return $this->render_from_template('core/auth_digital_minor_page', $context);
4769 * Renders a progress bar.
4771 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4773 * @param progress_bar $bar The bar.
4774 * @return string HTML fragment
4776 public function render_progress_bar(progress_bar $bar) {
4777 $data = $bar->export_for_template($this);
4778 return $this->render_from_template('core/progress_bar', $data);
4782 * Renders element for a toggle-all checkbox.
4784 * @param \core\output\checkbox_toggleall $element
4785 * @return string
4787 public function render_checkbox_toggleall(\core\output\checkbox_toggleall $element) {
4788 return $this->render_from_template($element->get_template(), $element->export_for_template($this));
4793 * A renderer that generates output for command-line scripts.
4795 * The implementation of this renderer is probably incomplete.
4797 * @copyright 2009 Tim Hunt
4798 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4799 * @since Moodle 2.0
4800 * @package core
4801 * @category output
4803 class core_renderer_cli extends core_renderer {
4806 * Returns the page header.
4808 * @return string HTML fragment
4810 public function header() {
4811 return $this->page->heading . "\n";
4815 * Renders a Check API result
4817 * To aid in CLI consistency this status is NOT translated and the visual
4818 * width is always exactly 10 chars.
4820 * @param result $result
4821 * @return string HTML fragment
4823 protected function render_check_result(core\check\result $result) {
4824 $status = $result->get_status();
4826 $labels = [
4827 core\check\result::NA => ' ' . cli_ansi_format('<colour:gray>' ) . ' NA ',
4828 core\check\result::OK => ' ' . cli_ansi_format('<colour:green>') . ' OK ',
4829 core\check\result::INFO => ' ' . cli_ansi_format('<colour:blue>' ) . ' INFO ',
4830 core\check\result::UNKNOWN => ' ' . cli_ansi_format('<colour:grey>' ) . ' UNKNOWN ',
4831 core\check\result::WARNING => ' ' . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
4832 core\check\result::ERROR => ' ' . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
4833 core\check\result::CRITICAL => '' . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
4835 $string = $labels[$status] . cli_ansi_format('<colour:normal>');
4836 return $string;
4840 * Renders a Check API result
4842 * @param result $result
4843 * @return string fragment
4845 public function check_result(core\check\result $result) {
4846 return $this->render_check_result($result);
4850 * Returns a template fragment representing a Heading.
4852 * @param string $text The text of the heading
4853 * @param int $level The level of importance of the heading
4854 * @param string $classes A space-separated list of CSS classes
4855 * @param string $id An optional ID
4856 * @return string A template fragment for a heading
4858 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4859 $text .= "\n";
4860 switch ($level) {
4861 case 1:
4862 return '=>' . $text;
4863 case 2:
4864 return '-->' . $text;
4865 default:
4866 return $text;
4871 * Returns a template fragment representing a fatal error.
4873 * @param string $message The message to output
4874 * @param string $moreinfourl URL where more info can be found about the error
4875 * @param string $link Link for the Continue button
4876 * @param array $backtrace The execution backtrace
4877 * @param string $debuginfo Debugging information
4878 * @return string A template fragment for a fatal error
4880 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4881 global $CFG;
4883 $output = "!!! $message !!!\n";
4885 if ($CFG->debugdeveloper) {
4886 if (!empty($debuginfo)) {
4887 $output .= $this->notification($debuginfo, 'notifytiny');
4889 if (!empty($backtrace)) {
4890 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
4894 return $output;
4898 * Returns a template fragment representing a notification.
4900 * @param string $message The message to print out.
4901 * @param string $type The type of notification. See constants on \core\output\notification.
4902 * @return string A template fragment for a notification
4904 public function notification($message, $type = null) {
4905 $message = clean_text($message);
4906 if ($type === 'notifysuccess' || $type === 'success') {
4907 return "++ $message ++\n";
4909 return "!! $message !!\n";
4913 * There is no footer for a cli request, however we must override the
4914 * footer method to prevent the default footer.
4916 public function footer() {}
4919 * Render a notification (that is, a status message about something that has
4920 * just happened).
4922 * @param \core\output\notification $notification the notification to print out
4923 * @return string plain text output
4925 public function render_notification(\core\output\notification $notification) {
4926 return $this->notification($notification->get_message(), $notification->get_message_type());
4932 * A renderer that generates output for ajax scripts.
4934 * This renderer prevents accidental sends back only json
4935 * encoded error messages, all other output is ignored.
4937 * @copyright 2010 Petr Skoda
4938 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4939 * @since Moodle 2.0
4940 * @package core
4941 * @category output
4943 class core_renderer_ajax extends core_renderer {
4946 * Returns a template fragment representing a fatal error.
4948 * @param string $message The message to output
4949 * @param string $moreinfourl URL where more info can be found about the error
4950 * @param string $link Link for the Continue button
4951 * @param array $backtrace The execution backtrace
4952 * @param string $debuginfo Debugging information
4953 * @return string A template fragment for a fatal error
4955 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4956 global $CFG;
4958 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
4960 $e = new stdClass();
4961 $e->error = $message;
4962 $e->errorcode = $errorcode;
4963 $e->stacktrace = NULL;
4964 $e->debuginfo = NULL;
4965 $e->reproductionlink = NULL;
4966 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
4967 $link = (string) $link;
4968 if ($link) {
4969 $e->reproductionlink = $link;
4971 if (!empty($debuginfo)) {
4972 $e->debuginfo = $debuginfo;
4974 if (!empty($backtrace)) {
4975 $e->stacktrace = format_backtrace($backtrace, true);
4978 $this->header();
4979 return json_encode($e);
4983 * Used to display a notification.
4984 * For the AJAX notifications are discarded.
4986 * @param string $message The message to print out.
4987 * @param string $type The type of notification. See constants on \core\output\notification.
4989 public function notification($message, $type = null) {}
4992 * Used to display a redirection message.
4993 * AJAX redirections should not occur and as such redirection messages
4994 * are discarded.
4996 * @param moodle_url|string $encodedurl
4997 * @param string $message
4998 * @param int $delay
4999 * @param bool $debugdisableredirect
5000 * @param string $messagetype The type of notification to show the message in.
5001 * See constants on \core\output\notification.
5003 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
5004 $messagetype = \core\output\notification::NOTIFY_INFO) {}
5007 * Prepares the start of an AJAX output.
5009 public function header() {
5010 // unfortunately YUI iframe upload does not support application/json
5011 if (!empty($_FILES)) {
5012 @header('Content-type: text/plain; charset=utf-8');
5013 if (!core_useragent::supports_json_contenttype()) {
5014 @header('X-Content-Type-Options: nosniff');
5016 } else if (!core_useragent::supports_json_contenttype()) {
5017 @header('Content-type: text/plain; charset=utf-8');
5018 @header('X-Content-Type-Options: nosniff');
5019 } else {
5020 @header('Content-type: application/json; charset=utf-8');
5023 // Headers to make it not cacheable and json
5024 @header('Cache-Control: no-store, no-cache, must-revalidate');
5025 @header('Cache-Control: post-check=0, pre-check=0', false);
5026 @header('Pragma: no-cache');
5027 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
5028 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
5029 @header('Accept-Ranges: none');
5033 * There is no footer for an AJAX request, however we must override the
5034 * footer method to prevent the default footer.
5036 public function footer() {}
5039 * No need for headers in an AJAX request... this should never happen.
5040 * @param string $text
5041 * @param int $level
5042 * @param string $classes
5043 * @param string $id
5045 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
5051 * The maintenance renderer.
5053 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
5054 * is running a maintenance related task.
5055 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
5057 * @since Moodle 2.6
5058 * @package core
5059 * @category output
5060 * @copyright 2013 Sam Hemelryk
5061 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5063 class core_renderer_maintenance extends core_renderer {
5066 * Initialises the renderer instance.
5068 * @param moodle_page $page
5069 * @param string $target
5070 * @throws coding_exception
5072 public function __construct(moodle_page $page, $target) {
5073 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
5074 throw new coding_exception('Invalid request for the maintenance renderer.');
5076 parent::__construct($page, $target);
5080 * Does nothing. The maintenance renderer cannot produce blocks.
5082 * @param block_contents $bc
5083 * @param string $region
5084 * @return string
5086 public function block(block_contents $bc, $region) {
5087 return '';
5091 * Does nothing. The maintenance renderer cannot produce blocks.
5093 * @param string $region
5094 * @param array $classes
5095 * @param string $tag
5096 * @return string
5098 public function blocks($region, $classes = array(), $tag = 'aside') {
5099 return '';
5103 * Does nothing. The maintenance renderer cannot produce blocks.
5105 * @param string $region
5106 * @return string
5108 public function blocks_for_region($region) {
5109 return '';
5113 * Does nothing. The maintenance renderer cannot produce a course content header.
5115 * @param bool $onlyifnotcalledbefore
5116 * @return string
5118 public function course_content_header($onlyifnotcalledbefore = false) {
5119 return '';
5123 * Does nothing. The maintenance renderer cannot produce a course content footer.
5125 * @param bool $onlyifnotcalledbefore
5126 * @return string
5128 public function course_content_footer($onlyifnotcalledbefore = false) {
5129 return '';
5133 * Does nothing. The maintenance renderer cannot produce a course header.
5135 * @return string
5137 public function course_header() {
5138 return '';
5142 * Does nothing. The maintenance renderer cannot produce a course footer.
5144 * @return string
5146 public function course_footer() {
5147 return '';
5151 * Does nothing. The maintenance renderer cannot produce a custom menu.
5153 * @param string $custommenuitems
5154 * @return string
5156 public function custom_menu($custommenuitems = '') {
5157 return '';
5161 * Does nothing. The maintenance renderer cannot produce a file picker.
5163 * @param array $options
5164 * @return string
5166 public function file_picker($options) {
5167 return '';
5171 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
5173 * @param array $dir
5174 * @return string
5176 public function htmllize_file_tree($dir) {
5177 return '';
5182 * Overridden confirm message for upgrades.
5184 * @param string $message The question to ask the user
5185 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5186 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5187 * @return string HTML fragment
5189 public function confirm($message, $continue, $cancel) {
5190 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5191 // from any previous version of Moodle).
5192 if ($continue instanceof single_button) {
5193 $continue->primary = true;
5194 } else if (is_string($continue)) {
5195 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
5196 } else if ($continue instanceof moodle_url) {
5197 $continue = new single_button($continue, get_string('continue'), 'post', true);
5198 } else {
5199 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5200 ' (string/moodle_url) or a single_button instance.');
5203 if ($cancel instanceof single_button) {
5204 $output = '';
5205 } else if (is_string($cancel)) {
5206 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5207 } else if ($cancel instanceof moodle_url) {
5208 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5209 } else {
5210 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5211 ' (string/moodle_url) or a single_button instance.');
5214 $output = $this->box_start('generalbox', 'notice');
5215 $output .= html_writer::tag('h4', get_string('confirm'));
5216 $output .= html_writer::tag('p', $message);
5217 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
5218 $output .= $this->box_end();
5219 return $output;
5223 * Does nothing. The maintenance renderer does not support JS.
5225 * @param block_contents $bc
5227 public function init_block_hider_js(block_contents $bc) {
5228 // Does nothing.
5232 * Does nothing. The maintenance renderer cannot produce language menus.
5234 * @return string
5236 public function lang_menu() {
5237 return '';
5241 * Does nothing. The maintenance renderer has no need for login information.
5243 * @param null $withlinks
5244 * @return string
5246 public function login_info($withlinks = null) {
5247 return '';
5251 * Secure login info.
5253 * @return string
5255 public function secure_login_info() {
5256 return $this->login_info(false);
5260 * Does nothing. The maintenance renderer cannot produce user pictures.
5262 * @param stdClass $user
5263 * @param array $options
5264 * @return string
5266 public function user_picture(stdClass $user, array $options = null) {
5267 return '';