MDL-69542 enrol_lti: add LTI Advantage member sync task
[moodle.git] / lib / outputrenderers.php
bloba4ff3c420b8b4ebdf5af92b01061e3ff0401628a
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_nowrap_on_items();
3473 if ($withlinks) {
3474 $navitemcount = count($opts->navitems);
3475 $idx = 0;
3476 foreach ($opts->navitems as $key => $value) {
3478 switch ($value->itemtype) {
3479 case 'divider':
3480 // If the nav item is a divider, add one and skip link processing.
3481 $am->add($divider);
3482 break;
3484 case 'invalid':
3485 // Silently skip invalid entries (should we post a notification?).
3486 break;
3488 case 'link':
3489 // Process this as a link item.
3490 $pix = null;
3491 if (isset($value->pix) && !empty($value->pix)) {
3492 $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
3493 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3494 $value->title = html_writer::img(
3495 $value->imgsrc,
3496 $value->title,
3497 array('class' => 'iconsmall')
3498 ) . $value->title;
3501 $al = new action_menu_link_secondary(
3502 $value->url,
3503 $pix,
3504 $value->title,
3505 array('class' => 'icon')
3507 if (!empty($value->titleidentifier)) {
3508 $al->attributes['data-title'] = $value->titleidentifier;
3510 $am->add($al);
3511 break;
3514 $idx++;
3516 // Add dividers after the first item and before the last item.
3517 if ($idx == 1 || $idx == $navitemcount - 1) {
3518 $am->add($divider);
3523 return html_writer::div(
3524 $this->render($am),
3525 $usermenuclasses
3530 * Secure layout login info.
3532 * @return string
3534 public function secure_layout_login_info() {
3535 if (get_config('core', 'logininfoinsecurelayout')) {
3536 return $this->login_info(false);
3537 } else {
3538 return '';
3543 * Returns the language menu in the secure layout.
3545 * No custom menu items are passed though, such that it will render only the language selection.
3547 * @return string
3549 public function secure_layout_language_menu() {
3550 if (get_config('core', 'langmenuinsecurelayout')) {
3551 $custommenu = new custom_menu('', current_language());
3552 return $this->render_custom_menu($custommenu);
3553 } else {
3554 return '';
3559 * This renders the navbar.
3560 * Uses bootstrap compatible html.
3562 public function navbar() {
3563 return $this->render_from_template('core/navbar', $this->page->navbar);
3567 * Renders a breadcrumb navigation node object.
3569 * @param breadcrumb_navigation_node $item The navigation node to render.
3570 * @return string HTML fragment
3572 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3574 if ($item->action instanceof moodle_url) {
3575 $content = $item->get_content();
3576 $title = $item->get_title();
3577 $attributes = array();
3578 $attributes['itemprop'] = 'url';
3579 if ($title !== '') {
3580 $attributes['title'] = $title;
3582 if ($item->hidden) {
3583 $attributes['class'] = 'dimmed_text';
3585 if ($item->is_last()) {
3586 $attributes['aria-current'] = 'page';
3588 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3589 $content = html_writer::link($item->action, $content, $attributes);
3591 $attributes = array();
3592 $attributes['itemscope'] = '';
3593 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3594 $content = html_writer::tag('span', $content, $attributes);
3596 } else {
3597 $content = $this->render_navigation_node($item);
3599 return $content;
3603 * Renders a navigation node object.
3605 * @param navigation_node $item The navigation node to render.
3606 * @return string HTML fragment
3608 protected function render_navigation_node(navigation_node $item) {
3609 $content = $item->get_content();
3610 $title = $item->get_title();
3611 if ($item->icon instanceof renderable && !$item->hideicon) {
3612 $icon = $this->render($item->icon);
3613 $content = $icon.$content; // use CSS for spacing of icons
3615 if ($item->helpbutton !== null) {
3616 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3618 if ($content === '') {
3619 return '';
3621 if ($item->action instanceof action_link) {
3622 $link = $item->action;
3623 if ($item->hidden) {
3624 $link->add_class('dimmed');
3626 if (!empty($content)) {
3627 // Providing there is content we will use that for the link content.
3628 $link->text = $content;
3630 $content = $this->render($link);
3631 } else if ($item->action instanceof moodle_url) {
3632 $attributes = array();
3633 if ($title !== '') {
3634 $attributes['title'] = $title;
3636 if ($item->hidden) {
3637 $attributes['class'] = 'dimmed_text';
3639 $content = html_writer::link($item->action, $content, $attributes);
3641 } else if (is_string($item->action) || empty($item->action)) {
3642 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3643 if ($title !== '') {
3644 $attributes['title'] = $title;
3646 if ($item->hidden) {
3647 $attributes['class'] = 'dimmed_text';
3649 $content = html_writer::tag('span', $content, $attributes);
3651 return $content;
3655 * Accessibility: Right arrow-like character is
3656 * used in the breadcrumb trail, course navigation menu
3657 * (previous/next activity), calendar, and search forum block.
3658 * If the theme does not set characters, appropriate defaults
3659 * are set automatically. Please DO NOT
3660 * use &lt; &gt; &raquo; - these are confusing for blind users.
3662 * @return string
3664 public function rarrow() {
3665 return $this->page->theme->rarrow;
3669 * Accessibility: Left arrow-like character is
3670 * used in the breadcrumb trail, course navigation menu
3671 * (previous/next activity), calendar, and search forum block.
3672 * If the theme does not set characters, appropriate defaults
3673 * are set automatically. Please DO NOT
3674 * use &lt; &gt; &raquo; - these are confusing for blind users.
3676 * @return string
3678 public function larrow() {
3679 return $this->page->theme->larrow;
3683 * Accessibility: Up arrow-like character is used in
3684 * the book heirarchical navigation.
3685 * If the theme does not set characters, appropriate defaults
3686 * are set automatically. Please DO NOT
3687 * use ^ - this is confusing for blind users.
3689 * @return string
3691 public function uarrow() {
3692 return $this->page->theme->uarrow;
3696 * Accessibility: Down arrow-like character.
3697 * If the theme does not set characters, appropriate defaults
3698 * are set automatically.
3700 * @return string
3702 public function darrow() {
3703 return $this->page->theme->darrow;
3707 * Returns the custom menu if one has been set
3709 * A custom menu can be configured by browsing to
3710 * Settings: Administration > Appearance > Themes > Theme settings
3711 * and then configuring the custommenu config setting as described.
3713 * Theme developers: DO NOT OVERRIDE! Please override function
3714 * {@link core_renderer::render_custom_menu()} instead.
3716 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3717 * @return string
3719 public function custom_menu($custommenuitems = '') {
3720 global $CFG;
3722 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3723 $custommenuitems = $CFG->custommenuitems;
3725 $custommenu = new custom_menu($custommenuitems, current_language());
3726 return $this->render_custom_menu($custommenu);
3730 * We want to show the custom menus as a list of links in the footer on small screens.
3731 * Just return the menu object exported so we can render it differently.
3733 public function custom_menu_flat() {
3734 global $CFG;
3735 $custommenuitems = '';
3737 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3738 $custommenuitems = $CFG->custommenuitems;
3740 $custommenu = new custom_menu($custommenuitems, current_language());
3741 $langs = get_string_manager()->get_list_of_translations();
3742 $haslangmenu = $this->lang_menu() != '';
3744 if ($haslangmenu) {
3745 $strlang = get_string('language');
3746 $currentlang = current_language();
3747 if (isset($langs[$currentlang])) {
3748 $currentlang = $langs[$currentlang];
3749 } else {
3750 $currentlang = $strlang;
3752 $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3753 foreach ($langs as $langtype => $langname) {
3754 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3758 return $custommenu->export_for_template($this);
3762 * Renders a custom menu object (located in outputcomponents.php)
3764 * The custom menu this method produces makes use of the YUI3 menunav widget
3765 * and requires very specific html elements and classes.
3767 * @staticvar int $menucount
3768 * @param custom_menu $menu
3769 * @return string
3771 protected function render_custom_menu(custom_menu $menu) {
3772 global $CFG;
3774 $langs = get_string_manager()->get_list_of_translations();
3775 $haslangmenu = $this->lang_menu() != '';
3777 if (!$menu->has_children() && !$haslangmenu) {
3778 return '';
3781 if ($haslangmenu) {
3782 $strlang = get_string('language');
3783 $currentlang = current_language();
3784 if (isset($langs[$currentlang])) {
3785 $currentlang = $langs[$currentlang];
3786 } else {
3787 $currentlang = $strlang;
3789 $this->language = $menu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3790 foreach ($langs as $langtype => $langname) {
3791 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3795 $content = '';
3796 foreach ($menu->get_children() as $item) {
3797 $context = $item->export_for_template($this);
3798 $content .= $this->render_from_template('core/custom_menu_item', $context);
3801 return $content;
3805 * Renders a custom menu node as part of a submenu
3807 * The custom menu this method produces makes use of the YUI3 menunav widget
3808 * and requires very specific html elements and classes.
3810 * @see core:renderer::render_custom_menu()
3812 * @staticvar int $submenucount
3813 * @param custom_menu_item $menunode
3814 * @return string
3816 protected function render_custom_menu_item(custom_menu_item $menunode) {
3817 // Required to ensure we get unique trackable id's
3818 static $submenucount = 0;
3819 if ($menunode->has_children()) {
3820 // If the child has menus render it as a sub menu
3821 $submenucount++;
3822 $content = html_writer::start_tag('li');
3823 if ($menunode->get_url() !== null) {
3824 $url = $menunode->get_url();
3825 } else {
3826 $url = '#cm_submenu_'.$submenucount;
3828 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3829 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3830 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3831 $content .= html_writer::start_tag('ul');
3832 foreach ($menunode->get_children() as $menunode) {
3833 $content .= $this->render_custom_menu_item($menunode);
3835 $content .= html_writer::end_tag('ul');
3836 $content .= html_writer::end_tag('div');
3837 $content .= html_writer::end_tag('div');
3838 $content .= html_writer::end_tag('li');
3839 } else {
3840 // The node doesn't have children so produce a final menuitem.
3841 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3842 $content = '';
3843 if (preg_match("/^#+$/", $menunode->get_text())) {
3845 // This is a divider.
3846 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3847 } else {
3848 $content = html_writer::start_tag(
3849 'li',
3850 array(
3851 'class' => 'yui3-menuitem'
3854 if ($menunode->get_url() !== null) {
3855 $url = $menunode->get_url();
3856 } else {
3857 $url = '#';
3859 $content .= html_writer::link(
3860 $url,
3861 $menunode->get_text(),
3862 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3865 $content .= html_writer::end_tag('li');
3867 // Return the sub menu
3868 return $content;
3872 * Renders theme links for switching between default and other themes.
3874 * @return string
3876 protected function theme_switch_links() {
3878 $actualdevice = core_useragent::get_device_type();
3879 $currentdevice = $this->page->devicetypeinuse;
3880 $switched = ($actualdevice != $currentdevice);
3882 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3883 // The user is using the a default device and hasn't switched so don't shown the switch
3884 // device links.
3885 return '';
3888 if ($switched) {
3889 $linktext = get_string('switchdevicerecommended');
3890 $devicetype = $actualdevice;
3891 } else {
3892 $linktext = get_string('switchdevicedefault');
3893 $devicetype = 'default';
3895 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3897 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3898 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3899 $content .= html_writer::end_tag('div');
3901 return $content;
3905 * Renders tabs
3907 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3909 * Theme developers: In order to change how tabs are displayed please override functions
3910 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3912 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3913 * @param string|null $selected which tab to mark as selected, all parent tabs will
3914 * automatically be marked as activated
3915 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3916 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3917 * @return string
3919 public final function tabtree($tabs, $selected = null, $inactive = null) {
3920 return $this->render(new tabtree($tabs, $selected, $inactive));
3924 * Renders tabtree
3926 * @param tabtree $tabtree
3927 * @return string
3929 protected function render_tabtree(tabtree $tabtree) {
3930 if (empty($tabtree->subtree)) {
3931 return '';
3933 $data = $tabtree->export_for_template($this);
3934 return $this->render_from_template('core/tabtree', $data);
3938 * Renders tabobject (part of tabtree)
3940 * This function is called from {@link core_renderer::render_tabtree()}
3941 * and also it calls itself when printing the $tabobject subtree recursively.
3943 * Property $tabobject->level indicates the number of row of tabs.
3945 * @param tabobject $tabobject
3946 * @return string HTML fragment
3948 protected function render_tabobject(tabobject $tabobject) {
3949 $str = '';
3951 // Print name of the current tab.
3952 if ($tabobject instanceof tabtree) {
3953 // No name for tabtree root.
3954 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3955 // Tab name without a link. The <a> tag is used for styling.
3956 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3957 } else {
3958 // Tab name with a link.
3959 if (!($tabobject->link instanceof moodle_url)) {
3960 // backward compartibility when link was passed as quoted string
3961 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3962 } else {
3963 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3967 if (empty($tabobject->subtree)) {
3968 if ($tabobject->selected) {
3969 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3971 return $str;
3974 // Print subtree.
3975 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
3976 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3977 $cnt = 0;
3978 foreach ($tabobject->subtree as $tab) {
3979 $liclass = '';
3980 if (!$cnt) {
3981 $liclass .= ' first';
3983 if ($cnt == count($tabobject->subtree) - 1) {
3984 $liclass .= ' last';
3986 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3987 $liclass .= ' onerow';
3990 if ($tab->selected) {
3991 $liclass .= ' here selected';
3992 } else if ($tab->activated) {
3993 $liclass .= ' here active';
3996 // This will recursively call function render_tabobject() for each item in subtree.
3997 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3998 $cnt++;
4000 $str .= html_writer::end_tag('ul');
4003 return $str;
4007 * Get the HTML for blocks in the given region.
4009 * @since Moodle 2.5.1 2.6
4010 * @param string $region The region to get HTML for.
4011 * @param array $classes Wrapping tag classes.
4012 * @param string $tag Wrapping tag.
4013 * @param boolean $fakeblocksonly Include fake blocks only.
4014 * @return string HTML.
4016 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
4017 $displayregion = $this->page->apply_theme_region_manipulations($region);
4018 $classes = (array)$classes;
4019 $classes[] = 'block-region';
4020 $attributes = array(
4021 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
4022 'class' => join(' ', $classes),
4023 'data-blockregion' => $displayregion,
4024 'data-droptarget' => '1'
4026 if ($this->page->blocks->region_has_content($displayregion, $this)) {
4027 $content = $this->blocks_for_region($displayregion, $fakeblocksonly);
4028 } else {
4029 $content = '';
4031 return html_writer::tag($tag, $content, $attributes);
4035 * Renders a custom block region.
4037 * Use this method if you want to add an additional block region to the content of the page.
4038 * Please note this should only be used in special situations.
4039 * We want to leave the theme is control where ever possible!
4041 * This method must use the same method that the theme uses within its layout file.
4042 * As such it asks the theme what method it is using.
4043 * It can be one of two values, blocks or blocks_for_region (deprecated).
4045 * @param string $regionname The name of the custom region to add.
4046 * @return string HTML for the block region.
4048 public function custom_block_region($regionname) {
4049 if ($this->page->theme->get_block_render_method() === 'blocks') {
4050 return $this->blocks($regionname);
4051 } else {
4052 return $this->blocks_for_region($regionname);
4057 * Returns the CSS classes to apply to the body tag.
4059 * @since Moodle 2.5.1 2.6
4060 * @param array $additionalclasses Any additional classes to apply.
4061 * @return string
4063 public function body_css_classes(array $additionalclasses = array()) {
4064 return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses);
4068 * The ID attribute to apply to the body tag.
4070 * @since Moodle 2.5.1 2.6
4071 * @return string
4073 public function body_id() {
4074 return $this->page->bodyid;
4078 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4080 * @since Moodle 2.5.1 2.6
4081 * @param string|array $additionalclasses Any additional classes to give the body tag,
4082 * @return string
4084 public function body_attributes($additionalclasses = array()) {
4085 if (!is_array($additionalclasses)) {
4086 $additionalclasses = explode(' ', $additionalclasses);
4088 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4092 * Gets HTML for the page heading.
4094 * @since Moodle 2.5.1 2.6
4095 * @param string $tag The tag to encase the heading in. h1 by default.
4096 * @return string HTML.
4098 public function page_heading($tag = 'h1') {
4099 return html_writer::tag($tag, $this->page->heading);
4103 * Gets the HTML for the page heading button.
4105 * @since Moodle 2.5.1 2.6
4106 * @return string HTML.
4108 public function page_heading_button() {
4109 return $this->page->button;
4113 * Returns the Moodle docs link to use for this page.
4115 * @since Moodle 2.5.1 2.6
4116 * @param string $text
4117 * @return string
4119 public function page_doc_link($text = null) {
4120 if ($text === null) {
4121 $text = get_string('moodledocslink');
4123 $path = page_get_doc_link_path($this->page);
4124 if (!$path) {
4125 return '';
4127 return $this->doc_link($path, $text);
4131 * Returns the HTML for the site support email link
4133 * @return string The html code for the support email link.
4135 public function supportemail(): string {
4136 global $CFG;
4138 if (empty($CFG->supportemail)) {
4139 return '';
4142 $supportemail = $CFG->supportemail;
4143 $label = get_string('contactsitesupport', 'admin');
4144 $icon = $this->pix_icon('t/email', '', 'moodle', ['class' => 'iconhelp icon-pre']);
4145 return html_writer::tag('a', $icon . $label, ['href' => 'mailto:' . $supportemail]);
4149 * Returns the services and support link for the help pop-up.
4151 * @return string
4153 public function services_support_link(): string {
4154 global $CFG;
4156 if (during_initial_install() ||
4157 (isset($CFG->showservicesandsupportcontent) && $CFG->showservicesandsupportcontent == false) ||
4158 !is_siteadmin()) {
4159 return '';
4162 $liferingicon = $this->pix_icon('t/life-ring', '', 'moodle', ['class' => 'fa fa-life-ring']);
4163 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle',
4164 ['class' => 'fa fa-externallink fa-fw']);
4165 $link = 'https://moodle.com/help/?utm_source=CTA-banner&utm_medium=platform&utm_campaign=name~Moodle4+cat~lms+mp~no';
4166 $content = $liferingicon . get_string('moodleservicesandsupport') . $newwindowicon;
4168 return html_writer::tag('a', $content, ['target' => '_blank', 'href' => $link]);
4172 * Helper function to decide whether to show the help popover header or not.
4174 * @return bool
4176 public function has_popover_links(): bool {
4177 return !empty($this->services_support_link()) || !empty($this->page_doc_link()) || !empty($this->supportemail());
4181 * Returns the page heading menu.
4183 * @since Moodle 2.5.1 2.6
4184 * @return string HTML.
4186 public function page_heading_menu() {
4187 return $this->page->headingmenu;
4191 * Returns the title to use on the page.
4193 * @since Moodle 2.5.1 2.6
4194 * @return string
4196 public function page_title() {
4197 return $this->page->title;
4201 * Returns the moodle_url for the favicon.
4203 * @since Moodle 2.5.1 2.6
4204 * @return moodle_url The moodle_url for the favicon
4206 public function favicon() {
4207 return $this->image_url('favicon', 'theme');
4211 * Renders preferences groups.
4213 * @param preferences_groups $renderable The renderable
4214 * @return string The output.
4216 public function render_preferences_groups(preferences_groups $renderable) {
4217 return $this->render_from_template('core/preferences_groups', $renderable);
4221 * Renders preferences group.
4223 * @param preferences_group $renderable The renderable
4224 * @return string The output.
4226 public function render_preferences_group(preferences_group $renderable) {
4227 $html = '';
4228 $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4229 $html .= $this->heading($renderable->title, 3);
4230 $html .= html_writer::start_tag('ul');
4231 foreach ($renderable->nodes as $node) {
4232 if ($node->has_children()) {
4233 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4235 $html .= html_writer::tag('li', $this->render($node));
4237 $html .= html_writer::end_tag('ul');
4238 $html .= html_writer::end_tag('div');
4239 return $html;
4242 public function context_header($headerinfo = null, $headinglevel = 1) {
4243 global $DB, $USER, $CFG, $SITE;
4244 require_once($CFG->dirroot . '/user/lib.php');
4245 $context = $this->page->context;
4246 $heading = null;
4247 $imagedata = null;
4248 $subheader = null;
4249 $userbuttons = null;
4251 // Make sure to use the heading if it has been set.
4252 if (isset($headerinfo['heading'])) {
4253 $heading = $headerinfo['heading'];
4254 } else {
4255 $heading = $this->page->heading;
4258 // The user context currently has images and buttons. Other contexts may follow.
4259 if ((isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) && $this->page->pagetype !== 'my-index') {
4260 if (isset($headerinfo['user'])) {
4261 $user = $headerinfo['user'];
4262 } else {
4263 // Look up the user information if it is not supplied.
4264 $user = $DB->get_record('user', array('id' => $context->instanceid));
4267 // If the user context is set, then use that for capability checks.
4268 if (isset($headerinfo['usercontext'])) {
4269 $context = $headerinfo['usercontext'];
4272 // Only provide user information if the user is the current user, or a user which the current user can view.
4273 // When checking user_can_view_profile(), either:
4274 // If the page context is course, check the course context (from the page object) or;
4275 // If page context is NOT course, then check across all courses.
4276 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4278 if (user_can_view_profile($user, $course)) {
4279 // Use the user's full name if the heading isn't set.
4280 if (empty($heading)) {
4281 $heading = fullname($user);
4284 $imagedata = $this->user_picture($user, array('size' => 100));
4286 // Check to see if we should be displaying a message button.
4287 if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
4288 $userbuttons = array(
4289 'messages' => array(
4290 'buttontype' => 'message',
4291 'title' => get_string('message', 'message'),
4292 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4293 'image' => 'message',
4294 'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
4295 'page' => $this->page
4299 if ($USER->id != $user->id) {
4300 $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4301 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4302 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4303 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4304 $userbuttons['togglecontact'] = array(
4305 'buttontype' => 'togglecontact',
4306 'title' => get_string($contacttitle, 'message'),
4307 'url' => new moodle_url('/message/index.php', array(
4308 'user1' => $USER->id,
4309 'user2' => $user->id,
4310 $contacturlaction => $user->id,
4311 'sesskey' => sesskey())
4313 'image' => $contactimage,
4314 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4315 'page' => $this->page
4319 } else {
4320 $heading = null;
4325 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4326 return $this->render_context_header($contextheader);
4330 * Renders the skip links for the page.
4332 * @param array $links List of skip links.
4333 * @return string HTML for the skip links.
4335 public function render_skip_links($links) {
4336 $context = [ 'links' => []];
4338 foreach ($links as $url => $text) {
4339 $context['links'][] = [ 'url' => $url, 'text' => $text];
4342 return $this->render_from_template('core/skip_links', $context);
4346 * Renders the header bar.
4348 * @param context_header $contextheader Header bar object.
4349 * @return string HTML for the header bar.
4351 protected function render_context_header(context_header $contextheader) {
4353 // Generate the heading first and before everything else as we might have to do an early return.
4354 if (!isset($contextheader->heading)) {
4355 $heading = $this->heading($this->page->heading, $contextheader->headinglevel);
4356 } else {
4357 $heading = $this->heading($contextheader->heading, $contextheader->headinglevel);
4360 $showheader = empty($this->page->layout_options['nocontextheader']);
4361 if (!$showheader) {
4362 // Return the heading wrapped in an sr-only element so it is only visible to screen-readers.
4363 return html_writer::div($heading, 'sr-only');
4366 // All the html stuff goes here.
4367 $html = html_writer::start_div('page-context-header');
4369 // Image data.
4370 if (isset($contextheader->imagedata)) {
4371 // Header specific image.
4372 $html .= html_writer::div($contextheader->imagedata, 'page-header-image icon-size-7');
4375 // Headings.
4376 if (isset($contextheader->prefix)) {
4377 $prefix = html_writer::div($contextheader->prefix, 'text-muted');
4378 $heading = $prefix . $heading;
4380 $html .= html_writer::tag('div', $heading, array('class' => 'page-header-headings'));
4382 // Buttons.
4383 if (isset($contextheader->additionalbuttons)) {
4384 $html .= html_writer::start_div('btn-group header-button-group');
4385 foreach ($contextheader->additionalbuttons as $button) {
4386 if (!isset($button->page)) {
4387 // Include js for messaging.
4388 if ($button['buttontype'] === 'togglecontact') {
4389 \core_message\helper::togglecontact_requirejs();
4391 if ($button['buttontype'] === 'message') {
4392 \core_message\helper::messageuser_requirejs();
4394 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4395 'class' => 'iconsmall',
4396 'role' => 'presentation'
4398 $image .= html_writer::span($button['title'], 'header-button-title');
4399 } else {
4400 $image = html_writer::empty_tag('img', array(
4401 'src' => $button['formattedimage'],
4402 'role' => 'presentation'
4405 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4407 $html .= html_writer::end_div();
4409 $html .= html_writer::end_div();
4411 return $html;
4415 * Wrapper for header elements.
4417 * @return string HTML to display the main header.
4419 public function full_header() {
4420 $pagetype = $this->page->pagetype;
4421 $homepage = get_home_page();
4422 $homepagetype = null;
4423 // Add a special case since /my/courses is a part of the /my subsystem.
4424 if ($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES) {
4425 $homepagetype = 'my-index';
4426 } else if ($homepage == HOMEPAGE_SITE) {
4427 $homepagetype = 'site-index';
4429 if ($this->page->include_region_main_settings_in_header_actions() &&
4430 !$this->page->blocks->is_block_present('settings')) {
4431 // Only include the region main settings if the page has requested it and it doesn't already have
4432 // the settings block on it. The region main settings are included in the settings block and
4433 // duplicating the content causes behat failures.
4434 $this->page->add_header_action(html_writer::div(
4435 $this->region_main_settings_menu(),
4436 'd-print-none',
4437 ['id' => 'region-main-settings-menu']
4441 $header = new stdClass();
4442 $header->settingsmenu = $this->context_header_settings_menu();
4443 $header->contextheader = $this->context_header();
4444 $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
4445 $header->navbar = $this->navbar();
4446 $header->pageheadingbutton = $this->page_heading_button();
4447 $header->courseheader = $this->course_header();
4448 $header->headeractions = $this->page->get_header_actions();
4449 if (!empty($pagetype) && !empty($homepagetype) && $pagetype == $homepagetype) {
4450 $header->welcomemessage = \core_user::welcome_message();
4452 return $this->render_from_template('core/full_header', $header);
4456 * This is an optional menu that can be added to a layout by a theme. It contains the
4457 * menu for the course administration, only on the course main page.
4459 * @return string
4461 public function context_header_settings_menu() {
4462 $context = $this->page->context;
4463 $menu = new action_menu();
4465 $items = $this->page->navbar->get_items();
4466 $currentnode = end($items);
4468 $showcoursemenu = false;
4469 $showfrontpagemenu = false;
4470 $showusermenu = false;
4472 // We are on the course home page.
4473 if (($context->contextlevel == CONTEXT_COURSE) &&
4474 !empty($currentnode) &&
4475 ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
4476 $showcoursemenu = true;
4479 $courseformat = course_get_format($this->page->course);
4480 // This is a single activity course format, always show the course menu on the activity main page.
4481 if ($context->contextlevel == CONTEXT_MODULE &&
4482 !$courseformat->has_view_page()) {
4484 $this->page->navigation->initialise();
4485 $activenode = $this->page->navigation->find_active_node();
4486 // If the settings menu has been forced then show the menu.
4487 if ($this->page->is_settings_menu_forced()) {
4488 $showcoursemenu = true;
4489 } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
4490 $activenode->type == navigation_node::TYPE_RESOURCE)) {
4492 // We only want to show the menu on the first page of the activity. This means
4493 // the breadcrumb has no additional nodes.
4494 if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
4495 $showcoursemenu = true;
4500 // This is the site front page.
4501 if ($context->contextlevel == CONTEXT_COURSE &&
4502 !empty($currentnode) &&
4503 $currentnode->key === 'home') {
4504 $showfrontpagemenu = true;
4507 // This is the user profile page.
4508 if ($context->contextlevel == CONTEXT_USER &&
4509 !empty($currentnode) &&
4510 ($currentnode->key === 'myprofile')) {
4511 $showusermenu = true;
4514 if ($showfrontpagemenu) {
4515 $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
4516 if ($settingsnode) {
4517 // Build an action menu based on the visible nodes from this navigation tree.
4518 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4520 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4521 if ($skipped) {
4522 $text = get_string('morenavigationlinks');
4523 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4524 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4525 $menu->add_secondary_action($link);
4528 } else if ($showcoursemenu) {
4529 $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
4530 if ($settingsnode) {
4531 // Build an action menu based on the visible nodes from this navigation tree.
4532 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4534 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4535 if ($skipped) {
4536 $text = get_string('morenavigationlinks');
4537 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4538 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4539 $menu->add_secondary_action($link);
4542 } else if ($showusermenu) {
4543 // Get the course admin node from the settings navigation.
4544 $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
4545 if ($settingsnode) {
4546 // Build an action menu based on the visible nodes from this navigation tree.
4547 $this->build_action_menu_from_navigation($menu, $settingsnode);
4551 return $this->render($menu);
4555 * Take a node in the nav tree and make an action menu out of it.
4556 * The links are injected in the action menu.
4558 * @param action_menu $menu
4559 * @param navigation_node $node
4560 * @param boolean $indent
4561 * @param boolean $onlytopleafnodes
4562 * @return boolean nodesskipped - True if nodes were skipped in building the menu
4564 protected function build_action_menu_from_navigation(action_menu $menu,
4565 navigation_node $node,
4566 $indent = false,
4567 $onlytopleafnodes = false) {
4568 $skipped = false;
4569 // Build an action menu based on the visible nodes from this navigation tree.
4570 foreach ($node->children as $menuitem) {
4571 if ($menuitem->display) {
4572 if ($onlytopleafnodes && $menuitem->children->count()) {
4573 $skipped = true;
4574 continue;
4576 if ($menuitem->action) {
4577 if ($menuitem->action instanceof action_link) {
4578 $link = $menuitem->action;
4579 // Give preference to setting icon over action icon.
4580 if (!empty($menuitem->icon)) {
4581 $link->icon = $menuitem->icon;
4583 } else {
4584 $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
4586 } else {
4587 if ($onlytopleafnodes) {
4588 $skipped = true;
4589 continue;
4591 $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
4593 if ($indent) {
4594 $link->add_class('ml-4');
4596 if (!empty($menuitem->classes)) {
4597 $link->add_class(implode(" ", $menuitem->classes));
4600 $menu->add_secondary_action($link);
4601 $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
4604 return $skipped;
4608 * This is an optional menu that can be added to a layout by a theme. It contains the
4609 * menu for the most specific thing from the settings block. E.g. Module administration.
4611 * @return string
4613 public function region_main_settings_menu() {
4614 $context = $this->page->context;
4615 $menu = new action_menu();
4617 if ($context->contextlevel == CONTEXT_MODULE) {
4619 $this->page->navigation->initialise();
4620 $node = $this->page->navigation->find_active_node();
4621 $buildmenu = false;
4622 // If the settings menu has been forced then show the menu.
4623 if ($this->page->is_settings_menu_forced()) {
4624 $buildmenu = true;
4625 } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
4626 $node->type == navigation_node::TYPE_RESOURCE)) {
4628 $items = $this->page->navbar->get_items();
4629 $navbarnode = end($items);
4630 // We only want to show the menu on the first page of the activity. This means
4631 // the breadcrumb has no additional nodes.
4632 if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
4633 $buildmenu = true;
4636 if ($buildmenu) {
4637 // Get the course admin node from the settings navigation.
4638 $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
4639 if ($node) {
4640 // Build an action menu based on the visible nodes from this navigation tree.
4641 $this->build_action_menu_from_navigation($menu, $node);
4645 } else if ($context->contextlevel == CONTEXT_COURSECAT) {
4646 // For course category context, show category settings menu, if we're on the course category page.
4647 if ($this->page->pagetype === 'course-index-category') {
4648 $node = $this->page->settingsnav->find('categorysettings', navigation_node::TYPE_CONTAINER);
4649 if ($node) {
4650 // Build an action menu based on the visible nodes from this navigation tree.
4651 $this->build_action_menu_from_navigation($menu, $node);
4655 } else {
4656 $items = $this->page->navbar->get_items();
4657 $navbarnode = end($items);
4659 if ($navbarnode && ($navbarnode->key === 'participants')) {
4660 $node = $this->page->settingsnav->find('users', navigation_node::TYPE_CONTAINER);
4661 if ($node) {
4662 // Build an action menu based on the visible nodes from this navigation tree.
4663 $this->build_action_menu_from_navigation($menu, $node);
4668 return $this->render($menu);
4672 * Displays the list of tags associated with an entry
4674 * @param array $tags list of instances of core_tag or stdClass
4675 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4676 * to use default, set to '' (empty string) to omit the label completely
4677 * @param string $classes additional classes for the enclosing div element
4678 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4679 * will be appended to the end, JS will toggle the rest of the tags
4680 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4681 * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
4682 * @return string
4684 public function tag_list($tags, $label = null, $classes = '', $limit = 10,
4685 $pagecontext = null, $accesshidelabel = false) {
4686 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
4687 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4691 * Renders element for inline editing of any value
4693 * @param \core\output\inplace_editable $element
4694 * @return string
4696 public function render_inplace_editable(\core\output\inplace_editable $element) {
4697 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4701 * Renders a bar chart.
4703 * @param \core\chart_bar $chart The chart.
4704 * @return string.
4706 public function render_chart_bar(\core\chart_bar $chart) {
4707 return $this->render_chart($chart);
4711 * Renders a line chart.
4713 * @param \core\chart_line $chart The chart.
4714 * @return string.
4716 public function render_chart_line(\core\chart_line $chart) {
4717 return $this->render_chart($chart);
4721 * Renders a pie chart.
4723 * @param \core\chart_pie $chart The chart.
4724 * @return string.
4726 public function render_chart_pie(\core\chart_pie $chart) {
4727 return $this->render_chart($chart);
4731 * Renders a chart.
4733 * @param \core\chart_base $chart The chart.
4734 * @param bool $withtable Whether to include a data table with the chart.
4735 * @return string.
4737 public function render_chart(\core\chart_base $chart, $withtable = true) {
4738 $chartdata = json_encode($chart);
4739 return $this->render_from_template('core/chart', (object) [
4740 'chartdata' => $chartdata,
4741 'withtable' => $withtable
4746 * Renders the login form.
4748 * @param \core_auth\output\login $form The renderable.
4749 * @return string
4751 public function render_login(\core_auth\output\login $form) {
4752 global $CFG, $SITE;
4754 $context = $form->export_for_template($this);
4756 // Override because rendering is not supported in template yet.
4757 if ($CFG->rememberusername == 0) {
4758 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabledonlysession');
4759 } else {
4760 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
4762 $context->errorformatted = $this->error_text($context->error);
4763 $url = $this->get_logo_url();
4764 if ($url) {
4765 $url = $url->out(false);
4767 $context->logourl = $url;
4768 $context->sitename = format_string($SITE->fullname, true,
4769 ['context' => context_course::instance(SITEID), "escape" => false]);
4771 return $this->render_from_template('core/loginform', $context);
4775 * Renders an mform element from a template.
4777 * @param HTML_QuickForm_element $element element
4778 * @param bool $required if input is required field
4779 * @param bool $advanced if input is an advanced field
4780 * @param string $error error message to display
4781 * @param bool $ingroup True if this element is rendered as part of a group
4782 * @return mixed string|bool
4784 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4785 $templatename = 'core_form/element-' . $element->getType();
4786 if ($ingroup) {
4787 $templatename .= "-inline";
4789 try {
4790 // We call this to generate a file not found exception if there is no template.
4791 // We don't want to call export_for_template if there is no template.
4792 core\output\mustache_template_finder::get_template_filepath($templatename);
4794 if ($element instanceof templatable) {
4795 $elementcontext = $element->export_for_template($this);
4797 $helpbutton = '';
4798 if (method_exists($element, 'getHelpButton')) {
4799 $helpbutton = $element->getHelpButton();
4801 $label = $element->getLabel();
4802 $text = '';
4803 if (method_exists($element, 'getText')) {
4804 // There currently exists code that adds a form element with an empty label.
4805 // If this is the case then set the label to the description.
4806 if (empty($label)) {
4807 $label = $element->getText();
4808 } else {
4809 $text = $element->getText();
4813 // Generate the form element wrapper ids and names to pass to the template.
4814 // This differs between group and non-group elements.
4815 if ($element->getType() === 'group') {
4816 // Group element.
4817 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
4818 $elementcontext['wrapperid'] = $elementcontext['id'];
4820 // Ensure group elements pass through the group name as the element name.
4821 $elementcontext['name'] = $elementcontext['groupname'];
4822 } else {
4823 // Non grouped element.
4824 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
4825 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
4828 $context = array(
4829 'element' => $elementcontext,
4830 'label' => $label,
4831 'text' => $text,
4832 'required' => $required,
4833 'advanced' => $advanced,
4834 'helpbutton' => $helpbutton,
4835 'error' => $error
4837 return $this->render_from_template($templatename, $context);
4839 } catch (Exception $e) {
4840 // No template for this element.
4841 return false;
4846 * Render the login signup form into a nice template for the theme.
4848 * @param mform $form
4849 * @return string
4851 public function render_login_signup_form($form) {
4852 global $SITE;
4854 $context = $form->export_for_template($this);
4855 $url = $this->get_logo_url();
4856 if ($url) {
4857 $url = $url->out(false);
4859 $context['logourl'] = $url;
4860 $context['sitename'] = format_string($SITE->fullname, true,
4861 ['context' => context_course::instance(SITEID), "escape" => false]);
4863 return $this->render_from_template('core/signup_form_layout', $context);
4867 * Render the verify age and location page into a nice template for the theme.
4869 * @param \core_auth\output\verify_age_location_page $page The renderable
4870 * @return string
4872 protected function render_verify_age_location_page($page) {
4873 $context = $page->export_for_template($this);
4875 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4879 * Render the digital minor contact information page into a nice template for the theme.
4881 * @param \core_auth\output\digital_minor_page $page The renderable
4882 * @return string
4884 protected function render_digital_minor_page($page) {
4885 $context = $page->export_for_template($this);
4887 return $this->render_from_template('core/auth_digital_minor_page', $context);
4891 * Renders a progress bar.
4893 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4895 * @param progress_bar $bar The bar.
4896 * @return string HTML fragment
4898 public function render_progress_bar(progress_bar $bar) {
4899 $data = $bar->export_for_template($this);
4900 return $this->render_from_template('core/progress_bar', $data);
4904 * Renders an update to a progress bar.
4906 * Note: This does not cleanly map to a renderable class and should
4907 * never be used directly.
4909 * @param string $id
4910 * @param float $percent
4911 * @param string $msg Message
4912 * @param string $estimate time remaining message
4913 * @return string ascii fragment
4915 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
4916 return html_writer::script(js_writer::function_call('updateProgressBar', [$id, $percent, $msg, $estimate]));
4920 * Renders element for a toggle-all checkbox.
4922 * @param \core\output\checkbox_toggleall $element
4923 * @return string
4925 public function render_checkbox_toggleall(\core\output\checkbox_toggleall $element) {
4926 return $this->render_from_template($element->get_template(), $element->export_for_template($this));
4930 * Renders the tertiary nav for the participants page
4932 * @param object $course The course we are operating within
4933 * @param string|null $renderedbuttons Any additional buttons/content to be displayed in line with the nav
4934 * @return string
4936 public function render_participants_tertiary_nav(object $course, ?string $renderedbuttons = null) {
4937 $actionbar = new \core\output\participants_action_bar($course, $this->page, $renderedbuttons);
4938 $content = $this->render_from_template('core_course/participants_actionbar', $actionbar->export_for_template($this));
4939 return $content ?: "";
4943 * Renders release information in the footer popup
4944 * @return string Moodle release info.
4946 public function moodle_release() {
4947 global $CFG;
4948 if (!during_initial_install() && is_siteadmin()) {
4949 return $CFG->release;
4954 * Generate the add block button when editing mode is turned on and the user can edit blocks.
4956 * @param string $region where new blocks should be added.
4957 * @return string html for the add block button.
4959 public function addblockbutton($region = ''): string {
4960 $addblockbutton = '';
4961 if (isset($this->page->theme->addblockposition) &&
4962 $this->page->user_is_editing() &&
4963 $this->page->user_can_edit_blocks() &&
4964 $this->page->pagelayout !== 'mycourses'
4966 $params = ['bui_addblock' => '', 'sesskey' => sesskey()];
4967 if (!empty($region)) {
4968 $params['bui_blockregion'] = $region;
4970 $url = new moodle_url($this->page->url, $params);
4971 $addblockbutton = $this->render_from_template('core/add_block_button',
4973 'link' => $url->out(false),
4974 'escapedlink' => "?{$url->get_query_string(false)}",
4975 'pageType' => $this->page->pagetype,
4976 'pageLayout' => $this->page->pagelayout,
4977 'subPage' => $this->page->subpage,
4981 return $addblockbutton;
4986 * A renderer that generates output for command-line scripts.
4988 * The implementation of this renderer is probably incomplete.
4990 * @copyright 2009 Tim Hunt
4991 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4992 * @since Moodle 2.0
4993 * @package core
4994 * @category output
4996 class core_renderer_cli extends core_renderer {
4999 * @var array $progressmaximums stores the largest percentage for a progress bar.
5000 * @return string ascii fragment
5002 private $progressmaximums = [];
5005 * Returns the page header.
5007 * @return string HTML fragment
5009 public function header() {
5010 return $this->page->heading . "\n";
5014 * Renders a Check API result
5016 * To aid in CLI consistency this status is NOT translated and the visual
5017 * width is always exactly 10 chars.
5019 * @param core\check\result $result
5020 * @return string HTML fragment
5022 protected function render_check_result(core\check\result $result) {
5023 $status = $result->get_status();
5025 $labels = [
5026 core\check\result::NA => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' NA ',
5027 core\check\result::OK => ' ' . cli_ansi_format('<colour:green>') . ' OK ',
5028 core\check\result::INFO => ' ' . cli_ansi_format('<colour:blue>' ) . ' INFO ',
5029 core\check\result::UNKNOWN => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' UNKNOWN ',
5030 core\check\result::WARNING => ' ' . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
5031 core\check\result::ERROR => ' ' . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
5032 core\check\result::CRITICAL => '' . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
5034 $string = $labels[$status] . cli_ansi_format('<colour:normal>');
5035 return $string;
5039 * Renders a Check API result
5041 * @param result $result
5042 * @return string fragment
5044 public function check_result(core\check\result $result) {
5045 return $this->render_check_result($result);
5049 * Renders a progress bar.
5051 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
5053 * @param progress_bar $bar The bar.
5054 * @return string ascii fragment
5056 public function render_progress_bar(progress_bar $bar) {
5057 global $CFG;
5059 $size = 55; // The width of the progress bar in chars.
5060 $ascii = "\n";
5062 if (stream_isatty(STDOUT)) {
5063 require_once($CFG->libdir.'/clilib.php');
5065 $ascii .= "[" . str_repeat(' ', $size) . "] 0% \n";
5066 return cli_ansi_format($ascii);
5069 $this->progressmaximums[$bar->get_id()] = 0;
5070 $ascii .= '[';
5071 return $ascii;
5075 * Renders an update to a progress bar.
5077 * Note: This does not cleanly map to a renderable class and should
5078 * never be used directly.
5080 * @param string $id
5081 * @param float $percent
5082 * @param string $msg Message
5083 * @param string $estimate time remaining message
5084 * @return string ascii fragment
5086 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
5087 $size = 55; // The width of the progress bar in chars.
5088 $ascii = '';
5090 // If we are rendering to a terminal then we can safely use ansii codes
5091 // to move the cursor and redraw the complete progress bar each time
5092 // it is updated.
5093 if (stream_isatty(STDOUT)) {
5094 $colour = $percent == 100 ? 'green' : 'blue';
5096 $done = $percent * $size * 0.01;
5097 $whole = floor($done);
5098 $bar = "<colour:$colour>";
5099 $bar .= str_repeat('█', $whole);
5101 if ($whole < $size) {
5102 // By using unicode chars for partial blocks we can have higher
5103 // precision progress bar.
5104 $fraction = floor(($done - $whole) * 8);
5105 $bar .= core_text::substr(' ▏▎▍▌▋▊▉', $fraction, 1);
5107 // Fill the rest of the empty bar.
5108 $bar .= str_repeat(' ', $size - $whole - 1);
5111 $bar .= '<colour:normal>';
5113 if ($estimate) {
5114 $estimate = "- $estimate";
5117 $ascii .= '<cursor:up>';
5118 $ascii .= '<cursor:up>';
5119 $ascii .= sprintf("[$bar] %3.1f%% %-22s\n", $percent, $estimate);
5120 $ascii .= sprintf("%-80s\n", $msg);
5121 return cli_ansi_format($ascii);
5124 // If we are not rendering to a tty, ie when piped to another command
5125 // or on windows we need to progressively render the progress bar
5126 // which can only ever go forwards.
5127 $done = round($percent * $size * 0.01);
5128 $delta = max(0, $done - $this->progressmaximums[$id]);
5130 $ascii .= str_repeat('#', $delta);
5131 if ($percent >= 100 && $delta > 0) {
5132 $ascii .= sprintf("] %3.1f%%\n$msg\n", $percent);
5134 $this->progressmaximums[$id] += $delta;
5135 return $ascii;
5139 * Returns a template fragment representing a Heading.
5141 * @param string $text The text of the heading
5142 * @param int $level The level of importance of the heading
5143 * @param string $classes A space-separated list of CSS classes
5144 * @param string $id An optional ID
5145 * @return string A template fragment for a heading
5147 public function heading($text, $level = 2, $classes = 'main', $id = null) {
5148 $text .= "\n";
5149 switch ($level) {
5150 case 1:
5151 return '=>' . $text;
5152 case 2:
5153 return '-->' . $text;
5154 default:
5155 return $text;
5160 * Returns a template fragment representing a fatal error.
5162 * @param string $message The message to output
5163 * @param string $moreinfourl URL where more info can be found about the error
5164 * @param string $link Link for the Continue button
5165 * @param array $backtrace The execution backtrace
5166 * @param string $debuginfo Debugging information
5167 * @return string A template fragment for a fatal error
5169 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5170 global $CFG;
5172 $output = "!!! $message !!!\n";
5174 if ($CFG->debugdeveloper) {
5175 if (!empty($debuginfo)) {
5176 $output .= $this->notification($debuginfo, 'notifytiny');
5178 if (!empty($backtrace)) {
5179 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
5183 return $output;
5187 * Returns a template fragment representing a notification.
5189 * @param string $message The message to print out.
5190 * @param string $type The type of notification. See constants on \core\output\notification.
5191 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5192 * @return string A template fragment for a notification
5194 public function notification($message, $type = null, $closebutton = true) {
5195 $message = clean_text($message);
5196 if ($type === 'notifysuccess' || $type === 'success') {
5197 return "++ $message ++\n";
5199 return "!! $message !!\n";
5203 * There is no footer for a cli request, however we must override the
5204 * footer method to prevent the default footer.
5206 public function footer() {}
5209 * Render a notification (that is, a status message about something that has
5210 * just happened).
5212 * @param \core\output\notification $notification the notification to print out
5213 * @return string plain text output
5215 public function render_notification(\core\output\notification $notification) {
5216 return $this->notification($notification->get_message(), $notification->get_message_type());
5222 * A renderer that generates output for ajax scripts.
5224 * This renderer prevents accidental sends back only json
5225 * encoded error messages, all other output is ignored.
5227 * @copyright 2010 Petr Skoda
5228 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5229 * @since Moodle 2.0
5230 * @package core
5231 * @category output
5233 class core_renderer_ajax extends core_renderer {
5236 * Returns a template fragment representing a fatal error.
5238 * @param string $message The message to output
5239 * @param string $moreinfourl URL where more info can be found about the error
5240 * @param string $link Link for the Continue button
5241 * @param array $backtrace The execution backtrace
5242 * @param string $debuginfo Debugging information
5243 * @return string A template fragment for a fatal error
5245 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5246 global $CFG;
5248 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
5250 $e = new stdClass();
5251 $e->error = $message;
5252 $e->errorcode = $errorcode;
5253 $e->stacktrace = NULL;
5254 $e->debuginfo = NULL;
5255 $e->reproductionlink = NULL;
5256 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
5257 $link = (string) $link;
5258 if ($link) {
5259 $e->reproductionlink = $link;
5261 if (!empty($debuginfo)) {
5262 $e->debuginfo = $debuginfo;
5264 if (!empty($backtrace)) {
5265 $e->stacktrace = format_backtrace($backtrace, true);
5268 $this->header();
5269 return json_encode($e);
5273 * Used to display a notification.
5274 * For the AJAX notifications are discarded.
5276 * @param string $message The message to print out.
5277 * @param string $type The type of notification. See constants on \core\output\notification.
5278 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5280 public function notification($message, $type = null, $closebutton = true) {
5284 * Used to display a redirection message.
5285 * AJAX redirections should not occur and as such redirection messages
5286 * are discarded.
5288 * @param moodle_url|string $encodedurl
5289 * @param string $message
5290 * @param int $delay
5291 * @param bool $debugdisableredirect
5292 * @param string $messagetype The type of notification to show the message in.
5293 * See constants on \core\output\notification.
5295 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
5296 $messagetype = \core\output\notification::NOTIFY_INFO) {}
5299 * Prepares the start of an AJAX output.
5301 public function header() {
5302 // unfortunately YUI iframe upload does not support application/json
5303 if (!empty($_FILES)) {
5304 @header('Content-type: text/plain; charset=utf-8');
5305 if (!core_useragent::supports_json_contenttype()) {
5306 @header('X-Content-Type-Options: nosniff');
5308 } else if (!core_useragent::supports_json_contenttype()) {
5309 @header('Content-type: text/plain; charset=utf-8');
5310 @header('X-Content-Type-Options: nosniff');
5311 } else {
5312 @header('Content-type: application/json; charset=utf-8');
5315 // Headers to make it not cacheable and json
5316 @header('Cache-Control: no-store, no-cache, must-revalidate');
5317 @header('Cache-Control: post-check=0, pre-check=0', false);
5318 @header('Pragma: no-cache');
5319 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
5320 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
5321 @header('Accept-Ranges: none');
5325 * There is no footer for an AJAX request, however we must override the
5326 * footer method to prevent the default footer.
5328 public function footer() {}
5331 * No need for headers in an AJAX request... this should never happen.
5332 * @param string $text
5333 * @param int $level
5334 * @param string $classes
5335 * @param string $id
5337 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
5343 * The maintenance renderer.
5345 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
5346 * is running a maintenance related task.
5347 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
5349 * @since Moodle 2.6
5350 * @package core
5351 * @category output
5352 * @copyright 2013 Sam Hemelryk
5353 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5355 class core_renderer_maintenance extends core_renderer {
5358 * Initialises the renderer instance.
5360 * @param moodle_page $page
5361 * @param string $target
5362 * @throws coding_exception
5364 public function __construct(moodle_page $page, $target) {
5365 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
5366 throw new coding_exception('Invalid request for the maintenance renderer.');
5368 parent::__construct($page, $target);
5372 * Does nothing. The maintenance renderer cannot produce blocks.
5374 * @param block_contents $bc
5375 * @param string $region
5376 * @return string
5378 public function block(block_contents $bc, $region) {
5379 return '';
5383 * Does nothing. The maintenance renderer cannot produce blocks.
5385 * @param string $region
5386 * @param array $classes
5387 * @param string $tag
5388 * @param boolean $fakeblocksonly
5389 * @return string
5391 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
5392 return '';
5396 * Does nothing. The maintenance renderer cannot produce blocks.
5398 * @param string $region
5399 * @param boolean $fakeblocksonly Output fake block only.
5400 * @return string
5402 public function blocks_for_region($region, $fakeblocksonly = false) {
5403 return '';
5407 * Does nothing. The maintenance renderer cannot produce a course content header.
5409 * @param bool $onlyifnotcalledbefore
5410 * @return string
5412 public function course_content_header($onlyifnotcalledbefore = false) {
5413 return '';
5417 * Does nothing. The maintenance renderer cannot produce a course content footer.
5419 * @param bool $onlyifnotcalledbefore
5420 * @return string
5422 public function course_content_footer($onlyifnotcalledbefore = false) {
5423 return '';
5427 * Does nothing. The maintenance renderer cannot produce a course header.
5429 * @return string
5431 public function course_header() {
5432 return '';
5436 * Does nothing. The maintenance renderer cannot produce a course footer.
5438 * @return string
5440 public function course_footer() {
5441 return '';
5445 * Does nothing. The maintenance renderer cannot produce a custom menu.
5447 * @param string $custommenuitems
5448 * @return string
5450 public function custom_menu($custommenuitems = '') {
5451 return '';
5455 * Does nothing. The maintenance renderer cannot produce a file picker.
5457 * @param array $options
5458 * @return string
5460 public function file_picker($options) {
5461 return '';
5465 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
5467 * @param array $dir
5468 * @return string
5470 public function htmllize_file_tree($dir) {
5471 return '';
5476 * Overridden confirm message for upgrades.
5478 * @param string $message The question to ask the user
5479 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5480 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5481 * @param array $displayoptions optional extra display options
5482 * @return string HTML fragment
5484 public function confirm($message, $continue, $cancel, array $displayoptions = []) {
5485 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5486 // from any previous version of Moodle).
5487 if ($continue instanceof single_button) {
5488 $continue->primary = true;
5489 } else if (is_string($continue)) {
5490 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
5491 } else if ($continue instanceof moodle_url) {
5492 $continue = new single_button($continue, get_string('continue'), 'post', true);
5493 } else {
5494 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5495 ' (string/moodle_url) or a single_button instance.');
5498 if ($cancel instanceof single_button) {
5499 $output = '';
5500 } else if (is_string($cancel)) {
5501 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5502 } else if ($cancel instanceof moodle_url) {
5503 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5504 } else {
5505 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5506 ' (string/moodle_url) or a single_button instance.');
5509 $output = $this->box_start('generalbox', 'notice');
5510 $output .= html_writer::tag('h4', get_string('confirm'));
5511 $output .= html_writer::tag('p', $message);
5512 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
5513 $output .= $this->box_end();
5514 return $output;
5518 * Does nothing. The maintenance renderer does not support JS.
5520 * @param block_contents $bc
5522 public function init_block_hider_js(block_contents $bc) {
5523 // Does nothing.
5527 * Does nothing. The maintenance renderer cannot produce language menus.
5529 * @return string
5531 public function lang_menu() {
5532 return '';
5536 * Does nothing. The maintenance renderer has no need for login information.
5538 * @param null $withlinks
5539 * @return string
5541 public function login_info($withlinks = null) {
5542 return '';
5546 * Secure login info.
5548 * @return string
5550 public function secure_login_info() {
5551 return $this->login_info(false);
5555 * Does nothing. The maintenance renderer cannot produce user pictures.
5557 * @param stdClass $user
5558 * @param array $options
5559 * @return string
5561 public function user_picture(stdClass $user, array $options = null) {
5562 return '';