Automatically generated installer lang files
[moodle.git] / lib / outputrenderers.php
blobd81e43a10dfd2f66e71e16bab26d0590ba8665bc
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
21 * for an overview.
23 * Included in this file are the primary renderer classes:
24 * - renderer_base: The renderer outline class that all renderers
25 * should inherit from.
26 * - core_renderer: The standard HTML renderer.
27 * - core_renderer_cli: An adaption of the standard renderer for CLI scripts.
28 * - core_renderer_ajax: An adaption of the standard renderer for AJAX scripts.
29 * - plugin_renderer_base: A renderer class that should be extended by all
30 * plugin renderers.
32 * @package core
33 * @category output
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') || die();
40 /**
41 * Simple base class for Moodle renderers.
43 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
45 * Also has methods to facilitate generating HTML output.
47 * @copyright 2009 Tim Hunt
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 * @since Moodle 2.0
50 * @package core
51 * @category output
53 class renderer_base {
54 /**
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
59 /**
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
62 protected $page;
64 /**
65 * @var string The requested rendering target.
67 protected $target;
69 /**
70 * @var Mustache_Engine $mustache The mustache template compiler
72 private $mustache;
74 /**
75 * Return an instance of the mustache class.
77 * @since 2.9
78 * @return Mustache_Engine
80 protected function get_mustache() {
81 global $CFG;
83 if ($this->mustache === null) {
84 require_once("{$CFG->libdir}/filelib.php");
86 $themename = $this->page->theme->name;
87 $themerev = theme_get_revision();
89 // Create new localcache directory.
90 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
92 // Remove old localcache directories.
93 $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR);
94 foreach ($mustachecachedirs as $localcachedir) {
95 $cachedrev = [];
96 preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
97 $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
98 if ($cachedrev > 0 && $cachedrev < $themerev) {
99 fulldelete($localcachedir);
103 $loader = new \core\output\mustache_filesystem_loader();
104 $stringhelper = new \core\output\mustache_string_helper();
105 $quotehelper = new \core\output\mustache_quote_helper();
106 $jshelper = new \core\output\mustache_javascript_helper($this->page);
107 $pixhelper = new \core\output\mustache_pix_helper($this);
108 $shortentexthelper = new \core\output\mustache_shorten_text_helper();
109 $userdatehelper = new \core\output\mustache_user_date_helper();
111 // We only expose the variables that are exposed to JS templates.
112 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
114 $helpers = array('config' => $safeconfig,
115 'str' => array($stringhelper, 'str'),
116 'quote' => array($quotehelper, 'quote'),
117 'js' => array($jshelper, 'help'),
118 'pix' => array($pixhelper, 'pix'),
119 'shortentext' => array($shortentexthelper, 'shorten'),
120 'userdate' => array($userdatehelper, 'transform'),
123 $this->mustache = new \core\output\mustache_engine(array(
124 'cache' => $cachedir,
125 'escape' => 's',
126 'loader' => $loader,
127 'helpers' => $helpers,
128 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS],
129 // Don't allow the JavaScript helper to be executed from within another
130 // helper. If it's allowed it can be used by users to inject malicious
131 // JS into the page.
132 'disallowednestedhelpers' => ['js']));
136 return $this->mustache;
141 * Constructor
143 * The constructor takes two arguments. The first is the page that the renderer
144 * has been created to assist with, and the second is the target.
145 * The target is an additional identifier that can be used to load different
146 * renderers for different options.
148 * @param moodle_page $page the page we are doing output for.
149 * @param string $target one of rendering target constants
151 public function __construct(moodle_page $page, $target) {
152 $this->opencontainers = $page->opencontainers;
153 $this->page = $page;
154 $this->target = $target;
158 * Renders a template by name with the given context.
160 * The provided data needs to be array/stdClass made up of only simple types.
161 * Simple types are array,stdClass,bool,int,float,string
163 * @since 2.9
164 * @param array|stdClass $context Context containing data for the template.
165 * @return string|boolean
167 public function render_from_template($templatename, $context) {
168 static $templatecache = array();
169 $mustache = $this->get_mustache();
171 try {
172 // Grab a copy of the existing helper to be restored later.
173 $uniqidhelper = $mustache->getHelper('uniqid');
174 } catch (Mustache_Exception_UnknownHelperException $e) {
175 // Helper doesn't exist.
176 $uniqidhelper = null;
179 // Provide 1 random value that will not change within a template
180 // but will be different from template to template. This is useful for
181 // e.g. aria attributes that only work with id attributes and must be
182 // unique in a page.
183 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
184 if (isset($templatecache[$templatename])) {
185 $template = $templatecache[$templatename];
186 } else {
187 try {
188 $template = $mustache->loadTemplate($templatename);
189 $templatecache[$templatename] = $template;
190 } catch (Mustache_Exception_UnknownTemplateException $e) {
191 throw new moodle_exception('Unknown template: ' . $templatename);
195 $renderedtemplate = trim($template->render($context));
197 // If we had an existing uniqid helper then we need to restore it to allow
198 // handle nested calls of render_from_template.
199 if ($uniqidhelper) {
200 $mustache->addHelper('uniqid', $uniqidhelper);
203 return $renderedtemplate;
208 * Returns rendered widget.
210 * The provided widget needs to be an object that extends the renderable
211 * interface.
212 * If will then be rendered by a method based upon the classname for the widget.
213 * For instance a widget of class `crazywidget` will be rendered by a protected
214 * render_crazywidget method of this renderer.
215 * If no render_crazywidget method exists and crazywidget implements templatable,
216 * look for the 'crazywidget' template in the same component and render that.
218 * @param renderable $widget instance with renderable interface
219 * @return string
221 public function render(renderable $widget) {
222 $classparts = explode('\\', get_class($widget));
223 // Strip namespaces.
224 $classname = array_pop($classparts);
225 // Remove _renderable suffixes
226 $classname = preg_replace('/_renderable$/', '', $classname);
228 $rendermethod = 'render_'.$classname;
229 if (method_exists($this, $rendermethod)) {
230 return $this->$rendermethod($widget);
232 if ($widget instanceof templatable) {
233 $component = array_shift($classparts);
234 if (!$component) {
235 $component = 'core';
237 $template = $component . '/' . $classname;
238 $context = $widget->export_for_template($this);
239 return $this->render_from_template($template, $context);
241 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
245 * Adds a JS action for the element with the provided id.
247 * This method adds a JS event for the provided component action to the page
248 * and then returns the id that the event has been attached to.
249 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
251 * @param component_action $action
252 * @param string $id
253 * @return string id of element, either original submitted or random new if not supplied
255 public function add_action_handler(component_action $action, $id = null) {
256 if (!$id) {
257 $id = html_writer::random_id($action->event);
259 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
260 return $id;
264 * Returns true is output has already started, and false if not.
266 * @return boolean true if the header has been printed.
268 public function has_started() {
269 return $this->page->state >= moodle_page::STATE_IN_BODY;
273 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
275 * @param mixed $classes Space-separated string or array of classes
276 * @return string HTML class attribute value
278 public static function prepare_classes($classes) {
279 if (is_array($classes)) {
280 return implode(' ', array_unique($classes));
282 return $classes;
286 * Return the direct URL for an image from the pix folder.
288 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
290 * @deprecated since Moodle 3.3
291 * @param string $imagename the name of the icon.
292 * @param string $component specification of one plugin like in get_string()
293 * @return moodle_url
295 public function pix_url($imagename, $component = 'moodle') {
296 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
297 return $this->page->theme->image_url($imagename, $component);
301 * Return the moodle_url for an image.
303 * The exact image location and extension is determined
304 * automatically by searching for gif|png|jpg|jpeg, please
305 * note there can not be diferent images with the different
306 * extension. The imagename is for historical reasons
307 * a relative path name, it may be changed later for core
308 * images. It is recommended to not use subdirectories
309 * in plugin and theme pix directories.
311 * There are three types of images:
312 * 1/ theme images - stored in theme/mytheme/pix/,
313 * use component 'theme'
314 * 2/ core images - stored in /pix/,
315 * overridden via theme/mytheme/pix_core/
316 * 3/ plugin images - stored in mod/mymodule/pix,
317 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
318 * example: image_url('comment', 'mod_glossary')
320 * @param string $imagename the pathname of the image
321 * @param string $component full plugin name (aka component) or 'theme'
322 * @return moodle_url
324 public function image_url($imagename, $component = 'moodle') {
325 return $this->page->theme->image_url($imagename, $component);
329 * Return the site's logo URL, if any.
331 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
332 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
333 * @return moodle_url|false
335 public function get_logo_url($maxwidth = null, $maxheight = 200) {
336 global $CFG;
337 $logo = get_config('core_admin', 'logo');
338 if (empty($logo)) {
339 return false;
342 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
343 // It's not worth the overhead of detecting and serving 2 different images based on the device.
345 // Hide the requested size in the file path.
346 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
348 // Use $CFG->themerev to prevent browser caching when the file changes.
349 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
350 theme_get_revision(), $logo);
354 * Return the site's compact logo URL, if any.
356 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
357 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
358 * @return moodle_url|false
360 public function get_compact_logo_url($maxwidth = 300, $maxheight = 300) {
361 global $CFG;
362 $logo = get_config('core_admin', 'logocompact');
363 if (empty($logo)) {
364 return false;
367 // Hide the requested size in the file path.
368 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
370 // Use $CFG->themerev to prevent browser caching when the file changes.
371 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
372 theme_get_revision(), $logo);
376 * Whether we should display the logo in the navbar.
378 * We will when there are no main logos, and we have compact logo.
380 * @return bool
382 public function should_display_navbar_logo() {
383 $logo = $this->get_compact_logo_url();
384 return !empty($logo) && !$this->should_display_main_logo();
388 * Whether we should display the main logo.
390 * @param int $headinglevel The heading level we want to check against.
391 * @return bool
393 public function should_display_main_logo($headinglevel = 1) {
395 // Only render the logo if we're on the front page or login page and the we have a logo.
396 $logo = $this->get_logo_url();
397 if ($headinglevel == 1 && !empty($logo)) {
398 if ($this->page->pagelayout == 'frontpage' || $this->page->pagelayout == 'login') {
399 return true;
403 return false;
410 * Basis for all plugin renderers.
412 * @copyright Petr Skoda (skodak)
413 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
414 * @since Moodle 2.0
415 * @package core
416 * @category output
418 class plugin_renderer_base extends renderer_base {
421 * @var renderer_base|core_renderer A reference to the current renderer.
422 * The renderer provided here will be determined by the page but will in 90%
423 * of cases by the {@link core_renderer}
425 protected $output;
428 * Constructor method, calls the parent constructor
430 * @param moodle_page $page
431 * @param string $target one of rendering target constants
433 public function __construct(moodle_page $page, $target) {
434 if (empty($target) && $page->pagelayout === 'maintenance') {
435 // If the page is using the maintenance layout then we're going to force the target to maintenance.
436 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
437 // unavailable for this page layout.
438 $target = RENDERER_TARGET_MAINTENANCE;
440 $this->output = $page->get_renderer('core', null, $target);
441 parent::__construct($page, $target);
445 * Renders the provided widget and returns the HTML to display it.
447 * @param renderable $widget instance with renderable interface
448 * @return string
450 public function render(renderable $widget) {
451 $classname = get_class($widget);
452 // Strip namespaces.
453 $classname = preg_replace('/^.*\\\/', '', $classname);
454 // Keep a copy at this point, we may need to look for a deprecated method.
455 $deprecatedmethod = 'render_'.$classname;
456 // Remove _renderable suffixes
457 $classname = preg_replace('/_renderable$/', '', $classname);
459 $rendermethod = 'render_'.$classname;
460 if (method_exists($this, $rendermethod)) {
461 return $this->$rendermethod($widget);
463 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
464 // This is exactly where we don't want to be.
465 // If you have arrived here you have a renderable component within your plugin that has the name
466 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
467 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
468 // and the _renderable suffix now gets removed when looking for a render method.
469 // You need to change your renderers render_blah_renderable to render_blah.
470 // Until you do this it will not be possible for a theme to override the renderer to override your method.
471 // Please do it ASAP.
472 static $debugged = array();
473 if (!isset($debugged[$deprecatedmethod])) {
474 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
475 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
476 $debugged[$deprecatedmethod] = true;
478 return $this->$deprecatedmethod($widget);
480 // pass to core renderer if method not found here
481 return $this->output->render($widget);
485 * Magic method used to pass calls otherwise meant for the standard renderer
486 * to it to ensure we don't go causing unnecessary grief.
488 * @param string $method
489 * @param array $arguments
490 * @return mixed
492 public function __call($method, $arguments) {
493 if (method_exists('renderer_base', $method)) {
494 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
496 if (method_exists($this->output, $method)) {
497 return call_user_func_array(array($this->output, $method), $arguments);
498 } else {
499 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
506 * The standard implementation of the core_renderer interface.
508 * @copyright 2009 Tim Hunt
509 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
510 * @since Moodle 2.0
511 * @package core
512 * @category output
514 class core_renderer extends renderer_base {
516 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
517 * in layout files instead.
518 * @deprecated
519 * @var string used in {@link core_renderer::header()}.
521 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
524 * @var string Used to pass information from {@link core_renderer::doctype()} to
525 * {@link core_renderer::standard_head_html()}.
527 protected $contenttype;
530 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
531 * with {@link core_renderer::header()}.
533 protected $metarefreshtag = '';
536 * @var string Unique token for the closing HTML
538 protected $unique_end_html_token;
541 * @var string Unique token for performance information
543 protected $unique_performance_info_token;
546 * @var string Unique token for the main content.
548 protected $unique_main_content_token;
550 /** @var custom_menu_item language The language menu if created */
551 protected $language = null;
554 * Constructor
556 * @param moodle_page $page the page we are doing output for.
557 * @param string $target one of rendering target constants
559 public function __construct(moodle_page $page, $target) {
560 $this->opencontainers = $page->opencontainers;
561 $this->page = $page;
562 $this->target = $target;
564 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
565 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
566 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
570 * Get the DOCTYPE declaration that should be used with this page. Designed to
571 * be called in theme layout.php files.
573 * @return string the DOCTYPE declaration that should be used.
575 public function doctype() {
576 if ($this->page->theme->doctype === 'html5') {
577 $this->contenttype = 'text/html; charset=utf-8';
578 return "<!DOCTYPE html>\n";
580 } else if ($this->page->theme->doctype === 'xhtml5') {
581 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
582 return "<!DOCTYPE html>\n";
584 } else {
585 // legacy xhtml 1.0
586 $this->contenttype = 'text/html; charset=utf-8';
587 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
592 * The attributes that should be added to the <html> tag. Designed to
593 * be called in theme layout.php files.
595 * @return string HTML fragment.
597 public function htmlattributes() {
598 $return = get_html_lang(true);
599 $attributes = array();
600 if ($this->page->theme->doctype !== 'html5') {
601 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
604 // Give plugins an opportunity to add things like xml namespaces to the html element.
605 // This function should return an array of html attribute names => values.
606 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
607 foreach ($pluginswithfunction as $plugins) {
608 foreach ($plugins as $function) {
609 $newattrs = $function();
610 unset($newattrs['dir']);
611 unset($newattrs['lang']);
612 unset($newattrs['xmlns']);
613 unset($newattrs['xml:lang']);
614 $attributes += $newattrs;
618 foreach ($attributes as $key => $val) {
619 $val = s($val);
620 $return .= " $key=\"$val\"";
623 return $return;
627 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
628 * that should be included in the <head> tag. Designed to be called in theme
629 * layout.php files.
631 * @return string HTML fragment.
633 public function standard_head_html() {
634 global $CFG, $SESSION, $SITE;
636 // Before we output any content, we need to ensure that certain
637 // page components are set up.
639 // Blocks must be set up early as they may require javascript which
640 // has to be included in the page header before output is created.
641 foreach ($this->page->blocks->get_regions() as $region) {
642 $this->page->blocks->ensure_content_created($region, $this);
645 $output = '';
647 // Give plugins an opportunity to add any head elements. The callback
648 // must always return a string containing valid html head content.
649 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
650 foreach ($pluginswithfunction as $plugins) {
651 foreach ($plugins as $function) {
652 $output .= $function();
656 // Allow a url_rewrite plugin to setup any dynamic head content.
657 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
658 $class = $CFG->urlrewriteclass;
659 $output .= $class::html_head_setup();
662 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
663 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
664 // This is only set by the {@link redirect()} method
665 $output .= $this->metarefreshtag;
667 // Check if a periodic refresh delay has been set and make sure we arn't
668 // already meta refreshing
669 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
670 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
673 // Set up help link popups for all links with the helptooltip class
674 $this->page->requires->js_init_call('M.util.help_popups.setup');
676 $focus = $this->page->focuscontrol;
677 if (!empty($focus)) {
678 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
679 // This is a horrifically bad way to handle focus but it is passed in
680 // through messy formslib::moodleform
681 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
682 } else if (strpos($focus, '.')!==false) {
683 // Old style of focus, bad way to do it
684 debugging('This code is using the old style focus event, Please update this code to focus on an element id or the moodleform focus method.', DEBUG_DEVELOPER);
685 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
686 } else {
687 // Focus element with given id
688 $this->page->requires->js_function_call('focuscontrol', array($focus));
692 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
693 // any other custom CSS can not be overridden via themes and is highly discouraged
694 $urls = $this->page->theme->css_urls($this->page);
695 foreach ($urls as $url) {
696 $this->page->requires->css_theme($url);
699 // Get the theme javascript head and footer
700 if ($jsurl = $this->page->theme->javascript_url(true)) {
701 $this->page->requires->js($jsurl, true);
703 if ($jsurl = $this->page->theme->javascript_url(false)) {
704 $this->page->requires->js($jsurl);
707 // Get any HTML from the page_requirements_manager.
708 $output .= $this->page->requires->get_head_code($this->page, $this);
710 // List alternate versions.
711 foreach ($this->page->alternateversions as $type => $alt) {
712 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
713 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
716 // Add noindex tag if relevant page and setting applied.
717 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
718 $loginpages = array('login-index', 'login-signup');
719 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
720 if (!isset($CFG->additionalhtmlhead)) {
721 $CFG->additionalhtmlhead = '';
723 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
726 if (!empty($CFG->additionalhtmlhead)) {
727 $output .= "\n".$CFG->additionalhtmlhead;
730 if ($this->page->pagelayout == 'frontpage') {
731 $summary = s(strip_tags(format_text($SITE->summary, FORMAT_HTML)));
732 if (!empty($summary)) {
733 $output .= "<meta name=\"description\" content=\"$summary\" />\n";
737 return $output;
741 * The standard tags (typically skip links) that should be output just inside
742 * the start of the <body> tag. Designed to be called in theme layout.php files.
744 * @return string HTML fragment.
746 public function standard_top_of_body_html() {
747 global $CFG;
748 $output = $this->page->requires->get_top_of_body_code($this);
749 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
750 $output .= "\n".$CFG->additionalhtmltopofbody;
753 // Give subsystems an opportunity to inject extra html content. The callback
754 // must always return a string containing valid html.
755 foreach (\core_component::get_core_subsystems() as $name => $path) {
756 if ($path) {
757 $output .= component_callback($name, 'before_standard_top_of_body_html', [], '');
761 // Give plugins an opportunity to inject extra html content. The callback
762 // must always return a string containing valid html.
763 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
764 foreach ($pluginswithfunction as $plugins) {
765 foreach ($plugins as $function) {
766 $output .= $function();
770 $output .= $this->maintenance_warning();
772 return $output;
776 * Scheduled maintenance warning message.
778 * Note: This is a nasty hack to display maintenance notice, this should be moved
779 * to some general notification area once we have it.
781 * @return string
783 public function maintenance_warning() {
784 global $CFG;
786 $output = '';
787 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
788 $timeleft = $CFG->maintenance_later - time();
789 // If timeleft less than 30 sec, set the class on block to error to highlight.
790 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
791 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-3 alert');
792 $a = new stdClass();
793 $a->hour = (int)($timeleft / 3600);
794 $a->min = (int)(($timeleft / 60) % 60);
795 $a->sec = (int)($timeleft % 60);
796 if ($a->hour > 0) {
797 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
798 } else {
799 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
802 $output .= $this->box_end();
803 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
804 array(array('timeleftinsec' => $timeleft)));
805 $this->page->requires->strings_for_js(
806 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
807 'admin');
809 return $output;
813 * The standard tags (typically performance information and validation links,
814 * if we are in developer debug mode) that should be output in the footer area
815 * of the page. Designed to be called in theme layout.php files.
817 * @return string HTML fragment.
819 public function standard_footer_html() {
820 global $CFG, $SCRIPT;
822 $output = '';
823 if (during_initial_install()) {
824 // Debugging info can not work before install is finished,
825 // in any case we do not want any links during installation!
826 return $output;
829 // Give plugins an opportunity to add any footer elements.
830 // The callback must always return a string containing valid html footer content.
831 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
832 foreach ($pluginswithfunction as $plugins) {
833 foreach ($plugins as $function) {
834 $output .= $function();
838 if (core_userfeedback::can_give_feedback()) {
839 $output .= html_writer::div(
840 $this->render_from_template('core/userfeedback_footer_link', ['url' => core_userfeedback::make_link()->out(false)])
844 // This function is normally called from a layout.php file in {@link core_renderer::header()}
845 // but some of the content won't be known until later, so we return a placeholder
846 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
847 $output .= $this->unique_performance_info_token;
848 if ($this->page->devicetypeinuse == 'legacy') {
849 // The legacy theme is in use print the notification
850 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
853 // Get links to switch device types (only shown for users not on a default device)
854 $output .= $this->theme_switch_links();
856 if (!empty($CFG->debugpageinfo)) {
857 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
858 $this->page->debug_summary()) . '</div>';
860 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
861 // Add link to profiling report if necessary
862 if (function_exists('profiling_is_running') && profiling_is_running()) {
863 $txt = get_string('profiledscript', 'admin');
864 $title = get_string('profiledscriptview', 'admin');
865 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
866 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
867 $output .= '<div class="profilingfooter">' . $link . '</div>';
869 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
870 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
871 $output .= '<div class="purgecaches">' .
872 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
874 if (!empty($CFG->debugvalidators)) {
875 // NOTE: this is not a nice hack, $this->page->url is not always accurate and
876 // $FULLME neither, it is not a bug if it fails. --skodak.
877 $output .= '<div class="validators"><ul class="list-unstyled ml-1">
878 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
879 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
880 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&amp;warnp2n3e=1&amp;url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
881 </ul></div>';
883 return $output;
887 * Returns standard main content placeholder.
888 * Designed to be called in theme layout.php files.
890 * @return string HTML fragment.
892 public function main_content() {
893 // This is here because it is the only place we can inject the "main" role over the entire main content area
894 // without requiring all theme's to manually do it, and without creating yet another thing people need to
895 // remember in the theme.
896 // This is an unfortunate hack. DO NO EVER add anything more here.
897 // DO NOT add classes.
898 // DO NOT add an id.
899 return '<div role="main">'.$this->unique_main_content_token.'</div>';
903 * Returns standard navigation between activities in a course.
905 * @return string the navigation HTML.
907 public function activity_navigation() {
908 // First we should check if we want to add navigation.
909 $context = $this->page->context;
910 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
911 || $context->contextlevel != CONTEXT_MODULE) {
912 return '';
915 // If the activity is in stealth mode, show no links.
916 if ($this->page->cm->is_stealth()) {
917 return '';
920 // Get a list of all the activities in the course.
921 $course = $this->page->cm->get_course();
922 $modules = get_fast_modinfo($course->id)->get_cms();
924 // Put the modules into an array in order by the position they are shown in the course.
925 $mods = [];
926 $activitylist = [];
927 foreach ($modules as $module) {
928 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
929 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
930 continue;
932 $mods[$module->id] = $module;
934 // No need to add the current module to the list for the activity dropdown menu.
935 if ($module->id == $this->page->cm->id) {
936 continue;
938 // Module name.
939 $modname = $module->get_formatted_name();
940 // Display the hidden text if necessary.
941 if (!$module->visible) {
942 $modname .= ' ' . get_string('hiddenwithbrackets');
944 // Module URL.
945 $linkurl = new moodle_url($module->url, array('forceview' => 1));
946 // Add module URL (as key) and name (as value) to the activity list array.
947 $activitylist[$linkurl->out(false)] = $modname;
950 $nummods = count($mods);
952 // If there is only one mod then do nothing.
953 if ($nummods == 1) {
954 return '';
957 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
958 $modids = array_keys($mods);
960 // Get the position in the array of the course module we are viewing.
961 $position = array_search($this->page->cm->id, $modids);
963 $prevmod = null;
964 $nextmod = null;
966 // Check if we have a previous mod to show.
967 if ($position > 0) {
968 $prevmod = $mods[$modids[$position - 1]];
971 // Check if we have a next mod to show.
972 if ($position < ($nummods - 1)) {
973 $nextmod = $mods[$modids[$position + 1]];
976 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
977 $renderer = $this->page->get_renderer('core', 'course');
978 return $renderer->render($activitynav);
982 * The standard tags (typically script tags that are not needed earlier) that
983 * should be output after everything else. Designed to be called in theme layout.php files.
985 * @return string HTML fragment.
987 public function standard_end_of_body_html() {
988 global $CFG;
990 // This function is normally called from a layout.php file in {@link core_renderer::header()}
991 // but some of the content won't be known until later, so we return a placeholder
992 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
993 $output = '';
994 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
995 $output .= "\n".$CFG->additionalhtmlfooter;
997 $output .= $this->unique_end_html_token;
998 return $output;
1002 * The standard HTML that should be output just before the <footer> tag.
1003 * Designed to be called in theme layout.php files.
1005 * @return string HTML fragment.
1007 public function standard_after_main_region_html() {
1008 global $CFG;
1009 $output = '';
1010 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlbottomofbody)) {
1011 $output .= "\n".$CFG->additionalhtmlbottomofbody;
1014 // Give subsystems an opportunity to inject extra html content. The callback
1015 // must always return a string containing valid html.
1016 foreach (\core_component::get_core_subsystems() as $name => $path) {
1017 if ($path) {
1018 $output .= component_callback($name, 'standard_after_main_region_html', [], '');
1022 // Give plugins an opportunity to inject extra html content. The callback
1023 // must always return a string containing valid html.
1024 $pluginswithfunction = get_plugins_with_function('standard_after_main_region_html', 'lib.php');
1025 foreach ($pluginswithfunction as $plugins) {
1026 foreach ($plugins as $function) {
1027 $output .= $function();
1031 return $output;
1035 * Return the standard string that says whether you are logged in (and switched
1036 * roles/logged in as another user).
1037 * @param bool $withlinks if false, then don't include any links in the HTML produced.
1038 * If not set, the default is the nologinlinks option from the theme config.php file,
1039 * and if that is not set, then links are included.
1040 * @return string HTML fragment.
1042 public function login_info($withlinks = null) {
1043 global $USER, $CFG, $DB, $SESSION;
1045 if (during_initial_install()) {
1046 return '';
1049 if (is_null($withlinks)) {
1050 $withlinks = empty($this->page->layout_options['nologinlinks']);
1053 $course = $this->page->course;
1054 if (\core\session\manager::is_loggedinas()) {
1055 $realuser = \core\session\manager::get_realuser();
1056 $fullname = fullname($realuser);
1057 if ($withlinks) {
1058 $loginastitle = get_string('loginas');
1059 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
1060 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
1061 } else {
1062 $realuserinfo = " [$fullname] ";
1064 } else {
1065 $realuserinfo = '';
1068 $loginpage = $this->is_login_page();
1069 $loginurl = get_login_url();
1071 if (empty($course->id)) {
1072 // $course->id is not defined during installation
1073 return '';
1074 } else if (isloggedin()) {
1075 $context = context_course::instance($course->id);
1077 $fullname = fullname($USER);
1078 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
1079 if ($withlinks) {
1080 $linktitle = get_string('viewprofile');
1081 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
1082 } else {
1083 $username = $fullname;
1085 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
1086 if ($withlinks) {
1087 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1088 } else {
1089 $username .= " from {$idprovider->name}";
1092 if (isguestuser()) {
1093 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1094 if (!$loginpage && $withlinks) {
1095 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1097 } else if (is_role_switched($course->id)) { // Has switched roles
1098 $rolename = '';
1099 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1100 $rolename = ': '.role_get_name($role, $context);
1102 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1103 if ($withlinks) {
1104 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1105 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1107 } else {
1108 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1109 if ($withlinks) {
1110 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1113 } else {
1114 $loggedinas = get_string('loggedinnot', 'moodle');
1115 if (!$loginpage && $withlinks) {
1116 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1120 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1122 if (isset($SESSION->justloggedin)) {
1123 unset($SESSION->justloggedin);
1124 if (!empty($CFG->displayloginfailures)) {
1125 if (!isguestuser()) {
1126 // Include this file only when required.
1127 require_once($CFG->dirroot . '/user/lib.php');
1128 if ($count = user_count_login_failures($USER)) {
1129 $loggedinas .= '<div class="loginfailures">';
1130 $a = new stdClass();
1131 $a->attempts = $count;
1132 $loggedinas .= get_string('failedloginattempts', '', $a);
1133 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1134 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1135 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1137 $loggedinas .= '</div>';
1143 return $loggedinas;
1147 * Check whether the current page is a login page.
1149 * @since Moodle 2.9
1150 * @return bool
1152 protected function is_login_page() {
1153 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1154 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1155 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1156 return in_array(
1157 $this->page->url->out_as_local_url(false, array()),
1158 array(
1159 '/login/index.php',
1160 '/login/forgot_password.php',
1166 * Return the 'back' link that normally appears in the footer.
1168 * @return string HTML fragment.
1170 public function home_link() {
1171 global $CFG, $SITE;
1173 if ($this->page->pagetype == 'site-index') {
1174 // Special case for site home page - please do not remove
1175 return '<div class="sitelink">' .
1176 '<a title="Moodle" class="d-inline-block aalink" href="http://moodle.org/">' .
1177 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1179 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1180 // Special case for during install/upgrade.
1181 return '<div class="sitelink">'.
1182 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1183 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1185 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1186 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1187 get_string('home') . '</a></div>';
1189 } else {
1190 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1191 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1196 * Redirects the user by any means possible given the current state
1198 * This function should not be called directly, it should always be called using
1199 * the redirect function in lib/weblib.php
1201 * The redirect function should really only be called before page output has started
1202 * however it will allow itself to be called during the state STATE_IN_BODY
1204 * @param string $encodedurl The URL to send to encoded if required
1205 * @param string $message The message to display to the user if any
1206 * @param int $delay The delay before redirecting a user, if $message has been
1207 * set this is a requirement and defaults to 3, set to 0 no delay
1208 * @param boolean $debugdisableredirect this redirect has been disabled for
1209 * debugging purposes. Display a message that explains, and don't
1210 * trigger the redirect.
1211 * @param string $messagetype The type of notification to show the message in.
1212 * See constants on \core\output\notification.
1213 * @return string The HTML to display to the user before dying, may contain
1214 * meta refresh, javascript refresh, and may have set header redirects
1216 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1217 $messagetype = \core\output\notification::NOTIFY_INFO) {
1218 global $CFG;
1219 $url = str_replace('&amp;', '&', $encodedurl);
1221 switch ($this->page->state) {
1222 case moodle_page::STATE_BEFORE_HEADER :
1223 // No output yet it is safe to delivery the full arsenal of redirect methods
1224 if (!$debugdisableredirect) {
1225 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1226 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1227 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1229 $output = $this->header();
1230 break;
1231 case moodle_page::STATE_PRINTING_HEADER :
1232 // We should hopefully never get here
1233 throw new coding_exception('You cannot redirect while printing the page header');
1234 break;
1235 case moodle_page::STATE_IN_BODY :
1236 // We really shouldn't be here but we can deal with this
1237 debugging("You should really redirect before you start page output");
1238 if (!$debugdisableredirect) {
1239 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1241 $output = $this->opencontainers->pop_all_but_last();
1242 break;
1243 case moodle_page::STATE_DONE :
1244 // Too late to be calling redirect now
1245 throw new coding_exception('You cannot redirect after the entire page has been generated');
1246 break;
1248 $output .= $this->notification($message, $messagetype);
1249 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1250 if ($debugdisableredirect) {
1251 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1253 $output .= $this->footer();
1254 return $output;
1258 * Start output by sending the HTTP headers, and printing the HTML <head>
1259 * and the start of the <body>.
1261 * To control what is printed, you should set properties on $PAGE.
1263 * @return string HTML that you must output this, preferably immediately.
1265 public function header() {
1266 global $USER, $CFG, $SESSION;
1268 // Give plugins an opportunity touch things before the http headers are sent
1269 // such as adding additional headers. The return value is ignored.
1270 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1271 foreach ($pluginswithfunction as $plugins) {
1272 foreach ($plugins as $function) {
1273 $function();
1277 if (\core\session\manager::is_loggedinas()) {
1278 $this->page->add_body_class('userloggedinas');
1281 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1282 require_once($CFG->dirroot . '/user/lib.php');
1283 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1284 if ($count = user_count_login_failures($USER, false)) {
1285 $this->page->add_body_class('loginfailures');
1289 // If the user is logged in, and we're not in initial install,
1290 // check to see if the user is role-switched and add the appropriate
1291 // CSS class to the body element.
1292 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1293 $this->page->add_body_class('userswitchedrole');
1296 // Give themes a chance to init/alter the page object.
1297 $this->page->theme->init_page($this->page);
1299 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1301 // Find the appropriate page layout file, based on $this->page->pagelayout.
1302 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1303 // Render the layout using the layout file.
1304 $rendered = $this->render_page_layout($layoutfile);
1306 // Slice the rendered output into header and footer.
1307 $cutpos = strpos($rendered, $this->unique_main_content_token);
1308 if ($cutpos === false) {
1309 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1310 $token = self::MAIN_CONTENT_TOKEN;
1311 } else {
1312 $token = $this->unique_main_content_token;
1315 if ($cutpos === false) {
1316 throw new coding_exception('page layout file ' . $layoutfile . ' does not contain the main content placeholder, please include "<?php echo $OUTPUT->main_content() ?>" in theme layout file.');
1318 $header = substr($rendered, 0, $cutpos);
1319 $footer = substr($rendered, $cutpos + strlen($token));
1321 if (empty($this->contenttype)) {
1322 debugging('The page layout file did not call $OUTPUT->doctype()');
1323 $header = $this->doctype() . $header;
1326 // If this theme version is below 2.4 release and this is a course view page
1327 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1328 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1329 // check if course content header/footer have not been output during render of theme layout
1330 $coursecontentheader = $this->course_content_header(true);
1331 $coursecontentfooter = $this->course_content_footer(true);
1332 if (!empty($coursecontentheader)) {
1333 // display debug message and add header and footer right above and below main content
1334 // Please note that course header and footer (to be displayed above and below the whole page)
1335 // are not displayed in this case at all.
1336 // Besides the content header and footer are not displayed on any other course page
1337 debugging('The current theme is not optimised for 2.4, the course-specific header and footer defined in course format will not be output', DEBUG_DEVELOPER);
1338 $header .= $coursecontentheader;
1339 $footer = $coursecontentfooter. $footer;
1343 send_headers($this->contenttype, $this->page->cacheable);
1345 $this->opencontainers->push('header/footer', $footer);
1346 $this->page->set_state(moodle_page::STATE_IN_BODY);
1348 return $header . $this->skip_link_target('maincontent');
1352 * Renders and outputs the page layout file.
1354 * This is done by preparing the normal globals available to a script, and
1355 * then including the layout file provided by the current theme for the
1356 * requested layout.
1358 * @param string $layoutfile The name of the layout file
1359 * @return string HTML code
1361 protected function render_page_layout($layoutfile) {
1362 global $CFG, $SITE, $USER;
1363 // The next lines are a bit tricky. The point is, here we are in a method
1364 // of a renderer class, and this object may, or may not, be the same as
1365 // the global $OUTPUT object. When rendering the page layout file, we want to use
1366 // this object. However, people writing Moodle code expect the current
1367 // renderer to be called $OUTPUT, not $this, so define a variable called
1368 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1369 $OUTPUT = $this;
1370 $PAGE = $this->page;
1371 $COURSE = $this->page->course;
1373 ob_start();
1374 include($layoutfile);
1375 $rendered = ob_get_contents();
1376 ob_end_clean();
1377 return $rendered;
1381 * Outputs the page's footer
1383 * @return string HTML fragment
1385 public function footer() {
1386 global $CFG, $DB;
1388 $output = '';
1390 // Give plugins an opportunity to touch the page before JS is finalized.
1391 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1392 foreach ($pluginswithfunction as $plugins) {
1393 foreach ($plugins as $function) {
1394 $extrafooter = $function();
1395 if (is_string($extrafooter)) {
1396 $output .= $extrafooter;
1401 $output .= $this->container_end_all(true);
1403 $footer = $this->opencontainers->pop('header/footer');
1405 if (debugging() and $DB and $DB->is_transaction_started()) {
1406 // TODO: MDL-20625 print warning - transaction will be rolled back
1409 // Provide some performance info if required
1410 $performanceinfo = '';
1411 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1412 $perf = get_performance_info();
1413 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1414 $performanceinfo = $perf['html'];
1418 // We always want performance data when running a performance test, even if the user is redirected to another page.
1419 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1420 $footer = $this->unique_performance_info_token . $footer;
1422 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1424 // Only show notifications when the current page has a context id.
1425 if (!empty($this->page->context->id)) {
1426 $this->page->requires->js_call_amd('core/notification', 'init', array(
1427 $this->page->context->id,
1428 \core\notification::fetch_as_array($this),
1429 isloggedin()
1432 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1434 $this->page->set_state(moodle_page::STATE_DONE);
1436 return $output . $footer;
1440 * Close all but the last open container. This is useful in places like error
1441 * handling, where you want to close all the open containers (apart from <body>)
1442 * before outputting the error message.
1444 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1445 * developer debug warning if it isn't.
1446 * @return string the HTML required to close any open containers inside <body>.
1448 public function container_end_all($shouldbenone = false) {
1449 return $this->opencontainers->pop_all_but_last($shouldbenone);
1453 * Returns course-specific information to be output immediately above content on any course page
1454 * (for the current course)
1456 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1457 * @return string
1459 public function course_content_header($onlyifnotcalledbefore = false) {
1460 global $CFG;
1461 static $functioncalled = false;
1462 if ($functioncalled && $onlyifnotcalledbefore) {
1463 // we have already output the content header
1464 return '';
1467 // Output any session notification.
1468 $notifications = \core\notification::fetch();
1470 $bodynotifications = '';
1471 foreach ($notifications as $notification) {
1472 $bodynotifications .= $this->render_from_template(
1473 $notification->get_template_name(),
1474 $notification->export_for_template($this)
1478 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1480 if ($this->page->course->id == SITEID) {
1481 // return immediately and do not include /course/lib.php if not necessary
1482 return $output;
1485 require_once($CFG->dirroot.'/course/lib.php');
1486 $functioncalled = true;
1487 $courseformat = course_get_format($this->page->course);
1488 if (($obj = $courseformat->course_content_header()) !== null) {
1489 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1491 return $output;
1495 * Returns course-specific information to be output immediately below content on any course page
1496 * (for the current course)
1498 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1499 * @return string
1501 public function course_content_footer($onlyifnotcalledbefore = false) {
1502 global $CFG;
1503 if ($this->page->course->id == SITEID) {
1504 // return immediately and do not include /course/lib.php if not necessary
1505 return '';
1507 static $functioncalled = false;
1508 if ($functioncalled && $onlyifnotcalledbefore) {
1509 // we have already output the content footer
1510 return '';
1512 $functioncalled = true;
1513 require_once($CFG->dirroot.'/course/lib.php');
1514 $courseformat = course_get_format($this->page->course);
1515 if (($obj = $courseformat->course_content_footer()) !== null) {
1516 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1518 return '';
1522 * Returns course-specific information to be output on any course page in the header area
1523 * (for the current course)
1525 * @return string
1527 public function course_header() {
1528 global $CFG;
1529 if ($this->page->course->id == SITEID) {
1530 // return immediately and do not include /course/lib.php if not necessary
1531 return '';
1533 require_once($CFG->dirroot.'/course/lib.php');
1534 $courseformat = course_get_format($this->page->course);
1535 if (($obj = $courseformat->course_header()) !== null) {
1536 return $courseformat->get_renderer($this->page)->render($obj);
1538 return '';
1542 * Returns course-specific information to be output on any course page in the footer area
1543 * (for the current course)
1545 * @return string
1547 public function course_footer() {
1548 global $CFG;
1549 if ($this->page->course->id == SITEID) {
1550 // return immediately and do not include /course/lib.php if not necessary
1551 return '';
1553 require_once($CFG->dirroot.'/course/lib.php');
1554 $courseformat = course_get_format($this->page->course);
1555 if (($obj = $courseformat->course_footer()) !== null) {
1556 return $courseformat->get_renderer($this->page)->render($obj);
1558 return '';
1562 * Get the course pattern datauri to show on a course card.
1564 * The datauri is an encoded svg that can be passed as a url.
1565 * @param int $id Id to use when generating the pattern
1566 * @return string datauri
1568 public function get_generated_image_for_id($id) {
1569 $color = $this->get_generated_color_for_id($id);
1570 $pattern = new \core_geopattern();
1571 $pattern->setColor($color);
1572 $pattern->patternbyid($id);
1573 return $pattern->datauri();
1577 * Get the course color to show on a course card.
1579 * @param int $id Id to use when generating the color.
1580 * @return string hex color code.
1582 public function get_generated_color_for_id($id) {
1583 $colornumbers = range(1, 10);
1584 $basecolors = [];
1585 foreach ($colornumbers as $number) {
1586 $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1589 $color = $basecolors[$id % 10];
1590 return $color;
1594 * Returns lang menu or '', this method also checks forcing of languages in courses.
1596 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1598 * @return string The lang menu HTML or empty string
1600 public function lang_menu() {
1601 global $CFG;
1603 if (empty($CFG->langmenu)) {
1604 return '';
1607 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1608 // do not show lang menu if language forced
1609 return '';
1612 $currlang = current_language();
1613 $langs = get_string_manager()->get_list_of_translations();
1615 if (count($langs) < 2) {
1616 return '';
1619 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1620 $s->label = get_accesshide(get_string('language'));
1621 $s->class = 'langmenu';
1622 return $this->render($s);
1626 * Output the row of editing icons for a block, as defined by the controls array.
1628 * @param array $controls an array like {@link block_contents::$controls}.
1629 * @param string $blockid The ID given to the block.
1630 * @return string HTML fragment.
1632 public function block_controls($actions, $blockid = null) {
1633 global $CFG;
1634 if (empty($actions)) {
1635 return '';
1637 $menu = new action_menu($actions);
1638 if ($blockid !== null) {
1639 $menu->set_owner_selector('#'.$blockid);
1641 $menu->set_constraint('.block-region');
1642 $menu->attributes['class'] .= ' block-control-actions commands';
1643 return $this->render($menu);
1647 * Returns the HTML for a basic textarea field.
1649 * @param string $name Name to use for the textarea element
1650 * @param string $id The id to use fort he textarea element
1651 * @param string $value Initial content to display in the textarea
1652 * @param int $rows Number of rows to display
1653 * @param int $cols Number of columns to display
1654 * @return string the HTML to display
1656 public function print_textarea($name, $id, $value, $rows, $cols) {
1657 editors_head_setup();
1658 $editor = editors_get_preferred_editor(FORMAT_HTML);
1659 $editor->set_text($value);
1660 $editor->use_editor($id, []);
1662 $context = [
1663 'id' => $id,
1664 'name' => $name,
1665 'value' => $value,
1666 'rows' => $rows,
1667 'cols' => $cols
1670 return $this->render_from_template('core_form/editor_textarea', $context);
1674 * Renders an action menu component.
1676 * @param action_menu $menu
1677 * @return string HTML
1679 public function render_action_menu(action_menu $menu) {
1681 // We don't want the class icon there!
1682 foreach ($menu->get_secondary_actions() as $action) {
1683 if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1684 $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1688 if ($menu->is_empty()) {
1689 return '';
1691 $context = $menu->export_for_template($this);
1693 return $this->render_from_template('core/action_menu', $context);
1697 * Renders a Check API result
1699 * @param result $result
1700 * @return string HTML fragment
1702 protected function render_check_result(core\check\result $result) {
1703 return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1707 * Renders a Check API result
1709 * @param result $result
1710 * @return string HTML fragment
1712 public function check_result(core\check\result $result) {
1713 return $this->render_check_result($result);
1717 * Renders an action_menu_link item.
1719 * @param action_menu_link $action
1720 * @return string HTML fragment
1722 protected function render_action_menu_link(action_menu_link $action) {
1723 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1727 * Renders a primary action_menu_filler item.
1729 * @param action_menu_link_filler $action
1730 * @return string HTML fragment
1732 protected function render_action_menu_filler(action_menu_filler $action) {
1733 return html_writer::span('&nbsp;', 'filler');
1737 * Renders a primary action_menu_link item.
1739 * @param action_menu_link_primary $action
1740 * @return string HTML fragment
1742 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1743 return $this->render_action_menu_link($action);
1747 * Renders a secondary action_menu_link item.
1749 * @param action_menu_link_secondary $action
1750 * @return string HTML fragment
1752 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1753 return $this->render_action_menu_link($action);
1757 * Prints a nice side block with an optional header.
1759 * @param block_contents $bc HTML for the content
1760 * @param string $region the region the block is appearing in.
1761 * @return string the HTML to be output.
1763 public function block(block_contents $bc, $region) {
1764 $bc = clone($bc); // Avoid messing up the object passed in.
1765 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1766 $bc->collapsible = block_contents::NOT_HIDEABLE;
1769 $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1770 $context = new stdClass();
1771 $context->skipid = $bc->skipid;
1772 $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
1773 $context->dockable = $bc->dockable;
1774 $context->id = $id;
1775 $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1776 $context->skiptitle = strip_tags($bc->title);
1777 $context->showskiplink = !empty($context->skiptitle);
1778 $context->arialabel = $bc->arialabel;
1779 $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
1780 $context->class = $bc->attributes['class'];
1781 $context->type = $bc->attributes['data-block'];
1782 $context->title = $bc->title;
1783 $context->content = $bc->content;
1784 $context->annotation = $bc->annotation;
1785 $context->footer = $bc->footer;
1786 $context->hascontrols = !empty($bc->controls);
1787 if ($context->hascontrols) {
1788 $context->controls = $this->block_controls($bc->controls, $id);
1791 return $this->render_from_template('core/block', $context);
1795 * Render the contents of a block_list.
1797 * @param array $icons the icon for each item.
1798 * @param array $items the content of each item.
1799 * @return string HTML
1801 public function list_block_contents($icons, $items) {
1802 $row = 0;
1803 $lis = array();
1804 foreach ($items as $key => $string) {
1805 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1806 if (!empty($icons[$key])) { //test if the content has an assigned icon
1807 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1809 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1810 $item .= html_writer::end_tag('li');
1811 $lis[] = $item;
1812 $row = 1 - $row; // Flip even/odd.
1814 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1818 * Output all the blocks in a particular region.
1820 * @param string $region the name of a region on this page.
1821 * @return string the HTML to be output.
1823 public function blocks_for_region($region) {
1824 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1825 $lastblock = null;
1826 $zones = array();
1827 foreach ($blockcontents as $bc) {
1828 if ($bc instanceof block_contents) {
1829 $zones[] = $bc->title;
1832 $output = '';
1834 foreach ($blockcontents as $bc) {
1835 if ($bc instanceof block_contents) {
1836 $output .= $this->block($bc, $region);
1837 $lastblock = $bc->title;
1838 } else if ($bc instanceof block_move_target) {
1839 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1840 } else {
1841 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1844 return $output;
1848 * Output a place where the block that is currently being moved can be dropped.
1850 * @param block_move_target $target with the necessary details.
1851 * @param array $zones array of areas where the block can be moved to
1852 * @param string $previous the block located before the area currently being rendered.
1853 * @param string $region the name of the region
1854 * @return string the HTML to be output.
1856 public function block_move_target($target, $zones, $previous, $region) {
1857 if ($previous == null) {
1858 if (empty($zones)) {
1859 // There are no zones, probably because there are no blocks.
1860 $regions = $this->page->theme->get_all_block_regions();
1861 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1862 } else {
1863 $position = get_string('moveblockbefore', 'block', $zones[0]);
1865 } else {
1866 $position = get_string('moveblockafter', 'block', $previous);
1868 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1872 * Renders a special html link with attached action
1874 * Theme developers: DO NOT OVERRIDE! Please override function
1875 * {@link core_renderer::render_action_link()} instead.
1877 * @param string|moodle_url $url
1878 * @param string $text HTML fragment
1879 * @param component_action $action
1880 * @param array $attributes associative array of html link attributes + disabled
1881 * @param pix_icon optional pix icon to render with the link
1882 * @return string HTML fragment
1884 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1885 if (!($url instanceof moodle_url)) {
1886 $url = new moodle_url($url);
1888 $link = new action_link($url, $text, $action, $attributes, $icon);
1890 return $this->render($link);
1894 * Renders an action_link object.
1896 * The provided link is renderer and the HTML returned. At the same time the
1897 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1899 * @param action_link $link
1900 * @return string HTML fragment
1902 protected function render_action_link(action_link $link) {
1903 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1907 * Renders an action_icon.
1909 * This function uses the {@link core_renderer::action_link()} method for the
1910 * most part. What it does different is prepare the icon as HTML and use it
1911 * as the link text.
1913 * Theme developers: If you want to change how action links and/or icons are rendered,
1914 * consider overriding function {@link core_renderer::render_action_link()} and
1915 * {@link core_renderer::render_pix_icon()}.
1917 * @param string|moodle_url $url A string URL or moodel_url
1918 * @param pix_icon $pixicon
1919 * @param component_action $action
1920 * @param array $attributes associative array of html link attributes + disabled
1921 * @param bool $linktext show title next to image in link
1922 * @return string HTML fragment
1924 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1925 if (!($url instanceof moodle_url)) {
1926 $url = new moodle_url($url);
1928 $attributes = (array)$attributes;
1930 if (empty($attributes['class'])) {
1931 // let ppl override the class via $options
1932 $attributes['class'] = 'action-icon';
1935 $icon = $this->render($pixicon);
1937 if ($linktext) {
1938 $text = $pixicon->attributes['alt'];
1939 } else {
1940 $text = '';
1943 return $this->action_link($url, $text.$icon, $action, $attributes);
1947 * Print a message along with button choices for Continue/Cancel
1949 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1951 * @param string $message The question to ask the user
1952 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1953 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1954 * @return string HTML fragment
1956 public function confirm($message, $continue, $cancel) {
1957 if ($continue instanceof single_button) {
1958 // ok
1959 $continue->primary = true;
1960 } else if (is_string($continue)) {
1961 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1962 } else if ($continue instanceof moodle_url) {
1963 $continue = new single_button($continue, get_string('continue'), 'post', true);
1964 } else {
1965 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1968 if ($cancel instanceof single_button) {
1969 // ok
1970 } else if (is_string($cancel)) {
1971 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1972 } else if ($cancel instanceof moodle_url) {
1973 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1974 } else {
1975 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1978 $attributes = [
1979 'role'=>'alertdialog',
1980 'aria-labelledby'=>'modal-header',
1981 'aria-describedby'=>'modal-body',
1982 'aria-modal'=>'true'
1985 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
1986 $output .= $this->box_start('modal-content', 'modal-content');
1987 $output .= $this->box_start('modal-header px-3', 'modal-header');
1988 $output .= html_writer::tag('h4', get_string('confirm'));
1989 $output .= $this->box_end();
1990 $attributes = [
1991 'role'=>'alert',
1992 'data-aria-autofocus'=>'true'
1994 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
1995 $output .= html_writer::tag('p', $message);
1996 $output .= $this->box_end();
1997 $output .= $this->box_start('modal-footer', 'modal-footer');
1998 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1999 $output .= $this->box_end();
2000 $output .= $this->box_end();
2001 $output .= $this->box_end();
2002 return $output;
2006 * Returns a form with a single button.
2008 * Theme developers: DO NOT OVERRIDE! Please override function
2009 * {@link core_renderer::render_single_button()} instead.
2011 * @param string|moodle_url $url
2012 * @param string $label button text
2013 * @param string $method get or post submit method
2014 * @param array $options associative array {disabled, title, etc.}
2015 * @return string HTML fragment
2017 public function single_button($url, $label, $method='post', array $options=null) {
2018 if (!($url instanceof moodle_url)) {
2019 $url = new moodle_url($url);
2021 $button = new single_button($url, $label, $method);
2023 foreach ((array)$options as $key=>$value) {
2024 if (property_exists($button, $key)) {
2025 $button->$key = $value;
2026 } else {
2027 $button->set_attribute($key, $value);
2031 return $this->render($button);
2035 * Renders a single button widget.
2037 * This will return HTML to display a form containing a single button.
2039 * @param single_button $button
2040 * @return string HTML fragment
2042 protected function render_single_button(single_button $button) {
2043 return $this->render_from_template('core/single_button', $button->export_for_template($this));
2047 * Returns a form with a single select widget.
2049 * Theme developers: DO NOT OVERRIDE! Please override function
2050 * {@link core_renderer::render_single_select()} instead.
2052 * @param moodle_url $url form action target, includes hidden fields
2053 * @param string $name name of selection field - the changing parameter in url
2054 * @param array $options list of options
2055 * @param string $selected selected element
2056 * @param array $nothing
2057 * @param string $formid
2058 * @param array $attributes other attributes for the single select
2059 * @return string HTML fragment
2061 public function single_select($url, $name, array $options, $selected = '',
2062 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2063 if (!($url instanceof moodle_url)) {
2064 $url = new moodle_url($url);
2066 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2068 if (array_key_exists('label', $attributes)) {
2069 $select->set_label($attributes['label']);
2070 unset($attributes['label']);
2072 $select->attributes = $attributes;
2074 return $this->render($select);
2078 * Returns a dataformat selection and download form
2080 * @param string $label A text label
2081 * @param moodle_url|string $base The download page url
2082 * @param string $name The query param which will hold the type of the download
2083 * @param array $params Extra params sent to the download page
2084 * @return string HTML fragment
2086 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2088 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2089 $options = array();
2090 foreach ($formats as $format) {
2091 if ($format->is_enabled()) {
2092 $options[] = array(
2093 'value' => $format->name,
2094 'label' => get_string('dataformat', $format->component),
2098 $hiddenparams = array();
2099 foreach ($params as $key => $value) {
2100 $hiddenparams[] = array(
2101 'name' => $key,
2102 'value' => $value,
2105 $data = array(
2106 'label' => $label,
2107 'base' => $base,
2108 'name' => $name,
2109 'params' => $hiddenparams,
2110 'options' => $options,
2111 'sesskey' => sesskey(),
2112 'submit' => get_string('download'),
2115 return $this->render_from_template('core/dataformat_selector', $data);
2120 * Internal implementation of single_select rendering
2122 * @param single_select $select
2123 * @return string HTML fragment
2125 protected function render_single_select(single_select $select) {
2126 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2130 * Returns a form with a url select widget.
2132 * Theme developers: DO NOT OVERRIDE! Please override function
2133 * {@link core_renderer::render_url_select()} instead.
2135 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2136 * @param string $selected selected element
2137 * @param array $nothing
2138 * @param string $formid
2139 * @return string HTML fragment
2141 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2142 $select = new url_select($urls, $selected, $nothing, $formid);
2143 return $this->render($select);
2147 * Internal implementation of url_select rendering
2149 * @param url_select $select
2150 * @return string HTML fragment
2152 protected function render_url_select(url_select $select) {
2153 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2157 * Returns a string containing a link to the user documentation.
2158 * Also contains an icon by default. Shown to teachers and admin only.
2160 * @param string $path The page link after doc root and language, no leading slash.
2161 * @param string $text The text to be displayed for the link
2162 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2163 * @param array $attributes htm attributes
2164 * @return string
2166 public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
2167 global $CFG;
2169 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2171 $attributes['href'] = new moodle_url(get_docs_url($path));
2172 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2173 $attributes['class'] = 'helplinkpopup';
2176 return html_writer::tag('a', $icon.$text, $attributes);
2180 * Return HTML for an image_icon.
2182 * Theme developers: DO NOT OVERRIDE! Please override function
2183 * {@link core_renderer::render_image_icon()} instead.
2185 * @param string $pix short pix name
2186 * @param string $alt mandatory alt attribute
2187 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2188 * @param array $attributes htm attributes
2189 * @return string HTML fragment
2191 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2192 $icon = new image_icon($pix, $alt, $component, $attributes);
2193 return $this->render($icon);
2197 * Renders a pix_icon widget and returns the HTML to display it.
2199 * @param image_icon $icon
2200 * @return string HTML fragment
2202 protected function render_image_icon(image_icon $icon) {
2203 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2204 return $system->render_pix_icon($this, $icon);
2208 * Return HTML for a pix_icon.
2210 * Theme developers: DO NOT OVERRIDE! Please override function
2211 * {@link core_renderer::render_pix_icon()} instead.
2213 * @param string $pix short pix name
2214 * @param string $alt mandatory alt attribute
2215 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2216 * @param array $attributes htm lattributes
2217 * @return string HTML fragment
2219 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2220 $icon = new pix_icon($pix, $alt, $component, $attributes);
2221 return $this->render($icon);
2225 * Renders a pix_icon widget and returns the HTML to display it.
2227 * @param pix_icon $icon
2228 * @return string HTML fragment
2230 protected function render_pix_icon(pix_icon $icon) {
2231 $system = \core\output\icon_system::instance();
2232 return $system->render_pix_icon($this, $icon);
2236 * Return HTML to display an emoticon icon.
2238 * @param pix_emoticon $emoticon
2239 * @return string HTML fragment
2241 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2242 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2243 return $system->render_pix_icon($this, $emoticon);
2247 * Produces the html that represents this rating in the UI
2249 * @param rating $rating the page object on which this rating will appear
2250 * @return string
2252 function render_rating(rating $rating) {
2253 global $CFG, $USER;
2255 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2256 return null;//ratings are turned off
2259 $ratingmanager = new rating_manager();
2260 // Initialise the JavaScript so ratings can be done by AJAX.
2261 $ratingmanager->initialise_rating_javascript($this->page);
2263 $strrate = get_string("rate", "rating");
2264 $ratinghtml = ''; //the string we'll return
2266 // permissions check - can they view the aggregate?
2267 if ($rating->user_can_view_aggregate()) {
2269 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2270 $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2271 $aggregatestr = $rating->get_aggregate_string();
2273 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2274 if ($rating->count > 0) {
2275 $countstr = "({$rating->count})";
2276 } else {
2277 $countstr = '-';
2279 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2281 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2283 $nonpopuplink = $rating->get_view_ratings_url();
2284 $popuplink = $rating->get_view_ratings_url(true);
2286 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2287 $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
2290 $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
2293 $formstart = null;
2294 // if the item doesn't belong to the current user, the user has permission to rate
2295 // and we're within the assessable period
2296 if ($rating->user_can_rate()) {
2298 $rateurl = $rating->get_rate_url();
2299 $inputs = $rateurl->params();
2301 //start the rating form
2302 $formattrs = array(
2303 'id' => "postrating{$rating->itemid}",
2304 'class' => 'postratingform',
2305 'method' => 'post',
2306 'action' => $rateurl->out_omit_querystring()
2308 $formstart = html_writer::start_tag('form', $formattrs);
2309 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2311 // add the hidden inputs
2312 foreach ($inputs as $name => $value) {
2313 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2314 $formstart .= html_writer::empty_tag('input', $attributes);
2317 if (empty($ratinghtml)) {
2318 $ratinghtml .= $strrate.': ';
2320 $ratinghtml = $formstart.$ratinghtml;
2322 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2323 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2324 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2325 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2327 //output submit button
2328 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2330 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2331 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2333 if (!$rating->settings->scale->isnumeric) {
2334 // If a global scale, try to find current course ID from the context
2335 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2336 $courseid = $coursecontext->instanceid;
2337 } else {
2338 $courseid = $rating->settings->scale->courseid;
2340 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2342 $ratinghtml .= html_writer::end_tag('span');
2343 $ratinghtml .= html_writer::end_tag('div');
2344 $ratinghtml .= html_writer::end_tag('form');
2347 return $ratinghtml;
2351 * Centered heading with attached help button (same title text)
2352 * and optional icon attached.
2354 * @param string $text A heading text
2355 * @param string $helpidentifier The keyword that defines a help page
2356 * @param string $component component name
2357 * @param string|moodle_url $icon
2358 * @param string $iconalt icon alt text
2359 * @param int $level The level of importance of the heading. Defaulting to 2
2360 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2361 * @return string HTML fragment
2363 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2364 $image = '';
2365 if ($icon) {
2366 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2369 $help = '';
2370 if ($helpidentifier) {
2371 $help = $this->help_icon($helpidentifier, $component);
2374 return $this->heading($image.$text.$help, $level, $classnames);
2378 * Returns HTML to display a help icon.
2380 * @deprecated since Moodle 2.0
2382 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2383 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2387 * Returns HTML to display a help icon.
2389 * Theme developers: DO NOT OVERRIDE! Please override function
2390 * {@link core_renderer::render_help_icon()} instead.
2392 * @param string $identifier The keyword that defines a help page
2393 * @param string $component component name
2394 * @param string|bool $linktext true means use $title as link text, string means link text value
2395 * @return string HTML fragment
2397 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2398 $icon = new help_icon($identifier, $component);
2399 $icon->diag_strings();
2400 if ($linktext === true) {
2401 $icon->linktext = get_string($icon->identifier, $icon->component);
2402 } else if (!empty($linktext)) {
2403 $icon->linktext = $linktext;
2405 return $this->render($icon);
2409 * Implementation of user image rendering.
2411 * @param help_icon $helpicon A help icon instance
2412 * @return string HTML fragment
2414 protected function render_help_icon(help_icon $helpicon) {
2415 $context = $helpicon->export_for_template($this);
2416 return $this->render_from_template('core/help_icon', $context);
2420 * Returns HTML to display a scale help icon.
2422 * @param int $courseid
2423 * @param stdClass $scale instance
2424 * @return string HTML fragment
2426 public function help_icon_scale($courseid, stdClass $scale) {
2427 global $CFG;
2429 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2431 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2433 $scaleid = abs($scale->id);
2435 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2436 $action = new popup_action('click', $link, 'ratingscale');
2438 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2442 * Creates and returns a spacer image with optional line break.
2444 * @param array $attributes Any HTML attributes to add to the spaced.
2445 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2446 * laxy do it with CSS which is a much better solution.
2447 * @return string HTML fragment
2449 public function spacer(array $attributes = null, $br = false) {
2450 $attributes = (array)$attributes;
2451 if (empty($attributes['width'])) {
2452 $attributes['width'] = 1;
2454 if (empty($attributes['height'])) {
2455 $attributes['height'] = 1;
2457 $attributes['class'] = 'spacer';
2459 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2461 if (!empty($br)) {
2462 $output .= '<br />';
2465 return $output;
2469 * Returns HTML to display the specified user's avatar.
2471 * User avatar may be obtained in two ways:
2472 * <pre>
2473 * // Option 1: (shortcut for simple cases, preferred way)
2474 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2475 * $OUTPUT->user_picture($user, array('popup'=>true));
2477 * // Option 2:
2478 * $userpic = new user_picture($user);
2479 * // Set properties of $userpic
2480 * $userpic->popup = true;
2481 * $OUTPUT->render($userpic);
2482 * </pre>
2484 * Theme developers: DO NOT OVERRIDE! Please override function
2485 * {@link core_renderer::render_user_picture()} instead.
2487 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2488 * If any of these are missing, the database is queried. Avoid this
2489 * if at all possible, particularly for reports. It is very bad for performance.
2490 * @param array $options associative array with user picture options, used only if not a user_picture object,
2491 * options are:
2492 * - courseid=$this->page->course->id (course id of user profile in link)
2493 * - size=35 (size of image)
2494 * - link=true (make image clickable - the link leads to user profile)
2495 * - popup=false (open in popup)
2496 * - alttext=true (add image alt attribute)
2497 * - class = image class attribute (default 'userpicture')
2498 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2499 * - includefullname=false (whether to include the user's full name together with the user picture)
2500 * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2501 * @return string HTML fragment
2503 public function user_picture(stdClass $user, array $options = null) {
2504 $userpicture = new user_picture($user);
2505 foreach ((array)$options as $key=>$value) {
2506 if (property_exists($userpicture, $key)) {
2507 $userpicture->$key = $value;
2510 return $this->render($userpicture);
2514 * Internal implementation of user image rendering.
2516 * @param user_picture $userpicture
2517 * @return string
2519 protected function render_user_picture(user_picture $userpicture) {
2520 global $CFG, $DB;
2522 $user = $userpicture->user;
2523 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
2525 if ($userpicture->alttext) {
2526 if (!empty($user->imagealt)) {
2527 $alt = $user->imagealt;
2528 } else {
2529 $alt = get_string('pictureof', '', fullname($user, $canviewfullnames));
2531 } else {
2532 $alt = '';
2535 if (empty($userpicture->size)) {
2536 $size = 35;
2537 } else if ($userpicture->size === true or $userpicture->size == 1) {
2538 $size = 100;
2539 } else {
2540 $size = $userpicture->size;
2543 $class = $userpicture->class;
2545 if ($user->picture == 0) {
2546 $class .= ' defaultuserpic';
2549 $src = $userpicture->get_url($this->page, $this);
2551 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2552 if (!$userpicture->visibletoscreenreaders) {
2553 $alt = '';
2554 $attributes['aria-hidden'] = 'true';
2557 if (!empty($alt)) {
2558 $attributes['alt'] = $alt;
2559 $attributes['title'] = $alt;
2562 // get the image html output fisrt
2563 $output = html_writer::empty_tag('img', $attributes);
2565 // Show fullname together with the picture when desired.
2566 if ($userpicture->includefullname) {
2567 $output .= fullname($userpicture->user, $canviewfullnames);
2570 // then wrap it in link if needed
2571 if (!$userpicture->link) {
2572 return $output;
2575 if (empty($userpicture->courseid)) {
2576 $courseid = $this->page->course->id;
2577 } else {
2578 $courseid = $userpicture->courseid;
2581 if ($courseid == SITEID) {
2582 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2583 } else {
2584 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2587 $attributes = array('href' => $url, 'class' => 'd-inline-block aabtn');
2588 if (!$userpicture->visibletoscreenreaders) {
2589 $attributes['tabindex'] = '-1';
2590 $attributes['aria-hidden'] = 'true';
2593 if ($userpicture->popup) {
2594 $id = html_writer::random_id('userpicture');
2595 $attributes['id'] = $id;
2596 $this->add_action_handler(new popup_action('click', $url), $id);
2599 return html_writer::tag('a', $output, $attributes);
2603 * Internal implementation of file tree viewer items rendering.
2605 * @param array $dir
2606 * @return string
2608 public function htmllize_file_tree($dir) {
2609 if (empty($dir['subdirs']) and empty($dir['files'])) {
2610 return '';
2612 $result = '<ul>';
2613 foreach ($dir['subdirs'] as $subdir) {
2614 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2616 foreach ($dir['files'] as $file) {
2617 $filename = $file->get_filename();
2618 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2620 $result .= '</ul>';
2622 return $result;
2626 * Returns HTML to display the file picker
2628 * <pre>
2629 * $OUTPUT->file_picker($options);
2630 * </pre>
2632 * Theme developers: DO NOT OVERRIDE! Please override function
2633 * {@link core_renderer::render_file_picker()} instead.
2635 * @param array $options associative array with file manager options
2636 * options are:
2637 * maxbytes=>-1,
2638 * itemid=>0,
2639 * client_id=>uniqid(),
2640 * acepted_types=>'*',
2641 * return_types=>FILE_INTERNAL,
2642 * context=>current page context
2643 * @return string HTML fragment
2645 public function file_picker($options) {
2646 $fp = new file_picker($options);
2647 return $this->render($fp);
2651 * Internal implementation of file picker rendering.
2653 * @param file_picker $fp
2654 * @return string
2656 public function render_file_picker(file_picker $fp) {
2657 $options = $fp->options;
2658 $client_id = $options->client_id;
2659 $strsaved = get_string('filesaved', 'repository');
2660 $straddfile = get_string('openpicker', 'repository');
2661 $strloading = get_string('loading', 'repository');
2662 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2663 $strdroptoupload = get_string('droptoupload', 'moodle');
2664 $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
2666 $currentfile = $options->currentfile;
2667 if (empty($currentfile)) {
2668 $currentfile = '';
2669 } else {
2670 $currentfile .= ' - ';
2672 if ($options->maxbytes) {
2673 $size = $options->maxbytes;
2674 } else {
2675 $size = get_max_upload_file_size();
2677 if ($size == -1) {
2678 $maxsize = '';
2679 } else {
2680 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2682 if ($options->buttonname) {
2683 $buttonname = ' name="' . $options->buttonname . '"';
2684 } else {
2685 $buttonname = '';
2687 $html = <<<EOD
2688 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2689 $iconprogress
2690 </div>
2691 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2692 <div>
2693 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2694 <span> $maxsize </span>
2695 </div>
2696 EOD;
2697 if ($options->env != 'url') {
2698 $html .= <<<EOD
2699 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2700 <div class="filepicker-filename">
2701 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2702 <div class="dndupload-progressbars"></div>
2703 </div>
2704 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2705 </div>
2706 EOD;
2708 $html .= '</div>';
2709 return $html;
2713 * @deprecated since Moodle 3.2
2715 public function update_module_button() {
2716 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2717 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2718 'Themes can choose to display the link in the buttons row consistently for all module types.');
2722 * Returns HTML to display a "Turn editing on/off" button in a form.
2724 * @param moodle_url $url The URL + params to send through when clicking the button
2725 * @return string HTML the button
2727 public function edit_button(moodle_url $url) {
2729 $url->param('sesskey', sesskey());
2730 if ($this->page->user_is_editing()) {
2731 $url->param('edit', 'off');
2732 $editstring = get_string('turneditingoff');
2733 } else {
2734 $url->param('edit', 'on');
2735 $editstring = get_string('turneditingon');
2738 return $this->single_button($url, $editstring);
2742 * Returns HTML to display a simple button to close a window
2744 * @param string $text The lang string for the button's label (already output from get_string())
2745 * @return string html fragment
2747 public function close_window_button($text='') {
2748 if (empty($text)) {
2749 $text = get_string('closewindow');
2751 $button = new single_button(new moodle_url('#'), $text, 'get');
2752 $button->add_action(new component_action('click', 'close_window'));
2754 return $this->container($this->render($button), 'closewindow');
2758 * Output an error message. By default wraps the error message in <span class="error">.
2759 * If the error message is blank, nothing is output.
2761 * @param string $message the error message.
2762 * @return string the HTML to output.
2764 public function error_text($message) {
2765 if (empty($message)) {
2766 return '';
2768 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2769 return html_writer::tag('span', $message, array('class' => 'error'));
2773 * Do not call this function directly.
2775 * To terminate the current script with a fatal error, call the {@link print_error}
2776 * function, or throw an exception. Doing either of those things will then call this
2777 * function to display the error, before terminating the execution.
2779 * @param string $message The message to output
2780 * @param string $moreinfourl URL where more info can be found about the error
2781 * @param string $link Link for the Continue button
2782 * @param array $backtrace The execution backtrace
2783 * @param string $debuginfo Debugging information
2784 * @return string the HTML to output.
2786 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2787 global $CFG;
2789 $output = '';
2790 $obbuffer = '';
2792 if ($this->has_started()) {
2793 // we can not always recover properly here, we have problems with output buffering,
2794 // html tables, etc.
2795 $output .= $this->opencontainers->pop_all_but_last();
2797 } else {
2798 // It is really bad if library code throws exception when output buffering is on,
2799 // because the buffered text would be printed before our start of page.
2800 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2801 error_reporting(0); // disable notices from gzip compression, etc.
2802 while (ob_get_level() > 0) {
2803 $buff = ob_get_clean();
2804 if ($buff === false) {
2805 break;
2807 $obbuffer .= $buff;
2809 error_reporting($CFG->debug);
2811 // Output not yet started.
2812 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2813 if (empty($_SERVER['HTTP_RANGE'])) {
2814 @header($protocol . ' 404 Not Found');
2815 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2816 // Coax iOS 10 into sending the session cookie.
2817 @header($protocol . ' 403 Forbidden');
2818 } else {
2819 // Must stop byteserving attempts somehow,
2820 // this is weird but Chrome PDF viewer can be stopped only with 407!
2821 @header($protocol . ' 407 Proxy Authentication Required');
2824 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2825 $this->page->set_url('/'); // no url
2826 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2827 $this->page->set_title(get_string('error'));
2828 $this->page->set_heading($this->page->course->fullname);
2829 $output .= $this->header();
2832 $message = '<p class="errormessage">' . s($message) . '</p>'.
2833 '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
2834 get_string('moreinformation') . '</a></p>';
2835 if (empty($CFG->rolesactive)) {
2836 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2837 //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.
2839 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2841 if ($CFG->debugdeveloper) {
2842 $labelsep = get_string('labelsep', 'langconfig');
2843 if (!empty($debuginfo)) {
2844 $debuginfo = s($debuginfo); // removes all nasty JS
2845 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2846 $label = get_string('debuginfo', 'debug') . $labelsep;
2847 $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
2849 if (!empty($backtrace)) {
2850 $label = get_string('stacktrace', 'debug') . $labelsep;
2851 $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
2853 if ($obbuffer !== '' ) {
2854 $label = get_string('outputbuffer', 'debug') . $labelsep;
2855 $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
2859 if (empty($CFG->rolesactive)) {
2860 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2861 } else if (!empty($link)) {
2862 $output .= $this->continue_button($link);
2865 $output .= $this->footer();
2867 // Padding to encourage IE to display our error page, rather than its own.
2868 $output .= str_repeat(' ', 512);
2870 return $output;
2874 * Output a notification (that is, a status message about something that has just happened).
2876 * Note: \core\notification::add() may be more suitable for your usage.
2878 * @param string $message The message to print out.
2879 * @param string $type The type of notification. See constants on \core\output\notification.
2880 * @return string the HTML to output.
2882 public function notification($message, $type = null) {
2883 $typemappings = [
2884 // Valid types.
2885 'success' => \core\output\notification::NOTIFY_SUCCESS,
2886 'info' => \core\output\notification::NOTIFY_INFO,
2887 'warning' => \core\output\notification::NOTIFY_WARNING,
2888 'error' => \core\output\notification::NOTIFY_ERROR,
2890 // Legacy types mapped to current types.
2891 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2892 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2893 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2894 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2895 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2896 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2897 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2900 $extraclasses = [];
2902 if ($type) {
2903 if (strpos($type, ' ') === false) {
2904 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2905 if (isset($typemappings[$type])) {
2906 $type = $typemappings[$type];
2907 } else {
2908 // The value provided did not match a known type. It must be an extra class.
2909 $extraclasses = [$type];
2911 } else {
2912 // Identify what type of notification this is.
2913 $classarray = explode(' ', self::prepare_classes($type));
2915 // Separate out the type of notification from the extra classes.
2916 foreach ($classarray as $class) {
2917 if (isset($typemappings[$class])) {
2918 $type = $typemappings[$class];
2919 } else {
2920 $extraclasses[] = $class;
2926 $notification = new \core\output\notification($message, $type);
2927 if (count($extraclasses)) {
2928 $notification->set_extra_classes($extraclasses);
2931 // Return the rendered template.
2932 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2936 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2938 public function notify_problem() {
2939 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
2940 'please use \core\notification::add(), or \core\output\notification as required.');
2944 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2946 public function notify_success() {
2947 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
2948 'please use \core\notification::add(), or \core\output\notification as required.');
2952 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2954 public function notify_message() {
2955 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
2956 'please use \core\notification::add(), or \core\output\notification as required.');
2960 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2962 public function notify_redirect() {
2963 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
2964 'please use \core\notification::add(), or \core\output\notification as required.');
2968 * Render a notification (that is, a status message about something that has
2969 * just happened).
2971 * @param \core\output\notification $notification the notification to print out
2972 * @return string the HTML to output.
2974 protected function render_notification(\core\output\notification $notification) {
2975 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2979 * Returns HTML to display a continue button that goes to a particular URL.
2981 * @param string|moodle_url $url The url the button goes to.
2982 * @return string the HTML to output.
2984 public function continue_button($url) {
2985 if (!($url instanceof moodle_url)) {
2986 $url = new moodle_url($url);
2988 $button = new single_button($url, get_string('continue'), 'get', true);
2989 $button->class = 'continuebutton';
2991 return $this->render($button);
2995 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2997 * Theme developers: DO NOT OVERRIDE! Please override function
2998 * {@link core_renderer::render_paging_bar()} instead.
3000 * @param int $totalcount The total number of entries available to be paged through
3001 * @param int $page The page you are currently viewing
3002 * @param int $perpage The number of entries that should be shown per page
3003 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3004 * @param string $pagevar name of page parameter that holds the page number
3005 * @return string the HTML to output.
3007 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3008 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3009 return $this->render($pb);
3013 * Returns HTML to display the paging bar.
3015 * @param paging_bar $pagingbar
3016 * @return string the HTML to output.
3018 protected function render_paging_bar(paging_bar $pagingbar) {
3019 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3020 $pagingbar->maxdisplay = 10;
3021 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3025 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3027 * @param string $current the currently selected letter.
3028 * @param string $class class name to add to this initial bar.
3029 * @param string $title the name to put in front of this initial bar.
3030 * @param string $urlvar URL parameter name for this initial.
3031 * @param string $url URL object.
3032 * @param array $alpha of letters in the alphabet.
3033 * @return string the HTML to output.
3035 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3036 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3037 return $this->render($ib);
3041 * Internal implementation of initials bar rendering.
3043 * @param initials_bar $initialsbar
3044 * @return string
3046 protected function render_initials_bar(initials_bar $initialsbar) {
3047 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3051 * Output the place a skip link goes to.
3053 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3054 * @return string the HTML to output.
3056 public function skip_link_target($id = null) {
3057 return html_writer::span('', '', array('id' => $id));
3061 * Outputs a heading
3063 * @param string $text The text of the heading
3064 * @param int $level The level of importance of the heading. Defaulting to 2
3065 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3066 * @param string $id An optional ID
3067 * @return string the HTML to output.
3069 public function heading($text, $level = 2, $classes = null, $id = null) {
3070 $level = (integer) $level;
3071 if ($level < 1 or $level > 6) {
3072 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3074 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3078 * Outputs a box.
3080 * @param string $contents The contents of the box
3081 * @param string $classes A space-separated list of CSS classes
3082 * @param string $id An optional ID
3083 * @param array $attributes An array of other attributes to give the box.
3084 * @return string the HTML to output.
3086 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3087 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3091 * Outputs the opening section of a box.
3093 * @param string $classes A space-separated list of CSS classes
3094 * @param string $id An optional ID
3095 * @param array $attributes An array of other attributes to give the box.
3096 * @return string the HTML to output.
3098 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3099 $this->opencontainers->push('box', html_writer::end_tag('div'));
3100 $attributes['id'] = $id;
3101 $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes);
3102 return html_writer::start_tag('div', $attributes);
3106 * Outputs the closing section of a box.
3108 * @return string the HTML to output.
3110 public function box_end() {
3111 return $this->opencontainers->pop('box');
3115 * Outputs a container.
3117 * @param string $contents The contents of the box
3118 * @param string $classes A space-separated list of CSS classes
3119 * @param string $id An optional ID
3120 * @return string the HTML to output.
3122 public function container($contents, $classes = null, $id = null) {
3123 return $this->container_start($classes, $id) . $contents . $this->container_end();
3127 * Outputs the opening section of a container.
3129 * @param string $classes A space-separated list of CSS classes
3130 * @param string $id An optional ID
3131 * @return string the HTML to output.
3133 public function container_start($classes = null, $id = null) {
3134 $this->opencontainers->push('container', html_writer::end_tag('div'));
3135 return html_writer::start_tag('div', array('id' => $id,
3136 'class' => renderer_base::prepare_classes($classes)));
3140 * Outputs the closing section of a container.
3142 * @return string the HTML to output.
3144 public function container_end() {
3145 return $this->opencontainers->pop('container');
3149 * Make nested HTML lists out of the items
3151 * The resulting list will look something like this:
3153 * <pre>
3154 * <<ul>>
3155 * <<li>><div class='tree_item parent'>(item contents)</div>
3156 * <<ul>
3157 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3158 * <</ul>>
3159 * <</li>>
3160 * <</ul>>
3161 * </pre>
3163 * @param array $items
3164 * @param array $attrs html attributes passed to the top ofs the list
3165 * @return string HTML
3167 public function tree_block_contents($items, $attrs = array()) {
3168 // exit if empty, we don't want an empty ul element
3169 if (empty($items)) {
3170 return '';
3172 // array of nested li elements
3173 $lis = array();
3174 foreach ($items as $item) {
3175 // this applies to the li item which contains all child lists too
3176 $content = $item->content($this);
3177 $liclasses = array($item->get_css_type());
3178 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3179 $liclasses[] = 'collapsed';
3181 if ($item->isactive === true) {
3182 $liclasses[] = 'current_branch';
3184 $liattr = array('class'=>join(' ',$liclasses));
3185 // class attribute on the div item which only contains the item content
3186 $divclasses = array('tree_item');
3187 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3188 $divclasses[] = 'branch';
3189 } else {
3190 $divclasses[] = 'leaf';
3192 if (!empty($item->classes) && count($item->classes)>0) {
3193 $divclasses[] = join(' ', $item->classes);
3195 $divattr = array('class'=>join(' ', $divclasses));
3196 if (!empty($item->id)) {
3197 $divattr['id'] = $item->id;
3199 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3200 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3201 $content = html_writer::empty_tag('hr') . $content;
3203 $content = html_writer::tag('li', $content, $liattr);
3204 $lis[] = $content;
3206 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3210 * Returns a search box.
3212 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3213 * @return string HTML with the search form hidden by default.
3215 public function search_box($id = false) {
3216 global $CFG;
3218 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3219 // result in an extra included file for each site, even the ones where global search
3220 // is disabled.
3221 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3222 return '';
3225 $data = [
3226 'action' => new moodle_url('/search/index.php'),
3227 'hiddenfields' => (object) ['name' => 'context', 'value' => $this->page->context->id],
3228 'inputname' => 'q',
3229 'searchstring' => get_string('search'),
3231 return $this->render_from_template('core/search_input_navbar', $data);
3235 * Allow plugins to provide some content to be rendered in the navbar.
3236 * The plugin must define a PLUGIN_render_navbar_output function that returns
3237 * the HTML they wish to add to the navbar.
3239 * @return string HTML for the navbar
3241 public function navbar_plugin_output() {
3242 $output = '';
3244 // Give subsystems an opportunity to inject extra html content. The callback
3245 // must always return a string containing valid html.
3246 foreach (\core_component::get_core_subsystems() as $name => $path) {
3247 if ($path) {
3248 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3252 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3253 foreach ($pluginsfunction as $plugintype => $plugins) {
3254 foreach ($plugins as $pluginfunction) {
3255 $output .= $pluginfunction($this);
3260 return $output;
3264 * Construct a user menu, returning HTML that can be echoed out by a
3265 * layout file.
3267 * @param stdClass $user A user object, usually $USER.
3268 * @param bool $withlinks true if a dropdown should be built.
3269 * @return string HTML fragment.
3271 public function user_menu($user = null, $withlinks = null) {
3272 global $USER, $CFG;
3273 require_once($CFG->dirroot . '/user/lib.php');
3275 if (is_null($user)) {
3276 $user = $USER;
3279 // Note: this behaviour is intended to match that of core_renderer::login_info,
3280 // but should not be considered to be good practice; layout options are
3281 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3282 if (is_null($withlinks)) {
3283 $withlinks = empty($this->page->layout_options['nologinlinks']);
3286 // Add a class for when $withlinks is false.
3287 $usermenuclasses = 'usermenu';
3288 if (!$withlinks) {
3289 $usermenuclasses .= ' withoutlinks';
3292 $returnstr = "";
3294 // If during initial install, return the empty return string.
3295 if (during_initial_install()) {
3296 return $returnstr;
3299 $loginpage = $this->is_login_page();
3300 $loginurl = get_login_url();
3301 // If not logged in, show the typical not-logged-in string.
3302 if (!isloggedin()) {
3303 $returnstr = get_string('loggedinnot', 'moodle');
3304 if (!$loginpage) {
3305 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3307 return html_writer::div(
3308 html_writer::span(
3309 $returnstr,
3310 'login'
3312 $usermenuclasses
3317 // If logged in as a guest user, show a string to that effect.
3318 if (isguestuser()) {
3319 $returnstr = get_string('loggedinasguest');
3320 if (!$loginpage && $withlinks) {
3321 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3324 return html_writer::div(
3325 html_writer::span(
3326 $returnstr,
3327 'login'
3329 $usermenuclasses
3333 // Get some navigation opts.
3334 $opts = user_get_user_navigation_info($user, $this->page);
3336 $avatarclasses = "avatars";
3337 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3338 $usertextcontents = $opts->metadata['userfullname'];
3340 // Other user.
3341 if (!empty($opts->metadata['asotheruser'])) {
3342 $avatarcontents .= html_writer::span(
3343 $opts->metadata['realuseravatar'],
3344 'avatar realuser'
3346 $usertextcontents = $opts->metadata['realuserfullname'];
3347 $usertextcontents .= html_writer::tag(
3348 'span',
3349 get_string(
3350 'loggedinas',
3351 'moodle',
3352 html_writer::span(
3353 $opts->metadata['userfullname'],
3354 'value'
3357 array('class' => 'meta viewingas')
3361 // Role.
3362 if (!empty($opts->metadata['asotherrole'])) {
3363 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3364 $usertextcontents .= html_writer::span(
3365 $opts->metadata['rolename'],
3366 'meta role role-' . $role
3370 // User login failures.
3371 if (!empty($opts->metadata['userloginfail'])) {
3372 $usertextcontents .= html_writer::span(
3373 $opts->metadata['userloginfail'],
3374 'meta loginfailures'
3378 // MNet.
3379 if (!empty($opts->metadata['asmnetuser'])) {
3380 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3381 $usertextcontents .= html_writer::span(
3382 $opts->metadata['mnetidprovidername'],
3383 'meta mnet mnet-' . $mnet
3387 $returnstr .= html_writer::span(
3388 html_writer::span($usertextcontents, 'usertext mr-1') .
3389 html_writer::span($avatarcontents, $avatarclasses),
3390 'userbutton'
3393 // Create a divider (well, a filler).
3394 $divider = new action_menu_filler();
3395 $divider->primary = false;
3397 $am = new action_menu();
3398 $am->set_menu_trigger(
3399 $returnstr
3401 $am->set_action_label(get_string('usermenu'));
3402 $am->set_alignment(action_menu::TR, action_menu::BR);
3403 $am->set_nowrap_on_items();
3404 if ($withlinks) {
3405 $navitemcount = count($opts->navitems);
3406 $idx = 0;
3407 foreach ($opts->navitems as $key => $value) {
3409 switch ($value->itemtype) {
3410 case 'divider':
3411 // If the nav item is a divider, add one and skip link processing.
3412 $am->add($divider);
3413 break;
3415 case 'invalid':
3416 // Silently skip invalid entries (should we post a notification?).
3417 break;
3419 case 'link':
3420 // Process this as a link item.
3421 $pix = null;
3422 if (isset($value->pix) && !empty($value->pix)) {
3423 $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
3424 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3425 $value->title = html_writer::img(
3426 $value->imgsrc,
3427 $value->title,
3428 array('class' => 'iconsmall')
3429 ) . $value->title;
3432 $al = new action_menu_link_secondary(
3433 $value->url,
3434 $pix,
3435 $value->title,
3436 array('class' => 'icon')
3438 if (!empty($value->titleidentifier)) {
3439 $al->attributes['data-title'] = $value->titleidentifier;
3441 $am->add($al);
3442 break;
3445 $idx++;
3447 // Add dividers after the first item and before the last item.
3448 if ($idx == 1 || $idx == $navitemcount - 1) {
3449 $am->add($divider);
3454 return html_writer::div(
3455 $this->render($am),
3456 $usermenuclasses
3461 * Secure layout login info.
3463 * @return string
3465 public function secure_layout_login_info() {
3466 if (get_config('core', 'logininfoinsecurelayout')) {
3467 return $this->login_info(false);
3468 } else {
3469 return '';
3474 * Returns the language menu in the secure layout.
3476 * No custom menu items are passed though, such that it will render only the language selection.
3478 * @return string
3480 public function secure_layout_language_menu() {
3481 if (get_config('core', 'langmenuinsecurelayout')) {
3482 $custommenu = new custom_menu('', current_language());
3483 return $this->render_custom_menu($custommenu);
3484 } else {
3485 return '';
3490 * This renders the navbar.
3491 * Uses bootstrap compatible html.
3493 public function navbar() {
3494 return $this->render_from_template('core/navbar', $this->page->navbar);
3498 * Renders a breadcrumb navigation node object.
3500 * @param breadcrumb_navigation_node $item The navigation node to render.
3501 * @return string HTML fragment
3503 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3505 if ($item->action instanceof moodle_url) {
3506 $content = $item->get_content();
3507 $title = $item->get_title();
3508 $attributes = array();
3509 $attributes['itemprop'] = 'url';
3510 if ($title !== '') {
3511 $attributes['title'] = $title;
3513 if ($item->hidden) {
3514 $attributes['class'] = 'dimmed_text';
3516 if ($item->is_last()) {
3517 $attributes['aria-current'] = 'page';
3519 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3520 $content = html_writer::link($item->action, $content, $attributes);
3522 $attributes = array();
3523 $attributes['itemscope'] = '';
3524 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3525 $content = html_writer::tag('span', $content, $attributes);
3527 } else {
3528 $content = $this->render_navigation_node($item);
3530 return $content;
3534 * Renders a navigation node object.
3536 * @param navigation_node $item The navigation node to render.
3537 * @return string HTML fragment
3539 protected function render_navigation_node(navigation_node $item) {
3540 $content = $item->get_content();
3541 $title = $item->get_title();
3542 if ($item->icon instanceof renderable && !$item->hideicon) {
3543 $icon = $this->render($item->icon);
3544 $content = $icon.$content; // use CSS for spacing of icons
3546 if ($item->helpbutton !== null) {
3547 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3549 if ($content === '') {
3550 return '';
3552 if ($item->action instanceof action_link) {
3553 $link = $item->action;
3554 if ($item->hidden) {
3555 $link->add_class('dimmed');
3557 if (!empty($content)) {
3558 // Providing there is content we will use that for the link content.
3559 $link->text = $content;
3561 $content = $this->render($link);
3562 } else if ($item->action instanceof moodle_url) {
3563 $attributes = array();
3564 if ($title !== '') {
3565 $attributes['title'] = $title;
3567 if ($item->hidden) {
3568 $attributes['class'] = 'dimmed_text';
3570 $content = html_writer::link($item->action, $content, $attributes);
3572 } else if (is_string($item->action) || empty($item->action)) {
3573 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3574 if ($title !== '') {
3575 $attributes['title'] = $title;
3577 if ($item->hidden) {
3578 $attributes['class'] = 'dimmed_text';
3580 $content = html_writer::tag('span', $content, $attributes);
3582 return $content;
3586 * Accessibility: Right arrow-like character is
3587 * used in the breadcrumb trail, course navigation menu
3588 * (previous/next activity), calendar, and search forum block.
3589 * If the theme does not set characters, appropriate defaults
3590 * are set automatically. Please DO NOT
3591 * use &lt; &gt; &raquo; - these are confusing for blind users.
3593 * @return string
3595 public function rarrow() {
3596 return $this->page->theme->rarrow;
3600 * Accessibility: Left arrow-like character is
3601 * used in the breadcrumb trail, course navigation menu
3602 * (previous/next activity), calendar, and search forum block.
3603 * If the theme does not set characters, appropriate defaults
3604 * are set automatically. Please DO NOT
3605 * use &lt; &gt; &raquo; - these are confusing for blind users.
3607 * @return string
3609 public function larrow() {
3610 return $this->page->theme->larrow;
3614 * Accessibility: Up arrow-like character is used in
3615 * the book heirarchical navigation.
3616 * If the theme does not set characters, appropriate defaults
3617 * are set automatically. Please DO NOT
3618 * use ^ - this is confusing for blind users.
3620 * @return string
3622 public function uarrow() {
3623 return $this->page->theme->uarrow;
3627 * Accessibility: Down arrow-like character.
3628 * If the theme does not set characters, appropriate defaults
3629 * are set automatically.
3631 * @return string
3633 public function darrow() {
3634 return $this->page->theme->darrow;
3638 * Returns the custom menu if one has been set
3640 * A custom menu can be configured by browsing to
3641 * Settings: Administration > Appearance > Themes > Theme settings
3642 * and then configuring the custommenu config setting as described.
3644 * Theme developers: DO NOT OVERRIDE! Please override function
3645 * {@link core_renderer::render_custom_menu()} instead.
3647 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3648 * @return string
3650 public function custom_menu($custommenuitems = '') {
3651 global $CFG;
3653 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3654 $custommenuitems = $CFG->custommenuitems;
3656 $custommenu = new custom_menu($custommenuitems, current_language());
3657 return $this->render_custom_menu($custommenu);
3661 * We want to show the custom menus as a list of links in the footer on small screens.
3662 * Just return the menu object exported so we can render it differently.
3664 public function custom_menu_flat() {
3665 global $CFG;
3666 $custommenuitems = '';
3668 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3669 $custommenuitems = $CFG->custommenuitems;
3671 $custommenu = new custom_menu($custommenuitems, current_language());
3672 $langs = get_string_manager()->get_list_of_translations();
3673 $haslangmenu = $this->lang_menu() != '';
3675 if ($haslangmenu) {
3676 $strlang = get_string('language');
3677 $currentlang = current_language();
3678 if (isset($langs[$currentlang])) {
3679 $currentlang = $langs[$currentlang];
3680 } else {
3681 $currentlang = $strlang;
3683 $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3684 foreach ($langs as $langtype => $langname) {
3685 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3689 return $custommenu->export_for_template($this);
3693 * Renders a custom menu object (located in outputcomponents.php)
3695 * The custom menu this method produces makes use of the YUI3 menunav widget
3696 * and requires very specific html elements and classes.
3698 * @staticvar int $menucount
3699 * @param custom_menu $menu
3700 * @return string
3702 protected function render_custom_menu(custom_menu $menu) {
3703 global $CFG;
3705 $langs = get_string_manager()->get_list_of_translations();
3706 $haslangmenu = $this->lang_menu() != '';
3708 if (!$menu->has_children() && !$haslangmenu) {
3709 return '';
3712 if ($haslangmenu) {
3713 $strlang = get_string('language');
3714 $currentlang = current_language();
3715 if (isset($langs[$currentlang])) {
3716 $currentlang = $langs[$currentlang];
3717 } else {
3718 $currentlang = $strlang;
3720 $this->language = $menu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3721 foreach ($langs as $langtype => $langname) {
3722 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3726 $content = '';
3727 foreach ($menu->get_children() as $item) {
3728 $context = $item->export_for_template($this);
3729 $content .= $this->render_from_template('core/custom_menu_item', $context);
3732 return $content;
3736 * Renders a custom menu node as part of a submenu
3738 * The custom menu this method produces makes use of the YUI3 menunav widget
3739 * and requires very specific html elements and classes.
3741 * @see core:renderer::render_custom_menu()
3743 * @staticvar int $submenucount
3744 * @param custom_menu_item $menunode
3745 * @return string
3747 protected function render_custom_menu_item(custom_menu_item $menunode) {
3748 // Required to ensure we get unique trackable id's
3749 static $submenucount = 0;
3750 if ($menunode->has_children()) {
3751 // If the child has menus render it as a sub menu
3752 $submenucount++;
3753 $content = html_writer::start_tag('li');
3754 if ($menunode->get_url() !== null) {
3755 $url = $menunode->get_url();
3756 } else {
3757 $url = '#cm_submenu_'.$submenucount;
3759 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3760 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3761 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3762 $content .= html_writer::start_tag('ul');
3763 foreach ($menunode->get_children() as $menunode) {
3764 $content .= $this->render_custom_menu_item($menunode);
3766 $content .= html_writer::end_tag('ul');
3767 $content .= html_writer::end_tag('div');
3768 $content .= html_writer::end_tag('div');
3769 $content .= html_writer::end_tag('li');
3770 } else {
3771 // The node doesn't have children so produce a final menuitem.
3772 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3773 $content = '';
3774 if (preg_match("/^#+$/", $menunode->get_text())) {
3776 // This is a divider.
3777 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3778 } else {
3779 $content = html_writer::start_tag(
3780 'li',
3781 array(
3782 'class' => 'yui3-menuitem'
3785 if ($menunode->get_url() !== null) {
3786 $url = $menunode->get_url();
3787 } else {
3788 $url = '#';
3790 $content .= html_writer::link(
3791 $url,
3792 $menunode->get_text(),
3793 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3796 $content .= html_writer::end_tag('li');
3798 // Return the sub menu
3799 return $content;
3803 * Renders theme links for switching between default and other themes.
3805 * @return string
3807 protected function theme_switch_links() {
3809 $actualdevice = core_useragent::get_device_type();
3810 $currentdevice = $this->page->devicetypeinuse;
3811 $switched = ($actualdevice != $currentdevice);
3813 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3814 // The user is using the a default device and hasn't switched so don't shown the switch
3815 // device links.
3816 return '';
3819 if ($switched) {
3820 $linktext = get_string('switchdevicerecommended');
3821 $devicetype = $actualdevice;
3822 } else {
3823 $linktext = get_string('switchdevicedefault');
3824 $devicetype = 'default';
3826 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3828 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3829 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3830 $content .= html_writer::end_tag('div');
3832 return $content;
3836 * Renders tabs
3838 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3840 * Theme developers: In order to change how tabs are displayed please override functions
3841 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3843 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3844 * @param string|null $selected which tab to mark as selected, all parent tabs will
3845 * automatically be marked as activated
3846 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3847 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3848 * @return string
3850 public final function tabtree($tabs, $selected = null, $inactive = null) {
3851 return $this->render(new tabtree($tabs, $selected, $inactive));
3855 * Renders tabtree
3857 * @param tabtree $tabtree
3858 * @return string
3860 protected function render_tabtree(tabtree $tabtree) {
3861 if (empty($tabtree->subtree)) {
3862 return '';
3864 $data = $tabtree->export_for_template($this);
3865 return $this->render_from_template('core/tabtree', $data);
3869 * Renders tabobject (part of tabtree)
3871 * This function is called from {@link core_renderer::render_tabtree()}
3872 * and also it calls itself when printing the $tabobject subtree recursively.
3874 * Property $tabobject->level indicates the number of row of tabs.
3876 * @param tabobject $tabobject
3877 * @return string HTML fragment
3879 protected function render_tabobject(tabobject $tabobject) {
3880 $str = '';
3882 // Print name of the current tab.
3883 if ($tabobject instanceof tabtree) {
3884 // No name for tabtree root.
3885 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3886 // Tab name without a link. The <a> tag is used for styling.
3887 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3888 } else {
3889 // Tab name with a link.
3890 if (!($tabobject->link instanceof moodle_url)) {
3891 // backward compartibility when link was passed as quoted string
3892 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3893 } else {
3894 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3898 if (empty($tabobject->subtree)) {
3899 if ($tabobject->selected) {
3900 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3902 return $str;
3905 // Print subtree.
3906 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
3907 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3908 $cnt = 0;
3909 foreach ($tabobject->subtree as $tab) {
3910 $liclass = '';
3911 if (!$cnt) {
3912 $liclass .= ' first';
3914 if ($cnt == count($tabobject->subtree) - 1) {
3915 $liclass .= ' last';
3917 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3918 $liclass .= ' onerow';
3921 if ($tab->selected) {
3922 $liclass .= ' here selected';
3923 } else if ($tab->activated) {
3924 $liclass .= ' here active';
3927 // This will recursively call function render_tabobject() for each item in subtree.
3928 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3929 $cnt++;
3931 $str .= html_writer::end_tag('ul');
3934 return $str;
3938 * Get the HTML for blocks in the given region.
3940 * @since Moodle 2.5.1 2.6
3941 * @param string $region The region to get HTML for.
3942 * @return string HTML.
3944 public function blocks($region, $classes = array(), $tag = 'aside') {
3945 $displayregion = $this->page->apply_theme_region_manipulations($region);
3946 $classes = (array)$classes;
3947 $classes[] = 'block-region';
3948 $attributes = array(
3949 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3950 'class' => join(' ', $classes),
3951 'data-blockregion' => $displayregion,
3952 'data-droptarget' => '1'
3954 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3955 $content = $this->blocks_for_region($displayregion);
3956 } else {
3957 $content = '';
3959 return html_writer::tag($tag, $content, $attributes);
3963 * Renders a custom block region.
3965 * Use this method if you want to add an additional block region to the content of the page.
3966 * Please note this should only be used in special situations.
3967 * We want to leave the theme is control where ever possible!
3969 * This method must use the same method that the theme uses within its layout file.
3970 * As such it asks the theme what method it is using.
3971 * It can be one of two values, blocks or blocks_for_region (deprecated).
3973 * @param string $regionname The name of the custom region to add.
3974 * @return string HTML for the block region.
3976 public function custom_block_region($regionname) {
3977 if ($this->page->theme->get_block_render_method() === 'blocks') {
3978 return $this->blocks($regionname);
3979 } else {
3980 return $this->blocks_for_region($regionname);
3985 * Returns the CSS classes to apply to the body tag.
3987 * @since Moodle 2.5.1 2.6
3988 * @param array $additionalclasses Any additional classes to apply.
3989 * @return string
3991 public function body_css_classes(array $additionalclasses = array()) {
3992 return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses);
3996 * The ID attribute to apply to the body tag.
3998 * @since Moodle 2.5.1 2.6
3999 * @return string
4001 public function body_id() {
4002 return $this->page->bodyid;
4006 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4008 * @since Moodle 2.5.1 2.6
4009 * @param string|array $additionalclasses Any additional classes to give the body tag,
4010 * @return string
4012 public function body_attributes($additionalclasses = array()) {
4013 if (!is_array($additionalclasses)) {
4014 $additionalclasses = explode(' ', $additionalclasses);
4016 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4020 * Gets HTML for the page heading.
4022 * @since Moodle 2.5.1 2.6
4023 * @param string $tag The tag to encase the heading in. h1 by default.
4024 * @return string HTML.
4026 public function page_heading($tag = 'h1') {
4027 return html_writer::tag($tag, $this->page->heading);
4031 * Gets the HTML for the page heading button.
4033 * @since Moodle 2.5.1 2.6
4034 * @return string HTML.
4036 public function page_heading_button() {
4037 return $this->page->button;
4041 * Returns the Moodle docs link to use for this page.
4043 * @since Moodle 2.5.1 2.6
4044 * @param string $text
4045 * @return string
4047 public function page_doc_link($text = null) {
4048 if ($text === null) {
4049 $text = get_string('moodledocslink');
4051 $path = page_get_doc_link_path($this->page);
4052 if (!$path) {
4053 return '';
4055 return $this->doc_link($path, $text);
4059 * Returns the page heading menu.
4061 * @since Moodle 2.5.1 2.6
4062 * @return string HTML.
4064 public function page_heading_menu() {
4065 return $this->page->headingmenu;
4069 * Returns the title to use on the page.
4071 * @since Moodle 2.5.1 2.6
4072 * @return string
4074 public function page_title() {
4075 return $this->page->title;
4079 * Returns the moodle_url for the favicon.
4081 * @since Moodle 2.5.1 2.6
4082 * @return moodle_url The moodle_url for the favicon
4084 public function favicon() {
4085 return $this->image_url('favicon', 'theme');
4089 * Renders preferences groups.
4091 * @param preferences_groups $renderable The renderable
4092 * @return string The output.
4094 public function render_preferences_groups(preferences_groups $renderable) {
4095 return $this->render_from_template('core/preferences_groups', $renderable);
4099 * Renders preferences group.
4101 * @param preferences_group $renderable The renderable
4102 * @return string The output.
4104 public function render_preferences_group(preferences_group $renderable) {
4105 $html = '';
4106 $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4107 $html .= $this->heading($renderable->title, 3);
4108 $html .= html_writer::start_tag('ul');
4109 foreach ($renderable->nodes as $node) {
4110 if ($node->has_children()) {
4111 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4113 $html .= html_writer::tag('li', $this->render($node));
4115 $html .= html_writer::end_tag('ul');
4116 $html .= html_writer::end_tag('div');
4117 return $html;
4120 public function context_header($headerinfo = null, $headinglevel = 1) {
4121 global $DB, $USER, $CFG, $SITE;
4122 require_once($CFG->dirroot . '/user/lib.php');
4123 $context = $this->page->context;
4124 $heading = null;
4125 $imagedata = null;
4126 $subheader = null;
4127 $userbuttons = null;
4129 if ($this->should_display_main_logo($headinglevel)) {
4130 $sitename = format_string($SITE->fullname, true, array('context' => context_course::instance(SITEID)));
4131 return html_writer::div(html_writer::empty_tag('img', [
4132 'src' => $this->get_logo_url(null, 150), 'alt' => $sitename, 'class' => 'img-fluid']), 'logo');
4135 // Make sure to use the heading if it has been set.
4136 if (isset($headerinfo['heading'])) {
4137 $heading = $headerinfo['heading'];
4140 // The user context currently has images and buttons. Other contexts may follow.
4141 if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
4142 if (isset($headerinfo['user'])) {
4143 $user = $headerinfo['user'];
4144 } else {
4145 // Look up the user information if it is not supplied.
4146 $user = $DB->get_record('user', array('id' => $context->instanceid));
4149 // If the user context is set, then use that for capability checks.
4150 if (isset($headerinfo['usercontext'])) {
4151 $context = $headerinfo['usercontext'];
4154 // Only provide user information if the user is the current user, or a user which the current user can view.
4155 // When checking user_can_view_profile(), either:
4156 // If the page context is course, check the course context (from the page object) or;
4157 // If page context is NOT course, then check across all courses.
4158 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4160 if (user_can_view_profile($user, $course)) {
4161 // Use the user's full name if the heading isn't set.
4162 if (!isset($heading)) {
4163 $heading = fullname($user);
4166 $imagedata = $this->user_picture($user, array('size' => 100));
4168 // Check to see if we should be displaying a message button.
4169 if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
4170 $userbuttons = array(
4171 'messages' => array(
4172 'buttontype' => 'message',
4173 'title' => get_string('message', 'message'),
4174 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4175 'image' => 'message',
4176 'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
4177 'page' => $this->page
4181 if ($USER->id != $user->id) {
4182 $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4183 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4184 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4185 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4186 $userbuttons['togglecontact'] = array(
4187 'buttontype' => 'togglecontact',
4188 'title' => get_string($contacttitle, 'message'),
4189 'url' => new moodle_url('/message/index.php', array(
4190 'user1' => $USER->id,
4191 'user2' => $user->id,
4192 $contacturlaction => $user->id,
4193 'sesskey' => sesskey())
4195 'image' => $contactimage,
4196 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4197 'page' => $this->page
4201 $this->page->requires->string_for_js('changesmadereallygoaway', 'moodle');
4203 } else {
4204 $heading = null;
4208 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4209 return $this->render_context_header($contextheader);
4213 * Renders the skip links for the page.
4215 * @param array $links List of skip links.
4216 * @return string HTML for the skip links.
4218 public function render_skip_links($links) {
4219 $context = [ 'links' => []];
4221 foreach ($links as $url => $text) {
4222 $context['links'][] = [ 'url' => $url, 'text' => $text];
4225 return $this->render_from_template('core/skip_links', $context);
4229 * Renders the header bar.
4231 * @param context_header $contextheader Header bar object.
4232 * @return string HTML for the header bar.
4234 protected function render_context_header(context_header $contextheader) {
4236 $showheader = empty($this->page->layout_options['nocontextheader']);
4237 if (!$showheader) {
4238 return '';
4241 // All the html stuff goes here.
4242 $html = html_writer::start_div('page-context-header');
4244 // Image data.
4245 if (isset($contextheader->imagedata)) {
4246 // Header specific image.
4247 $html .= html_writer::div($contextheader->imagedata, 'page-header-image');
4250 // Headings.
4251 if (!isset($contextheader->heading)) {
4252 $headings = $this->heading($this->page->heading, $contextheader->headinglevel);
4253 } else {
4254 $headings = $this->heading($contextheader->heading, $contextheader->headinglevel);
4257 $html .= html_writer::tag('div', $headings, array('class' => 'page-header-headings'));
4259 // Buttons.
4260 if (isset($contextheader->additionalbuttons)) {
4261 $html .= html_writer::start_div('btn-group header-button-group');
4262 foreach ($contextheader->additionalbuttons as $button) {
4263 if (!isset($button->page)) {
4264 // Include js for messaging.
4265 if ($button['buttontype'] === 'togglecontact') {
4266 \core_message\helper::togglecontact_requirejs();
4268 if ($button['buttontype'] === 'message') {
4269 \core_message\helper::messageuser_requirejs();
4271 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4272 'class' => 'iconsmall',
4273 'role' => 'presentation'
4275 $image .= html_writer::span($button['title'], 'header-button-title');
4276 } else {
4277 $image = html_writer::empty_tag('img', array(
4278 'src' => $button['formattedimage'],
4279 'role' => 'presentation'
4282 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4284 $html .= html_writer::end_div();
4286 $html .= html_writer::end_div();
4288 return $html;
4292 * Wrapper for header elements.
4294 * @return string HTML to display the main header.
4296 public function full_header() {
4298 if ($this->page->include_region_main_settings_in_header_actions() &&
4299 !$this->page->blocks->is_block_present('settings')) {
4300 // Only include the region main settings if the page has requested it and it doesn't already have
4301 // the settings block on it. The region main settings are included in the settings block and
4302 // duplicating the content causes behat failures.
4303 $this->page->add_header_action(html_writer::div(
4304 $this->region_main_settings_menu(),
4305 'd-print-none',
4306 ['id' => 'region-main-settings-menu']
4310 $header = new stdClass();
4311 $header->settingsmenu = $this->context_header_settings_menu();
4312 $header->contextheader = $this->context_header();
4313 $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
4314 $header->navbar = $this->navbar();
4315 $header->pageheadingbutton = $this->page_heading_button();
4316 $header->courseheader = $this->course_header();
4317 $header->headeractions = $this->page->get_header_actions();
4318 return $this->render_from_template('core/full_header', $header);
4322 * This is an optional menu that can be added to a layout by a theme. It contains the
4323 * menu for the course administration, only on the course main page.
4325 * @return string
4327 public function context_header_settings_menu() {
4328 $context = $this->page->context;
4329 $menu = new action_menu();
4331 $items = $this->page->navbar->get_items();
4332 $currentnode = end($items);
4334 $showcoursemenu = false;
4335 $showfrontpagemenu = false;
4336 $showusermenu = false;
4338 // We are on the course home page.
4339 if (($context->contextlevel == CONTEXT_COURSE) &&
4340 !empty($currentnode) &&
4341 ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
4342 $showcoursemenu = true;
4345 $courseformat = course_get_format($this->page->course);
4346 // This is a single activity course format, always show the course menu on the activity main page.
4347 if ($context->contextlevel == CONTEXT_MODULE &&
4348 !$courseformat->has_view_page()) {
4350 $this->page->navigation->initialise();
4351 $activenode = $this->page->navigation->find_active_node();
4352 // If the settings menu has been forced then show the menu.
4353 if ($this->page->is_settings_menu_forced()) {
4354 $showcoursemenu = true;
4355 } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
4356 $activenode->type == navigation_node::TYPE_RESOURCE)) {
4358 // We only want to show the menu on the first page of the activity. This means
4359 // the breadcrumb has no additional nodes.
4360 if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
4361 $showcoursemenu = true;
4366 // This is the site front page.
4367 if ($context->contextlevel == CONTEXT_COURSE &&
4368 !empty($currentnode) &&
4369 $currentnode->key === 'home') {
4370 $showfrontpagemenu = true;
4373 // This is the user profile page.
4374 if ($context->contextlevel == CONTEXT_USER &&
4375 !empty($currentnode) &&
4376 ($currentnode->key === 'myprofile')) {
4377 $showusermenu = true;
4380 if ($showfrontpagemenu) {
4381 $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
4382 if ($settingsnode) {
4383 // Build an action menu based on the visible nodes from this navigation tree.
4384 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4386 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4387 if ($skipped) {
4388 $text = get_string('morenavigationlinks');
4389 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4390 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4391 $menu->add_secondary_action($link);
4394 } else if ($showcoursemenu) {
4395 $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
4396 if ($settingsnode) {
4397 // Build an action menu based on the visible nodes from this navigation tree.
4398 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4400 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4401 if ($skipped) {
4402 $text = get_string('morenavigationlinks');
4403 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4404 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4405 $menu->add_secondary_action($link);
4408 } else if ($showusermenu) {
4409 // Get the course admin node from the settings navigation.
4410 $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
4411 if ($settingsnode) {
4412 // Build an action menu based on the visible nodes from this navigation tree.
4413 $this->build_action_menu_from_navigation($menu, $settingsnode);
4417 return $this->render($menu);
4421 * Take a node in the nav tree and make an action menu out of it.
4422 * The links are injected in the action menu.
4424 * @param action_menu $menu
4425 * @param navigation_node $node
4426 * @param boolean $indent
4427 * @param boolean $onlytopleafnodes
4428 * @return boolean nodesskipped - True if nodes were skipped in building the menu
4430 protected function build_action_menu_from_navigation(action_menu $menu,
4431 navigation_node $node,
4432 $indent = false,
4433 $onlytopleafnodes = false) {
4434 $skipped = false;
4435 // Build an action menu based on the visible nodes from this navigation tree.
4436 foreach ($node->children as $menuitem) {
4437 if ($menuitem->display) {
4438 if ($onlytopleafnodes && $menuitem->children->count()) {
4439 $skipped = true;
4440 continue;
4442 if ($menuitem->action) {
4443 if ($menuitem->action instanceof action_link) {
4444 $link = $menuitem->action;
4445 // Give preference to setting icon over action icon.
4446 if (!empty($menuitem->icon)) {
4447 $link->icon = $menuitem->icon;
4449 } else {
4450 $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
4452 } else {
4453 if ($onlytopleafnodes) {
4454 $skipped = true;
4455 continue;
4457 $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
4459 if ($indent) {
4460 $link->add_class('ml-4');
4462 if (!empty($menuitem->classes)) {
4463 $link->add_class(implode(" ", $menuitem->classes));
4466 $menu->add_secondary_action($link);
4467 $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
4470 return $skipped;
4474 * This is an optional menu that can be added to a layout by a theme. It contains the
4475 * menu for the most specific thing from the settings block. E.g. Module administration.
4477 * @return string
4479 public function region_main_settings_menu() {
4480 $context = $this->page->context;
4481 $menu = new action_menu();
4483 if ($context->contextlevel == CONTEXT_MODULE) {
4485 $this->page->navigation->initialise();
4486 $node = $this->page->navigation->find_active_node();
4487 $buildmenu = false;
4488 // If the settings menu has been forced then show the menu.
4489 if ($this->page->is_settings_menu_forced()) {
4490 $buildmenu = true;
4491 } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
4492 $node->type == navigation_node::TYPE_RESOURCE)) {
4494 $items = $this->page->navbar->get_items();
4495 $navbarnode = end($items);
4496 // We only want to show the menu on the first page of the activity. This means
4497 // the breadcrumb has no additional nodes.
4498 if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
4499 $buildmenu = true;
4502 if ($buildmenu) {
4503 // Get the course admin node from the settings navigation.
4504 $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
4505 if ($node) {
4506 // Build an action menu based on the visible nodes from this navigation tree.
4507 $this->build_action_menu_from_navigation($menu, $node);
4511 } else if ($context->contextlevel == CONTEXT_COURSECAT) {
4512 // For course category context, show category settings menu, if we're on the course category page.
4513 if ($this->page->pagetype === 'course-index-category') {
4514 $node = $this->page->settingsnav->find('categorysettings', navigation_node::TYPE_CONTAINER);
4515 if ($node) {
4516 // Build an action menu based on the visible nodes from this navigation tree.
4517 $this->build_action_menu_from_navigation($menu, $node);
4521 } else {
4522 $items = $this->page->navbar->get_items();
4523 $navbarnode = end($items);
4525 if ($navbarnode && ($navbarnode->key === 'participants')) {
4526 $node = $this->page->settingsnav->find('users', 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);
4534 return $this->render($menu);
4538 * Displays the list of tags associated with an entry
4540 * @param array $tags list of instances of core_tag or stdClass
4541 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4542 * to use default, set to '' (empty string) to omit the label completely
4543 * @param string $classes additional classes for the enclosing div element
4544 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4545 * will be appended to the end, JS will toggle the rest of the tags
4546 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4547 * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
4548 * @return string
4550 public function tag_list($tags, $label = null, $classes = '', $limit = 10,
4551 $pagecontext = null, $accesshidelabel = false) {
4552 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
4553 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4557 * Renders element for inline editing of any value
4559 * @param \core\output\inplace_editable $element
4560 * @return string
4562 public function render_inplace_editable(\core\output\inplace_editable $element) {
4563 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4567 * Renders a bar chart.
4569 * @param \core\chart_bar $chart The chart.
4570 * @return string.
4572 public function render_chart_bar(\core\chart_bar $chart) {
4573 return $this->render_chart($chart);
4577 * Renders a line chart.
4579 * @param \core\chart_line $chart The chart.
4580 * @return string.
4582 public function render_chart_line(\core\chart_line $chart) {
4583 return $this->render_chart($chart);
4587 * Renders a pie chart.
4589 * @param \core\chart_pie $chart The chart.
4590 * @return string.
4592 public function render_chart_pie(\core\chart_pie $chart) {
4593 return $this->render_chart($chart);
4597 * Renders a chart.
4599 * @param \core\chart_base $chart The chart.
4600 * @param bool $withtable Whether to include a data table with the chart.
4601 * @return string.
4603 public function render_chart(\core\chart_base $chart, $withtable = true) {
4604 $chartdata = json_encode($chart);
4605 return $this->render_from_template('core/chart', (object) [
4606 'chartdata' => $chartdata,
4607 'withtable' => $withtable
4612 * Renders the login form.
4614 * @param \core_auth\output\login $form The renderable.
4615 * @return string
4617 public function render_login(\core_auth\output\login $form) {
4618 global $CFG, $SITE;
4620 $context = $form->export_for_template($this);
4622 // Override because rendering is not supported in template yet.
4623 if ($CFG->rememberusername == 0) {
4624 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabledonlysession');
4625 } else {
4626 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
4628 $context->errorformatted = $this->error_text($context->error);
4629 $url = $this->get_logo_url();
4630 if ($url) {
4631 $url = $url->out(false);
4633 $context->logourl = $url;
4634 $context->sitename = format_string($SITE->fullname, true,
4635 ['context' => context_course::instance(SITEID), "escape" => false]);
4637 return $this->render_from_template('core/loginform', $context);
4641 * Renders an mform element from a template.
4643 * @param HTML_QuickForm_element $element element
4644 * @param bool $required if input is required field
4645 * @param bool $advanced if input is an advanced field
4646 * @param string $error error message to display
4647 * @param bool $ingroup True if this element is rendered as part of a group
4648 * @return mixed string|bool
4650 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4651 $templatename = 'core_form/element-' . $element->getType();
4652 if ($ingroup) {
4653 $templatename .= "-inline";
4655 try {
4656 // We call this to generate a file not found exception if there is no template.
4657 // We don't want to call export_for_template if there is no template.
4658 core\output\mustache_template_finder::get_template_filepath($templatename);
4660 if ($element instanceof templatable) {
4661 $elementcontext = $element->export_for_template($this);
4663 $helpbutton = '';
4664 if (method_exists($element, 'getHelpButton')) {
4665 $helpbutton = $element->getHelpButton();
4667 $label = $element->getLabel();
4668 $text = '';
4669 if (method_exists($element, 'getText')) {
4670 // There currently exists code that adds a form element with an empty label.
4671 // If this is the case then set the label to the description.
4672 if (empty($label)) {
4673 $label = $element->getText();
4674 } else {
4675 $text = $element->getText();
4679 // Generate the form element wrapper ids and names to pass to the template.
4680 // This differs between group and non-group elements.
4681 if ($element->getType() === 'group') {
4682 // Group element.
4683 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
4684 $elementcontext['wrapperid'] = $elementcontext['id'];
4686 // Ensure group elements pass through the group name as the element name.
4687 $elementcontext['name'] = $elementcontext['groupname'];
4688 } else {
4689 // Non grouped element.
4690 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
4691 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
4694 $context = array(
4695 'element' => $elementcontext,
4696 'label' => $label,
4697 'text' => $text,
4698 'required' => $required,
4699 'advanced' => $advanced,
4700 'helpbutton' => $helpbutton,
4701 'error' => $error
4703 return $this->render_from_template($templatename, $context);
4705 } catch (Exception $e) {
4706 // No template for this element.
4707 return false;
4712 * Render the login signup form into a nice template for the theme.
4714 * @param mform $form
4715 * @return string
4717 public function render_login_signup_form($form) {
4718 global $SITE;
4720 $context = $form->export_for_template($this);
4721 $url = $this->get_logo_url();
4722 if ($url) {
4723 $url = $url->out(false);
4725 $context['logourl'] = $url;
4726 $context['sitename'] = format_string($SITE->fullname, true,
4727 ['context' => context_course::instance(SITEID), "escape" => false]);
4729 return $this->render_from_template('core/signup_form_layout', $context);
4733 * Render the verify age and location page into a nice template for the theme.
4735 * @param \core_auth\output\verify_age_location_page $page The renderable
4736 * @return string
4738 protected function render_verify_age_location_page($page) {
4739 $context = $page->export_for_template($this);
4741 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4745 * Render the digital minor contact information page into a nice template for the theme.
4747 * @param \core_auth\output\digital_minor_page $page The renderable
4748 * @return string
4750 protected function render_digital_minor_page($page) {
4751 $context = $page->export_for_template($this);
4753 return $this->render_from_template('core/auth_digital_minor_page', $context);
4757 * Renders a progress bar.
4759 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4761 * @param progress_bar $bar The bar.
4762 * @return string HTML fragment
4764 public function render_progress_bar(progress_bar $bar) {
4765 $data = $bar->export_for_template($this);
4766 return $this->render_from_template('core/progress_bar', $data);
4770 * Renders element for a toggle-all checkbox.
4772 * @param \core\output\checkbox_toggleall $element
4773 * @return string
4775 public function render_checkbox_toggleall(\core\output\checkbox_toggleall $element) {
4776 return $this->render_from_template($element->get_template(), $element->export_for_template($this));
4781 * A renderer that generates output for command-line scripts.
4783 * The implementation of this renderer is probably incomplete.
4785 * @copyright 2009 Tim Hunt
4786 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4787 * @since Moodle 2.0
4788 * @package core
4789 * @category output
4791 class core_renderer_cli extends core_renderer {
4794 * Returns the page header.
4796 * @return string HTML fragment
4798 public function header() {
4799 return $this->page->heading . "\n";
4803 * Renders a Check API result
4805 * To aid in CLI consistency this status is NOT translated and the visual
4806 * width is always exactly 10 chars.
4808 * @param result $result
4809 * @return string HTML fragment
4811 protected function render_check_result(core\check\result $result) {
4812 $status = $result->get_status();
4814 $labels = [
4815 core\check\result::NA => ' ' . cli_ansi_format('<colour:gray>' ) . ' NA ',
4816 core\check\result::OK => ' ' . cli_ansi_format('<colour:green>') . ' OK ',
4817 core\check\result::INFO => ' ' . cli_ansi_format('<colour:blue>' ) . ' INFO ',
4818 core\check\result::UNKNOWN => ' ' . cli_ansi_format('<colour:grey>' ) . ' UNKNOWN ',
4819 core\check\result::WARNING => ' ' . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
4820 core\check\result::ERROR => ' ' . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
4821 core\check\result::CRITICAL => '' . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
4823 $string = $labels[$status] . cli_ansi_format('<colour:normal>');
4824 return $string;
4828 * Renders a Check API result
4830 * @param result $result
4831 * @return string fragment
4833 public function check_result(core\check\result $result) {
4834 return $this->render_check_result($result);
4838 * Returns a template fragment representing a Heading.
4840 * @param string $text The text of the heading
4841 * @param int $level The level of importance of the heading
4842 * @param string $classes A space-separated list of CSS classes
4843 * @param string $id An optional ID
4844 * @return string A template fragment for a heading
4846 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4847 $text .= "\n";
4848 switch ($level) {
4849 case 1:
4850 return '=>' . $text;
4851 case 2:
4852 return '-->' . $text;
4853 default:
4854 return $text;
4859 * Returns a template fragment representing a fatal error.
4861 * @param string $message The message to output
4862 * @param string $moreinfourl URL where more info can be found about the error
4863 * @param string $link Link for the Continue button
4864 * @param array $backtrace The execution backtrace
4865 * @param string $debuginfo Debugging information
4866 * @return string A template fragment for a fatal error
4868 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4869 global $CFG;
4871 $output = "!!! $message !!!\n";
4873 if ($CFG->debugdeveloper) {
4874 if (!empty($debuginfo)) {
4875 $output .= $this->notification($debuginfo, 'notifytiny');
4877 if (!empty($backtrace)) {
4878 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
4882 return $output;
4886 * Returns a template fragment representing a notification.
4888 * @param string $message The message to print out.
4889 * @param string $type The type of notification. See constants on \core\output\notification.
4890 * @return string A template fragment for a notification
4892 public function notification($message, $type = null) {
4893 $message = clean_text($message);
4894 if ($type === 'notifysuccess' || $type === 'success') {
4895 return "++ $message ++\n";
4897 return "!! $message !!\n";
4901 * There is no footer for a cli request, however we must override the
4902 * footer method to prevent the default footer.
4904 public function footer() {}
4907 * Render a notification (that is, a status message about something that has
4908 * just happened).
4910 * @param \core\output\notification $notification the notification to print out
4911 * @return string plain text output
4913 public function render_notification(\core\output\notification $notification) {
4914 return $this->notification($notification->get_message(), $notification->get_message_type());
4920 * A renderer that generates output for ajax scripts.
4922 * This renderer prevents accidental sends back only json
4923 * encoded error messages, all other output is ignored.
4925 * @copyright 2010 Petr Skoda
4926 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4927 * @since Moodle 2.0
4928 * @package core
4929 * @category output
4931 class core_renderer_ajax extends core_renderer {
4934 * Returns a template fragment representing a fatal error.
4936 * @param string $message The message to output
4937 * @param string $moreinfourl URL where more info can be found about the error
4938 * @param string $link Link for the Continue button
4939 * @param array $backtrace The execution backtrace
4940 * @param string $debuginfo Debugging information
4941 * @return string A template fragment for a fatal error
4943 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4944 global $CFG;
4946 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
4948 $e = new stdClass();
4949 $e->error = $message;
4950 $e->errorcode = $errorcode;
4951 $e->stacktrace = NULL;
4952 $e->debuginfo = NULL;
4953 $e->reproductionlink = NULL;
4954 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
4955 $link = (string) $link;
4956 if ($link) {
4957 $e->reproductionlink = $link;
4959 if (!empty($debuginfo)) {
4960 $e->debuginfo = $debuginfo;
4962 if (!empty($backtrace)) {
4963 $e->stacktrace = format_backtrace($backtrace, true);
4966 $this->header();
4967 return json_encode($e);
4971 * Used to display a notification.
4972 * For the AJAX notifications are discarded.
4974 * @param string $message The message to print out.
4975 * @param string $type The type of notification. See constants on \core\output\notification.
4977 public function notification($message, $type = null) {}
4980 * Used to display a redirection message.
4981 * AJAX redirections should not occur and as such redirection messages
4982 * are discarded.
4984 * @param moodle_url|string $encodedurl
4985 * @param string $message
4986 * @param int $delay
4987 * @param bool $debugdisableredirect
4988 * @param string $messagetype The type of notification to show the message in.
4989 * See constants on \core\output\notification.
4991 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
4992 $messagetype = \core\output\notification::NOTIFY_INFO) {}
4995 * Prepares the start of an AJAX output.
4997 public function header() {
4998 // unfortunately YUI iframe upload does not support application/json
4999 if (!empty($_FILES)) {
5000 @header('Content-type: text/plain; charset=utf-8');
5001 if (!core_useragent::supports_json_contenttype()) {
5002 @header('X-Content-Type-Options: nosniff');
5004 } else if (!core_useragent::supports_json_contenttype()) {
5005 @header('Content-type: text/plain; charset=utf-8');
5006 @header('X-Content-Type-Options: nosniff');
5007 } else {
5008 @header('Content-type: application/json; charset=utf-8');
5011 // Headers to make it not cacheable and json
5012 @header('Cache-Control: no-store, no-cache, must-revalidate');
5013 @header('Cache-Control: post-check=0, pre-check=0', false);
5014 @header('Pragma: no-cache');
5015 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
5016 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
5017 @header('Accept-Ranges: none');
5021 * There is no footer for an AJAX request, however we must override the
5022 * footer method to prevent the default footer.
5024 public function footer() {}
5027 * No need for headers in an AJAX request... this should never happen.
5028 * @param string $text
5029 * @param int $level
5030 * @param string $classes
5031 * @param string $id
5033 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
5039 * The maintenance renderer.
5041 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
5042 * is running a maintenance related task.
5043 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
5045 * @since Moodle 2.6
5046 * @package core
5047 * @category output
5048 * @copyright 2013 Sam Hemelryk
5049 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5051 class core_renderer_maintenance extends core_renderer {
5054 * Initialises the renderer instance.
5056 * @param moodle_page $page
5057 * @param string $target
5058 * @throws coding_exception
5060 public function __construct(moodle_page $page, $target) {
5061 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
5062 throw new coding_exception('Invalid request for the maintenance renderer.');
5064 parent::__construct($page, $target);
5068 * Does nothing. The maintenance renderer cannot produce blocks.
5070 * @param block_contents $bc
5071 * @param string $region
5072 * @return string
5074 public function block(block_contents $bc, $region) {
5075 return '';
5079 * Does nothing. The maintenance renderer cannot produce blocks.
5081 * @param string $region
5082 * @param array $classes
5083 * @param string $tag
5084 * @return string
5086 public function blocks($region, $classes = array(), $tag = 'aside') {
5087 return '';
5091 * Does nothing. The maintenance renderer cannot produce blocks.
5093 * @param string $region
5094 * @return string
5096 public function blocks_for_region($region) {
5097 return '';
5101 * Does nothing. The maintenance renderer cannot produce a course content header.
5103 * @param bool $onlyifnotcalledbefore
5104 * @return string
5106 public function course_content_header($onlyifnotcalledbefore = false) {
5107 return '';
5111 * Does nothing. The maintenance renderer cannot produce a course content footer.
5113 * @param bool $onlyifnotcalledbefore
5114 * @return string
5116 public function course_content_footer($onlyifnotcalledbefore = false) {
5117 return '';
5121 * Does nothing. The maintenance renderer cannot produce a course header.
5123 * @return string
5125 public function course_header() {
5126 return '';
5130 * Does nothing. The maintenance renderer cannot produce a course footer.
5132 * @return string
5134 public function course_footer() {
5135 return '';
5139 * Does nothing. The maintenance renderer cannot produce a custom menu.
5141 * @param string $custommenuitems
5142 * @return string
5144 public function custom_menu($custommenuitems = '') {
5145 return '';
5149 * Does nothing. The maintenance renderer cannot produce a file picker.
5151 * @param array $options
5152 * @return string
5154 public function file_picker($options) {
5155 return '';
5159 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
5161 * @param array $dir
5162 * @return string
5164 public function htmllize_file_tree($dir) {
5165 return '';
5170 * Overridden confirm message for upgrades.
5172 * @param string $message The question to ask the user
5173 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5174 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5175 * @return string HTML fragment
5177 public function confirm($message, $continue, $cancel) {
5178 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5179 // from any previous version of Moodle).
5180 if ($continue instanceof single_button) {
5181 $continue->primary = true;
5182 } else if (is_string($continue)) {
5183 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
5184 } else if ($continue instanceof moodle_url) {
5185 $continue = new single_button($continue, get_string('continue'), 'post', true);
5186 } else {
5187 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5188 ' (string/moodle_url) or a single_button instance.');
5191 if ($cancel instanceof single_button) {
5192 $output = '';
5193 } else if (is_string($cancel)) {
5194 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5195 } else if ($cancel instanceof moodle_url) {
5196 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5197 } else {
5198 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5199 ' (string/moodle_url) or a single_button instance.');
5202 $output = $this->box_start('generalbox', 'notice');
5203 $output .= html_writer::tag('h4', get_string('confirm'));
5204 $output .= html_writer::tag('p', $message);
5205 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
5206 $output .= $this->box_end();
5207 return $output;
5211 * Does nothing. The maintenance renderer does not support JS.
5213 * @param block_contents $bc
5215 public function init_block_hider_js(block_contents $bc) {
5216 // Does nothing.
5220 * Does nothing. The maintenance renderer cannot produce language menus.
5222 * @return string
5224 public function lang_menu() {
5225 return '';
5229 * Does nothing. The maintenance renderer has no need for login information.
5231 * @param null $withlinks
5232 * @return string
5234 public function login_info($withlinks = null) {
5235 return '';
5239 * Secure login info.
5241 * @return string
5243 public function secure_login_info() {
5244 return $this->login_info(false);
5248 * Does nothing. The maintenance renderer cannot produce user pictures.
5250 * @param stdClass $user
5251 * @param array $options
5252 * @return string
5254 public function user_picture(stdClass $user, array $options = null) {
5255 return '';