Merge branch 'MDL-73502' of https://github.com/stronk7/moodle
[moodle.git] / lib / outputrenderers.php
blob6165d02ff4bbc6aac564379ffd74e45be934681e
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
21 * for an overview.
23 * Included in this file are the primary renderer classes:
24 * - renderer_base: The renderer outline class that all renderers
25 * should inherit from.
26 * - core_renderer: The standard HTML renderer.
27 * - core_renderer_cli: An adaption of the standard renderer for CLI scripts.
28 * - core_renderer_ajax: An adaption of the standard renderer for AJAX scripts.
29 * - plugin_renderer_base: A renderer class that should be extended by all
30 * plugin renderers.
32 * @package core
33 * @category output
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 use core_completion\cm_completion_details;
39 use core_course\output\activity_information;
41 defined('MOODLE_INTERNAL') || die();
43 /**
44 * Simple base class for Moodle renderers.
46 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
48 * Also has methods to facilitate generating HTML output.
50 * @copyright 2009 Tim Hunt
51 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
52 * @since Moodle 2.0
53 * @package core
54 * @category output
56 class renderer_base {
57 /**
58 * @var xhtml_container_stack The xhtml_container_stack to use.
60 protected $opencontainers;
62 /**
63 * @var moodle_page The Moodle page the renderer has been created to assist with.
65 protected $page;
67 /**
68 * @var string The requested rendering target.
70 protected $target;
72 /**
73 * @var Mustache_Engine $mustache The mustache template compiler
75 private $mustache;
77 /**
78 * Return an instance of the mustache class.
80 * @since 2.9
81 * @return Mustache_Engine
83 protected function get_mustache() {
84 global $CFG;
86 if ($this->mustache === null) {
87 require_once("{$CFG->libdir}/filelib.php");
89 $themename = $this->page->theme->name;
90 $themerev = theme_get_revision();
92 // Create new localcache directory.
93 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
95 // Remove old localcache directories.
96 $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR);
97 foreach ($mustachecachedirs as $localcachedir) {
98 $cachedrev = [];
99 preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
100 $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
101 if ($cachedrev > 0 && $cachedrev < $themerev) {
102 fulldelete($localcachedir);
106 $loader = new \core\output\mustache_filesystem_loader();
107 $stringhelper = new \core\output\mustache_string_helper();
108 $cleanstringhelper = new \core\output\mustache_clean_string_helper();
109 $quotehelper = new \core\output\mustache_quote_helper();
110 $jshelper = new \core\output\mustache_javascript_helper($this->page);
111 $pixhelper = new \core\output\mustache_pix_helper($this);
112 $shortentexthelper = new \core\output\mustache_shorten_text_helper();
113 $userdatehelper = new \core\output\mustache_user_date_helper();
115 // We only expose the variables that are exposed to JS templates.
116 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
118 $helpers = array('config' => $safeconfig,
119 'str' => array($stringhelper, 'str'),
120 'cleanstr' => array($cleanstringhelper, 'cleanstr'),
121 'quote' => array($quotehelper, 'quote'),
122 'js' => array($jshelper, 'help'),
123 'pix' => array($pixhelper, 'pix'),
124 'shortentext' => array($shortentexthelper, 'shorten'),
125 'userdate' => array($userdatehelper, 'transform'),
128 $this->mustache = new \core\output\mustache_engine(array(
129 'cache' => $cachedir,
130 'escape' => 's',
131 'loader' => $loader,
132 'helpers' => $helpers,
133 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS],
134 // Don't allow the JavaScript helper to be executed from within another
135 // helper. If it's allowed it can be used by users to inject malicious
136 // JS into the page.
137 'disallowednestedhelpers' => ['js']));
141 return $this->mustache;
146 * Constructor
148 * The constructor takes two arguments. The first is the page that the renderer
149 * has been created to assist with, and the second is the target.
150 * The target is an additional identifier that can be used to load different
151 * renderers for different options.
153 * @param moodle_page $page the page we are doing output for.
154 * @param string $target one of rendering target constants
156 public function __construct(moodle_page $page, $target) {
157 $this->opencontainers = $page->opencontainers;
158 $this->page = $page;
159 $this->target = $target;
163 * Renders a template by name with the given context.
165 * The provided data needs to be array/stdClass made up of only simple types.
166 * Simple types are array,stdClass,bool,int,float,string
168 * @since 2.9
169 * @param array|stdClass $context Context containing data for the template.
170 * @return string|boolean
172 public function render_from_template($templatename, $context) {
173 static $templatecache = array();
174 $mustache = $this->get_mustache();
176 try {
177 // Grab a copy of the existing helper to be restored later.
178 $uniqidhelper = $mustache->getHelper('uniqid');
179 } catch (Mustache_Exception_UnknownHelperException $e) {
180 // Helper doesn't exist.
181 $uniqidhelper = null;
184 // Provide 1 random value that will not change within a template
185 // but will be different from template to template. This is useful for
186 // e.g. aria attributes that only work with id attributes and must be
187 // unique in a page.
188 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
189 if (isset($templatecache[$templatename])) {
190 $template = $templatecache[$templatename];
191 } else {
192 try {
193 $template = $mustache->loadTemplate($templatename);
194 $templatecache[$templatename] = $template;
195 } catch (Mustache_Exception_UnknownTemplateException $e) {
196 throw new moodle_exception('Unknown template: ' . $templatename);
200 $renderedtemplate = trim($template->render($context));
202 // If we had an existing uniqid helper then we need to restore it to allow
203 // handle nested calls of render_from_template.
204 if ($uniqidhelper) {
205 $mustache->addHelper('uniqid', $uniqidhelper);
208 return $renderedtemplate;
213 * Returns rendered widget.
215 * The provided widget needs to be an object that extends the renderable
216 * interface.
217 * If will then be rendered by a method based upon the classname for the widget.
218 * For instance a widget of class `crazywidget` will be rendered by a protected
219 * render_crazywidget method of this renderer.
220 * If no render_crazywidget method exists and crazywidget implements templatable,
221 * look for the 'crazywidget' template in the same component and render that.
223 * @param renderable $widget instance with renderable interface
224 * @return string
226 public function render(renderable $widget) {
227 $classparts = explode('\\', get_class($widget));
228 // Strip namespaces.
229 $classname = array_pop($classparts);
230 // Remove _renderable suffixes
231 $classname = preg_replace('/_renderable$/', '', $classname);
233 $rendermethod = 'render_'.$classname;
234 if (method_exists($this, $rendermethod)) {
235 return $this->$rendermethod($widget);
237 if ($widget instanceof templatable) {
238 $component = array_shift($classparts);
239 if (!$component) {
240 $component = 'core';
242 $template = $component . '/' . $classname;
243 $context = $widget->export_for_template($this);
244 return $this->render_from_template($template, $context);
246 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
250 * Adds a JS action for the element with the provided id.
252 * This method adds a JS event for the provided component action to the page
253 * and then returns the id that the event has been attached to.
254 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
256 * @param component_action $action
257 * @param string $id
258 * @return string id of element, either original submitted or random new if not supplied
260 public function add_action_handler(component_action $action, $id = null) {
261 if (!$id) {
262 $id = html_writer::random_id($action->event);
264 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
265 return $id;
269 * Returns true is output has already started, and false if not.
271 * @return boolean true if the header has been printed.
273 public function has_started() {
274 return $this->page->state >= moodle_page::STATE_IN_BODY;
278 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
280 * @param mixed $classes Space-separated string or array of classes
281 * @return string HTML class attribute value
283 public static function prepare_classes($classes) {
284 if (is_array($classes)) {
285 return implode(' ', array_unique($classes));
287 return $classes;
291 * Return the direct URL for an image from the pix folder.
293 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
295 * @deprecated since Moodle 3.3
296 * @param string $imagename the name of the icon.
297 * @param string $component specification of one plugin like in get_string()
298 * @return moodle_url
300 public function pix_url($imagename, $component = 'moodle') {
301 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
302 return $this->page->theme->image_url($imagename, $component);
306 * Return the moodle_url for an image.
308 * The exact image location and extension is determined
309 * automatically by searching for gif|png|jpg|jpeg, please
310 * note there can not be diferent images with the different
311 * extension. The imagename is for historical reasons
312 * a relative path name, it may be changed later for core
313 * images. It is recommended to not use subdirectories
314 * in plugin and theme pix directories.
316 * There are three types of images:
317 * 1/ theme images - stored in theme/mytheme/pix/,
318 * use component 'theme'
319 * 2/ core images - stored in /pix/,
320 * overridden via theme/mytheme/pix_core/
321 * 3/ plugin images - stored in mod/mymodule/pix,
322 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
323 * example: image_url('comment', 'mod_glossary')
325 * @param string $imagename the pathname of the image
326 * @param string $component full plugin name (aka component) or 'theme'
327 * @return moodle_url
329 public function image_url($imagename, $component = 'moodle') {
330 return $this->page->theme->image_url($imagename, $component);
334 * Return the site's logo URL, if any.
336 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
337 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
338 * @return moodle_url|false
340 public function get_logo_url($maxwidth = null, $maxheight = 200) {
341 global $CFG;
342 $logo = get_config('core_admin', 'logo');
343 if (empty($logo)) {
344 return false;
347 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
348 // It's not worth the overhead of detecting and serving 2 different images based on the device.
350 // Hide the requested size in the file path.
351 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
353 // Use $CFG->themerev to prevent browser caching when the file changes.
354 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
355 theme_get_revision(), $logo);
359 * Return the site's compact logo URL, if any.
361 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
362 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
363 * @return moodle_url|false
365 public function get_compact_logo_url($maxwidth = 300, $maxheight = 300) {
366 global $CFG;
367 $logo = get_config('core_admin', 'logocompact');
368 if (empty($logo)) {
369 return false;
372 // Hide the requested size in the file path.
373 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
375 // Use $CFG->themerev to prevent browser caching when the file changes.
376 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
377 theme_get_revision(), $logo);
381 * Whether we should display the logo in the navbar.
383 * We will when there are no main logos, and we have compact logo.
385 * @return bool
387 public function should_display_navbar_logo() {
388 $logo = $this->get_compact_logo_url();
389 return !empty($logo);
393 * Whether we should display the main logo.
394 * @deprecated since Moodle 4.0
395 * @todo final deprecation. To be removed in Moodle 4.4 MDL-73165.
396 * @param int $headinglevel The heading level we want to check against.
397 * @return bool
399 public function should_display_main_logo($headinglevel = 1) {
400 debugging('should_display_main_logo() is deprecated and will be removed in Moodle 4.4.', DEBUG_DEVELOPER);
401 // Only render the logo if we're on the front page or login page and the we have a logo.
402 $logo = $this->get_logo_url();
403 if ($headinglevel == 1 && !empty($logo)) {
404 if ($this->page->pagelayout == 'frontpage' || $this->page->pagelayout == 'login') {
405 return true;
409 return false;
416 * Basis for all plugin renderers.
418 * @copyright Petr Skoda (skodak)
419 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
420 * @since Moodle 2.0
421 * @package core
422 * @category output
424 class plugin_renderer_base extends renderer_base {
427 * @var renderer_base|core_renderer A reference to the current renderer.
428 * The renderer provided here will be determined by the page but will in 90%
429 * of cases by the {@link core_renderer}
431 protected $output;
434 * Constructor method, calls the parent constructor
436 * @param moodle_page $page
437 * @param string $target one of rendering target constants
439 public function __construct(moodle_page $page, $target) {
440 if (empty($target) && $page->pagelayout === 'maintenance') {
441 // If the page is using the maintenance layout then we're going to force the target to maintenance.
442 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
443 // unavailable for this page layout.
444 $target = RENDERER_TARGET_MAINTENANCE;
446 $this->output = $page->get_renderer('core', null, $target);
447 parent::__construct($page, $target);
451 * Renders the provided widget and returns the HTML to display it.
453 * @param renderable $widget instance with renderable interface
454 * @return string
456 public function render(renderable $widget) {
457 $classname = get_class($widget);
458 // Strip namespaces.
459 $classname = preg_replace('/^.*\\\/', '', $classname);
460 // Keep a copy at this point, we may need to look for a deprecated method.
461 $deprecatedmethod = 'render_'.$classname;
462 // Remove _renderable suffixes
463 $classname = preg_replace('/_renderable$/', '', $classname);
465 $rendermethod = 'render_'.$classname;
466 if (method_exists($this, $rendermethod)) {
467 return $this->$rendermethod($widget);
469 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
470 // This is exactly where we don't want to be.
471 // If you have arrived here you have a renderable component within your plugin that has the name
472 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
473 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
474 // and the _renderable suffix now gets removed when looking for a render method.
475 // You need to change your renderers render_blah_renderable to render_blah.
476 // Until you do this it will not be possible for a theme to override the renderer to override your method.
477 // Please do it ASAP.
478 static $debugged = array();
479 if (!isset($debugged[$deprecatedmethod])) {
480 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
481 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
482 $debugged[$deprecatedmethod] = true;
484 return $this->$deprecatedmethod($widget);
486 // pass to core renderer if method not found here
487 return $this->output->render($widget);
491 * Magic method used to pass calls otherwise meant for the standard renderer
492 * to it to ensure we don't go causing unnecessary grief.
494 * @param string $method
495 * @param array $arguments
496 * @return mixed
498 public function __call($method, $arguments) {
499 if (method_exists('renderer_base', $method)) {
500 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
502 if (method_exists($this->output, $method)) {
503 return call_user_func_array(array($this->output, $method), $arguments);
504 } else {
505 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
512 * The standard implementation of the core_renderer interface.
514 * @copyright 2009 Tim Hunt
515 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
516 * @since Moodle 2.0
517 * @package core
518 * @category output
520 class core_renderer extends renderer_base {
522 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
523 * in layout files instead.
524 * @deprecated
525 * @var string used in {@link core_renderer::header()}.
527 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
530 * @var string Used to pass information from {@link core_renderer::doctype()} to
531 * {@link core_renderer::standard_head_html()}.
533 protected $contenttype;
536 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
537 * with {@link core_renderer::header()}.
539 protected $metarefreshtag = '';
542 * @var string Unique token for the closing HTML
544 protected $unique_end_html_token;
547 * @var string Unique token for performance information
549 protected $unique_performance_info_token;
552 * @var string Unique token for the main content.
554 protected $unique_main_content_token;
556 /** @var custom_menu_item language The language menu if created */
557 protected $language = null;
560 * Constructor
562 * @param moodle_page $page the page we are doing output for.
563 * @param string $target one of rendering target constants
565 public function __construct(moodle_page $page, $target) {
566 $this->opencontainers = $page->opencontainers;
567 $this->page = $page;
568 $this->target = $target;
570 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
571 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
572 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
576 * Get the DOCTYPE declaration that should be used with this page. Designed to
577 * be called in theme layout.php files.
579 * @return string the DOCTYPE declaration that should be used.
581 public function doctype() {
582 if ($this->page->theme->doctype === 'html5') {
583 $this->contenttype = 'text/html; charset=utf-8';
584 return "<!DOCTYPE html>\n";
586 } else if ($this->page->theme->doctype === 'xhtml5') {
587 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
588 return "<!DOCTYPE html>\n";
590 } else {
591 // legacy xhtml 1.0
592 $this->contenttype = 'text/html; charset=utf-8';
593 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
598 * The attributes that should be added to the <html> tag. Designed to
599 * be called in theme layout.php files.
601 * @return string HTML fragment.
603 public function htmlattributes() {
604 $return = get_html_lang(true);
605 $attributes = array();
606 if ($this->page->theme->doctype !== 'html5') {
607 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
610 // Give plugins an opportunity to add things like xml namespaces to the html element.
611 // This function should return an array of html attribute names => values.
612 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
613 foreach ($pluginswithfunction as $plugins) {
614 foreach ($plugins as $function) {
615 $newattrs = $function();
616 unset($newattrs['dir']);
617 unset($newattrs['lang']);
618 unset($newattrs['xmlns']);
619 unset($newattrs['xml:lang']);
620 $attributes += $newattrs;
624 foreach ($attributes as $key => $val) {
625 $val = s($val);
626 $return .= " $key=\"$val\"";
629 return $return;
633 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
634 * that should be included in the <head> tag. Designed to be called in theme
635 * layout.php files.
637 * @return string HTML fragment.
639 public function standard_head_html() {
640 global $CFG, $SESSION, $SITE;
642 // Before we output any content, we need to ensure that certain
643 // page components are set up.
645 // Blocks must be set up early as they may require javascript which
646 // has to be included in the page header before output is created.
647 foreach ($this->page->blocks->get_regions() as $region) {
648 $this->page->blocks->ensure_content_created($region, $this);
651 $output = '';
653 // Give plugins an opportunity to add any head elements. The callback
654 // must always return a string containing valid html head content.
655 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
656 foreach ($pluginswithfunction as $plugins) {
657 foreach ($plugins as $function) {
658 $output .= $function();
662 // Allow a url_rewrite plugin to setup any dynamic head content.
663 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
664 $class = $CFG->urlrewriteclass;
665 $output .= $class::html_head_setup();
668 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
669 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
670 // This is only set by the {@link redirect()} method
671 $output .= $this->metarefreshtag;
673 // Check if a periodic refresh delay has been set and make sure we arn't
674 // already meta refreshing
675 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
676 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
679 // Set up help link popups for all links with the helptooltip class
680 $this->page->requires->js_init_call('M.util.help_popups.setup');
682 $focus = $this->page->focuscontrol;
683 if (!empty($focus)) {
684 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
685 // This is a horrifically bad way to handle focus but it is passed in
686 // through messy formslib::moodleform
687 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
688 } else if (strpos($focus, '.')!==false) {
689 // Old style of focus, bad way to do it
690 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);
691 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
692 } else {
693 // Focus element with given id
694 $this->page->requires->js_function_call('focuscontrol', array($focus));
698 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
699 // any other custom CSS can not be overridden via themes and is highly discouraged
700 $urls = $this->page->theme->css_urls($this->page);
701 foreach ($urls as $url) {
702 $this->page->requires->css_theme($url);
705 // Get the theme javascript head and footer
706 if ($jsurl = $this->page->theme->javascript_url(true)) {
707 $this->page->requires->js($jsurl, true);
709 if ($jsurl = $this->page->theme->javascript_url(false)) {
710 $this->page->requires->js($jsurl);
713 // Get any HTML from the page_requirements_manager.
714 $output .= $this->page->requires->get_head_code($this->page, $this);
716 // List alternate versions.
717 foreach ($this->page->alternateversions as $type => $alt) {
718 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
719 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
722 // Add noindex tag if relevant page and setting applied.
723 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
724 $loginpages = array('login-index', 'login-signup');
725 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
726 if (!isset($CFG->additionalhtmlhead)) {
727 $CFG->additionalhtmlhead = '';
729 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
732 if (!empty($CFG->additionalhtmlhead)) {
733 $output .= "\n".$CFG->additionalhtmlhead;
736 if ($this->page->pagelayout == 'frontpage') {
737 $summary = s(strip_tags(format_text($SITE->summary, FORMAT_HTML)));
738 if (!empty($summary)) {
739 $output .= "<meta name=\"description\" content=\"$summary\" />\n";
743 return $output;
747 * The standard tags (typically skip links) that should be output just inside
748 * the start of the <body> tag. Designed to be called in theme layout.php files.
750 * @return string HTML fragment.
752 public function standard_top_of_body_html() {
753 global $CFG;
754 $output = $this->page->requires->get_top_of_body_code($this);
755 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
756 $output .= "\n".$CFG->additionalhtmltopofbody;
759 // Give subsystems an opportunity to inject extra html content. The callback
760 // must always return a string containing valid html.
761 foreach (\core_component::get_core_subsystems() as $name => $path) {
762 if ($path) {
763 $output .= component_callback($name, 'before_standard_top_of_body_html', [], '');
767 // Give plugins an opportunity to inject extra html content. The callback
768 // must always return a string containing valid html.
769 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
770 foreach ($pluginswithfunction as $plugins) {
771 foreach ($plugins as $function) {
772 $output .= $function();
776 $output .= $this->maintenance_warning();
778 return $output;
782 * Scheduled maintenance warning message.
784 * Note: This is a nasty hack to display maintenance notice, this should be moved
785 * to some general notification area once we have it.
787 * @return string
789 public function maintenance_warning() {
790 global $CFG;
792 $output = '';
793 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
794 $timeleft = $CFG->maintenance_later - time();
795 // If timeleft less than 30 sec, set the class on block to error to highlight.
796 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
797 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-3 alert');
798 $a = new stdClass();
799 $a->hour = (int)($timeleft / 3600);
800 $a->min = (int)(($timeleft / 60) % 60);
801 $a->sec = (int)($timeleft % 60);
802 if ($a->hour > 0) {
803 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
804 } else {
805 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
808 $output .= $this->box_end();
809 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
810 array(array('timeleftinsec' => $timeleft)));
811 $this->page->requires->strings_for_js(
812 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
813 'admin');
815 return $output;
819 * content that should be output in the footer area
820 * of the page. Designed to be called in theme layout.php files.
822 * @return string HTML fragment.
824 public function standard_footer_html() {
825 global $CFG;
827 $output = '';
828 if (during_initial_install()) {
829 // Debugging info can not work before install is finished,
830 // in any case we do not want any links during installation!
831 return $output;
834 // Give plugins an opportunity to add any footer elements.
835 // The callback must always return a string containing valid html footer content.
836 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
837 foreach ($pluginswithfunction as $plugins) {
838 foreach ($plugins as $function) {
839 $output .= $function();
843 if (core_userfeedback::can_give_feedback()) {
844 $output .= html_writer::div(
845 $this->render_from_template('core/userfeedback_footer_link', ['url' => core_userfeedback::make_link()->out(false)])
849 if ($this->page->devicetypeinuse == 'legacy') {
850 // The legacy theme is in use print the notification
851 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
854 // Get links to switch device types (only shown for users not on a default device)
855 $output .= $this->theme_switch_links();
857 return $output;
861 * Performance information and validation links for debugging.
863 * @return string HTML fragment.
865 public function debug_footer_html() {
866 global $CFG, $SCRIPT;
867 $output = '';
869 if (during_initial_install()) {
870 // Debugging info can not work before install is finished.
871 return $output;
874 // This function is normally called from a layout.php file
875 // but some of the content won't be known until later, so we return a placeholder
876 // for now. This will be replaced with the real content in the footer.
877 $output .= $this->unique_performance_info_token;
879 if (!empty($CFG->debugpageinfo)) {
880 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
881 $this->page->debug_summary()) . '</div>';
883 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
885 // Add link to profiling report if necessary
886 if (function_exists('profiling_is_running') && profiling_is_running()) {
887 $txt = get_string('profiledscript', 'admin');
888 $title = get_string('profiledscriptview', 'admin');
889 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
890 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
891 $output .= '<div class="profilingfooter">' . $link . '</div>';
893 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
894 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
895 $output .= '<div class="purgecaches">' .
896 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
898 // Reactive module debug panel.
899 $output .= $this->render_from_template('core/local/reactive/debugpanel', []);
901 if (!empty($CFG->debugvalidators)) {
902 $siteurl = qualified_me();
903 $nuurl = new moodle_url('https://validator.w3.org/nu/', ['doc' => $siteurl, 'showsource' => 'yes']);
904 $waveurl = new moodle_url('https://wave.webaim.org/report#/' . urlencode($siteurl));
905 $validatorlinks = [
906 html_writer::link($nuurl, get_string('validatehtml')),
907 html_writer::link($waveurl, get_string('wcagcheck'))
909 $validatorlinkslist = html_writer::alist($validatorlinks, ['class' => 'list-unstyled ml-1']);
910 $output .= html_writer::div($validatorlinkslist, 'validators');
912 return $output;
916 * Returns standard main content placeholder.
917 * Designed to be called in theme layout.php files.
919 * @return string HTML fragment.
921 public function main_content() {
922 // This is here because it is the only place we can inject the "main" role over the entire main content area
923 // without requiring all theme's to manually do it, and without creating yet another thing people need to
924 // remember in the theme.
925 // This is an unfortunate hack. DO NO EVER add anything more here.
926 // DO NOT add classes.
927 // DO NOT add an id.
928 return '<div role="main">'.$this->unique_main_content_token.'</div>';
932 * Returns information about an activity.
934 * @param cm_info $cminfo The course module information.
935 * @param cm_completion_details $completiondetails The completion details for this activity module.
936 * @param array $activitydates The dates for this activity module.
937 * @return string the activity information HTML.
938 * @throws coding_exception
940 public function activity_information(cm_info $cminfo, cm_completion_details $completiondetails, array $activitydates): string {
941 if (!$completiondetails->has_completion() && empty($activitydates)) {
942 // No need to render the activity information when there's no completion info and activity dates to show.
943 return '';
945 $activityinfo = new activity_information($cminfo, $completiondetails, $activitydates);
946 $renderer = $this->page->get_renderer('core', 'course');
947 return $renderer->render($activityinfo);
951 * Returns standard navigation between activities in a course.
953 * @return string the navigation HTML.
955 public function activity_navigation() {
956 // First we should check if we want to add navigation.
957 $context = $this->page->context;
958 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
959 || $context->contextlevel != CONTEXT_MODULE) {
960 return '';
963 // If the activity is in stealth mode, show no links.
964 if ($this->page->cm->is_stealth()) {
965 return '';
968 $course = $this->page->cm->get_course();
969 $courseformat = course_get_format($course);
971 // If the theme implements course index and the current course format uses course index and the current
972 // page layout is not 'frametop' (this layout does not support course index), show no links.
973 if ($this->page->theme->usescourseindex && $courseformat->uses_course_index() &&
974 $this->page->pagelayout !== 'frametop') {
975 return '';
978 // Get a list of all the activities in the course.
979 $modules = get_fast_modinfo($course->id)->get_cms();
981 // Put the modules into an array in order by the position they are shown in the course.
982 $mods = [];
983 $activitylist = [];
984 foreach ($modules as $module) {
985 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
986 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
987 continue;
989 $mods[$module->id] = $module;
991 // No need to add the current module to the list for the activity dropdown menu.
992 if ($module->id == $this->page->cm->id) {
993 continue;
995 // Module name.
996 $modname = $module->get_formatted_name();
997 // Display the hidden text if necessary.
998 if (!$module->visible) {
999 $modname .= ' ' . get_string('hiddenwithbrackets');
1001 // Module URL.
1002 $linkurl = new moodle_url($module->url, array('forceview' => 1));
1003 // Add module URL (as key) and name (as value) to the activity list array.
1004 $activitylist[$linkurl->out(false)] = $modname;
1007 $nummods = count($mods);
1009 // If there is only one mod then do nothing.
1010 if ($nummods == 1) {
1011 return '';
1014 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
1015 $modids = array_keys($mods);
1017 // Get the position in the array of the course module we are viewing.
1018 $position = array_search($this->page->cm->id, $modids);
1020 $prevmod = null;
1021 $nextmod = null;
1023 // Check if we have a previous mod to show.
1024 if ($position > 0) {
1025 $prevmod = $mods[$modids[$position - 1]];
1028 // Check if we have a next mod to show.
1029 if ($position < ($nummods - 1)) {
1030 $nextmod = $mods[$modids[$position + 1]];
1033 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
1034 $renderer = $this->page->get_renderer('core', 'course');
1035 return $renderer->render($activitynav);
1039 * The standard tags (typically script tags that are not needed earlier) that
1040 * should be output after everything else. Designed to be called in theme layout.php files.
1042 * @return string HTML fragment.
1044 public function standard_end_of_body_html() {
1045 global $CFG;
1047 // This function is normally called from a layout.php file in {@link core_renderer::header()}
1048 // but some of the content won't be known until later, so we return a placeholder
1049 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
1050 $output = '';
1051 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
1052 $output .= "\n".$CFG->additionalhtmlfooter;
1054 $output .= $this->unique_end_html_token;
1055 return $output;
1059 * The standard HTML that should be output just before the <footer> tag.
1060 * Designed to be called in theme layout.php files.
1062 * @return string HTML fragment.
1064 public function standard_after_main_region_html() {
1065 global $CFG;
1066 $output = '';
1067 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlbottomofbody)) {
1068 $output .= "\n".$CFG->additionalhtmlbottomofbody;
1071 // Give subsystems an opportunity to inject extra html content. The callback
1072 // must always return a string containing valid html.
1073 foreach (\core_component::get_core_subsystems() as $name => $path) {
1074 if ($path) {
1075 $output .= component_callback($name, 'standard_after_main_region_html', [], '');
1079 // Give plugins an opportunity to inject extra html content. The callback
1080 // must always return a string containing valid html.
1081 $pluginswithfunction = get_plugins_with_function('standard_after_main_region_html', 'lib.php');
1082 foreach ($pluginswithfunction as $plugins) {
1083 foreach ($plugins as $function) {
1084 $output .= $function();
1088 return $output;
1092 * Return the standard string that says whether you are logged in (and switched
1093 * roles/logged in as another user).
1094 * @param bool $withlinks if false, then don't include any links in the HTML produced.
1095 * If not set, the default is the nologinlinks option from the theme config.php file,
1096 * and if that is not set, then links are included.
1097 * @return string HTML fragment.
1099 public function login_info($withlinks = null) {
1100 global $USER, $CFG, $DB, $SESSION;
1102 if (during_initial_install()) {
1103 return '';
1106 if (is_null($withlinks)) {
1107 $withlinks = empty($this->page->layout_options['nologinlinks']);
1110 $course = $this->page->course;
1111 if (\core\session\manager::is_loggedinas()) {
1112 $realuser = \core\session\manager::get_realuser();
1113 $fullname = fullname($realuser);
1114 if ($withlinks) {
1115 $loginastitle = get_string('loginas');
1116 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
1117 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
1118 } else {
1119 $realuserinfo = " [$fullname] ";
1121 } else {
1122 $realuserinfo = '';
1125 $loginpage = $this->is_login_page();
1126 $loginurl = get_login_url();
1128 if (empty($course->id)) {
1129 // $course->id is not defined during installation
1130 return '';
1131 } else if (isloggedin()) {
1132 $context = context_course::instance($course->id);
1134 $fullname = fullname($USER);
1135 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
1136 if ($withlinks) {
1137 $linktitle = get_string('viewprofile');
1138 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
1139 } else {
1140 $username = $fullname;
1142 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
1143 if ($withlinks) {
1144 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1145 } else {
1146 $username .= " from {$idprovider->name}";
1149 if (isguestuser()) {
1150 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1151 if (!$loginpage && $withlinks) {
1152 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1154 } else if (is_role_switched($course->id)) { // Has switched roles
1155 $rolename = '';
1156 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1157 $rolename = ': '.role_get_name($role, $context);
1159 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1160 if ($withlinks) {
1161 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1162 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1164 } else {
1165 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1166 if ($withlinks) {
1167 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1170 } else {
1171 $loggedinas = get_string('loggedinnot', 'moodle');
1172 if (!$loginpage && $withlinks) {
1173 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1177 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1179 if (isset($SESSION->justloggedin)) {
1180 unset($SESSION->justloggedin);
1181 if (!empty($CFG->displayloginfailures)) {
1182 if (!isguestuser()) {
1183 // Include this file only when required.
1184 require_once($CFG->dirroot . '/user/lib.php');
1185 if ($count = user_count_login_failures($USER)) {
1186 $loggedinas .= '<div class="loginfailures">';
1187 $a = new stdClass();
1188 $a->attempts = $count;
1189 $loggedinas .= get_string('failedloginattempts', '', $a);
1190 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1191 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1192 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1194 $loggedinas .= '</div>';
1200 return $loggedinas;
1204 * Check whether the current page is a login page.
1206 * @since Moodle 2.9
1207 * @return bool
1209 protected function is_login_page() {
1210 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1211 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1212 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1213 return in_array(
1214 $this->page->url->out_as_local_url(false, array()),
1215 array(
1216 '/login/index.php',
1217 '/login/forgot_password.php',
1223 * Return the 'back' link that normally appears in the footer.
1225 * @return string HTML fragment.
1227 public function home_link() {
1228 global $CFG, $SITE;
1230 if ($this->page->pagetype == 'site-index') {
1231 // Special case for site home page - please do not remove
1232 return '<div class="sitelink">' .
1233 '<a title="Moodle" class="d-inline-block aalink" href="http://moodle.org/">' .
1234 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1236 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1237 // Special case for during install/upgrade.
1238 return '<div class="sitelink">'.
1239 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1240 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1242 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1243 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1244 get_string('home') . '</a></div>';
1246 } else {
1247 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1248 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1253 * Redirects the user by any means possible given the current state
1255 * This function should not be called directly, it should always be called using
1256 * the redirect function in lib/weblib.php
1258 * The redirect function should really only be called before page output has started
1259 * however it will allow itself to be called during the state STATE_IN_BODY
1261 * @param string $encodedurl The URL to send to encoded if required
1262 * @param string $message The message to display to the user if any
1263 * @param int $delay The delay before redirecting a user, if $message has been
1264 * set this is a requirement and defaults to 3, set to 0 no delay
1265 * @param boolean $debugdisableredirect this redirect has been disabled for
1266 * debugging purposes. Display a message that explains, and don't
1267 * trigger the redirect.
1268 * @param string $messagetype The type of notification to show the message in.
1269 * See constants on \core\output\notification.
1270 * @return string The HTML to display to the user before dying, may contain
1271 * meta refresh, javascript refresh, and may have set header redirects
1273 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1274 $messagetype = \core\output\notification::NOTIFY_INFO) {
1275 global $CFG;
1276 $url = str_replace('&amp;', '&', $encodedurl);
1278 switch ($this->page->state) {
1279 case moodle_page::STATE_BEFORE_HEADER :
1280 // No output yet it is safe to delivery the full arsenal of redirect methods
1281 if (!$debugdisableredirect) {
1282 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1283 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1284 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1286 $output = $this->header();
1287 break;
1288 case moodle_page::STATE_PRINTING_HEADER :
1289 // We should hopefully never get here
1290 throw new coding_exception('You cannot redirect while printing the page header');
1291 break;
1292 case moodle_page::STATE_IN_BODY :
1293 // We really shouldn't be here but we can deal with this
1294 debugging("You should really redirect before you start page output");
1295 if (!$debugdisableredirect) {
1296 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1298 $output = $this->opencontainers->pop_all_but_last();
1299 break;
1300 case moodle_page::STATE_DONE :
1301 // Too late to be calling redirect now
1302 throw new coding_exception('You cannot redirect after the entire page has been generated');
1303 break;
1305 $output .= $this->notification($message, $messagetype);
1306 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1307 if ($debugdisableredirect) {
1308 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1310 $output .= $this->footer();
1311 return $output;
1315 * Start output by sending the HTTP headers, and printing the HTML <head>
1316 * and the start of the <body>.
1318 * To control what is printed, you should set properties on $PAGE.
1320 * @return string HTML that you must output this, preferably immediately.
1322 public function header() {
1323 global $USER, $CFG, $SESSION;
1325 // Give plugins an opportunity touch things before the http headers are sent
1326 // such as adding additional headers. The return value is ignored.
1327 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1328 foreach ($pluginswithfunction as $plugins) {
1329 foreach ($plugins as $function) {
1330 $function();
1334 if (\core\session\manager::is_loggedinas()) {
1335 $this->page->add_body_class('userloggedinas');
1338 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1339 require_once($CFG->dirroot . '/user/lib.php');
1340 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1341 if ($count = user_count_login_failures($USER, false)) {
1342 $this->page->add_body_class('loginfailures');
1346 // If the user is logged in, and we're not in initial install,
1347 // check to see if the user is role-switched and add the appropriate
1348 // CSS class to the body element.
1349 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1350 $this->page->add_body_class('userswitchedrole');
1353 // Give themes a chance to init/alter the page object.
1354 $this->page->theme->init_page($this->page);
1356 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1358 // Find the appropriate page layout file, based on $this->page->pagelayout.
1359 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1360 // Render the layout using the layout file.
1361 $rendered = $this->render_page_layout($layoutfile);
1363 // Slice the rendered output into header and footer.
1364 $cutpos = strpos($rendered, $this->unique_main_content_token);
1365 if ($cutpos === false) {
1366 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1367 $token = self::MAIN_CONTENT_TOKEN;
1368 } else {
1369 $token = $this->unique_main_content_token;
1372 if ($cutpos === false) {
1373 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.');
1375 $header = substr($rendered, 0, $cutpos);
1376 $footer = substr($rendered, $cutpos + strlen($token));
1378 if (empty($this->contenttype)) {
1379 debugging('The page layout file did not call $OUTPUT->doctype()');
1380 $header = $this->doctype() . $header;
1383 // If this theme version is below 2.4 release and this is a course view page
1384 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1385 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1386 // check if course content header/footer have not been output during render of theme layout
1387 $coursecontentheader = $this->course_content_header(true);
1388 $coursecontentfooter = $this->course_content_footer(true);
1389 if (!empty($coursecontentheader)) {
1390 // display debug message and add header and footer right above and below main content
1391 // Please note that course header and footer (to be displayed above and below the whole page)
1392 // are not displayed in this case at all.
1393 // Besides the content header and footer are not displayed on any other course page
1394 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);
1395 $header .= $coursecontentheader;
1396 $footer = $coursecontentfooter. $footer;
1400 send_headers($this->contenttype, $this->page->cacheable);
1402 $this->opencontainers->push('header/footer', $footer);
1403 $this->page->set_state(moodle_page::STATE_IN_BODY);
1405 // If an activity record has been set, activity_header will handle this.
1406 if (!$this->page->cm || !empty($this->page->layout_options['noactivityheader'])) {
1407 $header .= $this->skip_link_target('maincontent');
1409 return $header;
1413 * Renders and outputs the page layout file.
1415 * This is done by preparing the normal globals available to a script, and
1416 * then including the layout file provided by the current theme for the
1417 * requested layout.
1419 * @param string $layoutfile The name of the layout file
1420 * @return string HTML code
1422 protected function render_page_layout($layoutfile) {
1423 global $CFG, $SITE, $USER;
1424 // The next lines are a bit tricky. The point is, here we are in a method
1425 // of a renderer class, and this object may, or may not, be the same as
1426 // the global $OUTPUT object. When rendering the page layout file, we want to use
1427 // this object. However, people writing Moodle code expect the current
1428 // renderer to be called $OUTPUT, not $this, so define a variable called
1429 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1430 $OUTPUT = $this;
1431 $PAGE = $this->page;
1432 $COURSE = $this->page->course;
1434 ob_start();
1435 include($layoutfile);
1436 $rendered = ob_get_contents();
1437 ob_end_clean();
1438 return $rendered;
1442 * Outputs the page's footer
1444 * @return string HTML fragment
1446 public function footer() {
1447 global $CFG, $DB;
1449 $output = '';
1451 // Give plugins an opportunity to touch the page before JS is finalized.
1452 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1453 foreach ($pluginswithfunction as $plugins) {
1454 foreach ($plugins as $function) {
1455 $extrafooter = $function();
1456 if (is_string($extrafooter)) {
1457 $output .= $extrafooter;
1462 $output .= $this->container_end_all(true);
1464 $footer = $this->opencontainers->pop('header/footer');
1466 if (debugging() and $DB and $DB->is_transaction_started()) {
1467 // TODO: MDL-20625 print warning - transaction will be rolled back
1470 // Provide some performance info if required
1471 $performanceinfo = '';
1472 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1473 $perf = get_performance_info();
1474 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1475 $performanceinfo = $perf['html'];
1479 // We always want performance data when running a performance test, even if the user is redirected to another page.
1480 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1481 $footer = $this->unique_performance_info_token . $footer;
1483 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1485 // Only show notifications when the current page has a context id.
1486 if (!empty($this->page->context->id)) {
1487 $this->page->requires->js_call_amd('core/notification', 'init', array(
1488 $this->page->context->id,
1489 \core\notification::fetch_as_array($this)
1492 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1494 $this->page->set_state(moodle_page::STATE_DONE);
1496 return $output . $footer;
1500 * Close all but the last open container. This is useful in places like error
1501 * handling, where you want to close all the open containers (apart from <body>)
1502 * before outputting the error message.
1504 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1505 * developer debug warning if it isn't.
1506 * @return string the HTML required to close any open containers inside <body>.
1508 public function container_end_all($shouldbenone = false) {
1509 return $this->opencontainers->pop_all_but_last($shouldbenone);
1513 * Returns course-specific information to be output immediately above content on any course page
1514 * (for the current course)
1516 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1517 * @return string
1519 public function course_content_header($onlyifnotcalledbefore = false) {
1520 global $CFG;
1521 static $functioncalled = false;
1522 if ($functioncalled && $onlyifnotcalledbefore) {
1523 // we have already output the content header
1524 return '';
1527 // Output any session notification.
1528 $notifications = \core\notification::fetch();
1530 $bodynotifications = '';
1531 foreach ($notifications as $notification) {
1532 $bodynotifications .= $this->render_from_template(
1533 $notification->get_template_name(),
1534 $notification->export_for_template($this)
1538 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1540 if ($this->page->course->id == SITEID) {
1541 // return immediately and do not include /course/lib.php if not necessary
1542 return $output;
1545 require_once($CFG->dirroot.'/course/lib.php');
1546 $functioncalled = true;
1547 $courseformat = course_get_format($this->page->course);
1548 if (($obj = $courseformat->course_content_header()) !== null) {
1549 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1551 return $output;
1555 * Returns course-specific information to be output immediately below content on any course page
1556 * (for the current course)
1558 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1559 * @return string
1561 public function course_content_footer($onlyifnotcalledbefore = false) {
1562 global $CFG;
1563 if ($this->page->course->id == SITEID) {
1564 // return immediately and do not include /course/lib.php if not necessary
1565 return '';
1567 static $functioncalled = false;
1568 if ($functioncalled && $onlyifnotcalledbefore) {
1569 // we have already output the content footer
1570 return '';
1572 $functioncalled = true;
1573 require_once($CFG->dirroot.'/course/lib.php');
1574 $courseformat = course_get_format($this->page->course);
1575 if (($obj = $courseformat->course_content_footer()) !== null) {
1576 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1578 return '';
1582 * Returns course-specific information to be output on any course page in the header area
1583 * (for the current course)
1585 * @return string
1587 public function course_header() {
1588 global $CFG;
1589 if ($this->page->course->id == SITEID) {
1590 // return immediately and do not include /course/lib.php if not necessary
1591 return '';
1593 require_once($CFG->dirroot.'/course/lib.php');
1594 $courseformat = course_get_format($this->page->course);
1595 if (($obj = $courseformat->course_header()) !== null) {
1596 return $courseformat->get_renderer($this->page)->render($obj);
1598 return '';
1602 * Returns course-specific information to be output on any course page in the footer area
1603 * (for the current course)
1605 * @return string
1607 public function course_footer() {
1608 global $CFG;
1609 if ($this->page->course->id == SITEID) {
1610 // return immediately and do not include /course/lib.php if not necessary
1611 return '';
1613 require_once($CFG->dirroot.'/course/lib.php');
1614 $courseformat = course_get_format($this->page->course);
1615 if (($obj = $courseformat->course_footer()) !== null) {
1616 return $courseformat->get_renderer($this->page)->render($obj);
1618 return '';
1622 * Get the course pattern datauri to show on a course card.
1624 * The datauri is an encoded svg that can be passed as a url.
1625 * @param int $id Id to use when generating the pattern
1626 * @return string datauri
1628 public function get_generated_image_for_id($id) {
1629 $color = $this->get_generated_color_for_id($id);
1630 $pattern = new \core_geopattern();
1631 $pattern->setColor($color);
1632 $pattern->patternbyid($id);
1633 return $pattern->datauri();
1637 * Get the course color to show on a course card.
1639 * @param int $id Id to use when generating the color.
1640 * @return string hex color code.
1642 public function get_generated_color_for_id($id) {
1643 $colornumbers = range(1, 10);
1644 $basecolors = [];
1645 foreach ($colornumbers as $number) {
1646 $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1649 $color = $basecolors[$id % 10];
1650 return $color;
1654 * Returns lang menu or '', this method also checks forcing of languages in courses.
1656 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1658 * @return string The lang menu HTML or empty string
1660 public function lang_menu() {
1661 $languagemenu = new \core\output\language_menu($this->page);
1662 $data = $languagemenu->export_for_single_select($this);
1663 if ($data) {
1664 return $this->render_from_template('core/single_select', $data);
1666 return '';
1670 * Output the row of editing icons for a block, as defined by the controls array.
1672 * @param array $controls an array like {@link block_contents::$controls}.
1673 * @param string $blockid The ID given to the block.
1674 * @return string HTML fragment.
1676 public function block_controls($actions, $blockid = null) {
1677 global $CFG;
1678 if (empty($actions)) {
1679 return '';
1681 $menu = new action_menu($actions);
1682 if ($blockid !== null) {
1683 $menu->set_owner_selector('#'.$blockid);
1685 $menu->set_constraint('.block-region');
1686 $menu->attributes['class'] .= ' block-control-actions commands';
1687 return $this->render($menu);
1691 * Returns the HTML for a basic textarea field.
1693 * @param string $name Name to use for the textarea element
1694 * @param string $id The id to use fort he textarea element
1695 * @param string $value Initial content to display in the textarea
1696 * @param int $rows Number of rows to display
1697 * @param int $cols Number of columns to display
1698 * @return string the HTML to display
1700 public function print_textarea($name, $id, $value, $rows, $cols) {
1701 editors_head_setup();
1702 $editor = editors_get_preferred_editor(FORMAT_HTML);
1703 $editor->set_text($value);
1704 $editor->use_editor($id, []);
1706 $context = [
1707 'id' => $id,
1708 'name' => $name,
1709 'value' => $value,
1710 'rows' => $rows,
1711 'cols' => $cols
1714 return $this->render_from_template('core_form/editor_textarea', $context);
1718 * Renders an action menu component.
1720 * @param action_menu $menu
1721 * @return string HTML
1723 public function render_action_menu(action_menu $menu) {
1725 // We don't want the class icon there!
1726 foreach ($menu->get_secondary_actions() as $action) {
1727 if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1728 $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1732 if ($menu->is_empty()) {
1733 return '';
1735 $context = $menu->export_for_template($this);
1737 return $this->render_from_template('core/action_menu', $context);
1741 * Renders a Check API result
1743 * @param result $result
1744 * @return string HTML fragment
1746 protected function render_check_result(core\check\result $result) {
1747 return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1751 * Renders a Check API result
1753 * @param result $result
1754 * @return string HTML fragment
1756 public function check_result(core\check\result $result) {
1757 return $this->render_check_result($result);
1761 * Renders an action_menu_link item.
1763 * @param action_menu_link $action
1764 * @return string HTML fragment
1766 protected function render_action_menu_link(action_menu_link $action) {
1767 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1771 * Renders a primary action_menu_filler item.
1773 * @param action_menu_link_filler $action
1774 * @return string HTML fragment
1776 protected function render_action_menu_filler(action_menu_filler $action) {
1777 return html_writer::span('&nbsp;', 'filler');
1781 * Renders a primary action_menu_link item.
1783 * @param action_menu_link_primary $action
1784 * @return string HTML fragment
1786 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1787 return $this->render_action_menu_link($action);
1791 * Renders a secondary action_menu_link item.
1793 * @param action_menu_link_secondary $action
1794 * @return string HTML fragment
1796 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1797 return $this->render_action_menu_link($action);
1801 * Prints a nice side block with an optional header.
1803 * @param block_contents $bc HTML for the content
1804 * @param string $region the region the block is appearing in.
1805 * @return string the HTML to be output.
1807 public function block(block_contents $bc, $region) {
1808 $bc = clone($bc); // Avoid messing up the object passed in.
1809 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1810 $bc->collapsible = block_contents::NOT_HIDEABLE;
1813 $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1814 $context = new stdClass();
1815 $context->skipid = $bc->skipid;
1816 $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
1817 $context->dockable = $bc->dockable;
1818 $context->id = $id;
1819 $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1820 $context->skiptitle = strip_tags($bc->title);
1821 $context->showskiplink = !empty($context->skiptitle);
1822 $context->arialabel = $bc->arialabel;
1823 $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
1824 $context->class = $bc->attributes['class'];
1825 $context->type = $bc->attributes['data-block'];
1826 $context->title = $bc->title;
1827 $context->content = $bc->content;
1828 $context->annotation = $bc->annotation;
1829 $context->footer = $bc->footer;
1830 $context->hascontrols = !empty($bc->controls);
1831 if ($context->hascontrols) {
1832 $context->controls = $this->block_controls($bc->controls, $id);
1835 return $this->render_from_template('core/block', $context);
1839 * Render the contents of a block_list.
1841 * @param array $icons the icon for each item.
1842 * @param array $items the content of each item.
1843 * @return string HTML
1845 public function list_block_contents($icons, $items) {
1846 $row = 0;
1847 $lis = array();
1848 foreach ($items as $key => $string) {
1849 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1850 if (!empty($icons[$key])) { //test if the content has an assigned icon
1851 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1853 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1854 $item .= html_writer::end_tag('li');
1855 $lis[] = $item;
1856 $row = 1 - $row; // Flip even/odd.
1858 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1862 * Output all the blocks in a particular region.
1864 * @param string $region the name of a region on this page.
1865 * @param boolean $fakeblocksonly Output fake block only.
1866 * @return string the HTML to be output.
1868 public function blocks_for_region($region, $fakeblocksonly = false) {
1869 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1870 $lastblock = null;
1871 $zones = array();
1872 foreach ($blockcontents as $bc) {
1873 if ($bc instanceof block_contents) {
1874 $zones[] = $bc->title;
1877 $output = '';
1879 foreach ($blockcontents as $bc) {
1880 if ($bc instanceof block_contents) {
1881 if ($fakeblocksonly && !$bc->is_fake()) {
1882 // Skip rendering real blocks if we only want to show fake blocks.
1883 continue;
1885 $output .= $this->block($bc, $region);
1886 $lastblock = $bc->title;
1887 } else if ($bc instanceof block_move_target) {
1888 if (!$fakeblocksonly) {
1889 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1891 } else {
1892 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1895 return $output;
1899 * Output a place where the block that is currently being moved can be dropped.
1901 * @param block_move_target $target with the necessary details.
1902 * @param array $zones array of areas where the block can be moved to
1903 * @param string $previous the block located before the area currently being rendered.
1904 * @param string $region the name of the region
1905 * @return string the HTML to be output.
1907 public function block_move_target($target, $zones, $previous, $region) {
1908 if ($previous == null) {
1909 if (empty($zones)) {
1910 // There are no zones, probably because there are no blocks.
1911 $regions = $this->page->theme->get_all_block_regions();
1912 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1913 } else {
1914 $position = get_string('moveblockbefore', 'block', $zones[0]);
1916 } else {
1917 $position = get_string('moveblockafter', 'block', $previous);
1919 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1923 * Renders a special html link with attached action
1925 * Theme developers: DO NOT OVERRIDE! Please override function
1926 * {@link core_renderer::render_action_link()} instead.
1928 * @param string|moodle_url $url
1929 * @param string $text HTML fragment
1930 * @param component_action $action
1931 * @param array $attributes associative array of html link attributes + disabled
1932 * @param pix_icon optional pix icon to render with the link
1933 * @return string HTML fragment
1935 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1936 if (!($url instanceof moodle_url)) {
1937 $url = new moodle_url($url);
1939 $link = new action_link($url, $text, $action, $attributes, $icon);
1941 return $this->render($link);
1945 * Renders an action_link object.
1947 * The provided link is renderer and the HTML returned. At the same time the
1948 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1950 * @param action_link $link
1951 * @return string HTML fragment
1953 protected function render_action_link(action_link $link) {
1954 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1958 * Renders an action_icon.
1960 * This function uses the {@link core_renderer::action_link()} method for the
1961 * most part. What it does different is prepare the icon as HTML and use it
1962 * as the link text.
1964 * Theme developers: If you want to change how action links and/or icons are rendered,
1965 * consider overriding function {@link core_renderer::render_action_link()} and
1966 * {@link core_renderer::render_pix_icon()}.
1968 * @param string|moodle_url $url A string URL or moodel_url
1969 * @param pix_icon $pixicon
1970 * @param component_action $action
1971 * @param array $attributes associative array of html link attributes + disabled
1972 * @param bool $linktext show title next to image in link
1973 * @return string HTML fragment
1975 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1976 if (!($url instanceof moodle_url)) {
1977 $url = new moodle_url($url);
1979 $attributes = (array)$attributes;
1981 if (empty($attributes['class'])) {
1982 // let ppl override the class via $options
1983 $attributes['class'] = 'action-icon';
1986 $icon = $this->render($pixicon);
1988 if ($linktext) {
1989 $text = $pixicon->attributes['alt'];
1990 } else {
1991 $text = '';
1994 return $this->action_link($url, $text.$icon, $action, $attributes);
1998 * Print a message along with button choices for Continue/Cancel
2000 * If a string or moodle_url is given instead of a single_button, method defaults to post.
2002 * @param string $message The question to ask the user
2003 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
2004 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
2005 * @param array $displayoptions optional extra display options
2006 * @return string HTML fragment
2008 public function confirm($message, $continue, $cancel, array $displayoptions = []) {
2010 // Check existing displayoptions.
2011 $displayoptions['confirmtitle'] = $displayoptions['confirmtitle'] ?? get_string('confirm');
2012 $displayoptions['continuestr'] = $displayoptions['continuestr'] ?? get_string('continue');
2013 $displayoptions['cancelstr'] = $displayoptions['cancelstr'] ?? get_string('cancel');
2015 if ($continue instanceof single_button) {
2016 // ok
2017 $continue->primary = true;
2018 } else if (is_string($continue)) {
2019 $continue = new single_button(new moodle_url($continue), $displayoptions['continuestr'], 'post', true);
2020 } else if ($continue instanceof moodle_url) {
2021 $continue = new single_button($continue, $displayoptions['continuestr'], 'post', true);
2022 } else {
2023 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2026 if ($cancel instanceof single_button) {
2027 // ok
2028 } else if (is_string($cancel)) {
2029 $cancel = new single_button(new moodle_url($cancel), $displayoptions['cancelstr'], 'get');
2030 } else if ($cancel instanceof moodle_url) {
2031 $cancel = new single_button($cancel, $displayoptions['cancelstr'], 'get');
2032 } else {
2033 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2036 $attributes = [
2037 'role'=>'alertdialog',
2038 'aria-labelledby'=>'modal-header',
2039 'aria-describedby'=>'modal-body',
2040 'aria-modal'=>'true'
2043 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
2044 $output .= $this->box_start('modal-content', 'modal-content');
2045 $output .= $this->box_start('modal-header px-3', 'modal-header');
2046 $output .= html_writer::tag('h4', $displayoptions['confirmtitle']);
2047 $output .= $this->box_end();
2048 $attributes = [
2049 'role'=>'alert',
2050 'data-aria-autofocus'=>'true'
2052 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
2053 $output .= html_writer::tag('p', $message);
2054 $output .= $this->box_end();
2055 $output .= $this->box_start('modal-footer', 'modal-footer');
2056 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
2057 $output .= $this->box_end();
2058 $output .= $this->box_end();
2059 $output .= $this->box_end();
2060 return $output;
2064 * Returns a form with a single button.
2066 * Theme developers: DO NOT OVERRIDE! Please override function
2067 * {@link core_renderer::render_single_button()} instead.
2069 * @param string|moodle_url $url
2070 * @param string $label button text
2071 * @param string $method get or post submit method
2072 * @param array $options associative array {disabled, title, etc.}
2073 * @return string HTML fragment
2075 public function single_button($url, $label, $method='post', array $options=null) {
2076 if (!($url instanceof moodle_url)) {
2077 $url = new moodle_url($url);
2079 $button = new single_button($url, $label, $method);
2081 foreach ((array)$options as $key=>$value) {
2082 if (property_exists($button, $key)) {
2083 $button->$key = $value;
2084 } else {
2085 $button->set_attribute($key, $value);
2089 return $this->render($button);
2093 * Renders a single button widget.
2095 * This will return HTML to display a form containing a single button.
2097 * @param single_button $button
2098 * @return string HTML fragment
2100 protected function render_single_button(single_button $button) {
2101 return $this->render_from_template('core/single_button', $button->export_for_template($this));
2105 * Returns a form with a single select widget.
2107 * Theme developers: DO NOT OVERRIDE! Please override function
2108 * {@link core_renderer::render_single_select()} instead.
2110 * @param moodle_url $url form action target, includes hidden fields
2111 * @param string $name name of selection field - the changing parameter in url
2112 * @param array $options list of options
2113 * @param string $selected selected element
2114 * @param array $nothing
2115 * @param string $formid
2116 * @param array $attributes other attributes for the single select
2117 * @return string HTML fragment
2119 public function single_select($url, $name, array $options, $selected = '',
2120 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2121 if (!($url instanceof moodle_url)) {
2122 $url = new moodle_url($url);
2124 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2126 if (array_key_exists('label', $attributes)) {
2127 $select->set_label($attributes['label']);
2128 unset($attributes['label']);
2130 $select->attributes = $attributes;
2132 return $this->render($select);
2136 * Returns a dataformat selection and download form
2138 * @param string $label A text label
2139 * @param moodle_url|string $base The download page url
2140 * @param string $name The query param which will hold the type of the download
2141 * @param array $params Extra params sent to the download page
2142 * @return string HTML fragment
2144 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2146 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2147 $options = array();
2148 foreach ($formats as $format) {
2149 if ($format->is_enabled()) {
2150 $options[] = array(
2151 'value' => $format->name,
2152 'label' => get_string('dataformat', $format->component),
2156 $hiddenparams = array();
2157 foreach ($params as $key => $value) {
2158 $hiddenparams[] = array(
2159 'name' => $key,
2160 'value' => $value,
2163 $data = array(
2164 'label' => $label,
2165 'base' => $base,
2166 'name' => $name,
2167 'params' => $hiddenparams,
2168 'options' => $options,
2169 'sesskey' => sesskey(),
2170 'submit' => get_string('download'),
2173 return $this->render_from_template('core/dataformat_selector', $data);
2178 * Internal implementation of single_select rendering
2180 * @param single_select $select
2181 * @return string HTML fragment
2183 protected function render_single_select(single_select $select) {
2184 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2188 * Returns a form with a url select widget.
2190 * Theme developers: DO NOT OVERRIDE! Please override function
2191 * {@link core_renderer::render_url_select()} instead.
2193 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2194 * @param string $selected selected element
2195 * @param array $nothing
2196 * @param string $formid
2197 * @return string HTML fragment
2199 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2200 $select = new url_select($urls, $selected, $nothing, $formid);
2201 return $this->render($select);
2205 * Internal implementation of url_select rendering
2207 * @param url_select $select
2208 * @return string HTML fragment
2210 protected function render_url_select(url_select $select) {
2211 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2215 * Returns a string containing a link to the user documentation.
2216 * Also contains an icon by default. Shown to teachers and admin only.
2218 * @param string $path The page link after doc root and language, no leading slash.
2219 * @param string $text The text to be displayed for the link
2220 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2221 * @param array $attributes htm attributes
2222 * @return string
2224 public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
2225 global $CFG;
2227 $icon = $this->pix_icon('book', '', 'moodle', array('class' => 'iconhelp icon-pre', 'role' => 'presentation'));
2229 $attributes['href'] = new moodle_url(get_docs_url($path));
2230 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2231 $attributes['class'] = 'helplinkpopup';
2234 return html_writer::tag('a', $icon.$text, $attributes);
2238 * Return HTML for an image_icon.
2240 * Theme developers: DO NOT OVERRIDE! Please override function
2241 * {@link core_renderer::render_image_icon()} instead.
2243 * @param string $pix short pix name
2244 * @param string $alt mandatory alt attribute
2245 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2246 * @param array $attributes htm attributes
2247 * @return string HTML fragment
2249 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2250 $icon = new image_icon($pix, $alt, $component, $attributes);
2251 return $this->render($icon);
2255 * Renders a pix_icon widget and returns the HTML to display it.
2257 * @param image_icon $icon
2258 * @return string HTML fragment
2260 protected function render_image_icon(image_icon $icon) {
2261 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2262 return $system->render_pix_icon($this, $icon);
2266 * Return HTML for a pix_icon.
2268 * Theme developers: DO NOT OVERRIDE! Please override function
2269 * {@link core_renderer::render_pix_icon()} instead.
2271 * @param string $pix short pix name
2272 * @param string $alt mandatory alt attribute
2273 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2274 * @param array $attributes htm lattributes
2275 * @return string HTML fragment
2277 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2278 $icon = new pix_icon($pix, $alt, $component, $attributes);
2279 return $this->render($icon);
2283 * Renders a pix_icon widget and returns the HTML to display it.
2285 * @param pix_icon $icon
2286 * @return string HTML fragment
2288 protected function render_pix_icon(pix_icon $icon) {
2289 $system = \core\output\icon_system::instance();
2290 return $system->render_pix_icon($this, $icon);
2294 * Return HTML to display an emoticon icon.
2296 * @param pix_emoticon $emoticon
2297 * @return string HTML fragment
2299 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2300 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2301 return $system->render_pix_icon($this, $emoticon);
2305 * Produces the html that represents this rating in the UI
2307 * @param rating $rating the page object on which this rating will appear
2308 * @return string
2310 function render_rating(rating $rating) {
2311 global $CFG, $USER;
2313 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2314 return null;//ratings are turned off
2317 $ratingmanager = new rating_manager();
2318 // Initialise the JavaScript so ratings can be done by AJAX.
2319 $ratingmanager->initialise_rating_javascript($this->page);
2321 $strrate = get_string("rate", "rating");
2322 $ratinghtml = ''; //the string we'll return
2324 // permissions check - can they view the aggregate?
2325 if ($rating->user_can_view_aggregate()) {
2327 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2328 $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2329 $aggregatestr = $rating->get_aggregate_string();
2331 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2332 if ($rating->count > 0) {
2333 $countstr = "({$rating->count})";
2334 } else {
2335 $countstr = '-';
2337 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2339 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2341 $nonpopuplink = $rating->get_view_ratings_url();
2342 $popuplink = $rating->get_view_ratings_url(true);
2344 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2345 $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
2348 $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
2351 $formstart = null;
2352 // if the item doesn't belong to the current user, the user has permission to rate
2353 // and we're within the assessable period
2354 if ($rating->user_can_rate()) {
2356 $rateurl = $rating->get_rate_url();
2357 $inputs = $rateurl->params();
2359 //start the rating form
2360 $formattrs = array(
2361 'id' => "postrating{$rating->itemid}",
2362 'class' => 'postratingform',
2363 'method' => 'post',
2364 'action' => $rateurl->out_omit_querystring()
2366 $formstart = html_writer::start_tag('form', $formattrs);
2367 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2369 // add the hidden inputs
2370 foreach ($inputs as $name => $value) {
2371 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2372 $formstart .= html_writer::empty_tag('input', $attributes);
2375 if (empty($ratinghtml)) {
2376 $ratinghtml .= $strrate.': ';
2378 $ratinghtml = $formstart.$ratinghtml;
2380 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2381 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2382 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2383 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2385 //output submit button
2386 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2388 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2389 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2391 if (!$rating->settings->scale->isnumeric) {
2392 // If a global scale, try to find current course ID from the context
2393 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2394 $courseid = $coursecontext->instanceid;
2395 } else {
2396 $courseid = $rating->settings->scale->courseid;
2398 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2400 $ratinghtml .= html_writer::end_tag('span');
2401 $ratinghtml .= html_writer::end_tag('div');
2402 $ratinghtml .= html_writer::end_tag('form');
2405 return $ratinghtml;
2409 * Centered heading with attached help button (same title text)
2410 * and optional icon attached.
2412 * @param string $text A heading text
2413 * @param string $helpidentifier The keyword that defines a help page
2414 * @param string $component component name
2415 * @param string|moodle_url $icon
2416 * @param string $iconalt icon alt text
2417 * @param int $level The level of importance of the heading. Defaulting to 2
2418 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2419 * @return string HTML fragment
2421 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2422 $image = '';
2423 if ($icon) {
2424 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2427 $help = '';
2428 if ($helpidentifier) {
2429 $help = $this->help_icon($helpidentifier, $component);
2432 return $this->heading($image.$text.$help, $level, $classnames);
2436 * Returns HTML to display a help icon.
2438 * @deprecated since Moodle 2.0
2440 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2441 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2445 * Returns HTML to display a help icon.
2447 * Theme developers: DO NOT OVERRIDE! Please override function
2448 * {@link core_renderer::render_help_icon()} instead.
2450 * @param string $identifier The keyword that defines a help page
2451 * @param string $component component name
2452 * @param string|bool $linktext true means use $title as link text, string means link text value
2453 * @return string HTML fragment
2455 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2456 $icon = new help_icon($identifier, $component);
2457 $icon->diag_strings();
2458 if ($linktext === true) {
2459 $icon->linktext = get_string($icon->identifier, $icon->component);
2460 } else if (!empty($linktext)) {
2461 $icon->linktext = $linktext;
2463 return $this->render($icon);
2467 * Implementation of user image rendering.
2469 * @param help_icon $helpicon A help icon instance
2470 * @return string HTML fragment
2472 protected function render_help_icon(help_icon $helpicon) {
2473 $context = $helpicon->export_for_template($this);
2474 return $this->render_from_template('core/help_icon', $context);
2478 * Returns HTML to display a scale help icon.
2480 * @param int $courseid
2481 * @param stdClass $scale instance
2482 * @return string HTML fragment
2484 public function help_icon_scale($courseid, stdClass $scale) {
2485 global $CFG;
2487 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2489 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2491 $scaleid = abs($scale->id);
2493 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2494 $action = new popup_action('click', $link, 'ratingscale');
2496 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2500 * Creates and returns a spacer image with optional line break.
2502 * @param array $attributes Any HTML attributes to add to the spaced.
2503 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2504 * laxy do it with CSS which is a much better solution.
2505 * @return string HTML fragment
2507 public function spacer(array $attributes = null, $br = false) {
2508 $attributes = (array)$attributes;
2509 if (empty($attributes['width'])) {
2510 $attributes['width'] = 1;
2512 if (empty($attributes['height'])) {
2513 $attributes['height'] = 1;
2515 $attributes['class'] = 'spacer';
2517 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2519 if (!empty($br)) {
2520 $output .= '<br />';
2523 return $output;
2527 * Returns HTML to display the specified user's avatar.
2529 * User avatar may be obtained in two ways:
2530 * <pre>
2531 * // Option 1: (shortcut for simple cases, preferred way)
2532 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2533 * $OUTPUT->user_picture($user, array('popup'=>true));
2535 * // Option 2:
2536 * $userpic = new user_picture($user);
2537 * // Set properties of $userpic
2538 * $userpic->popup = true;
2539 * $OUTPUT->render($userpic);
2540 * </pre>
2542 * Theme developers: DO NOT OVERRIDE! Please override function
2543 * {@link core_renderer::render_user_picture()} instead.
2545 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2546 * If any of these are missing, the database is queried. Avoid this
2547 * if at all possible, particularly for reports. It is very bad for performance.
2548 * @param array $options associative array with user picture options, used only if not a user_picture object,
2549 * options are:
2550 * - courseid=$this->page->course->id (course id of user profile in link)
2551 * - size=35 (size of image)
2552 * - link=true (make image clickable - the link leads to user profile)
2553 * - popup=false (open in popup)
2554 * - alttext=true (add image alt attribute)
2555 * - class = image class attribute (default 'userpicture')
2556 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2557 * - includefullname=false (whether to include the user's full name together with the user picture)
2558 * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2559 * @return string HTML fragment
2561 public function user_picture(stdClass $user, array $options = null) {
2562 $userpicture = new user_picture($user);
2563 foreach ((array)$options as $key=>$value) {
2564 if (property_exists($userpicture, $key)) {
2565 $userpicture->$key = $value;
2568 return $this->render($userpicture);
2572 * Internal implementation of user image rendering.
2574 * @param user_picture $userpicture
2575 * @return string
2577 protected function render_user_picture(user_picture $userpicture) {
2578 $user = $userpicture->user;
2579 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
2581 $alt = '';
2582 if ($userpicture->alttext) {
2583 if (!empty($user->imagealt)) {
2584 $alt = $user->imagealt;
2588 if (empty($userpicture->size)) {
2589 $size = 35;
2590 } else if ($userpicture->size === true or $userpicture->size == 1) {
2591 $size = 100;
2592 } else {
2593 $size = $userpicture->size;
2596 $class = $userpicture->class;
2598 if ($user->picture == 0) {
2599 $class .= ' defaultuserpic';
2602 $src = $userpicture->get_url($this->page, $this);
2604 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2605 if (!$userpicture->visibletoscreenreaders) {
2606 $alt = '';
2608 $attributes['alt'] = $alt;
2610 if (!empty($alt)) {
2611 $attributes['title'] = $alt;
2614 // get the image html output first
2615 if ($user->picture == 0 && !defined('BEHAT_SITE_RUNNING')) {
2616 $output = html_writer::tag('span', mb_substr($user->firstname, 0, 1) . mb_substr($user->lastname, 0, 1),
2617 ['class' => 'userinitials size-' . $size]);
2618 } else {
2619 $output = html_writer::empty_tag('img', $attributes);
2622 // Show fullname together with the picture when desired.
2623 if ($userpicture->includefullname) {
2624 $output .= fullname($userpicture->user, $canviewfullnames);
2627 if (empty($userpicture->courseid)) {
2628 $courseid = $this->page->course->id;
2629 } else {
2630 $courseid = $userpicture->courseid;
2632 if ($courseid == SITEID) {
2633 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2634 } else {
2635 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2638 // Then wrap it in link if needed. Also we don't wrap it in link if the link redirects to itself.
2639 if (!$userpicture->link ||
2640 ($this->page->has_set_url() && $this->page->url == $url)) { // Protect against unset page->url.
2641 return $output;
2644 $attributes = array('href' => $url, 'class' => 'd-inline-block aabtn');
2645 if (!$userpicture->visibletoscreenreaders) {
2646 $attributes['tabindex'] = '-1';
2647 $attributes['aria-hidden'] = 'true';
2650 if ($userpicture->popup) {
2651 $id = html_writer::random_id('userpicture');
2652 $attributes['id'] = $id;
2653 $this->add_action_handler(new popup_action('click', $url), $id);
2656 return html_writer::tag('a', $output, $attributes);
2660 * Internal implementation of file tree viewer items rendering.
2662 * @param array $dir
2663 * @return string
2665 public function htmllize_file_tree($dir) {
2666 if (empty($dir['subdirs']) and empty($dir['files'])) {
2667 return '';
2669 $result = '<ul>';
2670 foreach ($dir['subdirs'] as $subdir) {
2671 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2673 foreach ($dir['files'] as $file) {
2674 $filename = $file->get_filename();
2675 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2677 $result .= '</ul>';
2679 return $result;
2683 * Returns HTML to display the file picker
2685 * <pre>
2686 * $OUTPUT->file_picker($options);
2687 * </pre>
2689 * Theme developers: DO NOT OVERRIDE! Please override function
2690 * {@link core_renderer::render_file_picker()} instead.
2692 * @param array $options associative array with file manager options
2693 * options are:
2694 * maxbytes=>-1,
2695 * itemid=>0,
2696 * client_id=>uniqid(),
2697 * acepted_types=>'*',
2698 * return_types=>FILE_INTERNAL,
2699 * context=>current page context
2700 * @return string HTML fragment
2702 public function file_picker($options) {
2703 $fp = new file_picker($options);
2704 return $this->render($fp);
2708 * Internal implementation of file picker rendering.
2710 * @param file_picker $fp
2711 * @return string
2713 public function render_file_picker(file_picker $fp) {
2714 $options = $fp->options;
2715 $client_id = $options->client_id;
2716 $strsaved = get_string('filesaved', 'repository');
2717 $straddfile = get_string('openpicker', 'repository');
2718 $strloading = get_string('loading', 'repository');
2719 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2720 $strdroptoupload = get_string('droptoupload', 'moodle');
2721 $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
2723 $currentfile = $options->currentfile;
2724 if (empty($currentfile)) {
2725 $currentfile = '';
2726 } else {
2727 $currentfile .= ' - ';
2729 if ($options->maxbytes) {
2730 $size = $options->maxbytes;
2731 } else {
2732 $size = get_max_upload_file_size();
2734 if ($size == -1) {
2735 $maxsize = '';
2736 } else {
2737 $maxsize = get_string('maxfilesize', 'moodle', display_size($size, 0));
2739 if ($options->buttonname) {
2740 $buttonname = ' name="' . $options->buttonname . '"';
2741 } else {
2742 $buttonname = '';
2744 $html = <<<EOD
2745 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2746 $iconprogress
2747 </div>
2748 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2749 <div>
2750 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2751 <span> $maxsize </span>
2752 </div>
2753 EOD;
2754 if ($options->env != 'url') {
2755 $html .= <<<EOD
2756 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2757 <div class="filepicker-filename">
2758 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2759 <div class="dndupload-progressbars"></div>
2760 </div>
2761 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2762 </div>
2763 EOD;
2765 $html .= '</div>';
2766 return $html;
2770 * @deprecated since Moodle 3.2
2772 public function update_module_button() {
2773 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2774 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2775 'Themes can choose to display the link in the buttons row consistently for all module types.');
2779 * Returns HTML to display a "Turn editing on/off" button in a form.
2781 * @param moodle_url $url The URL + params to send through when clicking the button
2782 * @return string HTML the button
2784 public function edit_button(moodle_url $url) {
2786 if ($this->page->theme->haseditswitch == true) {
2787 return;
2789 $url->param('sesskey', sesskey());
2790 if ($this->page->user_is_editing()) {
2791 $url->param('edit', 'off');
2792 $editstring = get_string('turneditingoff');
2793 } else {
2794 $url->param('edit', 'on');
2795 $editstring = get_string('turneditingon');
2798 return $this->single_button($url, $editstring);
2802 * Create a navbar switch for toggling editing mode.
2804 * @return string Html containing the edit switch
2806 public function edit_switch() {
2807 if ($this->page->user_allowed_editing()) {
2809 $temp = (object) [
2810 'legacyseturl' => (new moodle_url('/editmode.php'))->out(false),
2811 'pagecontextid' => $this->page->context->id,
2812 'pageurl' => $this->page->url,
2813 'sesskey' => sesskey(),
2815 if ($this->page->user_is_editing()) {
2816 $temp->checked = true;
2818 return $this->render_from_template('core/editswitch', $temp);
2823 * Returns HTML to display a simple button to close a window
2825 * @param string $text The lang string for the button's label (already output from get_string())
2826 * @return string html fragment
2828 public function close_window_button($text='') {
2829 if (empty($text)) {
2830 $text = get_string('closewindow');
2832 $button = new single_button(new moodle_url('#'), $text, 'get');
2833 $button->add_action(new component_action('click', 'close_window'));
2835 return $this->container($this->render($button), 'closewindow');
2839 * Output an error message. By default wraps the error message in <span class="error">.
2840 * If the error message is blank, nothing is output.
2842 * @param string $message the error message.
2843 * @return string the HTML to output.
2845 public function error_text($message) {
2846 if (empty($message)) {
2847 return '';
2849 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2850 return html_writer::tag('span', $message, array('class' => 'error'));
2854 * Do not call this function directly.
2856 * To terminate the current script with a fatal error, call the {@link print_error}
2857 * function, or throw an exception. Doing either of those things will then call this
2858 * function to display the error, before terminating the execution.
2860 * @param string $message The message to output
2861 * @param string $moreinfourl URL where more info can be found about the error
2862 * @param string $link Link for the Continue button
2863 * @param array $backtrace The execution backtrace
2864 * @param string $debuginfo Debugging information
2865 * @return string the HTML to output.
2867 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2868 global $CFG;
2870 $output = '';
2871 $obbuffer = '';
2873 if ($this->has_started()) {
2874 // we can not always recover properly here, we have problems with output buffering,
2875 // html tables, etc.
2876 $output .= $this->opencontainers->pop_all_but_last();
2878 } else {
2879 // It is really bad if library code throws exception when output buffering is on,
2880 // because the buffered text would be printed before our start of page.
2881 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2882 error_reporting(0); // disable notices from gzip compression, etc.
2883 while (ob_get_level() > 0) {
2884 $buff = ob_get_clean();
2885 if ($buff === false) {
2886 break;
2888 $obbuffer .= $buff;
2890 error_reporting($CFG->debug);
2892 // Output not yet started.
2893 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2894 if (empty($_SERVER['HTTP_RANGE'])) {
2895 @header($protocol . ' 404 Not Found');
2896 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2897 // Coax iOS 10 into sending the session cookie.
2898 @header($protocol . ' 403 Forbidden');
2899 } else {
2900 // Must stop byteserving attempts somehow,
2901 // this is weird but Chrome PDF viewer can be stopped only with 407!
2902 @header($protocol . ' 407 Proxy Authentication Required');
2905 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2906 $this->page->set_url('/'); // no url
2907 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2908 $this->page->set_title(get_string('error'));
2909 $this->page->set_heading($this->page->course->fullname);
2910 // No need to display the activity header when encountering an error.
2911 $this->page->activityheader->disable();
2912 $output .= $this->header();
2915 $message = '<p class="errormessage">' . s($message) . '</p>'.
2916 '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
2917 get_string('moreinformation') . '</a></p>';
2918 if (empty($CFG->rolesactive)) {
2919 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2920 //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.
2922 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2924 if ($CFG->debugdeveloper) {
2925 $labelsep = get_string('labelsep', 'langconfig');
2926 if (!empty($debuginfo)) {
2927 $debuginfo = s($debuginfo); // removes all nasty JS
2928 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2929 $label = get_string('debuginfo', 'debug') . $labelsep;
2930 $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
2932 if (!empty($backtrace)) {
2933 $label = get_string('stacktrace', 'debug') . $labelsep;
2934 $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
2936 if ($obbuffer !== '' ) {
2937 $label = get_string('outputbuffer', 'debug') . $labelsep;
2938 $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
2942 if (empty($CFG->rolesactive)) {
2943 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2944 } else if (!empty($link)) {
2945 $output .= $this->continue_button($link);
2948 $output .= $this->footer();
2950 // Padding to encourage IE to display our error page, rather than its own.
2951 $output .= str_repeat(' ', 512);
2953 return $output;
2957 * Output a notification (that is, a status message about something that has just happened).
2959 * Note: \core\notification::add() may be more suitable for your usage.
2961 * @param string $message The message to print out.
2962 * @param ?string $type The type of notification. See constants on \core\output\notification.
2963 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
2964 * @return string the HTML to output.
2966 public function notification($message, $type = null, $closebutton = true) {
2967 $typemappings = [
2968 // Valid types.
2969 'success' => \core\output\notification::NOTIFY_SUCCESS,
2970 'info' => \core\output\notification::NOTIFY_INFO,
2971 'warning' => \core\output\notification::NOTIFY_WARNING,
2972 'error' => \core\output\notification::NOTIFY_ERROR,
2974 // Legacy types mapped to current types.
2975 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2976 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2977 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2978 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2979 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2980 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2981 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2984 $extraclasses = [];
2986 if ($type) {
2987 if (strpos($type, ' ') === false) {
2988 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2989 if (isset($typemappings[$type])) {
2990 $type = $typemappings[$type];
2991 } else {
2992 // The value provided did not match a known type. It must be an extra class.
2993 $extraclasses = [$type];
2995 } else {
2996 // Identify what type of notification this is.
2997 $classarray = explode(' ', self::prepare_classes($type));
2999 // Separate out the type of notification from the extra classes.
3000 foreach ($classarray as $class) {
3001 if (isset($typemappings[$class])) {
3002 $type = $typemappings[$class];
3003 } else {
3004 $extraclasses[] = $class;
3010 $notification = new \core\output\notification($message, $type, $closebutton);
3011 if (count($extraclasses)) {
3012 $notification->set_extra_classes($extraclasses);
3015 // Return the rendered template.
3016 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3020 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3022 public function notify_problem() {
3023 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
3024 'please use \core\notification::add(), or \core\output\notification as required.');
3028 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3030 public function notify_success() {
3031 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
3032 'please use \core\notification::add(), or \core\output\notification as required.');
3036 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3038 public function notify_message() {
3039 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
3040 'please use \core\notification::add(), or \core\output\notification as required.');
3044 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3046 public function notify_redirect() {
3047 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
3048 'please use \core\notification::add(), or \core\output\notification as required.');
3052 * Render a notification (that is, a status message about something that has
3053 * just happened).
3055 * @param \core\output\notification $notification the notification to print out
3056 * @return string the HTML to output.
3058 protected function render_notification(\core\output\notification $notification) {
3059 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3063 * Returns HTML to display a continue button that goes to a particular URL.
3065 * @param string|moodle_url $url The url the button goes to.
3066 * @return string the HTML to output.
3068 public function continue_button($url) {
3069 if (!($url instanceof moodle_url)) {
3070 $url = new moodle_url($url);
3072 $button = new single_button($url, get_string('continue'), 'get', true);
3073 $button->class = 'continuebutton';
3075 return $this->render($button);
3079 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
3081 * Theme developers: DO NOT OVERRIDE! Please override function
3082 * {@link core_renderer::render_paging_bar()} instead.
3084 * @param int $totalcount The total number of entries available to be paged through
3085 * @param int $page The page you are currently viewing
3086 * @param int $perpage The number of entries that should be shown per page
3087 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3088 * @param string $pagevar name of page parameter that holds the page number
3089 * @return string the HTML to output.
3091 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3092 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3093 return $this->render($pb);
3097 * Returns HTML to display the paging bar.
3099 * @param paging_bar $pagingbar
3100 * @return string the HTML to output.
3102 protected function render_paging_bar(paging_bar $pagingbar) {
3103 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3104 $pagingbar->maxdisplay = 10;
3105 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3109 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3111 * @param string $current the currently selected letter.
3112 * @param string $class class name to add to this initial bar.
3113 * @param string $title the name to put in front of this initial bar.
3114 * @param string $urlvar URL parameter name for this initial.
3115 * @param string $url URL object.
3116 * @param array $alpha of letters in the alphabet.
3117 * @return string the HTML to output.
3119 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3120 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3121 return $this->render($ib);
3125 * Internal implementation of initials bar rendering.
3127 * @param initials_bar $initialsbar
3128 * @return string
3130 protected function render_initials_bar(initials_bar $initialsbar) {
3131 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3135 * Output the place a skip link goes to.
3137 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3138 * @return string the HTML to output.
3140 public function skip_link_target($id = null) {
3141 return html_writer::span('', '', array('id' => $id));
3145 * Outputs a heading
3147 * @param string $text The text of the heading
3148 * @param int $level The level of importance of the heading. Defaulting to 2
3149 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3150 * @param string $id An optional ID
3151 * @return string the HTML to output.
3153 public function heading($text, $level = 2, $classes = null, $id = null) {
3154 $level = (integer) $level;
3155 if ($level < 1 or $level > 6) {
3156 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3158 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3162 * Outputs a box.
3164 * @param string $contents The contents of the box
3165 * @param string $classes A space-separated list of CSS classes
3166 * @param string $id An optional ID
3167 * @param array $attributes An array of other attributes to give the box.
3168 * @return string the HTML to output.
3170 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3171 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3175 * Outputs the opening section of a box.
3177 * @param string $classes A space-separated list of CSS classes
3178 * @param string $id An optional ID
3179 * @param array $attributes An array of other attributes to give the box.
3180 * @return string the HTML to output.
3182 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3183 $this->opencontainers->push('box', html_writer::end_tag('div'));
3184 $attributes['id'] = $id;
3185 $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes);
3186 return html_writer::start_tag('div', $attributes);
3190 * Outputs the closing section of a box.
3192 * @return string the HTML to output.
3194 public function box_end() {
3195 return $this->opencontainers->pop('box');
3199 * Outputs a container.
3201 * @param string $contents The contents of the box
3202 * @param string $classes A space-separated list of CSS classes
3203 * @param string $id An optional ID
3204 * @return string the HTML to output.
3206 public function container($contents, $classes = null, $id = null) {
3207 return $this->container_start($classes, $id) . $contents . $this->container_end();
3211 * Outputs the opening section of a container.
3213 * @param string $classes A space-separated list of CSS classes
3214 * @param string $id An optional ID
3215 * @return string the HTML to output.
3217 public function container_start($classes = null, $id = null) {
3218 $this->opencontainers->push('container', html_writer::end_tag('div'));
3219 return html_writer::start_tag('div', array('id' => $id,
3220 'class' => renderer_base::prepare_classes($classes)));
3224 * Outputs the closing section of a container.
3226 * @return string the HTML to output.
3228 public function container_end() {
3229 return $this->opencontainers->pop('container');
3233 * Make nested HTML lists out of the items
3235 * The resulting list will look something like this:
3237 * <pre>
3238 * <<ul>>
3239 * <<li>><div class='tree_item parent'>(item contents)</div>
3240 * <<ul>
3241 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3242 * <</ul>>
3243 * <</li>>
3244 * <</ul>>
3245 * </pre>
3247 * @param array $items
3248 * @param array $attrs html attributes passed to the top ofs the list
3249 * @return string HTML
3251 public function tree_block_contents($items, $attrs = array()) {
3252 // exit if empty, we don't want an empty ul element
3253 if (empty($items)) {
3254 return '';
3256 // array of nested li elements
3257 $lis = array();
3258 foreach ($items as $item) {
3259 // this applies to the li item which contains all child lists too
3260 $content = $item->content($this);
3261 $liclasses = array($item->get_css_type());
3262 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3263 $liclasses[] = 'collapsed';
3265 if ($item->isactive === true) {
3266 $liclasses[] = 'current_branch';
3268 $liattr = array('class'=>join(' ',$liclasses));
3269 // class attribute on the div item which only contains the item content
3270 $divclasses = array('tree_item');
3271 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3272 $divclasses[] = 'branch';
3273 } else {
3274 $divclasses[] = 'leaf';
3276 if (!empty($item->classes) && count($item->classes)>0) {
3277 $divclasses[] = join(' ', $item->classes);
3279 $divattr = array('class'=>join(' ', $divclasses));
3280 if (!empty($item->id)) {
3281 $divattr['id'] = $item->id;
3283 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3284 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3285 $content = html_writer::empty_tag('hr') . $content;
3287 $content = html_writer::tag('li', $content, $liattr);
3288 $lis[] = $content;
3290 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3294 * Returns a search box.
3296 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3297 * @return string HTML with the search form hidden by default.
3299 public function search_box($id = false) {
3300 global $CFG;
3302 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3303 // result in an extra included file for each site, even the ones where global search
3304 // is disabled.
3305 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3306 return '';
3309 $data = [
3310 'action' => new moodle_url('/search/index.php'),
3311 'hiddenfields' => (object) ['name' => 'context', 'value' => $this->page->context->id],
3312 'inputname' => 'q',
3313 'searchstring' => get_string('search'),
3315 return $this->render_from_template('core/search_input_navbar', $data);
3319 * Allow plugins to provide some content to be rendered in the navbar.
3320 * The plugin must define a PLUGIN_render_navbar_output function that returns
3321 * the HTML they wish to add to the navbar.
3323 * @return string HTML for the navbar
3325 public function navbar_plugin_output() {
3326 $output = '';
3328 // Give subsystems an opportunity to inject extra html content. The callback
3329 // must always return a string containing valid html.
3330 foreach (\core_component::get_core_subsystems() as $name => $path) {
3331 if ($path) {
3332 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3336 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3337 foreach ($pluginsfunction as $plugintype => $plugins) {
3338 foreach ($plugins as $pluginfunction) {
3339 $output .= $pluginfunction($this);
3344 return $output;
3348 * Construct a user menu, returning HTML that can be echoed out by a
3349 * layout file.
3351 * @param stdClass $user A user object, usually $USER.
3352 * @param bool $withlinks true if a dropdown should be built.
3353 * @return string HTML fragment.
3355 public function user_menu($user = null, $withlinks = null) {
3356 global $USER, $CFG;
3357 require_once($CFG->dirroot . '/user/lib.php');
3359 if (is_null($user)) {
3360 $user = $USER;
3363 // Note: this behaviour is intended to match that of core_renderer::login_info,
3364 // but should not be considered to be good practice; layout options are
3365 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3366 if (is_null($withlinks)) {
3367 $withlinks = empty($this->page->layout_options['nologinlinks']);
3370 // Add a class for when $withlinks is false.
3371 $usermenuclasses = 'usermenu';
3372 if (!$withlinks) {
3373 $usermenuclasses .= ' withoutlinks';
3376 $returnstr = "";
3378 // If during initial install, return the empty return string.
3379 if (during_initial_install()) {
3380 return $returnstr;
3383 $loginpage = $this->is_login_page();
3384 $loginurl = get_login_url();
3386 // Get some navigation opts.
3387 $opts = user_get_user_navigation_info($user, $this->page);
3389 if (!empty($opts->unauthenticateduser)) {
3390 $returnstr = get_string($opts->unauthenticateduser['content'], 'moodle');
3391 // If not logged in, show the typical not-logged-in string.
3392 if (!$loginpage && (!$opts->unauthenticateduser['guest'] || $withlinks)) {
3393 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3396 return html_writer::div(
3397 html_writer::span(
3398 $returnstr,
3399 'login nav-link'
3401 $usermenuclasses
3405 $avatarclasses = "avatars";
3406 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3407 $usertextcontents = $opts->metadata['userfullname'];
3409 // Other user.
3410 if (!empty($opts->metadata['asotheruser'])) {
3411 $avatarcontents .= html_writer::span(
3412 $opts->metadata['realuseravatar'],
3413 'avatar realuser'
3415 $usertextcontents = $opts->metadata['realuserfullname'];
3416 $usertextcontents .= html_writer::tag(
3417 'span',
3418 get_string(
3419 'loggedinas',
3420 'moodle',
3421 html_writer::span(
3422 $opts->metadata['userfullname'],
3423 'value'
3426 array('class' => 'meta viewingas')
3430 // Role.
3431 if (!empty($opts->metadata['asotherrole'])) {
3432 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3433 $usertextcontents .= html_writer::span(
3434 $opts->metadata['rolename'],
3435 'meta role role-' . $role
3439 // User login failures.
3440 if (!empty($opts->metadata['userloginfail'])) {
3441 $usertextcontents .= html_writer::span(
3442 $opts->metadata['userloginfail'],
3443 'meta loginfailures'
3447 // MNet.
3448 if (!empty($opts->metadata['asmnetuser'])) {
3449 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3450 $usertextcontents .= html_writer::span(
3451 $opts->metadata['mnetidprovidername'],
3452 'meta mnet mnet-' . $mnet
3456 $returnstr .= html_writer::span(
3457 html_writer::span($usertextcontents, 'usertext mr-1') .
3458 html_writer::span($avatarcontents, $avatarclasses),
3459 'userbutton'
3462 // Create a divider (well, a filler).
3463 $divider = new action_menu_filler();
3464 $divider->primary = false;
3466 $am = new action_menu();
3467 $am->set_menu_trigger(
3468 $returnstr,
3469 'nav-link'
3471 $am->set_action_label(get_string('usermenu'));
3472 $am->set_alignment(action_menu::TR, action_menu::BR);
3473 $am->set_nowrap_on_items();
3474 if ($withlinks) {
3475 $navitemcount = count($opts->navitems);
3476 $idx = 0;
3477 foreach ($opts->navitems as $key => $value) {
3479 switch ($value->itemtype) {
3480 case 'divider':
3481 // If the nav item is a divider, add one and skip link processing.
3482 $am->add($divider);
3483 break;
3485 case 'invalid':
3486 // Silently skip invalid entries (should we post a notification?).
3487 break;
3489 case 'link':
3490 // Process this as a link item.
3491 $pix = null;
3492 if (isset($value->pix) && !empty($value->pix)) {
3493 $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
3494 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3495 $value->title = html_writer::img(
3496 $value->imgsrc,
3497 $value->title,
3498 array('class' => 'iconsmall')
3499 ) . $value->title;
3502 $al = new action_menu_link_secondary(
3503 $value->url,
3504 $pix,
3505 $value->title,
3506 array('class' => 'icon')
3508 if (!empty($value->titleidentifier)) {
3509 $al->attributes['data-title'] = $value->titleidentifier;
3511 $am->add($al);
3512 break;
3515 $idx++;
3517 // Add dividers after the first item and before the last item.
3518 if ($idx == 1 || $idx == $navitemcount - 1) {
3519 $am->add($divider);
3524 return html_writer::div(
3525 $this->render($am),
3526 $usermenuclasses
3531 * Secure layout login info.
3533 * @return string
3535 public function secure_layout_login_info() {
3536 if (get_config('core', 'logininfoinsecurelayout')) {
3537 return $this->login_info(false);
3538 } else {
3539 return '';
3544 * Returns the language menu in the secure layout.
3546 * No custom menu items are passed though, such that it will render only the language selection.
3548 * @return string
3550 public function secure_layout_language_menu() {
3551 if (get_config('core', 'langmenuinsecurelayout')) {
3552 $custommenu = new custom_menu('', current_language());
3553 return $this->render_custom_menu($custommenu);
3554 } else {
3555 return '';
3560 * This renders the navbar.
3561 * Uses bootstrap compatible html.
3563 public function navbar() {
3564 return $this->render_from_template('core/navbar', $this->page->navbar);
3568 * Renders a breadcrumb navigation node object.
3570 * @param breadcrumb_navigation_node $item The navigation node to render.
3571 * @return string HTML fragment
3573 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3575 if ($item->action instanceof moodle_url) {
3576 $content = $item->get_content();
3577 $title = $item->get_title();
3578 $attributes = array();
3579 $attributes['itemprop'] = 'url';
3580 if ($title !== '') {
3581 $attributes['title'] = $title;
3583 if ($item->hidden) {
3584 $attributes['class'] = 'dimmed_text';
3586 if ($item->is_last()) {
3587 $attributes['aria-current'] = 'page';
3589 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3590 $content = html_writer::link($item->action, $content, $attributes);
3592 $attributes = array();
3593 $attributes['itemscope'] = '';
3594 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3595 $content = html_writer::tag('span', $content, $attributes);
3597 } else {
3598 $content = $this->render_navigation_node($item);
3600 return $content;
3604 * Renders a navigation node object.
3606 * @param navigation_node $item The navigation node to render.
3607 * @return string HTML fragment
3609 protected function render_navigation_node(navigation_node $item) {
3610 $content = $item->get_content();
3611 $title = $item->get_title();
3612 if ($item->icon instanceof renderable && !$item->hideicon) {
3613 $icon = $this->render($item->icon);
3614 $content = $icon.$content; // use CSS for spacing of icons
3616 if ($item->helpbutton !== null) {
3617 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3619 if ($content === '') {
3620 return '';
3622 if ($item->action instanceof action_link) {
3623 $link = $item->action;
3624 if ($item->hidden) {
3625 $link->add_class('dimmed');
3627 if (!empty($content)) {
3628 // Providing there is content we will use that for the link content.
3629 $link->text = $content;
3631 $content = $this->render($link);
3632 } else if ($item->action instanceof moodle_url) {
3633 $attributes = array();
3634 if ($title !== '') {
3635 $attributes['title'] = $title;
3637 if ($item->hidden) {
3638 $attributes['class'] = 'dimmed_text';
3640 $content = html_writer::link($item->action, $content, $attributes);
3642 } else if (is_string($item->action) || empty($item->action)) {
3643 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3644 if ($title !== '') {
3645 $attributes['title'] = $title;
3647 if ($item->hidden) {
3648 $attributes['class'] = 'dimmed_text';
3650 $content = html_writer::tag('span', $content, $attributes);
3652 return $content;
3656 * Accessibility: Right arrow-like character is
3657 * used in the breadcrumb trail, course navigation menu
3658 * (previous/next activity), calendar, and search forum block.
3659 * If the theme does not set characters, appropriate defaults
3660 * are set automatically. Please DO NOT
3661 * use &lt; &gt; &raquo; - these are confusing for blind users.
3663 * @return string
3665 public function rarrow() {
3666 return $this->page->theme->rarrow;
3670 * Accessibility: Left arrow-like character is
3671 * used in the breadcrumb trail, course navigation menu
3672 * (previous/next activity), calendar, and search forum block.
3673 * If the theme does not set characters, appropriate defaults
3674 * are set automatically. Please DO NOT
3675 * use &lt; &gt; &raquo; - these are confusing for blind users.
3677 * @return string
3679 public function larrow() {
3680 return $this->page->theme->larrow;
3684 * Accessibility: Up arrow-like character is used in
3685 * the book heirarchical navigation.
3686 * If the theme does not set characters, appropriate defaults
3687 * are set automatically. Please DO NOT
3688 * use ^ - this is confusing for blind users.
3690 * @return string
3692 public function uarrow() {
3693 return $this->page->theme->uarrow;
3697 * Accessibility: Down arrow-like character.
3698 * If the theme does not set characters, appropriate defaults
3699 * are set automatically.
3701 * @return string
3703 public function darrow() {
3704 return $this->page->theme->darrow;
3708 * Returns the custom menu if one has been set
3710 * A custom menu can be configured by browsing to
3711 * Settings: Administration > Appearance > Themes > Theme settings
3712 * and then configuring the custommenu config setting as described.
3714 * Theme developers: DO NOT OVERRIDE! Please override function
3715 * {@link core_renderer::render_custom_menu()} instead.
3717 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3718 * @return string
3720 public function custom_menu($custommenuitems = '') {
3721 global $CFG;
3723 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3724 $custommenuitems = $CFG->custommenuitems;
3726 $custommenu = new custom_menu($custommenuitems, current_language());
3727 return $this->render_custom_menu($custommenu);
3731 * We want to show the custom menus as a list of links in the footer on small screens.
3732 * Just return the menu object exported so we can render it differently.
3734 public function custom_menu_flat() {
3735 global $CFG;
3736 $custommenuitems = '';
3738 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3739 $custommenuitems = $CFG->custommenuitems;
3741 $custommenu = new custom_menu($custommenuitems, current_language());
3742 $langs = get_string_manager()->get_list_of_translations();
3743 $haslangmenu = $this->lang_menu() != '';
3745 if ($haslangmenu) {
3746 $strlang = get_string('language');
3747 $currentlang = current_language();
3748 if (isset($langs[$currentlang])) {
3749 $currentlang = $langs[$currentlang];
3750 } else {
3751 $currentlang = $strlang;
3753 $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3754 foreach ($langs as $langtype => $langname) {
3755 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3759 return $custommenu->export_for_template($this);
3763 * Renders a custom menu object (located in outputcomponents.php)
3765 * The custom menu this method produces makes use of the YUI3 menunav widget
3766 * and requires very specific html elements and classes.
3768 * @staticvar int $menucount
3769 * @param custom_menu $menu
3770 * @return string
3772 protected function render_custom_menu(custom_menu $menu) {
3773 global $CFG;
3775 $langs = get_string_manager()->get_list_of_translations();
3776 $haslangmenu = $this->lang_menu() != '';
3778 if (!$menu->has_children() && !$haslangmenu) {
3779 return '';
3782 if ($haslangmenu) {
3783 $strlang = get_string('language');
3784 $currentlang = current_language();
3785 if (isset($langs[$currentlang])) {
3786 $currentlang = $langs[$currentlang];
3787 } else {
3788 $currentlang = $strlang;
3790 $this->language = $menu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3791 foreach ($langs as $langtype => $langname) {
3792 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3796 $content = '';
3797 foreach ($menu->get_children() as $item) {
3798 $context = $item->export_for_template($this);
3799 $content .= $this->render_from_template('core/custom_menu_item', $context);
3802 return $content;
3806 * Renders a custom menu node as part of a submenu
3808 * The custom menu this method produces makes use of the YUI3 menunav widget
3809 * and requires very specific html elements and classes.
3811 * @see core:renderer::render_custom_menu()
3813 * @staticvar int $submenucount
3814 * @param custom_menu_item $menunode
3815 * @return string
3817 protected function render_custom_menu_item(custom_menu_item $menunode) {
3818 // Required to ensure we get unique trackable id's
3819 static $submenucount = 0;
3820 if ($menunode->has_children()) {
3821 // If the child has menus render it as a sub menu
3822 $submenucount++;
3823 $content = html_writer::start_tag('li');
3824 if ($menunode->get_url() !== null) {
3825 $url = $menunode->get_url();
3826 } else {
3827 $url = '#cm_submenu_'.$submenucount;
3829 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3830 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3831 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3832 $content .= html_writer::start_tag('ul');
3833 foreach ($menunode->get_children() as $menunode) {
3834 $content .= $this->render_custom_menu_item($menunode);
3836 $content .= html_writer::end_tag('ul');
3837 $content .= html_writer::end_tag('div');
3838 $content .= html_writer::end_tag('div');
3839 $content .= html_writer::end_tag('li');
3840 } else {
3841 // The node doesn't have children so produce a final menuitem.
3842 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3843 $content = '';
3844 if (preg_match("/^#+$/", $menunode->get_text())) {
3846 // This is a divider.
3847 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3848 } else {
3849 $content = html_writer::start_tag(
3850 'li',
3851 array(
3852 'class' => 'yui3-menuitem'
3855 if ($menunode->get_url() !== null) {
3856 $url = $menunode->get_url();
3857 } else {
3858 $url = '#';
3860 $content .= html_writer::link(
3861 $url,
3862 $menunode->get_text(),
3863 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3866 $content .= html_writer::end_tag('li');
3868 // Return the sub menu
3869 return $content;
3873 * Renders theme links for switching between default and other themes.
3875 * @return string
3877 protected function theme_switch_links() {
3879 $actualdevice = core_useragent::get_device_type();
3880 $currentdevice = $this->page->devicetypeinuse;
3881 $switched = ($actualdevice != $currentdevice);
3883 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3884 // The user is using the a default device and hasn't switched so don't shown the switch
3885 // device links.
3886 return '';
3889 if ($switched) {
3890 $linktext = get_string('switchdevicerecommended');
3891 $devicetype = $actualdevice;
3892 } else {
3893 $linktext = get_string('switchdevicedefault');
3894 $devicetype = 'default';
3896 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3898 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3899 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3900 $content .= html_writer::end_tag('div');
3902 return $content;
3906 * Renders tabs
3908 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3910 * Theme developers: In order to change how tabs are displayed please override functions
3911 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3913 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3914 * @param string|null $selected which tab to mark as selected, all parent tabs will
3915 * automatically be marked as activated
3916 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3917 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3918 * @return string
3920 public final function tabtree($tabs, $selected = null, $inactive = null) {
3921 return $this->render(new tabtree($tabs, $selected, $inactive));
3925 * Renders tabtree
3927 * @param tabtree $tabtree
3928 * @return string
3930 protected function render_tabtree(tabtree $tabtree) {
3931 if (empty($tabtree->subtree)) {
3932 return '';
3934 $data = $tabtree->export_for_template($this);
3935 return $this->render_from_template('core/tabtree', $data);
3939 * Renders tabobject (part of tabtree)
3941 * This function is called from {@link core_renderer::render_tabtree()}
3942 * and also it calls itself when printing the $tabobject subtree recursively.
3944 * Property $tabobject->level indicates the number of row of tabs.
3946 * @param tabobject $tabobject
3947 * @return string HTML fragment
3949 protected function render_tabobject(tabobject $tabobject) {
3950 $str = '';
3952 // Print name of the current tab.
3953 if ($tabobject instanceof tabtree) {
3954 // No name for tabtree root.
3955 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3956 // Tab name without a link. The <a> tag is used for styling.
3957 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3958 } else {
3959 // Tab name with a link.
3960 if (!($tabobject->link instanceof moodle_url)) {
3961 // backward compartibility when link was passed as quoted string
3962 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3963 } else {
3964 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3968 if (empty($tabobject->subtree)) {
3969 if ($tabobject->selected) {
3970 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3972 return $str;
3975 // Print subtree.
3976 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
3977 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3978 $cnt = 0;
3979 foreach ($tabobject->subtree as $tab) {
3980 $liclass = '';
3981 if (!$cnt) {
3982 $liclass .= ' first';
3984 if ($cnt == count($tabobject->subtree) - 1) {
3985 $liclass .= ' last';
3987 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3988 $liclass .= ' onerow';
3991 if ($tab->selected) {
3992 $liclass .= ' here selected';
3993 } else if ($tab->activated) {
3994 $liclass .= ' here active';
3997 // This will recursively call function render_tabobject() for each item in subtree.
3998 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3999 $cnt++;
4001 $str .= html_writer::end_tag('ul');
4004 return $str;
4008 * Get the HTML for blocks in the given region.
4010 * @since Moodle 2.5.1 2.6
4011 * @param string $region The region to get HTML for.
4012 * @param array $classes Wrapping tag classes.
4013 * @param string $tag Wrapping tag.
4014 * @param boolean $fakeblocksonly Include fake blocks only.
4015 * @return string HTML.
4017 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
4018 $displayregion = $this->page->apply_theme_region_manipulations($region);
4019 $classes = (array)$classes;
4020 $classes[] = 'block-region';
4021 $attributes = array(
4022 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
4023 'class' => join(' ', $classes),
4024 'data-blockregion' => $displayregion,
4025 'data-droptarget' => '1'
4027 if ($this->page->blocks->region_has_content($displayregion, $this)) {
4028 $content = $this->blocks_for_region($displayregion, $fakeblocksonly);
4029 } else {
4030 $content = '';
4032 return html_writer::tag($tag, $content, $attributes);
4036 * Renders a custom block region.
4038 * Use this method if you want to add an additional block region to the content of the page.
4039 * Please note this should only be used in special situations.
4040 * We want to leave the theme is control where ever possible!
4042 * This method must use the same method that the theme uses within its layout file.
4043 * As such it asks the theme what method it is using.
4044 * It can be one of two values, blocks or blocks_for_region (deprecated).
4046 * @param string $regionname The name of the custom region to add.
4047 * @return string HTML for the block region.
4049 public function custom_block_region($regionname) {
4050 if ($this->page->theme->get_block_render_method() === 'blocks') {
4051 return $this->blocks($regionname);
4052 } else {
4053 return $this->blocks_for_region($regionname);
4058 * Returns the CSS classes to apply to the body tag.
4060 * @since Moodle 2.5.1 2.6
4061 * @param array $additionalclasses Any additional classes to apply.
4062 * @return string
4064 public function body_css_classes(array $additionalclasses = array()) {
4065 return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses);
4069 * The ID attribute to apply to the body tag.
4071 * @since Moodle 2.5.1 2.6
4072 * @return string
4074 public function body_id() {
4075 return $this->page->bodyid;
4079 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4081 * @since Moodle 2.5.1 2.6
4082 * @param string|array $additionalclasses Any additional classes to give the body tag,
4083 * @return string
4085 public function body_attributes($additionalclasses = array()) {
4086 if (!is_array($additionalclasses)) {
4087 $additionalclasses = explode(' ', $additionalclasses);
4089 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4093 * Gets HTML for the page heading.
4095 * @since Moodle 2.5.1 2.6
4096 * @param string $tag The tag to encase the heading in. h1 by default.
4097 * @return string HTML.
4099 public function page_heading($tag = 'h1') {
4100 return html_writer::tag($tag, $this->page->heading);
4104 * Gets the HTML for the page heading button.
4106 * @since Moodle 2.5.1 2.6
4107 * @return string HTML.
4109 public function page_heading_button() {
4110 return $this->page->button;
4114 * Returns the Moodle docs link to use for this page.
4116 * @since Moodle 2.5.1 2.6
4117 * @param string $text
4118 * @return string
4120 public function page_doc_link($text = null) {
4121 if ($text === null) {
4122 $text = get_string('moodledocslink');
4124 $path = page_get_doc_link_path($this->page);
4125 if (!$path) {
4126 return '';
4128 return $this->doc_link($path, $text);
4132 * Returns the HTML for the site support email link
4134 * @return string The html code for the support email link.
4136 public function supportemail(): string {
4137 global $CFG;
4139 if (empty($CFG->supportemail)) {
4140 return '';
4143 $supportemail = $CFG->supportemail;
4144 $label = get_string('contactsitesupport', 'admin');
4145 $icon = $this->pix_icon('t/email', '', 'moodle', ['class' => 'iconhelp icon-pre']);
4146 return html_writer::tag('a', $icon . $label, ['href' => 'mailto:' . $supportemail]);
4150 * Returns the services and support link for the help pop-up.
4152 * @return string
4154 public function services_support_link(): string {
4155 global $CFG;
4157 if ((isset($CFG->showservicesandsupportcontent) && $CFG->showservicesandsupportcontent == false) || !is_siteadmin()) {
4158 return '';
4161 $liferingicon = $this->pix_icon('t/life-ring', '', 'moodle', ['class' => 'fa fa-life-ring']);
4162 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle',
4163 ['class' => 'fa fa-externallink fa-fw']);
4164 $link = 'https://moodle.com/help/?utm_source=CTA-banner&utm_medium=platform&utm_campaign=name~Moodle4+cat~lms+mp~no';
4165 $content = $liferingicon . get_string('moodleservicesandsupport') . $newwindowicon;
4167 return html_writer::tag('a', $content, ['target' => '_blank', 'href' => $link]);
4171 * Helper function to decide whether to show the help popover header or not.
4173 * @return bool
4175 public function has_popover_links(): bool {
4176 return !empty($this->services_support_link()) || !empty($this->page_doc_link()) || !empty($this->supportemail());
4180 * Returns the page heading menu.
4182 * @since Moodle 2.5.1 2.6
4183 * @return string HTML.
4185 public function page_heading_menu() {
4186 return $this->page->headingmenu;
4190 * Returns the title to use on the page.
4192 * @since Moodle 2.5.1 2.6
4193 * @return string
4195 public function page_title() {
4196 return $this->page->title;
4200 * Returns the moodle_url for the favicon.
4202 * @since Moodle 2.5.1 2.6
4203 * @return moodle_url The moodle_url for the favicon
4205 public function favicon() {
4206 return $this->image_url('favicon', 'theme');
4210 * Renders preferences groups.
4212 * @param preferences_groups $renderable The renderable
4213 * @return string The output.
4215 public function render_preferences_groups(preferences_groups $renderable) {
4216 return $this->render_from_template('core/preferences_groups', $renderable);
4220 * Renders preferences group.
4222 * @param preferences_group $renderable The renderable
4223 * @return string The output.
4225 public function render_preferences_group(preferences_group $renderable) {
4226 $html = '';
4227 $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4228 $html .= $this->heading($renderable->title, 3);
4229 $html .= html_writer::start_tag('ul');
4230 foreach ($renderable->nodes as $node) {
4231 if ($node->has_children()) {
4232 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4234 $html .= html_writer::tag('li', $this->render($node));
4236 $html .= html_writer::end_tag('ul');
4237 $html .= html_writer::end_tag('div');
4238 return $html;
4241 public function context_header($headerinfo = null, $headinglevel = 1) {
4242 global $DB, $USER, $CFG, $SITE;
4243 require_once($CFG->dirroot . '/user/lib.php');
4244 $context = $this->page->context;
4245 $heading = null;
4246 $imagedata = null;
4247 $subheader = null;
4248 $userbuttons = null;
4250 // Make sure to use the heading if it has been set.
4251 if (isset($headerinfo['heading'])) {
4252 $heading = $headerinfo['heading'];
4253 } else {
4254 $heading = $this->page->heading;
4257 // The user context currently has images and buttons. Other contexts may follow.
4258 if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
4259 if (isset($headerinfo['user'])) {
4260 $user = $headerinfo['user'];
4261 } else {
4262 // Look up the user information if it is not supplied.
4263 $user = $DB->get_record('user', array('id' => $context->instanceid));
4266 // If the user context is set, then use that for capability checks.
4267 if (isset($headerinfo['usercontext'])) {
4268 $context = $headerinfo['usercontext'];
4271 // Only provide user information if the user is the current user, or a user which the current user can view.
4272 // When checking user_can_view_profile(), either:
4273 // If the page context is course, check the course context (from the page object) or;
4274 // If page context is NOT course, then check across all courses.
4275 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4277 if (user_can_view_profile($user, $course)) {
4278 // Use the user's full name if the heading isn't set.
4279 if (empty($heading)) {
4280 $heading = fullname($user);
4283 $imagedata = $this->user_picture($user, array('size' => 100));
4285 // Check to see if we should be displaying a message button.
4286 if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
4287 $userbuttons = array(
4288 'messages' => array(
4289 'buttontype' => 'message',
4290 'title' => get_string('message', 'message'),
4291 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4292 'image' => 'message',
4293 'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
4294 'page' => $this->page
4298 if ($USER->id != $user->id) {
4299 $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4300 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4301 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4302 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4303 $userbuttons['togglecontact'] = array(
4304 'buttontype' => 'togglecontact',
4305 'title' => get_string($contacttitle, 'message'),
4306 'url' => new moodle_url('/message/index.php', array(
4307 'user1' => $USER->id,
4308 'user2' => $user->id,
4309 $contacturlaction => $user->id,
4310 'sesskey' => sesskey())
4312 'image' => $contactimage,
4313 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4314 'page' => $this->page
4318 } else {
4319 $heading = null;
4324 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4325 return $this->render_context_header($contextheader);
4329 * Renders the skip links for the page.
4331 * @param array $links List of skip links.
4332 * @return string HTML for the skip links.
4334 public function render_skip_links($links) {
4335 $context = [ 'links' => []];
4337 foreach ($links as $url => $text) {
4338 $context['links'][] = [ 'url' => $url, 'text' => $text];
4341 return $this->render_from_template('core/skip_links', $context);
4345 * Renders the header bar.
4347 * @param context_header $contextheader Header bar object.
4348 * @return string HTML for the header bar.
4350 protected function render_context_header(context_header $contextheader) {
4352 // Generate the heading first and before everything else as we might have to do an early return.
4353 if (!isset($contextheader->heading)) {
4354 $heading = $this->heading($this->page->heading, $contextheader->headinglevel);
4355 } else {
4356 $heading = $this->heading($contextheader->heading, $contextheader->headinglevel);
4359 $showheader = empty($this->page->layout_options['nocontextheader']);
4360 if (!$showheader) {
4361 // Return the heading wrapped in an sr-only element so it is only visible to screen-readers.
4362 return html_writer::div($heading, 'sr-only');
4365 // All the html stuff goes here.
4366 $html = html_writer::start_div('page-context-header');
4368 // Image data.
4369 if (isset($contextheader->imagedata)) {
4370 // Header specific image.
4371 $html .= html_writer::div($contextheader->imagedata, 'page-header-image icon-size-7');
4374 // Headings.
4375 if (isset($contextheader->prefix)) {
4376 $prefix = html_writer::div($contextheader->prefix, 'text-muted');
4377 $heading = $prefix . $heading;
4379 $html .= html_writer::tag('div', $heading, array('class' => 'page-header-headings'));
4381 // Buttons.
4382 if (isset($contextheader->additionalbuttons)) {
4383 $html .= html_writer::start_div('btn-group header-button-group');
4384 foreach ($contextheader->additionalbuttons as $button) {
4385 if (!isset($button->page)) {
4386 // Include js for messaging.
4387 if ($button['buttontype'] === 'togglecontact') {
4388 \core_message\helper::togglecontact_requirejs();
4390 if ($button['buttontype'] === 'message') {
4391 \core_message\helper::messageuser_requirejs();
4393 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4394 'class' => 'iconsmall',
4395 'role' => 'presentation'
4397 $image .= html_writer::span($button['title'], 'header-button-title');
4398 } else {
4399 $image = html_writer::empty_tag('img', array(
4400 'src' => $button['formattedimage'],
4401 'role' => 'presentation'
4404 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4406 $html .= html_writer::end_div();
4408 $html .= html_writer::end_div();
4410 return $html;
4414 * Wrapper for header elements.
4416 * @return string HTML to display the main header.
4418 public function full_header() {
4419 $pagetype = $this->page->pagetype;
4420 $homepage = get_home_page();
4421 $homepagetype = null;
4422 // Add a special case since /my/courses is a part of the /my subsystem.
4423 if ($homepage == HOMEPAGE_MY && $this->page->title !== get_string('mycourses')) {
4424 $homepagetype = 'my-index';
4425 } else if ($homepage == HOMEPAGE_SITE) {
4426 $homepagetype = 'site-index';
4428 if ($this->page->include_region_main_settings_in_header_actions() &&
4429 !$this->page->blocks->is_block_present('settings')) {
4430 // Only include the region main settings if the page has requested it and it doesn't already have
4431 // the settings block on it. The region main settings are included in the settings block and
4432 // duplicating the content causes behat failures.
4433 $this->page->add_header_action(html_writer::div(
4434 $this->region_main_settings_menu(),
4435 'd-print-none',
4436 ['id' => 'region-main-settings-menu']
4440 $header = new stdClass();
4441 $header->settingsmenu = $this->context_header_settings_menu();
4442 $header->contextheader = $this->context_header();
4443 $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
4444 $header->navbar = $this->navbar();
4445 $header->pageheadingbutton = $this->page_heading_button();
4446 $header->courseheader = $this->course_header();
4447 $header->headeractions = $this->page->get_header_actions();
4448 if (!empty($pagetype) && !empty($homepagetype) && $pagetype == $homepagetype) {
4449 $header->welcomemessage = \core_user::welcome_message();
4451 return $this->render_from_template('core/full_header', $header);
4455 * This is an optional menu that can be added to a layout by a theme. It contains the
4456 * menu for the course administration, only on the course main page.
4458 * @return string
4460 public function context_header_settings_menu() {
4461 $context = $this->page->context;
4462 $menu = new action_menu();
4464 $items = $this->page->navbar->get_items();
4465 $currentnode = end($items);
4467 $showcoursemenu = false;
4468 $showfrontpagemenu = false;
4469 $showusermenu = false;
4471 // We are on the course home page.
4472 if (($context->contextlevel == CONTEXT_COURSE) &&
4473 !empty($currentnode) &&
4474 ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
4475 $showcoursemenu = true;
4478 $courseformat = course_get_format($this->page->course);
4479 // This is a single activity course format, always show the course menu on the activity main page.
4480 if ($context->contextlevel == CONTEXT_MODULE &&
4481 !$courseformat->has_view_page()) {
4483 $this->page->navigation->initialise();
4484 $activenode = $this->page->navigation->find_active_node();
4485 // If the settings menu has been forced then show the menu.
4486 if ($this->page->is_settings_menu_forced()) {
4487 $showcoursemenu = true;
4488 } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
4489 $activenode->type == navigation_node::TYPE_RESOURCE)) {
4491 // We only want to show the menu on the first page of the activity. This means
4492 // the breadcrumb has no additional nodes.
4493 if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
4494 $showcoursemenu = true;
4499 // This is the site front page.
4500 if ($context->contextlevel == CONTEXT_COURSE &&
4501 !empty($currentnode) &&
4502 $currentnode->key === 'home') {
4503 $showfrontpagemenu = true;
4506 // This is the user profile page.
4507 if ($context->contextlevel == CONTEXT_USER &&
4508 !empty($currentnode) &&
4509 ($currentnode->key === 'myprofile')) {
4510 $showusermenu = true;
4513 if ($showfrontpagemenu) {
4514 $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
4515 if ($settingsnode) {
4516 // Build an action menu based on the visible nodes from this navigation tree.
4517 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4519 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4520 if ($skipped) {
4521 $text = get_string('morenavigationlinks');
4522 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4523 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4524 $menu->add_secondary_action($link);
4527 } else if ($showcoursemenu) {
4528 $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
4529 if ($settingsnode) {
4530 // Build an action menu based on the visible nodes from this navigation tree.
4531 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4533 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4534 if ($skipped) {
4535 $text = get_string('morenavigationlinks');
4536 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4537 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4538 $menu->add_secondary_action($link);
4541 } else if ($showusermenu) {
4542 // Get the course admin node from the settings navigation.
4543 $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
4544 if ($settingsnode) {
4545 // Build an action menu based on the visible nodes from this navigation tree.
4546 $this->build_action_menu_from_navigation($menu, $settingsnode);
4550 return $this->render($menu);
4554 * Take a node in the nav tree and make an action menu out of it.
4555 * The links are injected in the action menu.
4557 * @param action_menu $menu
4558 * @param navigation_node $node
4559 * @param boolean $indent
4560 * @param boolean $onlytopleafnodes
4561 * @return boolean nodesskipped - True if nodes were skipped in building the menu
4563 protected function build_action_menu_from_navigation(action_menu $menu,
4564 navigation_node $node,
4565 $indent = false,
4566 $onlytopleafnodes = false) {
4567 $skipped = false;
4568 // Build an action menu based on the visible nodes from this navigation tree.
4569 foreach ($node->children as $menuitem) {
4570 if ($menuitem->display) {
4571 if ($onlytopleafnodes && $menuitem->children->count()) {
4572 $skipped = true;
4573 continue;
4575 if ($menuitem->action) {
4576 if ($menuitem->action instanceof action_link) {
4577 $link = $menuitem->action;
4578 // Give preference to setting icon over action icon.
4579 if (!empty($menuitem->icon)) {
4580 $link->icon = $menuitem->icon;
4582 } else {
4583 $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
4585 } else {
4586 if ($onlytopleafnodes) {
4587 $skipped = true;
4588 continue;
4590 $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
4592 if ($indent) {
4593 $link->add_class('ml-4');
4595 if (!empty($menuitem->classes)) {
4596 $link->add_class(implode(" ", $menuitem->classes));
4599 $menu->add_secondary_action($link);
4600 $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
4603 return $skipped;
4607 * This is an optional menu that can be added to a layout by a theme. It contains the
4608 * menu for the most specific thing from the settings block. E.g. Module administration.
4610 * @return string
4612 public function region_main_settings_menu() {
4613 $context = $this->page->context;
4614 $menu = new action_menu();
4616 if ($context->contextlevel == CONTEXT_MODULE) {
4618 $this->page->navigation->initialise();
4619 $node = $this->page->navigation->find_active_node();
4620 $buildmenu = false;
4621 // If the settings menu has been forced then show the menu.
4622 if ($this->page->is_settings_menu_forced()) {
4623 $buildmenu = true;
4624 } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
4625 $node->type == navigation_node::TYPE_RESOURCE)) {
4627 $items = $this->page->navbar->get_items();
4628 $navbarnode = end($items);
4629 // We only want to show the menu on the first page of the activity. This means
4630 // the breadcrumb has no additional nodes.
4631 if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
4632 $buildmenu = true;
4635 if ($buildmenu) {
4636 // Get the course admin node from the settings navigation.
4637 $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
4638 if ($node) {
4639 // Build an action menu based on the visible nodes from this navigation tree.
4640 $this->build_action_menu_from_navigation($menu, $node);
4644 } else if ($context->contextlevel == CONTEXT_COURSECAT) {
4645 // For course category context, show category settings menu, if we're on the course category page.
4646 if ($this->page->pagetype === 'course-index-category') {
4647 $node = $this->page->settingsnav->find('categorysettings', navigation_node::TYPE_CONTAINER);
4648 if ($node) {
4649 // Build an action menu based on the visible nodes from this navigation tree.
4650 $this->build_action_menu_from_navigation($menu, $node);
4654 } else {
4655 $items = $this->page->navbar->get_items();
4656 $navbarnode = end($items);
4658 if ($navbarnode && ($navbarnode->key === 'participants')) {
4659 $node = $this->page->settingsnav->find('users', navigation_node::TYPE_CONTAINER);
4660 if ($node) {
4661 // Build an action menu based on the visible nodes from this navigation tree.
4662 $this->build_action_menu_from_navigation($menu, $node);
4667 return $this->render($menu);
4671 * Displays the list of tags associated with an entry
4673 * @param array $tags list of instances of core_tag or stdClass
4674 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4675 * to use default, set to '' (empty string) to omit the label completely
4676 * @param string $classes additional classes for the enclosing div element
4677 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4678 * will be appended to the end, JS will toggle the rest of the tags
4679 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4680 * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
4681 * @return string
4683 public function tag_list($tags, $label = null, $classes = '', $limit = 10,
4684 $pagecontext = null, $accesshidelabel = false) {
4685 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
4686 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4690 * Renders element for inline editing of any value
4692 * @param \core\output\inplace_editable $element
4693 * @return string
4695 public function render_inplace_editable(\core\output\inplace_editable $element) {
4696 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4700 * Renders a bar chart.
4702 * @param \core\chart_bar $chart The chart.
4703 * @return string.
4705 public function render_chart_bar(\core\chart_bar $chart) {
4706 return $this->render_chart($chart);
4710 * Renders a line chart.
4712 * @param \core\chart_line $chart The chart.
4713 * @return string.
4715 public function render_chart_line(\core\chart_line $chart) {
4716 return $this->render_chart($chart);
4720 * Renders a pie chart.
4722 * @param \core\chart_pie $chart The chart.
4723 * @return string.
4725 public function render_chart_pie(\core\chart_pie $chart) {
4726 return $this->render_chart($chart);
4730 * Renders a chart.
4732 * @param \core\chart_base $chart The chart.
4733 * @param bool $withtable Whether to include a data table with the chart.
4734 * @return string.
4736 public function render_chart(\core\chart_base $chart, $withtable = true) {
4737 $chartdata = json_encode($chart);
4738 return $this->render_from_template('core/chart', (object) [
4739 'chartdata' => $chartdata,
4740 'withtable' => $withtable
4745 * Renders the login form.
4747 * @param \core_auth\output\login $form The renderable.
4748 * @return string
4750 public function render_login(\core_auth\output\login $form) {
4751 global $CFG, $SITE;
4753 $context = $form->export_for_template($this);
4755 // Override because rendering is not supported in template yet.
4756 if ($CFG->rememberusername == 0) {
4757 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabledonlysession');
4758 } else {
4759 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
4761 $context->errorformatted = $this->error_text($context->error);
4762 $url = $this->get_logo_url();
4763 if ($url) {
4764 $url = $url->out(false);
4766 $context->logourl = $url;
4767 $context->sitename = format_string($SITE->fullname, true,
4768 ['context' => context_course::instance(SITEID), "escape" => false]);
4770 return $this->render_from_template('core/loginform', $context);
4774 * Renders an mform element from a template.
4776 * @param HTML_QuickForm_element $element element
4777 * @param bool $required if input is required field
4778 * @param bool $advanced if input is an advanced field
4779 * @param string $error error message to display
4780 * @param bool $ingroup True if this element is rendered as part of a group
4781 * @return mixed string|bool
4783 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4784 $templatename = 'core_form/element-' . $element->getType();
4785 if ($ingroup) {
4786 $templatename .= "-inline";
4788 try {
4789 // We call this to generate a file not found exception if there is no template.
4790 // We don't want to call export_for_template if there is no template.
4791 core\output\mustache_template_finder::get_template_filepath($templatename);
4793 if ($element instanceof templatable) {
4794 $elementcontext = $element->export_for_template($this);
4796 $helpbutton = '';
4797 if (method_exists($element, 'getHelpButton')) {
4798 $helpbutton = $element->getHelpButton();
4800 $label = $element->getLabel();
4801 $text = '';
4802 if (method_exists($element, 'getText')) {
4803 // There currently exists code that adds a form element with an empty label.
4804 // If this is the case then set the label to the description.
4805 if (empty($label)) {
4806 $label = $element->getText();
4807 } else {
4808 $text = $element->getText();
4812 // Generate the form element wrapper ids and names to pass to the template.
4813 // This differs between group and non-group elements.
4814 if ($element->getType() === 'group') {
4815 // Group element.
4816 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
4817 $elementcontext['wrapperid'] = $elementcontext['id'];
4819 // Ensure group elements pass through the group name as the element name.
4820 $elementcontext['name'] = $elementcontext['groupname'];
4821 } else {
4822 // Non grouped element.
4823 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
4824 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
4827 $context = array(
4828 'element' => $elementcontext,
4829 'label' => $label,
4830 'text' => $text,
4831 'required' => $required,
4832 'advanced' => $advanced,
4833 'helpbutton' => $helpbutton,
4834 'error' => $error
4836 return $this->render_from_template($templatename, $context);
4838 } catch (Exception $e) {
4839 // No template for this element.
4840 return false;
4845 * Render the login signup form into a nice template for the theme.
4847 * @param mform $form
4848 * @return string
4850 public function render_login_signup_form($form) {
4851 global $SITE;
4853 $context = $form->export_for_template($this);
4854 $url = $this->get_logo_url();
4855 if ($url) {
4856 $url = $url->out(false);
4858 $context['logourl'] = $url;
4859 $context['sitename'] = format_string($SITE->fullname, true,
4860 ['context' => context_course::instance(SITEID), "escape" => false]);
4862 return $this->render_from_template('core/signup_form_layout', $context);
4866 * Render the verify age and location page into a nice template for the theme.
4868 * @param \core_auth\output\verify_age_location_page $page The renderable
4869 * @return string
4871 protected function render_verify_age_location_page($page) {
4872 $context = $page->export_for_template($this);
4874 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4878 * Render the digital minor contact information page into a nice template for the theme.
4880 * @param \core_auth\output\digital_minor_page $page The renderable
4881 * @return string
4883 protected function render_digital_minor_page($page) {
4884 $context = $page->export_for_template($this);
4886 return $this->render_from_template('core/auth_digital_minor_page', $context);
4890 * Renders a progress bar.
4892 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4894 * @param progress_bar $bar The bar.
4895 * @return string HTML fragment
4897 public function render_progress_bar(progress_bar $bar) {
4898 $data = $bar->export_for_template($this);
4899 return $this->render_from_template('core/progress_bar', $data);
4903 * Renders an update to a progress bar.
4905 * Note: This does not cleanly map to a renderable class and should
4906 * never be used directly.
4908 * @param string $id
4909 * @param float $percent
4910 * @param string $msg Message
4911 * @param string $estimate time remaining message
4912 * @return string ascii fragment
4914 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
4915 return html_writer::script(js_writer::function_call('updateProgressBar', [$id, $percent, $msg, $estimate]));
4919 * Renders element for a toggle-all checkbox.
4921 * @param \core\output\checkbox_toggleall $element
4922 * @return string
4924 public function render_checkbox_toggleall(\core\output\checkbox_toggleall $element) {
4925 return $this->render_from_template($element->get_template(), $element->export_for_template($this));
4929 * Renders the tertiary nav for the participants page
4931 * @param object $course The course we are operating within
4932 * @param string|null $renderedbuttons Any additional buttons/content to be displayed in line with the nav
4933 * @return string
4935 public function render_participants_tertiary_nav(object $course, ?string $renderedbuttons = null) {
4936 $actionbar = new \core\output\participants_action_bar($course, $this->page, $renderedbuttons);
4937 $content = $this->render_from_template('core_course/participants_actionbar', $actionbar->export_for_template($this));
4938 return $content ?: "";
4942 * Renders release information in the footer popup
4943 * @return string Moodle release info.
4945 public function moodle_release() {
4946 global $CFG;
4947 if (!during_initial_install() && is_siteadmin()) {
4948 return $CFG->release;
4953 * Generate the add block button when editing mode is turned on and the user can edit blocks.
4955 * @param string $region where new blocks should be added.
4956 * @return string html for the add block button.
4958 public function addblockbutton($region = ''): string {
4959 $addblockbutton = '';
4960 if (isset($this->page->theme->addblockposition) &&
4961 $this->page->user_is_editing() &&
4962 $this->page->user_can_edit_blocks() &&
4963 $this->page->pagelayout !== 'mycourses'
4965 $params = ['bui_addblock' => '', 'sesskey' => sesskey()];
4966 if (!empty($region)) {
4967 $params['bui_blockregion'] = $region;
4969 $url = new moodle_url($this->page->url, $params);
4970 $addblockbutton = $this->render_from_template('core/add_block_button',
4972 'link' => $url->out(false),
4973 'escapedlink' => "?{$url->get_query_string(false)}",
4974 'pageType' => $this->page->pagetype,
4975 'pageLayout' => $this->page->pagelayout,
4976 'subPage' => $this->page->subpage,
4980 return $addblockbutton;
4985 * A renderer that generates output for command-line scripts.
4987 * The implementation of this renderer is probably incomplete.
4989 * @copyright 2009 Tim Hunt
4990 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4991 * @since Moodle 2.0
4992 * @package core
4993 * @category output
4995 class core_renderer_cli extends core_renderer {
4998 * @var array $progressmaximums stores the largest percentage for a progress bar.
4999 * @return string ascii fragment
5001 private $progressmaximums = [];
5004 * Returns the page header.
5006 * @return string HTML fragment
5008 public function header() {
5009 return $this->page->heading . "\n";
5013 * Renders a Check API result
5015 * To aid in CLI consistency this status is NOT translated and the visual
5016 * width is always exactly 10 chars.
5018 * @param core\check\result $result
5019 * @return string HTML fragment
5021 protected function render_check_result(core\check\result $result) {
5022 $status = $result->get_status();
5024 $labels = [
5025 core\check\result::NA => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' NA ',
5026 core\check\result::OK => ' ' . cli_ansi_format('<colour:green>') . ' OK ',
5027 core\check\result::INFO => ' ' . cli_ansi_format('<colour:blue>' ) . ' INFO ',
5028 core\check\result::UNKNOWN => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' UNKNOWN ',
5029 core\check\result::WARNING => ' ' . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
5030 core\check\result::ERROR => ' ' . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
5031 core\check\result::CRITICAL => '' . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
5033 $string = $labels[$status] . cli_ansi_format('<colour:normal>');
5034 return $string;
5038 * Renders a Check API result
5040 * @param result $result
5041 * @return string fragment
5043 public function check_result(core\check\result $result) {
5044 return $this->render_check_result($result);
5048 * Renders a progress bar.
5050 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
5052 * @param progress_bar $bar The bar.
5053 * @return string ascii fragment
5055 public function render_progress_bar(progress_bar $bar) {
5056 global $CFG;
5058 $size = 55; // The width of the progress bar in chars.
5059 $ascii = "\n";
5061 if (stream_isatty(STDOUT)) {
5062 require_once($CFG->libdir.'/clilib.php');
5064 $ascii .= "[" . str_repeat(' ', $size) . "] 0% \n";
5065 return cli_ansi_format($ascii);
5068 $this->progressmaximums[$bar->get_id()] = 0;
5069 $ascii .= '[';
5070 return $ascii;
5074 * Renders an update to a progress bar.
5076 * Note: This does not cleanly map to a renderable class and should
5077 * never be used directly.
5079 * @param string $id
5080 * @param float $percent
5081 * @param string $msg Message
5082 * @param string $estimate time remaining message
5083 * @return string ascii fragment
5085 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
5086 $size = 55; // The width of the progress bar in chars.
5087 $ascii = '';
5089 // If we are rendering to a terminal then we can safely use ansii codes
5090 // to move the cursor and redraw the complete progress bar each time
5091 // it is updated.
5092 if (stream_isatty(STDOUT)) {
5093 $colour = $percent == 100 ? 'green' : 'blue';
5095 $done = $percent * $size * 0.01;
5096 $whole = floor($done);
5097 $bar = "<colour:$colour>";
5098 $bar .= str_repeat('█', $whole);
5100 if ($whole < $size) {
5101 // By using unicode chars for partial blocks we can have higher
5102 // precision progress bar.
5103 $fraction = floor(($done - $whole) * 8);
5104 $bar .= core_text::substr(' ▏▎▍▌▋▊▉', $fraction, 1);
5106 // Fill the rest of the empty bar.
5107 $bar .= str_repeat(' ', $size - $whole - 1);
5110 $bar .= '<colour:normal>';
5112 if ($estimate) {
5113 $estimate = "- $estimate";
5116 $ascii .= '<cursor:up>';
5117 $ascii .= '<cursor:up>';
5118 $ascii .= sprintf("[$bar] %3.1f%% %-22s\n", $percent, $estimate);
5119 $ascii .= sprintf("%-80s\n", $msg);
5120 return cli_ansi_format($ascii);
5123 // If we are not rendering to a tty, ie when piped to another command
5124 // or on windows we need to progressively render the progress bar
5125 // which can only ever go forwards.
5126 $done = round($percent * $size * 0.01);
5127 $delta = max(0, $done - $this->progressmaximums[$id]);
5129 $ascii .= str_repeat('#', $delta);
5130 if ($percent >= 100 && $delta > 0) {
5131 $ascii .= sprintf("] %3.1f%%\n$msg\n", $percent);
5133 $this->progressmaximums[$id] += $delta;
5134 return $ascii;
5138 * Returns a template fragment representing a Heading.
5140 * @param string $text The text of the heading
5141 * @param int $level The level of importance of the heading
5142 * @param string $classes A space-separated list of CSS classes
5143 * @param string $id An optional ID
5144 * @return string A template fragment for a heading
5146 public function heading($text, $level = 2, $classes = 'main', $id = null) {
5147 $text .= "\n";
5148 switch ($level) {
5149 case 1:
5150 return '=>' . $text;
5151 case 2:
5152 return '-->' . $text;
5153 default:
5154 return $text;
5159 * Returns a template fragment representing a fatal error.
5161 * @param string $message The message to output
5162 * @param string $moreinfourl URL where more info can be found about the error
5163 * @param string $link Link for the Continue button
5164 * @param array $backtrace The execution backtrace
5165 * @param string $debuginfo Debugging information
5166 * @return string A template fragment for a fatal error
5168 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5169 global $CFG;
5171 $output = "!!! $message !!!\n";
5173 if ($CFG->debugdeveloper) {
5174 if (!empty($debuginfo)) {
5175 $output .= $this->notification($debuginfo, 'notifytiny');
5177 if (!empty($backtrace)) {
5178 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
5182 return $output;
5186 * Returns a template fragment representing a notification.
5188 * @param string $message The message to print out.
5189 * @param string $type The type of notification. See constants on \core\output\notification.
5190 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5191 * @return string A template fragment for a notification
5193 public function notification($message, $type = null, $closebutton = true) {
5194 $message = clean_text($message);
5195 if ($type === 'notifysuccess' || $type === 'success') {
5196 return "++ $message ++\n";
5198 return "!! $message !!\n";
5202 * There is no footer for a cli request, however we must override the
5203 * footer method to prevent the default footer.
5205 public function footer() {}
5208 * Render a notification (that is, a status message about something that has
5209 * just happened).
5211 * @param \core\output\notification $notification the notification to print out
5212 * @return string plain text output
5214 public function render_notification(\core\output\notification $notification) {
5215 return $this->notification($notification->get_message(), $notification->get_message_type());
5221 * A renderer that generates output for ajax scripts.
5223 * This renderer prevents accidental sends back only json
5224 * encoded error messages, all other output is ignored.
5226 * @copyright 2010 Petr Skoda
5227 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5228 * @since Moodle 2.0
5229 * @package core
5230 * @category output
5232 class core_renderer_ajax extends core_renderer {
5235 * Returns a template fragment representing a fatal error.
5237 * @param string $message The message to output
5238 * @param string $moreinfourl URL where more info can be found about the error
5239 * @param string $link Link for the Continue button
5240 * @param array $backtrace The execution backtrace
5241 * @param string $debuginfo Debugging information
5242 * @return string A template fragment for a fatal error
5244 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5245 global $CFG;
5247 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
5249 $e = new stdClass();
5250 $e->error = $message;
5251 $e->errorcode = $errorcode;
5252 $e->stacktrace = NULL;
5253 $e->debuginfo = NULL;
5254 $e->reproductionlink = NULL;
5255 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
5256 $link = (string) $link;
5257 if ($link) {
5258 $e->reproductionlink = $link;
5260 if (!empty($debuginfo)) {
5261 $e->debuginfo = $debuginfo;
5263 if (!empty($backtrace)) {
5264 $e->stacktrace = format_backtrace($backtrace, true);
5267 $this->header();
5268 return json_encode($e);
5272 * Used to display a notification.
5273 * For the AJAX notifications are discarded.
5275 * @param string $message The message to print out.
5276 * @param string $type The type of notification. See constants on \core\output\notification.
5277 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5279 public function notification($message, $type = null, $closebutton = true) {
5283 * Used to display a redirection message.
5284 * AJAX redirections should not occur and as such redirection messages
5285 * are discarded.
5287 * @param moodle_url|string $encodedurl
5288 * @param string $message
5289 * @param int $delay
5290 * @param bool $debugdisableredirect
5291 * @param string $messagetype The type of notification to show the message in.
5292 * See constants on \core\output\notification.
5294 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
5295 $messagetype = \core\output\notification::NOTIFY_INFO) {}
5298 * Prepares the start of an AJAX output.
5300 public function header() {
5301 // unfortunately YUI iframe upload does not support application/json
5302 if (!empty($_FILES)) {
5303 @header('Content-type: text/plain; charset=utf-8');
5304 if (!core_useragent::supports_json_contenttype()) {
5305 @header('X-Content-Type-Options: nosniff');
5307 } else if (!core_useragent::supports_json_contenttype()) {
5308 @header('Content-type: text/plain; charset=utf-8');
5309 @header('X-Content-Type-Options: nosniff');
5310 } else {
5311 @header('Content-type: application/json; charset=utf-8');
5314 // Headers to make it not cacheable and json
5315 @header('Cache-Control: no-store, no-cache, must-revalidate');
5316 @header('Cache-Control: post-check=0, pre-check=0', false);
5317 @header('Pragma: no-cache');
5318 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
5319 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
5320 @header('Accept-Ranges: none');
5324 * There is no footer for an AJAX request, however we must override the
5325 * footer method to prevent the default footer.
5327 public function footer() {}
5330 * No need for headers in an AJAX request... this should never happen.
5331 * @param string $text
5332 * @param int $level
5333 * @param string $classes
5334 * @param string $id
5336 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
5342 * The maintenance renderer.
5344 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
5345 * is running a maintenance related task.
5346 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
5348 * @since Moodle 2.6
5349 * @package core
5350 * @category output
5351 * @copyright 2013 Sam Hemelryk
5352 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5354 class core_renderer_maintenance extends core_renderer {
5357 * Initialises the renderer instance.
5359 * @param moodle_page $page
5360 * @param string $target
5361 * @throws coding_exception
5363 public function __construct(moodle_page $page, $target) {
5364 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
5365 throw new coding_exception('Invalid request for the maintenance renderer.');
5367 parent::__construct($page, $target);
5371 * Does nothing. The maintenance renderer cannot produce blocks.
5373 * @param block_contents $bc
5374 * @param string $region
5375 * @return string
5377 public function block(block_contents $bc, $region) {
5378 return '';
5382 * Does nothing. The maintenance renderer cannot produce blocks.
5384 * @param string $region
5385 * @param array $classes
5386 * @param string $tag
5387 * @param boolean $fakeblocksonly
5388 * @return string
5390 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
5391 return '';
5395 * Does nothing. The maintenance renderer cannot produce blocks.
5397 * @param string $region
5398 * @param boolean $fakeblocksonly Output fake block only.
5399 * @return string
5401 public function blocks_for_region($region, $fakeblocksonly = false) {
5402 return '';
5406 * Does nothing. The maintenance renderer cannot produce a course content header.
5408 * @param bool $onlyifnotcalledbefore
5409 * @return string
5411 public function course_content_header($onlyifnotcalledbefore = false) {
5412 return '';
5416 * Does nothing. The maintenance renderer cannot produce a course content footer.
5418 * @param bool $onlyifnotcalledbefore
5419 * @return string
5421 public function course_content_footer($onlyifnotcalledbefore = false) {
5422 return '';
5426 * Does nothing. The maintenance renderer cannot produce a course header.
5428 * @return string
5430 public function course_header() {
5431 return '';
5435 * Does nothing. The maintenance renderer cannot produce a course footer.
5437 * @return string
5439 public function course_footer() {
5440 return '';
5444 * Does nothing. The maintenance renderer cannot produce a custom menu.
5446 * @param string $custommenuitems
5447 * @return string
5449 public function custom_menu($custommenuitems = '') {
5450 return '';
5454 * Does nothing. The maintenance renderer cannot produce a file picker.
5456 * @param array $options
5457 * @return string
5459 public function file_picker($options) {
5460 return '';
5464 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
5466 * @param array $dir
5467 * @return string
5469 public function htmllize_file_tree($dir) {
5470 return '';
5475 * Overridden confirm message for upgrades.
5477 * @param string $message The question to ask the user
5478 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5479 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5480 * @param array $displayoptions optional extra display options
5481 * @return string HTML fragment
5483 public function confirm($message, $continue, $cancel, array $displayoptions = []) {
5484 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5485 // from any previous version of Moodle).
5486 if ($continue instanceof single_button) {
5487 $continue->primary = true;
5488 } else if (is_string($continue)) {
5489 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
5490 } else if ($continue instanceof moodle_url) {
5491 $continue = new single_button($continue, get_string('continue'), 'post', true);
5492 } else {
5493 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5494 ' (string/moodle_url) or a single_button instance.');
5497 if ($cancel instanceof single_button) {
5498 $output = '';
5499 } else if (is_string($cancel)) {
5500 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5501 } else if ($cancel instanceof moodle_url) {
5502 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5503 } else {
5504 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5505 ' (string/moodle_url) or a single_button instance.');
5508 $output = $this->box_start('generalbox', 'notice');
5509 $output .= html_writer::tag('h4', get_string('confirm'));
5510 $output .= html_writer::tag('p', $message);
5511 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
5512 $output .= $this->box_end();
5513 return $output;
5517 * Does nothing. The maintenance renderer does not support JS.
5519 * @param block_contents $bc
5521 public function init_block_hider_js(block_contents $bc) {
5522 // Does nothing.
5526 * Does nothing. The maintenance renderer cannot produce language menus.
5528 * @return string
5530 public function lang_menu() {
5531 return '';
5535 * Does nothing. The maintenance renderer has no need for login information.
5537 * @param null $withlinks
5538 * @return string
5540 public function login_info($withlinks = null) {
5541 return '';
5545 * Secure login info.
5547 * @return string
5549 public function secure_login_info() {
5550 return $this->login_info(false);
5554 * Does nothing. The maintenance renderer cannot produce user pictures.
5556 * @param stdClass $user
5557 * @param array $options
5558 * @return string
5560 public function user_picture(stdClass $user, array $options = null) {
5561 return '';