Merge branch 'MDL-73670-master' of https://github.com/jleyva/moodle
[moodle.git] / lib / outputrenderers.php
blob5b0e8d735b24f5b2a87b888b677098b9027fac53
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 * @var array $templatecache The mustache template cache.
81 protected $templatecache = [];
83 /**
84 * Return an instance of the mustache class.
86 * @since 2.9
87 * @return Mustache_Engine
89 protected function get_mustache() {
90 global $CFG;
92 if ($this->mustache === null) {
93 require_once("{$CFG->libdir}/filelib.php");
95 $themename = $this->page->theme->name;
96 $themerev = theme_get_revision();
98 // Create new localcache directory.
99 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
101 // Remove old localcache directories.
102 $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR);
103 foreach ($mustachecachedirs as $localcachedir) {
104 $cachedrev = [];
105 preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
106 $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
107 if ($cachedrev > 0 && $cachedrev < $themerev) {
108 fulldelete($localcachedir);
112 $loader = new \core\output\mustache_filesystem_loader();
113 $stringhelper = new \core\output\mustache_string_helper();
114 $cleanstringhelper = new \core\output\mustache_clean_string_helper();
115 $quotehelper = new \core\output\mustache_quote_helper();
116 $jshelper = new \core\output\mustache_javascript_helper($this->page);
117 $pixhelper = new \core\output\mustache_pix_helper($this);
118 $shortentexthelper = new \core\output\mustache_shorten_text_helper();
119 $userdatehelper = new \core\output\mustache_user_date_helper();
121 // We only expose the variables that are exposed to JS templates.
122 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
124 $helpers = array('config' => $safeconfig,
125 'str' => array($stringhelper, 'str'),
126 'cleanstr' => array($cleanstringhelper, 'cleanstr'),
127 'quote' => array($quotehelper, 'quote'),
128 'js' => array($jshelper, 'help'),
129 'pix' => array($pixhelper, 'pix'),
130 'shortentext' => array($shortentexthelper, 'shorten'),
131 'userdate' => array($userdatehelper, 'transform'),
134 $this->mustache = new \core\output\mustache_engine(array(
135 'cache' => $cachedir,
136 'escape' => 's',
137 'loader' => $loader,
138 'helpers' => $helpers,
139 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS],
140 // Don't allow the JavaScript helper to be executed from within another
141 // helper. If it's allowed it can be used by users to inject malicious
142 // JS into the page.
143 'disallowednestedhelpers' => ['js'],
144 // Disable lambda rendering - content in helpers is already rendered, no need to render it again.
145 'disable_lambda_rendering' => true,
150 return $this->mustache;
155 * Constructor
157 * The constructor takes two arguments. The first is the page that the renderer
158 * has been created to assist with, and the second is the target.
159 * The target is an additional identifier that can be used to load different
160 * renderers for different options.
162 * @param moodle_page $page the page we are doing output for.
163 * @param string $target one of rendering target constants
165 public function __construct(moodle_page $page, $target) {
166 $this->opencontainers = $page->opencontainers;
167 $this->page = $page;
168 $this->target = $target;
172 * Renders a template by name with the given context.
174 * The provided data needs to be array/stdClass made up of only simple types.
175 * Simple types are array,stdClass,bool,int,float,string
177 * @since 2.9
178 * @param array|stdClass $context Context containing data for the template.
179 * @return string|boolean
181 public function render_from_template($templatename, $context) {
182 $mustache = $this->get_mustache();
184 try {
185 // Grab a copy of the existing helper to be restored later.
186 $uniqidhelper = $mustache->getHelper('uniqid');
187 } catch (Mustache_Exception_UnknownHelperException $e) {
188 // Helper doesn't exist.
189 $uniqidhelper = null;
192 // Provide 1 random value that will not change within a template
193 // but will be different from template to template. This is useful for
194 // e.g. aria attributes that only work with id attributes and must be
195 // unique in a page.
196 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
197 if (isset($this->templatecache[$templatename])) {
198 $template = $this->templatecache[$templatename];
199 } else {
200 try {
201 $template = $mustache->loadTemplate($templatename);
202 $this->templatecache[$templatename] = $template;
203 } catch (Mustache_Exception_UnknownTemplateException $e) {
204 throw new moodle_exception('Unknown template: ' . $templatename);
208 $renderedtemplate = trim($template->render($context));
210 // If we had an existing uniqid helper then we need to restore it to allow
211 // handle nested calls of render_from_template.
212 if ($uniqidhelper) {
213 $mustache->addHelper('uniqid', $uniqidhelper);
216 return $renderedtemplate;
221 * Returns rendered widget.
223 * The provided widget needs to be an object that extends the renderable
224 * interface.
225 * If will then be rendered by a method based upon the classname for the widget.
226 * For instance a widget of class `crazywidget` will be rendered by a protected
227 * render_crazywidget method of this renderer.
228 * If no render_crazywidget method exists and crazywidget implements templatable,
229 * look for the 'crazywidget' template in the same component and render that.
231 * @param renderable $widget instance with renderable interface
232 * @return string
234 public function render(renderable $widget) {
235 $classparts = explode('\\', get_class($widget));
236 // Strip namespaces.
237 $classname = array_pop($classparts);
238 // Remove _renderable suffixes.
239 $classname = preg_replace('/_renderable$/', '', $classname);
241 $rendermethod = "render_{$classname}";
242 if (method_exists($this, $rendermethod)) {
243 // Call the render_[widget_name] function.
244 // Note: This has a higher priority than the named_templatable to allow the theme to override the template.
245 return $this->$rendermethod($widget);
248 if ($widget instanceof named_templatable) {
249 // This is a named templatable.
250 // Fetch the template name from the get_template_name function instead.
251 // Note: This has higher priority than the guessed template name.
252 return $this->render_from_template(
253 $widget->get_template_name($this),
254 $widget->export_for_template($this)
258 if ($widget instanceof templatable) {
259 // Guess the templat ename based on the class name.
260 // Note: There's no benefit to moving this aboved the named_templatable and this approach is more costly.
261 $component = array_shift($classparts);
262 if (!$component) {
263 $component = 'core';
265 $template = $component . '/' . $classname;
266 $context = $widget->export_for_template($this);
267 return $this->render_from_template($template, $context);
269 throw new coding_exception("Can not render widget, renderer method ('{$rendermethod}') not found.");
273 * Adds a JS action for the element with the provided id.
275 * This method adds a JS event for the provided component action to the page
276 * and then returns the id that the event has been attached to.
277 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
279 * @param component_action $action
280 * @param string $id
281 * @return string id of element, either original submitted or random new if not supplied
283 public function add_action_handler(component_action $action, $id = null) {
284 if (!$id) {
285 $id = html_writer::random_id($action->event);
287 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
288 return $id;
292 * Returns true is output has already started, and false if not.
294 * @return boolean true if the header has been printed.
296 public function has_started() {
297 return $this->page->state >= moodle_page::STATE_IN_BODY;
301 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
303 * @param mixed $classes Space-separated string or array of classes
304 * @return string HTML class attribute value
306 public static function prepare_classes($classes) {
307 if (is_array($classes)) {
308 return implode(' ', array_unique($classes));
310 return $classes;
314 * Return the direct URL for an image from the pix folder.
316 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
318 * @deprecated since Moodle 3.3
319 * @param string $imagename the name of the icon.
320 * @param string $component specification of one plugin like in get_string()
321 * @return moodle_url
323 public function pix_url($imagename, $component = 'moodle') {
324 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
325 return $this->page->theme->image_url($imagename, $component);
329 * Return the moodle_url for an image.
331 * The exact image location and extension is determined
332 * automatically by searching for gif|png|jpg|jpeg, please
333 * note there can not be diferent images with the different
334 * extension. The imagename is for historical reasons
335 * a relative path name, it may be changed later for core
336 * images. It is recommended to not use subdirectories
337 * in plugin and theme pix directories.
339 * There are three types of images:
340 * 1/ theme images - stored in theme/mytheme/pix/,
341 * use component 'theme'
342 * 2/ core images - stored in /pix/,
343 * overridden via theme/mytheme/pix_core/
344 * 3/ plugin images - stored in mod/mymodule/pix,
345 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
346 * example: image_url('comment', 'mod_glossary')
348 * @param string $imagename the pathname of the image
349 * @param string $component full plugin name (aka component) or 'theme'
350 * @return moodle_url
352 public function image_url($imagename, $component = 'moodle') {
353 return $this->page->theme->image_url($imagename, $component);
357 * Return the site's logo URL, if any.
359 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
360 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
361 * @return moodle_url|false
363 public function get_logo_url($maxwidth = null, $maxheight = 200) {
364 global $CFG;
365 $logo = get_config('core_admin', 'logo');
366 if (empty($logo)) {
367 return false;
370 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
371 // It's not worth the overhead of detecting and serving 2 different images based on the device.
373 // Hide the requested size in the file path.
374 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
376 // Use $CFG->themerev to prevent browser caching when the file changes.
377 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
378 theme_get_revision(), $logo);
382 * Return the site's compact logo URL, if any.
384 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
385 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
386 * @return moodle_url|false
388 public function get_compact_logo_url($maxwidth = 300, $maxheight = 300) {
389 global $CFG;
390 $logo = get_config('core_admin', 'logocompact');
391 if (empty($logo)) {
392 return false;
395 // Hide the requested size in the file path.
396 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
398 // Use $CFG->themerev to prevent browser caching when the file changes.
399 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
400 theme_get_revision(), $logo);
404 * Whether we should display the logo in the navbar.
406 * We will when there are no main logos, and we have compact logo.
408 * @return bool
410 public function should_display_navbar_logo() {
411 $logo = $this->get_compact_logo_url();
412 return !empty($logo);
416 * Whether we should display the main logo.
417 * @deprecated since Moodle 4.0
418 * @todo final deprecation. To be removed in Moodle 4.4 MDL-73165.
419 * @param int $headinglevel The heading level we want to check against.
420 * @return bool
422 public function should_display_main_logo($headinglevel = 1) {
423 debugging('should_display_main_logo() is deprecated and will be removed in Moodle 4.4.', DEBUG_DEVELOPER);
424 // Only render the logo if we're on the front page or login page and the we have a logo.
425 $logo = $this->get_logo_url();
426 if ($headinglevel == 1 && !empty($logo)) {
427 if ($this->page->pagelayout == 'frontpage' || $this->page->pagelayout == 'login') {
428 return true;
432 return false;
439 * Basis for all plugin renderers.
441 * @copyright Petr Skoda (skodak)
442 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
443 * @since Moodle 2.0
444 * @package core
445 * @category output
447 class plugin_renderer_base extends renderer_base {
450 * @var renderer_base|core_renderer A reference to the current renderer.
451 * The renderer provided here will be determined by the page but will in 90%
452 * of cases by the {@link core_renderer}
454 protected $output;
457 * Constructor method, calls the parent constructor
459 * @param moodle_page $page
460 * @param string $target one of rendering target constants
462 public function __construct(moodle_page $page, $target) {
463 if (empty($target) && $page->pagelayout === 'maintenance') {
464 // If the page is using the maintenance layout then we're going to force the target to maintenance.
465 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
466 // unavailable for this page layout.
467 $target = RENDERER_TARGET_MAINTENANCE;
469 $this->output = $page->get_renderer('core', null, $target);
470 parent::__construct($page, $target);
474 * Renders the provided widget and returns the HTML to display it.
476 * @param renderable $widget instance with renderable interface
477 * @return string
479 public function render(renderable $widget) {
480 $classname = get_class($widget);
482 // Strip namespaces.
483 $classname = preg_replace('/^.*\\\/', '', $classname);
485 // Keep a copy at this point, we may need to look for a deprecated method.
486 $deprecatedmethod = "render_{$classname}";
488 // Remove _renderable suffixes.
489 $classname = preg_replace('/_renderable$/', '', $classname);
490 $rendermethod = "render_{$classname}";
492 if (method_exists($this, $rendermethod)) {
493 // Call the render_[widget_name] function.
494 // Note: This has a higher priority than the named_templatable to allow the theme to override the template.
495 return $this->$rendermethod($widget);
498 if ($widget instanceof named_templatable) {
499 // This is a named templatable.
500 // Fetch the template name from the get_template_name function instead.
501 // Note: This has higher priority than the deprecated method which is not overridable by themes anyway.
502 return $this->render_from_template(
503 $widget->get_template_name($this),
504 $widget->export_for_template($this)
508 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
509 // This is exactly where we don't want to be.
510 // If you have arrived here you have a renderable component within your plugin that has the name
511 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
512 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
513 // and the _renderable suffix now gets removed when looking for a render method.
514 // You need to change your renderers render_blah_renderable to render_blah.
515 // Until you do this it will not be possible for a theme to override the renderer to override your method.
516 // Please do it ASAP.
517 static $debugged = [];
518 if (!isset($debugged[$deprecatedmethod])) {
519 debugging(sprintf(
520 'Deprecated call. Please rename your renderables render method from %s to %s.',
521 $deprecatedmethod,
522 $rendermethod
523 ), DEBUG_DEVELOPER);
524 $debugged[$deprecatedmethod] = true;
526 return $this->$deprecatedmethod($widget);
529 // Pass to core renderer if method not found here.
530 // Note: this is not a parent. This is _new_ renderer which respects the requested format, and output type.
531 return $this->output->render($widget);
535 * Magic method used to pass calls otherwise meant for the standard renderer
536 * to it to ensure we don't go causing unnecessary grief.
538 * @param string $method
539 * @param array $arguments
540 * @return mixed
542 public function __call($method, $arguments) {
543 if (method_exists('renderer_base', $method)) {
544 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
546 if (method_exists($this->output, $method)) {
547 return call_user_func_array(array($this->output, $method), $arguments);
548 } else {
549 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
556 * The standard implementation of the core_renderer interface.
558 * @copyright 2009 Tim Hunt
559 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
560 * @since Moodle 2.0
561 * @package core
562 * @category output
564 class core_renderer extends renderer_base {
566 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
567 * in layout files instead.
568 * @deprecated
569 * @var string used in {@link core_renderer::header()}.
571 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
574 * @var string Used to pass information from {@link core_renderer::doctype()} to
575 * {@link core_renderer::standard_head_html()}.
577 protected $contenttype;
580 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
581 * with {@link core_renderer::header()}.
583 protected $metarefreshtag = '';
586 * @var string Unique token for the closing HTML
588 protected $unique_end_html_token;
591 * @var string Unique token for performance information
593 protected $unique_performance_info_token;
596 * @var string Unique token for the main content.
598 protected $unique_main_content_token;
600 /** @var custom_menu_item language The language menu if created */
601 protected $language = null;
604 * Constructor
606 * @param moodle_page $page the page we are doing output for.
607 * @param string $target one of rendering target constants
609 public function __construct(moodle_page $page, $target) {
610 $this->opencontainers = $page->opencontainers;
611 $this->page = $page;
612 $this->target = $target;
614 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
615 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
616 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
620 * Get the DOCTYPE declaration that should be used with this page. Designed to
621 * be called in theme layout.php files.
623 * @return string the DOCTYPE declaration that should be used.
625 public function doctype() {
626 if ($this->page->theme->doctype === 'html5') {
627 $this->contenttype = 'text/html; charset=utf-8';
628 return "<!DOCTYPE html>\n";
630 } else if ($this->page->theme->doctype === 'xhtml5') {
631 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
632 return "<!DOCTYPE html>\n";
634 } else {
635 // legacy xhtml 1.0
636 $this->contenttype = 'text/html; charset=utf-8';
637 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
642 * The attributes that should be added to the <html> tag. Designed to
643 * be called in theme layout.php files.
645 * @return string HTML fragment.
647 public function htmlattributes() {
648 $return = get_html_lang(true);
649 $attributes = array();
650 if ($this->page->theme->doctype !== 'html5') {
651 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
654 // Give plugins an opportunity to add things like xml namespaces to the html element.
655 // This function should return an array of html attribute names => values.
656 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
657 foreach ($pluginswithfunction as $plugins) {
658 foreach ($plugins as $function) {
659 $newattrs = $function();
660 unset($newattrs['dir']);
661 unset($newattrs['lang']);
662 unset($newattrs['xmlns']);
663 unset($newattrs['xml:lang']);
664 $attributes += $newattrs;
668 foreach ($attributes as $key => $val) {
669 $val = s($val);
670 $return .= " $key=\"$val\"";
673 return $return;
677 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
678 * that should be included in the <head> tag. Designed to be called in theme
679 * layout.php files.
681 * @return string HTML fragment.
683 public function standard_head_html() {
684 global $CFG, $SESSION, $SITE;
686 // Before we output any content, we need to ensure that certain
687 // page components are set up.
689 // Blocks must be set up early as they may require javascript which
690 // has to be included in the page header before output is created.
691 foreach ($this->page->blocks->get_regions() as $region) {
692 $this->page->blocks->ensure_content_created($region, $this);
695 $output = '';
697 // Give plugins an opportunity to add any head elements. The callback
698 // must always return a string containing valid html head content.
699 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
700 foreach ($pluginswithfunction as $plugins) {
701 foreach ($plugins as $function) {
702 $output .= $function();
706 // Allow a url_rewrite plugin to setup any dynamic head content.
707 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
708 $class = $CFG->urlrewriteclass;
709 $output .= $class::html_head_setup();
712 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
713 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
714 // This is only set by the {@link redirect()} method
715 $output .= $this->metarefreshtag;
717 // Check if a periodic refresh delay has been set and make sure we arn't
718 // already meta refreshing
719 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
720 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
723 // Set up help link popups for all links with the helptooltip class
724 $this->page->requires->js_init_call('M.util.help_popups.setup');
726 $focus = $this->page->focuscontrol;
727 if (!empty($focus)) {
728 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
729 // This is a horrifically bad way to handle focus but it is passed in
730 // through messy formslib::moodleform
731 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
732 } else if (strpos($focus, '.')!==false) {
733 // Old style of focus, bad way to do it
734 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);
735 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
736 } else {
737 // Focus element with given id
738 $this->page->requires->js_function_call('focuscontrol', array($focus));
742 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
743 // any other custom CSS can not be overridden via themes and is highly discouraged
744 $urls = $this->page->theme->css_urls($this->page);
745 foreach ($urls as $url) {
746 $this->page->requires->css_theme($url);
749 // Get the theme javascript head and footer
750 if ($jsurl = $this->page->theme->javascript_url(true)) {
751 $this->page->requires->js($jsurl, true);
753 if ($jsurl = $this->page->theme->javascript_url(false)) {
754 $this->page->requires->js($jsurl);
757 // Get any HTML from the page_requirements_manager.
758 $output .= $this->page->requires->get_head_code($this->page, $this);
760 // List alternate versions.
761 foreach ($this->page->alternateversions as $type => $alt) {
762 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
763 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
766 // Add noindex tag if relevant page and setting applied.
767 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
768 $loginpages = array('login-index', 'login-signup');
769 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
770 if (!isset($CFG->additionalhtmlhead)) {
771 $CFG->additionalhtmlhead = '';
773 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
776 if (!empty($CFG->additionalhtmlhead)) {
777 $output .= "\n".$CFG->additionalhtmlhead;
780 if ($this->page->pagelayout == 'frontpage') {
781 $summary = s(strip_tags(format_text($SITE->summary, FORMAT_HTML)));
782 if (!empty($summary)) {
783 $output .= "<meta name=\"description\" content=\"$summary\" />\n";
787 return $output;
791 * The standard tags (typically skip links) that should be output just inside
792 * the start of the <body> tag. Designed to be called in theme layout.php files.
794 * @return string HTML fragment.
796 public function standard_top_of_body_html() {
797 global $CFG;
798 $output = $this->page->requires->get_top_of_body_code($this);
799 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
800 $output .= "\n".$CFG->additionalhtmltopofbody;
803 // Give subsystems an opportunity to inject extra html content. The callback
804 // must always return a string containing valid html.
805 foreach (\core_component::get_core_subsystems() as $name => $path) {
806 if ($path) {
807 $output .= component_callback($name, 'before_standard_top_of_body_html', [], '');
811 // Give plugins an opportunity to inject extra html content. The callback
812 // must always return a string containing valid html.
813 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
814 foreach ($pluginswithfunction as $plugins) {
815 foreach ($plugins as $function) {
816 $output .= $function();
820 $output .= $this->maintenance_warning();
822 return $output;
826 * Scheduled maintenance warning message.
828 * Note: This is a nasty hack to display maintenance notice, this should be moved
829 * to some general notification area once we have it.
831 * @return string
833 public function maintenance_warning() {
834 global $CFG;
836 $output = '';
837 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
838 $timeleft = $CFG->maintenance_later - time();
839 // If timeleft less than 30 sec, set the class on block to error to highlight.
840 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
841 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-3 alert');
842 $a = new stdClass();
843 $a->hour = (int)($timeleft / 3600);
844 $a->min = (int)(($timeleft / 60) % 60);
845 $a->sec = (int)($timeleft % 60);
846 if ($a->hour > 0) {
847 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
848 } else {
849 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
852 $output .= $this->box_end();
853 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
854 array(array('timeleftinsec' => $timeleft)));
855 $this->page->requires->strings_for_js(
856 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
857 'admin');
859 return $output;
863 * content that should be output in the footer area
864 * of the page. Designed to be called in theme layout.php files.
866 * @return string HTML fragment.
868 public function standard_footer_html() {
869 global $CFG;
871 $output = '';
872 if (during_initial_install()) {
873 // Debugging info can not work before install is finished,
874 // in any case we do not want any links during installation!
875 return $output;
878 // Give plugins an opportunity to add any footer elements.
879 // The callback must always return a string containing valid html footer content.
880 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
881 foreach ($pluginswithfunction as $plugins) {
882 foreach ($plugins as $function) {
883 $output .= $function();
887 if (core_userfeedback::can_give_feedback()) {
888 $output .= html_writer::div(
889 $this->render_from_template('core/userfeedback_footer_link', ['url' => core_userfeedback::make_link()->out(false)])
893 if ($this->page->devicetypeinuse == 'legacy') {
894 // The legacy theme is in use print the notification
895 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
898 // Get links to switch device types (only shown for users not on a default device)
899 $output .= $this->theme_switch_links();
901 return $output;
905 * Performance information and validation links for debugging.
907 * @return string HTML fragment.
909 public function debug_footer_html() {
910 global $CFG, $SCRIPT;
911 $output = '';
913 if (during_initial_install()) {
914 // Debugging info can not work before install is finished.
915 return $output;
918 // This function is normally called from a layout.php file
919 // but some of the content won't be known until later, so we return a placeholder
920 // for now. This will be replaced with the real content in the footer.
921 $output .= $this->unique_performance_info_token;
923 if (!empty($CFG->debugpageinfo)) {
924 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
925 $this->page->debug_summary()) . '</div>';
927 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
929 // Add link to profiling report if necessary
930 if (function_exists('profiling_is_running') && profiling_is_running()) {
931 $txt = get_string('profiledscript', 'admin');
932 $title = get_string('profiledscriptview', 'admin');
933 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
934 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
935 $output .= '<div class="profilingfooter">' . $link . '</div>';
937 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
938 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
939 $output .= '<div class="purgecaches">' .
940 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
942 // Reactive module debug panel.
943 $output .= $this->render_from_template('core/local/reactive/debugpanel', []);
945 if (!empty($CFG->debugvalidators)) {
946 $siteurl = qualified_me();
947 $nuurl = new moodle_url('https://validator.w3.org/nu/', ['doc' => $siteurl, 'showsource' => 'yes']);
948 $waveurl = new moodle_url('https://wave.webaim.org/report#/' . urlencode($siteurl));
949 $validatorlinks = [
950 html_writer::link($nuurl, get_string('validatehtml')),
951 html_writer::link($waveurl, get_string('wcagcheck'))
953 $validatorlinkslist = html_writer::alist($validatorlinks, ['class' => 'list-unstyled ml-1']);
954 $output .= html_writer::div($validatorlinkslist, 'validators');
956 return $output;
960 * Returns standard main content placeholder.
961 * Designed to be called in theme layout.php files.
963 * @return string HTML fragment.
965 public function main_content() {
966 // This is here because it is the only place we can inject the "main" role over the entire main content area
967 // without requiring all theme's to manually do it, and without creating yet another thing people need to
968 // remember in the theme.
969 // This is an unfortunate hack. DO NO EVER add anything more here.
970 // DO NOT add classes.
971 // DO NOT add an id.
972 return '<div role="main">'.$this->unique_main_content_token.'</div>';
976 * Returns information about an activity.
978 * @param cm_info $cminfo The course module information.
979 * @param cm_completion_details $completiondetails The completion details for this activity module.
980 * @param array $activitydates The dates for this activity module.
981 * @return string the activity information HTML.
982 * @throws coding_exception
984 public function activity_information(cm_info $cminfo, cm_completion_details $completiondetails, array $activitydates): string {
985 if (!$completiondetails->has_completion() && empty($activitydates)) {
986 // No need to render the activity information when there's no completion info and activity dates to show.
987 return '';
989 $activityinfo = new activity_information($cminfo, $completiondetails, $activitydates);
990 $renderer = $this->page->get_renderer('core', 'course');
991 return $renderer->render($activityinfo);
995 * Returns standard navigation between activities in a course.
997 * @return string the navigation HTML.
999 public function activity_navigation() {
1000 // First we should check if we want to add navigation.
1001 $context = $this->page->context;
1002 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
1003 || $context->contextlevel != CONTEXT_MODULE) {
1004 return '';
1007 // If the activity is in stealth mode, show no links.
1008 if ($this->page->cm->is_stealth()) {
1009 return '';
1012 $course = $this->page->cm->get_course();
1013 $courseformat = course_get_format($course);
1015 // If the theme implements course index and the current course format uses course index and the current
1016 // page layout is not 'frametop' (this layout does not support course index), show no links.
1017 if ($this->page->theme->usescourseindex && $courseformat->uses_course_index() &&
1018 $this->page->pagelayout !== 'frametop') {
1019 return '';
1022 // Get a list of all the activities in the course.
1023 $modules = get_fast_modinfo($course->id)->get_cms();
1025 // Put the modules into an array in order by the position they are shown in the course.
1026 $mods = [];
1027 $activitylist = [];
1028 foreach ($modules as $module) {
1029 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
1030 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
1031 continue;
1033 $mods[$module->id] = $module;
1035 // No need to add the current module to the list for the activity dropdown menu.
1036 if ($module->id == $this->page->cm->id) {
1037 continue;
1039 // Module name.
1040 $modname = $module->get_formatted_name();
1041 // Display the hidden text if necessary.
1042 if (!$module->visible) {
1043 $modname .= ' ' . get_string('hiddenwithbrackets');
1045 // Module URL.
1046 $linkurl = new moodle_url($module->url, array('forceview' => 1));
1047 // Add module URL (as key) and name (as value) to the activity list array.
1048 $activitylist[$linkurl->out(false)] = $modname;
1051 $nummods = count($mods);
1053 // If there is only one mod then do nothing.
1054 if ($nummods == 1) {
1055 return '';
1058 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
1059 $modids = array_keys($mods);
1061 // Get the position in the array of the course module we are viewing.
1062 $position = array_search($this->page->cm->id, $modids);
1064 $prevmod = null;
1065 $nextmod = null;
1067 // Check if we have a previous mod to show.
1068 if ($position > 0) {
1069 $prevmod = $mods[$modids[$position - 1]];
1072 // Check if we have a next mod to show.
1073 if ($position < ($nummods - 1)) {
1074 $nextmod = $mods[$modids[$position + 1]];
1077 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
1078 $renderer = $this->page->get_renderer('core', 'course');
1079 return $renderer->render($activitynav);
1083 * The standard tags (typically script tags that are not needed earlier) that
1084 * should be output after everything else. Designed to be called in theme layout.php files.
1086 * @return string HTML fragment.
1088 public function standard_end_of_body_html() {
1089 global $CFG;
1091 // This function is normally called from a layout.php file in {@link core_renderer::header()}
1092 // but some of the content won't be known until later, so we return a placeholder
1093 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
1094 $output = '';
1095 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
1096 $output .= "\n".$CFG->additionalhtmlfooter;
1098 $output .= $this->unique_end_html_token;
1099 return $output;
1103 * The standard HTML that should be output just before the <footer> tag.
1104 * Designed to be called in theme layout.php files.
1106 * @return string HTML fragment.
1108 public function standard_after_main_region_html() {
1109 global $CFG;
1110 $output = '';
1111 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlbottomofbody)) {
1112 $output .= "\n".$CFG->additionalhtmlbottomofbody;
1115 // Give subsystems an opportunity to inject extra html content. The callback
1116 // must always return a string containing valid html.
1117 foreach (\core_component::get_core_subsystems() as $name => $path) {
1118 if ($path) {
1119 $output .= component_callback($name, 'standard_after_main_region_html', [], '');
1123 // Give plugins an opportunity to inject extra html content. The callback
1124 // must always return a string containing valid html.
1125 $pluginswithfunction = get_plugins_with_function('standard_after_main_region_html', 'lib.php');
1126 foreach ($pluginswithfunction as $plugins) {
1127 foreach ($plugins as $function) {
1128 $output .= $function();
1132 return $output;
1136 * Return the standard string that says whether you are logged in (and switched
1137 * roles/logged in as another user).
1138 * @param bool $withlinks if false, then don't include any links in the HTML produced.
1139 * If not set, the default is the nologinlinks option from the theme config.php file,
1140 * and if that is not set, then links are included.
1141 * @return string HTML fragment.
1143 public function login_info($withlinks = null) {
1144 global $USER, $CFG, $DB, $SESSION;
1146 if (during_initial_install()) {
1147 return '';
1150 if (is_null($withlinks)) {
1151 $withlinks = empty($this->page->layout_options['nologinlinks']);
1154 $course = $this->page->course;
1155 if (\core\session\manager::is_loggedinas()) {
1156 $realuser = \core\session\manager::get_realuser();
1157 $fullname = fullname($realuser);
1158 if ($withlinks) {
1159 $loginastitle = get_string('loginas');
1160 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
1161 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
1162 } else {
1163 $realuserinfo = " [$fullname] ";
1165 } else {
1166 $realuserinfo = '';
1169 $loginpage = $this->is_login_page();
1170 $loginurl = get_login_url();
1172 if (empty($course->id)) {
1173 // $course->id is not defined during installation
1174 return '';
1175 } else if (isloggedin()) {
1176 $context = context_course::instance($course->id);
1178 $fullname = fullname($USER);
1179 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
1180 if ($withlinks) {
1181 $linktitle = get_string('viewprofile');
1182 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
1183 } else {
1184 $username = $fullname;
1186 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
1187 if ($withlinks) {
1188 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1189 } else {
1190 $username .= " from {$idprovider->name}";
1193 if (isguestuser()) {
1194 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1195 if (!$loginpage && $withlinks) {
1196 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1198 } else if (is_role_switched($course->id)) { // Has switched roles
1199 $rolename = '';
1200 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1201 $rolename = ': '.role_get_name($role, $context);
1203 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1204 if ($withlinks) {
1205 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1206 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1208 } else {
1209 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1210 if ($withlinks) {
1211 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1214 } else {
1215 $loggedinas = get_string('loggedinnot', 'moodle');
1216 if (!$loginpage && $withlinks) {
1217 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1221 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1223 if (isset($SESSION->justloggedin)) {
1224 unset($SESSION->justloggedin);
1225 if (!isguestuser()) {
1226 // Include this file only when required.
1227 require_once($CFG->dirroot . '/user/lib.php');
1228 if (($count = user_count_login_failures($USER)) && !empty($CFG->displayloginfailures)) {
1229 $loggedinas .= '<div class="loginfailures">';
1230 $a = new stdClass();
1231 $a->attempts = $count;
1232 $loggedinas .= get_string('failedloginattempts', '', $a);
1233 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1234 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1235 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1237 $loggedinas .= '</div>';
1242 return $loggedinas;
1246 * Check whether the current page is a login page.
1248 * @since Moodle 2.9
1249 * @return bool
1251 protected function is_login_page() {
1252 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1253 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1254 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1255 return in_array(
1256 $this->page->url->out_as_local_url(false, array()),
1257 array(
1258 '/login/index.php',
1259 '/login/forgot_password.php',
1265 * Return the 'back' link that normally appears in the footer.
1267 * @return string HTML fragment.
1269 public function home_link() {
1270 global $CFG, $SITE;
1272 if ($this->page->pagetype == 'site-index') {
1273 // Special case for site home page - please do not remove
1274 return '<div class="sitelink">' .
1275 '<a title="Moodle" class="d-inline-block aalink" href="http://moodle.org/">' .
1276 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1278 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1279 // Special case for during install/upgrade.
1280 return '<div class="sitelink">'.
1281 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1282 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1284 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1285 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1286 get_string('home') . '</a></div>';
1288 } else {
1289 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1290 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1295 * Redirects the user by any means possible given the current state
1297 * This function should not be called directly, it should always be called using
1298 * the redirect function in lib/weblib.php
1300 * The redirect function should really only be called before page output has started
1301 * however it will allow itself to be called during the state STATE_IN_BODY
1303 * @param string $encodedurl The URL to send to encoded if required
1304 * @param string $message The message to display to the user if any
1305 * @param int $delay The delay before redirecting a user, if $message has been
1306 * set this is a requirement and defaults to 3, set to 0 no delay
1307 * @param boolean $debugdisableredirect this redirect has been disabled for
1308 * debugging purposes. Display a message that explains, and don't
1309 * trigger the redirect.
1310 * @param string $messagetype The type of notification to show the message in.
1311 * See constants on \core\output\notification.
1312 * @return string The HTML to display to the user before dying, may contain
1313 * meta refresh, javascript refresh, and may have set header redirects
1315 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1316 $messagetype = \core\output\notification::NOTIFY_INFO) {
1317 global $CFG;
1318 $url = str_replace('&amp;', '&', $encodedurl);
1320 switch ($this->page->state) {
1321 case moodle_page::STATE_BEFORE_HEADER :
1322 // No output yet it is safe to delivery the full arsenal of redirect methods
1323 if (!$debugdisableredirect) {
1324 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1325 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1326 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1328 $output = $this->header();
1329 break;
1330 case moodle_page::STATE_PRINTING_HEADER :
1331 // We should hopefully never get here
1332 throw new coding_exception('You cannot redirect while printing the page header');
1333 break;
1334 case moodle_page::STATE_IN_BODY :
1335 // We really shouldn't be here but we can deal with this
1336 debugging("You should really redirect before you start page output");
1337 if (!$debugdisableredirect) {
1338 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1340 $output = $this->opencontainers->pop_all_but_last();
1341 break;
1342 case moodle_page::STATE_DONE :
1343 // Too late to be calling redirect now
1344 throw new coding_exception('You cannot redirect after the entire page has been generated');
1345 break;
1347 $output .= $this->notification($message, $messagetype);
1348 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1349 if ($debugdisableredirect) {
1350 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1352 $output .= $this->footer();
1353 return $output;
1357 * Start output by sending the HTTP headers, and printing the HTML <head>
1358 * and the start of the <body>.
1360 * To control what is printed, you should set properties on $PAGE.
1362 * @return string HTML that you must output this, preferably immediately.
1364 public function header() {
1365 global $USER, $CFG, $SESSION;
1367 // Give plugins an opportunity touch things before the http headers are sent
1368 // such as adding additional headers. The return value is ignored.
1369 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1370 foreach ($pluginswithfunction as $plugins) {
1371 foreach ($plugins as $function) {
1372 $function();
1376 if (\core\session\manager::is_loggedinas()) {
1377 $this->page->add_body_class('userloggedinas');
1380 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1381 require_once($CFG->dirroot . '/user/lib.php');
1382 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1383 if ($count = user_count_login_failures($USER, false)) {
1384 $this->page->add_body_class('loginfailures');
1388 // If the user is logged in, and we're not in initial install,
1389 // check to see if the user is role-switched and add the appropriate
1390 // CSS class to the body element.
1391 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1392 $this->page->add_body_class('userswitchedrole');
1395 // Give themes a chance to init/alter the page object.
1396 $this->page->theme->init_page($this->page);
1398 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1400 // Find the appropriate page layout file, based on $this->page->pagelayout.
1401 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1402 // Render the layout using the layout file.
1403 $rendered = $this->render_page_layout($layoutfile);
1405 // Slice the rendered output into header and footer.
1406 $cutpos = strpos($rendered, $this->unique_main_content_token);
1407 if ($cutpos === false) {
1408 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1409 $token = self::MAIN_CONTENT_TOKEN;
1410 } else {
1411 $token = $this->unique_main_content_token;
1414 if ($cutpos === false) {
1415 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.');
1417 $header = substr($rendered, 0, $cutpos);
1418 $footer = substr($rendered, $cutpos + strlen($token));
1420 if (empty($this->contenttype)) {
1421 debugging('The page layout file did not call $OUTPUT->doctype()');
1422 $header = $this->doctype() . $header;
1425 // If this theme version is below 2.4 release and this is a course view page
1426 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1427 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1428 // check if course content header/footer have not been output during render of theme layout
1429 $coursecontentheader = $this->course_content_header(true);
1430 $coursecontentfooter = $this->course_content_footer(true);
1431 if (!empty($coursecontentheader)) {
1432 // display debug message and add header and footer right above and below main content
1433 // Please note that course header and footer (to be displayed above and below the whole page)
1434 // are not displayed in this case at all.
1435 // Besides the content header and footer are not displayed on any other course page
1436 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);
1437 $header .= $coursecontentheader;
1438 $footer = $coursecontentfooter. $footer;
1442 send_headers($this->contenttype, $this->page->cacheable);
1444 $this->opencontainers->push('header/footer', $footer);
1445 $this->page->set_state(moodle_page::STATE_IN_BODY);
1447 // If an activity record has been set, activity_header will handle this.
1448 if (!$this->page->cm || !empty($this->page->layout_options['noactivityheader'])) {
1449 $header .= $this->skip_link_target('maincontent');
1451 return $header;
1455 * Renders and outputs the page layout file.
1457 * This is done by preparing the normal globals available to a script, and
1458 * then including the layout file provided by the current theme for the
1459 * requested layout.
1461 * @param string $layoutfile The name of the layout file
1462 * @return string HTML code
1464 protected function render_page_layout($layoutfile) {
1465 global $CFG, $SITE, $USER;
1466 // The next lines are a bit tricky. The point is, here we are in a method
1467 // of a renderer class, and this object may, or may not, be the same as
1468 // the global $OUTPUT object. When rendering the page layout file, we want to use
1469 // this object. However, people writing Moodle code expect the current
1470 // renderer to be called $OUTPUT, not $this, so define a variable called
1471 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1472 $OUTPUT = $this;
1473 $PAGE = $this->page;
1474 $COURSE = $this->page->course;
1476 ob_start();
1477 include($layoutfile);
1478 $rendered = ob_get_contents();
1479 ob_end_clean();
1480 return $rendered;
1484 * Outputs the page's footer
1486 * @return string HTML fragment
1488 public function footer() {
1489 global $CFG, $DB;
1491 $output = '';
1493 // Give plugins an opportunity to touch the page before JS is finalized.
1494 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1495 foreach ($pluginswithfunction as $plugins) {
1496 foreach ($plugins as $function) {
1497 $extrafooter = $function();
1498 if (is_string($extrafooter)) {
1499 $output .= $extrafooter;
1504 $output .= $this->container_end_all(true);
1506 $footer = $this->opencontainers->pop('header/footer');
1508 if (debugging() and $DB and $DB->is_transaction_started()) {
1509 // TODO: MDL-20625 print warning - transaction will be rolled back
1512 // Provide some performance info if required
1513 $performanceinfo = '';
1514 if ((defined('MDL_PERF') && MDL_PERF) || (!empty($CFG->perfdebug) && $CFG->perfdebug > 7)) {
1515 $perf = get_performance_info();
1516 if ((defined('MDL_PERFTOFOOT') && MDL_PERFTOFOOT) || debugging() || $CFG->perfdebug > 7) {
1517 $performanceinfo = $perf['html'];
1521 // We always want performance data when running a performance test, even if the user is redirected to another page.
1522 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1523 $footer = $this->unique_performance_info_token . $footer;
1525 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1527 // Only show notifications when the current page has a context id.
1528 if (!empty($this->page->context->id)) {
1529 $this->page->requires->js_call_amd('core/notification', 'init', array(
1530 $this->page->context->id,
1531 \core\notification::fetch_as_array($this)
1534 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1536 $this->page->set_state(moodle_page::STATE_DONE);
1538 return $output . $footer;
1542 * Close all but the last open container. This is useful in places like error
1543 * handling, where you want to close all the open containers (apart from <body>)
1544 * before outputting the error message.
1546 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1547 * developer debug warning if it isn't.
1548 * @return string the HTML required to close any open containers inside <body>.
1550 public function container_end_all($shouldbenone = false) {
1551 return $this->opencontainers->pop_all_but_last($shouldbenone);
1555 * Returns course-specific information to be output immediately above content on any course page
1556 * (for the current course)
1558 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1559 * @return string
1561 public function course_content_header($onlyifnotcalledbefore = false) {
1562 global $CFG;
1563 static $functioncalled = false;
1564 if ($functioncalled && $onlyifnotcalledbefore) {
1565 // we have already output the content header
1566 return '';
1569 // Output any session notification.
1570 $notifications = \core\notification::fetch();
1572 $bodynotifications = '';
1573 foreach ($notifications as $notification) {
1574 $bodynotifications .= $this->render_from_template(
1575 $notification->get_template_name(),
1576 $notification->export_for_template($this)
1580 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1582 if ($this->page->course->id == SITEID) {
1583 // return immediately and do not include /course/lib.php if not necessary
1584 return $output;
1587 require_once($CFG->dirroot.'/course/lib.php');
1588 $functioncalled = true;
1589 $courseformat = course_get_format($this->page->course);
1590 if (($obj = $courseformat->course_content_header()) !== null) {
1591 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1593 return $output;
1597 * Returns course-specific information to be output immediately below content on any course page
1598 * (for the current course)
1600 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1601 * @return string
1603 public function course_content_footer($onlyifnotcalledbefore = false) {
1604 global $CFG;
1605 if ($this->page->course->id == SITEID) {
1606 // return immediately and do not include /course/lib.php if not necessary
1607 return '';
1609 static $functioncalled = false;
1610 if ($functioncalled && $onlyifnotcalledbefore) {
1611 // we have already output the content footer
1612 return '';
1614 $functioncalled = true;
1615 require_once($CFG->dirroot.'/course/lib.php');
1616 $courseformat = course_get_format($this->page->course);
1617 if (($obj = $courseformat->course_content_footer()) !== null) {
1618 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1620 return '';
1624 * Returns course-specific information to be output on any course page in the header area
1625 * (for the current course)
1627 * @return string
1629 public function course_header() {
1630 global $CFG;
1631 if ($this->page->course->id == SITEID) {
1632 // return immediately and do not include /course/lib.php if not necessary
1633 return '';
1635 require_once($CFG->dirroot.'/course/lib.php');
1636 $courseformat = course_get_format($this->page->course);
1637 if (($obj = $courseformat->course_header()) !== null) {
1638 return $courseformat->get_renderer($this->page)->render($obj);
1640 return '';
1644 * Returns course-specific information to be output on any course page in the footer area
1645 * (for the current course)
1647 * @return string
1649 public function course_footer() {
1650 global $CFG;
1651 if ($this->page->course->id == SITEID) {
1652 // return immediately and do not include /course/lib.php if not necessary
1653 return '';
1655 require_once($CFG->dirroot.'/course/lib.php');
1656 $courseformat = course_get_format($this->page->course);
1657 if (($obj = $courseformat->course_footer()) !== null) {
1658 return $courseformat->get_renderer($this->page)->render($obj);
1660 return '';
1664 * Get the course pattern datauri to show on a course card.
1666 * The datauri is an encoded svg that can be passed as a url.
1667 * @param int $id Id to use when generating the pattern
1668 * @return string datauri
1670 public function get_generated_image_for_id($id) {
1671 $color = $this->get_generated_color_for_id($id);
1672 $pattern = new \core_geopattern();
1673 $pattern->setColor($color);
1674 $pattern->patternbyid($id);
1675 return $pattern->datauri();
1679 * Get the course color to show on a course card.
1681 * @param int $id Id to use when generating the color.
1682 * @return string hex color code.
1684 public function get_generated_color_for_id($id) {
1685 $colornumbers = range(1, 10);
1686 $basecolors = [];
1687 foreach ($colornumbers as $number) {
1688 $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1691 $color = $basecolors[$id % 10];
1692 return $color;
1696 * Returns lang menu or '', this method also checks forcing of languages in courses.
1698 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1700 * @return string The lang menu HTML or empty string
1702 public function lang_menu() {
1703 $languagemenu = new \core\output\language_menu($this->page);
1704 $data = $languagemenu->export_for_single_select($this);
1705 if ($data) {
1706 return $this->render_from_template('core/single_select', $data);
1708 return '';
1712 * Output the row of editing icons for a block, as defined by the controls array.
1714 * @param array $controls an array like {@link block_contents::$controls}.
1715 * @param string $blockid The ID given to the block.
1716 * @return string HTML fragment.
1718 public function block_controls($actions, $blockid = null) {
1719 global $CFG;
1720 if (empty($actions)) {
1721 return '';
1723 $menu = new action_menu($actions);
1724 if ($blockid !== null) {
1725 $menu->set_owner_selector('#'.$blockid);
1727 $menu->set_constraint('.block-region');
1728 $menu->attributes['class'] .= ' block-control-actions commands';
1729 return $this->render($menu);
1733 * Returns the HTML for a basic textarea field.
1735 * @param string $name Name to use for the textarea element
1736 * @param string $id The id to use fort he textarea element
1737 * @param string $value Initial content to display in the textarea
1738 * @param int $rows Number of rows to display
1739 * @param int $cols Number of columns to display
1740 * @return string the HTML to display
1742 public function print_textarea($name, $id, $value, $rows, $cols) {
1743 editors_head_setup();
1744 $editor = editors_get_preferred_editor(FORMAT_HTML);
1745 $editor->set_text($value);
1746 $editor->use_editor($id, []);
1748 $context = [
1749 'id' => $id,
1750 'name' => $name,
1751 'value' => $value,
1752 'rows' => $rows,
1753 'cols' => $cols
1756 return $this->render_from_template('core_form/editor_textarea', $context);
1760 * Renders an action menu component.
1762 * @param action_menu $menu
1763 * @return string HTML
1765 public function render_action_menu(action_menu $menu) {
1767 // We don't want the class icon there!
1768 foreach ($menu->get_secondary_actions() as $action) {
1769 if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1770 $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1774 if ($menu->is_empty()) {
1775 return '';
1777 $context = $menu->export_for_template($this);
1779 return $this->render_from_template('core/action_menu', $context);
1783 * Renders a Check API result
1785 * @param result $result
1786 * @return string HTML fragment
1788 protected function render_check_result(core\check\result $result) {
1789 return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1793 * Renders a Check API result
1795 * @param result $result
1796 * @return string HTML fragment
1798 public function check_result(core\check\result $result) {
1799 return $this->render_check_result($result);
1803 * Renders an action_menu_link item.
1805 * @param action_menu_link $action
1806 * @return string HTML fragment
1808 protected function render_action_menu_link(action_menu_link $action) {
1809 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1813 * Renders a primary action_menu_filler item.
1815 * @param action_menu_link_filler $action
1816 * @return string HTML fragment
1818 protected function render_action_menu_filler(action_menu_filler $action) {
1819 return html_writer::span('&nbsp;', 'filler');
1823 * Renders a primary action_menu_link item.
1825 * @param action_menu_link_primary $action
1826 * @return string HTML fragment
1828 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1829 return $this->render_action_menu_link($action);
1833 * Renders a secondary action_menu_link item.
1835 * @param action_menu_link_secondary $action
1836 * @return string HTML fragment
1838 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1839 return $this->render_action_menu_link($action);
1843 * Prints a nice side block with an optional header.
1845 * @param block_contents $bc HTML for the content
1846 * @param string $region the region the block is appearing in.
1847 * @return string the HTML to be output.
1849 public function block(block_contents $bc, $region) {
1850 $bc = clone($bc); // Avoid messing up the object passed in.
1851 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1852 $bc->collapsible = block_contents::NOT_HIDEABLE;
1855 $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1856 $context = new stdClass();
1857 $context->skipid = $bc->skipid;
1858 $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
1859 $context->dockable = $bc->dockable;
1860 $context->id = $id;
1861 $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1862 $context->skiptitle = strip_tags($bc->title);
1863 $context->showskiplink = !empty($context->skiptitle);
1864 $context->arialabel = $bc->arialabel;
1865 $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
1866 $context->class = $bc->attributes['class'];
1867 $context->type = $bc->attributes['data-block'];
1868 $context->title = $bc->title;
1869 $context->content = $bc->content;
1870 $context->annotation = $bc->annotation;
1871 $context->footer = $bc->footer;
1872 $context->hascontrols = !empty($bc->controls);
1873 if ($context->hascontrols) {
1874 $context->controls = $this->block_controls($bc->controls, $id);
1877 return $this->render_from_template('core/block', $context);
1881 * Render the contents of a block_list.
1883 * @param array $icons the icon for each item.
1884 * @param array $items the content of each item.
1885 * @return string HTML
1887 public function list_block_contents($icons, $items) {
1888 $row = 0;
1889 $lis = array();
1890 foreach ($items as $key => $string) {
1891 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1892 if (!empty($icons[$key])) { //test if the content has an assigned icon
1893 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1895 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1896 $item .= html_writer::end_tag('li');
1897 $lis[] = $item;
1898 $row = 1 - $row; // Flip even/odd.
1900 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1904 * Output all the blocks in a particular region.
1906 * @param string $region the name of a region on this page.
1907 * @param boolean $fakeblocksonly Output fake block only.
1908 * @return string the HTML to be output.
1910 public function blocks_for_region($region, $fakeblocksonly = false) {
1911 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1912 $lastblock = null;
1913 $zones = array();
1914 foreach ($blockcontents as $bc) {
1915 if ($bc instanceof block_contents) {
1916 $zones[] = $bc->title;
1919 $output = '';
1921 foreach ($blockcontents as $bc) {
1922 if ($bc instanceof block_contents) {
1923 if ($fakeblocksonly && !$bc->is_fake()) {
1924 // Skip rendering real blocks if we only want to show fake blocks.
1925 continue;
1927 $output .= $this->block($bc, $region);
1928 $lastblock = $bc->title;
1929 } else if ($bc instanceof block_move_target) {
1930 if (!$fakeblocksonly) {
1931 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1933 } else {
1934 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1937 return $output;
1941 * Output a place where the block that is currently being moved can be dropped.
1943 * @param block_move_target $target with the necessary details.
1944 * @param array $zones array of areas where the block can be moved to
1945 * @param string $previous the block located before the area currently being rendered.
1946 * @param string $region the name of the region
1947 * @return string the HTML to be output.
1949 public function block_move_target($target, $zones, $previous, $region) {
1950 if ($previous == null) {
1951 if (empty($zones)) {
1952 // There are no zones, probably because there are no blocks.
1953 $regions = $this->page->theme->get_all_block_regions();
1954 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1955 } else {
1956 $position = get_string('moveblockbefore', 'block', $zones[0]);
1958 } else {
1959 $position = get_string('moveblockafter', 'block', $previous);
1961 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1965 * Renders a special html link with attached action
1967 * Theme developers: DO NOT OVERRIDE! Please override function
1968 * {@link core_renderer::render_action_link()} instead.
1970 * @param string|moodle_url $url
1971 * @param string $text HTML fragment
1972 * @param component_action $action
1973 * @param array $attributes associative array of html link attributes + disabled
1974 * @param pix_icon optional pix icon to render with the link
1975 * @return string HTML fragment
1977 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1978 if (!($url instanceof moodle_url)) {
1979 $url = new moodle_url($url);
1981 $link = new action_link($url, $text, $action, $attributes, $icon);
1983 return $this->render($link);
1987 * Renders an action_link object.
1989 * The provided link is renderer and the HTML returned. At the same time the
1990 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1992 * @param action_link $link
1993 * @return string HTML fragment
1995 protected function render_action_link(action_link $link) {
1996 return $this->render_from_template('core/action_link', $link->export_for_template($this));
2000 * Renders an action_icon.
2002 * This function uses the {@link core_renderer::action_link()} method for the
2003 * most part. What it does different is prepare the icon as HTML and use it
2004 * as the link text.
2006 * Theme developers: If you want to change how action links and/or icons are rendered,
2007 * consider overriding function {@link core_renderer::render_action_link()} and
2008 * {@link core_renderer::render_pix_icon()}.
2010 * @param string|moodle_url $url A string URL or moodel_url
2011 * @param pix_icon $pixicon
2012 * @param component_action $action
2013 * @param array $attributes associative array of html link attributes + disabled
2014 * @param bool $linktext show title next to image in link
2015 * @return string HTML fragment
2017 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
2018 if (!($url instanceof moodle_url)) {
2019 $url = new moodle_url($url);
2021 $attributes = (array)$attributes;
2023 if (empty($attributes['class'])) {
2024 // let ppl override the class via $options
2025 $attributes['class'] = 'action-icon';
2028 $icon = $this->render($pixicon);
2030 if ($linktext) {
2031 $text = $pixicon->attributes['alt'];
2032 } else {
2033 $text = '';
2036 return $this->action_link($url, $text.$icon, $action, $attributes);
2040 * Print a message along with button choices for Continue/Cancel
2042 * If a string or moodle_url is given instead of a single_button, method defaults to post.
2044 * @param string $message The question to ask the user
2045 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
2046 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
2047 * @param array $displayoptions optional extra display options
2048 * @return string HTML fragment
2050 public function confirm($message, $continue, $cancel, array $displayoptions = []) {
2052 // Check existing displayoptions.
2053 $displayoptions['confirmtitle'] = $displayoptions['confirmtitle'] ?? get_string('confirm');
2054 $displayoptions['continuestr'] = $displayoptions['continuestr'] ?? get_string('continue');
2055 $displayoptions['cancelstr'] = $displayoptions['cancelstr'] ?? get_string('cancel');
2057 if ($continue instanceof single_button) {
2058 // Continue button should be primary if set to secondary type as it is the fefault.
2059 if ($continue->type === single_button::BUTTON_SECONDARY) {
2060 $continue->type = single_button::BUTTON_PRIMARY;
2062 } else if (is_string($continue)) {
2063 $continue = new single_button(new moodle_url($continue), $displayoptions['continuestr'], 'post',
2064 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
2065 } else if ($continue instanceof moodle_url) {
2066 $continue = new single_button($continue, $displayoptions['continuestr'], 'post',
2067 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
2068 } else {
2069 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2072 if ($cancel instanceof single_button) {
2073 // ok
2074 } else if (is_string($cancel)) {
2075 $cancel = new single_button(new moodle_url($cancel), $displayoptions['cancelstr'], 'get');
2076 } else if ($cancel instanceof moodle_url) {
2077 $cancel = new single_button($cancel, $displayoptions['cancelstr'], 'get');
2078 } else {
2079 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2082 $attributes = [
2083 'role'=>'alertdialog',
2084 'aria-labelledby'=>'modal-header',
2085 'aria-describedby'=>'modal-body',
2086 'aria-modal'=>'true'
2089 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
2090 $output .= $this->box_start('modal-content', 'modal-content');
2091 $output .= $this->box_start('modal-header px-3', 'modal-header');
2092 $output .= html_writer::tag('h4', $displayoptions['confirmtitle']);
2093 $output .= $this->box_end();
2094 $attributes = [
2095 'role'=>'alert',
2096 'data-aria-autofocus'=>'true'
2098 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
2099 $output .= html_writer::tag('p', $message);
2100 $output .= $this->box_end();
2101 $output .= $this->box_start('modal-footer', 'modal-footer');
2102 $output .= html_writer::tag('div', $this->render($cancel) . $this->render($continue), ['class' => 'buttons']);
2103 $output .= $this->box_end();
2104 $output .= $this->box_end();
2105 $output .= $this->box_end();
2106 return $output;
2110 * Returns a form with a single button.
2112 * Theme developers: DO NOT OVERRIDE! Please override function
2113 * {@link core_renderer::render_single_button()} instead.
2115 * @param string|moodle_url $url
2116 * @param string $label button text
2117 * @param string $method get or post submit method
2118 * @param array $options associative array {disabled, title, etc.}
2119 * @return string HTML fragment
2121 public function single_button($url, $label, $method='post', array $options=null) {
2122 if (!($url instanceof moodle_url)) {
2123 $url = new moodle_url($url);
2125 $button = new single_button($url, $label, $method);
2127 foreach ((array)$options as $key=>$value) {
2128 if (property_exists($button, $key)) {
2129 $button->$key = $value;
2130 } else {
2131 $button->set_attribute($key, $value);
2135 return $this->render($button);
2139 * Renders a single button widget.
2141 * This will return HTML to display a form containing a single button.
2143 * @param single_button $button
2144 * @return string HTML fragment
2146 protected function render_single_button(single_button $button) {
2147 return $this->render_from_template('core/single_button', $button->export_for_template($this));
2151 * Returns a form with a single select widget.
2153 * Theme developers: DO NOT OVERRIDE! Please override function
2154 * {@link core_renderer::render_single_select()} instead.
2156 * @param moodle_url $url form action target, includes hidden fields
2157 * @param string $name name of selection field - the changing parameter in url
2158 * @param array $options list of options
2159 * @param string $selected selected element
2160 * @param array $nothing
2161 * @param string $formid
2162 * @param array $attributes other attributes for the single select
2163 * @return string HTML fragment
2165 public function single_select($url, $name, array $options, $selected = '',
2166 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2167 if (!($url instanceof moodle_url)) {
2168 $url = new moodle_url($url);
2170 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2172 if (array_key_exists('label', $attributes)) {
2173 $select->set_label($attributes['label']);
2174 unset($attributes['label']);
2176 $select->attributes = $attributes;
2178 return $this->render($select);
2182 * Returns a dataformat selection and download form
2184 * @param string $label A text label
2185 * @param moodle_url|string $base The download page url
2186 * @param string $name The query param which will hold the type of the download
2187 * @param array $params Extra params sent to the download page
2188 * @return string HTML fragment
2190 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2192 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2193 $options = array();
2194 foreach ($formats as $format) {
2195 if ($format->is_enabled()) {
2196 $options[] = array(
2197 'value' => $format->name,
2198 'label' => get_string('dataformat', $format->component),
2202 $hiddenparams = array();
2203 foreach ($params as $key => $value) {
2204 $hiddenparams[] = array(
2205 'name' => $key,
2206 'value' => $value,
2209 $data = array(
2210 'label' => $label,
2211 'base' => $base,
2212 'name' => $name,
2213 'params' => $hiddenparams,
2214 'options' => $options,
2215 'sesskey' => sesskey(),
2216 'submit' => get_string('download'),
2219 return $this->render_from_template('core/dataformat_selector', $data);
2224 * Internal implementation of single_select rendering
2226 * @param single_select $select
2227 * @return string HTML fragment
2229 protected function render_single_select(single_select $select) {
2230 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2234 * Returns a form with a url select widget.
2236 * Theme developers: DO NOT OVERRIDE! Please override function
2237 * {@link core_renderer::render_url_select()} instead.
2239 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2240 * @param string $selected selected element
2241 * @param array $nothing
2242 * @param string $formid
2243 * @return string HTML fragment
2245 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2246 $select = new url_select($urls, $selected, $nothing, $formid);
2247 return $this->render($select);
2251 * Internal implementation of url_select rendering
2253 * @param url_select $select
2254 * @return string HTML fragment
2256 protected function render_url_select(url_select $select) {
2257 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2261 * Returns a string containing a link to the user documentation.
2262 * Also contains an icon by default. Shown to teachers and admin only.
2264 * @param string $path The page link after doc root and language, no leading slash.
2265 * @param string $text The text to be displayed for the link
2266 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2267 * @param array $attributes htm attributes
2268 * @return string
2270 public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
2271 global $CFG;
2273 $icon = $this->pix_icon('book', '', 'moodle', array('class' => 'iconhelp icon-pre', 'role' => 'presentation'));
2275 $attributes['href'] = new moodle_url(get_docs_url($path));
2276 $newwindowicon = '';
2277 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2278 $attributes['target'] = '_blank';
2279 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle',
2280 ['class' => 'fa fa-externallink fa-fw']);
2283 return html_writer::tag('a', $icon . $text . $newwindowicon, $attributes);
2287 * Return HTML for an image_icon.
2289 * Theme developers: DO NOT OVERRIDE! Please override function
2290 * {@link core_renderer::render_image_icon()} instead.
2292 * @param string $pix short pix name
2293 * @param string $alt mandatory alt attribute
2294 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2295 * @param array $attributes htm attributes
2296 * @return string HTML fragment
2298 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2299 $icon = new image_icon($pix, $alt, $component, $attributes);
2300 return $this->render($icon);
2304 * Renders a pix_icon widget and returns the HTML to display it.
2306 * @param image_icon $icon
2307 * @return string HTML fragment
2309 protected function render_image_icon(image_icon $icon) {
2310 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2311 return $system->render_pix_icon($this, $icon);
2315 * Return HTML for a pix_icon.
2317 * Theme developers: DO NOT OVERRIDE! Please override function
2318 * {@link core_renderer::render_pix_icon()} instead.
2320 * @param string $pix short pix name
2321 * @param string $alt mandatory alt attribute
2322 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2323 * @param array $attributes htm lattributes
2324 * @return string HTML fragment
2326 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2327 $icon = new pix_icon($pix, $alt, $component, $attributes);
2328 return $this->render($icon);
2332 * Renders a pix_icon widget and returns the HTML to display it.
2334 * @param pix_icon $icon
2335 * @return string HTML fragment
2337 protected function render_pix_icon(pix_icon $icon) {
2338 $system = \core\output\icon_system::instance();
2339 return $system->render_pix_icon($this, $icon);
2343 * Return HTML to display an emoticon icon.
2345 * @param pix_emoticon $emoticon
2346 * @return string HTML fragment
2348 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2349 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2350 return $system->render_pix_icon($this, $emoticon);
2354 * Produces the html that represents this rating in the UI
2356 * @param rating $rating the page object on which this rating will appear
2357 * @return string
2359 function render_rating(rating $rating) {
2360 global $CFG, $USER;
2362 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2363 return null;//ratings are turned off
2366 $ratingmanager = new rating_manager();
2367 // Initialise the JavaScript so ratings can be done by AJAX.
2368 $ratingmanager->initialise_rating_javascript($this->page);
2370 $strrate = get_string("rate", "rating");
2371 $ratinghtml = ''; //the string we'll return
2373 // permissions check - can they view the aggregate?
2374 if ($rating->user_can_view_aggregate()) {
2376 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2377 $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2378 $aggregatestr = $rating->get_aggregate_string();
2380 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2381 if ($rating->count > 0) {
2382 $countstr = "({$rating->count})";
2383 } else {
2384 $countstr = '-';
2386 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2388 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2390 $nonpopuplink = $rating->get_view_ratings_url();
2391 $popuplink = $rating->get_view_ratings_url(true);
2393 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2394 $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
2397 $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
2400 $formstart = null;
2401 // if the item doesn't belong to the current user, the user has permission to rate
2402 // and we're within the assessable period
2403 if ($rating->user_can_rate()) {
2405 $rateurl = $rating->get_rate_url();
2406 $inputs = $rateurl->params();
2408 //start the rating form
2409 $formattrs = array(
2410 'id' => "postrating{$rating->itemid}",
2411 'class' => 'postratingform',
2412 'method' => 'post',
2413 'action' => $rateurl->out_omit_querystring()
2415 $formstart = html_writer::start_tag('form', $formattrs);
2416 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2418 // add the hidden inputs
2419 foreach ($inputs as $name => $value) {
2420 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2421 $formstart .= html_writer::empty_tag('input', $attributes);
2424 if (empty($ratinghtml)) {
2425 $ratinghtml .= $strrate.': ';
2427 $ratinghtml = $formstart.$ratinghtml;
2429 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2430 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2431 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2432 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2434 //output submit button
2435 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2437 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2438 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2440 if (!$rating->settings->scale->isnumeric) {
2441 // If a global scale, try to find current course ID from the context
2442 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2443 $courseid = $coursecontext->instanceid;
2444 } else {
2445 $courseid = $rating->settings->scale->courseid;
2447 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2449 $ratinghtml .= html_writer::end_tag('span');
2450 $ratinghtml .= html_writer::end_tag('div');
2451 $ratinghtml .= html_writer::end_tag('form');
2454 return $ratinghtml;
2458 * Centered heading with attached help button (same title text)
2459 * and optional icon attached.
2461 * @param string $text A heading text
2462 * @param string $helpidentifier The keyword that defines a help page
2463 * @param string $component component name
2464 * @param string|moodle_url $icon
2465 * @param string $iconalt icon alt text
2466 * @param int $level The level of importance of the heading. Defaulting to 2
2467 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2468 * @return string HTML fragment
2470 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2471 $image = '';
2472 if ($icon) {
2473 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2476 $help = '';
2477 if ($helpidentifier) {
2478 $help = $this->help_icon($helpidentifier, $component);
2481 return $this->heading($image.$text.$help, $level, $classnames);
2485 * Returns HTML to display a help icon.
2487 * @deprecated since Moodle 2.0
2489 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2490 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2494 * Returns HTML to display a help icon.
2496 * Theme developers: DO NOT OVERRIDE! Please override function
2497 * {@link core_renderer::render_help_icon()} instead.
2499 * @param string $identifier The keyword that defines a help page
2500 * @param string $component component name
2501 * @param string|bool $linktext true means use $title as link text, string means link text value
2502 * @return string HTML fragment
2504 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2505 $icon = new help_icon($identifier, $component);
2506 $icon->diag_strings();
2507 if ($linktext === true) {
2508 $icon->linktext = get_string($icon->identifier, $icon->component);
2509 } else if (!empty($linktext)) {
2510 $icon->linktext = $linktext;
2512 return $this->render($icon);
2516 * Implementation of user image rendering.
2518 * @param help_icon $helpicon A help icon instance
2519 * @return string HTML fragment
2521 protected function render_help_icon(help_icon $helpicon) {
2522 $context = $helpicon->export_for_template($this);
2523 return $this->render_from_template('core/help_icon', $context);
2527 * Returns HTML to display a scale help icon.
2529 * @param int $courseid
2530 * @param stdClass $scale instance
2531 * @return string HTML fragment
2533 public function help_icon_scale($courseid, stdClass $scale) {
2534 global $CFG;
2536 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2538 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2540 $scaleid = abs($scale->id);
2542 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2543 $action = new popup_action('click', $link, 'ratingscale');
2545 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2549 * Creates and returns a spacer image with optional line break.
2551 * @param array $attributes Any HTML attributes to add to the spaced.
2552 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2553 * laxy do it with CSS which is a much better solution.
2554 * @return string HTML fragment
2556 public function spacer(array $attributes = null, $br = false) {
2557 $attributes = (array)$attributes;
2558 if (empty($attributes['width'])) {
2559 $attributes['width'] = 1;
2561 if (empty($attributes['height'])) {
2562 $attributes['height'] = 1;
2564 $attributes['class'] = 'spacer';
2566 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2568 if (!empty($br)) {
2569 $output .= '<br />';
2572 return $output;
2576 * Returns HTML to display the specified user's avatar.
2578 * User avatar may be obtained in two ways:
2579 * <pre>
2580 * // Option 1: (shortcut for simple cases, preferred way)
2581 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2582 * $OUTPUT->user_picture($user, array('popup'=>true));
2584 * // Option 2:
2585 * $userpic = new user_picture($user);
2586 * // Set properties of $userpic
2587 * $userpic->popup = true;
2588 * $OUTPUT->render($userpic);
2589 * </pre>
2591 * Theme developers: DO NOT OVERRIDE! Please override function
2592 * {@link core_renderer::render_user_picture()} instead.
2594 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2595 * If any of these are missing, the database is queried. Avoid this
2596 * if at all possible, particularly for reports. It is very bad for performance.
2597 * @param array $options associative array with user picture options, used only if not a user_picture object,
2598 * options are:
2599 * - courseid=$this->page->course->id (course id of user profile in link)
2600 * - size=35 (size of image)
2601 * - link=true (make image clickable - the link leads to user profile)
2602 * - popup=false (open in popup)
2603 * - alttext=true (add image alt attribute)
2604 * - class = image class attribute (default 'userpicture')
2605 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2606 * - includefullname=false (whether to include the user's full name together with the user picture)
2607 * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2608 * @return string HTML fragment
2610 public function user_picture(stdClass $user, array $options = null) {
2611 $userpicture = new user_picture($user);
2612 foreach ((array)$options as $key=>$value) {
2613 if (property_exists($userpicture, $key)) {
2614 $userpicture->$key = $value;
2617 return $this->render($userpicture);
2621 * Internal implementation of user image rendering.
2623 * @param user_picture $userpicture
2624 * @return string
2626 protected function render_user_picture(user_picture $userpicture) {
2627 global $CFG;
2629 $user = $userpicture->user;
2630 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
2632 $alt = '';
2633 if ($userpicture->alttext) {
2634 if (!empty($user->imagealt)) {
2635 $alt = $user->imagealt;
2639 if (empty($userpicture->size)) {
2640 $size = 35;
2641 } else if ($userpicture->size === true or $userpicture->size == 1) {
2642 $size = 100;
2643 } else {
2644 $size = $userpicture->size;
2647 $class = $userpicture->class;
2649 if ($user->picture == 0) {
2650 $class .= ' defaultuserpic';
2653 $src = $userpicture->get_url($this->page, $this);
2655 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2656 if (!$userpicture->visibletoscreenreaders) {
2657 $alt = '';
2659 $attributes['alt'] = $alt;
2661 if (!empty($alt)) {
2662 $attributes['title'] = $alt;
2665 // Get the image html output first, auto generated based on initials if one isn't already set.
2666 if ($user->picture == 0 && empty($CFG->enablegravatar) && !defined('BEHAT_SITE_RUNNING')) {
2667 $output = html_writer::tag('span', mb_substr($user->firstname, 0, 1) . mb_substr($user->lastname, 0, 1),
2668 ['class' => 'userinitials size-' . $size]);
2669 } else {
2670 $output = html_writer::empty_tag('img', $attributes);
2673 // Show fullname together with the picture when desired.
2674 if ($userpicture->includefullname) {
2675 $output .= fullname($userpicture->user, $canviewfullnames);
2678 if (empty($userpicture->courseid)) {
2679 $courseid = $this->page->course->id;
2680 } else {
2681 $courseid = $userpicture->courseid;
2683 if ($courseid == SITEID) {
2684 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2685 } else {
2686 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2689 // Then wrap it in link if needed. Also we don't wrap it in link if the link redirects to itself.
2690 if (!$userpicture->link ||
2691 ($this->page->has_set_url() && $this->page->url == $url)) { // Protect against unset page->url.
2692 return $output;
2695 $attributes = array('href' => $url, 'class' => 'd-inline-block aabtn');
2696 if (!$userpicture->visibletoscreenreaders) {
2697 $attributes['tabindex'] = '-1';
2698 $attributes['aria-hidden'] = 'true';
2701 if ($userpicture->popup) {
2702 $id = html_writer::random_id('userpicture');
2703 $attributes['id'] = $id;
2704 $this->add_action_handler(new popup_action('click', $url), $id);
2707 return html_writer::tag('a', $output, $attributes);
2711 * Internal implementation of file tree viewer items rendering.
2713 * @param array $dir
2714 * @return string
2716 public function htmllize_file_tree($dir) {
2717 if (empty($dir['subdirs']) and empty($dir['files'])) {
2718 return '';
2720 $result = '<ul>';
2721 foreach ($dir['subdirs'] as $subdir) {
2722 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2724 foreach ($dir['files'] as $file) {
2725 $filename = $file->get_filename();
2726 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2728 $result .= '</ul>';
2730 return $result;
2734 * Returns HTML to display the file picker
2736 * <pre>
2737 * $OUTPUT->file_picker($options);
2738 * </pre>
2740 * Theme developers: DO NOT OVERRIDE! Please override function
2741 * {@link core_renderer::render_file_picker()} instead.
2743 * @param array $options associative array with file manager options
2744 * options are:
2745 * maxbytes=>-1,
2746 * itemid=>0,
2747 * client_id=>uniqid(),
2748 * acepted_types=>'*',
2749 * return_types=>FILE_INTERNAL,
2750 * context=>current page context
2751 * @return string HTML fragment
2753 public function file_picker($options) {
2754 $fp = new file_picker($options);
2755 return $this->render($fp);
2759 * Internal implementation of file picker rendering.
2761 * @param file_picker $fp
2762 * @return string
2764 public function render_file_picker(file_picker $fp) {
2765 $options = $fp->options;
2766 $client_id = $options->client_id;
2767 $strsaved = get_string('filesaved', 'repository');
2768 $straddfile = get_string('openpicker', 'repository');
2769 $strloading = get_string('loading', 'repository');
2770 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2771 $strdroptoupload = get_string('droptoupload', 'moodle');
2772 $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
2774 $currentfile = $options->currentfile;
2775 if (empty($currentfile)) {
2776 $currentfile = '';
2777 } else {
2778 $currentfile .= ' - ';
2780 if ($options->maxbytes) {
2781 $size = $options->maxbytes;
2782 } else {
2783 $size = get_max_upload_file_size();
2785 if ($size == -1) {
2786 $maxsize = '';
2787 } else {
2788 $maxsize = get_string('maxfilesize', 'moodle', display_size($size, 0));
2790 if ($options->buttonname) {
2791 $buttonname = ' name="' . $options->buttonname . '"';
2792 } else {
2793 $buttonname = '';
2795 $html = <<<EOD
2796 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2797 $iconprogress
2798 </div>
2799 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2800 <div>
2801 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2802 <span> $maxsize </span>
2803 </div>
2804 EOD;
2805 if ($options->env != 'url') {
2806 $html .= <<<EOD
2807 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2808 <div class="filepicker-filename">
2809 <div class="filepicker-container">$currentfile
2810 <div class="dndupload-message">$strdndenabled <br/>
2811 <div class="dndupload-arrow d-flex"><i class="fa fa-arrow-circle-o-down fa-3x m-auto"></i></div>
2812 </div>
2813 </div>
2814 <div class="dndupload-progressbars"></div>
2815 </div>
2816 <div>
2817 <div class="dndupload-target">{$strdroptoupload}<br/>
2818 <div class="dndupload-arrow d-flex"><i class="fa fa-arrow-circle-o-down fa-3x m-auto"></i></div>
2819 </div>
2820 </div>
2821 </div>
2822 EOD;
2824 $html .= '</div>';
2825 return $html;
2829 * @deprecated since Moodle 3.2
2831 public function update_module_button() {
2832 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2833 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2834 'Themes can choose to display the link in the buttons row consistently for all module types.');
2838 * Returns HTML to display a "Turn editing on/off" button in a form.
2840 * @param moodle_url $url The URL + params to send through when clicking the button
2841 * @param string $method
2842 * @return string HTML the button
2844 public function edit_button(moodle_url $url, string $method = 'post') {
2846 if ($this->page->theme->haseditswitch == true) {
2847 return;
2849 $url->param('sesskey', sesskey());
2850 if ($this->page->user_is_editing()) {
2851 $url->param('edit', 'off');
2852 $editstring = get_string('turneditingoff');
2853 } else {
2854 $url->param('edit', 'on');
2855 $editstring = get_string('turneditingon');
2858 return $this->single_button($url, $editstring, $method);
2862 * Create a navbar switch for toggling editing mode.
2864 * @return string Html containing the edit switch
2866 public function edit_switch() {
2867 if ($this->page->user_allowed_editing()) {
2869 $temp = (object) [
2870 'legacyseturl' => (new moodle_url('/editmode.php'))->out(false),
2871 'pagecontextid' => $this->page->context->id,
2872 'pageurl' => $this->page->url,
2873 'sesskey' => sesskey(),
2875 if ($this->page->user_is_editing()) {
2876 $temp->checked = true;
2878 return $this->render_from_template('core/editswitch', $temp);
2883 * Returns HTML to display a simple button to close a window
2885 * @param string $text The lang string for the button's label (already output from get_string())
2886 * @return string html fragment
2888 public function close_window_button($text='') {
2889 if (empty($text)) {
2890 $text = get_string('closewindow');
2892 $button = new single_button(new moodle_url('#'), $text, 'get');
2893 $button->add_action(new component_action('click', 'close_window'));
2895 return $this->container($this->render($button), 'closewindow');
2899 * Output an error message. By default wraps the error message in <span class="error">.
2900 * If the error message is blank, nothing is output.
2902 * @param string $message the error message.
2903 * @return string the HTML to output.
2905 public function error_text($message) {
2906 if (empty($message)) {
2907 return '';
2909 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2910 return html_writer::tag('span', $message, array('class' => 'error'));
2914 * Do not call this function directly.
2916 * To terminate the current script with a fatal error, throw an exception.
2917 * Doing this will then call this function to display the error, before terminating the execution.
2919 * @param string $message The message to output
2920 * @param string $moreinfourl URL where more info can be found about the error
2921 * @param string $link Link for the Continue button
2922 * @param array $backtrace The execution backtrace
2923 * @param string $debuginfo Debugging information
2924 * @return string the HTML to output.
2926 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2927 global $CFG;
2929 $output = '';
2930 $obbuffer = '';
2932 if ($this->has_started()) {
2933 // we can not always recover properly here, we have problems with output buffering,
2934 // html tables, etc.
2935 $output .= $this->opencontainers->pop_all_but_last();
2937 } else {
2938 // It is really bad if library code throws exception when output buffering is on,
2939 // because the buffered text would be printed before our start of page.
2940 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2941 error_reporting(0); // disable notices from gzip compression, etc.
2942 while (ob_get_level() > 0) {
2943 $buff = ob_get_clean();
2944 if ($buff === false) {
2945 break;
2947 $obbuffer .= $buff;
2949 error_reporting($CFG->debug);
2951 // Output not yet started.
2952 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2953 if (empty($_SERVER['HTTP_RANGE'])) {
2954 @header($protocol . ' 404 Not Found');
2955 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2956 // Coax iOS 10 into sending the session cookie.
2957 @header($protocol . ' 403 Forbidden');
2958 } else {
2959 // Must stop byteserving attempts somehow,
2960 // this is weird but Chrome PDF viewer can be stopped only with 407!
2961 @header($protocol . ' 407 Proxy Authentication Required');
2964 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2965 $this->page->set_url('/'); // no url
2966 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2967 $this->page->set_title(get_string('error'));
2968 $this->page->set_heading($this->page->course->fullname);
2969 // No need to display the activity header when encountering an error.
2970 $this->page->activityheader->disable();
2971 $output .= $this->header();
2974 $message = '<p class="errormessage">' . s($message) . '</p>'.
2975 '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
2976 get_string('moreinformation') . '</a></p>';
2977 if (empty($CFG->rolesactive)) {
2978 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2979 //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.
2981 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2983 if ($CFG->debugdeveloper) {
2984 $labelsep = get_string('labelsep', 'langconfig');
2985 if (!empty($debuginfo)) {
2986 $debuginfo = s($debuginfo); // removes all nasty JS
2987 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2988 $label = get_string('debuginfo', 'debug') . $labelsep;
2989 $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
2991 if (!empty($backtrace)) {
2992 $label = get_string('stacktrace', 'debug') . $labelsep;
2993 $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
2995 if ($obbuffer !== '' ) {
2996 $label = get_string('outputbuffer', 'debug') . $labelsep;
2997 $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
3001 if (empty($CFG->rolesactive)) {
3002 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
3003 } else if (!empty($link)) {
3004 $output .= $this->continue_button($link);
3007 $output .= $this->footer();
3009 // Padding to encourage IE to display our error page, rather than its own.
3010 $output .= str_repeat(' ', 512);
3012 return $output;
3016 * Output a notification (that is, a status message about something that has just happened).
3018 * Note: \core\notification::add() may be more suitable for your usage.
3020 * @param string $message The message to print out.
3021 * @param ?string $type The type of notification. See constants on \core\output\notification.
3022 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
3023 * @return string the HTML to output.
3025 public function notification($message, $type = null, $closebutton = true) {
3026 $typemappings = [
3027 // Valid types.
3028 'success' => \core\output\notification::NOTIFY_SUCCESS,
3029 'info' => \core\output\notification::NOTIFY_INFO,
3030 'warning' => \core\output\notification::NOTIFY_WARNING,
3031 'error' => \core\output\notification::NOTIFY_ERROR,
3033 // Legacy types mapped to current types.
3034 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
3035 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
3036 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
3037 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
3038 'notifymessage' => \core\output\notification::NOTIFY_INFO,
3039 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
3040 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
3043 $extraclasses = [];
3045 if ($type) {
3046 if (strpos($type, ' ') === false) {
3047 // No spaces in the list of classes, therefore no need to loop over and determine the class.
3048 if (isset($typemappings[$type])) {
3049 $type = $typemappings[$type];
3050 } else {
3051 // The value provided did not match a known type. It must be an extra class.
3052 $extraclasses = [$type];
3054 } else {
3055 // Identify what type of notification this is.
3056 $classarray = explode(' ', self::prepare_classes($type));
3058 // Separate out the type of notification from the extra classes.
3059 foreach ($classarray as $class) {
3060 if (isset($typemappings[$class])) {
3061 $type = $typemappings[$class];
3062 } else {
3063 $extraclasses[] = $class;
3069 $notification = new \core\output\notification($message, $type, $closebutton);
3070 if (count($extraclasses)) {
3071 $notification->set_extra_classes($extraclasses);
3074 // Return the rendered template.
3075 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3079 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3081 public function notify_problem() {
3082 throw new coding_exception('core_renderer::notify_problem() 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_success() {
3090 throw new coding_exception('core_renderer::notify_success() 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_message() {
3098 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
3099 'please use \core\notification::add(), or \core\output\notification as required.');
3103 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3105 public function notify_redirect() {
3106 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
3107 'please use \core\notification::add(), or \core\output\notification as required.');
3111 * Render a notification (that is, a status message about something that has
3112 * just happened).
3114 * @param \core\output\notification $notification the notification to print out
3115 * @return string the HTML to output.
3117 protected function render_notification(\core\output\notification $notification) {
3118 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3122 * Returns HTML to display a continue button that goes to a particular URL.
3124 * @param string|moodle_url $url The url the button goes to.
3125 * @return string the HTML to output.
3127 public function continue_button($url) {
3128 if (!($url instanceof moodle_url)) {
3129 $url = new moodle_url($url);
3131 $button = new single_button($url, get_string('continue'), 'get', single_button::BUTTON_PRIMARY);
3132 $button->class = 'continuebutton';
3134 return $this->render($button);
3138 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
3140 * Theme developers: DO NOT OVERRIDE! Please override function
3141 * {@link core_renderer::render_paging_bar()} instead.
3143 * @param int $totalcount The total number of entries available to be paged through
3144 * @param int $page The page you are currently viewing
3145 * @param int $perpage The number of entries that should be shown per page
3146 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3147 * @param string $pagevar name of page parameter that holds the page number
3148 * @return string the HTML to output.
3150 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3151 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3152 return $this->render($pb);
3156 * Returns HTML to display the paging bar.
3158 * @param paging_bar $pagingbar
3159 * @return string the HTML to output.
3161 protected function render_paging_bar(paging_bar $pagingbar) {
3162 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3163 $pagingbar->maxdisplay = 10;
3164 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3168 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3170 * @param string $current the currently selected letter.
3171 * @param string $class class name to add to this initial bar.
3172 * @param string $title the name to put in front of this initial bar.
3173 * @param string $urlvar URL parameter name for this initial.
3174 * @param string $url URL object.
3175 * @param array $alpha of letters in the alphabet.
3176 * @param bool $minirender Return a trimmed down view of the initials bar.
3177 * @return string the HTML to output.
3179 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null, bool $minirender = false) {
3180 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha, $minirender);
3181 return $this->render($ib);
3185 * Internal implementation of initials bar rendering.
3187 * @param initials_bar $initialsbar
3188 * @return string
3190 protected function render_initials_bar(initials_bar $initialsbar) {
3191 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3195 * Output the place a skip link goes to.
3197 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3198 * @return string the HTML to output.
3200 public function skip_link_target($id = null) {
3201 return html_writer::span('', '', array('id' => $id));
3205 * Outputs a heading
3207 * @param string $text The text of the heading
3208 * @param int $level The level of importance of the heading. Defaulting to 2
3209 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3210 * @param string $id An optional ID
3211 * @return string the HTML to output.
3213 public function heading($text, $level = 2, $classes = null, $id = null) {
3214 $level = (integer) $level;
3215 if ($level < 1 or $level > 6) {
3216 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3218 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3222 * Outputs a box.
3224 * @param string $contents The contents of the box
3225 * @param string $classes A space-separated list of CSS classes
3226 * @param string $id An optional ID
3227 * @param array $attributes An array of other attributes to give the box.
3228 * @return string the HTML to output.
3230 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3231 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3235 * Outputs the opening section of a box.
3237 * @param string $classes A space-separated list of CSS classes
3238 * @param string $id An optional ID
3239 * @param array $attributes An array of other attributes to give the box.
3240 * @return string the HTML to output.
3242 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3243 $this->opencontainers->push('box', html_writer::end_tag('div'));
3244 $attributes['id'] = $id;
3245 $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes);
3246 return html_writer::start_tag('div', $attributes);
3250 * Outputs the closing section of a box.
3252 * @return string the HTML to output.
3254 public function box_end() {
3255 return $this->opencontainers->pop('box');
3259 * Outputs a container.
3261 * @param string $contents The contents of the box
3262 * @param string $classes A space-separated list of CSS classes
3263 * @param string $id An optional ID
3264 * @return string the HTML to output.
3266 public function container($contents, $classes = null, $id = null) {
3267 return $this->container_start($classes, $id) . $contents . $this->container_end();
3271 * Outputs the opening section of a container.
3273 * @param string $classes A space-separated list of CSS classes
3274 * @param string $id An optional ID
3275 * @return string the HTML to output.
3277 public function container_start($classes = null, $id = null) {
3278 $this->opencontainers->push('container', html_writer::end_tag('div'));
3279 return html_writer::start_tag('div', array('id' => $id,
3280 'class' => renderer_base::prepare_classes($classes)));
3284 * Outputs the closing section of a container.
3286 * @return string the HTML to output.
3288 public function container_end() {
3289 return $this->opencontainers->pop('container');
3293 * Make nested HTML lists out of the items
3295 * The resulting list will look something like this:
3297 * <pre>
3298 * <<ul>>
3299 * <<li>><div class='tree_item parent'>(item contents)</div>
3300 * <<ul>
3301 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3302 * <</ul>>
3303 * <</li>>
3304 * <</ul>>
3305 * </pre>
3307 * @param array $items
3308 * @param array $attrs html attributes passed to the top ofs the list
3309 * @return string HTML
3311 public function tree_block_contents($items, $attrs = array()) {
3312 // exit if empty, we don't want an empty ul element
3313 if (empty($items)) {
3314 return '';
3316 // array of nested li elements
3317 $lis = array();
3318 foreach ($items as $item) {
3319 // this applies to the li item which contains all child lists too
3320 $content = $item->content($this);
3321 $liclasses = array($item->get_css_type());
3322 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3323 $liclasses[] = 'collapsed';
3325 if ($item->isactive === true) {
3326 $liclasses[] = 'current_branch';
3328 $liattr = array('class'=>join(' ',$liclasses));
3329 // class attribute on the div item which only contains the item content
3330 $divclasses = array('tree_item');
3331 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3332 $divclasses[] = 'branch';
3333 } else {
3334 $divclasses[] = 'leaf';
3336 if (!empty($item->classes) && count($item->classes)>0) {
3337 $divclasses[] = join(' ', $item->classes);
3339 $divattr = array('class'=>join(' ', $divclasses));
3340 if (!empty($item->id)) {
3341 $divattr['id'] = $item->id;
3343 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3344 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3345 $content = html_writer::empty_tag('hr') . $content;
3347 $content = html_writer::tag('li', $content, $liattr);
3348 $lis[] = $content;
3350 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3354 * Returns a search box.
3356 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3357 * @return string HTML with the search form hidden by default.
3359 public function search_box($id = false) {
3360 global $CFG;
3362 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3363 // result in an extra included file for each site, even the ones where global search
3364 // is disabled.
3365 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3366 return '';
3369 $data = [
3370 'action' => new moodle_url('/search/index.php'),
3371 'hiddenfields' => (object) ['name' => 'context', 'value' => $this->page->context->id],
3372 'inputname' => 'q',
3373 'searchstring' => get_string('search'),
3375 return $this->render_from_template('core/search_input_navbar', $data);
3379 * Allow plugins to provide some content to be rendered in the navbar.
3380 * The plugin must define a PLUGIN_render_navbar_output function that returns
3381 * the HTML they wish to add to the navbar.
3383 * @return string HTML for the navbar
3385 public function navbar_plugin_output() {
3386 $output = '';
3388 // Give subsystems an opportunity to inject extra html content. The callback
3389 // must always return a string containing valid html.
3390 foreach (\core_component::get_core_subsystems() as $name => $path) {
3391 if ($path) {
3392 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3396 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3397 foreach ($pluginsfunction as $plugintype => $plugins) {
3398 foreach ($plugins as $pluginfunction) {
3399 $output .= $pluginfunction($this);
3404 return $output;
3408 * Construct a user menu, returning HTML that can be echoed out by a
3409 * layout file.
3411 * @param stdClass $user A user object, usually $USER.
3412 * @param bool $withlinks true if a dropdown should be built.
3413 * @return string HTML fragment.
3415 public function user_menu($user = null, $withlinks = null) {
3416 global $USER, $CFG;
3417 require_once($CFG->dirroot . '/user/lib.php');
3419 if (is_null($user)) {
3420 $user = $USER;
3423 // Note: this behaviour is intended to match that of core_renderer::login_info,
3424 // but should not be considered to be good practice; layout options are
3425 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3426 if (is_null($withlinks)) {
3427 $withlinks = empty($this->page->layout_options['nologinlinks']);
3430 // Add a class for when $withlinks is false.
3431 $usermenuclasses = 'usermenu';
3432 if (!$withlinks) {
3433 $usermenuclasses .= ' withoutlinks';
3436 $returnstr = "";
3438 // If during initial install, return the empty return string.
3439 if (during_initial_install()) {
3440 return $returnstr;
3443 $loginpage = $this->is_login_page();
3444 $loginurl = get_login_url();
3446 // Get some navigation opts.
3447 $opts = user_get_user_navigation_info($user, $this->page);
3449 if (!empty($opts->unauthenticateduser)) {
3450 $returnstr = get_string($opts->unauthenticateduser['content'], 'moodle');
3451 // If not logged in, show the typical not-logged-in string.
3452 if (!$loginpage && (!$opts->unauthenticateduser['guest'] || $withlinks)) {
3453 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3456 return html_writer::div(
3457 html_writer::span(
3458 $returnstr,
3459 'login nav-link'
3461 $usermenuclasses
3465 $avatarclasses = "avatars";
3466 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3467 $usertextcontents = $opts->metadata['userfullname'];
3469 // Other user.
3470 if (!empty($opts->metadata['asotheruser'])) {
3471 $avatarcontents .= html_writer::span(
3472 $opts->metadata['realuseravatar'],
3473 'avatar realuser'
3475 $usertextcontents = $opts->metadata['realuserfullname'];
3476 $usertextcontents .= html_writer::tag(
3477 'span',
3478 get_string(
3479 'loggedinas',
3480 'moodle',
3481 html_writer::span(
3482 $opts->metadata['userfullname'],
3483 'value'
3486 array('class' => 'meta viewingas')
3490 // Role.
3491 if (!empty($opts->metadata['asotherrole'])) {
3492 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3493 $usertextcontents .= html_writer::span(
3494 $opts->metadata['rolename'],
3495 'meta role role-' . $role
3499 // User login failures.
3500 if (!empty($opts->metadata['userloginfail'])) {
3501 $usertextcontents .= html_writer::span(
3502 $opts->metadata['userloginfail'],
3503 'meta loginfailures'
3507 // MNet.
3508 if (!empty($opts->metadata['asmnetuser'])) {
3509 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3510 $usertextcontents .= html_writer::span(
3511 $opts->metadata['mnetidprovidername'],
3512 'meta mnet mnet-' . $mnet
3516 $returnstr .= html_writer::span(
3517 html_writer::span($usertextcontents, 'usertext mr-1') .
3518 html_writer::span($avatarcontents, $avatarclasses),
3519 'userbutton'
3522 // Create a divider (well, a filler).
3523 $divider = new action_menu_filler();
3524 $divider->primary = false;
3526 $am = new action_menu();
3527 $am->set_menu_trigger(
3528 $returnstr,
3529 'nav-link'
3531 $am->set_action_label(get_string('usermenu'));
3532 $am->set_nowrap_on_items();
3533 if ($withlinks) {
3534 $navitemcount = count($opts->navitems);
3535 $idx = 0;
3536 foreach ($opts->navitems as $key => $value) {
3538 switch ($value->itemtype) {
3539 case 'divider':
3540 // If the nav item is a divider, add one and skip link processing.
3541 $am->add($divider);
3542 break;
3544 case 'invalid':
3545 // Silently skip invalid entries (should we post a notification?).
3546 break;
3548 case 'link':
3549 // Process this as a link item.
3550 $pix = null;
3551 if (isset($value->pix) && !empty($value->pix)) {
3552 $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
3553 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3554 $value->title = html_writer::img(
3555 $value->imgsrc,
3556 $value->title,
3557 array('class' => 'iconsmall')
3558 ) . $value->title;
3561 $al = new action_menu_link_secondary(
3562 $value->url,
3563 $pix,
3564 $value->title,
3565 array('class' => 'icon')
3567 if (!empty($value->titleidentifier)) {
3568 $al->attributes['data-title'] = $value->titleidentifier;
3570 $am->add($al);
3571 break;
3574 $idx++;
3576 // Add dividers after the first item and before the last item.
3577 if ($idx == 1 || $idx == $navitemcount - 1) {
3578 $am->add($divider);
3583 return html_writer::div(
3584 $this->render($am),
3585 $usermenuclasses
3590 * Secure layout login info.
3592 * @return string
3594 public function secure_layout_login_info() {
3595 if (get_config('core', 'logininfoinsecurelayout')) {
3596 return $this->login_info(false);
3597 } else {
3598 return '';
3603 * Returns the language menu in the secure layout.
3605 * No custom menu items are passed though, such that it will render only the language selection.
3607 * @return string
3609 public function secure_layout_language_menu() {
3610 if (get_config('core', 'langmenuinsecurelayout')) {
3611 $custommenu = new custom_menu('', current_language());
3612 return $this->render_custom_menu($custommenu);
3613 } else {
3614 return '';
3619 * This renders the navbar.
3620 * Uses bootstrap compatible html.
3622 public function navbar() {
3623 return $this->render_from_template('core/navbar', $this->page->navbar);
3627 * Renders a breadcrumb navigation node object.
3629 * @param breadcrumb_navigation_node $item The navigation node to render.
3630 * @return string HTML fragment
3632 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3634 if ($item->action instanceof moodle_url) {
3635 $content = $item->get_content();
3636 $title = $item->get_title();
3637 $attributes = array();
3638 $attributes['itemprop'] = 'url';
3639 if ($title !== '') {
3640 $attributes['title'] = $title;
3642 if ($item->hidden) {
3643 $attributes['class'] = 'dimmed_text';
3645 if ($item->is_last()) {
3646 $attributes['aria-current'] = 'page';
3648 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3649 $content = html_writer::link($item->action, $content, $attributes);
3651 $attributes = array();
3652 $attributes['itemscope'] = '';
3653 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3654 $content = html_writer::tag('span', $content, $attributes);
3656 } else {
3657 $content = $this->render_navigation_node($item);
3659 return $content;
3663 * Renders a navigation node object.
3665 * @param navigation_node $item The navigation node to render.
3666 * @return string HTML fragment
3668 protected function render_navigation_node(navigation_node $item) {
3669 $content = $item->get_content();
3670 $title = $item->get_title();
3671 if ($item->icon instanceof renderable && !$item->hideicon) {
3672 $icon = $this->render($item->icon);
3673 $content = $icon.$content; // use CSS for spacing of icons
3675 if ($item->helpbutton !== null) {
3676 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3678 if ($content === '') {
3679 return '';
3681 if ($item->action instanceof action_link) {
3682 $link = $item->action;
3683 if ($item->hidden) {
3684 $link->add_class('dimmed');
3686 if (!empty($content)) {
3687 // Providing there is content we will use that for the link content.
3688 $link->text = $content;
3690 $content = $this->render($link);
3691 } else if ($item->action instanceof moodle_url) {
3692 $attributes = array();
3693 if ($title !== '') {
3694 $attributes['title'] = $title;
3696 if ($item->hidden) {
3697 $attributes['class'] = 'dimmed_text';
3699 $content = html_writer::link($item->action, $content, $attributes);
3701 } else if (is_string($item->action) || empty($item->action)) {
3702 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3703 if ($title !== '') {
3704 $attributes['title'] = $title;
3706 if ($item->hidden) {
3707 $attributes['class'] = 'dimmed_text';
3709 $content = html_writer::tag('span', $content, $attributes);
3711 return $content;
3715 * Accessibility: Right arrow-like character is
3716 * used in the breadcrumb trail, course navigation menu
3717 * (previous/next activity), calendar, and search forum block.
3718 * If the theme does not set characters, appropriate defaults
3719 * are set automatically. Please DO NOT
3720 * use &lt; &gt; &raquo; - these are confusing for blind users.
3722 * @return string
3724 public function rarrow() {
3725 return $this->page->theme->rarrow;
3729 * Accessibility: Left arrow-like character is
3730 * used in the breadcrumb trail, course navigation menu
3731 * (previous/next activity), calendar, and search forum block.
3732 * If the theme does not set characters, appropriate defaults
3733 * are set automatically. Please DO NOT
3734 * use &lt; &gt; &raquo; - these are confusing for blind users.
3736 * @return string
3738 public function larrow() {
3739 return $this->page->theme->larrow;
3743 * Accessibility: Up arrow-like character is used in
3744 * the book heirarchical navigation.
3745 * If the theme does not set characters, appropriate defaults
3746 * are set automatically. Please DO NOT
3747 * use ^ - this is confusing for blind users.
3749 * @return string
3751 public function uarrow() {
3752 return $this->page->theme->uarrow;
3756 * Accessibility: Down arrow-like character.
3757 * If the theme does not set characters, appropriate defaults
3758 * are set automatically.
3760 * @return string
3762 public function darrow() {
3763 return $this->page->theme->darrow;
3767 * Returns the custom menu if one has been set
3769 * A custom menu can be configured by browsing to
3770 * Settings: Administration > Appearance > Themes > Theme settings
3771 * and then configuring the custommenu config setting as described.
3773 * Theme developers: DO NOT OVERRIDE! Please override function
3774 * {@link core_renderer::render_custom_menu()} instead.
3776 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3777 * @return string
3779 public function custom_menu($custommenuitems = '') {
3780 global $CFG;
3782 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3783 $custommenuitems = $CFG->custommenuitems;
3785 $custommenu = new custom_menu($custommenuitems, current_language());
3786 return $this->render_custom_menu($custommenu);
3790 * We want to show the custom menus as a list of links in the footer on small screens.
3791 * Just return the menu object exported so we can render it differently.
3793 public function custom_menu_flat() {
3794 global $CFG;
3795 $custommenuitems = '';
3797 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3798 $custommenuitems = $CFG->custommenuitems;
3800 $custommenu = new custom_menu($custommenuitems, current_language());
3801 $langs = get_string_manager()->get_list_of_translations();
3802 $haslangmenu = $this->lang_menu() != '';
3804 if ($haslangmenu) {
3805 $strlang = get_string('language');
3806 $currentlang = current_language();
3807 if (isset($langs[$currentlang])) {
3808 $currentlang = $langs[$currentlang];
3809 } else {
3810 $currentlang = $strlang;
3812 $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3813 foreach ($langs as $langtype => $langname) {
3814 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3818 return $custommenu->export_for_template($this);
3822 * Renders a custom menu object (located in outputcomponents.php)
3824 * The custom menu this method produces makes use of the YUI3 menunav widget
3825 * and requires very specific html elements and classes.
3827 * @staticvar int $menucount
3828 * @param custom_menu $menu
3829 * @return string
3831 protected function render_custom_menu(custom_menu $menu) {
3832 global $CFG;
3834 $langs = get_string_manager()->get_list_of_translations();
3835 $haslangmenu = $this->lang_menu() != '';
3837 if (!$menu->has_children() && !$haslangmenu) {
3838 return '';
3841 if ($haslangmenu) {
3842 $strlang = get_string('language');
3843 $currentlang = current_language();
3844 if (isset($langs[$currentlang])) {
3845 $currentlangstr = $langs[$currentlang];
3846 } else {
3847 $currentlangstr = $strlang;
3849 $this->language = $menu->add($currentlangstr, new moodle_url('#'), $strlang, 10000);
3850 foreach ($langs as $langtype => $langname) {
3851 $attributes = [];
3852 // Set the lang attribute for languages different from the page's current language.
3853 if ($langtype !== $currentlang) {
3854 $attributes[] = [
3855 'key' => 'lang',
3856 'value' => get_html_lang_attribute_value($langtype),
3859 $this->language->add($langname, new moodle_url($this->page->url, ['lang' => $langtype]), null, null, $attributes);
3863 $content = '';
3864 foreach ($menu->get_children() as $item) {
3865 $context = $item->export_for_template($this);
3866 $content .= $this->render_from_template('core/custom_menu_item', $context);
3869 return $content;
3873 * Renders a custom menu node as part of a submenu
3875 * The custom menu this method produces makes use of the YUI3 menunav widget
3876 * and requires very specific html elements and classes.
3878 * @see core:renderer::render_custom_menu()
3880 * @staticvar int $submenucount
3881 * @param custom_menu_item $menunode
3882 * @return string
3884 protected function render_custom_menu_item(custom_menu_item $menunode) {
3885 // Required to ensure we get unique trackable id's
3886 static $submenucount = 0;
3887 if ($menunode->has_children()) {
3888 // If the child has menus render it as a sub menu
3889 $submenucount++;
3890 $content = html_writer::start_tag('li');
3891 if ($menunode->get_url() !== null) {
3892 $url = $menunode->get_url();
3893 } else {
3894 $url = '#cm_submenu_'.$submenucount;
3896 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3897 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3898 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3899 $content .= html_writer::start_tag('ul');
3900 foreach ($menunode->get_children() as $menunode) {
3901 $content .= $this->render_custom_menu_item($menunode);
3903 $content .= html_writer::end_tag('ul');
3904 $content .= html_writer::end_tag('div');
3905 $content .= html_writer::end_tag('div');
3906 $content .= html_writer::end_tag('li');
3907 } else {
3908 // The node doesn't have children so produce a final menuitem.
3909 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3910 $content = '';
3911 if (preg_match("/^#+$/", $menunode->get_text())) {
3913 // This is a divider.
3914 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3915 } else {
3916 $content = html_writer::start_tag(
3917 'li',
3918 array(
3919 'class' => 'yui3-menuitem'
3922 if ($menunode->get_url() !== null) {
3923 $url = $menunode->get_url();
3924 } else {
3925 $url = '#';
3927 $content .= html_writer::link(
3928 $url,
3929 $menunode->get_text(),
3930 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3933 $content .= html_writer::end_tag('li');
3935 // Return the sub menu
3936 return $content;
3940 * Renders theme links for switching between default and other themes.
3942 * @return string
3944 protected function theme_switch_links() {
3946 $actualdevice = core_useragent::get_device_type();
3947 $currentdevice = $this->page->devicetypeinuse;
3948 $switched = ($actualdevice != $currentdevice);
3950 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3951 // The user is using the a default device and hasn't switched so don't shown the switch
3952 // device links.
3953 return '';
3956 if ($switched) {
3957 $linktext = get_string('switchdevicerecommended');
3958 $devicetype = $actualdevice;
3959 } else {
3960 $linktext = get_string('switchdevicedefault');
3961 $devicetype = 'default';
3963 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3965 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3966 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3967 $content .= html_writer::end_tag('div');
3969 return $content;
3973 * Renders tabs
3975 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3977 * Theme developers: In order to change how tabs are displayed please override functions
3978 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3980 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3981 * @param string|null $selected which tab to mark as selected, all parent tabs will
3982 * automatically be marked as activated
3983 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3984 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3985 * @return string
3987 public final function tabtree($tabs, $selected = null, $inactive = null) {
3988 return $this->render(new tabtree($tabs, $selected, $inactive));
3992 * Renders tabtree
3994 * @param tabtree $tabtree
3995 * @return string
3997 protected function render_tabtree(tabtree $tabtree) {
3998 if (empty($tabtree->subtree)) {
3999 return '';
4001 $data = $tabtree->export_for_template($this);
4002 return $this->render_from_template('core/tabtree', $data);
4006 * Renders tabobject (part of tabtree)
4008 * This function is called from {@link core_renderer::render_tabtree()}
4009 * and also it calls itself when printing the $tabobject subtree recursively.
4011 * Property $tabobject->level indicates the number of row of tabs.
4013 * @param tabobject $tabobject
4014 * @return string HTML fragment
4016 protected function render_tabobject(tabobject $tabobject) {
4017 $str = '';
4019 // Print name of the current tab.
4020 if ($tabobject instanceof tabtree) {
4021 // No name for tabtree root.
4022 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
4023 // Tab name without a link. The <a> tag is used for styling.
4024 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
4025 } else {
4026 // Tab name with a link.
4027 if (!($tabobject->link instanceof moodle_url)) {
4028 // backward compartibility when link was passed as quoted string
4029 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
4030 } else {
4031 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
4035 if (empty($tabobject->subtree)) {
4036 if ($tabobject->selected) {
4037 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
4039 return $str;
4042 // Print subtree.
4043 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
4044 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
4045 $cnt = 0;
4046 foreach ($tabobject->subtree as $tab) {
4047 $liclass = '';
4048 if (!$cnt) {
4049 $liclass .= ' first';
4051 if ($cnt == count($tabobject->subtree) - 1) {
4052 $liclass .= ' last';
4054 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
4055 $liclass .= ' onerow';
4058 if ($tab->selected) {
4059 $liclass .= ' here selected';
4060 } else if ($tab->activated) {
4061 $liclass .= ' here active';
4064 // This will recursively call function render_tabobject() for each item in subtree.
4065 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
4066 $cnt++;
4068 $str .= html_writer::end_tag('ul');
4071 return $str;
4075 * Get the HTML for blocks in the given region.
4077 * @since Moodle 2.5.1 2.6
4078 * @param string $region The region to get HTML for.
4079 * @param array $classes Wrapping tag classes.
4080 * @param string $tag Wrapping tag.
4081 * @param boolean $fakeblocksonly Include fake blocks only.
4082 * @return string HTML.
4084 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
4085 $displayregion = $this->page->apply_theme_region_manipulations($region);
4086 $classes = (array)$classes;
4087 $classes[] = 'block-region';
4088 $attributes = array(
4089 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
4090 'class' => join(' ', $classes),
4091 'data-blockregion' => $displayregion,
4092 'data-droptarget' => '1'
4094 if ($this->page->blocks->region_has_content($displayregion, $this)) {
4095 $content = $this->blocks_for_region($displayregion, $fakeblocksonly);
4096 } else {
4097 $content = '';
4099 return html_writer::tag($tag, $content, $attributes);
4103 * Renders a custom block region.
4105 * Use this method if you want to add an additional block region to the content of the page.
4106 * Please note this should only be used in special situations.
4107 * We want to leave the theme is control where ever possible!
4109 * This method must use the same method that the theme uses within its layout file.
4110 * As such it asks the theme what method it is using.
4111 * It can be one of two values, blocks or blocks_for_region (deprecated).
4113 * @param string $regionname The name of the custom region to add.
4114 * @return string HTML for the block region.
4116 public function custom_block_region($regionname) {
4117 if ($this->page->theme->get_block_render_method() === 'blocks') {
4118 return $this->blocks($regionname);
4119 } else {
4120 return $this->blocks_for_region($regionname);
4125 * Returns the CSS classes to apply to the body tag.
4127 * @since Moodle 2.5.1 2.6
4128 * @param array $additionalclasses Any additional classes to apply.
4129 * @return string
4131 public function body_css_classes(array $additionalclasses = array()) {
4132 return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses);
4136 * The ID attribute to apply to the body tag.
4138 * @since Moodle 2.5.1 2.6
4139 * @return string
4141 public function body_id() {
4142 return $this->page->bodyid;
4146 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4148 * @since Moodle 2.5.1 2.6
4149 * @param string|array $additionalclasses Any additional classes to give the body tag,
4150 * @return string
4152 public function body_attributes($additionalclasses = array()) {
4153 if (!is_array($additionalclasses)) {
4154 $additionalclasses = explode(' ', $additionalclasses);
4156 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4160 * Gets HTML for the page heading.
4162 * @since Moodle 2.5.1 2.6
4163 * @param string $tag The tag to encase the heading in. h1 by default.
4164 * @return string HTML.
4166 public function page_heading($tag = 'h1') {
4167 return html_writer::tag($tag, $this->page->heading);
4171 * Gets the HTML for the page heading button.
4173 * @since Moodle 2.5.1 2.6
4174 * @return string HTML.
4176 public function page_heading_button() {
4177 return $this->page->button;
4181 * Returns the Moodle docs link to use for this page.
4183 * @since Moodle 2.5.1 2.6
4184 * @param string $text
4185 * @return string
4187 public function page_doc_link($text = null) {
4188 if ($text === null) {
4189 $text = get_string('moodledocslink');
4191 $path = page_get_doc_link_path($this->page);
4192 if (!$path) {
4193 return '';
4195 return $this->doc_link($path, $text);
4199 * Returns the HTML for the site support email link
4201 * @param array $customattribs Array of custom attributes for the support email anchor tag.
4202 * @return string The html code for the support email link.
4204 public function supportemail(array $customattribs = []): string {
4205 global $CFG;
4207 // Do not provide a link to contact site support if it is unavailable to this user. This would be where the site has
4208 // disabled support, or limited it to authenticated users and the current user is a guest or not logged in.
4209 if (!isset($CFG->supportavailability) ||
4210 $CFG->supportavailability == CONTACT_SUPPORT_DISABLED ||
4211 ($CFG->supportavailability == CONTACT_SUPPORT_AUTHENTICATED && (!isloggedin() || isguestuser()))) {
4212 return '';
4215 $label = get_string('contactsitesupport', 'admin');
4216 $icon = $this->pix_icon('t/email', '');
4217 $content = $icon . $label;
4219 if (!empty($CFG->supportpage)) {
4220 $attributes = ['href' => $CFG->supportpage, 'target' => 'blank'];
4221 $content .= $this->pix_icon('i/externallink', '', 'moodle', ['class' => 'ml-1']);
4222 } else {
4223 $attributes = ['href' => $CFG->wwwroot . '/user/contactsitesupport.php'];
4226 $attributes += $customattribs;
4228 return html_writer::tag('a', $content, $attributes);
4232 * Returns the services and support link for the help pop-up.
4234 * @return string
4236 public function services_support_link(): string {
4237 global $CFG;
4239 if (during_initial_install() ||
4240 (isset($CFG->showservicesandsupportcontent) && $CFG->showservicesandsupportcontent == false) ||
4241 !is_siteadmin()) {
4242 return '';
4245 $liferingicon = $this->pix_icon('t/life-ring', '', 'moodle', ['class' => 'fa fa-life-ring']);
4246 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle', ['class' => 'ml-1']);
4247 $link = !empty($CFG->servicespage)
4248 ? $CFG->servicespage
4249 : 'https://moodle.com/help/?utm_source=CTA-banner&utm_medium=platform&utm_campaign=name~Moodle4+cat~lms+mp~no';
4250 $content = $liferingicon . get_string('moodleservicesandsupport') . $newwindowicon;
4252 return html_writer::tag('a', $content, ['target' => '_blank', 'href' => $link]);
4256 * Helper function to decide whether to show the help popover header or not.
4258 * @return bool
4260 public function has_popover_links(): bool {
4261 return !empty($this->services_support_link()) || !empty($this->page_doc_link()) || !empty($this->supportemail());
4265 * Returns the page heading menu.
4267 * @since Moodle 2.5.1 2.6
4268 * @return string HTML.
4270 public function page_heading_menu() {
4271 return $this->page->headingmenu;
4275 * Returns the title to use on the page.
4277 * @since Moodle 2.5.1 2.6
4278 * @return string
4280 public function page_title() {
4281 return $this->page->title;
4285 * Returns the moodle_url for the favicon.
4287 * @since Moodle 2.5.1 2.6
4288 * @return moodle_url The moodle_url for the favicon
4290 public function favicon() {
4291 $logo = null;
4292 if (!during_initial_install()) {
4293 $logo = get_config('core_admin', 'favicon');
4295 if (empty($logo)) {
4296 return $this->image_url('favicon', 'theme');
4299 // Use $CFG->themerev to prevent browser caching when the file changes.
4300 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'favicon', '64x64/',
4301 theme_get_revision(), $logo);
4305 * Renders preferences groups.
4307 * @param preferences_groups $renderable The renderable
4308 * @return string The output.
4310 public function render_preferences_groups(preferences_groups $renderable) {
4311 return $this->render_from_template('core/preferences_groups', $renderable);
4315 * Renders preferences group.
4317 * @param preferences_group $renderable The renderable
4318 * @return string The output.
4320 public function render_preferences_group(preferences_group $renderable) {
4321 $html = '';
4322 $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4323 $html .= $this->heading($renderable->title, 3);
4324 $html .= html_writer::start_tag('ul');
4325 foreach ($renderable->nodes as $node) {
4326 if ($node->has_children()) {
4327 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4329 $html .= html_writer::tag('li', $this->render($node));
4331 $html .= html_writer::end_tag('ul');
4332 $html .= html_writer::end_tag('div');
4333 return $html;
4336 public function context_header($headerinfo = null, $headinglevel = 1) {
4337 global $DB, $USER, $CFG, $SITE;
4338 require_once($CFG->dirroot . '/user/lib.php');
4339 $context = $this->page->context;
4340 $heading = null;
4341 $imagedata = null;
4342 $subheader = null;
4343 $userbuttons = null;
4345 // Make sure to use the heading if it has been set.
4346 if (isset($headerinfo['heading'])) {
4347 $heading = $headerinfo['heading'];
4348 } else {
4349 $heading = $this->page->heading;
4352 // The user context currently has images and buttons. Other contexts may follow.
4353 if ((isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) && $this->page->pagetype !== 'my-index') {
4354 if (isset($headerinfo['user'])) {
4355 $user = $headerinfo['user'];
4356 } else {
4357 // Look up the user information if it is not supplied.
4358 $user = $DB->get_record('user', array('id' => $context->instanceid));
4361 // If the user context is set, then use that for capability checks.
4362 if (isset($headerinfo['usercontext'])) {
4363 $context = $headerinfo['usercontext'];
4366 // Only provide user information if the user is the current user, or a user which the current user can view.
4367 // When checking user_can_view_profile(), either:
4368 // If the page context is course, check the course context (from the page object) or;
4369 // If page context is NOT course, then check across all courses.
4370 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4372 if (user_can_view_profile($user, $course)) {
4373 // Use the user's full name if the heading isn't set.
4374 if (empty($heading)) {
4375 $heading = fullname($user);
4378 $imagedata = $this->user_picture($user, array('size' => 100));
4380 // Check to see if we should be displaying a message button.
4381 if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
4382 $userbuttons = array(
4383 'messages' => array(
4384 'buttontype' => 'message',
4385 'title' => get_string('message', 'message'),
4386 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4387 'image' => 'message',
4388 'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
4389 'page' => $this->page
4393 if ($USER->id != $user->id) {
4394 $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4395 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4396 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4397 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4398 $userbuttons['togglecontact'] = array(
4399 'buttontype' => 'togglecontact',
4400 'title' => get_string($contacttitle, 'message'),
4401 'url' => new moodle_url('/message/index.php', array(
4402 'user1' => $USER->id,
4403 'user2' => $user->id,
4404 $contacturlaction => $user->id,
4405 'sesskey' => sesskey())
4407 'image' => $contactimage,
4408 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4409 'page' => $this->page
4413 } else {
4414 $heading = null;
4419 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4420 return $this->render_context_header($contextheader);
4424 * Renders the skip links for the page.
4426 * @param array $links List of skip links.
4427 * @return string HTML for the skip links.
4429 public function render_skip_links($links) {
4430 $context = [ 'links' => []];
4432 foreach ($links as $url => $text) {
4433 $context['links'][] = [ 'url' => $url, 'text' => $text];
4436 return $this->render_from_template('core/skip_links', $context);
4440 * Renders the header bar.
4442 * @param context_header $contextheader Header bar object.
4443 * @return string HTML for the header bar.
4445 protected function render_context_header(context_header $contextheader) {
4447 // Generate the heading first and before everything else as we might have to do an early return.
4448 if (!isset($contextheader->heading)) {
4449 $heading = $this->heading($this->page->heading, $contextheader->headinglevel);
4450 } else {
4451 $heading = $this->heading($contextheader->heading, $contextheader->headinglevel);
4454 $showheader = empty($this->page->layout_options['nocontextheader']);
4455 if (!$showheader) {
4456 // Return the heading wrapped in an sr-only element so it is only visible to screen-readers.
4457 return html_writer::div($heading, 'sr-only');
4460 // All the html stuff goes here.
4461 $html = html_writer::start_div('page-context-header');
4463 // Image data.
4464 if (isset($contextheader->imagedata)) {
4465 // Header specific image.
4466 $html .= html_writer::div($contextheader->imagedata, 'page-header-image icon-size-7');
4469 // Headings.
4470 if (isset($contextheader->prefix)) {
4471 $prefix = html_writer::div($contextheader->prefix, 'text-muted');
4472 $heading = $prefix . $heading;
4474 $html .= html_writer::tag('div', $heading, array('class' => 'page-header-headings'));
4476 // Buttons.
4477 if (isset($contextheader->additionalbuttons)) {
4478 $html .= html_writer::start_div('btn-group header-button-group');
4479 foreach ($contextheader->additionalbuttons as $button) {
4480 if (!isset($button->page)) {
4481 // Include js for messaging.
4482 if ($button['buttontype'] === 'togglecontact') {
4483 \core_message\helper::togglecontact_requirejs();
4485 if ($button['buttontype'] === 'message') {
4486 \core_message\helper::messageuser_requirejs();
4488 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4489 'class' => 'iconsmall',
4490 'role' => 'presentation'
4492 $image .= html_writer::span($button['title'], 'header-button-title');
4493 } else {
4494 $image = html_writer::empty_tag('img', array(
4495 'src' => $button['formattedimage'],
4496 'role' => 'presentation'
4499 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4501 $html .= html_writer::end_div();
4503 $html .= html_writer::end_div();
4505 return $html;
4509 * Wrapper for header elements.
4511 * @return string HTML to display the main header.
4513 public function full_header() {
4514 $pagetype = $this->page->pagetype;
4515 $homepage = get_home_page();
4516 $homepagetype = null;
4517 // Add a special case since /my/courses is a part of the /my subsystem.
4518 if ($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES) {
4519 $homepagetype = 'my-index';
4520 } else if ($homepage == HOMEPAGE_SITE) {
4521 $homepagetype = 'site-index';
4523 if ($this->page->include_region_main_settings_in_header_actions() &&
4524 !$this->page->blocks->is_block_present('settings')) {
4525 // Only include the region main settings if the page has requested it and it doesn't already have
4526 // the settings block on it. The region main settings are included in the settings block and
4527 // duplicating the content causes behat failures.
4528 $this->page->add_header_action(html_writer::div(
4529 $this->region_main_settings_menu(),
4530 'd-print-none',
4531 ['id' => 'region-main-settings-menu']
4535 $header = new stdClass();
4536 $header->settingsmenu = $this->context_header_settings_menu();
4537 $header->contextheader = $this->context_header();
4538 $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
4539 $header->navbar = $this->navbar();
4540 $header->pageheadingbutton = $this->page_heading_button();
4541 $header->courseheader = $this->course_header();
4542 $header->headeractions = $this->page->get_header_actions();
4543 if (!empty($pagetype) && !empty($homepagetype) && $pagetype == $homepagetype) {
4544 $header->welcomemessage = \core_user::welcome_message();
4546 return $this->render_from_template('core/full_header', $header);
4550 * This is an optional menu that can be added to a layout by a theme. It contains the
4551 * menu for the course administration, only on the course main page.
4553 * @return string
4555 public function context_header_settings_menu() {
4556 $context = $this->page->context;
4557 $menu = new action_menu();
4559 $items = $this->page->navbar->get_items();
4560 $currentnode = end($items);
4562 $showcoursemenu = false;
4563 $showfrontpagemenu = false;
4564 $showusermenu = false;
4566 // We are on the course home page.
4567 if (($context->contextlevel == CONTEXT_COURSE) &&
4568 !empty($currentnode) &&
4569 ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
4570 $showcoursemenu = true;
4573 $courseformat = course_get_format($this->page->course);
4574 // This is a single activity course format, always show the course menu on the activity main page.
4575 if ($context->contextlevel == CONTEXT_MODULE &&
4576 !$courseformat->has_view_page()) {
4578 $this->page->navigation->initialise();
4579 $activenode = $this->page->navigation->find_active_node();
4580 // If the settings menu has been forced then show the menu.
4581 if ($this->page->is_settings_menu_forced()) {
4582 $showcoursemenu = true;
4583 } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
4584 $activenode->type == navigation_node::TYPE_RESOURCE)) {
4586 // We only want to show the menu on the first page of the activity. This means
4587 // the breadcrumb has no additional nodes.
4588 if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
4589 $showcoursemenu = true;
4594 // This is the site front page.
4595 if ($context->contextlevel == CONTEXT_COURSE &&
4596 !empty($currentnode) &&
4597 $currentnode->key === 'home') {
4598 $showfrontpagemenu = true;
4601 // This is the user profile page.
4602 if ($context->contextlevel == CONTEXT_USER &&
4603 !empty($currentnode) &&
4604 ($currentnode->key === 'myprofile')) {
4605 $showusermenu = true;
4608 if ($showfrontpagemenu) {
4609 $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
4610 if ($settingsnode) {
4611 // Build an action menu based on the visible nodes from this navigation tree.
4612 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4614 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4615 if ($skipped) {
4616 $text = get_string('morenavigationlinks');
4617 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4618 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4619 $menu->add_secondary_action($link);
4622 } else if ($showcoursemenu) {
4623 $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
4624 if ($settingsnode) {
4625 // Build an action menu based on the visible nodes from this navigation tree.
4626 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4628 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4629 if ($skipped) {
4630 $text = get_string('morenavigationlinks');
4631 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4632 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4633 $menu->add_secondary_action($link);
4636 } else if ($showusermenu) {
4637 // Get the course admin node from the settings navigation.
4638 $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
4639 if ($settingsnode) {
4640 // Build an action menu based on the visible nodes from this navigation tree.
4641 $this->build_action_menu_from_navigation($menu, $settingsnode);
4645 return $this->render($menu);
4649 * Take a node in the nav tree and make an action menu out of it.
4650 * The links are injected in the action menu.
4652 * @param action_menu $menu
4653 * @param navigation_node $node
4654 * @param boolean $indent
4655 * @param boolean $onlytopleafnodes
4656 * @return boolean nodesskipped - True if nodes were skipped in building the menu
4658 protected function build_action_menu_from_navigation(action_menu $menu,
4659 navigation_node $node,
4660 $indent = false,
4661 $onlytopleafnodes = false) {
4662 $skipped = false;
4663 // Build an action menu based on the visible nodes from this navigation tree.
4664 foreach ($node->children as $menuitem) {
4665 if ($menuitem->display) {
4666 if ($onlytopleafnodes && $menuitem->children->count()) {
4667 $skipped = true;
4668 continue;
4670 if ($menuitem->action) {
4671 if ($menuitem->action instanceof action_link) {
4672 $link = $menuitem->action;
4673 // Give preference to setting icon over action icon.
4674 if (!empty($menuitem->icon)) {
4675 $link->icon = $menuitem->icon;
4677 } else {
4678 $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
4680 } else {
4681 if ($onlytopleafnodes) {
4682 $skipped = true;
4683 continue;
4685 $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
4687 if ($indent) {
4688 $link->add_class('ml-4');
4690 if (!empty($menuitem->classes)) {
4691 $link->add_class(implode(" ", $menuitem->classes));
4694 $menu->add_secondary_action($link);
4695 $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
4698 return $skipped;
4702 * This is an optional menu that can be added to a layout by a theme. It contains the
4703 * menu for the most specific thing from the settings block. E.g. Module administration.
4705 * @return string
4707 public function region_main_settings_menu() {
4708 $context = $this->page->context;
4709 $menu = new action_menu();
4711 if ($context->contextlevel == CONTEXT_MODULE) {
4713 $this->page->navigation->initialise();
4714 $node = $this->page->navigation->find_active_node();
4715 $buildmenu = false;
4716 // If the settings menu has been forced then show the menu.
4717 if ($this->page->is_settings_menu_forced()) {
4718 $buildmenu = true;
4719 } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
4720 $node->type == navigation_node::TYPE_RESOURCE)) {
4722 $items = $this->page->navbar->get_items();
4723 $navbarnode = end($items);
4724 // We only want to show the menu on the first page of the activity. This means
4725 // the breadcrumb has no additional nodes.
4726 if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
4727 $buildmenu = true;
4730 if ($buildmenu) {
4731 // Get the course admin node from the settings navigation.
4732 $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
4733 if ($node) {
4734 // Build an action menu based on the visible nodes from this navigation tree.
4735 $this->build_action_menu_from_navigation($menu, $node);
4739 } else if ($context->contextlevel == CONTEXT_COURSECAT) {
4740 // For course category context, show category settings menu, if we're on the course category page.
4741 if ($this->page->pagetype === 'course-index-category') {
4742 $node = $this->page->settingsnav->find('categorysettings', navigation_node::TYPE_CONTAINER);
4743 if ($node) {
4744 // Build an action menu based on the visible nodes from this navigation tree.
4745 $this->build_action_menu_from_navigation($menu, $node);
4749 } else {
4750 $items = $this->page->navbar->get_items();
4751 $navbarnode = end($items);
4753 if ($navbarnode && ($navbarnode->key === 'participants')) {
4754 $node = $this->page->settingsnav->find('users', navigation_node::TYPE_CONTAINER);
4755 if ($node) {
4756 // Build an action menu based on the visible nodes from this navigation tree.
4757 $this->build_action_menu_from_navigation($menu, $node);
4762 return $this->render($menu);
4766 * Displays the list of tags associated with an entry
4768 * @param array $tags list of instances of core_tag or stdClass
4769 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4770 * to use default, set to '' (empty string) to omit the label completely
4771 * @param string $classes additional classes for the enclosing div element
4772 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4773 * will be appended to the end, JS will toggle the rest of the tags
4774 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4775 * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
4776 * @return string
4778 public function tag_list($tags, $label = null, $classes = '', $limit = 10,
4779 $pagecontext = null, $accesshidelabel = false) {
4780 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
4781 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4785 * Renders element for inline editing of any value
4787 * @param \core\output\inplace_editable $element
4788 * @return string
4790 public function render_inplace_editable(\core\output\inplace_editable $element) {
4791 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4795 * Renders a bar chart.
4797 * @param \core\chart_bar $chart The chart.
4798 * @return string.
4800 public function render_chart_bar(\core\chart_bar $chart) {
4801 return $this->render_chart($chart);
4805 * Renders a line chart.
4807 * @param \core\chart_line $chart The chart.
4808 * @return string.
4810 public function render_chart_line(\core\chart_line $chart) {
4811 return $this->render_chart($chart);
4815 * Renders a pie chart.
4817 * @param \core\chart_pie $chart The chart.
4818 * @return string.
4820 public function render_chart_pie(\core\chart_pie $chart) {
4821 return $this->render_chart($chart);
4825 * Renders a chart.
4827 * @param \core\chart_base $chart The chart.
4828 * @param bool $withtable Whether to include a data table with the chart.
4829 * @return string.
4831 public function render_chart(\core\chart_base $chart, $withtable = true) {
4832 $chartdata = json_encode($chart);
4833 return $this->render_from_template('core/chart', (object) [
4834 'chartdata' => $chartdata,
4835 'withtable' => $withtable
4840 * Renders the login form.
4842 * @param \core_auth\output\login $form The renderable.
4843 * @return string
4845 public function render_login(\core_auth\output\login $form) {
4846 global $CFG, $SITE;
4848 $context = $form->export_for_template($this);
4850 $context->errorformatted = $this->error_text($context->error);
4851 $url = $this->get_logo_url();
4852 if ($url) {
4853 $url = $url->out(false);
4855 $context->logourl = $url;
4856 $context->sitename = format_string($SITE->fullname, true,
4857 ['context' => context_course::instance(SITEID), "escape" => false]);
4859 return $this->render_from_template('core/loginform', $context);
4863 * Renders an mform element from a template.
4865 * @param HTML_QuickForm_element $element element
4866 * @param bool $required if input is required field
4867 * @param bool $advanced if input is an advanced field
4868 * @param string $error error message to display
4869 * @param bool $ingroup True if this element is rendered as part of a group
4870 * @return mixed string|bool
4872 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4873 $templatename = 'core_form/element-' . $element->getType();
4874 if ($ingroup) {
4875 $templatename .= "-inline";
4877 try {
4878 // We call this to generate a file not found exception if there is no template.
4879 // We don't want to call export_for_template if there is no template.
4880 core\output\mustache_template_finder::get_template_filepath($templatename);
4882 if ($element instanceof templatable) {
4883 $elementcontext = $element->export_for_template($this);
4885 $helpbutton = '';
4886 if (method_exists($element, 'getHelpButton')) {
4887 $helpbutton = $element->getHelpButton();
4889 $label = $element->getLabel();
4890 $text = '';
4891 if (method_exists($element, 'getText')) {
4892 // There currently exists code that adds a form element with an empty label.
4893 // If this is the case then set the label to the description.
4894 if (empty($label)) {
4895 $label = $element->getText();
4896 } else {
4897 $text = $element->getText();
4901 // Generate the form element wrapper ids and names to pass to the template.
4902 // This differs between group and non-group elements.
4903 if ($element->getType() === 'group') {
4904 // Group element.
4905 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
4906 $elementcontext['wrapperid'] = $elementcontext['id'];
4908 // Ensure group elements pass through the group name as the element name.
4909 $elementcontext['name'] = $elementcontext['groupname'];
4910 } else {
4911 // Non grouped element.
4912 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
4913 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
4916 $context = array(
4917 'element' => $elementcontext,
4918 'label' => $label,
4919 'text' => $text,
4920 'required' => $required,
4921 'advanced' => $advanced,
4922 'helpbutton' => $helpbutton,
4923 'error' => $error
4925 return $this->render_from_template($templatename, $context);
4927 } catch (Exception $e) {
4928 // No template for this element.
4929 return false;
4934 * Render the login signup form into a nice template for the theme.
4936 * @param mform $form
4937 * @return string
4939 public function render_login_signup_form($form) {
4940 global $SITE;
4942 $context = $form->export_for_template($this);
4943 $url = $this->get_logo_url();
4944 if ($url) {
4945 $url = $url->out(false);
4947 $context['logourl'] = $url;
4948 $context['sitename'] = format_string($SITE->fullname, true,
4949 ['context' => context_course::instance(SITEID), "escape" => false]);
4951 return $this->render_from_template('core/signup_form_layout', $context);
4955 * Render the verify age and location page into a nice template for the theme.
4957 * @param \core_auth\output\verify_age_location_page $page The renderable
4958 * @return string
4960 protected function render_verify_age_location_page($page) {
4961 $context = $page->export_for_template($this);
4963 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4967 * Render the digital minor contact information page into a nice template for the theme.
4969 * @param \core_auth\output\digital_minor_page $page The renderable
4970 * @return string
4972 protected function render_digital_minor_page($page) {
4973 $context = $page->export_for_template($this);
4975 return $this->render_from_template('core/auth_digital_minor_page', $context);
4979 * Renders a progress bar.
4981 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4983 * @param progress_bar $bar The bar.
4984 * @return string HTML fragment
4986 public function render_progress_bar(progress_bar $bar) {
4987 $data = $bar->export_for_template($this);
4988 return $this->render_from_template('core/progress_bar', $data);
4992 * Renders an update to a progress bar.
4994 * Note: This does not cleanly map to a renderable class and should
4995 * never be used directly.
4997 * @param string $id
4998 * @param float $percent
4999 * @param string $msg Message
5000 * @param string $estimate time remaining message
5001 * @return string ascii fragment
5003 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
5004 return html_writer::script(js_writer::function_call('updateProgressBar', [$id, $percent, $msg, $estimate]));
5008 * Renders element for a toggle-all checkbox.
5010 * @param \core\output\checkbox_toggleall $element
5011 * @return string
5013 public function render_checkbox_toggleall(\core\output\checkbox_toggleall $element) {
5014 return $this->render_from_template($element->get_template(), $element->export_for_template($this));
5018 * Renders the tertiary nav for the participants page
5020 * @param object $course The course we are operating within
5021 * @param string|null $renderedbuttons Any additional buttons/content to be displayed in line with the nav
5022 * @return string
5024 public function render_participants_tertiary_nav(object $course, ?string $renderedbuttons = null) {
5025 $actionbar = new \core\output\participants_action_bar($course, $this->page, $renderedbuttons);
5026 $content = $this->render_from_template('core_course/participants_actionbar', $actionbar->export_for_template($this));
5027 return $content ?: "";
5031 * Renders release information in the footer popup
5032 * @return string Moodle release info.
5034 public function moodle_release() {
5035 global $CFG;
5036 if (!during_initial_install() && is_siteadmin()) {
5037 return $CFG->release;
5042 * Generate the add block button when editing mode is turned on and the user can edit blocks.
5044 * @param string $region where new blocks should be added.
5045 * @return string html for the add block button.
5047 public function addblockbutton($region = ''): string {
5048 $addblockbutton = '';
5049 $regions = $this->page->blocks->get_regions();
5050 if (count($regions) == 0) {
5051 return '';
5053 if (isset($this->page->theme->addblockposition) &&
5054 $this->page->user_is_editing() &&
5055 $this->page->user_can_edit_blocks() &&
5056 $this->page->pagelayout !== 'mycourses'
5058 $params = ['bui_addblock' => '', 'sesskey' => sesskey()];
5059 if (!empty($region)) {
5060 $params['bui_blockregion'] = $region;
5062 $url = new moodle_url($this->page->url, $params);
5063 $addblockbutton = $this->render_from_template('core/add_block_button',
5065 'link' => $url->out(false),
5066 'escapedlink' => "?{$url->get_query_string(false)}",
5067 'pageType' => $this->page->pagetype,
5068 'pageLayout' => $this->page->pagelayout,
5069 'subPage' => $this->page->subpage,
5073 return $addblockbutton;
5078 * A renderer that generates output for command-line scripts.
5080 * The implementation of this renderer is probably incomplete.
5082 * @copyright 2009 Tim Hunt
5083 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5084 * @since Moodle 2.0
5085 * @package core
5086 * @category output
5088 class core_renderer_cli extends core_renderer {
5091 * @var array $progressmaximums stores the largest percentage for a progress bar.
5092 * @return string ascii fragment
5094 private $progressmaximums = [];
5097 * Returns the page header.
5099 * @return string HTML fragment
5101 public function header() {
5102 return $this->page->heading . "\n";
5106 * Renders a Check API result
5108 * To aid in CLI consistency this status is NOT translated and the visual
5109 * width is always exactly 10 chars.
5111 * @param core\check\result $result
5112 * @return string HTML fragment
5114 protected function render_check_result(core\check\result $result) {
5115 $status = $result->get_status();
5117 $labels = [
5118 core\check\result::NA => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' NA ',
5119 core\check\result::OK => ' ' . cli_ansi_format('<colour:green>') . ' OK ',
5120 core\check\result::INFO => ' ' . cli_ansi_format('<colour:blue>' ) . ' INFO ',
5121 core\check\result::UNKNOWN => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' UNKNOWN ',
5122 core\check\result::WARNING => ' ' . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
5123 core\check\result::ERROR => ' ' . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
5124 core\check\result::CRITICAL => '' . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
5126 $string = $labels[$status] . cli_ansi_format('<colour:normal>');
5127 return $string;
5131 * Renders a Check API result
5133 * @param result $result
5134 * @return string fragment
5136 public function check_result(core\check\result $result) {
5137 return $this->render_check_result($result);
5141 * Renders a progress bar.
5143 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
5145 * @param progress_bar $bar The bar.
5146 * @return string ascii fragment
5148 public function render_progress_bar(progress_bar $bar) {
5149 global $CFG;
5151 $size = 55; // The width of the progress bar in chars.
5152 $ascii = "\n";
5154 if (stream_isatty(STDOUT)) {
5155 require_once($CFG->libdir.'/clilib.php');
5157 $ascii .= "[" . str_repeat(' ', $size) . "] 0% \n";
5158 return cli_ansi_format($ascii);
5161 $this->progressmaximums[$bar->get_id()] = 0;
5162 $ascii .= '[';
5163 return $ascii;
5167 * Renders an update to a progress bar.
5169 * Note: This does not cleanly map to a renderable class and should
5170 * never be used directly.
5172 * @param string $id
5173 * @param float $percent
5174 * @param string $msg Message
5175 * @param string $estimate time remaining message
5176 * @return string ascii fragment
5178 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
5179 $size = 55; // The width of the progress bar in chars.
5180 $ascii = '';
5182 // If we are rendering to a terminal then we can safely use ansii codes
5183 // to move the cursor and redraw the complete progress bar each time
5184 // it is updated.
5185 if (stream_isatty(STDOUT)) {
5186 $colour = $percent == 100 ? 'green' : 'blue';
5188 $done = $percent * $size * 0.01;
5189 $whole = floor($done);
5190 $bar = "<colour:$colour>";
5191 $bar .= str_repeat('█', $whole);
5193 if ($whole < $size) {
5194 // By using unicode chars for partial blocks we can have higher
5195 // precision progress bar.
5196 $fraction = floor(($done - $whole) * 8);
5197 $bar .= core_text::substr(' ▏▎▍▌▋▊▉', $fraction, 1);
5199 // Fill the rest of the empty bar.
5200 $bar .= str_repeat(' ', $size - $whole - 1);
5203 $bar .= '<colour:normal>';
5205 if ($estimate) {
5206 $estimate = "- $estimate";
5209 $ascii .= '<cursor:up>';
5210 $ascii .= '<cursor:up>';
5211 $ascii .= sprintf("[$bar] %3.1f%% %-22s\n", $percent, $estimate);
5212 $ascii .= sprintf("%-80s\n", $msg);
5213 return cli_ansi_format($ascii);
5216 // If we are not rendering to a tty, ie when piped to another command
5217 // or on windows we need to progressively render the progress bar
5218 // which can only ever go forwards.
5219 $done = round($percent * $size * 0.01);
5220 $delta = max(0, $done - $this->progressmaximums[$id]);
5222 $ascii .= str_repeat('#', $delta);
5223 if ($percent >= 100 && $delta > 0) {
5224 $ascii .= sprintf("] %3.1f%%\n$msg\n", $percent);
5226 $this->progressmaximums[$id] += $delta;
5227 return $ascii;
5231 * Returns a template fragment representing a Heading.
5233 * @param string $text The text of the heading
5234 * @param int $level The level of importance of the heading
5235 * @param string $classes A space-separated list of CSS classes
5236 * @param string $id An optional ID
5237 * @return string A template fragment for a heading
5239 public function heading($text, $level = 2, $classes = 'main', $id = null) {
5240 $text .= "\n";
5241 switch ($level) {
5242 case 1:
5243 return '=>' . $text;
5244 case 2:
5245 return '-->' . $text;
5246 default:
5247 return $text;
5252 * Returns a template fragment representing a fatal error.
5254 * @param string $message The message to output
5255 * @param string $moreinfourl URL where more info can be found about the error
5256 * @param string $link Link for the Continue button
5257 * @param array $backtrace The execution backtrace
5258 * @param string $debuginfo Debugging information
5259 * @return string A template fragment for a fatal error
5261 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5262 global $CFG;
5264 $output = "!!! $message !!!\n";
5266 if ($CFG->debugdeveloper) {
5267 if (!empty($debuginfo)) {
5268 $output .= $this->notification($debuginfo, 'notifytiny');
5270 if (!empty($backtrace)) {
5271 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
5275 return $output;
5279 * Returns a template fragment representing a notification.
5281 * @param string $message The message to print out.
5282 * @param string $type The type of notification. See constants on \core\output\notification.
5283 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5284 * @return string A template fragment for a notification
5286 public function notification($message, $type = null, $closebutton = true) {
5287 $message = clean_text($message);
5288 if ($type === 'notifysuccess' || $type === 'success') {
5289 return "++ $message ++\n";
5291 return "!! $message !!\n";
5295 * There is no footer for a cli request, however we must override the
5296 * footer method to prevent the default footer.
5298 public function footer() {}
5301 * Render a notification (that is, a status message about something that has
5302 * just happened).
5304 * @param \core\output\notification $notification the notification to print out
5305 * @return string plain text output
5307 public function render_notification(\core\output\notification $notification) {
5308 return $this->notification($notification->get_message(), $notification->get_message_type());
5314 * A renderer that generates output for ajax scripts.
5316 * This renderer prevents accidental sends back only json
5317 * encoded error messages, all other output is ignored.
5319 * @copyright 2010 Petr Skoda
5320 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5321 * @since Moodle 2.0
5322 * @package core
5323 * @category output
5325 class core_renderer_ajax extends core_renderer {
5328 * Returns a template fragment representing a fatal error.
5330 * @param string $message The message to output
5331 * @param string $moreinfourl URL where more info can be found about the error
5332 * @param string $link Link for the Continue button
5333 * @param array $backtrace The execution backtrace
5334 * @param string $debuginfo Debugging information
5335 * @return string A template fragment for a fatal error
5337 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5338 global $CFG;
5340 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
5342 $e = new stdClass();
5343 $e->error = $message;
5344 $e->errorcode = $errorcode;
5345 $e->stacktrace = NULL;
5346 $e->debuginfo = NULL;
5347 $e->reproductionlink = NULL;
5348 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
5349 $link = (string) $link;
5350 if ($link) {
5351 $e->reproductionlink = $link;
5353 if (!empty($debuginfo)) {
5354 $e->debuginfo = $debuginfo;
5356 if (!empty($backtrace)) {
5357 $e->stacktrace = format_backtrace($backtrace, true);
5360 $this->header();
5361 return json_encode($e);
5365 * Used to display a notification.
5366 * For the AJAX notifications are discarded.
5368 * @param string $message The message to print out.
5369 * @param string $type The type of notification. See constants on \core\output\notification.
5370 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5372 public function notification($message, $type = null, $closebutton = true) {
5376 * Used to display a redirection message.
5377 * AJAX redirections should not occur and as such redirection messages
5378 * are discarded.
5380 * @param moodle_url|string $encodedurl
5381 * @param string $message
5382 * @param int $delay
5383 * @param bool $debugdisableredirect
5384 * @param string $messagetype The type of notification to show the message in.
5385 * See constants on \core\output\notification.
5387 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
5388 $messagetype = \core\output\notification::NOTIFY_INFO) {}
5391 * Prepares the start of an AJAX output.
5393 public function header() {
5394 // unfortunately YUI iframe upload does not support application/json
5395 if (!empty($_FILES)) {
5396 @header('Content-type: text/plain; charset=utf-8');
5397 if (!core_useragent::supports_json_contenttype()) {
5398 @header('X-Content-Type-Options: nosniff');
5400 } else if (!core_useragent::supports_json_contenttype()) {
5401 @header('Content-type: text/plain; charset=utf-8');
5402 @header('X-Content-Type-Options: nosniff');
5403 } else {
5404 @header('Content-type: application/json; charset=utf-8');
5407 // Headers to make it not cacheable and json
5408 @header('Cache-Control: no-store, no-cache, must-revalidate');
5409 @header('Cache-Control: post-check=0, pre-check=0', false);
5410 @header('Pragma: no-cache');
5411 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
5412 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
5413 @header('Accept-Ranges: none');
5417 * There is no footer for an AJAX request, however we must override the
5418 * footer method to prevent the default footer.
5420 public function footer() {}
5423 * No need for headers in an AJAX request... this should never happen.
5424 * @param string $text
5425 * @param int $level
5426 * @param string $classes
5427 * @param string $id
5429 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
5435 * The maintenance renderer.
5437 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
5438 * is running a maintenance related task.
5439 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
5441 * @since Moodle 2.6
5442 * @package core
5443 * @category output
5444 * @copyright 2013 Sam Hemelryk
5445 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5447 class core_renderer_maintenance extends core_renderer {
5450 * Initialises the renderer instance.
5452 * @param moodle_page $page
5453 * @param string $target
5454 * @throws coding_exception
5456 public function __construct(moodle_page $page, $target) {
5457 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
5458 throw new coding_exception('Invalid request for the maintenance renderer.');
5460 parent::__construct($page, $target);
5464 * Does nothing. The maintenance renderer cannot produce blocks.
5466 * @param block_contents $bc
5467 * @param string $region
5468 * @return string
5470 public function block(block_contents $bc, $region) {
5471 return '';
5475 * Does nothing. The maintenance renderer cannot produce blocks.
5477 * @param string $region
5478 * @param array $classes
5479 * @param string $tag
5480 * @param boolean $fakeblocksonly
5481 * @return string
5483 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
5484 return '';
5488 * Does nothing. The maintenance renderer cannot produce blocks.
5490 * @param string $region
5491 * @param boolean $fakeblocksonly Output fake block only.
5492 * @return string
5494 public function blocks_for_region($region, $fakeblocksonly = false) {
5495 return '';
5499 * Does nothing. The maintenance renderer cannot produce a course content header.
5501 * @param bool $onlyifnotcalledbefore
5502 * @return string
5504 public function course_content_header($onlyifnotcalledbefore = false) {
5505 return '';
5509 * Does nothing. The maintenance renderer cannot produce a course content footer.
5511 * @param bool $onlyifnotcalledbefore
5512 * @return string
5514 public function course_content_footer($onlyifnotcalledbefore = false) {
5515 return '';
5519 * Does nothing. The maintenance renderer cannot produce a course header.
5521 * @return string
5523 public function course_header() {
5524 return '';
5528 * Does nothing. The maintenance renderer cannot produce a course footer.
5530 * @return string
5532 public function course_footer() {
5533 return '';
5537 * Does nothing. The maintenance renderer cannot produce a custom menu.
5539 * @param string $custommenuitems
5540 * @return string
5542 public function custom_menu($custommenuitems = '') {
5543 return '';
5547 * Does nothing. The maintenance renderer cannot produce a file picker.
5549 * @param array $options
5550 * @return string
5552 public function file_picker($options) {
5553 return '';
5557 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
5559 * @param array $dir
5560 * @return string
5562 public function htmllize_file_tree($dir) {
5563 return '';
5568 * Overridden confirm message for upgrades.
5570 * @param string $message The question to ask the user
5571 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5572 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5573 * @param array $displayoptions optional extra display options
5574 * @return string HTML fragment
5576 public function confirm($message, $continue, $cancel, array $displayoptions = []) {
5577 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5578 // from any previous version of Moodle).
5579 if ($continue instanceof single_button) {
5580 $continue->type = single_button::BUTTON_PRIMARY;
5581 } else if (is_string($continue)) {
5582 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post',
5583 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
5584 } else if ($continue instanceof moodle_url) {
5585 $continue = new single_button($continue, get_string('continue'), 'post',
5586 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
5587 } else {
5588 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5589 ' (string/moodle_url) or a single_button instance.');
5592 if ($cancel instanceof single_button) {
5593 $output = '';
5594 } else if (is_string($cancel)) {
5595 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5596 } else if ($cancel instanceof moodle_url) {
5597 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5598 } else {
5599 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5600 ' (string/moodle_url) or a single_button instance.');
5603 $output = $this->box_start('generalbox', 'notice');
5604 $output .= html_writer::tag('h4', get_string('confirm'));
5605 $output .= html_writer::tag('p', $message);
5606 $output .= html_writer::tag('div', $this->render($cancel) . $this->render($continue), ['class' => 'buttons']);
5607 $output .= $this->box_end();
5608 return $output;
5612 * Does nothing. The maintenance renderer does not support JS.
5614 * @param block_contents $bc
5616 public function init_block_hider_js(block_contents $bc) {
5617 // Does nothing.
5621 * Does nothing. The maintenance renderer cannot produce language menus.
5623 * @return string
5625 public function lang_menu() {
5626 return '';
5630 * Does nothing. The maintenance renderer has no need for login information.
5632 * @param null $withlinks
5633 * @return string
5635 public function login_info($withlinks = null) {
5636 return '';
5640 * Secure login info.
5642 * @return string
5644 public function secure_login_info() {
5645 return $this->login_info(false);
5649 * Does nothing. The maintenance renderer cannot produce user pictures.
5651 * @param stdClass $user
5652 * @param array $options
5653 * @return string
5655 public function user_picture(stdClass $user, array $options = null) {
5656 return '';