Merge branch 'MDL-74802-400-2' of https://github.com/junpataleta/moodle into MOODLE_4...
[moodle.git] / lib / outputrenderers.php
blobf379e2e44fdf01904c85ba6827332e549d866342
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
21 * for an overview.
23 * Included in this file are the primary renderer classes:
24 * - renderer_base: The renderer outline class that all renderers
25 * should inherit from.
26 * - core_renderer: The standard HTML renderer.
27 * - core_renderer_cli: An adaption of the standard renderer for CLI scripts.
28 * - core_renderer_ajax: An adaption of the standard renderer for AJAX scripts.
29 * - plugin_renderer_base: A renderer class that should be extended by all
30 * plugin renderers.
32 * @package core
33 * @category output
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 use core\output\named_templatable;
39 use core_completion\cm_completion_details;
40 use core_course\output\activity_information;
42 defined('MOODLE_INTERNAL') || die();
44 /**
45 * Simple base class for Moodle renderers.
47 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
49 * Also has methods to facilitate generating HTML output.
51 * @copyright 2009 Tim Hunt
52 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 * @since Moodle 2.0
54 * @package core
55 * @category output
57 class renderer_base {
58 /**
59 * @var xhtml_container_stack The xhtml_container_stack to use.
61 protected $opencontainers;
63 /**
64 * @var moodle_page The Moodle page the renderer has been created to assist with.
66 protected $page;
68 /**
69 * @var string The requested rendering target.
71 protected $target;
73 /**
74 * @var Mustache_Engine $mustache The mustache template compiler
76 private $mustache;
78 /**
79 * Return an instance of the mustache class.
81 * @since 2.9
82 * @return Mustache_Engine
84 protected function get_mustache() {
85 global $CFG;
87 if ($this->mustache === null) {
88 require_once("{$CFG->libdir}/filelib.php");
90 $themename = $this->page->theme->name;
91 $themerev = theme_get_revision();
93 // Create new localcache directory.
94 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
96 // Remove old localcache directories.
97 $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR);
98 foreach ($mustachecachedirs as $localcachedir) {
99 $cachedrev = [];
100 preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
101 $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
102 if ($cachedrev > 0 && $cachedrev < $themerev) {
103 fulldelete($localcachedir);
107 $loader = new \core\output\mustache_filesystem_loader();
108 $stringhelper = new \core\output\mustache_string_helper();
109 $cleanstringhelper = new \core\output\mustache_clean_string_helper();
110 $quotehelper = new \core\output\mustache_quote_helper();
111 $jshelper = new \core\output\mustache_javascript_helper($this->page);
112 $pixhelper = new \core\output\mustache_pix_helper($this);
113 $shortentexthelper = new \core\output\mustache_shorten_text_helper();
114 $userdatehelper = new \core\output\mustache_user_date_helper();
116 // We only expose the variables that are exposed to JS templates.
117 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
119 $helpers = array('config' => $safeconfig,
120 'str' => array($stringhelper, 'str'),
121 'cleanstr' => array($cleanstringhelper, 'cleanstr'),
122 'quote' => array($quotehelper, 'quote'),
123 'js' => array($jshelper, 'help'),
124 'pix' => array($pixhelper, 'pix'),
125 'shortentext' => array($shortentexthelper, 'shorten'),
126 'userdate' => array($userdatehelper, 'transform'),
129 $this->mustache = new \core\output\mustache_engine(array(
130 'cache' => $cachedir,
131 'escape' => 's',
132 'loader' => $loader,
133 'helpers' => $helpers,
134 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS],
135 // Don't allow the JavaScript helper to be executed from within another
136 // helper. If it's allowed it can be used by users to inject malicious
137 // JS into the page.
138 'disallowednestedhelpers' => ['js']));
142 return $this->mustache;
147 * Constructor
149 * The constructor takes two arguments. The first is the page that the renderer
150 * has been created to assist with, and the second is the target.
151 * The target is an additional identifier that can be used to load different
152 * renderers for different options.
154 * @param moodle_page $page the page we are doing output for.
155 * @param string $target one of rendering target constants
157 public function __construct(moodle_page $page, $target) {
158 $this->opencontainers = $page->opencontainers;
159 $this->page = $page;
160 $this->target = $target;
164 * Renders a template by name with the given context.
166 * The provided data needs to be array/stdClass made up of only simple types.
167 * Simple types are array,stdClass,bool,int,float,string
169 * @since 2.9
170 * @param array|stdClass $context Context containing data for the template.
171 * @return string|boolean
173 public function render_from_template($templatename, $context) {
174 static $templatecache = array();
175 $mustache = $this->get_mustache();
177 try {
178 // Grab a copy of the existing helper to be restored later.
179 $uniqidhelper = $mustache->getHelper('uniqid');
180 } catch (Mustache_Exception_UnknownHelperException $e) {
181 // Helper doesn't exist.
182 $uniqidhelper = null;
185 // Provide 1 random value that will not change within a template
186 // but will be different from template to template. This is useful for
187 // e.g. aria attributes that only work with id attributes and must be
188 // unique in a page.
189 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
190 if (isset($templatecache[$templatename])) {
191 $template = $templatecache[$templatename];
192 } else {
193 try {
194 $template = $mustache->loadTemplate($templatename);
195 $templatecache[$templatename] = $template;
196 } catch (Mustache_Exception_UnknownTemplateException $e) {
197 throw new moodle_exception('Unknown template: ' . $templatename);
201 $renderedtemplate = trim($template->render($context));
203 // If we had an existing uniqid helper then we need to restore it to allow
204 // handle nested calls of render_from_template.
205 if ($uniqidhelper) {
206 $mustache->addHelper('uniqid', $uniqidhelper);
209 return $renderedtemplate;
214 * Returns rendered widget.
216 * The provided widget needs to be an object that extends the renderable
217 * interface.
218 * If will then be rendered by a method based upon the classname for the widget.
219 * For instance a widget of class `crazywidget` will be rendered by a protected
220 * render_crazywidget method of this renderer.
221 * If no render_crazywidget method exists and crazywidget implements templatable,
222 * look for the 'crazywidget' template in the same component and render that.
224 * @param renderable $widget instance with renderable interface
225 * @return string
227 public function render(renderable $widget) {
228 $classparts = explode('\\', get_class($widget));
229 // Strip namespaces.
230 $classname = array_pop($classparts);
231 // Remove _renderable suffixes.
232 $classname = preg_replace('/_renderable$/', '', $classname);
234 $rendermethod = "render_{$classname}";
235 if (method_exists($this, $rendermethod)) {
236 // Call the render_[widget_name] function.
237 // Note: This has a higher priority than the named_templatable to allow the theme to override the template.
238 return $this->$rendermethod($widget);
241 if ($widget instanceof named_templatable) {
242 // This is a named templatable.
243 // Fetch the template name from the get_template_name function instead.
244 // Note: This has higher priority than the guessed template name.
245 return $this->render_from_template(
246 $widget->get_template_name($this),
247 $widget->export_for_template($this)
251 if ($widget instanceof templatable) {
252 // Guess the templat ename based on the class name.
253 // Note: There's no benefit to moving this aboved the named_templatable and this approach is more costly.
254 $component = array_shift($classparts);
255 if (!$component) {
256 $component = 'core';
258 $template = $component . '/' . $classname;
259 $context = $widget->export_for_template($this);
260 return $this->render_from_template($template, $context);
262 throw new coding_exception("Can not render widget, renderer method ('{$rendermethod}') not found.");
266 * Adds a JS action for the element with the provided id.
268 * This method adds a JS event for the provided component action to the page
269 * and then returns the id that the event has been attached to.
270 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
272 * @param component_action $action
273 * @param string $id
274 * @return string id of element, either original submitted or random new if not supplied
276 public function add_action_handler(component_action $action, $id = null) {
277 if (!$id) {
278 $id = html_writer::random_id($action->event);
280 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
281 return $id;
285 * Returns true is output has already started, and false if not.
287 * @return boolean true if the header has been printed.
289 public function has_started() {
290 return $this->page->state >= moodle_page::STATE_IN_BODY;
294 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
296 * @param mixed $classes Space-separated string or array of classes
297 * @return string HTML class attribute value
299 public static function prepare_classes($classes) {
300 if (is_array($classes)) {
301 return implode(' ', array_unique($classes));
303 return $classes;
307 * Return the direct URL for an image from the pix folder.
309 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
311 * @deprecated since Moodle 3.3
312 * @param string $imagename the name of the icon.
313 * @param string $component specification of one plugin like in get_string()
314 * @return moodle_url
316 public function pix_url($imagename, $component = 'moodle') {
317 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
318 return $this->page->theme->image_url($imagename, $component);
322 * Return the moodle_url for an image.
324 * The exact image location and extension is determined
325 * automatically by searching for gif|png|jpg|jpeg, please
326 * note there can not be diferent images with the different
327 * extension. The imagename is for historical reasons
328 * a relative path name, it may be changed later for core
329 * images. It is recommended to not use subdirectories
330 * in plugin and theme pix directories.
332 * There are three types of images:
333 * 1/ theme images - stored in theme/mytheme/pix/,
334 * use component 'theme'
335 * 2/ core images - stored in /pix/,
336 * overridden via theme/mytheme/pix_core/
337 * 3/ plugin images - stored in mod/mymodule/pix,
338 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
339 * example: image_url('comment', 'mod_glossary')
341 * @param string $imagename the pathname of the image
342 * @param string $component full plugin name (aka component) or 'theme'
343 * @return moodle_url
345 public function image_url($imagename, $component = 'moodle') {
346 return $this->page->theme->image_url($imagename, $component);
350 * Return the site's logo URL, if any.
352 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
353 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
354 * @return moodle_url|false
356 public function get_logo_url($maxwidth = null, $maxheight = 200) {
357 global $CFG;
358 $logo = get_config('core_admin', 'logo');
359 if (empty($logo)) {
360 return false;
363 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
364 // It's not worth the overhead of detecting and serving 2 different images based on the device.
366 // Hide the requested size in the file path.
367 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
369 // Use $CFG->themerev to prevent browser caching when the file changes.
370 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
371 theme_get_revision(), $logo);
375 * Return the site's compact logo URL, if any.
377 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
378 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
379 * @return moodle_url|false
381 public function get_compact_logo_url($maxwidth = 300, $maxheight = 300) {
382 global $CFG;
383 $logo = get_config('core_admin', 'logocompact');
384 if (empty($logo)) {
385 return false;
388 // Hide the requested size in the file path.
389 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
391 // Use $CFG->themerev to prevent browser caching when the file changes.
392 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
393 theme_get_revision(), $logo);
397 * Whether we should display the logo in the navbar.
399 * We will when there are no main logos, and we have compact logo.
401 * @return bool
403 public function should_display_navbar_logo() {
404 $logo = $this->get_compact_logo_url();
405 return !empty($logo);
409 * Whether we should display the main logo.
410 * @deprecated since Moodle 4.0
411 * @todo final deprecation. To be removed in Moodle 4.4 MDL-73165.
412 * @param int $headinglevel The heading level we want to check against.
413 * @return bool
415 public function should_display_main_logo($headinglevel = 1) {
416 debugging('should_display_main_logo() is deprecated and will be removed in Moodle 4.4.', DEBUG_DEVELOPER);
417 // Only render the logo if we're on the front page or login page and the we have a logo.
418 $logo = $this->get_logo_url();
419 if ($headinglevel == 1 && !empty($logo)) {
420 if ($this->page->pagelayout == 'frontpage' || $this->page->pagelayout == 'login') {
421 return true;
425 return false;
432 * Basis for all plugin renderers.
434 * @copyright Petr Skoda (skodak)
435 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
436 * @since Moodle 2.0
437 * @package core
438 * @category output
440 class plugin_renderer_base extends renderer_base {
443 * @var renderer_base|core_renderer A reference to the current renderer.
444 * The renderer provided here will be determined by the page but will in 90%
445 * of cases by the {@link core_renderer}
447 protected $output;
450 * Constructor method, calls the parent constructor
452 * @param moodle_page $page
453 * @param string $target one of rendering target constants
455 public function __construct(moodle_page $page, $target) {
456 if (empty($target) && $page->pagelayout === 'maintenance') {
457 // If the page is using the maintenance layout then we're going to force the target to maintenance.
458 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
459 // unavailable for this page layout.
460 $target = RENDERER_TARGET_MAINTENANCE;
462 $this->output = $page->get_renderer('core', null, $target);
463 parent::__construct($page, $target);
467 * Renders the provided widget and returns the HTML to display it.
469 * @param renderable $widget instance with renderable interface
470 * @return string
472 public function render(renderable $widget) {
473 $classname = get_class($widget);
475 // Strip namespaces.
476 $classname = preg_replace('/^.*\\\/', '', $classname);
478 // Keep a copy at this point, we may need to look for a deprecated method.
479 $deprecatedmethod = "render_{$classname}";
481 // Remove _renderable suffixes.
482 $classname = preg_replace('/_renderable$/', '', $classname);
483 $rendermethod = "render_{$classname}";
485 if (method_exists($this, $rendermethod)) {
486 // Call the render_[widget_name] function.
487 // Note: This has a higher priority than the named_templatable to allow the theme to override the template.
488 return $this->$rendermethod($widget);
491 if ($widget instanceof named_templatable) {
492 // This is a named templatable.
493 // Fetch the template name from the get_template_name function instead.
494 // Note: This has higher priority than the deprecated method which is not overridable by themes anyway.
495 return $this->render_from_template(
496 $widget->get_template_name($this),
497 $widget->export_for_template($this)
501 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
502 // This is exactly where we don't want to be.
503 // If you have arrived here you have a renderable component within your plugin that has the name
504 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
505 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
506 // and the _renderable suffix now gets removed when looking for a render method.
507 // You need to change your renderers render_blah_renderable to render_blah.
508 // Until you do this it will not be possible for a theme to override the renderer to override your method.
509 // Please do it ASAP.
510 static $debugged = [];
511 if (!isset($debugged[$deprecatedmethod])) {
512 debugging(sprintf(
513 'Deprecated call. Please rename your renderables render method from %s to %s.',
514 $deprecatedmethod,
515 $rendermethod
516 ), DEBUG_DEVELOPER);
517 $debugged[$deprecatedmethod] = true;
519 return $this->$deprecatedmethod($widget);
522 // Pass to core renderer if method not found here.
523 // Note: this is not a parent. This is _new_ renderer which respects the requested format, and output type.
524 return $this->output->render($widget);
528 * Magic method used to pass calls otherwise meant for the standard renderer
529 * to it to ensure we don't go causing unnecessary grief.
531 * @param string $method
532 * @param array $arguments
533 * @return mixed
535 public function __call($method, $arguments) {
536 if (method_exists('renderer_base', $method)) {
537 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
539 if (method_exists($this->output, $method)) {
540 return call_user_func_array(array($this->output, $method), $arguments);
541 } else {
542 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
549 * The standard implementation of the core_renderer interface.
551 * @copyright 2009 Tim Hunt
552 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
553 * @since Moodle 2.0
554 * @package core
555 * @category output
557 class core_renderer extends renderer_base {
559 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
560 * in layout files instead.
561 * @deprecated
562 * @var string used in {@link core_renderer::header()}.
564 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
567 * @var string Used to pass information from {@link core_renderer::doctype()} to
568 * {@link core_renderer::standard_head_html()}.
570 protected $contenttype;
573 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
574 * with {@link core_renderer::header()}.
576 protected $metarefreshtag = '';
579 * @var string Unique token for the closing HTML
581 protected $unique_end_html_token;
584 * @var string Unique token for performance information
586 protected $unique_performance_info_token;
589 * @var string Unique token for the main content.
591 protected $unique_main_content_token;
593 /** @var custom_menu_item language The language menu if created */
594 protected $language = null;
597 * Constructor
599 * @param moodle_page $page the page we are doing output for.
600 * @param string $target one of rendering target constants
602 public function __construct(moodle_page $page, $target) {
603 $this->opencontainers = $page->opencontainers;
604 $this->page = $page;
605 $this->target = $target;
607 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
608 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
609 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
613 * Get the DOCTYPE declaration that should be used with this page. Designed to
614 * be called in theme layout.php files.
616 * @return string the DOCTYPE declaration that should be used.
618 public function doctype() {
619 if ($this->page->theme->doctype === 'html5') {
620 $this->contenttype = 'text/html; charset=utf-8';
621 return "<!DOCTYPE html>\n";
623 } else if ($this->page->theme->doctype === 'xhtml5') {
624 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
625 return "<!DOCTYPE html>\n";
627 } else {
628 // legacy xhtml 1.0
629 $this->contenttype = 'text/html; charset=utf-8';
630 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
635 * The attributes that should be added to the <html> tag. Designed to
636 * be called in theme layout.php files.
638 * @return string HTML fragment.
640 public function htmlattributes() {
641 $return = get_html_lang(true);
642 $attributes = array();
643 if ($this->page->theme->doctype !== 'html5') {
644 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
647 // Give plugins an opportunity to add things like xml namespaces to the html element.
648 // This function should return an array of html attribute names => values.
649 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
650 foreach ($pluginswithfunction as $plugins) {
651 foreach ($plugins as $function) {
652 $newattrs = $function();
653 unset($newattrs['dir']);
654 unset($newattrs['lang']);
655 unset($newattrs['xmlns']);
656 unset($newattrs['xml:lang']);
657 $attributes += $newattrs;
661 foreach ($attributes as $key => $val) {
662 $val = s($val);
663 $return .= " $key=\"$val\"";
666 return $return;
670 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
671 * that should be included in the <head> tag. Designed to be called in theme
672 * layout.php files.
674 * @return string HTML fragment.
676 public function standard_head_html() {
677 global $CFG, $SESSION, $SITE;
679 // Before we output any content, we need to ensure that certain
680 // page components are set up.
682 // Blocks must be set up early as they may require javascript which
683 // has to be included in the page header before output is created.
684 foreach ($this->page->blocks->get_regions() as $region) {
685 $this->page->blocks->ensure_content_created($region, $this);
688 $output = '';
690 // Give plugins an opportunity to add any head elements. The callback
691 // must always return a string containing valid html head content.
692 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
693 foreach ($pluginswithfunction as $plugins) {
694 foreach ($plugins as $function) {
695 $output .= $function();
699 // Allow a url_rewrite plugin to setup any dynamic head content.
700 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
701 $class = $CFG->urlrewriteclass;
702 $output .= $class::html_head_setup();
705 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
706 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
707 // This is only set by the {@link redirect()} method
708 $output .= $this->metarefreshtag;
710 // Check if a periodic refresh delay has been set and make sure we arn't
711 // already meta refreshing
712 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
713 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
716 // Set up help link popups for all links with the helptooltip class
717 $this->page->requires->js_init_call('M.util.help_popups.setup');
719 $focus = $this->page->focuscontrol;
720 if (!empty($focus)) {
721 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
722 // This is a horrifically bad way to handle focus but it is passed in
723 // through messy formslib::moodleform
724 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
725 } else if (strpos($focus, '.')!==false) {
726 // Old style of focus, bad way to do it
727 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);
728 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
729 } else {
730 // Focus element with given id
731 $this->page->requires->js_function_call('focuscontrol', array($focus));
735 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
736 // any other custom CSS can not be overridden via themes and is highly discouraged
737 $urls = $this->page->theme->css_urls($this->page);
738 foreach ($urls as $url) {
739 $this->page->requires->css_theme($url);
742 // Get the theme javascript head and footer
743 if ($jsurl = $this->page->theme->javascript_url(true)) {
744 $this->page->requires->js($jsurl, true);
746 if ($jsurl = $this->page->theme->javascript_url(false)) {
747 $this->page->requires->js($jsurl);
750 // Get any HTML from the page_requirements_manager.
751 $output .= $this->page->requires->get_head_code($this->page, $this);
753 // List alternate versions.
754 foreach ($this->page->alternateversions as $type => $alt) {
755 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
756 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
759 // Add noindex tag if relevant page and setting applied.
760 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
761 $loginpages = array('login-index', 'login-signup');
762 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
763 if (!isset($CFG->additionalhtmlhead)) {
764 $CFG->additionalhtmlhead = '';
766 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
769 if (!empty($CFG->additionalhtmlhead)) {
770 $output .= "\n".$CFG->additionalhtmlhead;
773 if ($this->page->pagelayout == 'frontpage') {
774 $summary = s(strip_tags(format_text($SITE->summary, FORMAT_HTML)));
775 if (!empty($summary)) {
776 $output .= "<meta name=\"description\" content=\"$summary\" />\n";
780 return $output;
784 * The standard tags (typically skip links) that should be output just inside
785 * the start of the <body> tag. Designed to be called in theme layout.php files.
787 * @return string HTML fragment.
789 public function standard_top_of_body_html() {
790 global $CFG;
791 $output = $this->page->requires->get_top_of_body_code($this);
792 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
793 $output .= "\n".$CFG->additionalhtmltopofbody;
796 // Give subsystems an opportunity to inject extra html content. The callback
797 // must always return a string containing valid html.
798 foreach (\core_component::get_core_subsystems() as $name => $path) {
799 if ($path) {
800 $output .= component_callback($name, 'before_standard_top_of_body_html', [], '');
804 // Give plugins an opportunity to inject extra html content. The callback
805 // must always return a string containing valid html.
806 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
807 foreach ($pluginswithfunction as $plugins) {
808 foreach ($plugins as $function) {
809 $output .= $function();
813 $output .= $this->maintenance_warning();
815 return $output;
819 * Scheduled maintenance warning message.
821 * Note: This is a nasty hack to display maintenance notice, this should be moved
822 * to some general notification area once we have it.
824 * @return string
826 public function maintenance_warning() {
827 global $CFG;
829 $output = '';
830 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
831 $timeleft = $CFG->maintenance_later - time();
832 // If timeleft less than 30 sec, set the class on block to error to highlight.
833 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
834 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-3 alert');
835 $a = new stdClass();
836 $a->hour = (int)($timeleft / 3600);
837 $a->min = (int)(($timeleft / 60) % 60);
838 $a->sec = (int)($timeleft % 60);
839 if ($a->hour > 0) {
840 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
841 } else {
842 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
845 $output .= $this->box_end();
846 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
847 array(array('timeleftinsec' => $timeleft)));
848 $this->page->requires->strings_for_js(
849 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
850 'admin');
852 return $output;
856 * content that should be output in the footer area
857 * of the page. Designed to be called in theme layout.php files.
859 * @return string HTML fragment.
861 public function standard_footer_html() {
862 global $CFG;
864 $output = '';
865 if (during_initial_install()) {
866 // Debugging info can not work before install is finished,
867 // in any case we do not want any links during installation!
868 return $output;
871 // Give plugins an opportunity to add any footer elements.
872 // The callback must always return a string containing valid html footer content.
873 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
874 foreach ($pluginswithfunction as $plugins) {
875 foreach ($plugins as $function) {
876 $output .= $function();
880 if (core_userfeedback::can_give_feedback()) {
881 $output .= html_writer::div(
882 $this->render_from_template('core/userfeedback_footer_link', ['url' => core_userfeedback::make_link()->out(false)])
886 if ($this->page->devicetypeinuse == 'legacy') {
887 // The legacy theme is in use print the notification
888 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
891 // Get links to switch device types (only shown for users not on a default device)
892 $output .= $this->theme_switch_links();
894 return $output;
898 * Performance information and validation links for debugging.
900 * @return string HTML fragment.
902 public function debug_footer_html() {
903 global $CFG, $SCRIPT;
904 $output = '';
906 if (during_initial_install()) {
907 // Debugging info can not work before install is finished.
908 return $output;
911 // This function is normally called from a layout.php file
912 // but some of the content won't be known until later, so we return a placeholder
913 // for now. This will be replaced with the real content in the footer.
914 $output .= $this->unique_performance_info_token;
916 if (!empty($CFG->debugpageinfo)) {
917 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
918 $this->page->debug_summary()) . '</div>';
920 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
922 // Add link to profiling report if necessary
923 if (function_exists('profiling_is_running') && profiling_is_running()) {
924 $txt = get_string('profiledscript', 'admin');
925 $title = get_string('profiledscriptview', 'admin');
926 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
927 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
928 $output .= '<div class="profilingfooter">' . $link . '</div>';
930 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
931 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
932 $output .= '<div class="purgecaches">' .
933 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
935 // Reactive module debug panel.
936 $output .= $this->render_from_template('core/local/reactive/debugpanel', []);
938 if (!empty($CFG->debugvalidators)) {
939 $siteurl = qualified_me();
940 $nuurl = new moodle_url('https://validator.w3.org/nu/', ['doc' => $siteurl, 'showsource' => 'yes']);
941 $waveurl = new moodle_url('https://wave.webaim.org/report#/' . urlencode($siteurl));
942 $validatorlinks = [
943 html_writer::link($nuurl, get_string('validatehtml')),
944 html_writer::link($waveurl, get_string('wcagcheck'))
946 $validatorlinkslist = html_writer::alist($validatorlinks, ['class' => 'list-unstyled ml-1']);
947 $output .= html_writer::div($validatorlinkslist, 'validators');
949 return $output;
953 * Returns standard main content placeholder.
954 * Designed to be called in theme layout.php files.
956 * @return string HTML fragment.
958 public function main_content() {
959 // This is here because it is the only place we can inject the "main" role over the entire main content area
960 // without requiring all theme's to manually do it, and without creating yet another thing people need to
961 // remember in the theme.
962 // This is an unfortunate hack. DO NO EVER add anything more here.
963 // DO NOT add classes.
964 // DO NOT add an id.
965 return '<div role="main">'.$this->unique_main_content_token.'</div>';
969 * Returns information about an activity.
971 * @param cm_info $cminfo The course module information.
972 * @param cm_completion_details $completiondetails The completion details for this activity module.
973 * @param array $activitydates The dates for this activity module.
974 * @return string the activity information HTML.
975 * @throws coding_exception
977 public function activity_information(cm_info $cminfo, cm_completion_details $completiondetails, array $activitydates): string {
978 if (!$completiondetails->has_completion() && empty($activitydates)) {
979 // No need to render the activity information when there's no completion info and activity dates to show.
980 return '';
982 $activityinfo = new activity_information($cminfo, $completiondetails, $activitydates);
983 $renderer = $this->page->get_renderer('core', 'course');
984 return $renderer->render($activityinfo);
988 * Returns standard navigation between activities in a course.
990 * @return string the navigation HTML.
992 public function activity_navigation() {
993 // First we should check if we want to add navigation.
994 $context = $this->page->context;
995 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
996 || $context->contextlevel != CONTEXT_MODULE) {
997 return '';
1000 // If the activity is in stealth mode, show no links.
1001 if ($this->page->cm->is_stealth()) {
1002 return '';
1005 $course = $this->page->cm->get_course();
1006 $courseformat = course_get_format($course);
1008 // If the theme implements course index and the current course format uses course index and the current
1009 // page layout is not 'frametop' (this layout does not support course index), show no links.
1010 if ($this->page->theme->usescourseindex && $courseformat->uses_course_index() &&
1011 $this->page->pagelayout !== 'frametop') {
1012 return '';
1015 // Get a list of all the activities in the course.
1016 $modules = get_fast_modinfo($course->id)->get_cms();
1018 // Put the modules into an array in order by the position they are shown in the course.
1019 $mods = [];
1020 $activitylist = [];
1021 foreach ($modules as $module) {
1022 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
1023 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
1024 continue;
1026 $mods[$module->id] = $module;
1028 // No need to add the current module to the list for the activity dropdown menu.
1029 if ($module->id == $this->page->cm->id) {
1030 continue;
1032 // Module name.
1033 $modname = $module->get_formatted_name();
1034 // Display the hidden text if necessary.
1035 if (!$module->visible) {
1036 $modname .= ' ' . get_string('hiddenwithbrackets');
1038 // Module URL.
1039 $linkurl = new moodle_url($module->url, array('forceview' => 1));
1040 // Add module URL (as key) and name (as value) to the activity list array.
1041 $activitylist[$linkurl->out(false)] = $modname;
1044 $nummods = count($mods);
1046 // If there is only one mod then do nothing.
1047 if ($nummods == 1) {
1048 return '';
1051 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
1052 $modids = array_keys($mods);
1054 // Get the position in the array of the course module we are viewing.
1055 $position = array_search($this->page->cm->id, $modids);
1057 $prevmod = null;
1058 $nextmod = null;
1060 // Check if we have a previous mod to show.
1061 if ($position > 0) {
1062 $prevmod = $mods[$modids[$position - 1]];
1065 // Check if we have a next mod to show.
1066 if ($position < ($nummods - 1)) {
1067 $nextmod = $mods[$modids[$position + 1]];
1070 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
1071 $renderer = $this->page->get_renderer('core', 'course');
1072 return $renderer->render($activitynav);
1076 * The standard tags (typically script tags that are not needed earlier) that
1077 * should be output after everything else. Designed to be called in theme layout.php files.
1079 * @return string HTML fragment.
1081 public function standard_end_of_body_html() {
1082 global $CFG;
1084 // This function is normally called from a layout.php file in {@link core_renderer::header()}
1085 // but some of the content won't be known until later, so we return a placeholder
1086 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
1087 $output = '';
1088 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
1089 $output .= "\n".$CFG->additionalhtmlfooter;
1091 $output .= $this->unique_end_html_token;
1092 return $output;
1096 * The standard HTML that should be output just before the <footer> tag.
1097 * Designed to be called in theme layout.php files.
1099 * @return string HTML fragment.
1101 public function standard_after_main_region_html() {
1102 global $CFG;
1103 $output = '';
1104 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlbottomofbody)) {
1105 $output .= "\n".$CFG->additionalhtmlbottomofbody;
1108 // Give subsystems an opportunity to inject extra html content. The callback
1109 // must always return a string containing valid html.
1110 foreach (\core_component::get_core_subsystems() as $name => $path) {
1111 if ($path) {
1112 $output .= component_callback($name, 'standard_after_main_region_html', [], '');
1116 // Give plugins an opportunity to inject extra html content. The callback
1117 // must always return a string containing valid html.
1118 $pluginswithfunction = get_plugins_with_function('standard_after_main_region_html', 'lib.php');
1119 foreach ($pluginswithfunction as $plugins) {
1120 foreach ($plugins as $function) {
1121 $output .= $function();
1125 return $output;
1129 * Return the standard string that says whether you are logged in (and switched
1130 * roles/logged in as another user).
1131 * @param bool $withlinks if false, then don't include any links in the HTML produced.
1132 * If not set, the default is the nologinlinks option from the theme config.php file,
1133 * and if that is not set, then links are included.
1134 * @return string HTML fragment.
1136 public function login_info($withlinks = null) {
1137 global $USER, $CFG, $DB, $SESSION;
1139 if (during_initial_install()) {
1140 return '';
1143 if (is_null($withlinks)) {
1144 $withlinks = empty($this->page->layout_options['nologinlinks']);
1147 $course = $this->page->course;
1148 if (\core\session\manager::is_loggedinas()) {
1149 $realuser = \core\session\manager::get_realuser();
1150 $fullname = fullname($realuser);
1151 if ($withlinks) {
1152 $loginastitle = get_string('loginas');
1153 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
1154 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
1155 } else {
1156 $realuserinfo = " [$fullname] ";
1158 } else {
1159 $realuserinfo = '';
1162 $loginpage = $this->is_login_page();
1163 $loginurl = get_login_url();
1165 if (empty($course->id)) {
1166 // $course->id is not defined during installation
1167 return '';
1168 } else if (isloggedin()) {
1169 $context = context_course::instance($course->id);
1171 $fullname = fullname($USER);
1172 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
1173 if ($withlinks) {
1174 $linktitle = get_string('viewprofile');
1175 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
1176 } else {
1177 $username = $fullname;
1179 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
1180 if ($withlinks) {
1181 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1182 } else {
1183 $username .= " from {$idprovider->name}";
1186 if (isguestuser()) {
1187 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1188 if (!$loginpage && $withlinks) {
1189 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1191 } else if (is_role_switched($course->id)) { // Has switched roles
1192 $rolename = '';
1193 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1194 $rolename = ': '.role_get_name($role, $context);
1196 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1197 if ($withlinks) {
1198 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1199 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1201 } else {
1202 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1203 if ($withlinks) {
1204 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1207 } else {
1208 $loggedinas = get_string('loggedinnot', 'moodle');
1209 if (!$loginpage && $withlinks) {
1210 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1214 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1216 if (isset($SESSION->justloggedin)) {
1217 unset($SESSION->justloggedin);
1218 if (!isguestuser()) {
1219 // Include this file only when required.
1220 require_once($CFG->dirroot . '/user/lib.php');
1221 if (($count = user_count_login_failures($USER)) && !empty($CFG->displayloginfailures)) {
1222 $loggedinas .= '<div class="loginfailures">';
1223 $a = new stdClass();
1224 $a->attempts = $count;
1225 $loggedinas .= get_string('failedloginattempts', '', $a);
1226 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1227 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1228 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1230 $loggedinas .= '</div>';
1235 return $loggedinas;
1239 * Check whether the current page is a login page.
1241 * @since Moodle 2.9
1242 * @return bool
1244 protected function is_login_page() {
1245 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1246 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1247 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1248 return in_array(
1249 $this->page->url->out_as_local_url(false, array()),
1250 array(
1251 '/login/index.php',
1252 '/login/forgot_password.php',
1258 * Return the 'back' link that normally appears in the footer.
1260 * @return string HTML fragment.
1262 public function home_link() {
1263 global $CFG, $SITE;
1265 if ($this->page->pagetype == 'site-index') {
1266 // Special case for site home page - please do not remove
1267 return '<div class="sitelink">' .
1268 '<a title="Moodle" class="d-inline-block aalink" href="http://moodle.org/">' .
1269 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1271 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1272 // Special case for during install/upgrade.
1273 return '<div class="sitelink">'.
1274 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1275 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1277 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1278 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1279 get_string('home') . '</a></div>';
1281 } else {
1282 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1283 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1288 * Redirects the user by any means possible given the current state
1290 * This function should not be called directly, it should always be called using
1291 * the redirect function in lib/weblib.php
1293 * The redirect function should really only be called before page output has started
1294 * however it will allow itself to be called during the state STATE_IN_BODY
1296 * @param string $encodedurl The URL to send to encoded if required
1297 * @param string $message The message to display to the user if any
1298 * @param int $delay The delay before redirecting a user, if $message has been
1299 * set this is a requirement and defaults to 3, set to 0 no delay
1300 * @param boolean $debugdisableredirect this redirect has been disabled for
1301 * debugging purposes. Display a message that explains, and don't
1302 * trigger the redirect.
1303 * @param string $messagetype The type of notification to show the message in.
1304 * See constants on \core\output\notification.
1305 * @return string The HTML to display to the user before dying, may contain
1306 * meta refresh, javascript refresh, and may have set header redirects
1308 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1309 $messagetype = \core\output\notification::NOTIFY_INFO) {
1310 global $CFG;
1311 $url = str_replace('&amp;', '&', $encodedurl);
1313 switch ($this->page->state) {
1314 case moodle_page::STATE_BEFORE_HEADER :
1315 // No output yet it is safe to delivery the full arsenal of redirect methods
1316 if (!$debugdisableredirect) {
1317 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1318 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1319 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1321 $output = $this->header();
1322 break;
1323 case moodle_page::STATE_PRINTING_HEADER :
1324 // We should hopefully never get here
1325 throw new coding_exception('You cannot redirect while printing the page header');
1326 break;
1327 case moodle_page::STATE_IN_BODY :
1328 // We really shouldn't be here but we can deal with this
1329 debugging("You should really redirect before you start page output");
1330 if (!$debugdisableredirect) {
1331 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1333 $output = $this->opencontainers->pop_all_but_last();
1334 break;
1335 case moodle_page::STATE_DONE :
1336 // Too late to be calling redirect now
1337 throw new coding_exception('You cannot redirect after the entire page has been generated');
1338 break;
1340 $output .= $this->notification($message, $messagetype);
1341 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1342 if ($debugdisableredirect) {
1343 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1345 $output .= $this->footer();
1346 return $output;
1350 * Start output by sending the HTTP headers, and printing the HTML <head>
1351 * and the start of the <body>.
1353 * To control what is printed, you should set properties on $PAGE.
1355 * @return string HTML that you must output this, preferably immediately.
1357 public function header() {
1358 global $USER, $CFG, $SESSION;
1360 // Give plugins an opportunity touch things before the http headers are sent
1361 // such as adding additional headers. The return value is ignored.
1362 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1363 foreach ($pluginswithfunction as $plugins) {
1364 foreach ($plugins as $function) {
1365 $function();
1369 if (\core\session\manager::is_loggedinas()) {
1370 $this->page->add_body_class('userloggedinas');
1373 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1374 require_once($CFG->dirroot . '/user/lib.php');
1375 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1376 if ($count = user_count_login_failures($USER, false)) {
1377 $this->page->add_body_class('loginfailures');
1381 // If the user is logged in, and we're not in initial install,
1382 // check to see if the user is role-switched and add the appropriate
1383 // CSS class to the body element.
1384 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1385 $this->page->add_body_class('userswitchedrole');
1388 // Give themes a chance to init/alter the page object.
1389 $this->page->theme->init_page($this->page);
1391 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1393 // Find the appropriate page layout file, based on $this->page->pagelayout.
1394 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1395 // Render the layout using the layout file.
1396 $rendered = $this->render_page_layout($layoutfile);
1398 // Slice the rendered output into header and footer.
1399 $cutpos = strpos($rendered, $this->unique_main_content_token);
1400 if ($cutpos === false) {
1401 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1402 $token = self::MAIN_CONTENT_TOKEN;
1403 } else {
1404 $token = $this->unique_main_content_token;
1407 if ($cutpos === false) {
1408 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.');
1410 $header = substr($rendered, 0, $cutpos);
1411 $footer = substr($rendered, $cutpos + strlen($token));
1413 if (empty($this->contenttype)) {
1414 debugging('The page layout file did not call $OUTPUT->doctype()');
1415 $header = $this->doctype() . $header;
1418 // If this theme version is below 2.4 release and this is a course view page
1419 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1420 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1421 // check if course content header/footer have not been output during render of theme layout
1422 $coursecontentheader = $this->course_content_header(true);
1423 $coursecontentfooter = $this->course_content_footer(true);
1424 if (!empty($coursecontentheader)) {
1425 // display debug message and add header and footer right above and below main content
1426 // Please note that course header and footer (to be displayed above and below the whole page)
1427 // are not displayed in this case at all.
1428 // Besides the content header and footer are not displayed on any other course page
1429 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);
1430 $header .= $coursecontentheader;
1431 $footer = $coursecontentfooter. $footer;
1435 send_headers($this->contenttype, $this->page->cacheable);
1437 $this->opencontainers->push('header/footer', $footer);
1438 $this->page->set_state(moodle_page::STATE_IN_BODY);
1440 // If an activity record has been set, activity_header will handle this.
1441 if (!$this->page->cm || !empty($this->page->layout_options['noactivityheader'])) {
1442 $header .= $this->skip_link_target('maincontent');
1444 return $header;
1448 * Renders and outputs the page layout file.
1450 * This is done by preparing the normal globals available to a script, and
1451 * then including the layout file provided by the current theme for the
1452 * requested layout.
1454 * @param string $layoutfile The name of the layout file
1455 * @return string HTML code
1457 protected function render_page_layout($layoutfile) {
1458 global $CFG, $SITE, $USER;
1459 // The next lines are a bit tricky. The point is, here we are in a method
1460 // of a renderer class, and this object may, or may not, be the same as
1461 // the global $OUTPUT object. When rendering the page layout file, we want to use
1462 // this object. However, people writing Moodle code expect the current
1463 // renderer to be called $OUTPUT, not $this, so define a variable called
1464 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1465 $OUTPUT = $this;
1466 $PAGE = $this->page;
1467 $COURSE = $this->page->course;
1469 ob_start();
1470 include($layoutfile);
1471 $rendered = ob_get_contents();
1472 ob_end_clean();
1473 return $rendered;
1477 * Outputs the page's footer
1479 * @return string HTML fragment
1481 public function footer() {
1482 global $CFG, $DB;
1484 $output = '';
1486 // Give plugins an opportunity to touch the page before JS is finalized.
1487 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1488 foreach ($pluginswithfunction as $plugins) {
1489 foreach ($plugins as $function) {
1490 $extrafooter = $function();
1491 if (is_string($extrafooter)) {
1492 $output .= $extrafooter;
1497 $output .= $this->container_end_all(true);
1499 $footer = $this->opencontainers->pop('header/footer');
1501 if (debugging() and $DB and $DB->is_transaction_started()) {
1502 // TODO: MDL-20625 print warning - transaction will be rolled back
1505 // Provide some performance info if required
1506 $performanceinfo = '';
1507 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1508 $perf = get_performance_info();
1509 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1510 $performanceinfo = $perf['html'];
1514 // We always want performance data when running a performance test, even if the user is redirected to another page.
1515 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1516 $footer = $this->unique_performance_info_token . $footer;
1518 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1520 // Only show notifications when the current page has a context id.
1521 if (!empty($this->page->context->id)) {
1522 $this->page->requires->js_call_amd('core/notification', 'init', array(
1523 $this->page->context->id,
1524 \core\notification::fetch_as_array($this)
1527 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1529 $this->page->set_state(moodle_page::STATE_DONE);
1531 return $output . $footer;
1535 * Close all but the last open container. This is useful in places like error
1536 * handling, where you want to close all the open containers (apart from <body>)
1537 * before outputting the error message.
1539 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1540 * developer debug warning if it isn't.
1541 * @return string the HTML required to close any open containers inside <body>.
1543 public function container_end_all($shouldbenone = false) {
1544 return $this->opencontainers->pop_all_but_last($shouldbenone);
1548 * Returns course-specific information to be output immediately above content on any course page
1549 * (for the current course)
1551 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1552 * @return string
1554 public function course_content_header($onlyifnotcalledbefore = false) {
1555 global $CFG;
1556 static $functioncalled = false;
1557 if ($functioncalled && $onlyifnotcalledbefore) {
1558 // we have already output the content header
1559 return '';
1562 // Output any session notification.
1563 $notifications = \core\notification::fetch();
1565 $bodynotifications = '';
1566 foreach ($notifications as $notification) {
1567 $bodynotifications .= $this->render_from_template(
1568 $notification->get_template_name(),
1569 $notification->export_for_template($this)
1573 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1575 if ($this->page->course->id == SITEID) {
1576 // return immediately and do not include /course/lib.php if not necessary
1577 return $output;
1580 require_once($CFG->dirroot.'/course/lib.php');
1581 $functioncalled = true;
1582 $courseformat = course_get_format($this->page->course);
1583 if (($obj = $courseformat->course_content_header()) !== null) {
1584 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1586 return $output;
1590 * Returns course-specific information to be output immediately below content on any course page
1591 * (for the current course)
1593 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1594 * @return string
1596 public function course_content_footer($onlyifnotcalledbefore = false) {
1597 global $CFG;
1598 if ($this->page->course->id == SITEID) {
1599 // return immediately and do not include /course/lib.php if not necessary
1600 return '';
1602 static $functioncalled = false;
1603 if ($functioncalled && $onlyifnotcalledbefore) {
1604 // we have already output the content footer
1605 return '';
1607 $functioncalled = true;
1608 require_once($CFG->dirroot.'/course/lib.php');
1609 $courseformat = course_get_format($this->page->course);
1610 if (($obj = $courseformat->course_content_footer()) !== null) {
1611 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1613 return '';
1617 * Returns course-specific information to be output on any course page in the header area
1618 * (for the current course)
1620 * @return string
1622 public function course_header() {
1623 global $CFG;
1624 if ($this->page->course->id == SITEID) {
1625 // return immediately and do not include /course/lib.php if not necessary
1626 return '';
1628 require_once($CFG->dirroot.'/course/lib.php');
1629 $courseformat = course_get_format($this->page->course);
1630 if (($obj = $courseformat->course_header()) !== null) {
1631 return $courseformat->get_renderer($this->page)->render($obj);
1633 return '';
1637 * Returns course-specific information to be output on any course page in the footer area
1638 * (for the current course)
1640 * @return string
1642 public function course_footer() {
1643 global $CFG;
1644 if ($this->page->course->id == SITEID) {
1645 // return immediately and do not include /course/lib.php if not necessary
1646 return '';
1648 require_once($CFG->dirroot.'/course/lib.php');
1649 $courseformat = course_get_format($this->page->course);
1650 if (($obj = $courseformat->course_footer()) !== null) {
1651 return $courseformat->get_renderer($this->page)->render($obj);
1653 return '';
1657 * Get the course pattern datauri to show on a course card.
1659 * The datauri is an encoded svg that can be passed as a url.
1660 * @param int $id Id to use when generating the pattern
1661 * @return string datauri
1663 public function get_generated_image_for_id($id) {
1664 $color = $this->get_generated_color_for_id($id);
1665 $pattern = new \core_geopattern();
1666 $pattern->setColor($color);
1667 $pattern->patternbyid($id);
1668 return $pattern->datauri();
1672 * Get the course color to show on a course card.
1674 * @param int $id Id to use when generating the color.
1675 * @return string hex color code.
1677 public function get_generated_color_for_id($id) {
1678 $colornumbers = range(1, 10);
1679 $basecolors = [];
1680 foreach ($colornumbers as $number) {
1681 $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1684 $color = $basecolors[$id % 10];
1685 return $color;
1689 * Returns lang menu or '', this method also checks forcing of languages in courses.
1691 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1693 * @return string The lang menu HTML or empty string
1695 public function lang_menu() {
1696 $languagemenu = new \core\output\language_menu($this->page);
1697 $data = $languagemenu->export_for_single_select($this);
1698 if ($data) {
1699 return $this->render_from_template('core/single_select', $data);
1701 return '';
1705 * Output the row of editing icons for a block, as defined by the controls array.
1707 * @param array $controls an array like {@link block_contents::$controls}.
1708 * @param string $blockid The ID given to the block.
1709 * @return string HTML fragment.
1711 public function block_controls($actions, $blockid = null) {
1712 global $CFG;
1713 if (empty($actions)) {
1714 return '';
1716 $menu = new action_menu($actions);
1717 if ($blockid !== null) {
1718 $menu->set_owner_selector('#'.$blockid);
1720 $menu->set_constraint('.block-region');
1721 $menu->attributes['class'] .= ' block-control-actions commands';
1722 return $this->render($menu);
1726 * Returns the HTML for a basic textarea field.
1728 * @param string $name Name to use for the textarea element
1729 * @param string $id The id to use fort he textarea element
1730 * @param string $value Initial content to display in the textarea
1731 * @param int $rows Number of rows to display
1732 * @param int $cols Number of columns to display
1733 * @return string the HTML to display
1735 public function print_textarea($name, $id, $value, $rows, $cols) {
1736 editors_head_setup();
1737 $editor = editors_get_preferred_editor(FORMAT_HTML);
1738 $editor->set_text($value);
1739 $editor->use_editor($id, []);
1741 $context = [
1742 'id' => $id,
1743 'name' => $name,
1744 'value' => $value,
1745 'rows' => $rows,
1746 'cols' => $cols
1749 return $this->render_from_template('core_form/editor_textarea', $context);
1753 * Renders an action menu component.
1755 * @param action_menu $menu
1756 * @return string HTML
1758 public function render_action_menu(action_menu $menu) {
1760 // We don't want the class icon there!
1761 foreach ($menu->get_secondary_actions() as $action) {
1762 if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1763 $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1767 if ($menu->is_empty()) {
1768 return '';
1770 $context = $menu->export_for_template($this);
1772 return $this->render_from_template('core/action_menu', $context);
1776 * Renders a Check API result
1778 * @param result $result
1779 * @return string HTML fragment
1781 protected function render_check_result(core\check\result $result) {
1782 return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1786 * Renders a Check API result
1788 * @param result $result
1789 * @return string HTML fragment
1791 public function check_result(core\check\result $result) {
1792 return $this->render_check_result($result);
1796 * Renders an action_menu_link item.
1798 * @param action_menu_link $action
1799 * @return string HTML fragment
1801 protected function render_action_menu_link(action_menu_link $action) {
1802 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1806 * Renders a primary action_menu_filler item.
1808 * @param action_menu_link_filler $action
1809 * @return string HTML fragment
1811 protected function render_action_menu_filler(action_menu_filler $action) {
1812 return html_writer::span('&nbsp;', 'filler');
1816 * Renders a primary action_menu_link item.
1818 * @param action_menu_link_primary $action
1819 * @return string HTML fragment
1821 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1822 return $this->render_action_menu_link($action);
1826 * Renders a secondary action_menu_link item.
1828 * @param action_menu_link_secondary $action
1829 * @return string HTML fragment
1831 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1832 return $this->render_action_menu_link($action);
1836 * Prints a nice side block with an optional header.
1838 * @param block_contents $bc HTML for the content
1839 * @param string $region the region the block is appearing in.
1840 * @return string the HTML to be output.
1842 public function block(block_contents $bc, $region) {
1843 $bc = clone($bc); // Avoid messing up the object passed in.
1844 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1845 $bc->collapsible = block_contents::NOT_HIDEABLE;
1848 $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1849 $context = new stdClass();
1850 $context->skipid = $bc->skipid;
1851 $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
1852 $context->dockable = $bc->dockable;
1853 $context->id = $id;
1854 $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1855 $context->skiptitle = strip_tags($bc->title);
1856 $context->showskiplink = !empty($context->skiptitle);
1857 $context->arialabel = $bc->arialabel;
1858 $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
1859 $context->class = $bc->attributes['class'];
1860 $context->type = $bc->attributes['data-block'];
1861 $context->title = $bc->title;
1862 $context->content = $bc->content;
1863 $context->annotation = $bc->annotation;
1864 $context->footer = $bc->footer;
1865 $context->hascontrols = !empty($bc->controls);
1866 if ($context->hascontrols) {
1867 $context->controls = $this->block_controls($bc->controls, $id);
1870 return $this->render_from_template('core/block', $context);
1874 * Render the contents of a block_list.
1876 * @param array $icons the icon for each item.
1877 * @param array $items the content of each item.
1878 * @return string HTML
1880 public function list_block_contents($icons, $items) {
1881 $row = 0;
1882 $lis = array();
1883 foreach ($items as $key => $string) {
1884 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1885 if (!empty($icons[$key])) { //test if the content has an assigned icon
1886 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1888 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1889 $item .= html_writer::end_tag('li');
1890 $lis[] = $item;
1891 $row = 1 - $row; // Flip even/odd.
1893 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1897 * Output all the blocks in a particular region.
1899 * @param string $region the name of a region on this page.
1900 * @param boolean $fakeblocksonly Output fake block only.
1901 * @return string the HTML to be output.
1903 public function blocks_for_region($region, $fakeblocksonly = false) {
1904 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1905 $lastblock = null;
1906 $zones = array();
1907 foreach ($blockcontents as $bc) {
1908 if ($bc instanceof block_contents) {
1909 $zones[] = $bc->title;
1912 $output = '';
1914 foreach ($blockcontents as $bc) {
1915 if ($bc instanceof block_contents) {
1916 if ($fakeblocksonly && !$bc->is_fake()) {
1917 // Skip rendering real blocks if we only want to show fake blocks.
1918 continue;
1920 $output .= $this->block($bc, $region);
1921 $lastblock = $bc->title;
1922 } else if ($bc instanceof block_move_target) {
1923 if (!$fakeblocksonly) {
1924 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1926 } else {
1927 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1930 return $output;
1934 * Output a place where the block that is currently being moved can be dropped.
1936 * @param block_move_target $target with the necessary details.
1937 * @param array $zones array of areas where the block can be moved to
1938 * @param string $previous the block located before the area currently being rendered.
1939 * @param string $region the name of the region
1940 * @return string the HTML to be output.
1942 public function block_move_target($target, $zones, $previous, $region) {
1943 if ($previous == null) {
1944 if (empty($zones)) {
1945 // There are no zones, probably because there are no blocks.
1946 $regions = $this->page->theme->get_all_block_regions();
1947 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1948 } else {
1949 $position = get_string('moveblockbefore', 'block', $zones[0]);
1951 } else {
1952 $position = get_string('moveblockafter', 'block', $previous);
1954 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1958 * Renders a special html link with attached action
1960 * Theme developers: DO NOT OVERRIDE! Please override function
1961 * {@link core_renderer::render_action_link()} instead.
1963 * @param string|moodle_url $url
1964 * @param string $text HTML fragment
1965 * @param component_action $action
1966 * @param array $attributes associative array of html link attributes + disabled
1967 * @param pix_icon optional pix icon to render with the link
1968 * @return string HTML fragment
1970 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1971 if (!($url instanceof moodle_url)) {
1972 $url = new moodle_url($url);
1974 $link = new action_link($url, $text, $action, $attributes, $icon);
1976 return $this->render($link);
1980 * Renders an action_link object.
1982 * The provided link is renderer and the HTML returned. At the same time the
1983 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1985 * @param action_link $link
1986 * @return string HTML fragment
1988 protected function render_action_link(action_link $link) {
1989 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1993 * Renders an action_icon.
1995 * This function uses the {@link core_renderer::action_link()} method for the
1996 * most part. What it does different is prepare the icon as HTML and use it
1997 * as the link text.
1999 * Theme developers: If you want to change how action links and/or icons are rendered,
2000 * consider overriding function {@link core_renderer::render_action_link()} and
2001 * {@link core_renderer::render_pix_icon()}.
2003 * @param string|moodle_url $url A string URL or moodel_url
2004 * @param pix_icon $pixicon
2005 * @param component_action $action
2006 * @param array $attributes associative array of html link attributes + disabled
2007 * @param bool $linktext show title next to image in link
2008 * @return string HTML fragment
2010 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
2011 if (!($url instanceof moodle_url)) {
2012 $url = new moodle_url($url);
2014 $attributes = (array)$attributes;
2016 if (empty($attributes['class'])) {
2017 // let ppl override the class via $options
2018 $attributes['class'] = 'action-icon';
2021 $icon = $this->render($pixicon);
2023 if ($linktext) {
2024 $text = $pixicon->attributes['alt'];
2025 } else {
2026 $text = '';
2029 return $this->action_link($url, $text.$icon, $action, $attributes);
2033 * Print a message along with button choices for Continue/Cancel
2035 * If a string or moodle_url is given instead of a single_button, method defaults to post.
2037 * @param string $message The question to ask the user
2038 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
2039 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
2040 * @param array $displayoptions optional extra display options
2041 * @return string HTML fragment
2043 public function confirm($message, $continue, $cancel, array $displayoptions = []) {
2045 // Check existing displayoptions.
2046 $displayoptions['confirmtitle'] = $displayoptions['confirmtitle'] ?? get_string('confirm');
2047 $displayoptions['continuestr'] = $displayoptions['continuestr'] ?? get_string('continue');
2048 $displayoptions['cancelstr'] = $displayoptions['cancelstr'] ?? get_string('cancel');
2050 if ($continue instanceof single_button) {
2051 // ok
2052 $continue->primary = true;
2053 } else if (is_string($continue)) {
2054 $continue = new single_button(new moodle_url($continue), $displayoptions['continuestr'], 'post', true);
2055 } else if ($continue instanceof moodle_url) {
2056 $continue = new single_button($continue, $displayoptions['continuestr'], 'post', true);
2057 } else {
2058 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2061 if ($cancel instanceof single_button) {
2062 // ok
2063 } else if (is_string($cancel)) {
2064 $cancel = new single_button(new moodle_url($cancel), $displayoptions['cancelstr'], 'get');
2065 } else if ($cancel instanceof moodle_url) {
2066 $cancel = new single_button($cancel, $displayoptions['cancelstr'], 'get');
2067 } else {
2068 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2071 $attributes = [
2072 'role'=>'alertdialog',
2073 'aria-labelledby'=>'modal-header',
2074 'aria-describedby'=>'modal-body',
2075 'aria-modal'=>'true'
2078 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
2079 $output .= $this->box_start('modal-content', 'modal-content');
2080 $output .= $this->box_start('modal-header px-3', 'modal-header');
2081 $output .= html_writer::tag('h4', $displayoptions['confirmtitle']);
2082 $output .= $this->box_end();
2083 $attributes = [
2084 'role'=>'alert',
2085 'data-aria-autofocus'=>'true'
2087 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
2088 $output .= html_writer::tag('p', $message);
2089 $output .= $this->box_end();
2090 $output .= $this->box_start('modal-footer', 'modal-footer');
2091 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
2092 $output .= $this->box_end();
2093 $output .= $this->box_end();
2094 $output .= $this->box_end();
2095 return $output;
2099 * Returns a form with a single button.
2101 * Theme developers: DO NOT OVERRIDE! Please override function
2102 * {@link core_renderer::render_single_button()} instead.
2104 * @param string|moodle_url $url
2105 * @param string $label button text
2106 * @param string $method get or post submit method
2107 * @param array $options associative array {disabled, title, etc.}
2108 * @return string HTML fragment
2110 public function single_button($url, $label, $method='post', array $options=null) {
2111 if (!($url instanceof moodle_url)) {
2112 $url = new moodle_url($url);
2114 $button = new single_button($url, $label, $method);
2116 foreach ((array)$options as $key=>$value) {
2117 if (property_exists($button, $key)) {
2118 $button->$key = $value;
2119 } else {
2120 $button->set_attribute($key, $value);
2124 return $this->render($button);
2128 * Renders a single button widget.
2130 * This will return HTML to display a form containing a single button.
2132 * @param single_button $button
2133 * @return string HTML fragment
2135 protected function render_single_button(single_button $button) {
2136 return $this->render_from_template('core/single_button', $button->export_for_template($this));
2140 * Returns a form with a single select widget.
2142 * Theme developers: DO NOT OVERRIDE! Please override function
2143 * {@link core_renderer::render_single_select()} instead.
2145 * @param moodle_url $url form action target, includes hidden fields
2146 * @param string $name name of selection field - the changing parameter in url
2147 * @param array $options list of options
2148 * @param string $selected selected element
2149 * @param array $nothing
2150 * @param string $formid
2151 * @param array $attributes other attributes for the single select
2152 * @return string HTML fragment
2154 public function single_select($url, $name, array $options, $selected = '',
2155 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2156 if (!($url instanceof moodle_url)) {
2157 $url = new moodle_url($url);
2159 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2161 if (array_key_exists('label', $attributes)) {
2162 $select->set_label($attributes['label']);
2163 unset($attributes['label']);
2165 $select->attributes = $attributes;
2167 return $this->render($select);
2171 * Returns a dataformat selection and download form
2173 * @param string $label A text label
2174 * @param moodle_url|string $base The download page url
2175 * @param string $name The query param which will hold the type of the download
2176 * @param array $params Extra params sent to the download page
2177 * @return string HTML fragment
2179 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2181 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2182 $options = array();
2183 foreach ($formats as $format) {
2184 if ($format->is_enabled()) {
2185 $options[] = array(
2186 'value' => $format->name,
2187 'label' => get_string('dataformat', $format->component),
2191 $hiddenparams = array();
2192 foreach ($params as $key => $value) {
2193 $hiddenparams[] = array(
2194 'name' => $key,
2195 'value' => $value,
2198 $data = array(
2199 'label' => $label,
2200 'base' => $base,
2201 'name' => $name,
2202 'params' => $hiddenparams,
2203 'options' => $options,
2204 'sesskey' => sesskey(),
2205 'submit' => get_string('download'),
2208 return $this->render_from_template('core/dataformat_selector', $data);
2213 * Internal implementation of single_select rendering
2215 * @param single_select $select
2216 * @return string HTML fragment
2218 protected function render_single_select(single_select $select) {
2219 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2223 * Returns a form with a url select widget.
2225 * Theme developers: DO NOT OVERRIDE! Please override function
2226 * {@link core_renderer::render_url_select()} instead.
2228 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2229 * @param string $selected selected element
2230 * @param array $nothing
2231 * @param string $formid
2232 * @return string HTML fragment
2234 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2235 $select = new url_select($urls, $selected, $nothing, $formid);
2236 return $this->render($select);
2240 * Internal implementation of url_select rendering
2242 * @param url_select $select
2243 * @return string HTML fragment
2245 protected function render_url_select(url_select $select) {
2246 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2250 * Returns a string containing a link to the user documentation.
2251 * Also contains an icon by default. Shown to teachers and admin only.
2253 * @param string $path The page link after doc root and language, no leading slash.
2254 * @param string $text The text to be displayed for the link
2255 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2256 * @param array $attributes htm attributes
2257 * @return string
2259 public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
2260 global $CFG;
2262 $icon = $this->pix_icon('book', '', 'moodle', array('class' => 'iconhelp icon-pre', 'role' => 'presentation'));
2264 $attributes['href'] = new moodle_url(get_docs_url($path));
2265 $newwindowicon = '';
2266 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2267 $attributes['target'] = '_blank';
2268 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle',
2269 ['class' => 'fa fa-externallink fa-fw']);
2272 return html_writer::tag('a', $icon . $text . $newwindowicon, $attributes);
2276 * Return HTML for an image_icon.
2278 * Theme developers: DO NOT OVERRIDE! Please override function
2279 * {@link core_renderer::render_image_icon()} instead.
2281 * @param string $pix short pix name
2282 * @param string $alt mandatory alt attribute
2283 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2284 * @param array $attributes htm attributes
2285 * @return string HTML fragment
2287 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2288 $icon = new image_icon($pix, $alt, $component, $attributes);
2289 return $this->render($icon);
2293 * Renders a pix_icon widget and returns the HTML to display it.
2295 * @param image_icon $icon
2296 * @return string HTML fragment
2298 protected function render_image_icon(image_icon $icon) {
2299 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2300 return $system->render_pix_icon($this, $icon);
2304 * Return HTML for a pix_icon.
2306 * Theme developers: DO NOT OVERRIDE! Please override function
2307 * {@link core_renderer::render_pix_icon()} instead.
2309 * @param string $pix short pix name
2310 * @param string $alt mandatory alt attribute
2311 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2312 * @param array $attributes htm lattributes
2313 * @return string HTML fragment
2315 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2316 $icon = new pix_icon($pix, $alt, $component, $attributes);
2317 return $this->render($icon);
2321 * Renders a pix_icon widget and returns the HTML to display it.
2323 * @param pix_icon $icon
2324 * @return string HTML fragment
2326 protected function render_pix_icon(pix_icon $icon) {
2327 $system = \core\output\icon_system::instance();
2328 return $system->render_pix_icon($this, $icon);
2332 * Return HTML to display an emoticon icon.
2334 * @param pix_emoticon $emoticon
2335 * @return string HTML fragment
2337 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2338 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2339 return $system->render_pix_icon($this, $emoticon);
2343 * Produces the html that represents this rating in the UI
2345 * @param rating $rating the page object on which this rating will appear
2346 * @return string
2348 function render_rating(rating $rating) {
2349 global $CFG, $USER;
2351 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2352 return null;//ratings are turned off
2355 $ratingmanager = new rating_manager();
2356 // Initialise the JavaScript so ratings can be done by AJAX.
2357 $ratingmanager->initialise_rating_javascript($this->page);
2359 $strrate = get_string("rate", "rating");
2360 $ratinghtml = ''; //the string we'll return
2362 // permissions check - can they view the aggregate?
2363 if ($rating->user_can_view_aggregate()) {
2365 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2366 $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2367 $aggregatestr = $rating->get_aggregate_string();
2369 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2370 if ($rating->count > 0) {
2371 $countstr = "({$rating->count})";
2372 } else {
2373 $countstr = '-';
2375 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2377 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2379 $nonpopuplink = $rating->get_view_ratings_url();
2380 $popuplink = $rating->get_view_ratings_url(true);
2382 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2383 $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
2386 $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
2389 $formstart = null;
2390 // if the item doesn't belong to the current user, the user has permission to rate
2391 // and we're within the assessable period
2392 if ($rating->user_can_rate()) {
2394 $rateurl = $rating->get_rate_url();
2395 $inputs = $rateurl->params();
2397 //start the rating form
2398 $formattrs = array(
2399 'id' => "postrating{$rating->itemid}",
2400 'class' => 'postratingform',
2401 'method' => 'post',
2402 'action' => $rateurl->out_omit_querystring()
2404 $formstart = html_writer::start_tag('form', $formattrs);
2405 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2407 // add the hidden inputs
2408 foreach ($inputs as $name => $value) {
2409 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2410 $formstart .= html_writer::empty_tag('input', $attributes);
2413 if (empty($ratinghtml)) {
2414 $ratinghtml .= $strrate.': ';
2416 $ratinghtml = $formstart.$ratinghtml;
2418 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2419 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2420 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2421 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2423 //output submit button
2424 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2426 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2427 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2429 if (!$rating->settings->scale->isnumeric) {
2430 // If a global scale, try to find current course ID from the context
2431 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2432 $courseid = $coursecontext->instanceid;
2433 } else {
2434 $courseid = $rating->settings->scale->courseid;
2436 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2438 $ratinghtml .= html_writer::end_tag('span');
2439 $ratinghtml .= html_writer::end_tag('div');
2440 $ratinghtml .= html_writer::end_tag('form');
2443 return $ratinghtml;
2447 * Centered heading with attached help button (same title text)
2448 * and optional icon attached.
2450 * @param string $text A heading text
2451 * @param string $helpidentifier The keyword that defines a help page
2452 * @param string $component component name
2453 * @param string|moodle_url $icon
2454 * @param string $iconalt icon alt text
2455 * @param int $level The level of importance of the heading. Defaulting to 2
2456 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2457 * @return string HTML fragment
2459 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2460 $image = '';
2461 if ($icon) {
2462 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2465 $help = '';
2466 if ($helpidentifier) {
2467 $help = $this->help_icon($helpidentifier, $component);
2470 return $this->heading($image.$text.$help, $level, $classnames);
2474 * Returns HTML to display a help icon.
2476 * @deprecated since Moodle 2.0
2478 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2479 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2483 * Returns HTML to display a help icon.
2485 * Theme developers: DO NOT OVERRIDE! Please override function
2486 * {@link core_renderer::render_help_icon()} instead.
2488 * @param string $identifier The keyword that defines a help page
2489 * @param string $component component name
2490 * @param string|bool $linktext true means use $title as link text, string means link text value
2491 * @return string HTML fragment
2493 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2494 $icon = new help_icon($identifier, $component);
2495 $icon->diag_strings();
2496 if ($linktext === true) {
2497 $icon->linktext = get_string($icon->identifier, $icon->component);
2498 } else if (!empty($linktext)) {
2499 $icon->linktext = $linktext;
2501 return $this->render($icon);
2505 * Implementation of user image rendering.
2507 * @param help_icon $helpicon A help icon instance
2508 * @return string HTML fragment
2510 protected function render_help_icon(help_icon $helpicon) {
2511 $context = $helpicon->export_for_template($this);
2512 return $this->render_from_template('core/help_icon', $context);
2516 * Returns HTML to display a scale help icon.
2518 * @param int $courseid
2519 * @param stdClass $scale instance
2520 * @return string HTML fragment
2522 public function help_icon_scale($courseid, stdClass $scale) {
2523 global $CFG;
2525 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2527 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2529 $scaleid = abs($scale->id);
2531 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2532 $action = new popup_action('click', $link, 'ratingscale');
2534 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2538 * Creates and returns a spacer image with optional line break.
2540 * @param array $attributes Any HTML attributes to add to the spaced.
2541 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2542 * laxy do it with CSS which is a much better solution.
2543 * @return string HTML fragment
2545 public function spacer(array $attributes = null, $br = false) {
2546 $attributes = (array)$attributes;
2547 if (empty($attributes['width'])) {
2548 $attributes['width'] = 1;
2550 if (empty($attributes['height'])) {
2551 $attributes['height'] = 1;
2553 $attributes['class'] = 'spacer';
2555 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2557 if (!empty($br)) {
2558 $output .= '<br />';
2561 return $output;
2565 * Returns HTML to display the specified user's avatar.
2567 * User avatar may be obtained in two ways:
2568 * <pre>
2569 * // Option 1: (shortcut for simple cases, preferred way)
2570 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2571 * $OUTPUT->user_picture($user, array('popup'=>true));
2573 * // Option 2:
2574 * $userpic = new user_picture($user);
2575 * // Set properties of $userpic
2576 * $userpic->popup = true;
2577 * $OUTPUT->render($userpic);
2578 * </pre>
2580 * Theme developers: DO NOT OVERRIDE! Please override function
2581 * {@link core_renderer::render_user_picture()} instead.
2583 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2584 * If any of these are missing, the database is queried. Avoid this
2585 * if at all possible, particularly for reports. It is very bad for performance.
2586 * @param array $options associative array with user picture options, used only if not a user_picture object,
2587 * options are:
2588 * - courseid=$this->page->course->id (course id of user profile in link)
2589 * - size=35 (size of image)
2590 * - link=true (make image clickable - the link leads to user profile)
2591 * - popup=false (open in popup)
2592 * - alttext=true (add image alt attribute)
2593 * - class = image class attribute (default 'userpicture')
2594 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2595 * - includefullname=false (whether to include the user's full name together with the user picture)
2596 * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2597 * @return string HTML fragment
2599 public function user_picture(stdClass $user, array $options = null) {
2600 $userpicture = new user_picture($user);
2601 foreach ((array)$options as $key=>$value) {
2602 if (property_exists($userpicture, $key)) {
2603 $userpicture->$key = $value;
2606 return $this->render($userpicture);
2610 * Internal implementation of user image rendering.
2612 * @param user_picture $userpicture
2613 * @return string
2615 protected function render_user_picture(user_picture $userpicture) {
2616 global $CFG;
2618 $user = $userpicture->user;
2619 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
2621 $alt = '';
2622 if ($userpicture->alttext) {
2623 if (!empty($user->imagealt)) {
2624 $alt = $user->imagealt;
2628 if (empty($userpicture->size)) {
2629 $size = 35;
2630 } else if ($userpicture->size === true or $userpicture->size == 1) {
2631 $size = 100;
2632 } else {
2633 $size = $userpicture->size;
2636 $class = $userpicture->class;
2638 if ($user->picture == 0) {
2639 $class .= ' defaultuserpic';
2642 $src = $userpicture->get_url($this->page, $this);
2644 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2645 if (!$userpicture->visibletoscreenreaders) {
2646 $alt = '';
2648 $attributes['alt'] = $alt;
2650 if (!empty($alt)) {
2651 $attributes['title'] = $alt;
2654 // Get the image html output first, auto generated based on initials if one isn't already set.
2655 if ($user->picture == 0 && empty($CFG->enablegravatar) && !defined('BEHAT_SITE_RUNNING')) {
2656 $output = html_writer::tag('span', mb_substr($user->firstname, 0, 1) . mb_substr($user->lastname, 0, 1),
2657 ['class' => 'userinitials size-' . $size]);
2658 } else {
2659 $output = html_writer::empty_tag('img', $attributes);
2662 // Show fullname together with the picture when desired.
2663 if ($userpicture->includefullname) {
2664 $output .= fullname($userpicture->user, $canviewfullnames);
2667 if (empty($userpicture->courseid)) {
2668 $courseid = $this->page->course->id;
2669 } else {
2670 $courseid = $userpicture->courseid;
2672 if ($courseid == SITEID) {
2673 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2674 } else {
2675 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2678 // Then wrap it in link if needed. Also we don't wrap it in link if the link redirects to itself.
2679 if (!$userpicture->link ||
2680 ($this->page->has_set_url() && $this->page->url == $url)) { // Protect against unset page->url.
2681 return $output;
2684 $attributes = array('href' => $url, 'class' => 'd-inline-block aabtn');
2685 if (!$userpicture->visibletoscreenreaders) {
2686 $attributes['tabindex'] = '-1';
2687 $attributes['aria-hidden'] = 'true';
2690 if ($userpicture->popup) {
2691 $id = html_writer::random_id('userpicture');
2692 $attributes['id'] = $id;
2693 $this->add_action_handler(new popup_action('click', $url), $id);
2696 return html_writer::tag('a', $output, $attributes);
2700 * Internal implementation of file tree viewer items rendering.
2702 * @param array $dir
2703 * @return string
2705 public function htmllize_file_tree($dir) {
2706 if (empty($dir['subdirs']) and empty($dir['files'])) {
2707 return '';
2709 $result = '<ul>';
2710 foreach ($dir['subdirs'] as $subdir) {
2711 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2713 foreach ($dir['files'] as $file) {
2714 $filename = $file->get_filename();
2715 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2717 $result .= '</ul>';
2719 return $result;
2723 * Returns HTML to display the file picker
2725 * <pre>
2726 * $OUTPUT->file_picker($options);
2727 * </pre>
2729 * Theme developers: DO NOT OVERRIDE! Please override function
2730 * {@link core_renderer::render_file_picker()} instead.
2732 * @param array $options associative array with file manager options
2733 * options are:
2734 * maxbytes=>-1,
2735 * itemid=>0,
2736 * client_id=>uniqid(),
2737 * acepted_types=>'*',
2738 * return_types=>FILE_INTERNAL,
2739 * context=>current page context
2740 * @return string HTML fragment
2742 public function file_picker($options) {
2743 $fp = new file_picker($options);
2744 return $this->render($fp);
2748 * Internal implementation of file picker rendering.
2750 * @param file_picker $fp
2751 * @return string
2753 public function render_file_picker(file_picker $fp) {
2754 $options = $fp->options;
2755 $client_id = $options->client_id;
2756 $strsaved = get_string('filesaved', 'repository');
2757 $straddfile = get_string('openpicker', 'repository');
2758 $strloading = get_string('loading', 'repository');
2759 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2760 $strdroptoupload = get_string('droptoupload', 'moodle');
2761 $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
2763 $currentfile = $options->currentfile;
2764 if (empty($currentfile)) {
2765 $currentfile = '';
2766 } else {
2767 $currentfile .= ' - ';
2769 if ($options->maxbytes) {
2770 $size = $options->maxbytes;
2771 } else {
2772 $size = get_max_upload_file_size();
2774 if ($size == -1) {
2775 $maxsize = '';
2776 } else {
2777 $maxsize = get_string('maxfilesize', 'moodle', display_size($size, 0));
2779 if ($options->buttonname) {
2780 $buttonname = ' name="' . $options->buttonname . '"';
2781 } else {
2782 $buttonname = '';
2784 $html = <<<EOD
2785 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2786 $iconprogress
2787 </div>
2788 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2789 <div>
2790 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2791 <span> $maxsize </span>
2792 </div>
2793 EOD;
2794 if ($options->env != 'url') {
2795 $html .= <<<EOD
2796 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2797 <div class="filepicker-filename">
2798 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2799 <div class="dndupload-progressbars"></div>
2800 </div>
2801 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2802 </div>
2803 EOD;
2805 $html .= '</div>';
2806 return $html;
2810 * @deprecated since Moodle 3.2
2812 public function update_module_button() {
2813 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2814 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2815 'Themes can choose to display the link in the buttons row consistently for all module types.');
2819 * Returns HTML to display a "Turn editing on/off" button in a form.
2821 * @param moodle_url $url The URL + params to send through when clicking the button
2822 * @return string HTML the button
2824 public function edit_button(moodle_url $url) {
2826 if ($this->page->theme->haseditswitch == true) {
2827 return;
2829 $url->param('sesskey', sesskey());
2830 if ($this->page->user_is_editing()) {
2831 $url->param('edit', 'off');
2832 $editstring = get_string('turneditingoff');
2833 } else {
2834 $url->param('edit', 'on');
2835 $editstring = get_string('turneditingon');
2838 return $this->single_button($url, $editstring);
2842 * Create a navbar switch for toggling editing mode.
2844 * @return string Html containing the edit switch
2846 public function edit_switch() {
2847 if ($this->page->user_allowed_editing()) {
2849 $temp = (object) [
2850 'legacyseturl' => (new moodle_url('/editmode.php'))->out(false),
2851 'pagecontextid' => $this->page->context->id,
2852 'pageurl' => $this->page->url,
2853 'sesskey' => sesskey(),
2855 if ($this->page->user_is_editing()) {
2856 $temp->checked = true;
2858 return $this->render_from_template('core/editswitch', $temp);
2863 * Returns HTML to display a simple button to close a window
2865 * @param string $text The lang string for the button's label (already output from get_string())
2866 * @return string html fragment
2868 public function close_window_button($text='') {
2869 if (empty($text)) {
2870 $text = get_string('closewindow');
2872 $button = new single_button(new moodle_url('#'), $text, 'get');
2873 $button->add_action(new component_action('click', 'close_window'));
2875 return $this->container($this->render($button), 'closewindow');
2879 * Output an error message. By default wraps the error message in <span class="error">.
2880 * If the error message is blank, nothing is output.
2882 * @param string $message the error message.
2883 * @return string the HTML to output.
2885 public function error_text($message) {
2886 if (empty($message)) {
2887 return '';
2889 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2890 return html_writer::tag('span', $message, array('class' => 'error'));
2894 * Do not call this function directly.
2896 * To terminate the current script with a fatal error, call the {@link print_error}
2897 * function, or throw an exception. Doing either of those things will then call this
2898 * function to display the error, before terminating the execution.
2900 * @param string $message The message to output
2901 * @param string $moreinfourl URL where more info can be found about the error
2902 * @param string $link Link for the Continue button
2903 * @param array $backtrace The execution backtrace
2904 * @param string $debuginfo Debugging information
2905 * @return string the HTML to output.
2907 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2908 global $CFG;
2910 $output = '';
2911 $obbuffer = '';
2913 if ($this->has_started()) {
2914 // we can not always recover properly here, we have problems with output buffering,
2915 // html tables, etc.
2916 $output .= $this->opencontainers->pop_all_but_last();
2918 } else {
2919 // It is really bad if library code throws exception when output buffering is on,
2920 // because the buffered text would be printed before our start of page.
2921 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2922 error_reporting(0); // disable notices from gzip compression, etc.
2923 while (ob_get_level() > 0) {
2924 $buff = ob_get_clean();
2925 if ($buff === false) {
2926 break;
2928 $obbuffer .= $buff;
2930 error_reporting($CFG->debug);
2932 // Output not yet started.
2933 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2934 if (empty($_SERVER['HTTP_RANGE'])) {
2935 @header($protocol . ' 404 Not Found');
2936 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2937 // Coax iOS 10 into sending the session cookie.
2938 @header($protocol . ' 403 Forbidden');
2939 } else {
2940 // Must stop byteserving attempts somehow,
2941 // this is weird but Chrome PDF viewer can be stopped only with 407!
2942 @header($protocol . ' 407 Proxy Authentication Required');
2945 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2946 $this->page->set_url('/'); // no url
2947 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2948 $this->page->set_title(get_string('error'));
2949 $this->page->set_heading($this->page->course->fullname);
2950 // No need to display the activity header when encountering an error.
2951 $this->page->activityheader->disable();
2952 $output .= $this->header();
2955 $message = '<p class="errormessage">' . s($message) . '</p>'.
2956 '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
2957 get_string('moreinformation') . '</a></p>';
2958 if (empty($CFG->rolesactive)) {
2959 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2960 //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.
2962 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2964 if ($CFG->debugdeveloper) {
2965 $labelsep = get_string('labelsep', 'langconfig');
2966 if (!empty($debuginfo)) {
2967 $debuginfo = s($debuginfo); // removes all nasty JS
2968 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2969 $label = get_string('debuginfo', 'debug') . $labelsep;
2970 $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
2972 if (!empty($backtrace)) {
2973 $label = get_string('stacktrace', 'debug') . $labelsep;
2974 $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
2976 if ($obbuffer !== '' ) {
2977 $label = get_string('outputbuffer', 'debug') . $labelsep;
2978 $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
2982 if (empty($CFG->rolesactive)) {
2983 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2984 } else if (!empty($link)) {
2985 $output .= $this->continue_button($link);
2988 $output .= $this->footer();
2990 // Padding to encourage IE to display our error page, rather than its own.
2991 $output .= str_repeat(' ', 512);
2993 return $output;
2997 * Output a notification (that is, a status message about something that has just happened).
2999 * Note: \core\notification::add() may be more suitable for your usage.
3001 * @param string $message The message to print out.
3002 * @param ?string $type The type of notification. See constants on \core\output\notification.
3003 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
3004 * @return string the HTML to output.
3006 public function notification($message, $type = null, $closebutton = true) {
3007 $typemappings = [
3008 // Valid types.
3009 'success' => \core\output\notification::NOTIFY_SUCCESS,
3010 'info' => \core\output\notification::NOTIFY_INFO,
3011 'warning' => \core\output\notification::NOTIFY_WARNING,
3012 'error' => \core\output\notification::NOTIFY_ERROR,
3014 // Legacy types mapped to current types.
3015 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
3016 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
3017 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
3018 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
3019 'notifymessage' => \core\output\notification::NOTIFY_INFO,
3020 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
3021 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
3024 $extraclasses = [];
3026 if ($type) {
3027 if (strpos($type, ' ') === false) {
3028 // No spaces in the list of classes, therefore no need to loop over and determine the class.
3029 if (isset($typemappings[$type])) {
3030 $type = $typemappings[$type];
3031 } else {
3032 // The value provided did not match a known type. It must be an extra class.
3033 $extraclasses = [$type];
3035 } else {
3036 // Identify what type of notification this is.
3037 $classarray = explode(' ', self::prepare_classes($type));
3039 // Separate out the type of notification from the extra classes.
3040 foreach ($classarray as $class) {
3041 if (isset($typemappings[$class])) {
3042 $type = $typemappings[$class];
3043 } else {
3044 $extraclasses[] = $class;
3050 $notification = new \core\output\notification($message, $type, $closebutton);
3051 if (count($extraclasses)) {
3052 $notification->set_extra_classes($extraclasses);
3055 // Return the rendered template.
3056 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3060 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3062 public function notify_problem() {
3063 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
3064 'please use \core\notification::add(), or \core\output\notification as required.');
3068 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3070 public function notify_success() {
3071 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
3072 'please use \core\notification::add(), or \core\output\notification as required.');
3076 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3078 public function notify_message() {
3079 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
3080 'please use \core\notification::add(), or \core\output\notification as required.');
3084 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3086 public function notify_redirect() {
3087 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
3088 'please use \core\notification::add(), or \core\output\notification as required.');
3092 * Render a notification (that is, a status message about something that has
3093 * just happened).
3095 * @param \core\output\notification $notification the notification to print out
3096 * @return string the HTML to output.
3098 protected function render_notification(\core\output\notification $notification) {
3099 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3103 * Returns HTML to display a continue button that goes to a particular URL.
3105 * @param string|moodle_url $url The url the button goes to.
3106 * @return string the HTML to output.
3108 public function continue_button($url) {
3109 if (!($url instanceof moodle_url)) {
3110 $url = new moodle_url($url);
3112 $button = new single_button($url, get_string('continue'), 'get', true);
3113 $button->class = 'continuebutton';
3115 return $this->render($button);
3119 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
3121 * Theme developers: DO NOT OVERRIDE! Please override function
3122 * {@link core_renderer::render_paging_bar()} instead.
3124 * @param int $totalcount The total number of entries available to be paged through
3125 * @param int $page The page you are currently viewing
3126 * @param int $perpage The number of entries that should be shown per page
3127 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3128 * @param string $pagevar name of page parameter that holds the page number
3129 * @return string the HTML to output.
3131 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3132 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3133 return $this->render($pb);
3137 * Returns HTML to display the paging bar.
3139 * @param paging_bar $pagingbar
3140 * @return string the HTML to output.
3142 protected function render_paging_bar(paging_bar $pagingbar) {
3143 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3144 $pagingbar->maxdisplay = 10;
3145 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3149 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3151 * @param string $current the currently selected letter.
3152 * @param string $class class name to add to this initial bar.
3153 * @param string $title the name to put in front of this initial bar.
3154 * @param string $urlvar URL parameter name for this initial.
3155 * @param string $url URL object.
3156 * @param array $alpha of letters in the alphabet.
3157 * @return string the HTML to output.
3159 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3160 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3161 return $this->render($ib);
3165 * Internal implementation of initials bar rendering.
3167 * @param initials_bar $initialsbar
3168 * @return string
3170 protected function render_initials_bar(initials_bar $initialsbar) {
3171 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3175 * Output the place a skip link goes to.
3177 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3178 * @return string the HTML to output.
3180 public function skip_link_target($id = null) {
3181 return html_writer::span('', '', array('id' => $id));
3185 * Outputs a heading
3187 * @param string $text The text of the heading
3188 * @param int $level The level of importance of the heading. Defaulting to 2
3189 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3190 * @param string $id An optional ID
3191 * @return string the HTML to output.
3193 public function heading($text, $level = 2, $classes = null, $id = null) {
3194 $level = (integer) $level;
3195 if ($level < 1 or $level > 6) {
3196 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3198 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3202 * Outputs a box.
3204 * @param string $contents The contents of the box
3205 * @param string $classes A space-separated list of CSS classes
3206 * @param string $id An optional ID
3207 * @param array $attributes An array of other attributes to give the box.
3208 * @return string the HTML to output.
3210 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3211 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3215 * Outputs the opening section of a box.
3217 * @param string $classes A space-separated list of CSS classes
3218 * @param string $id An optional ID
3219 * @param array $attributes An array of other attributes to give the box.
3220 * @return string the HTML to output.
3222 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3223 $this->opencontainers->push('box', html_writer::end_tag('div'));
3224 $attributes['id'] = $id;
3225 $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes);
3226 return html_writer::start_tag('div', $attributes);
3230 * Outputs the closing section of a box.
3232 * @return string the HTML to output.
3234 public function box_end() {
3235 return $this->opencontainers->pop('box');
3239 * Outputs a container.
3241 * @param string $contents The contents of the box
3242 * @param string $classes A space-separated list of CSS classes
3243 * @param string $id An optional ID
3244 * @return string the HTML to output.
3246 public function container($contents, $classes = null, $id = null) {
3247 return $this->container_start($classes, $id) . $contents . $this->container_end();
3251 * Outputs the opening section of a container.
3253 * @param string $classes A space-separated list of CSS classes
3254 * @param string $id An optional ID
3255 * @return string the HTML to output.
3257 public function container_start($classes = null, $id = null) {
3258 $this->opencontainers->push('container', html_writer::end_tag('div'));
3259 return html_writer::start_tag('div', array('id' => $id,
3260 'class' => renderer_base::prepare_classes($classes)));
3264 * Outputs the closing section of a container.
3266 * @return string the HTML to output.
3268 public function container_end() {
3269 return $this->opencontainers->pop('container');
3273 * Make nested HTML lists out of the items
3275 * The resulting list will look something like this:
3277 * <pre>
3278 * <<ul>>
3279 * <<li>><div class='tree_item parent'>(item contents)</div>
3280 * <<ul>
3281 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3282 * <</ul>>
3283 * <</li>>
3284 * <</ul>>
3285 * </pre>
3287 * @param array $items
3288 * @param array $attrs html attributes passed to the top ofs the list
3289 * @return string HTML
3291 public function tree_block_contents($items, $attrs = array()) {
3292 // exit if empty, we don't want an empty ul element
3293 if (empty($items)) {
3294 return '';
3296 // array of nested li elements
3297 $lis = array();
3298 foreach ($items as $item) {
3299 // this applies to the li item which contains all child lists too
3300 $content = $item->content($this);
3301 $liclasses = array($item->get_css_type());
3302 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3303 $liclasses[] = 'collapsed';
3305 if ($item->isactive === true) {
3306 $liclasses[] = 'current_branch';
3308 $liattr = array('class'=>join(' ',$liclasses));
3309 // class attribute on the div item which only contains the item content
3310 $divclasses = array('tree_item');
3311 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3312 $divclasses[] = 'branch';
3313 } else {
3314 $divclasses[] = 'leaf';
3316 if (!empty($item->classes) && count($item->classes)>0) {
3317 $divclasses[] = join(' ', $item->classes);
3319 $divattr = array('class'=>join(' ', $divclasses));
3320 if (!empty($item->id)) {
3321 $divattr['id'] = $item->id;
3323 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3324 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3325 $content = html_writer::empty_tag('hr') . $content;
3327 $content = html_writer::tag('li', $content, $liattr);
3328 $lis[] = $content;
3330 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3334 * Returns a search box.
3336 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3337 * @return string HTML with the search form hidden by default.
3339 public function search_box($id = false) {
3340 global $CFG;
3342 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3343 // result in an extra included file for each site, even the ones where global search
3344 // is disabled.
3345 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3346 return '';
3349 $data = [
3350 'action' => new moodle_url('/search/index.php'),
3351 'hiddenfields' => (object) ['name' => 'context', 'value' => $this->page->context->id],
3352 'inputname' => 'q',
3353 'searchstring' => get_string('search'),
3355 return $this->render_from_template('core/search_input_navbar', $data);
3359 * Allow plugins to provide some content to be rendered in the navbar.
3360 * The plugin must define a PLUGIN_render_navbar_output function that returns
3361 * the HTML they wish to add to the navbar.
3363 * @return string HTML for the navbar
3365 public function navbar_plugin_output() {
3366 $output = '';
3368 // Give subsystems an opportunity to inject extra html content. The callback
3369 // must always return a string containing valid html.
3370 foreach (\core_component::get_core_subsystems() as $name => $path) {
3371 if ($path) {
3372 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3376 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3377 foreach ($pluginsfunction as $plugintype => $plugins) {
3378 foreach ($plugins as $pluginfunction) {
3379 $output .= $pluginfunction($this);
3384 return $output;
3388 * Construct a user menu, returning HTML that can be echoed out by a
3389 * layout file.
3391 * @param stdClass $user A user object, usually $USER.
3392 * @param bool $withlinks true if a dropdown should be built.
3393 * @return string HTML fragment.
3395 public function user_menu($user = null, $withlinks = null) {
3396 global $USER, $CFG;
3397 require_once($CFG->dirroot . '/user/lib.php');
3399 if (is_null($user)) {
3400 $user = $USER;
3403 // Note: this behaviour is intended to match that of core_renderer::login_info,
3404 // but should not be considered to be good practice; layout options are
3405 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3406 if (is_null($withlinks)) {
3407 $withlinks = empty($this->page->layout_options['nologinlinks']);
3410 // Add a class for when $withlinks is false.
3411 $usermenuclasses = 'usermenu';
3412 if (!$withlinks) {
3413 $usermenuclasses .= ' withoutlinks';
3416 $returnstr = "";
3418 // If during initial install, return the empty return string.
3419 if (during_initial_install()) {
3420 return $returnstr;
3423 $loginpage = $this->is_login_page();
3424 $loginurl = get_login_url();
3426 // Get some navigation opts.
3427 $opts = user_get_user_navigation_info($user, $this->page);
3429 if (!empty($opts->unauthenticateduser)) {
3430 $returnstr = get_string($opts->unauthenticateduser['content'], 'moodle');
3431 // If not logged in, show the typical not-logged-in string.
3432 if (!$loginpage && (!$opts->unauthenticateduser['guest'] || $withlinks)) {
3433 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3436 return html_writer::div(
3437 html_writer::span(
3438 $returnstr,
3439 'login nav-link'
3441 $usermenuclasses
3445 $avatarclasses = "avatars";
3446 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3447 $usertextcontents = $opts->metadata['userfullname'];
3449 // Other user.
3450 if (!empty($opts->metadata['asotheruser'])) {
3451 $avatarcontents .= html_writer::span(
3452 $opts->metadata['realuseravatar'],
3453 'avatar realuser'
3455 $usertextcontents = $opts->metadata['realuserfullname'];
3456 $usertextcontents .= html_writer::tag(
3457 'span',
3458 get_string(
3459 'loggedinas',
3460 'moodle',
3461 html_writer::span(
3462 $opts->metadata['userfullname'],
3463 'value'
3466 array('class' => 'meta viewingas')
3470 // Role.
3471 if (!empty($opts->metadata['asotherrole'])) {
3472 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3473 $usertextcontents .= html_writer::span(
3474 $opts->metadata['rolename'],
3475 'meta role role-' . $role
3479 // User login failures.
3480 if (!empty($opts->metadata['userloginfail'])) {
3481 $usertextcontents .= html_writer::span(
3482 $opts->metadata['userloginfail'],
3483 'meta loginfailures'
3487 // MNet.
3488 if (!empty($opts->metadata['asmnetuser'])) {
3489 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3490 $usertextcontents .= html_writer::span(
3491 $opts->metadata['mnetidprovidername'],
3492 'meta mnet mnet-' . $mnet
3496 $returnstr .= html_writer::span(
3497 html_writer::span($usertextcontents, 'usertext mr-1') .
3498 html_writer::span($avatarcontents, $avatarclasses),
3499 'userbutton'
3502 // Create a divider (well, a filler).
3503 $divider = new action_menu_filler();
3504 $divider->primary = false;
3506 $am = new action_menu();
3507 $am->set_menu_trigger(
3508 $returnstr,
3509 'nav-link'
3511 $am->set_action_label(get_string('usermenu'));
3512 $am->set_nowrap_on_items();
3513 if ($withlinks) {
3514 $navitemcount = count($opts->navitems);
3515 $idx = 0;
3516 foreach ($opts->navitems as $key => $value) {
3518 switch ($value->itemtype) {
3519 case 'divider':
3520 // If the nav item is a divider, add one and skip link processing.
3521 $am->add($divider);
3522 break;
3524 case 'invalid':
3525 // Silently skip invalid entries (should we post a notification?).
3526 break;
3528 case 'link':
3529 // Process this as a link item.
3530 $pix = null;
3531 if (isset($value->pix) && !empty($value->pix)) {
3532 $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
3533 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3534 $value->title = html_writer::img(
3535 $value->imgsrc,
3536 $value->title,
3537 array('class' => 'iconsmall')
3538 ) . $value->title;
3541 $al = new action_menu_link_secondary(
3542 $value->url,
3543 $pix,
3544 $value->title,
3545 array('class' => 'icon')
3547 if (!empty($value->titleidentifier)) {
3548 $al->attributes['data-title'] = $value->titleidentifier;
3550 $am->add($al);
3551 break;
3554 $idx++;
3556 // Add dividers after the first item and before the last item.
3557 if ($idx == 1 || $idx == $navitemcount - 1) {
3558 $am->add($divider);
3563 return html_writer::div(
3564 $this->render($am),
3565 $usermenuclasses
3570 * Secure layout login info.
3572 * @return string
3574 public function secure_layout_login_info() {
3575 if (get_config('core', 'logininfoinsecurelayout')) {
3576 return $this->login_info(false);
3577 } else {
3578 return '';
3583 * Returns the language menu in the secure layout.
3585 * No custom menu items are passed though, such that it will render only the language selection.
3587 * @return string
3589 public function secure_layout_language_menu() {
3590 if (get_config('core', 'langmenuinsecurelayout')) {
3591 $custommenu = new custom_menu('', current_language());
3592 return $this->render_custom_menu($custommenu);
3593 } else {
3594 return '';
3599 * This renders the navbar.
3600 * Uses bootstrap compatible html.
3602 public function navbar() {
3603 return $this->render_from_template('core/navbar', $this->page->navbar);
3607 * Renders a breadcrumb navigation node object.
3609 * @param breadcrumb_navigation_node $item The navigation node to render.
3610 * @return string HTML fragment
3612 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3614 if ($item->action instanceof moodle_url) {
3615 $content = $item->get_content();
3616 $title = $item->get_title();
3617 $attributes = array();
3618 $attributes['itemprop'] = 'url';
3619 if ($title !== '') {
3620 $attributes['title'] = $title;
3622 if ($item->hidden) {
3623 $attributes['class'] = 'dimmed_text';
3625 if ($item->is_last()) {
3626 $attributes['aria-current'] = 'page';
3628 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3629 $content = html_writer::link($item->action, $content, $attributes);
3631 $attributes = array();
3632 $attributes['itemscope'] = '';
3633 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3634 $content = html_writer::tag('span', $content, $attributes);
3636 } else {
3637 $content = $this->render_navigation_node($item);
3639 return $content;
3643 * Renders a navigation node object.
3645 * @param navigation_node $item The navigation node to render.
3646 * @return string HTML fragment
3648 protected function render_navigation_node(navigation_node $item) {
3649 $content = $item->get_content();
3650 $title = $item->get_title();
3651 if ($item->icon instanceof renderable && !$item->hideicon) {
3652 $icon = $this->render($item->icon);
3653 $content = $icon.$content; // use CSS for spacing of icons
3655 if ($item->helpbutton !== null) {
3656 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3658 if ($content === '') {
3659 return '';
3661 if ($item->action instanceof action_link) {
3662 $link = $item->action;
3663 if ($item->hidden) {
3664 $link->add_class('dimmed');
3666 if (!empty($content)) {
3667 // Providing there is content we will use that for the link content.
3668 $link->text = $content;
3670 $content = $this->render($link);
3671 } else if ($item->action instanceof moodle_url) {
3672 $attributes = array();
3673 if ($title !== '') {
3674 $attributes['title'] = $title;
3676 if ($item->hidden) {
3677 $attributes['class'] = 'dimmed_text';
3679 $content = html_writer::link($item->action, $content, $attributes);
3681 } else if (is_string($item->action) || empty($item->action)) {
3682 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3683 if ($title !== '') {
3684 $attributes['title'] = $title;
3686 if ($item->hidden) {
3687 $attributes['class'] = 'dimmed_text';
3689 $content = html_writer::tag('span', $content, $attributes);
3691 return $content;
3695 * Accessibility: Right arrow-like character is
3696 * used in the breadcrumb trail, course navigation menu
3697 * (previous/next activity), calendar, and search forum block.
3698 * If the theme does not set characters, appropriate defaults
3699 * are set automatically. Please DO NOT
3700 * use &lt; &gt; &raquo; - these are confusing for blind users.
3702 * @return string
3704 public function rarrow() {
3705 return $this->page->theme->rarrow;
3709 * Accessibility: Left arrow-like character is
3710 * used in the breadcrumb trail, course navigation menu
3711 * (previous/next activity), calendar, and search forum block.
3712 * If the theme does not set characters, appropriate defaults
3713 * are set automatically. Please DO NOT
3714 * use &lt; &gt; &raquo; - these are confusing for blind users.
3716 * @return string
3718 public function larrow() {
3719 return $this->page->theme->larrow;
3723 * Accessibility: Up arrow-like character is used in
3724 * the book heirarchical navigation.
3725 * If the theme does not set characters, appropriate defaults
3726 * are set automatically. Please DO NOT
3727 * use ^ - this is confusing for blind users.
3729 * @return string
3731 public function uarrow() {
3732 return $this->page->theme->uarrow;
3736 * Accessibility: Down arrow-like character.
3737 * If the theme does not set characters, appropriate defaults
3738 * are set automatically.
3740 * @return string
3742 public function darrow() {
3743 return $this->page->theme->darrow;
3747 * Returns the custom menu if one has been set
3749 * A custom menu can be configured by browsing to
3750 * Settings: Administration > Appearance > Themes > Theme settings
3751 * and then configuring the custommenu config setting as described.
3753 * Theme developers: DO NOT OVERRIDE! Please override function
3754 * {@link core_renderer::render_custom_menu()} instead.
3756 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3757 * @return string
3759 public function custom_menu($custommenuitems = '') {
3760 global $CFG;
3762 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3763 $custommenuitems = $CFG->custommenuitems;
3765 $custommenu = new custom_menu($custommenuitems, current_language());
3766 return $this->render_custom_menu($custommenu);
3770 * We want to show the custom menus as a list of links in the footer on small screens.
3771 * Just return the menu object exported so we can render it differently.
3773 public function custom_menu_flat() {
3774 global $CFG;
3775 $custommenuitems = '';
3777 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3778 $custommenuitems = $CFG->custommenuitems;
3780 $custommenu = new custom_menu($custommenuitems, current_language());
3781 $langs = get_string_manager()->get_list_of_translations();
3782 $haslangmenu = $this->lang_menu() != '';
3784 if ($haslangmenu) {
3785 $strlang = get_string('language');
3786 $currentlang = current_language();
3787 if (isset($langs[$currentlang])) {
3788 $currentlang = $langs[$currentlang];
3789 } else {
3790 $currentlang = $strlang;
3792 $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3793 foreach ($langs as $langtype => $langname) {
3794 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3798 return $custommenu->export_for_template($this);
3802 * Renders a custom menu object (located in outputcomponents.php)
3804 * The custom menu this method produces makes use of the YUI3 menunav widget
3805 * and requires very specific html elements and classes.
3807 * @staticvar int $menucount
3808 * @param custom_menu $menu
3809 * @return string
3811 protected function render_custom_menu(custom_menu $menu) {
3812 global $CFG;
3814 $langs = get_string_manager()->get_list_of_translations();
3815 $haslangmenu = $this->lang_menu() != '';
3817 if (!$menu->has_children() && !$haslangmenu) {
3818 return '';
3821 if ($haslangmenu) {
3822 $strlang = get_string('language');
3823 $currentlang = current_language();
3824 if (isset($langs[$currentlang])) {
3825 $currentlang = $langs[$currentlang];
3826 } else {
3827 $currentlang = $strlang;
3829 $this->language = $menu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3830 foreach ($langs as $langtype => $langname) {
3831 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3835 $content = '';
3836 foreach ($menu->get_children() as $item) {
3837 $context = $item->export_for_template($this);
3838 $content .= $this->render_from_template('core/custom_menu_item', $context);
3841 return $content;
3845 * Renders a custom menu node as part of a submenu
3847 * The custom menu this method produces makes use of the YUI3 menunav widget
3848 * and requires very specific html elements and classes.
3850 * @see core:renderer::render_custom_menu()
3852 * @staticvar int $submenucount
3853 * @param custom_menu_item $menunode
3854 * @return string
3856 protected function render_custom_menu_item(custom_menu_item $menunode) {
3857 // Required to ensure we get unique trackable id's
3858 static $submenucount = 0;
3859 if ($menunode->has_children()) {
3860 // If the child has menus render it as a sub menu
3861 $submenucount++;
3862 $content = html_writer::start_tag('li');
3863 if ($menunode->get_url() !== null) {
3864 $url = $menunode->get_url();
3865 } else {
3866 $url = '#cm_submenu_'.$submenucount;
3868 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3869 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3870 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3871 $content .= html_writer::start_tag('ul');
3872 foreach ($menunode->get_children() as $menunode) {
3873 $content .= $this->render_custom_menu_item($menunode);
3875 $content .= html_writer::end_tag('ul');
3876 $content .= html_writer::end_tag('div');
3877 $content .= html_writer::end_tag('div');
3878 $content .= html_writer::end_tag('li');
3879 } else {
3880 // The node doesn't have children so produce a final menuitem.
3881 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3882 $content = '';
3883 if (preg_match("/^#+$/", $menunode->get_text())) {
3885 // This is a divider.
3886 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3887 } else {
3888 $content = html_writer::start_tag(
3889 'li',
3890 array(
3891 'class' => 'yui3-menuitem'
3894 if ($menunode->get_url() !== null) {
3895 $url = $menunode->get_url();
3896 } else {
3897 $url = '#';
3899 $content .= html_writer::link(
3900 $url,
3901 $menunode->get_text(),
3902 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3905 $content .= html_writer::end_tag('li');
3907 // Return the sub menu
3908 return $content;
3912 * Renders theme links for switching between default and other themes.
3914 * @return string
3916 protected function theme_switch_links() {
3918 $actualdevice = core_useragent::get_device_type();
3919 $currentdevice = $this->page->devicetypeinuse;
3920 $switched = ($actualdevice != $currentdevice);
3922 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3923 // The user is using the a default device and hasn't switched so don't shown the switch
3924 // device links.
3925 return '';
3928 if ($switched) {
3929 $linktext = get_string('switchdevicerecommended');
3930 $devicetype = $actualdevice;
3931 } else {
3932 $linktext = get_string('switchdevicedefault');
3933 $devicetype = 'default';
3935 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3937 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3938 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3939 $content .= html_writer::end_tag('div');
3941 return $content;
3945 * Renders tabs
3947 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3949 * Theme developers: In order to change how tabs are displayed please override functions
3950 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3952 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3953 * @param string|null $selected which tab to mark as selected, all parent tabs will
3954 * automatically be marked as activated
3955 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3956 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3957 * @return string
3959 public final function tabtree($tabs, $selected = null, $inactive = null) {
3960 return $this->render(new tabtree($tabs, $selected, $inactive));
3964 * Renders tabtree
3966 * @param tabtree $tabtree
3967 * @return string
3969 protected function render_tabtree(tabtree $tabtree) {
3970 if (empty($tabtree->subtree)) {
3971 return '';
3973 $data = $tabtree->export_for_template($this);
3974 return $this->render_from_template('core/tabtree', $data);
3978 * Renders tabobject (part of tabtree)
3980 * This function is called from {@link core_renderer::render_tabtree()}
3981 * and also it calls itself when printing the $tabobject subtree recursively.
3983 * Property $tabobject->level indicates the number of row of tabs.
3985 * @param tabobject $tabobject
3986 * @return string HTML fragment
3988 protected function render_tabobject(tabobject $tabobject) {
3989 $str = '';
3991 // Print name of the current tab.
3992 if ($tabobject instanceof tabtree) {
3993 // No name for tabtree root.
3994 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3995 // Tab name without a link. The <a> tag is used for styling.
3996 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3997 } else {
3998 // Tab name with a link.
3999 if (!($tabobject->link instanceof moodle_url)) {
4000 // backward compartibility when link was passed as quoted string
4001 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
4002 } else {
4003 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
4007 if (empty($tabobject->subtree)) {
4008 if ($tabobject->selected) {
4009 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
4011 return $str;
4014 // Print subtree.
4015 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
4016 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
4017 $cnt = 0;
4018 foreach ($tabobject->subtree as $tab) {
4019 $liclass = '';
4020 if (!$cnt) {
4021 $liclass .= ' first';
4023 if ($cnt == count($tabobject->subtree) - 1) {
4024 $liclass .= ' last';
4026 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
4027 $liclass .= ' onerow';
4030 if ($tab->selected) {
4031 $liclass .= ' here selected';
4032 } else if ($tab->activated) {
4033 $liclass .= ' here active';
4036 // This will recursively call function render_tabobject() for each item in subtree.
4037 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
4038 $cnt++;
4040 $str .= html_writer::end_tag('ul');
4043 return $str;
4047 * Get the HTML for blocks in the given region.
4049 * @since Moodle 2.5.1 2.6
4050 * @param string $region The region to get HTML for.
4051 * @param array $classes Wrapping tag classes.
4052 * @param string $tag Wrapping tag.
4053 * @param boolean $fakeblocksonly Include fake blocks only.
4054 * @return string HTML.
4056 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
4057 $displayregion = $this->page->apply_theme_region_manipulations($region);
4058 $classes = (array)$classes;
4059 $classes[] = 'block-region';
4060 $attributes = array(
4061 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
4062 'class' => join(' ', $classes),
4063 'data-blockregion' => $displayregion,
4064 'data-droptarget' => '1'
4066 if ($this->page->blocks->region_has_content($displayregion, $this)) {
4067 $content = $this->blocks_for_region($displayregion, $fakeblocksonly);
4068 } else {
4069 $content = '';
4071 return html_writer::tag($tag, $content, $attributes);
4075 * Renders a custom block region.
4077 * Use this method if you want to add an additional block region to the content of the page.
4078 * Please note this should only be used in special situations.
4079 * We want to leave the theme is control where ever possible!
4081 * This method must use the same method that the theme uses within its layout file.
4082 * As such it asks the theme what method it is using.
4083 * It can be one of two values, blocks or blocks_for_region (deprecated).
4085 * @param string $regionname The name of the custom region to add.
4086 * @return string HTML for the block region.
4088 public function custom_block_region($regionname) {
4089 if ($this->page->theme->get_block_render_method() === 'blocks') {
4090 return $this->blocks($regionname);
4091 } else {
4092 return $this->blocks_for_region($regionname);
4097 * Returns the CSS classes to apply to the body tag.
4099 * @since Moodle 2.5.1 2.6
4100 * @param array $additionalclasses Any additional classes to apply.
4101 * @return string
4103 public function body_css_classes(array $additionalclasses = array()) {
4104 return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses);
4108 * The ID attribute to apply to the body tag.
4110 * @since Moodle 2.5.1 2.6
4111 * @return string
4113 public function body_id() {
4114 return $this->page->bodyid;
4118 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4120 * @since Moodle 2.5.1 2.6
4121 * @param string|array $additionalclasses Any additional classes to give the body tag,
4122 * @return string
4124 public function body_attributes($additionalclasses = array()) {
4125 if (!is_array($additionalclasses)) {
4126 $additionalclasses = explode(' ', $additionalclasses);
4128 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4132 * Gets HTML for the page heading.
4134 * @since Moodle 2.5.1 2.6
4135 * @param string $tag The tag to encase the heading in. h1 by default.
4136 * @return string HTML.
4138 public function page_heading($tag = 'h1') {
4139 return html_writer::tag($tag, $this->page->heading);
4143 * Gets the HTML for the page heading button.
4145 * @since Moodle 2.5.1 2.6
4146 * @return string HTML.
4148 public function page_heading_button() {
4149 return $this->page->button;
4153 * Returns the Moodle docs link to use for this page.
4155 * @since Moodle 2.5.1 2.6
4156 * @param string $text
4157 * @return string
4159 public function page_doc_link($text = null) {
4160 if ($text === null) {
4161 $text = get_string('moodledocslink');
4163 $path = page_get_doc_link_path($this->page);
4164 if (!$path) {
4165 return '';
4167 return $this->doc_link($path, $text);
4171 * Returns the HTML for the site support email link
4173 * @param array $customattribs Array of custom attributes for the support email anchor tag.
4174 * @return string The html code for the support email link.
4176 public function supportemail(array $customattribs = []): string {
4177 global $CFG;
4179 $label = get_string('contactsitesupport', 'admin');
4180 $icon = $this->pix_icon('t/email', '');
4181 $content = $icon . $label;
4183 if (!empty($CFG->supportpage)) {
4184 $attributes = ['href' => $CFG->supportpage, 'target' => 'blank'];
4185 $content .= $this->pix_icon('i/externallink', '', 'moodle', ['class' => 'ml-1']);
4186 } else {
4187 $attributes = ['href' => $CFG->wwwroot . '/user/contactsitesupport.php'];
4190 $attributes += $customattribs;
4192 return html_writer::tag('a', $content, $attributes);
4196 * Returns the services and support link for the help pop-up.
4198 * @return string
4200 public function services_support_link(): string {
4201 global $CFG;
4203 if (during_initial_install() ||
4204 (isset($CFG->showservicesandsupportcontent) && $CFG->showservicesandsupportcontent == false) ||
4205 !is_siteadmin()) {
4206 return '';
4209 $liferingicon = $this->pix_icon('t/life-ring', '', 'moodle', ['class' => 'fa fa-life-ring']);
4210 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle', ['class' => 'ml-1']);
4211 $link = 'https://moodle.com/help/?utm_source=CTA-banner&utm_medium=platform&utm_campaign=name~Moodle4+cat~lms+mp~no';
4212 $content = $liferingicon . get_string('moodleservicesandsupport') . $newwindowicon;
4214 return html_writer::tag('a', $content, ['target' => '_blank', 'href' => $link]);
4218 * Helper function to decide whether to show the help popover header or not.
4220 * @return bool
4222 public function has_popover_links(): bool {
4223 return !empty($this->services_support_link()) || !empty($this->page_doc_link()) || !empty($this->supportemail());
4227 * Returns the page heading menu.
4229 * @since Moodle 2.5.1 2.6
4230 * @return string HTML.
4232 public function page_heading_menu() {
4233 return $this->page->headingmenu;
4237 * Returns the title to use on the page.
4239 * @since Moodle 2.5.1 2.6
4240 * @return string
4242 public function page_title() {
4243 return $this->page->title;
4247 * Returns the moodle_url for the favicon.
4249 * @since Moodle 2.5.1 2.6
4250 * @return moodle_url The moodle_url for the favicon
4252 public function favicon() {
4253 return $this->image_url('favicon', 'theme');
4257 * Renders preferences groups.
4259 * @param preferences_groups $renderable The renderable
4260 * @return string The output.
4262 public function render_preferences_groups(preferences_groups $renderable) {
4263 return $this->render_from_template('core/preferences_groups', $renderable);
4267 * Renders preferences group.
4269 * @param preferences_group $renderable The renderable
4270 * @return string The output.
4272 public function render_preferences_group(preferences_group $renderable) {
4273 $html = '';
4274 $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4275 $html .= $this->heading($renderable->title, 3);
4276 $html .= html_writer::start_tag('ul');
4277 foreach ($renderable->nodes as $node) {
4278 if ($node->has_children()) {
4279 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4281 $html .= html_writer::tag('li', $this->render($node));
4283 $html .= html_writer::end_tag('ul');
4284 $html .= html_writer::end_tag('div');
4285 return $html;
4288 public function context_header($headerinfo = null, $headinglevel = 1) {
4289 global $DB, $USER, $CFG, $SITE;
4290 require_once($CFG->dirroot . '/user/lib.php');
4291 $context = $this->page->context;
4292 $heading = null;
4293 $imagedata = null;
4294 $subheader = null;
4295 $userbuttons = null;
4297 // Make sure to use the heading if it has been set.
4298 if (isset($headerinfo['heading'])) {
4299 $heading = $headerinfo['heading'];
4300 } else {
4301 $heading = $this->page->heading;
4304 // The user context currently has images and buttons. Other contexts may follow.
4305 if ((isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) && $this->page->pagetype !== 'my-index') {
4306 if (isset($headerinfo['user'])) {
4307 $user = $headerinfo['user'];
4308 } else {
4309 // Look up the user information if it is not supplied.
4310 $user = $DB->get_record('user', array('id' => $context->instanceid));
4313 // If the user context is set, then use that for capability checks.
4314 if (isset($headerinfo['usercontext'])) {
4315 $context = $headerinfo['usercontext'];
4318 // Only provide user information if the user is the current user, or a user which the current user can view.
4319 // When checking user_can_view_profile(), either:
4320 // If the page context is course, check the course context (from the page object) or;
4321 // If page context is NOT course, then check across all courses.
4322 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4324 if (user_can_view_profile($user, $course)) {
4325 // Use the user's full name if the heading isn't set.
4326 if (empty($heading)) {
4327 $heading = fullname($user);
4330 $imagedata = $this->user_picture($user, array('size' => 100));
4332 // Check to see if we should be displaying a message button.
4333 if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
4334 $userbuttons = array(
4335 'messages' => array(
4336 'buttontype' => 'message',
4337 'title' => get_string('message', 'message'),
4338 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4339 'image' => 'message',
4340 'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
4341 'page' => $this->page
4345 if ($USER->id != $user->id) {
4346 $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4347 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4348 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4349 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4350 $userbuttons['togglecontact'] = array(
4351 'buttontype' => 'togglecontact',
4352 'title' => get_string($contacttitle, 'message'),
4353 'url' => new moodle_url('/message/index.php', array(
4354 'user1' => $USER->id,
4355 'user2' => $user->id,
4356 $contacturlaction => $user->id,
4357 'sesskey' => sesskey())
4359 'image' => $contactimage,
4360 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4361 'page' => $this->page
4365 } else {
4366 $heading = null;
4371 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4372 return $this->render_context_header($contextheader);
4376 * Renders the skip links for the page.
4378 * @param array $links List of skip links.
4379 * @return string HTML for the skip links.
4381 public function render_skip_links($links) {
4382 $context = [ 'links' => []];
4384 foreach ($links as $url => $text) {
4385 $context['links'][] = [ 'url' => $url, 'text' => $text];
4388 return $this->render_from_template('core/skip_links', $context);
4392 * Renders the header bar.
4394 * @param context_header $contextheader Header bar object.
4395 * @return string HTML for the header bar.
4397 protected function render_context_header(context_header $contextheader) {
4399 // Generate the heading first and before everything else as we might have to do an early return.
4400 if (!isset($contextheader->heading)) {
4401 $heading = $this->heading($this->page->heading, $contextheader->headinglevel);
4402 } else {
4403 $heading = $this->heading($contextheader->heading, $contextheader->headinglevel);
4406 $showheader = empty($this->page->layout_options['nocontextheader']);
4407 if (!$showheader) {
4408 // Return the heading wrapped in an sr-only element so it is only visible to screen-readers.
4409 return html_writer::div($heading, 'sr-only');
4412 // All the html stuff goes here.
4413 $html = html_writer::start_div('page-context-header');
4415 // Image data.
4416 if (isset($contextheader->imagedata)) {
4417 // Header specific image.
4418 $html .= html_writer::div($contextheader->imagedata, 'page-header-image icon-size-7');
4421 // Headings.
4422 if (isset($contextheader->prefix)) {
4423 $prefix = html_writer::div($contextheader->prefix, 'text-muted');
4424 $heading = $prefix . $heading;
4426 $html .= html_writer::tag('div', $heading, array('class' => 'page-header-headings'));
4428 // Buttons.
4429 if (isset($contextheader->additionalbuttons)) {
4430 $html .= html_writer::start_div('btn-group header-button-group');
4431 foreach ($contextheader->additionalbuttons as $button) {
4432 if (!isset($button->page)) {
4433 // Include js for messaging.
4434 if ($button['buttontype'] === 'togglecontact') {
4435 \core_message\helper::togglecontact_requirejs();
4437 if ($button['buttontype'] === 'message') {
4438 \core_message\helper::messageuser_requirejs();
4440 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4441 'class' => 'iconsmall',
4442 'role' => 'presentation'
4444 $image .= html_writer::span($button['title'], 'header-button-title');
4445 } else {
4446 $image = html_writer::empty_tag('img', array(
4447 'src' => $button['formattedimage'],
4448 'role' => 'presentation'
4451 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4453 $html .= html_writer::end_div();
4455 $html .= html_writer::end_div();
4457 return $html;
4461 * Wrapper for header elements.
4463 * @return string HTML to display the main header.
4465 public function full_header() {
4466 $pagetype = $this->page->pagetype;
4467 $homepage = get_home_page();
4468 $homepagetype = null;
4469 // Add a special case since /my/courses is a part of the /my subsystem.
4470 if ($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES) {
4471 $homepagetype = 'my-index';
4472 } else if ($homepage == HOMEPAGE_SITE) {
4473 $homepagetype = 'site-index';
4475 if ($this->page->include_region_main_settings_in_header_actions() &&
4476 !$this->page->blocks->is_block_present('settings')) {
4477 // Only include the region main settings if the page has requested it and it doesn't already have
4478 // the settings block on it. The region main settings are included in the settings block and
4479 // duplicating the content causes behat failures.
4480 $this->page->add_header_action(html_writer::div(
4481 $this->region_main_settings_menu(),
4482 'd-print-none',
4483 ['id' => 'region-main-settings-menu']
4487 $header = new stdClass();
4488 $header->settingsmenu = $this->context_header_settings_menu();
4489 $header->contextheader = $this->context_header();
4490 $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
4491 $header->navbar = $this->navbar();
4492 $header->pageheadingbutton = $this->page_heading_button();
4493 $header->courseheader = $this->course_header();
4494 $header->headeractions = $this->page->get_header_actions();
4495 if (!empty($pagetype) && !empty($homepagetype) && $pagetype == $homepagetype) {
4496 $header->welcomemessage = \core_user::welcome_message();
4498 return $this->render_from_template('core/full_header', $header);
4502 * This is an optional menu that can be added to a layout by a theme. It contains the
4503 * menu for the course administration, only on the course main page.
4505 * @return string
4507 public function context_header_settings_menu() {
4508 $context = $this->page->context;
4509 $menu = new action_menu();
4511 $items = $this->page->navbar->get_items();
4512 $currentnode = end($items);
4514 $showcoursemenu = false;
4515 $showfrontpagemenu = false;
4516 $showusermenu = false;
4518 // We are on the course home page.
4519 if (($context->contextlevel == CONTEXT_COURSE) &&
4520 !empty($currentnode) &&
4521 ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
4522 $showcoursemenu = true;
4525 $courseformat = course_get_format($this->page->course);
4526 // This is a single activity course format, always show the course menu on the activity main page.
4527 if ($context->contextlevel == CONTEXT_MODULE &&
4528 !$courseformat->has_view_page()) {
4530 $this->page->navigation->initialise();
4531 $activenode = $this->page->navigation->find_active_node();
4532 // If the settings menu has been forced then show the menu.
4533 if ($this->page->is_settings_menu_forced()) {
4534 $showcoursemenu = true;
4535 } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
4536 $activenode->type == navigation_node::TYPE_RESOURCE)) {
4538 // We only want to show the menu on the first page of the activity. This means
4539 // the breadcrumb has no additional nodes.
4540 if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
4541 $showcoursemenu = true;
4546 // This is the site front page.
4547 if ($context->contextlevel == CONTEXT_COURSE &&
4548 !empty($currentnode) &&
4549 $currentnode->key === 'home') {
4550 $showfrontpagemenu = true;
4553 // This is the user profile page.
4554 if ($context->contextlevel == CONTEXT_USER &&
4555 !empty($currentnode) &&
4556 ($currentnode->key === 'myprofile')) {
4557 $showusermenu = true;
4560 if ($showfrontpagemenu) {
4561 $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
4562 if ($settingsnode) {
4563 // Build an action menu based on the visible nodes from this navigation tree.
4564 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4566 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4567 if ($skipped) {
4568 $text = get_string('morenavigationlinks');
4569 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4570 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4571 $menu->add_secondary_action($link);
4574 } else if ($showcoursemenu) {
4575 $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
4576 if ($settingsnode) {
4577 // Build an action menu based on the visible nodes from this navigation tree.
4578 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4580 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4581 if ($skipped) {
4582 $text = get_string('morenavigationlinks');
4583 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4584 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4585 $menu->add_secondary_action($link);
4588 } else if ($showusermenu) {
4589 // Get the course admin node from the settings navigation.
4590 $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
4591 if ($settingsnode) {
4592 // Build an action menu based on the visible nodes from this navigation tree.
4593 $this->build_action_menu_from_navigation($menu, $settingsnode);
4597 return $this->render($menu);
4601 * Take a node in the nav tree and make an action menu out of it.
4602 * The links are injected in the action menu.
4604 * @param action_menu $menu
4605 * @param navigation_node $node
4606 * @param boolean $indent
4607 * @param boolean $onlytopleafnodes
4608 * @return boolean nodesskipped - True if nodes were skipped in building the menu
4610 protected function build_action_menu_from_navigation(action_menu $menu,
4611 navigation_node $node,
4612 $indent = false,
4613 $onlytopleafnodes = false) {
4614 $skipped = false;
4615 // Build an action menu based on the visible nodes from this navigation tree.
4616 foreach ($node->children as $menuitem) {
4617 if ($menuitem->display) {
4618 if ($onlytopleafnodes && $menuitem->children->count()) {
4619 $skipped = true;
4620 continue;
4622 if ($menuitem->action) {
4623 if ($menuitem->action instanceof action_link) {
4624 $link = $menuitem->action;
4625 // Give preference to setting icon over action icon.
4626 if (!empty($menuitem->icon)) {
4627 $link->icon = $menuitem->icon;
4629 } else {
4630 $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
4632 } else {
4633 if ($onlytopleafnodes) {
4634 $skipped = true;
4635 continue;
4637 $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
4639 if ($indent) {
4640 $link->add_class('ml-4');
4642 if (!empty($menuitem->classes)) {
4643 $link->add_class(implode(" ", $menuitem->classes));
4646 $menu->add_secondary_action($link);
4647 $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
4650 return $skipped;
4654 * This is an optional menu that can be added to a layout by a theme. It contains the
4655 * menu for the most specific thing from the settings block. E.g. Module administration.
4657 * @return string
4659 public function region_main_settings_menu() {
4660 $context = $this->page->context;
4661 $menu = new action_menu();
4663 if ($context->contextlevel == CONTEXT_MODULE) {
4665 $this->page->navigation->initialise();
4666 $node = $this->page->navigation->find_active_node();
4667 $buildmenu = false;
4668 // If the settings menu has been forced then show the menu.
4669 if ($this->page->is_settings_menu_forced()) {
4670 $buildmenu = true;
4671 } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
4672 $node->type == navigation_node::TYPE_RESOURCE)) {
4674 $items = $this->page->navbar->get_items();
4675 $navbarnode = end($items);
4676 // We only want to show the menu on the first page of the activity. This means
4677 // the breadcrumb has no additional nodes.
4678 if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
4679 $buildmenu = true;
4682 if ($buildmenu) {
4683 // Get the course admin node from the settings navigation.
4684 $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
4685 if ($node) {
4686 // Build an action menu based on the visible nodes from this navigation tree.
4687 $this->build_action_menu_from_navigation($menu, $node);
4691 } else if ($context->contextlevel == CONTEXT_COURSECAT) {
4692 // For course category context, show category settings menu, if we're on the course category page.
4693 if ($this->page->pagetype === 'course-index-category') {
4694 $node = $this->page->settingsnav->find('categorysettings', navigation_node::TYPE_CONTAINER);
4695 if ($node) {
4696 // Build an action menu based on the visible nodes from this navigation tree.
4697 $this->build_action_menu_from_navigation($menu, $node);
4701 } else {
4702 $items = $this->page->navbar->get_items();
4703 $navbarnode = end($items);
4705 if ($navbarnode && ($navbarnode->key === 'participants')) {
4706 $node = $this->page->settingsnav->find('users', navigation_node::TYPE_CONTAINER);
4707 if ($node) {
4708 // Build an action menu based on the visible nodes from this navigation tree.
4709 $this->build_action_menu_from_navigation($menu, $node);
4714 return $this->render($menu);
4718 * Displays the list of tags associated with an entry
4720 * @param array $tags list of instances of core_tag or stdClass
4721 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4722 * to use default, set to '' (empty string) to omit the label completely
4723 * @param string $classes additional classes for the enclosing div element
4724 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4725 * will be appended to the end, JS will toggle the rest of the tags
4726 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4727 * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
4728 * @return string
4730 public function tag_list($tags, $label = null, $classes = '', $limit = 10,
4731 $pagecontext = null, $accesshidelabel = false) {
4732 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
4733 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4737 * Renders element for inline editing of any value
4739 * @param \core\output\inplace_editable $element
4740 * @return string
4742 public function render_inplace_editable(\core\output\inplace_editable $element) {
4743 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4747 * Renders a bar chart.
4749 * @param \core\chart_bar $chart The chart.
4750 * @return string.
4752 public function render_chart_bar(\core\chart_bar $chart) {
4753 return $this->render_chart($chart);
4757 * Renders a line chart.
4759 * @param \core\chart_line $chart The chart.
4760 * @return string.
4762 public function render_chart_line(\core\chart_line $chart) {
4763 return $this->render_chart($chart);
4767 * Renders a pie chart.
4769 * @param \core\chart_pie $chart The chart.
4770 * @return string.
4772 public function render_chart_pie(\core\chart_pie $chart) {
4773 return $this->render_chart($chart);
4777 * Renders a chart.
4779 * @param \core\chart_base $chart The chart.
4780 * @param bool $withtable Whether to include a data table with the chart.
4781 * @return string.
4783 public function render_chart(\core\chart_base $chart, $withtable = true) {
4784 $chartdata = json_encode($chart);
4785 return $this->render_from_template('core/chart', (object) [
4786 'chartdata' => $chartdata,
4787 'withtable' => $withtable
4792 * Renders the login form.
4794 * @param \core_auth\output\login $form The renderable.
4795 * @return string
4797 public function render_login(\core_auth\output\login $form) {
4798 global $CFG, $SITE;
4800 $context = $form->export_for_template($this);
4802 $context->errorformatted = $this->error_text($context->error);
4803 $url = $this->get_logo_url();
4804 if ($url) {
4805 $url = $url->out(false);
4807 $context->logourl = $url;
4808 $context->sitename = format_string($SITE->fullname, true,
4809 ['context' => context_course::instance(SITEID), "escape" => false]);
4811 return $this->render_from_template('core/loginform', $context);
4815 * Renders an mform element from a template.
4817 * @param HTML_QuickForm_element $element element
4818 * @param bool $required if input is required field
4819 * @param bool $advanced if input is an advanced field
4820 * @param string $error error message to display
4821 * @param bool $ingroup True if this element is rendered as part of a group
4822 * @return mixed string|bool
4824 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4825 $templatename = 'core_form/element-' . $element->getType();
4826 if ($ingroup) {
4827 $templatename .= "-inline";
4829 try {
4830 // We call this to generate a file not found exception if there is no template.
4831 // We don't want to call export_for_template if there is no template.
4832 core\output\mustache_template_finder::get_template_filepath($templatename);
4834 if ($element instanceof templatable) {
4835 $elementcontext = $element->export_for_template($this);
4837 $helpbutton = '';
4838 if (method_exists($element, 'getHelpButton')) {
4839 $helpbutton = $element->getHelpButton();
4841 $label = $element->getLabel();
4842 $text = '';
4843 if (method_exists($element, 'getText')) {
4844 // There currently exists code that adds a form element with an empty label.
4845 // If this is the case then set the label to the description.
4846 if (empty($label)) {
4847 $label = $element->getText();
4848 } else {
4849 $text = $element->getText();
4853 // Generate the form element wrapper ids and names to pass to the template.
4854 // This differs between group and non-group elements.
4855 if ($element->getType() === 'group') {
4856 // Group element.
4857 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
4858 $elementcontext['wrapperid'] = $elementcontext['id'];
4860 // Ensure group elements pass through the group name as the element name.
4861 $elementcontext['name'] = $elementcontext['groupname'];
4862 } else {
4863 // Non grouped element.
4864 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
4865 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
4868 $context = array(
4869 'element' => $elementcontext,
4870 'label' => $label,
4871 'text' => $text,
4872 'required' => $required,
4873 'advanced' => $advanced,
4874 'helpbutton' => $helpbutton,
4875 'error' => $error
4877 return $this->render_from_template($templatename, $context);
4879 } catch (Exception $e) {
4880 // No template for this element.
4881 return false;
4886 * Render the login signup form into a nice template for the theme.
4888 * @param mform $form
4889 * @return string
4891 public function render_login_signup_form($form) {
4892 global $SITE;
4894 $context = $form->export_for_template($this);
4895 $url = $this->get_logo_url();
4896 if ($url) {
4897 $url = $url->out(false);
4899 $context['logourl'] = $url;
4900 $context['sitename'] = format_string($SITE->fullname, true,
4901 ['context' => context_course::instance(SITEID), "escape" => false]);
4903 return $this->render_from_template('core/signup_form_layout', $context);
4907 * Render the verify age and location page into a nice template for the theme.
4909 * @param \core_auth\output\verify_age_location_page $page The renderable
4910 * @return string
4912 protected function render_verify_age_location_page($page) {
4913 $context = $page->export_for_template($this);
4915 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4919 * Render the digital minor contact information page into a nice template for the theme.
4921 * @param \core_auth\output\digital_minor_page $page The renderable
4922 * @return string
4924 protected function render_digital_minor_page($page) {
4925 $context = $page->export_for_template($this);
4927 return $this->render_from_template('core/auth_digital_minor_page', $context);
4931 * Renders a progress bar.
4933 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4935 * @param progress_bar $bar The bar.
4936 * @return string HTML fragment
4938 public function render_progress_bar(progress_bar $bar) {
4939 $data = $bar->export_for_template($this);
4940 return $this->render_from_template('core/progress_bar', $data);
4944 * Renders an update to a progress bar.
4946 * Note: This does not cleanly map to a renderable class and should
4947 * never be used directly.
4949 * @param string $id
4950 * @param float $percent
4951 * @param string $msg Message
4952 * @param string $estimate time remaining message
4953 * @return string ascii fragment
4955 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
4956 return html_writer::script(js_writer::function_call('updateProgressBar', [$id, $percent, $msg, $estimate]));
4960 * Renders element for a toggle-all checkbox.
4962 * @param \core\output\checkbox_toggleall $element
4963 * @return string
4965 public function render_checkbox_toggleall(\core\output\checkbox_toggleall $element) {
4966 return $this->render_from_template($element->get_template(), $element->export_for_template($this));
4970 * Renders the tertiary nav for the participants page
4972 * @param object $course The course we are operating within
4973 * @param string|null $renderedbuttons Any additional buttons/content to be displayed in line with the nav
4974 * @return string
4976 public function render_participants_tertiary_nav(object $course, ?string $renderedbuttons = null) {
4977 $actionbar = new \core\output\participants_action_bar($course, $this->page, $renderedbuttons);
4978 $content = $this->render_from_template('core_course/participants_actionbar', $actionbar->export_for_template($this));
4979 return $content ?: "";
4983 * Renders release information in the footer popup
4984 * @return string Moodle release info.
4986 public function moodle_release() {
4987 global $CFG;
4988 if (!during_initial_install() && is_siteadmin()) {
4989 return $CFG->release;
4994 * Generate the add block button when editing mode is turned on and the user can edit blocks.
4996 * @param string $region where new blocks should be added.
4997 * @return string html for the add block button.
4999 public function addblockbutton($region = ''): string {
5000 $addblockbutton = '';
5001 $regions = $this->page->blocks->get_regions();
5002 if (count($regions) == 0) {
5003 return '';
5005 if (isset($this->page->theme->addblockposition) &&
5006 $this->page->user_is_editing() &&
5007 $this->page->user_can_edit_blocks() &&
5008 $this->page->pagelayout !== 'mycourses'
5010 $params = ['bui_addblock' => '', 'sesskey' => sesskey()];
5011 if (!empty($region)) {
5012 $params['bui_blockregion'] = $region;
5014 $url = new moodle_url($this->page->url, $params);
5015 $addblockbutton = $this->render_from_template('core/add_block_button',
5017 'link' => $url->out(false),
5018 'escapedlink' => "?{$url->get_query_string(false)}",
5019 'pageType' => $this->page->pagetype,
5020 'pageLayout' => $this->page->pagelayout,
5021 'subPage' => $this->page->subpage,
5025 return $addblockbutton;
5030 * A renderer that generates output for command-line scripts.
5032 * The implementation of this renderer is probably incomplete.
5034 * @copyright 2009 Tim Hunt
5035 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5036 * @since Moodle 2.0
5037 * @package core
5038 * @category output
5040 class core_renderer_cli extends core_renderer {
5043 * @var array $progressmaximums stores the largest percentage for a progress bar.
5044 * @return string ascii fragment
5046 private $progressmaximums = [];
5049 * Returns the page header.
5051 * @return string HTML fragment
5053 public function header() {
5054 return $this->page->heading . "\n";
5058 * Renders a Check API result
5060 * To aid in CLI consistency this status is NOT translated and the visual
5061 * width is always exactly 10 chars.
5063 * @param core\check\result $result
5064 * @return string HTML fragment
5066 protected function render_check_result(core\check\result $result) {
5067 $status = $result->get_status();
5069 $labels = [
5070 core\check\result::NA => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' NA ',
5071 core\check\result::OK => ' ' . cli_ansi_format('<colour:green>') . ' OK ',
5072 core\check\result::INFO => ' ' . cli_ansi_format('<colour:blue>' ) . ' INFO ',
5073 core\check\result::UNKNOWN => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' UNKNOWN ',
5074 core\check\result::WARNING => ' ' . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
5075 core\check\result::ERROR => ' ' . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
5076 core\check\result::CRITICAL => '' . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
5078 $string = $labels[$status] . cli_ansi_format('<colour:normal>');
5079 return $string;
5083 * Renders a Check API result
5085 * @param result $result
5086 * @return string fragment
5088 public function check_result(core\check\result $result) {
5089 return $this->render_check_result($result);
5093 * Renders a progress bar.
5095 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
5097 * @param progress_bar $bar The bar.
5098 * @return string ascii fragment
5100 public function render_progress_bar(progress_bar $bar) {
5101 global $CFG;
5103 $size = 55; // The width of the progress bar in chars.
5104 $ascii = "\n";
5106 if (stream_isatty(STDOUT)) {
5107 require_once($CFG->libdir.'/clilib.php');
5109 $ascii .= "[" . str_repeat(' ', $size) . "] 0% \n";
5110 return cli_ansi_format($ascii);
5113 $this->progressmaximums[$bar->get_id()] = 0;
5114 $ascii .= '[';
5115 return $ascii;
5119 * Renders an update to a progress bar.
5121 * Note: This does not cleanly map to a renderable class and should
5122 * never be used directly.
5124 * @param string $id
5125 * @param float $percent
5126 * @param string $msg Message
5127 * @param string $estimate time remaining message
5128 * @return string ascii fragment
5130 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
5131 $size = 55; // The width of the progress bar in chars.
5132 $ascii = '';
5134 // If we are rendering to a terminal then we can safely use ansii codes
5135 // to move the cursor and redraw the complete progress bar each time
5136 // it is updated.
5137 if (stream_isatty(STDOUT)) {
5138 $colour = $percent == 100 ? 'green' : 'blue';
5140 $done = $percent * $size * 0.01;
5141 $whole = floor($done);
5142 $bar = "<colour:$colour>";
5143 $bar .= str_repeat('█', $whole);
5145 if ($whole < $size) {
5146 // By using unicode chars for partial blocks we can have higher
5147 // precision progress bar.
5148 $fraction = floor(($done - $whole) * 8);
5149 $bar .= core_text::substr(' ▏▎▍▌▋▊▉', $fraction, 1);
5151 // Fill the rest of the empty bar.
5152 $bar .= str_repeat(' ', $size - $whole - 1);
5155 $bar .= '<colour:normal>';
5157 if ($estimate) {
5158 $estimate = "- $estimate";
5161 $ascii .= '<cursor:up>';
5162 $ascii .= '<cursor:up>';
5163 $ascii .= sprintf("[$bar] %3.1f%% %-22s\n", $percent, $estimate);
5164 $ascii .= sprintf("%-80s\n", $msg);
5165 return cli_ansi_format($ascii);
5168 // If we are not rendering to a tty, ie when piped to another command
5169 // or on windows we need to progressively render the progress bar
5170 // which can only ever go forwards.
5171 $done = round($percent * $size * 0.01);
5172 $delta = max(0, $done - $this->progressmaximums[$id]);
5174 $ascii .= str_repeat('#', $delta);
5175 if ($percent >= 100 && $delta > 0) {
5176 $ascii .= sprintf("] %3.1f%%\n$msg\n", $percent);
5178 $this->progressmaximums[$id] += $delta;
5179 return $ascii;
5183 * Returns a template fragment representing a Heading.
5185 * @param string $text The text of the heading
5186 * @param int $level The level of importance of the heading
5187 * @param string $classes A space-separated list of CSS classes
5188 * @param string $id An optional ID
5189 * @return string A template fragment for a heading
5191 public function heading($text, $level = 2, $classes = 'main', $id = null) {
5192 $text .= "\n";
5193 switch ($level) {
5194 case 1:
5195 return '=>' . $text;
5196 case 2:
5197 return '-->' . $text;
5198 default:
5199 return $text;
5204 * Returns a template fragment representing a fatal error.
5206 * @param string $message The message to output
5207 * @param string $moreinfourl URL where more info can be found about the error
5208 * @param string $link Link for the Continue button
5209 * @param array $backtrace The execution backtrace
5210 * @param string $debuginfo Debugging information
5211 * @return string A template fragment for a fatal error
5213 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5214 global $CFG;
5216 $output = "!!! $message !!!\n";
5218 if ($CFG->debugdeveloper) {
5219 if (!empty($debuginfo)) {
5220 $output .= $this->notification($debuginfo, 'notifytiny');
5222 if (!empty($backtrace)) {
5223 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
5227 return $output;
5231 * Returns a template fragment representing a notification.
5233 * @param string $message The message to print out.
5234 * @param string $type The type of notification. See constants on \core\output\notification.
5235 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5236 * @return string A template fragment for a notification
5238 public function notification($message, $type = null, $closebutton = true) {
5239 $message = clean_text($message);
5240 if ($type === 'notifysuccess' || $type === 'success') {
5241 return "++ $message ++\n";
5243 return "!! $message !!\n";
5247 * There is no footer for a cli request, however we must override the
5248 * footer method to prevent the default footer.
5250 public function footer() {}
5253 * Render a notification (that is, a status message about something that has
5254 * just happened).
5256 * @param \core\output\notification $notification the notification to print out
5257 * @return string plain text output
5259 public function render_notification(\core\output\notification $notification) {
5260 return $this->notification($notification->get_message(), $notification->get_message_type());
5266 * A renderer that generates output for ajax scripts.
5268 * This renderer prevents accidental sends back only json
5269 * encoded error messages, all other output is ignored.
5271 * @copyright 2010 Petr Skoda
5272 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5273 * @since Moodle 2.0
5274 * @package core
5275 * @category output
5277 class core_renderer_ajax extends core_renderer {
5280 * Returns a template fragment representing a fatal error.
5282 * @param string $message The message to output
5283 * @param string $moreinfourl URL where more info can be found about the error
5284 * @param string $link Link for the Continue button
5285 * @param array $backtrace The execution backtrace
5286 * @param string $debuginfo Debugging information
5287 * @return string A template fragment for a fatal error
5289 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5290 global $CFG;
5292 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
5294 $e = new stdClass();
5295 $e->error = $message;
5296 $e->errorcode = $errorcode;
5297 $e->stacktrace = NULL;
5298 $e->debuginfo = NULL;
5299 $e->reproductionlink = NULL;
5300 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
5301 $link = (string) $link;
5302 if ($link) {
5303 $e->reproductionlink = $link;
5305 if (!empty($debuginfo)) {
5306 $e->debuginfo = $debuginfo;
5308 if (!empty($backtrace)) {
5309 $e->stacktrace = format_backtrace($backtrace, true);
5312 $this->header();
5313 return json_encode($e);
5317 * Used to display a notification.
5318 * For the AJAX notifications are discarded.
5320 * @param string $message The message to print out.
5321 * @param string $type The type of notification. See constants on \core\output\notification.
5322 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5324 public function notification($message, $type = null, $closebutton = true) {
5328 * Used to display a redirection message.
5329 * AJAX redirections should not occur and as such redirection messages
5330 * are discarded.
5332 * @param moodle_url|string $encodedurl
5333 * @param string $message
5334 * @param int $delay
5335 * @param bool $debugdisableredirect
5336 * @param string $messagetype The type of notification to show the message in.
5337 * See constants on \core\output\notification.
5339 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
5340 $messagetype = \core\output\notification::NOTIFY_INFO) {}
5343 * Prepares the start of an AJAX output.
5345 public function header() {
5346 // unfortunately YUI iframe upload does not support application/json
5347 if (!empty($_FILES)) {
5348 @header('Content-type: text/plain; charset=utf-8');
5349 if (!core_useragent::supports_json_contenttype()) {
5350 @header('X-Content-Type-Options: nosniff');
5352 } else if (!core_useragent::supports_json_contenttype()) {
5353 @header('Content-type: text/plain; charset=utf-8');
5354 @header('X-Content-Type-Options: nosniff');
5355 } else {
5356 @header('Content-type: application/json; charset=utf-8');
5359 // Headers to make it not cacheable and json
5360 @header('Cache-Control: no-store, no-cache, must-revalidate');
5361 @header('Cache-Control: post-check=0, pre-check=0', false);
5362 @header('Pragma: no-cache');
5363 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
5364 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
5365 @header('Accept-Ranges: none');
5369 * There is no footer for an AJAX request, however we must override the
5370 * footer method to prevent the default footer.
5372 public function footer() {}
5375 * No need for headers in an AJAX request... this should never happen.
5376 * @param string $text
5377 * @param int $level
5378 * @param string $classes
5379 * @param string $id
5381 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
5387 * The maintenance renderer.
5389 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
5390 * is running a maintenance related task.
5391 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
5393 * @since Moodle 2.6
5394 * @package core
5395 * @category output
5396 * @copyright 2013 Sam Hemelryk
5397 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5399 class core_renderer_maintenance extends core_renderer {
5402 * Initialises the renderer instance.
5404 * @param moodle_page $page
5405 * @param string $target
5406 * @throws coding_exception
5408 public function __construct(moodle_page $page, $target) {
5409 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
5410 throw new coding_exception('Invalid request for the maintenance renderer.');
5412 parent::__construct($page, $target);
5416 * Does nothing. The maintenance renderer cannot produce blocks.
5418 * @param block_contents $bc
5419 * @param string $region
5420 * @return string
5422 public function block(block_contents $bc, $region) {
5423 return '';
5427 * Does nothing. The maintenance renderer cannot produce blocks.
5429 * @param string $region
5430 * @param array $classes
5431 * @param string $tag
5432 * @param boolean $fakeblocksonly
5433 * @return string
5435 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
5436 return '';
5440 * Does nothing. The maintenance renderer cannot produce blocks.
5442 * @param string $region
5443 * @param boolean $fakeblocksonly Output fake block only.
5444 * @return string
5446 public function blocks_for_region($region, $fakeblocksonly = false) {
5447 return '';
5451 * Does nothing. The maintenance renderer cannot produce a course content header.
5453 * @param bool $onlyifnotcalledbefore
5454 * @return string
5456 public function course_content_header($onlyifnotcalledbefore = false) {
5457 return '';
5461 * Does nothing. The maintenance renderer cannot produce a course content footer.
5463 * @param bool $onlyifnotcalledbefore
5464 * @return string
5466 public function course_content_footer($onlyifnotcalledbefore = false) {
5467 return '';
5471 * Does nothing. The maintenance renderer cannot produce a course header.
5473 * @return string
5475 public function course_header() {
5476 return '';
5480 * Does nothing. The maintenance renderer cannot produce a course footer.
5482 * @return string
5484 public function course_footer() {
5485 return '';
5489 * Does nothing. The maintenance renderer cannot produce a custom menu.
5491 * @param string $custommenuitems
5492 * @return string
5494 public function custom_menu($custommenuitems = '') {
5495 return '';
5499 * Does nothing. The maintenance renderer cannot produce a file picker.
5501 * @param array $options
5502 * @return string
5504 public function file_picker($options) {
5505 return '';
5509 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
5511 * @param array $dir
5512 * @return string
5514 public function htmllize_file_tree($dir) {
5515 return '';
5520 * Overridden confirm message for upgrades.
5522 * @param string $message The question to ask the user
5523 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5524 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5525 * @param array $displayoptions optional extra display options
5526 * @return string HTML fragment
5528 public function confirm($message, $continue, $cancel, array $displayoptions = []) {
5529 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5530 // from any previous version of Moodle).
5531 if ($continue instanceof single_button) {
5532 $continue->primary = true;
5533 } else if (is_string($continue)) {
5534 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
5535 } else if ($continue instanceof moodle_url) {
5536 $continue = new single_button($continue, get_string('continue'), 'post', true);
5537 } else {
5538 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5539 ' (string/moodle_url) or a single_button instance.');
5542 if ($cancel instanceof single_button) {
5543 $output = '';
5544 } else if (is_string($cancel)) {
5545 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5546 } else if ($cancel instanceof moodle_url) {
5547 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5548 } else {
5549 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5550 ' (string/moodle_url) or a single_button instance.');
5553 $output = $this->box_start('generalbox', 'notice');
5554 $output .= html_writer::tag('h4', get_string('confirm'));
5555 $output .= html_writer::tag('p', $message);
5556 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
5557 $output .= $this->box_end();
5558 return $output;
5562 * Does nothing. The maintenance renderer does not support JS.
5564 * @param block_contents $bc
5566 public function init_block_hider_js(block_contents $bc) {
5567 // Does nothing.
5571 * Does nothing. The maintenance renderer cannot produce language menus.
5573 * @return string
5575 public function lang_menu() {
5576 return '';
5580 * Does nothing. The maintenance renderer has no need for login information.
5582 * @param null $withlinks
5583 * @return string
5585 public function login_info($withlinks = null) {
5586 return '';
5590 * Secure login info.
5592 * @return string
5594 public function secure_login_info() {
5595 return $this->login_info(false);
5599 * Does nothing. The maintenance renderer cannot produce user pictures.
5601 * @param stdClass $user
5602 * @param array $options
5603 * @return string
5605 public function user_picture(stdClass $user, array $options = null) {
5606 return '';