MDL-74955 reportbuilder: external method for listing custom reports.
[moodle.git] / lib / outputrenderers.php
blob0b39a4e0af053faf6f7d27e87298934cd6b6c4b1
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\output\named_templatable;
39 use core_completion\cm_completion_details;
40 use core_course\output\activity_information;
42 defined('MOODLE_INTERNAL') || die();
44 /**
45 * Simple base class for Moodle renderers.
47 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
49 * Also has methods to facilitate generating HTML output.
51 * @copyright 2009 Tim Hunt
52 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 * @since Moodle 2.0
54 * @package core
55 * @category output
57 class renderer_base {
58 /**
59 * @var xhtml_container_stack The xhtml_container_stack to use.
61 protected $opencontainers;
63 /**
64 * @var moodle_page The Moodle page the renderer has been created to assist with.
66 protected $page;
68 /**
69 * @var string The requested rendering target.
71 protected $target;
73 /**
74 * @var Mustache_Engine $mustache The mustache template compiler
76 private $mustache;
78 /**
79 * Return an instance of the mustache class.
81 * @since 2.9
82 * @return Mustache_Engine
84 protected function get_mustache() {
85 global $CFG;
87 if ($this->mustache === null) {
88 require_once("{$CFG->libdir}/filelib.php");
90 $themename = $this->page->theme->name;
91 $themerev = theme_get_revision();
93 // Create new localcache directory.
94 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
96 // Remove old localcache directories.
97 $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR);
98 foreach ($mustachecachedirs as $localcachedir) {
99 $cachedrev = [];
100 preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
101 $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
102 if ($cachedrev > 0 && $cachedrev < $themerev) {
103 fulldelete($localcachedir);
107 $loader = new \core\output\mustache_filesystem_loader();
108 $stringhelper = new \core\output\mustache_string_helper();
109 $cleanstringhelper = new \core\output\mustache_clean_string_helper();
110 $quotehelper = new \core\output\mustache_quote_helper();
111 $jshelper = new \core\output\mustache_javascript_helper($this->page);
112 $pixhelper = new \core\output\mustache_pix_helper($this);
113 $shortentexthelper = new \core\output\mustache_shorten_text_helper();
114 $userdatehelper = new \core\output\mustache_user_date_helper();
116 // We only expose the variables that are exposed to JS templates.
117 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
119 $helpers = array('config' => $safeconfig,
120 'str' => array($stringhelper, 'str'),
121 'cleanstr' => array($cleanstringhelper, 'cleanstr'),
122 'quote' => array($quotehelper, 'quote'),
123 'js' => array($jshelper, 'help'),
124 'pix' => array($pixhelper, 'pix'),
125 'shortentext' => array($shortentexthelper, 'shorten'),
126 'userdate' => array($userdatehelper, 'transform'),
129 $this->mustache = new \core\output\mustache_engine(array(
130 'cache' => $cachedir,
131 'escape' => 's',
132 'loader' => $loader,
133 'helpers' => $helpers,
134 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS],
135 // Don't allow the JavaScript helper to be executed from within another
136 // helper. If it's allowed it can be used by users to inject malicious
137 // JS into the page.
138 'disallowednestedhelpers' => ['js'],
139 // Disable lambda rendering - content in helpers is already rendered, no need to render it again.
140 'disable_lambda_rendering' => true,
145 return $this->mustache;
150 * Constructor
152 * The constructor takes two arguments. The first is the page that the renderer
153 * has been created to assist with, and the second is the target.
154 * The target is an additional identifier that can be used to load different
155 * renderers for different options.
157 * @param moodle_page $page the page we are doing output for.
158 * @param string $target one of rendering target constants
160 public function __construct(moodle_page $page, $target) {
161 $this->opencontainers = $page->opencontainers;
162 $this->page = $page;
163 $this->target = $target;
167 * Renders a template by name with the given context.
169 * The provided data needs to be array/stdClass made up of only simple types.
170 * Simple types are array,stdClass,bool,int,float,string
172 * @since 2.9
173 * @param array|stdClass $context Context containing data for the template.
174 * @return string|boolean
176 public function render_from_template($templatename, $context) {
177 static $templatecache = array();
178 $mustache = $this->get_mustache();
180 try {
181 // Grab a copy of the existing helper to be restored later.
182 $uniqidhelper = $mustache->getHelper('uniqid');
183 } catch (Mustache_Exception_UnknownHelperException $e) {
184 // Helper doesn't exist.
185 $uniqidhelper = null;
188 // Provide 1 random value that will not change within a template
189 // but will be different from template to template. This is useful for
190 // e.g. aria attributes that only work with id attributes and must be
191 // unique in a page.
192 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
193 if (isset($templatecache[$templatename])) {
194 $template = $templatecache[$templatename];
195 } else {
196 try {
197 $template = $mustache->loadTemplate($templatename);
198 $templatecache[$templatename] = $template;
199 } catch (Mustache_Exception_UnknownTemplateException $e) {
200 throw new moodle_exception('Unknown template: ' . $templatename);
204 $renderedtemplate = trim($template->render($context));
206 // If we had an existing uniqid helper then we need to restore it to allow
207 // handle nested calls of render_from_template.
208 if ($uniqidhelper) {
209 $mustache->addHelper('uniqid', $uniqidhelper);
212 return $renderedtemplate;
217 * Returns rendered widget.
219 * The provided widget needs to be an object that extends the renderable
220 * interface.
221 * If will then be rendered by a method based upon the classname for the widget.
222 * For instance a widget of class `crazywidget` will be rendered by a protected
223 * render_crazywidget method of this renderer.
224 * If no render_crazywidget method exists and crazywidget implements templatable,
225 * look for the 'crazywidget' template in the same component and render that.
227 * @param renderable $widget instance with renderable interface
228 * @return string
230 public function render(renderable $widget) {
231 $classparts = explode('\\', get_class($widget));
232 // Strip namespaces.
233 $classname = array_pop($classparts);
234 // Remove _renderable suffixes.
235 $classname = preg_replace('/_renderable$/', '', $classname);
237 $rendermethod = "render_{$classname}";
238 if (method_exists($this, $rendermethod)) {
239 // Call the render_[widget_name] function.
240 // Note: This has a higher priority than the named_templatable to allow the theme to override the template.
241 return $this->$rendermethod($widget);
244 if ($widget instanceof named_templatable) {
245 // This is a named templatable.
246 // Fetch the template name from the get_template_name function instead.
247 // Note: This has higher priority than the guessed template name.
248 return $this->render_from_template(
249 $widget->get_template_name($this),
250 $widget->export_for_template($this)
254 if ($widget instanceof templatable) {
255 // Guess the templat ename based on the class name.
256 // Note: There's no benefit to moving this aboved the named_templatable and this approach is more costly.
257 $component = array_shift($classparts);
258 if (!$component) {
259 $component = 'core';
261 $template = $component . '/' . $classname;
262 $context = $widget->export_for_template($this);
263 return $this->render_from_template($template, $context);
265 throw new coding_exception("Can not render widget, renderer method ('{$rendermethod}') not found.");
269 * Adds a JS action for the element with the provided id.
271 * This method adds a JS event for the provided component action to the page
272 * and then returns the id that the event has been attached to.
273 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
275 * @param component_action $action
276 * @param string $id
277 * @return string id of element, either original submitted or random new if not supplied
279 public function add_action_handler(component_action $action, $id = null) {
280 if (!$id) {
281 $id = html_writer::random_id($action->event);
283 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
284 return $id;
288 * Returns true is output has already started, and false if not.
290 * @return boolean true if the header has been printed.
292 public function has_started() {
293 return $this->page->state >= moodle_page::STATE_IN_BODY;
297 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
299 * @param mixed $classes Space-separated string or array of classes
300 * @return string HTML class attribute value
302 public static function prepare_classes($classes) {
303 if (is_array($classes)) {
304 return implode(' ', array_unique($classes));
306 return $classes;
310 * Return the direct URL for an image from the pix folder.
312 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
314 * @deprecated since Moodle 3.3
315 * @param string $imagename the name of the icon.
316 * @param string $component specification of one plugin like in get_string()
317 * @return moodle_url
319 public function pix_url($imagename, $component = 'moodle') {
320 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
321 return $this->page->theme->image_url($imagename, $component);
325 * Return the moodle_url for an image.
327 * The exact image location and extension is determined
328 * automatically by searching for gif|png|jpg|jpeg, please
329 * note there can not be diferent images with the different
330 * extension. The imagename is for historical reasons
331 * a relative path name, it may be changed later for core
332 * images. It is recommended to not use subdirectories
333 * in plugin and theme pix directories.
335 * There are three types of images:
336 * 1/ theme images - stored in theme/mytheme/pix/,
337 * use component 'theme'
338 * 2/ core images - stored in /pix/,
339 * overridden via theme/mytheme/pix_core/
340 * 3/ plugin images - stored in mod/mymodule/pix,
341 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
342 * example: image_url('comment', 'mod_glossary')
344 * @param string $imagename the pathname of the image
345 * @param string $component full plugin name (aka component) or 'theme'
346 * @return moodle_url
348 public function image_url($imagename, $component = 'moodle') {
349 return $this->page->theme->image_url($imagename, $component);
353 * Return the site's logo URL, if any.
355 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
356 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
357 * @return moodle_url|false
359 public function get_logo_url($maxwidth = null, $maxheight = 200) {
360 global $CFG;
361 $logo = get_config('core_admin', 'logo');
362 if (empty($logo)) {
363 return false;
366 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
367 // It's not worth the overhead of detecting and serving 2 different images based on the device.
369 // Hide the requested size in the file path.
370 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
372 // Use $CFG->themerev to prevent browser caching when the file changes.
373 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
374 theme_get_revision(), $logo);
378 * Return the site's compact logo URL, if any.
380 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
381 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
382 * @return moodle_url|false
384 public function get_compact_logo_url($maxwidth = 300, $maxheight = 300) {
385 global $CFG;
386 $logo = get_config('core_admin', 'logocompact');
387 if (empty($logo)) {
388 return false;
391 // Hide the requested size in the file path.
392 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
394 // Use $CFG->themerev to prevent browser caching when the file changes.
395 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
396 theme_get_revision(), $logo);
400 * Whether we should display the logo in the navbar.
402 * We will when there are no main logos, and we have compact logo.
404 * @return bool
406 public function should_display_navbar_logo() {
407 $logo = $this->get_compact_logo_url();
408 return !empty($logo);
412 * Whether we should display the main logo.
413 * @deprecated since Moodle 4.0
414 * @todo final deprecation. To be removed in Moodle 4.4 MDL-73165.
415 * @param int $headinglevel The heading level we want to check against.
416 * @return bool
418 public function should_display_main_logo($headinglevel = 1) {
419 debugging('should_display_main_logo() is deprecated and will be removed in Moodle 4.4.', DEBUG_DEVELOPER);
420 // Only render the logo if we're on the front page or login page and the we have a logo.
421 $logo = $this->get_logo_url();
422 if ($headinglevel == 1 && !empty($logo)) {
423 if ($this->page->pagelayout == 'frontpage' || $this->page->pagelayout == 'login') {
424 return true;
428 return false;
435 * Basis for all plugin renderers.
437 * @copyright Petr Skoda (skodak)
438 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
439 * @since Moodle 2.0
440 * @package core
441 * @category output
443 class plugin_renderer_base extends renderer_base {
446 * @var renderer_base|core_renderer A reference to the current renderer.
447 * The renderer provided here will be determined by the page but will in 90%
448 * of cases by the {@link core_renderer}
450 protected $output;
453 * Constructor method, calls the parent constructor
455 * @param moodle_page $page
456 * @param string $target one of rendering target constants
458 public function __construct(moodle_page $page, $target) {
459 if (empty($target) && $page->pagelayout === 'maintenance') {
460 // If the page is using the maintenance layout then we're going to force the target to maintenance.
461 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
462 // unavailable for this page layout.
463 $target = RENDERER_TARGET_MAINTENANCE;
465 $this->output = $page->get_renderer('core', null, $target);
466 parent::__construct($page, $target);
470 * Renders the provided widget and returns the HTML to display it.
472 * @param renderable $widget instance with renderable interface
473 * @return string
475 public function render(renderable $widget) {
476 $classname = get_class($widget);
478 // Strip namespaces.
479 $classname = preg_replace('/^.*\\\/', '', $classname);
481 // Keep a copy at this point, we may need to look for a deprecated method.
482 $deprecatedmethod = "render_{$classname}";
484 // Remove _renderable suffixes.
485 $classname = preg_replace('/_renderable$/', '', $classname);
486 $rendermethod = "render_{$classname}";
488 if (method_exists($this, $rendermethod)) {
489 // Call the render_[widget_name] function.
490 // Note: This has a higher priority than the named_templatable to allow the theme to override the template.
491 return $this->$rendermethod($widget);
494 if ($widget instanceof named_templatable) {
495 // This is a named templatable.
496 // Fetch the template name from the get_template_name function instead.
497 // Note: This has higher priority than the deprecated method which is not overridable by themes anyway.
498 return $this->render_from_template(
499 $widget->get_template_name($this),
500 $widget->export_for_template($this)
504 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
505 // This is exactly where we don't want to be.
506 // If you have arrived here you have a renderable component within your plugin that has the name
507 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
508 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
509 // and the _renderable suffix now gets removed when looking for a render method.
510 // You need to change your renderers render_blah_renderable to render_blah.
511 // Until you do this it will not be possible for a theme to override the renderer to override your method.
512 // Please do it ASAP.
513 static $debugged = [];
514 if (!isset($debugged[$deprecatedmethod])) {
515 debugging(sprintf(
516 'Deprecated call. Please rename your renderables render method from %s to %s.',
517 $deprecatedmethod,
518 $rendermethod
519 ), DEBUG_DEVELOPER);
520 $debugged[$deprecatedmethod] = true;
522 return $this->$deprecatedmethod($widget);
525 // Pass to core renderer if method not found here.
526 // Note: this is not a parent. This is _new_ renderer which respects the requested format, and output type.
527 return $this->output->render($widget);
531 * Magic method used to pass calls otherwise meant for the standard renderer
532 * to it to ensure we don't go causing unnecessary grief.
534 * @param string $method
535 * @param array $arguments
536 * @return mixed
538 public function __call($method, $arguments) {
539 if (method_exists('renderer_base', $method)) {
540 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
542 if (method_exists($this->output, $method)) {
543 return call_user_func_array(array($this->output, $method), $arguments);
544 } else {
545 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
552 * The standard implementation of the core_renderer interface.
554 * @copyright 2009 Tim Hunt
555 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
556 * @since Moodle 2.0
557 * @package core
558 * @category output
560 class core_renderer extends renderer_base {
562 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
563 * in layout files instead.
564 * @deprecated
565 * @var string used in {@link core_renderer::header()}.
567 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
570 * @var string Used to pass information from {@link core_renderer::doctype()} to
571 * {@link core_renderer::standard_head_html()}.
573 protected $contenttype;
576 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
577 * with {@link core_renderer::header()}.
579 protected $metarefreshtag = '';
582 * @var string Unique token for the closing HTML
584 protected $unique_end_html_token;
587 * @var string Unique token for performance information
589 protected $unique_performance_info_token;
592 * @var string Unique token for the main content.
594 protected $unique_main_content_token;
596 /** @var custom_menu_item language The language menu if created */
597 protected $language = null;
600 * Constructor
602 * @param moodle_page $page the page we are doing output for.
603 * @param string $target one of rendering target constants
605 public function __construct(moodle_page $page, $target) {
606 $this->opencontainers = $page->opencontainers;
607 $this->page = $page;
608 $this->target = $target;
610 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
611 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
612 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
616 * Get the DOCTYPE declaration that should be used with this page. Designed to
617 * be called in theme layout.php files.
619 * @return string the DOCTYPE declaration that should be used.
621 public function doctype() {
622 if ($this->page->theme->doctype === 'html5') {
623 $this->contenttype = 'text/html; charset=utf-8';
624 return "<!DOCTYPE html>\n";
626 } else if ($this->page->theme->doctype === 'xhtml5') {
627 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
628 return "<!DOCTYPE html>\n";
630 } else {
631 // legacy xhtml 1.0
632 $this->contenttype = 'text/html; charset=utf-8';
633 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
638 * The attributes that should be added to the <html> tag. Designed to
639 * be called in theme layout.php files.
641 * @return string HTML fragment.
643 public function htmlattributes() {
644 $return = get_html_lang(true);
645 $attributes = array();
646 if ($this->page->theme->doctype !== 'html5') {
647 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
650 // Give plugins an opportunity to add things like xml namespaces to the html element.
651 // This function should return an array of html attribute names => values.
652 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
653 foreach ($pluginswithfunction as $plugins) {
654 foreach ($plugins as $function) {
655 $newattrs = $function();
656 unset($newattrs['dir']);
657 unset($newattrs['lang']);
658 unset($newattrs['xmlns']);
659 unset($newattrs['xml:lang']);
660 $attributes += $newattrs;
664 foreach ($attributes as $key => $val) {
665 $val = s($val);
666 $return .= " $key=\"$val\"";
669 return $return;
673 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
674 * that should be included in the <head> tag. Designed to be called in theme
675 * layout.php files.
677 * @return string HTML fragment.
679 public function standard_head_html() {
680 global $CFG, $SESSION, $SITE;
682 // Before we output any content, we need to ensure that certain
683 // page components are set up.
685 // Blocks must be set up early as they may require javascript which
686 // has to be included in the page header before output is created.
687 foreach ($this->page->blocks->get_regions() as $region) {
688 $this->page->blocks->ensure_content_created($region, $this);
691 $output = '';
693 // Give plugins an opportunity to add any head elements. The callback
694 // must always return a string containing valid html head content.
695 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
696 foreach ($pluginswithfunction as $plugins) {
697 foreach ($plugins as $function) {
698 $output .= $function();
702 // Allow a url_rewrite plugin to setup any dynamic head content.
703 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
704 $class = $CFG->urlrewriteclass;
705 $output .= $class::html_head_setup();
708 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
709 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
710 // This is only set by the {@link redirect()} method
711 $output .= $this->metarefreshtag;
713 // Check if a periodic refresh delay has been set and make sure we arn't
714 // already meta refreshing
715 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
716 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
719 // Set up help link popups for all links with the helptooltip class
720 $this->page->requires->js_init_call('M.util.help_popups.setup');
722 $focus = $this->page->focuscontrol;
723 if (!empty($focus)) {
724 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
725 // This is a horrifically bad way to handle focus but it is passed in
726 // through messy formslib::moodleform
727 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
728 } else if (strpos($focus, '.')!==false) {
729 // Old style of focus, bad way to do it
730 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);
731 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
732 } else {
733 // Focus element with given id
734 $this->page->requires->js_function_call('focuscontrol', array($focus));
738 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
739 // any other custom CSS can not be overridden via themes and is highly discouraged
740 $urls = $this->page->theme->css_urls($this->page);
741 foreach ($urls as $url) {
742 $this->page->requires->css_theme($url);
745 // Get the theme javascript head and footer
746 if ($jsurl = $this->page->theme->javascript_url(true)) {
747 $this->page->requires->js($jsurl, true);
749 if ($jsurl = $this->page->theme->javascript_url(false)) {
750 $this->page->requires->js($jsurl);
753 // Get any HTML from the page_requirements_manager.
754 $output .= $this->page->requires->get_head_code($this->page, $this);
756 // List alternate versions.
757 foreach ($this->page->alternateversions as $type => $alt) {
758 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
759 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
762 // Add noindex tag if relevant page and setting applied.
763 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
764 $loginpages = array('login-index', 'login-signup');
765 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
766 if (!isset($CFG->additionalhtmlhead)) {
767 $CFG->additionalhtmlhead = '';
769 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
772 if (!empty($CFG->additionalhtmlhead)) {
773 $output .= "\n".$CFG->additionalhtmlhead;
776 if ($this->page->pagelayout == 'frontpage') {
777 $summary = s(strip_tags(format_text($SITE->summary, FORMAT_HTML)));
778 if (!empty($summary)) {
779 $output .= "<meta name=\"description\" content=\"$summary\" />\n";
783 return $output;
787 * The standard tags (typically skip links) that should be output just inside
788 * the start of the <body> tag. Designed to be called in theme layout.php files.
790 * @return string HTML fragment.
792 public function standard_top_of_body_html() {
793 global $CFG;
794 $output = $this->page->requires->get_top_of_body_code($this);
795 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
796 $output .= "\n".$CFG->additionalhtmltopofbody;
799 // Give subsystems an opportunity to inject extra html content. The callback
800 // must always return a string containing valid html.
801 foreach (\core_component::get_core_subsystems() as $name => $path) {
802 if ($path) {
803 $output .= component_callback($name, 'before_standard_top_of_body_html', [], '');
807 // Give plugins an opportunity to inject extra html content. The callback
808 // must always return a string containing valid html.
809 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
810 foreach ($pluginswithfunction as $plugins) {
811 foreach ($plugins as $function) {
812 $output .= $function();
816 $output .= $this->maintenance_warning();
818 return $output;
822 * Scheduled maintenance warning message.
824 * Note: This is a nasty hack to display maintenance notice, this should be moved
825 * to some general notification area once we have it.
827 * @return string
829 public function maintenance_warning() {
830 global $CFG;
832 $output = '';
833 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
834 $timeleft = $CFG->maintenance_later - time();
835 // If timeleft less than 30 sec, set the class on block to error to highlight.
836 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
837 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-3 alert');
838 $a = new stdClass();
839 $a->hour = (int)($timeleft / 3600);
840 $a->min = (int)(($timeleft / 60) % 60);
841 $a->sec = (int)($timeleft % 60);
842 if ($a->hour > 0) {
843 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
844 } else {
845 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
848 $output .= $this->box_end();
849 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
850 array(array('timeleftinsec' => $timeleft)));
851 $this->page->requires->strings_for_js(
852 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
853 'admin');
855 return $output;
859 * content that should be output in the footer area
860 * of the page. Designed to be called in theme layout.php files.
862 * @return string HTML fragment.
864 public function standard_footer_html() {
865 global $CFG;
867 $output = '';
868 if (during_initial_install()) {
869 // Debugging info can not work before install is finished,
870 // in any case we do not want any links during installation!
871 return $output;
874 // Give plugins an opportunity to add any footer elements.
875 // The callback must always return a string containing valid html footer content.
876 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
877 foreach ($pluginswithfunction as $plugins) {
878 foreach ($plugins as $function) {
879 $output .= $function();
883 if (core_userfeedback::can_give_feedback()) {
884 $output .= html_writer::div(
885 $this->render_from_template('core/userfeedback_footer_link', ['url' => core_userfeedback::make_link()->out(false)])
889 if ($this->page->devicetypeinuse == 'legacy') {
890 // The legacy theme is in use print the notification
891 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
894 // Get links to switch device types (only shown for users not on a default device)
895 $output .= $this->theme_switch_links();
897 return $output;
901 * Performance information and validation links for debugging.
903 * @return string HTML fragment.
905 public function debug_footer_html() {
906 global $CFG, $SCRIPT;
907 $output = '';
909 if (during_initial_install()) {
910 // Debugging info can not work before install is finished.
911 return $output;
914 // This function is normally called from a layout.php file
915 // but some of the content won't be known until later, so we return a placeholder
916 // for now. This will be replaced with the real content in the footer.
917 $output .= $this->unique_performance_info_token;
919 if (!empty($CFG->debugpageinfo)) {
920 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
921 $this->page->debug_summary()) . '</div>';
923 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
925 // Add link to profiling report if necessary
926 if (function_exists('profiling_is_running') && profiling_is_running()) {
927 $txt = get_string('profiledscript', 'admin');
928 $title = get_string('profiledscriptview', 'admin');
929 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
930 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
931 $output .= '<div class="profilingfooter">' . $link . '</div>';
933 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
934 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
935 $output .= '<div class="purgecaches">' .
936 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
938 // Reactive module debug panel.
939 $output .= $this->render_from_template('core/local/reactive/debugpanel', []);
941 if (!empty($CFG->debugvalidators)) {
942 $siteurl = qualified_me();
943 $nuurl = new moodle_url('https://validator.w3.org/nu/', ['doc' => $siteurl, 'showsource' => 'yes']);
944 $waveurl = new moodle_url('https://wave.webaim.org/report#/' . urlencode($siteurl));
945 $validatorlinks = [
946 html_writer::link($nuurl, get_string('validatehtml')),
947 html_writer::link($waveurl, get_string('wcagcheck'))
949 $validatorlinkslist = html_writer::alist($validatorlinks, ['class' => 'list-unstyled ml-1']);
950 $output .= html_writer::div($validatorlinkslist, 'validators');
952 return $output;
956 * Returns standard main content placeholder.
957 * Designed to be called in theme layout.php files.
959 * @return string HTML fragment.
961 public function main_content() {
962 // This is here because it is the only place we can inject the "main" role over the entire main content area
963 // without requiring all theme's to manually do it, and without creating yet another thing people need to
964 // remember in the theme.
965 // This is an unfortunate hack. DO NO EVER add anything more here.
966 // DO NOT add classes.
967 // DO NOT add an id.
968 return '<div role="main">'.$this->unique_main_content_token.'</div>';
972 * Returns information about an activity.
974 * @param cm_info $cminfo The course module information.
975 * @param cm_completion_details $completiondetails The completion details for this activity module.
976 * @param array $activitydates The dates for this activity module.
977 * @return string the activity information HTML.
978 * @throws coding_exception
980 public function activity_information(cm_info $cminfo, cm_completion_details $completiondetails, array $activitydates): string {
981 if (!$completiondetails->has_completion() && empty($activitydates)) {
982 // No need to render the activity information when there's no completion info and activity dates to show.
983 return '';
985 $activityinfo = new activity_information($cminfo, $completiondetails, $activitydates);
986 $renderer = $this->page->get_renderer('core', 'course');
987 return $renderer->render($activityinfo);
991 * Returns standard navigation between activities in a course.
993 * @return string the navigation HTML.
995 public function activity_navigation() {
996 // First we should check if we want to add navigation.
997 $context = $this->page->context;
998 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
999 || $context->contextlevel != CONTEXT_MODULE) {
1000 return '';
1003 // If the activity is in stealth mode, show no links.
1004 if ($this->page->cm->is_stealth()) {
1005 return '';
1008 $course = $this->page->cm->get_course();
1009 $courseformat = course_get_format($course);
1011 // If the theme implements course index and the current course format uses course index and the current
1012 // page layout is not 'frametop' (this layout does not support course index), show no links.
1013 if ($this->page->theme->usescourseindex && $courseformat->uses_course_index() &&
1014 $this->page->pagelayout !== 'frametop') {
1015 return '';
1018 // Get a list of all the activities in the course.
1019 $modules = get_fast_modinfo($course->id)->get_cms();
1021 // Put the modules into an array in order by the position they are shown in the course.
1022 $mods = [];
1023 $activitylist = [];
1024 foreach ($modules as $module) {
1025 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
1026 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
1027 continue;
1029 $mods[$module->id] = $module;
1031 // No need to add the current module to the list for the activity dropdown menu.
1032 if ($module->id == $this->page->cm->id) {
1033 continue;
1035 // Module name.
1036 $modname = $module->get_formatted_name();
1037 // Display the hidden text if necessary.
1038 if (!$module->visible) {
1039 $modname .= ' ' . get_string('hiddenwithbrackets');
1041 // Module URL.
1042 $linkurl = new moodle_url($module->url, array('forceview' => 1));
1043 // Add module URL (as key) and name (as value) to the activity list array.
1044 $activitylist[$linkurl->out(false)] = $modname;
1047 $nummods = count($mods);
1049 // If there is only one mod then do nothing.
1050 if ($nummods == 1) {
1051 return '';
1054 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
1055 $modids = array_keys($mods);
1057 // Get the position in the array of the course module we are viewing.
1058 $position = array_search($this->page->cm->id, $modids);
1060 $prevmod = null;
1061 $nextmod = null;
1063 // Check if we have a previous mod to show.
1064 if ($position > 0) {
1065 $prevmod = $mods[$modids[$position - 1]];
1068 // Check if we have a next mod to show.
1069 if ($position < ($nummods - 1)) {
1070 $nextmod = $mods[$modids[$position + 1]];
1073 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
1074 $renderer = $this->page->get_renderer('core', 'course');
1075 return $renderer->render($activitynav);
1079 * The standard tags (typically script tags that are not needed earlier) that
1080 * should be output after everything else. Designed to be called in theme layout.php files.
1082 * @return string HTML fragment.
1084 public function standard_end_of_body_html() {
1085 global $CFG;
1087 // This function is normally called from a layout.php file in {@link core_renderer::header()}
1088 // but some of the content won't be known until later, so we return a placeholder
1089 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
1090 $output = '';
1091 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
1092 $output .= "\n".$CFG->additionalhtmlfooter;
1094 $output .= $this->unique_end_html_token;
1095 return $output;
1099 * The standard HTML that should be output just before the <footer> tag.
1100 * Designed to be called in theme layout.php files.
1102 * @return string HTML fragment.
1104 public function standard_after_main_region_html() {
1105 global $CFG;
1106 $output = '';
1107 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlbottomofbody)) {
1108 $output .= "\n".$CFG->additionalhtmlbottomofbody;
1111 // Give subsystems an opportunity to inject extra html content. The callback
1112 // must always return a string containing valid html.
1113 foreach (\core_component::get_core_subsystems() as $name => $path) {
1114 if ($path) {
1115 $output .= component_callback($name, 'standard_after_main_region_html', [], '');
1119 // Give plugins an opportunity to inject extra html content. The callback
1120 // must always return a string containing valid html.
1121 $pluginswithfunction = get_plugins_with_function('standard_after_main_region_html', 'lib.php');
1122 foreach ($pluginswithfunction as $plugins) {
1123 foreach ($plugins as $function) {
1124 $output .= $function();
1128 return $output;
1132 * Return the standard string that says whether you are logged in (and switched
1133 * roles/logged in as another user).
1134 * @param bool $withlinks if false, then don't include any links in the HTML produced.
1135 * If not set, the default is the nologinlinks option from the theme config.php file,
1136 * and if that is not set, then links are included.
1137 * @return string HTML fragment.
1139 public function login_info($withlinks = null) {
1140 global $USER, $CFG, $DB, $SESSION;
1142 if (during_initial_install()) {
1143 return '';
1146 if (is_null($withlinks)) {
1147 $withlinks = empty($this->page->layout_options['nologinlinks']);
1150 $course = $this->page->course;
1151 if (\core\session\manager::is_loggedinas()) {
1152 $realuser = \core\session\manager::get_realuser();
1153 $fullname = fullname($realuser);
1154 if ($withlinks) {
1155 $loginastitle = get_string('loginas');
1156 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
1157 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
1158 } else {
1159 $realuserinfo = " [$fullname] ";
1161 } else {
1162 $realuserinfo = '';
1165 $loginpage = $this->is_login_page();
1166 $loginurl = get_login_url();
1168 if (empty($course->id)) {
1169 // $course->id is not defined during installation
1170 return '';
1171 } else if (isloggedin()) {
1172 $context = context_course::instance($course->id);
1174 $fullname = fullname($USER);
1175 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
1176 if ($withlinks) {
1177 $linktitle = get_string('viewprofile');
1178 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
1179 } else {
1180 $username = $fullname;
1182 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
1183 if ($withlinks) {
1184 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1185 } else {
1186 $username .= " from {$idprovider->name}";
1189 if (isguestuser()) {
1190 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1191 if (!$loginpage && $withlinks) {
1192 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1194 } else if (is_role_switched($course->id)) { // Has switched roles
1195 $rolename = '';
1196 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1197 $rolename = ': '.role_get_name($role, $context);
1199 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1200 if ($withlinks) {
1201 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1202 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1204 } else {
1205 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1206 if ($withlinks) {
1207 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1210 } else {
1211 $loggedinas = get_string('loggedinnot', 'moodle');
1212 if (!$loginpage && $withlinks) {
1213 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1217 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1219 if (isset($SESSION->justloggedin)) {
1220 unset($SESSION->justloggedin);
1221 if (!isguestuser()) {
1222 // Include this file only when required.
1223 require_once($CFG->dirroot . '/user/lib.php');
1224 if (($count = user_count_login_failures($USER)) && !empty($CFG->displayloginfailures)) {
1225 $loggedinas .= '<div class="loginfailures">';
1226 $a = new stdClass();
1227 $a->attempts = $count;
1228 $loggedinas .= get_string('failedloginattempts', '', $a);
1229 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1230 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1231 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1233 $loggedinas .= '</div>';
1238 return $loggedinas;
1242 * Check whether the current page is a login page.
1244 * @since Moodle 2.9
1245 * @return bool
1247 protected function is_login_page() {
1248 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1249 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1250 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1251 return in_array(
1252 $this->page->url->out_as_local_url(false, array()),
1253 array(
1254 '/login/index.php',
1255 '/login/forgot_password.php',
1261 * Return the 'back' link that normally appears in the footer.
1263 * @return string HTML fragment.
1265 public function home_link() {
1266 global $CFG, $SITE;
1268 if ($this->page->pagetype == 'site-index') {
1269 // Special case for site home page - please do not remove
1270 return '<div class="sitelink">' .
1271 '<a title="Moodle" class="d-inline-block aalink" href="http://moodle.org/">' .
1272 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1274 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1275 // Special case for during install/upgrade.
1276 return '<div class="sitelink">'.
1277 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1278 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1280 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1281 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1282 get_string('home') . '</a></div>';
1284 } else {
1285 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1286 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1291 * Redirects the user by any means possible given the current state
1293 * This function should not be called directly, it should always be called using
1294 * the redirect function in lib/weblib.php
1296 * The redirect function should really only be called before page output has started
1297 * however it will allow itself to be called during the state STATE_IN_BODY
1299 * @param string $encodedurl The URL to send to encoded if required
1300 * @param string $message The message to display to the user if any
1301 * @param int $delay The delay before redirecting a user, if $message has been
1302 * set this is a requirement and defaults to 3, set to 0 no delay
1303 * @param boolean $debugdisableredirect this redirect has been disabled for
1304 * debugging purposes. Display a message that explains, and don't
1305 * trigger the redirect.
1306 * @param string $messagetype The type of notification to show the message in.
1307 * See constants on \core\output\notification.
1308 * @return string The HTML to display to the user before dying, may contain
1309 * meta refresh, javascript refresh, and may have set header redirects
1311 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1312 $messagetype = \core\output\notification::NOTIFY_INFO) {
1313 global $CFG;
1314 $url = str_replace('&amp;', '&', $encodedurl);
1316 switch ($this->page->state) {
1317 case moodle_page::STATE_BEFORE_HEADER :
1318 // No output yet it is safe to delivery the full arsenal of redirect methods
1319 if (!$debugdisableredirect) {
1320 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1321 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1322 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1324 $output = $this->header();
1325 break;
1326 case moodle_page::STATE_PRINTING_HEADER :
1327 // We should hopefully never get here
1328 throw new coding_exception('You cannot redirect while printing the page header');
1329 break;
1330 case moodle_page::STATE_IN_BODY :
1331 // We really shouldn't be here but we can deal with this
1332 debugging("You should really redirect before you start page output");
1333 if (!$debugdisableredirect) {
1334 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1336 $output = $this->opencontainers->pop_all_but_last();
1337 break;
1338 case moodle_page::STATE_DONE :
1339 // Too late to be calling redirect now
1340 throw new coding_exception('You cannot redirect after the entire page has been generated');
1341 break;
1343 $output .= $this->notification($message, $messagetype);
1344 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1345 if ($debugdisableredirect) {
1346 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1348 $output .= $this->footer();
1349 return $output;
1353 * Start output by sending the HTTP headers, and printing the HTML <head>
1354 * and the start of the <body>.
1356 * To control what is printed, you should set properties on $PAGE.
1358 * @return string HTML that you must output this, preferably immediately.
1360 public function header() {
1361 global $USER, $CFG, $SESSION;
1363 // Give plugins an opportunity touch things before the http headers are sent
1364 // such as adding additional headers. The return value is ignored.
1365 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1366 foreach ($pluginswithfunction as $plugins) {
1367 foreach ($plugins as $function) {
1368 $function();
1372 if (\core\session\manager::is_loggedinas()) {
1373 $this->page->add_body_class('userloggedinas');
1376 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1377 require_once($CFG->dirroot . '/user/lib.php');
1378 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1379 if ($count = user_count_login_failures($USER, false)) {
1380 $this->page->add_body_class('loginfailures');
1384 // If the user is logged in, and we're not in initial install,
1385 // check to see if the user is role-switched and add the appropriate
1386 // CSS class to the body element.
1387 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1388 $this->page->add_body_class('userswitchedrole');
1391 // Give themes a chance to init/alter the page object.
1392 $this->page->theme->init_page($this->page);
1394 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1396 // Find the appropriate page layout file, based on $this->page->pagelayout.
1397 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1398 // Render the layout using the layout file.
1399 $rendered = $this->render_page_layout($layoutfile);
1401 // Slice the rendered output into header and footer.
1402 $cutpos = strpos($rendered, $this->unique_main_content_token);
1403 if ($cutpos === false) {
1404 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1405 $token = self::MAIN_CONTENT_TOKEN;
1406 } else {
1407 $token = $this->unique_main_content_token;
1410 if ($cutpos === false) {
1411 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.');
1413 $header = substr($rendered, 0, $cutpos);
1414 $footer = substr($rendered, $cutpos + strlen($token));
1416 if (empty($this->contenttype)) {
1417 debugging('The page layout file did not call $OUTPUT->doctype()');
1418 $header = $this->doctype() . $header;
1421 // If this theme version is below 2.4 release and this is a course view page
1422 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1423 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1424 // check if course content header/footer have not been output during render of theme layout
1425 $coursecontentheader = $this->course_content_header(true);
1426 $coursecontentfooter = $this->course_content_footer(true);
1427 if (!empty($coursecontentheader)) {
1428 // display debug message and add header and footer right above and below main content
1429 // Please note that course header and footer (to be displayed above and below the whole page)
1430 // are not displayed in this case at all.
1431 // Besides the content header and footer are not displayed on any other course page
1432 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);
1433 $header .= $coursecontentheader;
1434 $footer = $coursecontentfooter. $footer;
1438 send_headers($this->contenttype, $this->page->cacheable);
1440 $this->opencontainers->push('header/footer', $footer);
1441 $this->page->set_state(moodle_page::STATE_IN_BODY);
1443 // If an activity record has been set, activity_header will handle this.
1444 if (!$this->page->cm || !empty($this->page->layout_options['noactivityheader'])) {
1445 $header .= $this->skip_link_target('maincontent');
1447 return $header;
1451 * Renders and outputs the page layout file.
1453 * This is done by preparing the normal globals available to a script, and
1454 * then including the layout file provided by the current theme for the
1455 * requested layout.
1457 * @param string $layoutfile The name of the layout file
1458 * @return string HTML code
1460 protected function render_page_layout($layoutfile) {
1461 global $CFG, $SITE, $USER;
1462 // The next lines are a bit tricky. The point is, here we are in a method
1463 // of a renderer class, and this object may, or may not, be the same as
1464 // the global $OUTPUT object. When rendering the page layout file, we want to use
1465 // this object. However, people writing Moodle code expect the current
1466 // renderer to be called $OUTPUT, not $this, so define a variable called
1467 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1468 $OUTPUT = $this;
1469 $PAGE = $this->page;
1470 $COURSE = $this->page->course;
1472 ob_start();
1473 include($layoutfile);
1474 $rendered = ob_get_contents();
1475 ob_end_clean();
1476 return $rendered;
1480 * Outputs the page's footer
1482 * @return string HTML fragment
1484 public function footer() {
1485 global $CFG, $DB;
1487 $output = '';
1489 // Give plugins an opportunity to touch the page before JS is finalized.
1490 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1491 foreach ($pluginswithfunction as $plugins) {
1492 foreach ($plugins as $function) {
1493 $extrafooter = $function();
1494 if (is_string($extrafooter)) {
1495 $output .= $extrafooter;
1500 $output .= $this->container_end_all(true);
1502 $footer = $this->opencontainers->pop('header/footer');
1504 if (debugging() and $DB and $DB->is_transaction_started()) {
1505 // TODO: MDL-20625 print warning - transaction will be rolled back
1508 // Provide some performance info if required
1509 $performanceinfo = '';
1510 if ((defined('MDL_PERF') && MDL_PERF) || (!empty($CFG->perfdebug) && $CFG->perfdebug > 7)) {
1511 $perf = get_performance_info();
1512 if ((defined('MDL_PERFTOFOOT') && MDL_PERFTOFOOT) || debugging() || $CFG->perfdebug > 7) {
1513 $performanceinfo = $perf['html'];
1517 // We always want performance data when running a performance test, even if the user is redirected to another page.
1518 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1519 $footer = $this->unique_performance_info_token . $footer;
1521 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1523 // Only show notifications when the current page has a context id.
1524 if (!empty($this->page->context->id)) {
1525 $this->page->requires->js_call_amd('core/notification', 'init', array(
1526 $this->page->context->id,
1527 \core\notification::fetch_as_array($this)
1530 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1532 $this->page->set_state(moodle_page::STATE_DONE);
1534 return $output . $footer;
1538 * Close all but the last open container. This is useful in places like error
1539 * handling, where you want to close all the open containers (apart from <body>)
1540 * before outputting the error message.
1542 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1543 * developer debug warning if it isn't.
1544 * @return string the HTML required to close any open containers inside <body>.
1546 public function container_end_all($shouldbenone = false) {
1547 return $this->opencontainers->pop_all_but_last($shouldbenone);
1551 * Returns course-specific information to be output immediately above content on any course page
1552 * (for the current course)
1554 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1555 * @return string
1557 public function course_content_header($onlyifnotcalledbefore = false) {
1558 global $CFG;
1559 static $functioncalled = false;
1560 if ($functioncalled && $onlyifnotcalledbefore) {
1561 // we have already output the content header
1562 return '';
1565 // Output any session notification.
1566 $notifications = \core\notification::fetch();
1568 $bodynotifications = '';
1569 foreach ($notifications as $notification) {
1570 $bodynotifications .= $this->render_from_template(
1571 $notification->get_template_name(),
1572 $notification->export_for_template($this)
1576 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1578 if ($this->page->course->id == SITEID) {
1579 // return immediately and do not include /course/lib.php if not necessary
1580 return $output;
1583 require_once($CFG->dirroot.'/course/lib.php');
1584 $functioncalled = true;
1585 $courseformat = course_get_format($this->page->course);
1586 if (($obj = $courseformat->course_content_header()) !== null) {
1587 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1589 return $output;
1593 * Returns course-specific information to be output immediately below content on any course page
1594 * (for the current course)
1596 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1597 * @return string
1599 public function course_content_footer($onlyifnotcalledbefore = false) {
1600 global $CFG;
1601 if ($this->page->course->id == SITEID) {
1602 // return immediately and do not include /course/lib.php if not necessary
1603 return '';
1605 static $functioncalled = false;
1606 if ($functioncalled && $onlyifnotcalledbefore) {
1607 // we have already output the content footer
1608 return '';
1610 $functioncalled = true;
1611 require_once($CFG->dirroot.'/course/lib.php');
1612 $courseformat = course_get_format($this->page->course);
1613 if (($obj = $courseformat->course_content_footer()) !== null) {
1614 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1616 return '';
1620 * Returns course-specific information to be output on any course page in the header area
1621 * (for the current course)
1623 * @return string
1625 public function course_header() {
1626 global $CFG;
1627 if ($this->page->course->id == SITEID) {
1628 // return immediately and do not include /course/lib.php if not necessary
1629 return '';
1631 require_once($CFG->dirroot.'/course/lib.php');
1632 $courseformat = course_get_format($this->page->course);
1633 if (($obj = $courseformat->course_header()) !== null) {
1634 return $courseformat->get_renderer($this->page)->render($obj);
1636 return '';
1640 * Returns course-specific information to be output on any course page in the footer area
1641 * (for the current course)
1643 * @return string
1645 public function course_footer() {
1646 global $CFG;
1647 if ($this->page->course->id == SITEID) {
1648 // return immediately and do not include /course/lib.php if not necessary
1649 return '';
1651 require_once($CFG->dirroot.'/course/lib.php');
1652 $courseformat = course_get_format($this->page->course);
1653 if (($obj = $courseformat->course_footer()) !== null) {
1654 return $courseformat->get_renderer($this->page)->render($obj);
1656 return '';
1660 * Get the course pattern datauri to show on a course card.
1662 * The datauri is an encoded svg that can be passed as a url.
1663 * @param int $id Id to use when generating the pattern
1664 * @return string datauri
1666 public function get_generated_image_for_id($id) {
1667 $color = $this->get_generated_color_for_id($id);
1668 $pattern = new \core_geopattern();
1669 $pattern->setColor($color);
1670 $pattern->patternbyid($id);
1671 return $pattern->datauri();
1675 * Get the course color to show on a course card.
1677 * @param int $id Id to use when generating the color.
1678 * @return string hex color code.
1680 public function get_generated_color_for_id($id) {
1681 $colornumbers = range(1, 10);
1682 $basecolors = [];
1683 foreach ($colornumbers as $number) {
1684 $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1687 $color = $basecolors[$id % 10];
1688 return $color;
1692 * Returns lang menu or '', this method also checks forcing of languages in courses.
1694 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1696 * @return string The lang menu HTML or empty string
1698 public function lang_menu() {
1699 $languagemenu = new \core\output\language_menu($this->page);
1700 $data = $languagemenu->export_for_single_select($this);
1701 if ($data) {
1702 return $this->render_from_template('core/single_select', $data);
1704 return '';
1708 * Output the row of editing icons for a block, as defined by the controls array.
1710 * @param array $controls an array like {@link block_contents::$controls}.
1711 * @param string $blockid The ID given to the block.
1712 * @return string HTML fragment.
1714 public function block_controls($actions, $blockid = null) {
1715 global $CFG;
1716 if (empty($actions)) {
1717 return '';
1719 $menu = new action_menu($actions);
1720 if ($blockid !== null) {
1721 $menu->set_owner_selector('#'.$blockid);
1723 $menu->set_constraint('.block-region');
1724 $menu->attributes['class'] .= ' block-control-actions commands';
1725 return $this->render($menu);
1729 * Returns the HTML for a basic textarea field.
1731 * @param string $name Name to use for the textarea element
1732 * @param string $id The id to use fort he textarea element
1733 * @param string $value Initial content to display in the textarea
1734 * @param int $rows Number of rows to display
1735 * @param int $cols Number of columns to display
1736 * @return string the HTML to display
1738 public function print_textarea($name, $id, $value, $rows, $cols) {
1739 editors_head_setup();
1740 $editor = editors_get_preferred_editor(FORMAT_HTML);
1741 $editor->set_text($value);
1742 $editor->use_editor($id, []);
1744 $context = [
1745 'id' => $id,
1746 'name' => $name,
1747 'value' => $value,
1748 'rows' => $rows,
1749 'cols' => $cols
1752 return $this->render_from_template('core_form/editor_textarea', $context);
1756 * Renders an action menu component.
1758 * @param action_menu $menu
1759 * @return string HTML
1761 public function render_action_menu(action_menu $menu) {
1763 // We don't want the class icon there!
1764 foreach ($menu->get_secondary_actions() as $action) {
1765 if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1766 $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1770 if ($menu->is_empty()) {
1771 return '';
1773 $context = $menu->export_for_template($this);
1775 return $this->render_from_template('core/action_menu', $context);
1779 * Renders a Check API result
1781 * @param result $result
1782 * @return string HTML fragment
1784 protected function render_check_result(core\check\result $result) {
1785 return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1789 * Renders a Check API result
1791 * @param result $result
1792 * @return string HTML fragment
1794 public function check_result(core\check\result $result) {
1795 return $this->render_check_result($result);
1799 * Renders an action_menu_link item.
1801 * @param action_menu_link $action
1802 * @return string HTML fragment
1804 protected function render_action_menu_link(action_menu_link $action) {
1805 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1809 * Renders a primary action_menu_filler item.
1811 * @param action_menu_link_filler $action
1812 * @return string HTML fragment
1814 protected function render_action_menu_filler(action_menu_filler $action) {
1815 return html_writer::span('&nbsp;', 'filler');
1819 * Renders a primary action_menu_link item.
1821 * @param action_menu_link_primary $action
1822 * @return string HTML fragment
1824 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1825 return $this->render_action_menu_link($action);
1829 * Renders a secondary action_menu_link item.
1831 * @param action_menu_link_secondary $action
1832 * @return string HTML fragment
1834 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1835 return $this->render_action_menu_link($action);
1839 * Prints a nice side block with an optional header.
1841 * @param block_contents $bc HTML for the content
1842 * @param string $region the region the block is appearing in.
1843 * @return string the HTML to be output.
1845 public function block(block_contents $bc, $region) {
1846 $bc = clone($bc); // Avoid messing up the object passed in.
1847 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1848 $bc->collapsible = block_contents::NOT_HIDEABLE;
1851 $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1852 $context = new stdClass();
1853 $context->skipid = $bc->skipid;
1854 $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
1855 $context->dockable = $bc->dockable;
1856 $context->id = $id;
1857 $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1858 $context->skiptitle = strip_tags($bc->title);
1859 $context->showskiplink = !empty($context->skiptitle);
1860 $context->arialabel = $bc->arialabel;
1861 $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
1862 $context->class = $bc->attributes['class'];
1863 $context->type = $bc->attributes['data-block'];
1864 $context->title = $bc->title;
1865 $context->content = $bc->content;
1866 $context->annotation = $bc->annotation;
1867 $context->footer = $bc->footer;
1868 $context->hascontrols = !empty($bc->controls);
1869 if ($context->hascontrols) {
1870 $context->controls = $this->block_controls($bc->controls, $id);
1873 return $this->render_from_template('core/block', $context);
1877 * Render the contents of a block_list.
1879 * @param array $icons the icon for each item.
1880 * @param array $items the content of each item.
1881 * @return string HTML
1883 public function list_block_contents($icons, $items) {
1884 $row = 0;
1885 $lis = array();
1886 foreach ($items as $key => $string) {
1887 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1888 if (!empty($icons[$key])) { //test if the content has an assigned icon
1889 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1891 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1892 $item .= html_writer::end_tag('li');
1893 $lis[] = $item;
1894 $row = 1 - $row; // Flip even/odd.
1896 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1900 * Output all the blocks in a particular region.
1902 * @param string $region the name of a region on this page.
1903 * @param boolean $fakeblocksonly Output fake block only.
1904 * @return string the HTML to be output.
1906 public function blocks_for_region($region, $fakeblocksonly = false) {
1907 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1908 $lastblock = null;
1909 $zones = array();
1910 foreach ($blockcontents as $bc) {
1911 if ($bc instanceof block_contents) {
1912 $zones[] = $bc->title;
1915 $output = '';
1917 foreach ($blockcontents as $bc) {
1918 if ($bc instanceof block_contents) {
1919 if ($fakeblocksonly && !$bc->is_fake()) {
1920 // Skip rendering real blocks if we only want to show fake blocks.
1921 continue;
1923 $output .= $this->block($bc, $region);
1924 $lastblock = $bc->title;
1925 } else if ($bc instanceof block_move_target) {
1926 if (!$fakeblocksonly) {
1927 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1929 } else {
1930 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1933 return $output;
1937 * Output a place where the block that is currently being moved can be dropped.
1939 * @param block_move_target $target with the necessary details.
1940 * @param array $zones array of areas where the block can be moved to
1941 * @param string $previous the block located before the area currently being rendered.
1942 * @param string $region the name of the region
1943 * @return string the HTML to be output.
1945 public function block_move_target($target, $zones, $previous, $region) {
1946 if ($previous == null) {
1947 if (empty($zones)) {
1948 // There are no zones, probably because there are no blocks.
1949 $regions = $this->page->theme->get_all_block_regions();
1950 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1951 } else {
1952 $position = get_string('moveblockbefore', 'block', $zones[0]);
1954 } else {
1955 $position = get_string('moveblockafter', 'block', $previous);
1957 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1961 * Renders a special html link with attached action
1963 * Theme developers: DO NOT OVERRIDE! Please override function
1964 * {@link core_renderer::render_action_link()} instead.
1966 * @param string|moodle_url $url
1967 * @param string $text HTML fragment
1968 * @param component_action $action
1969 * @param array $attributes associative array of html link attributes + disabled
1970 * @param pix_icon optional pix icon to render with the link
1971 * @return string HTML fragment
1973 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1974 if (!($url instanceof moodle_url)) {
1975 $url = new moodle_url($url);
1977 $link = new action_link($url, $text, $action, $attributes, $icon);
1979 return $this->render($link);
1983 * Renders an action_link object.
1985 * The provided link is renderer and the HTML returned. At the same time the
1986 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1988 * @param action_link $link
1989 * @return string HTML fragment
1991 protected function render_action_link(action_link $link) {
1992 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1996 * Renders an action_icon.
1998 * This function uses the {@link core_renderer::action_link()} method for the
1999 * most part. What it does different is prepare the icon as HTML and use it
2000 * as the link text.
2002 * Theme developers: If you want to change how action links and/or icons are rendered,
2003 * consider overriding function {@link core_renderer::render_action_link()} and
2004 * {@link core_renderer::render_pix_icon()}.
2006 * @param string|moodle_url $url A string URL or moodel_url
2007 * @param pix_icon $pixicon
2008 * @param component_action $action
2009 * @param array $attributes associative array of html link attributes + disabled
2010 * @param bool $linktext show title next to image in link
2011 * @return string HTML fragment
2013 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
2014 if (!($url instanceof moodle_url)) {
2015 $url = new moodle_url($url);
2017 $attributes = (array)$attributes;
2019 if (empty($attributes['class'])) {
2020 // let ppl override the class via $options
2021 $attributes['class'] = 'action-icon';
2024 $icon = $this->render($pixicon);
2026 if ($linktext) {
2027 $text = $pixicon->attributes['alt'];
2028 } else {
2029 $text = '';
2032 return $this->action_link($url, $text.$icon, $action, $attributes);
2036 * Print a message along with button choices for Continue/Cancel
2038 * If a string or moodle_url is given instead of a single_button, method defaults to post.
2040 * @param string $message The question to ask the user
2041 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
2042 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
2043 * @param array $displayoptions optional extra display options
2044 * @return string HTML fragment
2046 public function confirm($message, $continue, $cancel, array $displayoptions = []) {
2048 // Check existing displayoptions.
2049 $displayoptions['confirmtitle'] = $displayoptions['confirmtitle'] ?? get_string('confirm');
2050 $displayoptions['continuestr'] = $displayoptions['continuestr'] ?? get_string('continue');
2051 $displayoptions['cancelstr'] = $displayoptions['cancelstr'] ?? get_string('cancel');
2053 if ($continue instanceof single_button) {
2054 // ok
2055 $continue->primary = true;
2056 } else if (is_string($continue)) {
2057 $continue = new single_button(new moodle_url($continue), $displayoptions['continuestr'], 'post', true);
2058 } else if ($continue instanceof moodle_url) {
2059 $continue = new single_button($continue, $displayoptions['continuestr'], 'post', true);
2060 } else {
2061 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2064 if ($cancel instanceof single_button) {
2065 // ok
2066 } else if (is_string($cancel)) {
2067 $cancel = new single_button(new moodle_url($cancel), $displayoptions['cancelstr'], 'get');
2068 } else if ($cancel instanceof moodle_url) {
2069 $cancel = new single_button($cancel, $displayoptions['cancelstr'], 'get');
2070 } else {
2071 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2074 $attributes = [
2075 'role'=>'alertdialog',
2076 'aria-labelledby'=>'modal-header',
2077 'aria-describedby'=>'modal-body',
2078 'aria-modal'=>'true'
2081 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
2082 $output .= $this->box_start('modal-content', 'modal-content');
2083 $output .= $this->box_start('modal-header px-3', 'modal-header');
2084 $output .= html_writer::tag('h4', $displayoptions['confirmtitle']);
2085 $output .= $this->box_end();
2086 $attributes = [
2087 'role'=>'alert',
2088 'data-aria-autofocus'=>'true'
2090 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
2091 $output .= html_writer::tag('p', $message);
2092 $output .= $this->box_end();
2093 $output .= $this->box_start('modal-footer', 'modal-footer');
2094 $output .= html_writer::tag('div', $this->render($cancel) . $this->render($continue), ['class' => 'buttons']);
2095 $output .= $this->box_end();
2096 $output .= $this->box_end();
2097 $output .= $this->box_end();
2098 return $output;
2102 * Returns a form with a single button.
2104 * Theme developers: DO NOT OVERRIDE! Please override function
2105 * {@link core_renderer::render_single_button()} instead.
2107 * @param string|moodle_url $url
2108 * @param string $label button text
2109 * @param string $method get or post submit method
2110 * @param array $options associative array {disabled, title, etc.}
2111 * @return string HTML fragment
2113 public function single_button($url, $label, $method='post', array $options=null) {
2114 if (!($url instanceof moodle_url)) {
2115 $url = new moodle_url($url);
2117 $button = new single_button($url, $label, $method);
2119 foreach ((array)$options as $key=>$value) {
2120 if (property_exists($button, $key)) {
2121 $button->$key = $value;
2122 } else {
2123 $button->set_attribute($key, $value);
2127 return $this->render($button);
2131 * Renders a single button widget.
2133 * This will return HTML to display a form containing a single button.
2135 * @param single_button $button
2136 * @return string HTML fragment
2138 protected function render_single_button(single_button $button) {
2139 return $this->render_from_template('core/single_button', $button->export_for_template($this));
2143 * Returns a form with a single select widget.
2145 * Theme developers: DO NOT OVERRIDE! Please override function
2146 * {@link core_renderer::render_single_select()} instead.
2148 * @param moodle_url $url form action target, includes hidden fields
2149 * @param string $name name of selection field - the changing parameter in url
2150 * @param array $options list of options
2151 * @param string $selected selected element
2152 * @param array $nothing
2153 * @param string $formid
2154 * @param array $attributes other attributes for the single select
2155 * @return string HTML fragment
2157 public function single_select($url, $name, array $options, $selected = '',
2158 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2159 if (!($url instanceof moodle_url)) {
2160 $url = new moodle_url($url);
2162 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2164 if (array_key_exists('label', $attributes)) {
2165 $select->set_label($attributes['label']);
2166 unset($attributes['label']);
2168 $select->attributes = $attributes;
2170 return $this->render($select);
2174 * Returns a dataformat selection and download form
2176 * @param string $label A text label
2177 * @param moodle_url|string $base The download page url
2178 * @param string $name The query param which will hold the type of the download
2179 * @param array $params Extra params sent to the download page
2180 * @return string HTML fragment
2182 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2184 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2185 $options = array();
2186 foreach ($formats as $format) {
2187 if ($format->is_enabled()) {
2188 $options[] = array(
2189 'value' => $format->name,
2190 'label' => get_string('dataformat', $format->component),
2194 $hiddenparams = array();
2195 foreach ($params as $key => $value) {
2196 $hiddenparams[] = array(
2197 'name' => $key,
2198 'value' => $value,
2201 $data = array(
2202 'label' => $label,
2203 'base' => $base,
2204 'name' => $name,
2205 'params' => $hiddenparams,
2206 'options' => $options,
2207 'sesskey' => sesskey(),
2208 'submit' => get_string('download'),
2211 return $this->render_from_template('core/dataformat_selector', $data);
2216 * Internal implementation of single_select rendering
2218 * @param single_select $select
2219 * @return string HTML fragment
2221 protected function render_single_select(single_select $select) {
2222 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2226 * Returns a form with a url select widget.
2228 * Theme developers: DO NOT OVERRIDE! Please override function
2229 * {@link core_renderer::render_url_select()} instead.
2231 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2232 * @param string $selected selected element
2233 * @param array $nothing
2234 * @param string $formid
2235 * @return string HTML fragment
2237 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2238 $select = new url_select($urls, $selected, $nothing, $formid);
2239 return $this->render($select);
2243 * Internal implementation of url_select rendering
2245 * @param url_select $select
2246 * @return string HTML fragment
2248 protected function render_url_select(url_select $select) {
2249 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2253 * Returns a string containing a link to the user documentation.
2254 * Also contains an icon by default. Shown to teachers and admin only.
2256 * @param string $path The page link after doc root and language, no leading slash.
2257 * @param string $text The text to be displayed for the link
2258 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2259 * @param array $attributes htm attributes
2260 * @return string
2262 public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
2263 global $CFG;
2265 $icon = $this->pix_icon('book', '', 'moodle', array('class' => 'iconhelp icon-pre', 'role' => 'presentation'));
2267 $attributes['href'] = new moodle_url(get_docs_url($path));
2268 $newwindowicon = '';
2269 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2270 $attributes['target'] = '_blank';
2271 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle',
2272 ['class' => 'fa fa-externallink fa-fw']);
2275 return html_writer::tag('a', $icon . $text . $newwindowicon, $attributes);
2279 * Return HTML for an image_icon.
2281 * Theme developers: DO NOT OVERRIDE! Please override function
2282 * {@link core_renderer::render_image_icon()} instead.
2284 * @param string $pix short pix name
2285 * @param string $alt mandatory alt attribute
2286 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2287 * @param array $attributes htm attributes
2288 * @return string HTML fragment
2290 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2291 $icon = new image_icon($pix, $alt, $component, $attributes);
2292 return $this->render($icon);
2296 * Renders a pix_icon widget and returns the HTML to display it.
2298 * @param image_icon $icon
2299 * @return string HTML fragment
2301 protected function render_image_icon(image_icon $icon) {
2302 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2303 return $system->render_pix_icon($this, $icon);
2307 * Return HTML for a pix_icon.
2309 * Theme developers: DO NOT OVERRIDE! Please override function
2310 * {@link core_renderer::render_pix_icon()} instead.
2312 * @param string $pix short pix name
2313 * @param string $alt mandatory alt attribute
2314 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2315 * @param array $attributes htm lattributes
2316 * @return string HTML fragment
2318 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2319 $icon = new pix_icon($pix, $alt, $component, $attributes);
2320 return $this->render($icon);
2324 * Renders a pix_icon widget and returns the HTML to display it.
2326 * @param pix_icon $icon
2327 * @return string HTML fragment
2329 protected function render_pix_icon(pix_icon $icon) {
2330 $system = \core\output\icon_system::instance();
2331 return $system->render_pix_icon($this, $icon);
2335 * Return HTML to display an emoticon icon.
2337 * @param pix_emoticon $emoticon
2338 * @return string HTML fragment
2340 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2341 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2342 return $system->render_pix_icon($this, $emoticon);
2346 * Produces the html that represents this rating in the UI
2348 * @param rating $rating the page object on which this rating will appear
2349 * @return string
2351 function render_rating(rating $rating) {
2352 global $CFG, $USER;
2354 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2355 return null;//ratings are turned off
2358 $ratingmanager = new rating_manager();
2359 // Initialise the JavaScript so ratings can be done by AJAX.
2360 $ratingmanager->initialise_rating_javascript($this->page);
2362 $strrate = get_string("rate", "rating");
2363 $ratinghtml = ''; //the string we'll return
2365 // permissions check - can they view the aggregate?
2366 if ($rating->user_can_view_aggregate()) {
2368 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2369 $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2370 $aggregatestr = $rating->get_aggregate_string();
2372 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2373 if ($rating->count > 0) {
2374 $countstr = "({$rating->count})";
2375 } else {
2376 $countstr = '-';
2378 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2380 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2382 $nonpopuplink = $rating->get_view_ratings_url();
2383 $popuplink = $rating->get_view_ratings_url(true);
2385 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2386 $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
2389 $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
2392 $formstart = null;
2393 // if the item doesn't belong to the current user, the user has permission to rate
2394 // and we're within the assessable period
2395 if ($rating->user_can_rate()) {
2397 $rateurl = $rating->get_rate_url();
2398 $inputs = $rateurl->params();
2400 //start the rating form
2401 $formattrs = array(
2402 'id' => "postrating{$rating->itemid}",
2403 'class' => 'postratingform',
2404 'method' => 'post',
2405 'action' => $rateurl->out_omit_querystring()
2407 $formstart = html_writer::start_tag('form', $formattrs);
2408 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2410 // add the hidden inputs
2411 foreach ($inputs as $name => $value) {
2412 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2413 $formstart .= html_writer::empty_tag('input', $attributes);
2416 if (empty($ratinghtml)) {
2417 $ratinghtml .= $strrate.': ';
2419 $ratinghtml = $formstart.$ratinghtml;
2421 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2422 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2423 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2424 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2426 //output submit button
2427 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2429 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2430 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2432 if (!$rating->settings->scale->isnumeric) {
2433 // If a global scale, try to find current course ID from the context
2434 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2435 $courseid = $coursecontext->instanceid;
2436 } else {
2437 $courseid = $rating->settings->scale->courseid;
2439 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2441 $ratinghtml .= html_writer::end_tag('span');
2442 $ratinghtml .= html_writer::end_tag('div');
2443 $ratinghtml .= html_writer::end_tag('form');
2446 return $ratinghtml;
2450 * Centered heading with attached help button (same title text)
2451 * and optional icon attached.
2453 * @param string $text A heading text
2454 * @param string $helpidentifier The keyword that defines a help page
2455 * @param string $component component name
2456 * @param string|moodle_url $icon
2457 * @param string $iconalt icon alt text
2458 * @param int $level The level of importance of the heading. Defaulting to 2
2459 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2460 * @return string HTML fragment
2462 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2463 $image = '';
2464 if ($icon) {
2465 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2468 $help = '';
2469 if ($helpidentifier) {
2470 $help = $this->help_icon($helpidentifier, $component);
2473 return $this->heading($image.$text.$help, $level, $classnames);
2477 * Returns HTML to display a help icon.
2479 * @deprecated since Moodle 2.0
2481 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2482 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2486 * Returns HTML to display a help icon.
2488 * Theme developers: DO NOT OVERRIDE! Please override function
2489 * {@link core_renderer::render_help_icon()} instead.
2491 * @param string $identifier The keyword that defines a help page
2492 * @param string $component component name
2493 * @param string|bool $linktext true means use $title as link text, string means link text value
2494 * @return string HTML fragment
2496 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2497 $icon = new help_icon($identifier, $component);
2498 $icon->diag_strings();
2499 if ($linktext === true) {
2500 $icon->linktext = get_string($icon->identifier, $icon->component);
2501 } else if (!empty($linktext)) {
2502 $icon->linktext = $linktext;
2504 return $this->render($icon);
2508 * Implementation of user image rendering.
2510 * @param help_icon $helpicon A help icon instance
2511 * @return string HTML fragment
2513 protected function render_help_icon(help_icon $helpicon) {
2514 $context = $helpicon->export_for_template($this);
2515 return $this->render_from_template('core/help_icon', $context);
2519 * Returns HTML to display a scale help icon.
2521 * @param int $courseid
2522 * @param stdClass $scale instance
2523 * @return string HTML fragment
2525 public function help_icon_scale($courseid, stdClass $scale) {
2526 global $CFG;
2528 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2530 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2532 $scaleid = abs($scale->id);
2534 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2535 $action = new popup_action('click', $link, 'ratingscale');
2537 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2541 * Creates and returns a spacer image with optional line break.
2543 * @param array $attributes Any HTML attributes to add to the spaced.
2544 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2545 * laxy do it with CSS which is a much better solution.
2546 * @return string HTML fragment
2548 public function spacer(array $attributes = null, $br = false) {
2549 $attributes = (array)$attributes;
2550 if (empty($attributes['width'])) {
2551 $attributes['width'] = 1;
2553 if (empty($attributes['height'])) {
2554 $attributes['height'] = 1;
2556 $attributes['class'] = 'spacer';
2558 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2560 if (!empty($br)) {
2561 $output .= '<br />';
2564 return $output;
2568 * Returns HTML to display the specified user's avatar.
2570 * User avatar may be obtained in two ways:
2571 * <pre>
2572 * // Option 1: (shortcut for simple cases, preferred way)
2573 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2574 * $OUTPUT->user_picture($user, array('popup'=>true));
2576 * // Option 2:
2577 * $userpic = new user_picture($user);
2578 * // Set properties of $userpic
2579 * $userpic->popup = true;
2580 * $OUTPUT->render($userpic);
2581 * </pre>
2583 * Theme developers: DO NOT OVERRIDE! Please override function
2584 * {@link core_renderer::render_user_picture()} instead.
2586 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2587 * If any of these are missing, the database is queried. Avoid this
2588 * if at all possible, particularly for reports. It is very bad for performance.
2589 * @param array $options associative array with user picture options, used only if not a user_picture object,
2590 * options are:
2591 * - courseid=$this->page->course->id (course id of user profile in link)
2592 * - size=35 (size of image)
2593 * - link=true (make image clickable - the link leads to user profile)
2594 * - popup=false (open in popup)
2595 * - alttext=true (add image alt attribute)
2596 * - class = image class attribute (default 'userpicture')
2597 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2598 * - includefullname=false (whether to include the user's full name together with the user picture)
2599 * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2600 * @return string HTML fragment
2602 public function user_picture(stdClass $user, array $options = null) {
2603 $userpicture = new user_picture($user);
2604 foreach ((array)$options as $key=>$value) {
2605 if (property_exists($userpicture, $key)) {
2606 $userpicture->$key = $value;
2609 return $this->render($userpicture);
2613 * Internal implementation of user image rendering.
2615 * @param user_picture $userpicture
2616 * @return string
2618 protected function render_user_picture(user_picture $userpicture) {
2619 global $CFG;
2621 $user = $userpicture->user;
2622 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
2624 $alt = '';
2625 if ($userpicture->alttext) {
2626 if (!empty($user->imagealt)) {
2627 $alt = $user->imagealt;
2631 if (empty($userpicture->size)) {
2632 $size = 35;
2633 } else if ($userpicture->size === true or $userpicture->size == 1) {
2634 $size = 100;
2635 } else {
2636 $size = $userpicture->size;
2639 $class = $userpicture->class;
2641 if ($user->picture == 0) {
2642 $class .= ' defaultuserpic';
2645 $src = $userpicture->get_url($this->page, $this);
2647 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2648 if (!$userpicture->visibletoscreenreaders) {
2649 $alt = '';
2651 $attributes['alt'] = $alt;
2653 if (!empty($alt)) {
2654 $attributes['title'] = $alt;
2657 // Get the image html output first, auto generated based on initials if one isn't already set.
2658 if ($user->picture == 0 && empty($CFG->enablegravatar) && !defined('BEHAT_SITE_RUNNING')) {
2659 $output = html_writer::tag('span', mb_substr($user->firstname, 0, 1) . mb_substr($user->lastname, 0, 1),
2660 ['class' => 'userinitials size-' . $size]);
2661 } else {
2662 $output = html_writer::empty_tag('img', $attributes);
2665 // Show fullname together with the picture when desired.
2666 if ($userpicture->includefullname) {
2667 $output .= fullname($userpicture->user, $canviewfullnames);
2670 if (empty($userpicture->courseid)) {
2671 $courseid = $this->page->course->id;
2672 } else {
2673 $courseid = $userpicture->courseid;
2675 if ($courseid == SITEID) {
2676 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2677 } else {
2678 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2681 // Then wrap it in link if needed. Also we don't wrap it in link if the link redirects to itself.
2682 if (!$userpicture->link ||
2683 ($this->page->has_set_url() && $this->page->url == $url)) { // Protect against unset page->url.
2684 return $output;
2687 $attributes = array('href' => $url, 'class' => 'd-inline-block aabtn');
2688 if (!$userpicture->visibletoscreenreaders) {
2689 $attributes['tabindex'] = '-1';
2690 $attributes['aria-hidden'] = 'true';
2693 if ($userpicture->popup) {
2694 $id = html_writer::random_id('userpicture');
2695 $attributes['id'] = $id;
2696 $this->add_action_handler(new popup_action('click', $url), $id);
2699 return html_writer::tag('a', $output, $attributes);
2703 * Internal implementation of file tree viewer items rendering.
2705 * @param array $dir
2706 * @return string
2708 public function htmllize_file_tree($dir) {
2709 if (empty($dir['subdirs']) and empty($dir['files'])) {
2710 return '';
2712 $result = '<ul>';
2713 foreach ($dir['subdirs'] as $subdir) {
2714 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2716 foreach ($dir['files'] as $file) {
2717 $filename = $file->get_filename();
2718 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2720 $result .= '</ul>';
2722 return $result;
2726 * Returns HTML to display the file picker
2728 * <pre>
2729 * $OUTPUT->file_picker($options);
2730 * </pre>
2732 * Theme developers: DO NOT OVERRIDE! Please override function
2733 * {@link core_renderer::render_file_picker()} instead.
2735 * @param array $options associative array with file manager options
2736 * options are:
2737 * maxbytes=>-1,
2738 * itemid=>0,
2739 * client_id=>uniqid(),
2740 * acepted_types=>'*',
2741 * return_types=>FILE_INTERNAL,
2742 * context=>current page context
2743 * @return string HTML fragment
2745 public function file_picker($options) {
2746 $fp = new file_picker($options);
2747 return $this->render($fp);
2751 * Internal implementation of file picker rendering.
2753 * @param file_picker $fp
2754 * @return string
2756 public function render_file_picker(file_picker $fp) {
2757 $options = $fp->options;
2758 $client_id = $options->client_id;
2759 $strsaved = get_string('filesaved', 'repository');
2760 $straddfile = get_string('openpicker', 'repository');
2761 $strloading = get_string('loading', 'repository');
2762 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2763 $strdroptoupload = get_string('droptoupload', 'moodle');
2764 $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
2766 $currentfile = $options->currentfile;
2767 if (empty($currentfile)) {
2768 $currentfile = '';
2769 } else {
2770 $currentfile .= ' - ';
2772 if ($options->maxbytes) {
2773 $size = $options->maxbytes;
2774 } else {
2775 $size = get_max_upload_file_size();
2777 if ($size == -1) {
2778 $maxsize = '';
2779 } else {
2780 $maxsize = get_string('maxfilesize', 'moodle', display_size($size, 0));
2782 if ($options->buttonname) {
2783 $buttonname = ' name="' . $options->buttonname . '"';
2784 } else {
2785 $buttonname = '';
2787 $html = <<<EOD
2788 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2789 $iconprogress
2790 </div>
2791 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2792 <div>
2793 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2794 <span> $maxsize </span>
2795 </div>
2796 EOD;
2797 if ($options->env != 'url') {
2798 $html .= <<<EOD
2799 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2800 <div class="filepicker-filename">
2801 <div class="filepicker-container">$currentfile
2802 <div class="dndupload-message">$strdndenabled <br/>
2803 <div class="dndupload-arrow d-flex"><i class="fa fa-arrow-circle-o-down fa-3x m-auto"></i></div>
2804 </div>
2805 </div>
2806 <div class="dndupload-progressbars"></div>
2807 </div>
2808 <div>
2809 <div class="dndupload-target">{$strdroptoupload}<br/>
2810 <div class="dndupload-arrow d-flex"><i class="fa fa-arrow-circle-o-down fa-3x m-auto"></i></div>
2811 </div>
2812 </div>
2813 </div>
2814 EOD;
2816 $html .= '</div>';
2817 return $html;
2821 * @deprecated since Moodle 3.2
2823 public function update_module_button() {
2824 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2825 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2826 'Themes can choose to display the link in the buttons row consistently for all module types.');
2830 * Returns HTML to display a "Turn editing on/off" button in a form.
2832 * @param moodle_url $url The URL + params to send through when clicking the button
2833 * @param string $method
2834 * @return string HTML the button
2836 public function edit_button(moodle_url $url, string $method = 'post') {
2838 if ($this->page->theme->haseditswitch == true) {
2839 return;
2841 $url->param('sesskey', sesskey());
2842 if ($this->page->user_is_editing()) {
2843 $url->param('edit', 'off');
2844 $editstring = get_string('turneditingoff');
2845 } else {
2846 $url->param('edit', 'on');
2847 $editstring = get_string('turneditingon');
2850 return $this->single_button($url, $editstring, $method);
2854 * Create a navbar switch for toggling editing mode.
2856 * @return string Html containing the edit switch
2858 public function edit_switch() {
2859 if ($this->page->user_allowed_editing()) {
2861 $temp = (object) [
2862 'legacyseturl' => (new moodle_url('/editmode.php'))->out(false),
2863 'pagecontextid' => $this->page->context->id,
2864 'pageurl' => $this->page->url,
2865 'sesskey' => sesskey(),
2867 if ($this->page->user_is_editing()) {
2868 $temp->checked = true;
2870 return $this->render_from_template('core/editswitch', $temp);
2875 * Returns HTML to display a simple button to close a window
2877 * @param string $text The lang string for the button's label (already output from get_string())
2878 * @return string html fragment
2880 public function close_window_button($text='') {
2881 if (empty($text)) {
2882 $text = get_string('closewindow');
2884 $button = new single_button(new moodle_url('#'), $text, 'get');
2885 $button->add_action(new component_action('click', 'close_window'));
2887 return $this->container($this->render($button), 'closewindow');
2891 * Output an error message. By default wraps the error message in <span class="error">.
2892 * If the error message is blank, nothing is output.
2894 * @param string $message the error message.
2895 * @return string the HTML to output.
2897 public function error_text($message) {
2898 if (empty($message)) {
2899 return '';
2901 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2902 return html_writer::tag('span', $message, array('class' => 'error'));
2906 * Do not call this function directly.
2908 * To terminate the current script with a fatal error, throw an exception.
2909 * Doing this will then call this function to display the error, before terminating the execution.
2911 * @param string $message The message to output
2912 * @param string $moreinfourl URL where more info can be found about the error
2913 * @param string $link Link for the Continue button
2914 * @param array $backtrace The execution backtrace
2915 * @param string $debuginfo Debugging information
2916 * @return string the HTML to output.
2918 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2919 global $CFG;
2921 $output = '';
2922 $obbuffer = '';
2924 if ($this->has_started()) {
2925 // we can not always recover properly here, we have problems with output buffering,
2926 // html tables, etc.
2927 $output .= $this->opencontainers->pop_all_but_last();
2929 } else {
2930 // It is really bad if library code throws exception when output buffering is on,
2931 // because the buffered text would be printed before our start of page.
2932 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2933 error_reporting(0); // disable notices from gzip compression, etc.
2934 while (ob_get_level() > 0) {
2935 $buff = ob_get_clean();
2936 if ($buff === false) {
2937 break;
2939 $obbuffer .= $buff;
2941 error_reporting($CFG->debug);
2943 // Output not yet started.
2944 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2945 if (empty($_SERVER['HTTP_RANGE'])) {
2946 @header($protocol . ' 404 Not Found');
2947 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2948 // Coax iOS 10 into sending the session cookie.
2949 @header($protocol . ' 403 Forbidden');
2950 } else {
2951 // Must stop byteserving attempts somehow,
2952 // this is weird but Chrome PDF viewer can be stopped only with 407!
2953 @header($protocol . ' 407 Proxy Authentication Required');
2956 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2957 $this->page->set_url('/'); // no url
2958 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2959 $this->page->set_title(get_string('error'));
2960 $this->page->set_heading($this->page->course->fullname);
2961 // No need to display the activity header when encountering an error.
2962 $this->page->activityheader->disable();
2963 $output .= $this->header();
2966 $message = '<p class="errormessage">' . s($message) . '</p>'.
2967 '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
2968 get_string('moreinformation') . '</a></p>';
2969 if (empty($CFG->rolesactive)) {
2970 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2971 //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.
2973 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2975 if ($CFG->debugdeveloper) {
2976 $labelsep = get_string('labelsep', 'langconfig');
2977 if (!empty($debuginfo)) {
2978 $debuginfo = s($debuginfo); // removes all nasty JS
2979 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2980 $label = get_string('debuginfo', 'debug') . $labelsep;
2981 $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
2983 if (!empty($backtrace)) {
2984 $label = get_string('stacktrace', 'debug') . $labelsep;
2985 $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
2987 if ($obbuffer !== '' ) {
2988 $label = get_string('outputbuffer', 'debug') . $labelsep;
2989 $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
2993 if (empty($CFG->rolesactive)) {
2994 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2995 } else if (!empty($link)) {
2996 $output .= $this->continue_button($link);
2999 $output .= $this->footer();
3001 // Padding to encourage IE to display our error page, rather than its own.
3002 $output .= str_repeat(' ', 512);
3004 return $output;
3008 * Output a notification (that is, a status message about something that has just happened).
3010 * Note: \core\notification::add() may be more suitable for your usage.
3012 * @param string $message The message to print out.
3013 * @param ?string $type The type of notification. See constants on \core\output\notification.
3014 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
3015 * @return string the HTML to output.
3017 public function notification($message, $type = null, $closebutton = true) {
3018 $typemappings = [
3019 // Valid types.
3020 'success' => \core\output\notification::NOTIFY_SUCCESS,
3021 'info' => \core\output\notification::NOTIFY_INFO,
3022 'warning' => \core\output\notification::NOTIFY_WARNING,
3023 'error' => \core\output\notification::NOTIFY_ERROR,
3025 // Legacy types mapped to current types.
3026 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
3027 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
3028 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
3029 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
3030 'notifymessage' => \core\output\notification::NOTIFY_INFO,
3031 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
3032 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
3035 $extraclasses = [];
3037 if ($type) {
3038 if (strpos($type, ' ') === false) {
3039 // No spaces in the list of classes, therefore no need to loop over and determine the class.
3040 if (isset($typemappings[$type])) {
3041 $type = $typemappings[$type];
3042 } else {
3043 // The value provided did not match a known type. It must be an extra class.
3044 $extraclasses = [$type];
3046 } else {
3047 // Identify what type of notification this is.
3048 $classarray = explode(' ', self::prepare_classes($type));
3050 // Separate out the type of notification from the extra classes.
3051 foreach ($classarray as $class) {
3052 if (isset($typemappings[$class])) {
3053 $type = $typemappings[$class];
3054 } else {
3055 $extraclasses[] = $class;
3061 $notification = new \core\output\notification($message, $type, $closebutton);
3062 if (count($extraclasses)) {
3063 $notification->set_extra_classes($extraclasses);
3066 // Return the rendered template.
3067 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3071 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3073 public function notify_problem() {
3074 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
3075 'please use \core\notification::add(), or \core\output\notification as required.');
3079 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3081 public function notify_success() {
3082 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
3083 'please use \core\notification::add(), or \core\output\notification as required.');
3087 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3089 public function notify_message() {
3090 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
3091 'please use \core\notification::add(), or \core\output\notification as required.');
3095 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3097 public function notify_redirect() {
3098 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
3099 'please use \core\notification::add(), or \core\output\notification as required.');
3103 * Render a notification (that is, a status message about something that has
3104 * just happened).
3106 * @param \core\output\notification $notification the notification to print out
3107 * @return string the HTML to output.
3109 protected function render_notification(\core\output\notification $notification) {
3110 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3114 * Returns HTML to display a continue button that goes to a particular URL.
3116 * @param string|moodle_url $url The url the button goes to.
3117 * @return string the HTML to output.
3119 public function continue_button($url) {
3120 if (!($url instanceof moodle_url)) {
3121 $url = new moodle_url($url);
3123 $button = new single_button($url, get_string('continue'), 'get', true);
3124 $button->class = 'continuebutton';
3126 return $this->render($button);
3130 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
3132 * Theme developers: DO NOT OVERRIDE! Please override function
3133 * {@link core_renderer::render_paging_bar()} instead.
3135 * @param int $totalcount The total number of entries available to be paged through
3136 * @param int $page The page you are currently viewing
3137 * @param int $perpage The number of entries that should be shown per page
3138 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3139 * @param string $pagevar name of page parameter that holds the page number
3140 * @return string the HTML to output.
3142 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3143 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3144 return $this->render($pb);
3148 * Returns HTML to display the paging bar.
3150 * @param paging_bar $pagingbar
3151 * @return string the HTML to output.
3153 protected function render_paging_bar(paging_bar $pagingbar) {
3154 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3155 $pagingbar->maxdisplay = 10;
3156 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3160 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3162 * @param string $current the currently selected letter.
3163 * @param string $class class name to add to this initial bar.
3164 * @param string $title the name to put in front of this initial bar.
3165 * @param string $urlvar URL parameter name for this initial.
3166 * @param string $url URL object.
3167 * @param array $alpha of letters in the alphabet.
3168 * @return string the HTML to output.
3170 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3171 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3172 return $this->render($ib);
3176 * Internal implementation of initials bar rendering.
3178 * @param initials_bar $initialsbar
3179 * @return string
3181 protected function render_initials_bar(initials_bar $initialsbar) {
3182 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3186 * Output the place a skip link goes to.
3188 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3189 * @return string the HTML to output.
3191 public function skip_link_target($id = null) {
3192 return html_writer::span('', '', array('id' => $id));
3196 * Outputs a heading
3198 * @param string $text The text of the heading
3199 * @param int $level The level of importance of the heading. Defaulting to 2
3200 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3201 * @param string $id An optional ID
3202 * @return string the HTML to output.
3204 public function heading($text, $level = 2, $classes = null, $id = null) {
3205 $level = (integer) $level;
3206 if ($level < 1 or $level > 6) {
3207 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3209 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3213 * Outputs a box.
3215 * @param string $contents The contents of the box
3216 * @param string $classes A space-separated list of CSS classes
3217 * @param string $id An optional ID
3218 * @param array $attributes An array of other attributes to give the box.
3219 * @return string the HTML to output.
3221 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3222 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3226 * Outputs the opening section of a box.
3228 * @param string $classes A space-separated list of CSS classes
3229 * @param string $id An optional ID
3230 * @param array $attributes An array of other attributes to give the box.
3231 * @return string the HTML to output.
3233 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3234 $this->opencontainers->push('box', html_writer::end_tag('div'));
3235 $attributes['id'] = $id;
3236 $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes);
3237 return html_writer::start_tag('div', $attributes);
3241 * Outputs the closing section of a box.
3243 * @return string the HTML to output.
3245 public function box_end() {
3246 return $this->opencontainers->pop('box');
3250 * Outputs a container.
3252 * @param string $contents The contents of the box
3253 * @param string $classes A space-separated list of CSS classes
3254 * @param string $id An optional ID
3255 * @return string the HTML to output.
3257 public function container($contents, $classes = null, $id = null) {
3258 return $this->container_start($classes, $id) . $contents . $this->container_end();
3262 * Outputs the opening section of a container.
3264 * @param string $classes A space-separated list of CSS classes
3265 * @param string $id An optional ID
3266 * @return string the HTML to output.
3268 public function container_start($classes = null, $id = null) {
3269 $this->opencontainers->push('container', html_writer::end_tag('div'));
3270 return html_writer::start_tag('div', array('id' => $id,
3271 'class' => renderer_base::prepare_classes($classes)));
3275 * Outputs the closing section of a container.
3277 * @return string the HTML to output.
3279 public function container_end() {
3280 return $this->opencontainers->pop('container');
3284 * Make nested HTML lists out of the items
3286 * The resulting list will look something like this:
3288 * <pre>
3289 * <<ul>>
3290 * <<li>><div class='tree_item parent'>(item contents)</div>
3291 * <<ul>
3292 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3293 * <</ul>>
3294 * <</li>>
3295 * <</ul>>
3296 * </pre>
3298 * @param array $items
3299 * @param array $attrs html attributes passed to the top ofs the list
3300 * @return string HTML
3302 public function tree_block_contents($items, $attrs = array()) {
3303 // exit if empty, we don't want an empty ul element
3304 if (empty($items)) {
3305 return '';
3307 // array of nested li elements
3308 $lis = array();
3309 foreach ($items as $item) {
3310 // this applies to the li item which contains all child lists too
3311 $content = $item->content($this);
3312 $liclasses = array($item->get_css_type());
3313 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3314 $liclasses[] = 'collapsed';
3316 if ($item->isactive === true) {
3317 $liclasses[] = 'current_branch';
3319 $liattr = array('class'=>join(' ',$liclasses));
3320 // class attribute on the div item which only contains the item content
3321 $divclasses = array('tree_item');
3322 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3323 $divclasses[] = 'branch';
3324 } else {
3325 $divclasses[] = 'leaf';
3327 if (!empty($item->classes) && count($item->classes)>0) {
3328 $divclasses[] = join(' ', $item->classes);
3330 $divattr = array('class'=>join(' ', $divclasses));
3331 if (!empty($item->id)) {
3332 $divattr['id'] = $item->id;
3334 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3335 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3336 $content = html_writer::empty_tag('hr') . $content;
3338 $content = html_writer::tag('li', $content, $liattr);
3339 $lis[] = $content;
3341 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3345 * Returns a search box.
3347 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3348 * @return string HTML with the search form hidden by default.
3350 public function search_box($id = false) {
3351 global $CFG;
3353 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3354 // result in an extra included file for each site, even the ones where global search
3355 // is disabled.
3356 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3357 return '';
3360 $data = [
3361 'action' => new moodle_url('/search/index.php'),
3362 'hiddenfields' => (object) ['name' => 'context', 'value' => $this->page->context->id],
3363 'inputname' => 'q',
3364 'searchstring' => get_string('search'),
3366 return $this->render_from_template('core/search_input_navbar', $data);
3370 * Allow plugins to provide some content to be rendered in the navbar.
3371 * The plugin must define a PLUGIN_render_navbar_output function that returns
3372 * the HTML they wish to add to the navbar.
3374 * @return string HTML for the navbar
3376 public function navbar_plugin_output() {
3377 $output = '';
3379 // Give subsystems an opportunity to inject extra html content. The callback
3380 // must always return a string containing valid html.
3381 foreach (\core_component::get_core_subsystems() as $name => $path) {
3382 if ($path) {
3383 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3387 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3388 foreach ($pluginsfunction as $plugintype => $plugins) {
3389 foreach ($plugins as $pluginfunction) {
3390 $output .= $pluginfunction($this);
3395 return $output;
3399 * Construct a user menu, returning HTML that can be echoed out by a
3400 * layout file.
3402 * @param stdClass $user A user object, usually $USER.
3403 * @param bool $withlinks true if a dropdown should be built.
3404 * @return string HTML fragment.
3406 public function user_menu($user = null, $withlinks = null) {
3407 global $USER, $CFG;
3408 require_once($CFG->dirroot . '/user/lib.php');
3410 if (is_null($user)) {
3411 $user = $USER;
3414 // Note: this behaviour is intended to match that of core_renderer::login_info,
3415 // but should not be considered to be good practice; layout options are
3416 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3417 if (is_null($withlinks)) {
3418 $withlinks = empty($this->page->layout_options['nologinlinks']);
3421 // Add a class for when $withlinks is false.
3422 $usermenuclasses = 'usermenu';
3423 if (!$withlinks) {
3424 $usermenuclasses .= ' withoutlinks';
3427 $returnstr = "";
3429 // If during initial install, return the empty return string.
3430 if (during_initial_install()) {
3431 return $returnstr;
3434 $loginpage = $this->is_login_page();
3435 $loginurl = get_login_url();
3437 // Get some navigation opts.
3438 $opts = user_get_user_navigation_info($user, $this->page);
3440 if (!empty($opts->unauthenticateduser)) {
3441 $returnstr = get_string($opts->unauthenticateduser['content'], 'moodle');
3442 // If not logged in, show the typical not-logged-in string.
3443 if (!$loginpage && (!$opts->unauthenticateduser['guest'] || $withlinks)) {
3444 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3447 return html_writer::div(
3448 html_writer::span(
3449 $returnstr,
3450 'login nav-link'
3452 $usermenuclasses
3456 $avatarclasses = "avatars";
3457 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3458 $usertextcontents = $opts->metadata['userfullname'];
3460 // Other user.
3461 if (!empty($opts->metadata['asotheruser'])) {
3462 $avatarcontents .= html_writer::span(
3463 $opts->metadata['realuseravatar'],
3464 'avatar realuser'
3466 $usertextcontents = $opts->metadata['realuserfullname'];
3467 $usertextcontents .= html_writer::tag(
3468 'span',
3469 get_string(
3470 'loggedinas',
3471 'moodle',
3472 html_writer::span(
3473 $opts->metadata['userfullname'],
3474 'value'
3477 array('class' => 'meta viewingas')
3481 // Role.
3482 if (!empty($opts->metadata['asotherrole'])) {
3483 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3484 $usertextcontents .= html_writer::span(
3485 $opts->metadata['rolename'],
3486 'meta role role-' . $role
3490 // User login failures.
3491 if (!empty($opts->metadata['userloginfail'])) {
3492 $usertextcontents .= html_writer::span(
3493 $opts->metadata['userloginfail'],
3494 'meta loginfailures'
3498 // MNet.
3499 if (!empty($opts->metadata['asmnetuser'])) {
3500 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3501 $usertextcontents .= html_writer::span(
3502 $opts->metadata['mnetidprovidername'],
3503 'meta mnet mnet-' . $mnet
3507 $returnstr .= html_writer::span(
3508 html_writer::span($usertextcontents, 'usertext mr-1') .
3509 html_writer::span($avatarcontents, $avatarclasses),
3510 'userbutton'
3513 // Create a divider (well, a filler).
3514 $divider = new action_menu_filler();
3515 $divider->primary = false;
3517 $am = new action_menu();
3518 $am->set_menu_trigger(
3519 $returnstr,
3520 'nav-link'
3522 $am->set_action_label(get_string('usermenu'));
3523 $am->set_nowrap_on_items();
3524 if ($withlinks) {
3525 $navitemcount = count($opts->navitems);
3526 $idx = 0;
3527 foreach ($opts->navitems as $key => $value) {
3529 switch ($value->itemtype) {
3530 case 'divider':
3531 // If the nav item is a divider, add one and skip link processing.
3532 $am->add($divider);
3533 break;
3535 case 'invalid':
3536 // Silently skip invalid entries (should we post a notification?).
3537 break;
3539 case 'link':
3540 // Process this as a link item.
3541 $pix = null;
3542 if (isset($value->pix) && !empty($value->pix)) {
3543 $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
3544 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3545 $value->title = html_writer::img(
3546 $value->imgsrc,
3547 $value->title,
3548 array('class' => 'iconsmall')
3549 ) . $value->title;
3552 $al = new action_menu_link_secondary(
3553 $value->url,
3554 $pix,
3555 $value->title,
3556 array('class' => 'icon')
3558 if (!empty($value->titleidentifier)) {
3559 $al->attributes['data-title'] = $value->titleidentifier;
3561 $am->add($al);
3562 break;
3565 $idx++;
3567 // Add dividers after the first item and before the last item.
3568 if ($idx == 1 || $idx == $navitemcount - 1) {
3569 $am->add($divider);
3574 return html_writer::div(
3575 $this->render($am),
3576 $usermenuclasses
3581 * Secure layout login info.
3583 * @return string
3585 public function secure_layout_login_info() {
3586 if (get_config('core', 'logininfoinsecurelayout')) {
3587 return $this->login_info(false);
3588 } else {
3589 return '';
3594 * Returns the language menu in the secure layout.
3596 * No custom menu items are passed though, such that it will render only the language selection.
3598 * @return string
3600 public function secure_layout_language_menu() {
3601 if (get_config('core', 'langmenuinsecurelayout')) {
3602 $custommenu = new custom_menu('', current_language());
3603 return $this->render_custom_menu($custommenu);
3604 } else {
3605 return '';
3610 * This renders the navbar.
3611 * Uses bootstrap compatible html.
3613 public function navbar() {
3614 return $this->render_from_template('core/navbar', $this->page->navbar);
3618 * Renders a breadcrumb navigation node object.
3620 * @param breadcrumb_navigation_node $item The navigation node to render.
3621 * @return string HTML fragment
3623 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3625 if ($item->action instanceof moodle_url) {
3626 $content = $item->get_content();
3627 $title = $item->get_title();
3628 $attributes = array();
3629 $attributes['itemprop'] = 'url';
3630 if ($title !== '') {
3631 $attributes['title'] = $title;
3633 if ($item->hidden) {
3634 $attributes['class'] = 'dimmed_text';
3636 if ($item->is_last()) {
3637 $attributes['aria-current'] = 'page';
3639 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3640 $content = html_writer::link($item->action, $content, $attributes);
3642 $attributes = array();
3643 $attributes['itemscope'] = '';
3644 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3645 $content = html_writer::tag('span', $content, $attributes);
3647 } else {
3648 $content = $this->render_navigation_node($item);
3650 return $content;
3654 * Renders a navigation node object.
3656 * @param navigation_node $item The navigation node to render.
3657 * @return string HTML fragment
3659 protected function render_navigation_node(navigation_node $item) {
3660 $content = $item->get_content();
3661 $title = $item->get_title();
3662 if ($item->icon instanceof renderable && !$item->hideicon) {
3663 $icon = $this->render($item->icon);
3664 $content = $icon.$content; // use CSS for spacing of icons
3666 if ($item->helpbutton !== null) {
3667 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3669 if ($content === '') {
3670 return '';
3672 if ($item->action instanceof action_link) {
3673 $link = $item->action;
3674 if ($item->hidden) {
3675 $link->add_class('dimmed');
3677 if (!empty($content)) {
3678 // Providing there is content we will use that for the link content.
3679 $link->text = $content;
3681 $content = $this->render($link);
3682 } else if ($item->action instanceof moodle_url) {
3683 $attributes = array();
3684 if ($title !== '') {
3685 $attributes['title'] = $title;
3687 if ($item->hidden) {
3688 $attributes['class'] = 'dimmed_text';
3690 $content = html_writer::link($item->action, $content, $attributes);
3692 } else if (is_string($item->action) || empty($item->action)) {
3693 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3694 if ($title !== '') {
3695 $attributes['title'] = $title;
3697 if ($item->hidden) {
3698 $attributes['class'] = 'dimmed_text';
3700 $content = html_writer::tag('span', $content, $attributes);
3702 return $content;
3706 * Accessibility: Right arrow-like character is
3707 * used in the breadcrumb trail, course navigation menu
3708 * (previous/next activity), calendar, and search forum block.
3709 * If the theme does not set characters, appropriate defaults
3710 * are set automatically. Please DO NOT
3711 * use &lt; &gt; &raquo; - these are confusing for blind users.
3713 * @return string
3715 public function rarrow() {
3716 return $this->page->theme->rarrow;
3720 * Accessibility: Left arrow-like character is
3721 * used in the breadcrumb trail, course navigation menu
3722 * (previous/next activity), calendar, and search forum block.
3723 * If the theme does not set characters, appropriate defaults
3724 * are set automatically. Please DO NOT
3725 * use &lt; &gt; &raquo; - these are confusing for blind users.
3727 * @return string
3729 public function larrow() {
3730 return $this->page->theme->larrow;
3734 * Accessibility: Up arrow-like character is used in
3735 * the book heirarchical navigation.
3736 * If the theme does not set characters, appropriate defaults
3737 * are set automatically. Please DO NOT
3738 * use ^ - this is confusing for blind users.
3740 * @return string
3742 public function uarrow() {
3743 return $this->page->theme->uarrow;
3747 * Accessibility: Down arrow-like character.
3748 * If the theme does not set characters, appropriate defaults
3749 * are set automatically.
3751 * @return string
3753 public function darrow() {
3754 return $this->page->theme->darrow;
3758 * Returns the custom menu if one has been set
3760 * A custom menu can be configured by browsing to
3761 * Settings: Administration > Appearance > Themes > Theme settings
3762 * and then configuring the custommenu config setting as described.
3764 * Theme developers: DO NOT OVERRIDE! Please override function
3765 * {@link core_renderer::render_custom_menu()} instead.
3767 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3768 * @return string
3770 public function custom_menu($custommenuitems = '') {
3771 global $CFG;
3773 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3774 $custommenuitems = $CFG->custommenuitems;
3776 $custommenu = new custom_menu($custommenuitems, current_language());
3777 return $this->render_custom_menu($custommenu);
3781 * We want to show the custom menus as a list of links in the footer on small screens.
3782 * Just return the menu object exported so we can render it differently.
3784 public function custom_menu_flat() {
3785 global $CFG;
3786 $custommenuitems = '';
3788 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3789 $custommenuitems = $CFG->custommenuitems;
3791 $custommenu = new custom_menu($custommenuitems, current_language());
3792 $langs = get_string_manager()->get_list_of_translations();
3793 $haslangmenu = $this->lang_menu() != '';
3795 if ($haslangmenu) {
3796 $strlang = get_string('language');
3797 $currentlang = current_language();
3798 if (isset($langs[$currentlang])) {
3799 $currentlang = $langs[$currentlang];
3800 } else {
3801 $currentlang = $strlang;
3803 $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3804 foreach ($langs as $langtype => $langname) {
3805 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3809 return $custommenu->export_for_template($this);
3813 * Renders a custom menu object (located in outputcomponents.php)
3815 * The custom menu this method produces makes use of the YUI3 menunav widget
3816 * and requires very specific html elements and classes.
3818 * @staticvar int $menucount
3819 * @param custom_menu $menu
3820 * @return string
3822 protected function render_custom_menu(custom_menu $menu) {
3823 global $CFG;
3825 $langs = get_string_manager()->get_list_of_translations();
3826 $haslangmenu = $this->lang_menu() != '';
3828 if (!$menu->has_children() && !$haslangmenu) {
3829 return '';
3832 if ($haslangmenu) {
3833 $strlang = get_string('language');
3834 $currentlang = current_language();
3835 if (isset($langs[$currentlang])) {
3836 $currentlangstr = $langs[$currentlang];
3837 } else {
3838 $currentlangstr = $strlang;
3840 $this->language = $menu->add($currentlangstr, new moodle_url('#'), $strlang, 10000);
3841 foreach ($langs as $langtype => $langname) {
3842 $attributes = [];
3843 // Set the lang attribute for languages different from the page's current language.
3844 if ($langtype !== $currentlang) {
3845 $attributes[] = [
3846 'key' => 'lang',
3847 'value' => get_html_lang_attribute_value($langtype),
3850 $this->language->add($langname, new moodle_url($this->page->url, ['lang' => $langtype]), null, null, $attributes);
3854 $content = '';
3855 foreach ($menu->get_children() as $item) {
3856 $context = $item->export_for_template($this);
3857 $content .= $this->render_from_template('core/custom_menu_item', $context);
3860 return $content;
3864 * Renders a custom menu node as part of a submenu
3866 * The custom menu this method produces makes use of the YUI3 menunav widget
3867 * and requires very specific html elements and classes.
3869 * @see core:renderer::render_custom_menu()
3871 * @staticvar int $submenucount
3872 * @param custom_menu_item $menunode
3873 * @return string
3875 protected function render_custom_menu_item(custom_menu_item $menunode) {
3876 // Required to ensure we get unique trackable id's
3877 static $submenucount = 0;
3878 if ($menunode->has_children()) {
3879 // If the child has menus render it as a sub menu
3880 $submenucount++;
3881 $content = html_writer::start_tag('li');
3882 if ($menunode->get_url() !== null) {
3883 $url = $menunode->get_url();
3884 } else {
3885 $url = '#cm_submenu_'.$submenucount;
3887 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3888 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3889 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3890 $content .= html_writer::start_tag('ul');
3891 foreach ($menunode->get_children() as $menunode) {
3892 $content .= $this->render_custom_menu_item($menunode);
3894 $content .= html_writer::end_tag('ul');
3895 $content .= html_writer::end_tag('div');
3896 $content .= html_writer::end_tag('div');
3897 $content .= html_writer::end_tag('li');
3898 } else {
3899 // The node doesn't have children so produce a final menuitem.
3900 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3901 $content = '';
3902 if (preg_match("/^#+$/", $menunode->get_text())) {
3904 // This is a divider.
3905 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3906 } else {
3907 $content = html_writer::start_tag(
3908 'li',
3909 array(
3910 'class' => 'yui3-menuitem'
3913 if ($menunode->get_url() !== null) {
3914 $url = $menunode->get_url();
3915 } else {
3916 $url = '#';
3918 $content .= html_writer::link(
3919 $url,
3920 $menunode->get_text(),
3921 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3924 $content .= html_writer::end_tag('li');
3926 // Return the sub menu
3927 return $content;
3931 * Renders theme links for switching between default and other themes.
3933 * @return string
3935 protected function theme_switch_links() {
3937 $actualdevice = core_useragent::get_device_type();
3938 $currentdevice = $this->page->devicetypeinuse;
3939 $switched = ($actualdevice != $currentdevice);
3941 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3942 // The user is using the a default device and hasn't switched so don't shown the switch
3943 // device links.
3944 return '';
3947 if ($switched) {
3948 $linktext = get_string('switchdevicerecommended');
3949 $devicetype = $actualdevice;
3950 } else {
3951 $linktext = get_string('switchdevicedefault');
3952 $devicetype = 'default';
3954 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3956 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3957 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3958 $content .= html_writer::end_tag('div');
3960 return $content;
3964 * Renders tabs
3966 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3968 * Theme developers: In order to change how tabs are displayed please override functions
3969 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3971 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3972 * @param string|null $selected which tab to mark as selected, all parent tabs will
3973 * automatically be marked as activated
3974 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3975 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3976 * @return string
3978 public final function tabtree($tabs, $selected = null, $inactive = null) {
3979 return $this->render(new tabtree($tabs, $selected, $inactive));
3983 * Renders tabtree
3985 * @param tabtree $tabtree
3986 * @return string
3988 protected function render_tabtree(tabtree $tabtree) {
3989 if (empty($tabtree->subtree)) {
3990 return '';
3992 $data = $tabtree->export_for_template($this);
3993 return $this->render_from_template('core/tabtree', $data);
3997 * Renders tabobject (part of tabtree)
3999 * This function is called from {@link core_renderer::render_tabtree()}
4000 * and also it calls itself when printing the $tabobject subtree recursively.
4002 * Property $tabobject->level indicates the number of row of tabs.
4004 * @param tabobject $tabobject
4005 * @return string HTML fragment
4007 protected function render_tabobject(tabobject $tabobject) {
4008 $str = '';
4010 // Print name of the current tab.
4011 if ($tabobject instanceof tabtree) {
4012 // No name for tabtree root.
4013 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
4014 // Tab name without a link. The <a> tag is used for styling.
4015 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
4016 } else {
4017 // Tab name with a link.
4018 if (!($tabobject->link instanceof moodle_url)) {
4019 // backward compartibility when link was passed as quoted string
4020 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
4021 } else {
4022 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
4026 if (empty($tabobject->subtree)) {
4027 if ($tabobject->selected) {
4028 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
4030 return $str;
4033 // Print subtree.
4034 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
4035 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
4036 $cnt = 0;
4037 foreach ($tabobject->subtree as $tab) {
4038 $liclass = '';
4039 if (!$cnt) {
4040 $liclass .= ' first';
4042 if ($cnt == count($tabobject->subtree) - 1) {
4043 $liclass .= ' last';
4045 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
4046 $liclass .= ' onerow';
4049 if ($tab->selected) {
4050 $liclass .= ' here selected';
4051 } else if ($tab->activated) {
4052 $liclass .= ' here active';
4055 // This will recursively call function render_tabobject() for each item in subtree.
4056 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
4057 $cnt++;
4059 $str .= html_writer::end_tag('ul');
4062 return $str;
4066 * Get the HTML for blocks in the given region.
4068 * @since Moodle 2.5.1 2.6
4069 * @param string $region The region to get HTML for.
4070 * @param array $classes Wrapping tag classes.
4071 * @param string $tag Wrapping tag.
4072 * @param boolean $fakeblocksonly Include fake blocks only.
4073 * @return string HTML.
4075 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
4076 $displayregion = $this->page->apply_theme_region_manipulations($region);
4077 $classes = (array)$classes;
4078 $classes[] = 'block-region';
4079 $attributes = array(
4080 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
4081 'class' => join(' ', $classes),
4082 'data-blockregion' => $displayregion,
4083 'data-droptarget' => '1'
4085 if ($this->page->blocks->region_has_content($displayregion, $this)) {
4086 $content = $this->blocks_for_region($displayregion, $fakeblocksonly);
4087 } else {
4088 $content = '';
4090 return html_writer::tag($tag, $content, $attributes);
4094 * Renders a custom block region.
4096 * Use this method if you want to add an additional block region to the content of the page.
4097 * Please note this should only be used in special situations.
4098 * We want to leave the theme is control where ever possible!
4100 * This method must use the same method that the theme uses within its layout file.
4101 * As such it asks the theme what method it is using.
4102 * It can be one of two values, blocks or blocks_for_region (deprecated).
4104 * @param string $regionname The name of the custom region to add.
4105 * @return string HTML for the block region.
4107 public function custom_block_region($regionname) {
4108 if ($this->page->theme->get_block_render_method() === 'blocks') {
4109 return $this->blocks($regionname);
4110 } else {
4111 return $this->blocks_for_region($regionname);
4116 * Returns the CSS classes to apply to the body tag.
4118 * @since Moodle 2.5.1 2.6
4119 * @param array $additionalclasses Any additional classes to apply.
4120 * @return string
4122 public function body_css_classes(array $additionalclasses = array()) {
4123 return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses);
4127 * The ID attribute to apply to the body tag.
4129 * @since Moodle 2.5.1 2.6
4130 * @return string
4132 public function body_id() {
4133 return $this->page->bodyid;
4137 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4139 * @since Moodle 2.5.1 2.6
4140 * @param string|array $additionalclasses Any additional classes to give the body tag,
4141 * @return string
4143 public function body_attributes($additionalclasses = array()) {
4144 if (!is_array($additionalclasses)) {
4145 $additionalclasses = explode(' ', $additionalclasses);
4147 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4151 * Gets HTML for the page heading.
4153 * @since Moodle 2.5.1 2.6
4154 * @param string $tag The tag to encase the heading in. h1 by default.
4155 * @return string HTML.
4157 public function page_heading($tag = 'h1') {
4158 return html_writer::tag($tag, $this->page->heading);
4162 * Gets the HTML for the page heading button.
4164 * @since Moodle 2.5.1 2.6
4165 * @return string HTML.
4167 public function page_heading_button() {
4168 return $this->page->button;
4172 * Returns the Moodle docs link to use for this page.
4174 * @since Moodle 2.5.1 2.6
4175 * @param string $text
4176 * @return string
4178 public function page_doc_link($text = null) {
4179 if ($text === null) {
4180 $text = get_string('moodledocslink');
4182 $path = page_get_doc_link_path($this->page);
4183 if (!$path) {
4184 return '';
4186 return $this->doc_link($path, $text);
4190 * Returns the HTML for the site support email link
4192 * @param array $customattribs Array of custom attributes for the support email anchor tag.
4193 * @return string The html code for the support email link.
4195 public function supportemail(array $customattribs = []): string {
4196 global $CFG;
4198 $label = get_string('contactsitesupport', 'admin');
4199 $icon = $this->pix_icon('t/email', '');
4200 $content = $icon . $label;
4202 if (!empty($CFG->supportpage)) {
4203 $attributes = ['href' => $CFG->supportpage, 'target' => 'blank'];
4204 $content .= $this->pix_icon('i/externallink', '', 'moodle', ['class' => 'ml-1']);
4205 } else {
4206 $attributes = ['href' => $CFG->wwwroot . '/user/contactsitesupport.php'];
4209 $attributes += $customattribs;
4211 return html_writer::tag('a', $content, $attributes);
4215 * Returns the services and support link for the help pop-up.
4217 * @return string
4219 public function services_support_link(): string {
4220 global $CFG;
4222 if (during_initial_install() ||
4223 (isset($CFG->showservicesandsupportcontent) && $CFG->showservicesandsupportcontent == false) ||
4224 !is_siteadmin()) {
4225 return '';
4228 $liferingicon = $this->pix_icon('t/life-ring', '', 'moodle', ['class' => 'fa fa-life-ring']);
4229 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle', ['class' => 'ml-1']);
4230 $link = 'https://moodle.com/help/?utm_source=CTA-banner&utm_medium=platform&utm_campaign=name~Moodle4+cat~lms+mp~no';
4231 $content = $liferingicon . get_string('moodleservicesandsupport') . $newwindowicon;
4233 return html_writer::tag('a', $content, ['target' => '_blank', 'href' => $link]);
4237 * Helper function to decide whether to show the help popover header or not.
4239 * @return bool
4241 public function has_popover_links(): bool {
4242 return !empty($this->services_support_link()) || !empty($this->page_doc_link()) || !empty($this->supportemail());
4246 * Returns the page heading menu.
4248 * @since Moodle 2.5.1 2.6
4249 * @return string HTML.
4251 public function page_heading_menu() {
4252 return $this->page->headingmenu;
4256 * Returns the title to use on the page.
4258 * @since Moodle 2.5.1 2.6
4259 * @return string
4261 public function page_title() {
4262 return $this->page->title;
4266 * Returns the moodle_url for the favicon.
4268 * @since Moodle 2.5.1 2.6
4269 * @return moodle_url The moodle_url for the favicon
4271 public function favicon() {
4272 $logo = null;
4273 if (!during_initial_install()) {
4274 $logo = get_config('core_admin', 'favicon');
4276 if (empty($logo)) {
4277 return $this->image_url('favicon', 'theme');
4280 // Use $CFG->themerev to prevent browser caching when the file changes.
4281 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'favicon', '64x64/',
4282 theme_get_revision(), $logo);
4286 * Renders preferences groups.
4288 * @param preferences_groups $renderable The renderable
4289 * @return string The output.
4291 public function render_preferences_groups(preferences_groups $renderable) {
4292 return $this->render_from_template('core/preferences_groups', $renderable);
4296 * Renders preferences group.
4298 * @param preferences_group $renderable The renderable
4299 * @return string The output.
4301 public function render_preferences_group(preferences_group $renderable) {
4302 $html = '';
4303 $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4304 $html .= $this->heading($renderable->title, 3);
4305 $html .= html_writer::start_tag('ul');
4306 foreach ($renderable->nodes as $node) {
4307 if ($node->has_children()) {
4308 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4310 $html .= html_writer::tag('li', $this->render($node));
4312 $html .= html_writer::end_tag('ul');
4313 $html .= html_writer::end_tag('div');
4314 return $html;
4317 public function context_header($headerinfo = null, $headinglevel = 1) {
4318 global $DB, $USER, $CFG, $SITE;
4319 require_once($CFG->dirroot . '/user/lib.php');
4320 $context = $this->page->context;
4321 $heading = null;
4322 $imagedata = null;
4323 $subheader = null;
4324 $userbuttons = null;
4326 // Make sure to use the heading if it has been set.
4327 if (isset($headerinfo['heading'])) {
4328 $heading = $headerinfo['heading'];
4329 } else {
4330 $heading = $this->page->heading;
4333 // The user context currently has images and buttons. Other contexts may follow.
4334 if ((isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) && $this->page->pagetype !== 'my-index') {
4335 if (isset($headerinfo['user'])) {
4336 $user = $headerinfo['user'];
4337 } else {
4338 // Look up the user information if it is not supplied.
4339 $user = $DB->get_record('user', array('id' => $context->instanceid));
4342 // If the user context is set, then use that for capability checks.
4343 if (isset($headerinfo['usercontext'])) {
4344 $context = $headerinfo['usercontext'];
4347 // Only provide user information if the user is the current user, or a user which the current user can view.
4348 // When checking user_can_view_profile(), either:
4349 // If the page context is course, check the course context (from the page object) or;
4350 // If page context is NOT course, then check across all courses.
4351 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4353 if (user_can_view_profile($user, $course)) {
4354 // Use the user's full name if the heading isn't set.
4355 if (empty($heading)) {
4356 $heading = fullname($user);
4359 $imagedata = $this->user_picture($user, array('size' => 100));
4361 // Check to see if we should be displaying a message button.
4362 if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
4363 $userbuttons = array(
4364 'messages' => array(
4365 'buttontype' => 'message',
4366 'title' => get_string('message', 'message'),
4367 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4368 'image' => 'message',
4369 'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
4370 'page' => $this->page
4374 if ($USER->id != $user->id) {
4375 $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4376 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4377 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4378 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4379 $userbuttons['togglecontact'] = array(
4380 'buttontype' => 'togglecontact',
4381 'title' => get_string($contacttitle, 'message'),
4382 'url' => new moodle_url('/message/index.php', array(
4383 'user1' => $USER->id,
4384 'user2' => $user->id,
4385 $contacturlaction => $user->id,
4386 'sesskey' => sesskey())
4388 'image' => $contactimage,
4389 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4390 'page' => $this->page
4394 } else {
4395 $heading = null;
4400 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4401 return $this->render_context_header($contextheader);
4405 * Renders the skip links for the page.
4407 * @param array $links List of skip links.
4408 * @return string HTML for the skip links.
4410 public function render_skip_links($links) {
4411 $context = [ 'links' => []];
4413 foreach ($links as $url => $text) {
4414 $context['links'][] = [ 'url' => $url, 'text' => $text];
4417 return $this->render_from_template('core/skip_links', $context);
4421 * Renders the header bar.
4423 * @param context_header $contextheader Header bar object.
4424 * @return string HTML for the header bar.
4426 protected function render_context_header(context_header $contextheader) {
4428 // Generate the heading first and before everything else as we might have to do an early return.
4429 if (!isset($contextheader->heading)) {
4430 $heading = $this->heading($this->page->heading, $contextheader->headinglevel);
4431 } else {
4432 $heading = $this->heading($contextheader->heading, $contextheader->headinglevel);
4435 $showheader = empty($this->page->layout_options['nocontextheader']);
4436 if (!$showheader) {
4437 // Return the heading wrapped in an sr-only element so it is only visible to screen-readers.
4438 return html_writer::div($heading, 'sr-only');
4441 // All the html stuff goes here.
4442 $html = html_writer::start_div('page-context-header');
4444 // Image data.
4445 if (isset($contextheader->imagedata)) {
4446 // Header specific image.
4447 $html .= html_writer::div($contextheader->imagedata, 'page-header-image icon-size-7');
4450 // Headings.
4451 if (isset($contextheader->prefix)) {
4452 $prefix = html_writer::div($contextheader->prefix, 'text-muted');
4453 $heading = $prefix . $heading;
4455 $html .= html_writer::tag('div', $heading, array('class' => 'page-header-headings'));
4457 // Buttons.
4458 if (isset($contextheader->additionalbuttons)) {
4459 $html .= html_writer::start_div('btn-group header-button-group');
4460 foreach ($contextheader->additionalbuttons as $button) {
4461 if (!isset($button->page)) {
4462 // Include js for messaging.
4463 if ($button['buttontype'] === 'togglecontact') {
4464 \core_message\helper::togglecontact_requirejs();
4466 if ($button['buttontype'] === 'message') {
4467 \core_message\helper::messageuser_requirejs();
4469 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4470 'class' => 'iconsmall',
4471 'role' => 'presentation'
4473 $image .= html_writer::span($button['title'], 'header-button-title');
4474 } else {
4475 $image = html_writer::empty_tag('img', array(
4476 'src' => $button['formattedimage'],
4477 'role' => 'presentation'
4480 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4482 $html .= html_writer::end_div();
4484 $html .= html_writer::end_div();
4486 return $html;
4490 * Wrapper for header elements.
4492 * @return string HTML to display the main header.
4494 public function full_header() {
4495 $pagetype = $this->page->pagetype;
4496 $homepage = get_home_page();
4497 $homepagetype = null;
4498 // Add a special case since /my/courses is a part of the /my subsystem.
4499 if ($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES) {
4500 $homepagetype = 'my-index';
4501 } else if ($homepage == HOMEPAGE_SITE) {
4502 $homepagetype = 'site-index';
4504 if ($this->page->include_region_main_settings_in_header_actions() &&
4505 !$this->page->blocks->is_block_present('settings')) {
4506 // Only include the region main settings if the page has requested it and it doesn't already have
4507 // the settings block on it. The region main settings are included in the settings block and
4508 // duplicating the content causes behat failures.
4509 $this->page->add_header_action(html_writer::div(
4510 $this->region_main_settings_menu(),
4511 'd-print-none',
4512 ['id' => 'region-main-settings-menu']
4516 $header = new stdClass();
4517 $header->settingsmenu = $this->context_header_settings_menu();
4518 $header->contextheader = $this->context_header();
4519 $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
4520 $header->navbar = $this->navbar();
4521 $header->pageheadingbutton = $this->page_heading_button();
4522 $header->courseheader = $this->course_header();
4523 $header->headeractions = $this->page->get_header_actions();
4524 if (!empty($pagetype) && !empty($homepagetype) && $pagetype == $homepagetype) {
4525 $header->welcomemessage = \core_user::welcome_message();
4527 return $this->render_from_template('core/full_header', $header);
4531 * This is an optional menu that can be added to a layout by a theme. It contains the
4532 * menu for the course administration, only on the course main page.
4534 * @return string
4536 public function context_header_settings_menu() {
4537 $context = $this->page->context;
4538 $menu = new action_menu();
4540 $items = $this->page->navbar->get_items();
4541 $currentnode = end($items);
4543 $showcoursemenu = false;
4544 $showfrontpagemenu = false;
4545 $showusermenu = false;
4547 // We are on the course home page.
4548 if (($context->contextlevel == CONTEXT_COURSE) &&
4549 !empty($currentnode) &&
4550 ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
4551 $showcoursemenu = true;
4554 $courseformat = course_get_format($this->page->course);
4555 // This is a single activity course format, always show the course menu on the activity main page.
4556 if ($context->contextlevel == CONTEXT_MODULE &&
4557 !$courseformat->has_view_page()) {
4559 $this->page->navigation->initialise();
4560 $activenode = $this->page->navigation->find_active_node();
4561 // If the settings menu has been forced then show the menu.
4562 if ($this->page->is_settings_menu_forced()) {
4563 $showcoursemenu = true;
4564 } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
4565 $activenode->type == navigation_node::TYPE_RESOURCE)) {
4567 // We only want to show the menu on the first page of the activity. This means
4568 // the breadcrumb has no additional nodes.
4569 if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
4570 $showcoursemenu = true;
4575 // This is the site front page.
4576 if ($context->contextlevel == CONTEXT_COURSE &&
4577 !empty($currentnode) &&
4578 $currentnode->key === 'home') {
4579 $showfrontpagemenu = true;
4582 // This is the user profile page.
4583 if ($context->contextlevel == CONTEXT_USER &&
4584 !empty($currentnode) &&
4585 ($currentnode->key === 'myprofile')) {
4586 $showusermenu = true;
4589 if ($showfrontpagemenu) {
4590 $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
4591 if ($settingsnode) {
4592 // Build an action menu based on the visible nodes from this navigation tree.
4593 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4595 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4596 if ($skipped) {
4597 $text = get_string('morenavigationlinks');
4598 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4599 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4600 $menu->add_secondary_action($link);
4603 } else if ($showcoursemenu) {
4604 $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
4605 if ($settingsnode) {
4606 // Build an action menu based on the visible nodes from this navigation tree.
4607 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4609 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4610 if ($skipped) {
4611 $text = get_string('morenavigationlinks');
4612 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4613 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4614 $menu->add_secondary_action($link);
4617 } else if ($showusermenu) {
4618 // Get the course admin node from the settings navigation.
4619 $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
4620 if ($settingsnode) {
4621 // Build an action menu based on the visible nodes from this navigation tree.
4622 $this->build_action_menu_from_navigation($menu, $settingsnode);
4626 return $this->render($menu);
4630 * Take a node in the nav tree and make an action menu out of it.
4631 * The links are injected in the action menu.
4633 * @param action_menu $menu
4634 * @param navigation_node $node
4635 * @param boolean $indent
4636 * @param boolean $onlytopleafnodes
4637 * @return boolean nodesskipped - True if nodes were skipped in building the menu
4639 protected function build_action_menu_from_navigation(action_menu $menu,
4640 navigation_node $node,
4641 $indent = false,
4642 $onlytopleafnodes = false) {
4643 $skipped = false;
4644 // Build an action menu based on the visible nodes from this navigation tree.
4645 foreach ($node->children as $menuitem) {
4646 if ($menuitem->display) {
4647 if ($onlytopleafnodes && $menuitem->children->count()) {
4648 $skipped = true;
4649 continue;
4651 if ($menuitem->action) {
4652 if ($menuitem->action instanceof action_link) {
4653 $link = $menuitem->action;
4654 // Give preference to setting icon over action icon.
4655 if (!empty($menuitem->icon)) {
4656 $link->icon = $menuitem->icon;
4658 } else {
4659 $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
4661 } else {
4662 if ($onlytopleafnodes) {
4663 $skipped = true;
4664 continue;
4666 $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
4668 if ($indent) {
4669 $link->add_class('ml-4');
4671 if (!empty($menuitem->classes)) {
4672 $link->add_class(implode(" ", $menuitem->classes));
4675 $menu->add_secondary_action($link);
4676 $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
4679 return $skipped;
4683 * This is an optional menu that can be added to a layout by a theme. It contains the
4684 * menu for the most specific thing from the settings block. E.g. Module administration.
4686 * @return string
4688 public function region_main_settings_menu() {
4689 $context = $this->page->context;
4690 $menu = new action_menu();
4692 if ($context->contextlevel == CONTEXT_MODULE) {
4694 $this->page->navigation->initialise();
4695 $node = $this->page->navigation->find_active_node();
4696 $buildmenu = false;
4697 // If the settings menu has been forced then show the menu.
4698 if ($this->page->is_settings_menu_forced()) {
4699 $buildmenu = true;
4700 } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
4701 $node->type == navigation_node::TYPE_RESOURCE)) {
4703 $items = $this->page->navbar->get_items();
4704 $navbarnode = end($items);
4705 // We only want to show the menu on the first page of the activity. This means
4706 // the breadcrumb has no additional nodes.
4707 if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
4708 $buildmenu = true;
4711 if ($buildmenu) {
4712 // Get the course admin node from the settings navigation.
4713 $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
4714 if ($node) {
4715 // Build an action menu based on the visible nodes from this navigation tree.
4716 $this->build_action_menu_from_navigation($menu, $node);
4720 } else if ($context->contextlevel == CONTEXT_COURSECAT) {
4721 // For course category context, show category settings menu, if we're on the course category page.
4722 if ($this->page->pagetype === 'course-index-category') {
4723 $node = $this->page->settingsnav->find('categorysettings', navigation_node::TYPE_CONTAINER);
4724 if ($node) {
4725 // Build an action menu based on the visible nodes from this navigation tree.
4726 $this->build_action_menu_from_navigation($menu, $node);
4730 } else {
4731 $items = $this->page->navbar->get_items();
4732 $navbarnode = end($items);
4734 if ($navbarnode && ($navbarnode->key === 'participants')) {
4735 $node = $this->page->settingsnav->find('users', navigation_node::TYPE_CONTAINER);
4736 if ($node) {
4737 // Build an action menu based on the visible nodes from this navigation tree.
4738 $this->build_action_menu_from_navigation($menu, $node);
4743 return $this->render($menu);
4747 * Displays the list of tags associated with an entry
4749 * @param array $tags list of instances of core_tag or stdClass
4750 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4751 * to use default, set to '' (empty string) to omit the label completely
4752 * @param string $classes additional classes for the enclosing div element
4753 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4754 * will be appended to the end, JS will toggle the rest of the tags
4755 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4756 * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
4757 * @return string
4759 public function tag_list($tags, $label = null, $classes = '', $limit = 10,
4760 $pagecontext = null, $accesshidelabel = false) {
4761 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
4762 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4766 * Renders element for inline editing of any value
4768 * @param \core\output\inplace_editable $element
4769 * @return string
4771 public function render_inplace_editable(\core\output\inplace_editable $element) {
4772 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4776 * Renders a bar chart.
4778 * @param \core\chart_bar $chart The chart.
4779 * @return string.
4781 public function render_chart_bar(\core\chart_bar $chart) {
4782 return $this->render_chart($chart);
4786 * Renders a line chart.
4788 * @param \core\chart_line $chart The chart.
4789 * @return string.
4791 public function render_chart_line(\core\chart_line $chart) {
4792 return $this->render_chart($chart);
4796 * Renders a pie chart.
4798 * @param \core\chart_pie $chart The chart.
4799 * @return string.
4801 public function render_chart_pie(\core\chart_pie $chart) {
4802 return $this->render_chart($chart);
4806 * Renders a chart.
4808 * @param \core\chart_base $chart The chart.
4809 * @param bool $withtable Whether to include a data table with the chart.
4810 * @return string.
4812 public function render_chart(\core\chart_base $chart, $withtable = true) {
4813 $chartdata = json_encode($chart);
4814 return $this->render_from_template('core/chart', (object) [
4815 'chartdata' => $chartdata,
4816 'withtable' => $withtable
4821 * Renders the login form.
4823 * @param \core_auth\output\login $form The renderable.
4824 * @return string
4826 public function render_login(\core_auth\output\login $form) {
4827 global $CFG, $SITE;
4829 $context = $form->export_for_template($this);
4831 $context->errorformatted = $this->error_text($context->error);
4832 $url = $this->get_logo_url();
4833 if ($url) {
4834 $url = $url->out(false);
4836 $context->logourl = $url;
4837 $context->sitename = format_string($SITE->fullname, true,
4838 ['context' => context_course::instance(SITEID), "escape" => false]);
4840 return $this->render_from_template('core/loginform', $context);
4844 * Renders an mform element from a template.
4846 * @param HTML_QuickForm_element $element element
4847 * @param bool $required if input is required field
4848 * @param bool $advanced if input is an advanced field
4849 * @param string $error error message to display
4850 * @param bool $ingroup True if this element is rendered as part of a group
4851 * @return mixed string|bool
4853 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4854 $templatename = 'core_form/element-' . $element->getType();
4855 if ($ingroup) {
4856 $templatename .= "-inline";
4858 try {
4859 // We call this to generate a file not found exception if there is no template.
4860 // We don't want to call export_for_template if there is no template.
4861 core\output\mustache_template_finder::get_template_filepath($templatename);
4863 if ($element instanceof templatable) {
4864 $elementcontext = $element->export_for_template($this);
4866 $helpbutton = '';
4867 if (method_exists($element, 'getHelpButton')) {
4868 $helpbutton = $element->getHelpButton();
4870 $label = $element->getLabel();
4871 $text = '';
4872 if (method_exists($element, 'getText')) {
4873 // There currently exists code that adds a form element with an empty label.
4874 // If this is the case then set the label to the description.
4875 if (empty($label)) {
4876 $label = $element->getText();
4877 } else {
4878 $text = $element->getText();
4882 // Generate the form element wrapper ids and names to pass to the template.
4883 // This differs between group and non-group elements.
4884 if ($element->getType() === 'group') {
4885 // Group element.
4886 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
4887 $elementcontext['wrapperid'] = $elementcontext['id'];
4889 // Ensure group elements pass through the group name as the element name.
4890 $elementcontext['name'] = $elementcontext['groupname'];
4891 } else {
4892 // Non grouped element.
4893 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
4894 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
4897 $context = array(
4898 'element' => $elementcontext,
4899 'label' => $label,
4900 'text' => $text,
4901 'required' => $required,
4902 'advanced' => $advanced,
4903 'helpbutton' => $helpbutton,
4904 'error' => $error
4906 return $this->render_from_template($templatename, $context);
4908 } catch (Exception $e) {
4909 // No template for this element.
4910 return false;
4915 * Render the login signup form into a nice template for the theme.
4917 * @param mform $form
4918 * @return string
4920 public function render_login_signup_form($form) {
4921 global $SITE;
4923 $context = $form->export_for_template($this);
4924 $url = $this->get_logo_url();
4925 if ($url) {
4926 $url = $url->out(false);
4928 $context['logourl'] = $url;
4929 $context['sitename'] = format_string($SITE->fullname, true,
4930 ['context' => context_course::instance(SITEID), "escape" => false]);
4932 return $this->render_from_template('core/signup_form_layout', $context);
4936 * Render the verify age and location page into a nice template for the theme.
4938 * @param \core_auth\output\verify_age_location_page $page The renderable
4939 * @return string
4941 protected function render_verify_age_location_page($page) {
4942 $context = $page->export_for_template($this);
4944 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4948 * Render the digital minor contact information page into a nice template for the theme.
4950 * @param \core_auth\output\digital_minor_page $page The renderable
4951 * @return string
4953 protected function render_digital_minor_page($page) {
4954 $context = $page->export_for_template($this);
4956 return $this->render_from_template('core/auth_digital_minor_page', $context);
4960 * Renders a progress bar.
4962 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4964 * @param progress_bar $bar The bar.
4965 * @return string HTML fragment
4967 public function render_progress_bar(progress_bar $bar) {
4968 $data = $bar->export_for_template($this);
4969 return $this->render_from_template('core/progress_bar', $data);
4973 * Renders an update to a progress bar.
4975 * Note: This does not cleanly map to a renderable class and should
4976 * never be used directly.
4978 * @param string $id
4979 * @param float $percent
4980 * @param string $msg Message
4981 * @param string $estimate time remaining message
4982 * @return string ascii fragment
4984 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
4985 return html_writer::script(js_writer::function_call('updateProgressBar', [$id, $percent, $msg, $estimate]));
4989 * Renders element for a toggle-all checkbox.
4991 * @param \core\output\checkbox_toggleall $element
4992 * @return string
4994 public function render_checkbox_toggleall(\core\output\checkbox_toggleall $element) {
4995 return $this->render_from_template($element->get_template(), $element->export_for_template($this));
4999 * Renders the tertiary nav for the participants page
5001 * @param object $course The course we are operating within
5002 * @param string|null $renderedbuttons Any additional buttons/content to be displayed in line with the nav
5003 * @return string
5005 public function render_participants_tertiary_nav(object $course, ?string $renderedbuttons = null) {
5006 $actionbar = new \core\output\participants_action_bar($course, $this->page, $renderedbuttons);
5007 $content = $this->render_from_template('core_course/participants_actionbar', $actionbar->export_for_template($this));
5008 return $content ?: "";
5012 * Renders release information in the footer popup
5013 * @return string Moodle release info.
5015 public function moodle_release() {
5016 global $CFG;
5017 if (!during_initial_install() && is_siteadmin()) {
5018 return $CFG->release;
5023 * Generate the add block button when editing mode is turned on and the user can edit blocks.
5025 * @param string $region where new blocks should be added.
5026 * @return string html for the add block button.
5028 public function addblockbutton($region = ''): string {
5029 $addblockbutton = '';
5030 $regions = $this->page->blocks->get_regions();
5031 if (count($regions) == 0) {
5032 return '';
5034 if (isset($this->page->theme->addblockposition) &&
5035 $this->page->user_is_editing() &&
5036 $this->page->user_can_edit_blocks() &&
5037 $this->page->pagelayout !== 'mycourses'
5039 $params = ['bui_addblock' => '', 'sesskey' => sesskey()];
5040 if (!empty($region)) {
5041 $params['bui_blockregion'] = $region;
5043 $url = new moodle_url($this->page->url, $params);
5044 $addblockbutton = $this->render_from_template('core/add_block_button',
5046 'link' => $url->out(false),
5047 'escapedlink' => "?{$url->get_query_string(false)}",
5048 'pageType' => $this->page->pagetype,
5049 'pageLayout' => $this->page->pagelayout,
5050 'subPage' => $this->page->subpage,
5054 return $addblockbutton;
5059 * A renderer that generates output for command-line scripts.
5061 * The implementation of this renderer is probably incomplete.
5063 * @copyright 2009 Tim Hunt
5064 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5065 * @since Moodle 2.0
5066 * @package core
5067 * @category output
5069 class core_renderer_cli extends core_renderer {
5072 * @var array $progressmaximums stores the largest percentage for a progress bar.
5073 * @return string ascii fragment
5075 private $progressmaximums = [];
5078 * Returns the page header.
5080 * @return string HTML fragment
5082 public function header() {
5083 return $this->page->heading . "\n";
5087 * Renders a Check API result
5089 * To aid in CLI consistency this status is NOT translated and the visual
5090 * width is always exactly 10 chars.
5092 * @param core\check\result $result
5093 * @return string HTML fragment
5095 protected function render_check_result(core\check\result $result) {
5096 $status = $result->get_status();
5098 $labels = [
5099 core\check\result::NA => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' NA ',
5100 core\check\result::OK => ' ' . cli_ansi_format('<colour:green>') . ' OK ',
5101 core\check\result::INFO => ' ' . cli_ansi_format('<colour:blue>' ) . ' INFO ',
5102 core\check\result::UNKNOWN => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' UNKNOWN ',
5103 core\check\result::WARNING => ' ' . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
5104 core\check\result::ERROR => ' ' . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
5105 core\check\result::CRITICAL => '' . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
5107 $string = $labels[$status] . cli_ansi_format('<colour:normal>');
5108 return $string;
5112 * Renders a Check API result
5114 * @param result $result
5115 * @return string fragment
5117 public function check_result(core\check\result $result) {
5118 return $this->render_check_result($result);
5122 * Renders a progress bar.
5124 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
5126 * @param progress_bar $bar The bar.
5127 * @return string ascii fragment
5129 public function render_progress_bar(progress_bar $bar) {
5130 global $CFG;
5132 $size = 55; // The width of the progress bar in chars.
5133 $ascii = "\n";
5135 if (stream_isatty(STDOUT)) {
5136 require_once($CFG->libdir.'/clilib.php');
5138 $ascii .= "[" . str_repeat(' ', $size) . "] 0% \n";
5139 return cli_ansi_format($ascii);
5142 $this->progressmaximums[$bar->get_id()] = 0;
5143 $ascii .= '[';
5144 return $ascii;
5148 * Renders an update to a progress bar.
5150 * Note: This does not cleanly map to a renderable class and should
5151 * never be used directly.
5153 * @param string $id
5154 * @param float $percent
5155 * @param string $msg Message
5156 * @param string $estimate time remaining message
5157 * @return string ascii fragment
5159 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
5160 $size = 55; // The width of the progress bar in chars.
5161 $ascii = '';
5163 // If we are rendering to a terminal then we can safely use ansii codes
5164 // to move the cursor and redraw the complete progress bar each time
5165 // it is updated.
5166 if (stream_isatty(STDOUT)) {
5167 $colour = $percent == 100 ? 'green' : 'blue';
5169 $done = $percent * $size * 0.01;
5170 $whole = floor($done);
5171 $bar = "<colour:$colour>";
5172 $bar .= str_repeat('█', $whole);
5174 if ($whole < $size) {
5175 // By using unicode chars for partial blocks we can have higher
5176 // precision progress bar.
5177 $fraction = floor(($done - $whole) * 8);
5178 $bar .= core_text::substr(' ▏▎▍▌▋▊▉', $fraction, 1);
5180 // Fill the rest of the empty bar.
5181 $bar .= str_repeat(' ', $size - $whole - 1);
5184 $bar .= '<colour:normal>';
5186 if ($estimate) {
5187 $estimate = "- $estimate";
5190 $ascii .= '<cursor:up>';
5191 $ascii .= '<cursor:up>';
5192 $ascii .= sprintf("[$bar] %3.1f%% %-22s\n", $percent, $estimate);
5193 $ascii .= sprintf("%-80s\n", $msg);
5194 return cli_ansi_format($ascii);
5197 // If we are not rendering to a tty, ie when piped to another command
5198 // or on windows we need to progressively render the progress bar
5199 // which can only ever go forwards.
5200 $done = round($percent * $size * 0.01);
5201 $delta = max(0, $done - $this->progressmaximums[$id]);
5203 $ascii .= str_repeat('#', $delta);
5204 if ($percent >= 100 && $delta > 0) {
5205 $ascii .= sprintf("] %3.1f%%\n$msg\n", $percent);
5207 $this->progressmaximums[$id] += $delta;
5208 return $ascii;
5212 * Returns a template fragment representing a Heading.
5214 * @param string $text The text of the heading
5215 * @param int $level The level of importance of the heading
5216 * @param string $classes A space-separated list of CSS classes
5217 * @param string $id An optional ID
5218 * @return string A template fragment for a heading
5220 public function heading($text, $level = 2, $classes = 'main', $id = null) {
5221 $text .= "\n";
5222 switch ($level) {
5223 case 1:
5224 return '=>' . $text;
5225 case 2:
5226 return '-->' . $text;
5227 default:
5228 return $text;
5233 * Returns a template fragment representing a fatal error.
5235 * @param string $message The message to output
5236 * @param string $moreinfourl URL where more info can be found about the error
5237 * @param string $link Link for the Continue button
5238 * @param array $backtrace The execution backtrace
5239 * @param string $debuginfo Debugging information
5240 * @return string A template fragment for a fatal error
5242 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5243 global $CFG;
5245 $output = "!!! $message !!!\n";
5247 if ($CFG->debugdeveloper) {
5248 if (!empty($debuginfo)) {
5249 $output .= $this->notification($debuginfo, 'notifytiny');
5251 if (!empty($backtrace)) {
5252 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
5256 return $output;
5260 * Returns a template fragment representing a notification.
5262 * @param string $message The message to print out.
5263 * @param string $type The type of notification. See constants on \core\output\notification.
5264 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5265 * @return string A template fragment for a notification
5267 public function notification($message, $type = null, $closebutton = true) {
5268 $message = clean_text($message);
5269 if ($type === 'notifysuccess' || $type === 'success') {
5270 return "++ $message ++\n";
5272 return "!! $message !!\n";
5276 * There is no footer for a cli request, however we must override the
5277 * footer method to prevent the default footer.
5279 public function footer() {}
5282 * Render a notification (that is, a status message about something that has
5283 * just happened).
5285 * @param \core\output\notification $notification the notification to print out
5286 * @return string plain text output
5288 public function render_notification(\core\output\notification $notification) {
5289 return $this->notification($notification->get_message(), $notification->get_message_type());
5295 * A renderer that generates output for ajax scripts.
5297 * This renderer prevents accidental sends back only json
5298 * encoded error messages, all other output is ignored.
5300 * @copyright 2010 Petr Skoda
5301 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5302 * @since Moodle 2.0
5303 * @package core
5304 * @category output
5306 class core_renderer_ajax extends core_renderer {
5309 * Returns a template fragment representing a fatal error.
5311 * @param string $message The message to output
5312 * @param string $moreinfourl URL where more info can be found about the error
5313 * @param string $link Link for the Continue button
5314 * @param array $backtrace The execution backtrace
5315 * @param string $debuginfo Debugging information
5316 * @return string A template fragment for a fatal error
5318 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5319 global $CFG;
5321 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
5323 $e = new stdClass();
5324 $e->error = $message;
5325 $e->errorcode = $errorcode;
5326 $e->stacktrace = NULL;
5327 $e->debuginfo = NULL;
5328 $e->reproductionlink = NULL;
5329 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
5330 $link = (string) $link;
5331 if ($link) {
5332 $e->reproductionlink = $link;
5334 if (!empty($debuginfo)) {
5335 $e->debuginfo = $debuginfo;
5337 if (!empty($backtrace)) {
5338 $e->stacktrace = format_backtrace($backtrace, true);
5341 $this->header();
5342 return json_encode($e);
5346 * Used to display a notification.
5347 * For the AJAX notifications are discarded.
5349 * @param string $message The message to print out.
5350 * @param string $type The type of notification. See constants on \core\output\notification.
5351 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5353 public function notification($message, $type = null, $closebutton = true) {
5357 * Used to display a redirection message.
5358 * AJAX redirections should not occur and as such redirection messages
5359 * are discarded.
5361 * @param moodle_url|string $encodedurl
5362 * @param string $message
5363 * @param int $delay
5364 * @param bool $debugdisableredirect
5365 * @param string $messagetype The type of notification to show the message in.
5366 * See constants on \core\output\notification.
5368 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
5369 $messagetype = \core\output\notification::NOTIFY_INFO) {}
5372 * Prepares the start of an AJAX output.
5374 public function header() {
5375 // unfortunately YUI iframe upload does not support application/json
5376 if (!empty($_FILES)) {
5377 @header('Content-type: text/plain; charset=utf-8');
5378 if (!core_useragent::supports_json_contenttype()) {
5379 @header('X-Content-Type-Options: nosniff');
5381 } else if (!core_useragent::supports_json_contenttype()) {
5382 @header('Content-type: text/plain; charset=utf-8');
5383 @header('X-Content-Type-Options: nosniff');
5384 } else {
5385 @header('Content-type: application/json; charset=utf-8');
5388 // Headers to make it not cacheable and json
5389 @header('Cache-Control: no-store, no-cache, must-revalidate');
5390 @header('Cache-Control: post-check=0, pre-check=0', false);
5391 @header('Pragma: no-cache');
5392 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
5393 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
5394 @header('Accept-Ranges: none');
5398 * There is no footer for an AJAX request, however we must override the
5399 * footer method to prevent the default footer.
5401 public function footer() {}
5404 * No need for headers in an AJAX request... this should never happen.
5405 * @param string $text
5406 * @param int $level
5407 * @param string $classes
5408 * @param string $id
5410 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
5416 * The maintenance renderer.
5418 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
5419 * is running a maintenance related task.
5420 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
5422 * @since Moodle 2.6
5423 * @package core
5424 * @category output
5425 * @copyright 2013 Sam Hemelryk
5426 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5428 class core_renderer_maintenance extends core_renderer {
5431 * Initialises the renderer instance.
5433 * @param moodle_page $page
5434 * @param string $target
5435 * @throws coding_exception
5437 public function __construct(moodle_page $page, $target) {
5438 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
5439 throw new coding_exception('Invalid request for the maintenance renderer.');
5441 parent::__construct($page, $target);
5445 * Does nothing. The maintenance renderer cannot produce blocks.
5447 * @param block_contents $bc
5448 * @param string $region
5449 * @return string
5451 public function block(block_contents $bc, $region) {
5452 return '';
5456 * Does nothing. The maintenance renderer cannot produce blocks.
5458 * @param string $region
5459 * @param array $classes
5460 * @param string $tag
5461 * @param boolean $fakeblocksonly
5462 * @return string
5464 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
5465 return '';
5469 * Does nothing. The maintenance renderer cannot produce blocks.
5471 * @param string $region
5472 * @param boolean $fakeblocksonly Output fake block only.
5473 * @return string
5475 public function blocks_for_region($region, $fakeblocksonly = false) {
5476 return '';
5480 * Does nothing. The maintenance renderer cannot produce a course content header.
5482 * @param bool $onlyifnotcalledbefore
5483 * @return string
5485 public function course_content_header($onlyifnotcalledbefore = false) {
5486 return '';
5490 * Does nothing. The maintenance renderer cannot produce a course content footer.
5492 * @param bool $onlyifnotcalledbefore
5493 * @return string
5495 public function course_content_footer($onlyifnotcalledbefore = false) {
5496 return '';
5500 * Does nothing. The maintenance renderer cannot produce a course header.
5502 * @return string
5504 public function course_header() {
5505 return '';
5509 * Does nothing. The maintenance renderer cannot produce a course footer.
5511 * @return string
5513 public function course_footer() {
5514 return '';
5518 * Does nothing. The maintenance renderer cannot produce a custom menu.
5520 * @param string $custommenuitems
5521 * @return string
5523 public function custom_menu($custommenuitems = '') {
5524 return '';
5528 * Does nothing. The maintenance renderer cannot produce a file picker.
5530 * @param array $options
5531 * @return string
5533 public function file_picker($options) {
5534 return '';
5538 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
5540 * @param array $dir
5541 * @return string
5543 public function htmllize_file_tree($dir) {
5544 return '';
5549 * Overridden confirm message for upgrades.
5551 * @param string $message The question to ask the user
5552 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5553 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5554 * @param array $displayoptions optional extra display options
5555 * @return string HTML fragment
5557 public function confirm($message, $continue, $cancel, array $displayoptions = []) {
5558 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5559 // from any previous version of Moodle).
5560 if ($continue instanceof single_button) {
5561 $continue->primary = true;
5562 } else if (is_string($continue)) {
5563 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
5564 } else if ($continue instanceof moodle_url) {
5565 $continue = new single_button($continue, get_string('continue'), 'post', true);
5566 } else {
5567 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5568 ' (string/moodle_url) or a single_button instance.');
5571 if ($cancel instanceof single_button) {
5572 $output = '';
5573 } else if (is_string($cancel)) {
5574 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5575 } else if ($cancel instanceof moodle_url) {
5576 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5577 } else {
5578 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5579 ' (string/moodle_url) or a single_button instance.');
5582 $output = $this->box_start('generalbox', 'notice');
5583 $output .= html_writer::tag('h4', get_string('confirm'));
5584 $output .= html_writer::tag('p', $message);
5585 $output .= html_writer::tag('div', $this->render($cancel) . $this->render($continue), ['class' => 'buttons']);
5586 $output .= $this->box_end();
5587 return $output;
5591 * Does nothing. The maintenance renderer does not support JS.
5593 * @param block_contents $bc
5595 public function init_block_hider_js(block_contents $bc) {
5596 // Does nothing.
5600 * Does nothing. The maintenance renderer cannot produce language menus.
5602 * @return string
5604 public function lang_menu() {
5605 return '';
5609 * Does nothing. The maintenance renderer has no need for login information.
5611 * @param null $withlinks
5612 * @return string
5614 public function login_info($withlinks = null) {
5615 return '';
5619 * Secure login info.
5621 * @return string
5623 public function secure_login_info() {
5624 return $this->login_info(false);
5628 * Does nothing. The maintenance renderer cannot produce user pictures.
5630 * @param stdClass $user
5631 * @param array $options
5632 * @return string
5634 public function user_picture(stdClass $user, array $options = null) {
5635 return '';