MDL-78165 mod_bigbluebuttonbn: Fetch cron status using API
[moodle.git] / lib / outputrenderers.php
blob2bcc1b27619ec9ae0e105517bff8ba678f9dc65f
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
21 * for an overview.
23 * Included in this file are the primary renderer classes:
24 * - renderer_base: The renderer outline class that all renderers
25 * should inherit from.
26 * - core_renderer: The standard HTML renderer.
27 * - core_renderer_cli: An adaption of the standard renderer for CLI scripts.
28 * - core_renderer_ajax: An adaption of the standard renderer for AJAX scripts.
29 * - plugin_renderer_base: A renderer class that should be extended by all
30 * plugin renderers.
32 * @package core
33 * @category output
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 use core\output\named_templatable;
39 use core_completion\cm_completion_details;
40 use core_course\output\activity_information;
42 defined('MOODLE_INTERNAL') || die();
44 /**
45 * Simple base class for Moodle renderers.
47 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
49 * Also has methods to facilitate generating HTML output.
51 * @copyright 2009 Tim Hunt
52 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 * @since Moodle 2.0
54 * @package core
55 * @category output
57 class renderer_base {
58 /**
59 * @var xhtml_container_stack The xhtml_container_stack to use.
61 protected $opencontainers;
63 /**
64 * @var moodle_page The Moodle page the renderer has been created to assist with.
66 protected $page;
68 /**
69 * @var string The requested rendering target.
71 protected $target;
73 /**
74 * @var Mustache_Engine $mustache The mustache template compiler
76 private $mustache;
78 /**
79 * @var array $templatecache The mustache template cache.
81 protected $templatecache = [];
83 /**
84 * Return an instance of the mustache class.
86 * @since 2.9
87 * @return Mustache_Engine
89 protected function get_mustache() {
90 global $CFG;
92 if ($this->mustache === null) {
93 require_once("{$CFG->libdir}/filelib.php");
95 $themename = $this->page->theme->name;
96 $themerev = theme_get_revision();
98 // Create new localcache directory.
99 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
101 // Remove old localcache directories.
102 $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR);
103 foreach ($mustachecachedirs as $localcachedir) {
104 $cachedrev = [];
105 preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
106 $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
107 if ($cachedrev > 0 && $cachedrev < $themerev) {
108 fulldelete($localcachedir);
112 $loader = new \core\output\mustache_filesystem_loader();
113 $stringhelper = new \core\output\mustache_string_helper();
114 $cleanstringhelper = new \core\output\mustache_clean_string_helper();
115 $quotehelper = new \core\output\mustache_quote_helper();
116 $jshelper = new \core\output\mustache_javascript_helper($this->page);
117 $pixhelper = new \core\output\mustache_pix_helper($this);
118 $shortentexthelper = new \core\output\mustache_shorten_text_helper();
119 $userdatehelper = new \core\output\mustache_user_date_helper();
121 // We only expose the variables that are exposed to JS templates.
122 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
124 $helpers = array('config' => $safeconfig,
125 'str' => array($stringhelper, 'str'),
126 'cleanstr' => array($cleanstringhelper, 'cleanstr'),
127 'quote' => array($quotehelper, 'quote'),
128 'js' => array($jshelper, 'help'),
129 'pix' => array($pixhelper, 'pix'),
130 'shortentext' => array($shortentexthelper, 'shorten'),
131 'userdate' => array($userdatehelper, 'transform'),
134 $this->mustache = new \core\output\mustache_engine(array(
135 'cache' => $cachedir,
136 'escape' => 's',
137 'loader' => $loader,
138 'helpers' => $helpers,
139 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS],
140 // Don't allow the JavaScript helper to be executed from within another
141 // helper. If it's allowed it can be used by users to inject malicious
142 // JS into the page.
143 'disallowednestedhelpers' => ['js'],
144 // Disable lambda rendering - content in helpers is already rendered, no need to render it again.
145 'disable_lambda_rendering' => true,
150 return $this->mustache;
155 * Constructor
157 * The constructor takes two arguments. The first is the page that the renderer
158 * has been created to assist with, and the second is the target.
159 * The target is an additional identifier that can be used to load different
160 * renderers for different options.
162 * @param moodle_page $page the page we are doing output for.
163 * @param string $target one of rendering target constants
165 public function __construct(moodle_page $page, $target) {
166 $this->opencontainers = $page->opencontainers;
167 $this->page = $page;
168 $this->target = $target;
172 * Renders a template by name with the given context.
174 * The provided data needs to be array/stdClass made up of only simple types.
175 * Simple types are array,stdClass,bool,int,float,string
177 * @since 2.9
178 * @param array|stdClass $context Context containing data for the template.
179 * @return string|boolean
181 public function render_from_template($templatename, $context) {
182 $mustache = $this->get_mustache();
184 try {
185 // Grab a copy of the existing helper to be restored later.
186 $uniqidhelper = $mustache->getHelper('uniqid');
187 } catch (Mustache_Exception_UnknownHelperException $e) {
188 // Helper doesn't exist.
189 $uniqidhelper = null;
192 // Provide 1 random value that will not change within a template
193 // but will be different from template to template. This is useful for
194 // e.g. aria attributes that only work with id attributes and must be
195 // unique in a page.
196 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
197 if (isset($this->templatecache[$templatename])) {
198 $template = $this->templatecache[$templatename];
199 } else {
200 try {
201 $template = $mustache->loadTemplate($templatename);
202 $this->templatecache[$templatename] = $template;
203 } catch (Mustache_Exception_UnknownTemplateException $e) {
204 throw new moodle_exception('Unknown template: ' . $templatename);
208 $renderedtemplate = trim($template->render($context));
210 // If we had an existing uniqid helper then we need to restore it to allow
211 // handle nested calls of render_from_template.
212 if ($uniqidhelper) {
213 $mustache->addHelper('uniqid', $uniqidhelper);
216 return $renderedtemplate;
221 * Returns rendered widget.
223 * The provided widget needs to be an object that extends the renderable
224 * interface.
225 * If will then be rendered by a method based upon the classname for the widget.
226 * For instance a widget of class `crazywidget` will be rendered by a protected
227 * render_crazywidget method of this renderer.
228 * If no render_crazywidget method exists and crazywidget implements templatable,
229 * look for the 'crazywidget' template in the same component and render that.
231 * @param renderable $widget instance with renderable interface
232 * @return string
234 public function render(renderable $widget) {
235 $classparts = explode('\\', get_class($widget));
236 // Strip namespaces.
237 $classname = array_pop($classparts);
238 // Remove _renderable suffixes.
239 $classname = preg_replace('/_renderable$/', '', $classname);
241 $rendermethod = "render_{$classname}";
242 if (method_exists($this, $rendermethod)) {
243 // Call the render_[widget_name] function.
244 // Note: This has a higher priority than the named_templatable to allow the theme to override the template.
245 return $this->$rendermethod($widget);
248 if ($widget instanceof named_templatable) {
249 // This is a named templatable.
250 // Fetch the template name from the get_template_name function instead.
251 // Note: This has higher priority than the guessed template name.
252 return $this->render_from_template(
253 $widget->get_template_name($this),
254 $widget->export_for_template($this)
258 if ($widget instanceof templatable) {
259 // Guess the templat ename based on the class name.
260 // Note: There's no benefit to moving this aboved the named_templatable and this approach is more costly.
261 $component = array_shift($classparts);
262 if (!$component) {
263 $component = 'core';
265 $template = $component . '/' . $classname;
266 $context = $widget->export_for_template($this);
267 return $this->render_from_template($template, $context);
269 throw new coding_exception("Can not render widget, renderer method ('{$rendermethod}') not found.");
273 * Adds a JS action for the element with the provided id.
275 * This method adds a JS event for the provided component action to the page
276 * and then returns the id that the event has been attached to.
277 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
279 * @param component_action $action
280 * @param string $id
281 * @return string id of element, either original submitted or random new if not supplied
283 public function add_action_handler(component_action $action, $id = null) {
284 if (!$id) {
285 $id = html_writer::random_id($action->event);
287 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
288 return $id;
292 * Returns true is output has already started, and false if not.
294 * @return boolean true if the header has been printed.
296 public function has_started() {
297 return $this->page->state >= moodle_page::STATE_IN_BODY;
301 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
303 * @param mixed $classes Space-separated string or array of classes
304 * @return string HTML class attribute value
306 public static function prepare_classes($classes) {
307 if (is_array($classes)) {
308 return implode(' ', array_unique($classes));
310 return $classes;
314 * Return the direct URL for an image from the pix folder.
316 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
318 * @deprecated since Moodle 3.3
319 * @param string $imagename the name of the icon.
320 * @param string $component specification of one plugin like in get_string()
321 * @return moodle_url
323 public function pix_url($imagename, $component = 'moodle') {
324 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
325 return $this->page->theme->image_url($imagename, $component);
329 * Return the moodle_url for an image.
331 * The exact image location and extension is determined
332 * automatically by searching for gif|png|jpg|jpeg, please
333 * note there can not be diferent images with the different
334 * extension. The imagename is for historical reasons
335 * a relative path name, it may be changed later for core
336 * images. It is recommended to not use subdirectories
337 * in plugin and theme pix directories.
339 * There are three types of images:
340 * 1/ theme images - stored in theme/mytheme/pix/,
341 * use component 'theme'
342 * 2/ core images - stored in /pix/,
343 * overridden via theme/mytheme/pix_core/
344 * 3/ plugin images - stored in mod/mymodule/pix,
345 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
346 * example: image_url('comment', 'mod_glossary')
348 * @param string $imagename the pathname of the image
349 * @param string $component full plugin name (aka component) or 'theme'
350 * @return moodle_url
352 public function image_url($imagename, $component = 'moodle') {
353 return $this->page->theme->image_url($imagename, $component);
357 * Return the site's logo URL, if any.
359 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
360 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
361 * @return moodle_url|false
363 public function get_logo_url($maxwidth = null, $maxheight = 200) {
364 global $CFG;
365 $logo = get_config('core_admin', 'logo');
366 if (empty($logo)) {
367 return false;
370 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
371 // It's not worth the overhead of detecting and serving 2 different images based on the device.
373 // Hide the requested size in the file path.
374 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
376 // Use $CFG->themerev to prevent browser caching when the file changes.
377 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
378 theme_get_revision(), $logo);
382 * Return the site's compact logo URL, if any.
384 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
385 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
386 * @return moodle_url|false
388 public function get_compact_logo_url($maxwidth = 300, $maxheight = 300) {
389 global $CFG;
390 $logo = get_config('core_admin', 'logocompact');
391 if (empty($logo)) {
392 return false;
395 // Hide the requested size in the file path.
396 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
398 // Use $CFG->themerev to prevent browser caching when the file changes.
399 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
400 theme_get_revision(), $logo);
404 * Whether we should display the logo in the navbar.
406 * We will when there are no main logos, and we have compact logo.
408 * @return bool
410 public function should_display_navbar_logo() {
411 $logo = $this->get_compact_logo_url();
412 return !empty($logo);
416 * Whether we should display the main logo.
417 * @deprecated since Moodle 4.0
418 * @todo final deprecation. To be removed in Moodle 4.4 MDL-73165.
419 * @param int $headinglevel The heading level we want to check against.
420 * @return bool
422 public function should_display_main_logo($headinglevel = 1) {
423 debugging('should_display_main_logo() is deprecated and will be removed in Moodle 4.4.', DEBUG_DEVELOPER);
424 // Only render the logo if we're on the front page or login page and the we have a logo.
425 $logo = $this->get_logo_url();
426 if ($headinglevel == 1 && !empty($logo)) {
427 if ($this->page->pagelayout == 'frontpage' || $this->page->pagelayout == 'login') {
428 return true;
432 return false;
439 * Basis for all plugin renderers.
441 * @copyright Petr Skoda (skodak)
442 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
443 * @since Moodle 2.0
444 * @package core
445 * @category output
447 class plugin_renderer_base extends renderer_base {
450 * @var renderer_base|core_renderer A reference to the current renderer.
451 * The renderer provided here will be determined by the page but will in 90%
452 * of cases by the {@link core_renderer}
454 protected $output;
457 * Constructor method, calls the parent constructor
459 * @param moodle_page $page
460 * @param string $target one of rendering target constants
462 public function __construct(moodle_page $page, $target) {
463 if (empty($target) && $page->pagelayout === 'maintenance') {
464 // If the page is using the maintenance layout then we're going to force the target to maintenance.
465 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
466 // unavailable for this page layout.
467 $target = RENDERER_TARGET_MAINTENANCE;
469 $this->output = $page->get_renderer('core', null, $target);
470 parent::__construct($page, $target);
474 * Renders the provided widget and returns the HTML to display it.
476 * @param renderable $widget instance with renderable interface
477 * @return string
479 public function render(renderable $widget) {
480 $classname = get_class($widget);
482 // Strip namespaces.
483 $classname = preg_replace('/^.*\\\/', '', $classname);
485 // Keep a copy at this point, we may need to look for a deprecated method.
486 $deprecatedmethod = "render_{$classname}";
488 // Remove _renderable suffixes.
489 $classname = preg_replace('/_renderable$/', '', $classname);
490 $rendermethod = "render_{$classname}";
492 if (method_exists($this, $rendermethod)) {
493 // Call the render_[widget_name] function.
494 // Note: This has a higher priority than the named_templatable to allow the theme to override the template.
495 return $this->$rendermethod($widget);
498 if ($widget instanceof named_templatable) {
499 // This is a named templatable.
500 // Fetch the template name from the get_template_name function instead.
501 // Note: This has higher priority than the deprecated method which is not overridable by themes anyway.
502 return $this->render_from_template(
503 $widget->get_template_name($this),
504 $widget->export_for_template($this)
508 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
509 // This is exactly where we don't want to be.
510 // If you have arrived here you have a renderable component within your plugin that has the name
511 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
512 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
513 // and the _renderable suffix now gets removed when looking for a render method.
514 // You need to change your renderers render_blah_renderable to render_blah.
515 // Until you do this it will not be possible for a theme to override the renderer to override your method.
516 // Please do it ASAP.
517 static $debugged = [];
518 if (!isset($debugged[$deprecatedmethod])) {
519 debugging(sprintf(
520 'Deprecated call. Please rename your renderables render method from %s to %s.',
521 $deprecatedmethod,
522 $rendermethod
523 ), DEBUG_DEVELOPER);
524 $debugged[$deprecatedmethod] = true;
526 return $this->$deprecatedmethod($widget);
529 // Pass to core renderer if method not found here.
530 // Note: this is not a parent. This is _new_ renderer which respects the requested format, and output type.
531 return $this->output->render($widget);
535 * Magic method used to pass calls otherwise meant for the standard renderer
536 * to it to ensure we don't go causing unnecessary grief.
538 * @param string $method
539 * @param array $arguments
540 * @return mixed
542 public function __call($method, $arguments) {
543 if (method_exists('renderer_base', $method)) {
544 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
546 if (method_exists($this->output, $method)) {
547 return call_user_func_array(array($this->output, $method), $arguments);
548 } else {
549 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
556 * The standard implementation of the core_renderer interface.
558 * @copyright 2009 Tim Hunt
559 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
560 * @since Moodle 2.0
561 * @package core
562 * @category output
564 class core_renderer extends renderer_base {
566 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
567 * in layout files instead.
568 * @deprecated
569 * @var string used in {@link core_renderer::header()}.
571 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
574 * @var string Used to pass information from {@link core_renderer::doctype()} to
575 * {@link core_renderer::standard_head_html()}.
577 protected $contenttype;
580 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
581 * with {@link core_renderer::header()}.
583 protected $metarefreshtag = '';
586 * @var string Unique token for the closing HTML
588 protected $unique_end_html_token;
591 * @var string Unique token for performance information
593 protected $unique_performance_info_token;
596 * @var string Unique token for the main content.
598 protected $unique_main_content_token;
600 /** @var custom_menu_item language The language menu if created */
601 protected $language = null;
604 * Constructor
606 * @param moodle_page $page the page we are doing output for.
607 * @param string $target one of rendering target constants
609 public function __construct(moodle_page $page, $target) {
610 $this->opencontainers = $page->opencontainers;
611 $this->page = $page;
612 $this->target = $target;
614 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
615 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
616 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
620 * Get the DOCTYPE declaration that should be used with this page. Designed to
621 * be called in theme layout.php files.
623 * @return string the DOCTYPE declaration that should be used.
625 public function doctype() {
626 if ($this->page->theme->doctype === 'html5') {
627 $this->contenttype = 'text/html; charset=utf-8';
628 return "<!DOCTYPE html>\n";
630 } else if ($this->page->theme->doctype === 'xhtml5') {
631 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
632 return "<!DOCTYPE html>\n";
634 } else {
635 // legacy xhtml 1.0
636 $this->contenttype = 'text/html; charset=utf-8';
637 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
642 * The attributes that should be added to the <html> tag. Designed to
643 * be called in theme layout.php files.
645 * @return string HTML fragment.
647 public function htmlattributes() {
648 $return = get_html_lang(true);
649 $attributes = array();
650 if ($this->page->theme->doctype !== 'html5') {
651 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
654 // Give plugins an opportunity to add things like xml namespaces to the html element.
655 // This function should return an array of html attribute names => values.
656 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
657 foreach ($pluginswithfunction as $plugins) {
658 foreach ($plugins as $function) {
659 $newattrs = $function();
660 unset($newattrs['dir']);
661 unset($newattrs['lang']);
662 unset($newattrs['xmlns']);
663 unset($newattrs['xml:lang']);
664 $attributes += $newattrs;
668 foreach ($attributes as $key => $val) {
669 $val = s($val);
670 $return .= " $key=\"$val\"";
673 return $return;
677 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
678 * that should be included in the <head> tag. Designed to be called in theme
679 * layout.php files.
681 * @return string HTML fragment.
683 public function standard_head_html() {
684 global $CFG, $SESSION, $SITE;
686 // Before we output any content, we need to ensure that certain
687 // page components are set up.
689 // Blocks must be set up early as they may require javascript which
690 // has to be included in the page header before output is created.
691 foreach ($this->page->blocks->get_regions() as $region) {
692 $this->page->blocks->ensure_content_created($region, $this);
695 $output = '';
697 // Give plugins an opportunity to add any head elements. The callback
698 // must always return a string containing valid html head content.
699 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
700 foreach ($pluginswithfunction as $plugins) {
701 foreach ($plugins as $function) {
702 $output .= $function();
706 // Allow a url_rewrite plugin to setup any dynamic head content.
707 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
708 $class = $CFG->urlrewriteclass;
709 $output .= $class::html_head_setup();
712 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
713 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
714 // This is only set by the {@link redirect()} method
715 $output .= $this->metarefreshtag;
717 // Check if a periodic refresh delay has been set and make sure we arn't
718 // already meta refreshing
719 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
720 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
723 // Set up help link popups for all links with the helptooltip class
724 $this->page->requires->js_init_call('M.util.help_popups.setup');
726 $focus = $this->page->focuscontrol;
727 if (!empty($focus)) {
728 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
729 // This is a horrifically bad way to handle focus but it is passed in
730 // through messy formslib::moodleform
731 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
732 } else if (strpos($focus, '.')!==false) {
733 // Old style of focus, bad way to do it
734 debugging('This code is using the old style focus event, Please update this code to focus on an element id or the moodleform focus method.', DEBUG_DEVELOPER);
735 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
736 } else {
737 // Focus element with given id
738 $this->page->requires->js_function_call('focuscontrol', array($focus));
742 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
743 // any other custom CSS can not be overridden via themes and is highly discouraged
744 $urls = $this->page->theme->css_urls($this->page);
745 foreach ($urls as $url) {
746 $this->page->requires->css_theme($url);
749 // Get the theme javascript head and footer
750 if ($jsurl = $this->page->theme->javascript_url(true)) {
751 $this->page->requires->js($jsurl, true);
753 if ($jsurl = $this->page->theme->javascript_url(false)) {
754 $this->page->requires->js($jsurl);
757 // Get any HTML from the page_requirements_manager.
758 $output .= $this->page->requires->get_head_code($this->page, $this);
760 // List alternate versions.
761 foreach ($this->page->alternateversions as $type => $alt) {
762 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
763 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
766 // Add noindex tag if relevant page and setting applied.
767 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
768 $loginpages = array('login-index', 'login-signup');
769 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
770 if (!isset($CFG->additionalhtmlhead)) {
771 $CFG->additionalhtmlhead = '';
773 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
776 if (!empty($CFG->additionalhtmlhead)) {
777 $output .= "\n".$CFG->additionalhtmlhead;
780 if ($this->page->pagelayout == 'frontpage') {
781 $summary = s(strip_tags(format_text($SITE->summary, FORMAT_HTML)));
782 if (!empty($summary)) {
783 $output .= "<meta name=\"description\" content=\"$summary\" />\n";
787 return $output;
791 * The standard tags (typically skip links) that should be output just inside
792 * the start of the <body> tag. Designed to be called in theme layout.php files.
794 * @return string HTML fragment.
796 public function standard_top_of_body_html() {
797 global $CFG;
798 $output = $this->page->requires->get_top_of_body_code($this);
799 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
800 $output .= "\n".$CFG->additionalhtmltopofbody;
803 // Give subsystems an opportunity to inject extra html content. The callback
804 // must always return a string containing valid html.
805 foreach (\core_component::get_core_subsystems() as $name => $path) {
806 if ($path) {
807 $output .= component_callback($name, 'before_standard_top_of_body_html', [], '');
811 // Give plugins an opportunity to inject extra html content. The callback
812 // must always return a string containing valid html.
813 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
814 foreach ($pluginswithfunction as $plugins) {
815 foreach ($plugins as $function) {
816 $output .= $function();
820 $output .= $this->maintenance_warning();
822 return $output;
826 * Scheduled maintenance warning message.
828 * Note: This is a nasty hack to display maintenance notice, this should be moved
829 * to some general notification area once we have it.
831 * @return string
833 public function maintenance_warning() {
834 global $CFG;
836 $output = '';
837 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
838 $timeleft = $CFG->maintenance_later - time();
839 // If timeleft less than 30 sec, set the class on block to error to highlight.
840 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
841 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-3 alert');
842 $a = new stdClass();
843 $a->hour = (int)($timeleft / 3600);
844 $a->min = (int)(($timeleft / 60) % 60);
845 $a->sec = (int)($timeleft % 60);
846 if ($a->hour > 0) {
847 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
848 } else {
849 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
852 $output .= $this->box_end();
853 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
854 array(array('timeleftinsec' => $timeleft)));
855 $this->page->requires->strings_for_js(
856 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
857 'admin');
859 return $output;
863 * content that should be output in the footer area
864 * of the page. Designed to be called in theme layout.php files.
866 * @return string HTML fragment.
868 public function standard_footer_html() {
869 global $CFG;
871 $output = '';
872 if (during_initial_install()) {
873 // Debugging info can not work before install is finished,
874 // in any case we do not want any links during installation!
875 return $output;
878 // Give plugins an opportunity to add any footer elements.
879 // The callback must always return a string containing valid html footer content.
880 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
881 foreach ($pluginswithfunction as $plugins) {
882 foreach ($plugins as $function) {
883 $output .= $function();
887 if (core_userfeedback::can_give_feedback()) {
888 $output .= html_writer::div(
889 $this->render_from_template('core/userfeedback_footer_link', ['url' => core_userfeedback::make_link()->out(false)])
893 if ($this->page->devicetypeinuse == 'legacy') {
894 // The legacy theme is in use print the notification
895 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
898 // Get links to switch device types (only shown for users not on a default device)
899 $output .= $this->theme_switch_links();
901 return $output;
905 * Performance information and validation links for debugging.
907 * @return string HTML fragment.
909 public function debug_footer_html() {
910 global $CFG, $SCRIPT;
911 $output = '';
913 if (during_initial_install()) {
914 // Debugging info can not work before install is finished.
915 return $output;
918 // This function is normally called from a layout.php file
919 // but some of the content won't be known until later, so we return a placeholder
920 // for now. This will be replaced with the real content in the footer.
921 $output .= $this->unique_performance_info_token;
923 if (!empty($CFG->debugpageinfo)) {
924 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
925 $this->page->debug_summary()) . '</div>';
927 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
929 // Add link to profiling report if necessary
930 if (function_exists('profiling_is_running') && profiling_is_running()) {
931 $txt = get_string('profiledscript', 'admin');
932 $title = get_string('profiledscriptview', 'admin');
933 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
934 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
935 $output .= '<div class="profilingfooter">' . $link . '</div>';
937 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
938 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
939 $output .= '<div class="purgecaches">' .
940 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
942 // Reactive module debug panel.
943 $output .= $this->render_from_template('core/local/reactive/debugpanel', []);
945 if (!empty($CFG->debugvalidators)) {
946 $siteurl = qualified_me();
947 $nuurl = new moodle_url('https://validator.w3.org/nu/', ['doc' => $siteurl, 'showsource' => 'yes']);
948 $waveurl = new moodle_url('https://wave.webaim.org/report#/' . urlencode($siteurl));
949 $validatorlinks = [
950 html_writer::link($nuurl, get_string('validatehtml')),
951 html_writer::link($waveurl, get_string('wcagcheck'))
953 $validatorlinkslist = html_writer::alist($validatorlinks, ['class' => 'list-unstyled ml-1']);
954 $output .= html_writer::div($validatorlinkslist, 'validators');
956 return $output;
960 * Returns standard main content placeholder.
961 * Designed to be called in theme layout.php files.
963 * @return string HTML fragment.
965 public function main_content() {
966 // This is here because it is the only place we can inject the "main" role over the entire main content area
967 // without requiring all theme's to manually do it, and without creating yet another thing people need to
968 // remember in the theme.
969 // This is an unfortunate hack. DO NO EVER add anything more here.
970 // DO NOT add classes.
971 // DO NOT add an id.
972 return '<div role="main">'.$this->unique_main_content_token.'</div>';
976 * Returns information about an activity.
978 * @param cm_info $cminfo The course module information.
979 * @param cm_completion_details $completiondetails The completion details for this activity module.
980 * @param array $activitydates The dates for this activity module.
981 * @return string the activity information HTML.
982 * @throws coding_exception
984 public function activity_information(cm_info $cminfo, cm_completion_details $completiondetails, array $activitydates): string {
985 if (!$completiondetails->has_completion() && empty($activitydates)) {
986 // No need to render the activity information when there's no completion info and activity dates to show.
987 return '';
989 $activityinfo = new activity_information($cminfo, $completiondetails, $activitydates);
990 $renderer = $this->page->get_renderer('core', 'course');
991 return $renderer->render($activityinfo);
995 * Returns standard navigation between activities in a course.
997 * @return string the navigation HTML.
999 public function activity_navigation() {
1000 // First we should check if we want to add navigation.
1001 $context = $this->page->context;
1002 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
1003 || $context->contextlevel != CONTEXT_MODULE) {
1004 return '';
1007 // If the activity is in stealth mode, show no links.
1008 if ($this->page->cm->is_stealth()) {
1009 return '';
1012 $course = $this->page->cm->get_course();
1013 $courseformat = course_get_format($course);
1015 // If the theme implements course index and the current course format uses course index and the current
1016 // page layout is not 'frametop' (this layout does not support course index), show no links.
1017 if ($this->page->theme->usescourseindex && $courseformat->uses_course_index() &&
1018 $this->page->pagelayout !== 'frametop') {
1019 return '';
1022 // Get a list of all the activities in the course.
1023 $modules = get_fast_modinfo($course->id)->get_cms();
1025 // Put the modules into an array in order by the position they are shown in the course.
1026 $mods = [];
1027 $activitylist = [];
1028 foreach ($modules as $module) {
1029 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
1030 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
1031 continue;
1033 $mods[$module->id] = $module;
1035 // No need to add the current module to the list for the activity dropdown menu.
1036 if ($module->id == $this->page->cm->id) {
1037 continue;
1039 // Module name.
1040 $modname = $module->get_formatted_name();
1041 // Display the hidden text if necessary.
1042 if (!$module->visible) {
1043 $modname .= ' ' . get_string('hiddenwithbrackets');
1045 // Module URL.
1046 $linkurl = new moodle_url($module->url, array('forceview' => 1));
1047 // Add module URL (as key) and name (as value) to the activity list array.
1048 $activitylist[$linkurl->out(false)] = $modname;
1051 $nummods = count($mods);
1053 // If there is only one mod then do nothing.
1054 if ($nummods == 1) {
1055 return '';
1058 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
1059 $modids = array_keys($mods);
1061 // Get the position in the array of the course module we are viewing.
1062 $position = array_search($this->page->cm->id, $modids);
1064 $prevmod = null;
1065 $nextmod = null;
1067 // Check if we have a previous mod to show.
1068 if ($position > 0) {
1069 $prevmod = $mods[$modids[$position - 1]];
1072 // Check if we have a next mod to show.
1073 if ($position < ($nummods - 1)) {
1074 $nextmod = $mods[$modids[$position + 1]];
1077 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
1078 $renderer = $this->page->get_renderer('core', 'course');
1079 return $renderer->render($activitynav);
1083 * The standard tags (typically script tags that are not needed earlier) that
1084 * should be output after everything else. Designed to be called in theme layout.php files.
1086 * @return string HTML fragment.
1088 public function standard_end_of_body_html() {
1089 global $CFG;
1091 // This function is normally called from a layout.php file in {@link core_renderer::header()}
1092 // but some of the content won't be known until later, so we return a placeholder
1093 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
1094 $output = '';
1095 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
1096 $output .= "\n".$CFG->additionalhtmlfooter;
1098 $output .= $this->unique_end_html_token;
1099 return $output;
1103 * The standard HTML that should be output just before the <footer> tag.
1104 * Designed to be called in theme layout.php files.
1106 * @return string HTML fragment.
1108 public function standard_after_main_region_html() {
1109 global $CFG;
1110 $output = '';
1111 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlbottomofbody)) {
1112 $output .= "\n".$CFG->additionalhtmlbottomofbody;
1115 // Give subsystems an opportunity to inject extra html content. The callback
1116 // must always return a string containing valid html.
1117 foreach (\core_component::get_core_subsystems() as $name => $path) {
1118 if ($path) {
1119 $output .= component_callback($name, 'standard_after_main_region_html', [], '');
1123 // Give plugins an opportunity to inject extra html content. The callback
1124 // must always return a string containing valid html.
1125 $pluginswithfunction = get_plugins_with_function('standard_after_main_region_html', 'lib.php');
1126 foreach ($pluginswithfunction as $plugins) {
1127 foreach ($plugins as $function) {
1128 $output .= $function();
1132 return $output;
1136 * Return the standard string that says whether you are logged in (and switched
1137 * roles/logged in as another user).
1138 * @param bool $withlinks if false, then don't include any links in the HTML produced.
1139 * If not set, the default is the nologinlinks option from the theme config.php file,
1140 * and if that is not set, then links are included.
1141 * @return string HTML fragment.
1143 public function login_info($withlinks = null) {
1144 global $USER, $CFG, $DB, $SESSION;
1146 if (during_initial_install()) {
1147 return '';
1150 if (is_null($withlinks)) {
1151 $withlinks = empty($this->page->layout_options['nologinlinks']);
1154 $course = $this->page->course;
1155 if (\core\session\manager::is_loggedinas()) {
1156 $realuser = \core\session\manager::get_realuser();
1157 $fullname = fullname($realuser);
1158 if ($withlinks) {
1159 $loginastitle = get_string('loginas');
1160 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
1161 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
1162 } else {
1163 $realuserinfo = " [$fullname] ";
1165 } else {
1166 $realuserinfo = '';
1169 $loginpage = $this->is_login_page();
1170 $loginurl = get_login_url();
1172 if (empty($course->id)) {
1173 // $course->id is not defined during installation
1174 return '';
1175 } else if (isloggedin()) {
1176 $context = context_course::instance($course->id);
1178 $fullname = fullname($USER);
1179 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
1180 if ($withlinks) {
1181 $linktitle = get_string('viewprofile');
1182 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
1183 } else {
1184 $username = $fullname;
1186 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
1187 if ($withlinks) {
1188 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1189 } else {
1190 $username .= " from {$idprovider->name}";
1193 if (isguestuser()) {
1194 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1195 if (!$loginpage && $withlinks) {
1196 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1198 } else if (is_role_switched($course->id)) { // Has switched roles
1199 $rolename = '';
1200 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1201 $rolename = ': '.role_get_name($role, $context);
1203 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1204 if ($withlinks) {
1205 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1206 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1208 } else {
1209 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1210 if ($withlinks) {
1211 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1214 } else {
1215 $loggedinas = get_string('loggedinnot', 'moodle');
1216 if (!$loginpage && $withlinks) {
1217 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1221 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1223 if (isset($SESSION->justloggedin)) {
1224 unset($SESSION->justloggedin);
1225 if (!isguestuser()) {
1226 // Include this file only when required.
1227 require_once($CFG->dirroot . '/user/lib.php');
1228 if (($count = user_count_login_failures($USER)) && !empty($CFG->displayloginfailures)) {
1229 $loggedinas .= '<div class="loginfailures">';
1230 $a = new stdClass();
1231 $a->attempts = $count;
1232 $loggedinas .= get_string('failedloginattempts', '', $a);
1233 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1234 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1235 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1237 $loggedinas .= '</div>';
1242 return $loggedinas;
1246 * Check whether the current page is a login page.
1248 * @since Moodle 2.9
1249 * @return bool
1251 protected function is_login_page() {
1252 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1253 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1254 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1255 return in_array(
1256 $this->page->url->out_as_local_url(false, array()),
1257 array(
1258 '/login/index.php',
1259 '/login/forgot_password.php',
1265 * Return the 'back' link that normally appears in the footer.
1267 * @return string HTML fragment.
1269 public function home_link() {
1270 global $CFG, $SITE;
1272 if ($this->page->pagetype == 'site-index') {
1273 // Special case for site home page - please do not remove
1274 return '<div class="sitelink">' .
1275 '<a title="Moodle" class="d-inline-block aalink" href="http://moodle.org/">' .
1276 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1278 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1279 // Special case for during install/upgrade.
1280 return '<div class="sitelink">'.
1281 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1282 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1284 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1285 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1286 get_string('home') . '</a></div>';
1288 } else {
1289 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1290 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1295 * Redirects the user by any means possible given the current state
1297 * This function should not be called directly, it should always be called using
1298 * the redirect function in lib/weblib.php
1300 * The redirect function should really only be called before page output has started
1301 * however it will allow itself to be called during the state STATE_IN_BODY
1303 * @param string $encodedurl The URL to send to encoded if required
1304 * @param string $message The message to display to the user if any
1305 * @param int $delay The delay before redirecting a user, if $message has been
1306 * set this is a requirement and defaults to 3, set to 0 no delay
1307 * @param boolean $debugdisableredirect this redirect has been disabled for
1308 * debugging purposes. Display a message that explains, and don't
1309 * trigger the redirect.
1310 * @param string $messagetype The type of notification to show the message in.
1311 * See constants on \core\output\notification.
1312 * @return string The HTML to display to the user before dying, may contain
1313 * meta refresh, javascript refresh, and may have set header redirects
1315 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1316 $messagetype = \core\output\notification::NOTIFY_INFO) {
1317 global $CFG;
1318 $url = str_replace('&amp;', '&', $encodedurl);
1320 switch ($this->page->state) {
1321 case moodle_page::STATE_BEFORE_HEADER :
1322 // No output yet it is safe to delivery the full arsenal of redirect methods
1323 if (!$debugdisableredirect) {
1324 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1325 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1326 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1328 $output = $this->header();
1329 break;
1330 case moodle_page::STATE_PRINTING_HEADER :
1331 // We should hopefully never get here
1332 throw new coding_exception('You cannot redirect while printing the page header');
1333 break;
1334 case moodle_page::STATE_IN_BODY :
1335 // We really shouldn't be here but we can deal with this
1336 debugging("You should really redirect before you start page output");
1337 if (!$debugdisableredirect) {
1338 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1340 $output = $this->opencontainers->pop_all_but_last();
1341 break;
1342 case moodle_page::STATE_DONE :
1343 // Too late to be calling redirect now
1344 throw new coding_exception('You cannot redirect after the entire page has been generated');
1345 break;
1347 $output .= $this->notification($message, $messagetype);
1348 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1349 if ($debugdisableredirect) {
1350 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1352 $output .= $this->footer();
1353 return $output;
1357 * Start output by sending the HTTP headers, and printing the HTML <head>
1358 * and the start of the <body>.
1360 * To control what is printed, you should set properties on $PAGE.
1362 * @return string HTML that you must output this, preferably immediately.
1364 public function header() {
1365 global $USER, $CFG, $SESSION;
1367 // Give plugins an opportunity touch things before the http headers are sent
1368 // such as adding additional headers. The return value is ignored.
1369 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1370 foreach ($pluginswithfunction as $plugins) {
1371 foreach ($plugins as $function) {
1372 $function();
1376 if (\core\session\manager::is_loggedinas()) {
1377 $this->page->add_body_class('userloggedinas');
1380 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1381 require_once($CFG->dirroot . '/user/lib.php');
1382 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1383 if ($count = user_count_login_failures($USER, false)) {
1384 $this->page->add_body_class('loginfailures');
1388 // If the user is logged in, and we're not in initial install,
1389 // check to see if the user is role-switched and add the appropriate
1390 // CSS class to the body element.
1391 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1392 $this->page->add_body_class('userswitchedrole');
1395 // Give themes a chance to init/alter the page object.
1396 $this->page->theme->init_page($this->page);
1398 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1400 // Find the appropriate page layout file, based on $this->page->pagelayout.
1401 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1402 // Render the layout using the layout file.
1403 $rendered = $this->render_page_layout($layoutfile);
1405 // Slice the rendered output into header and footer.
1406 $cutpos = strpos($rendered, $this->unique_main_content_token);
1407 if ($cutpos === false) {
1408 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1409 $token = self::MAIN_CONTENT_TOKEN;
1410 } else {
1411 $token = $this->unique_main_content_token;
1414 if ($cutpos === false) {
1415 throw new coding_exception('page layout file ' . $layoutfile . ' does not contain the main content placeholder, please include "<?php echo $OUTPUT->main_content() ?>" in theme layout file.');
1417 $header = substr($rendered, 0, $cutpos);
1418 $footer = substr($rendered, $cutpos + strlen($token));
1420 if (empty($this->contenttype)) {
1421 debugging('The page layout file did not call $OUTPUT->doctype()');
1422 $header = $this->doctype() . $header;
1425 // If this theme version is below 2.4 release and this is a course view page
1426 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1427 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1428 // check if course content header/footer have not been output during render of theme layout
1429 $coursecontentheader = $this->course_content_header(true);
1430 $coursecontentfooter = $this->course_content_footer(true);
1431 if (!empty($coursecontentheader)) {
1432 // display debug message and add header and footer right above and below main content
1433 // Please note that course header and footer (to be displayed above and below the whole page)
1434 // are not displayed in this case at all.
1435 // Besides the content header and footer are not displayed on any other course page
1436 debugging('The current theme is not optimised for 2.4, the course-specific header and footer defined in course format will not be output', DEBUG_DEVELOPER);
1437 $header .= $coursecontentheader;
1438 $footer = $coursecontentfooter. $footer;
1442 send_headers($this->contenttype, $this->page->cacheable);
1444 $this->opencontainers->push('header/footer', $footer);
1445 $this->page->set_state(moodle_page::STATE_IN_BODY);
1447 // If an activity record has been set, activity_header will handle this.
1448 if (!$this->page->cm || !empty($this->page->layout_options['noactivityheader'])) {
1449 $header .= $this->skip_link_target('maincontent');
1451 return $header;
1455 * Renders and outputs the page layout file.
1457 * This is done by preparing the normal globals available to a script, and
1458 * then including the layout file provided by the current theme for the
1459 * requested layout.
1461 * @param string $layoutfile The name of the layout file
1462 * @return string HTML code
1464 protected function render_page_layout($layoutfile) {
1465 global $CFG, $SITE, $USER;
1466 // The next lines are a bit tricky. The point is, here we are in a method
1467 // of a renderer class, and this object may, or may not, be the same as
1468 // the global $OUTPUT object. When rendering the page layout file, we want to use
1469 // this object. However, people writing Moodle code expect the current
1470 // renderer to be called $OUTPUT, not $this, so define a variable called
1471 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1472 $OUTPUT = $this;
1473 $PAGE = $this->page;
1474 $COURSE = $this->page->course;
1476 ob_start();
1477 include($layoutfile);
1478 $rendered = ob_get_contents();
1479 ob_end_clean();
1480 return $rendered;
1484 * Outputs the page's footer
1486 * @return string HTML fragment
1488 public function footer() {
1489 global $CFG, $DB;
1491 $output = '';
1493 // Give plugins an opportunity to touch the page before JS is finalized.
1494 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1495 foreach ($pluginswithfunction as $plugins) {
1496 foreach ($plugins as $function) {
1497 $extrafooter = $function();
1498 if (is_string($extrafooter)) {
1499 $output .= $extrafooter;
1504 $output .= $this->container_end_all(true);
1506 $footer = $this->opencontainers->pop('header/footer');
1508 if (debugging() and $DB and $DB->is_transaction_started()) {
1509 // TODO: MDL-20625 print warning - transaction will be rolled back
1512 // Provide some performance info if required
1513 $performanceinfo = '';
1514 if ((defined('MDL_PERF') && MDL_PERF) || (!empty($CFG->perfdebug) && $CFG->perfdebug > 7)) {
1515 $perf = get_performance_info();
1516 if ((defined('MDL_PERFTOFOOT') && MDL_PERFTOFOOT) || debugging() || $CFG->perfdebug > 7) {
1517 $performanceinfo = $perf['html'];
1521 // We always want performance data when running a performance test, even if the user is redirected to another page.
1522 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1523 $footer = $this->unique_performance_info_token . $footer;
1525 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1527 // Only show notifications when the current page has a context id.
1528 if (!empty($this->page->context->id)) {
1529 $this->page->requires->js_call_amd('core/notification', 'init', array(
1530 $this->page->context->id,
1531 \core\notification::fetch_as_array($this)
1534 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1536 $this->page->set_state(moodle_page::STATE_DONE);
1538 return $output . $footer;
1542 * Close all but the last open container. This is useful in places like error
1543 * handling, where you want to close all the open containers (apart from <body>)
1544 * before outputting the error message.
1546 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1547 * developer debug warning if it isn't.
1548 * @return string the HTML required to close any open containers inside <body>.
1550 public function container_end_all($shouldbenone = false) {
1551 return $this->opencontainers->pop_all_but_last($shouldbenone);
1555 * Returns course-specific information to be output immediately above content on any course page
1556 * (for the current course)
1558 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1559 * @return string
1561 public function course_content_header($onlyifnotcalledbefore = false) {
1562 global $CFG;
1563 static $functioncalled = false;
1564 if ($functioncalled && $onlyifnotcalledbefore) {
1565 // we have already output the content header
1566 return '';
1569 // Output any session notification.
1570 $notifications = \core\notification::fetch();
1572 $bodynotifications = '';
1573 foreach ($notifications as $notification) {
1574 $bodynotifications .= $this->render_from_template(
1575 $notification->get_template_name(),
1576 $notification->export_for_template($this)
1580 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1582 if ($this->page->course->id == SITEID) {
1583 // return immediately and do not include /course/lib.php if not necessary
1584 return $output;
1587 require_once($CFG->dirroot.'/course/lib.php');
1588 $functioncalled = true;
1589 $courseformat = course_get_format($this->page->course);
1590 if (($obj = $courseformat->course_content_header()) !== null) {
1591 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1593 return $output;
1597 * Returns course-specific information to be output immediately below content on any course page
1598 * (for the current course)
1600 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1601 * @return string
1603 public function course_content_footer($onlyifnotcalledbefore = false) {
1604 global $CFG;
1605 if ($this->page->course->id == SITEID) {
1606 // return immediately and do not include /course/lib.php if not necessary
1607 return '';
1609 static $functioncalled = false;
1610 if ($functioncalled && $onlyifnotcalledbefore) {
1611 // we have already output the content footer
1612 return '';
1614 $functioncalled = true;
1615 require_once($CFG->dirroot.'/course/lib.php');
1616 $courseformat = course_get_format($this->page->course);
1617 if (($obj = $courseformat->course_content_footer()) !== null) {
1618 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1620 return '';
1624 * Returns course-specific information to be output on any course page in the header area
1625 * (for the current course)
1627 * @return string
1629 public function course_header() {
1630 global $CFG;
1631 if ($this->page->course->id == SITEID) {
1632 // return immediately and do not include /course/lib.php if not necessary
1633 return '';
1635 require_once($CFG->dirroot.'/course/lib.php');
1636 $courseformat = course_get_format($this->page->course);
1637 if (($obj = $courseformat->course_header()) !== null) {
1638 return $courseformat->get_renderer($this->page)->render($obj);
1640 return '';
1644 * Returns course-specific information to be output on any course page in the footer area
1645 * (for the current course)
1647 * @return string
1649 public function course_footer() {
1650 global $CFG;
1651 if ($this->page->course->id == SITEID) {
1652 // return immediately and do not include /course/lib.php if not necessary
1653 return '';
1655 require_once($CFG->dirroot.'/course/lib.php');
1656 $courseformat = course_get_format($this->page->course);
1657 if (($obj = $courseformat->course_footer()) !== null) {
1658 return $courseformat->get_renderer($this->page)->render($obj);
1660 return '';
1664 * Get the course pattern datauri to show on a course card.
1666 * The datauri is an encoded svg that can be passed as a url.
1667 * @param int $id Id to use when generating the pattern
1668 * @return string datauri
1670 public function get_generated_image_for_id($id) {
1671 $color = $this->get_generated_color_for_id($id);
1672 $pattern = new \core_geopattern();
1673 $pattern->setColor($color);
1674 $pattern->patternbyid($id);
1675 return $pattern->datauri();
1679 * Get the course pattern image URL.
1681 * @param context_course $context course context object
1682 * @return string URL of the course pattern image in SVG format
1684 public function get_generated_url_for_course(context_course $context): string {
1685 return moodle_url::make_pluginfile_url($context->id, 'course', 'generated', null, '/', 'course.svg')->out();
1689 * Get the course pattern in SVG format to show on a course card.
1691 * @param int $id id to use when generating the pattern
1692 * @return string SVG file contents
1694 public function get_generated_svg_for_id(int $id): string {
1695 $color = $this->get_generated_color_for_id($id);
1696 $pattern = new \core_geopattern();
1697 $pattern->setColor($color);
1698 $pattern->patternbyid($id);
1699 return $pattern->toSVG();
1703 * Get the course color to show on a course card.
1705 * @param int $id Id to use when generating the color.
1706 * @return string hex color code.
1708 public function get_generated_color_for_id($id) {
1709 $colornumbers = range(1, 10);
1710 $basecolors = [];
1711 foreach ($colornumbers as $number) {
1712 $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1715 $color = $basecolors[$id % 10];
1716 return $color;
1720 * Returns lang menu or '', this method also checks forcing of languages in courses.
1722 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1724 * @return string The lang menu HTML or empty string
1726 public function lang_menu() {
1727 $languagemenu = new \core\output\language_menu($this->page);
1728 $data = $languagemenu->export_for_single_select($this);
1729 if ($data) {
1730 return $this->render_from_template('core/single_select', $data);
1732 return '';
1736 * Output the row of editing icons for a block, as defined by the controls array.
1738 * @param array $controls an array like {@link block_contents::$controls}.
1739 * @param string $blockid The ID given to the block.
1740 * @return string HTML fragment.
1742 public function block_controls($actions, $blockid = null) {
1743 global $CFG;
1744 if (empty($actions)) {
1745 return '';
1747 $menu = new action_menu($actions);
1748 if ($blockid !== null) {
1749 $menu->set_owner_selector('#'.$blockid);
1751 $menu->set_constraint('.block-region');
1752 $menu->attributes['class'] .= ' block-control-actions commands';
1753 return $this->render($menu);
1757 * Returns the HTML for a basic textarea field.
1759 * @param string $name Name to use for the textarea element
1760 * @param string $id The id to use fort he textarea element
1761 * @param string $value Initial content to display in the textarea
1762 * @param int $rows Number of rows to display
1763 * @param int $cols Number of columns to display
1764 * @return string the HTML to display
1766 public function print_textarea($name, $id, $value, $rows, $cols) {
1767 editors_head_setup();
1768 $editor = editors_get_preferred_editor(FORMAT_HTML);
1769 $editor->set_text($value);
1770 $editor->use_editor($id, []);
1772 $context = [
1773 'id' => $id,
1774 'name' => $name,
1775 'value' => $value,
1776 'rows' => $rows,
1777 'cols' => $cols
1780 return $this->render_from_template('core_form/editor_textarea', $context);
1784 * Renders an action menu component.
1786 * @param action_menu $menu
1787 * @return string HTML
1789 public function render_action_menu(action_menu $menu) {
1791 // We don't want the class icon there!
1792 foreach ($menu->get_secondary_actions() as $action) {
1793 if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1794 $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1798 if ($menu->is_empty()) {
1799 return '';
1801 $context = $menu->export_for_template($this);
1803 return $this->render_from_template('core/action_menu', $context);
1807 * Renders a Check API result
1809 * @param core\check\result $result
1810 * @return string HTML fragment
1812 protected function render_check_result(core\check\result $result) {
1813 return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1817 * Renders a Check API result
1819 * @param core\check\result $result
1820 * @return string HTML fragment
1822 public function check_result(core\check\result $result) {
1823 return $this->render_check_result($result);
1827 * Renders an action_menu_link item.
1829 * @param action_menu_link $action
1830 * @return string HTML fragment
1832 protected function render_action_menu_link(action_menu_link $action) {
1833 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1837 * Renders a primary action_menu_filler item.
1839 * @param action_menu_link_filler $action
1840 * @return string HTML fragment
1842 protected function render_action_menu_filler(action_menu_filler $action) {
1843 return html_writer::span('&nbsp;', 'filler');
1847 * Renders a primary action_menu_link item.
1849 * @param action_menu_link_primary $action
1850 * @return string HTML fragment
1852 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1853 return $this->render_action_menu_link($action);
1857 * Renders a secondary action_menu_link item.
1859 * @param action_menu_link_secondary $action
1860 * @return string HTML fragment
1862 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1863 return $this->render_action_menu_link($action);
1867 * Prints a nice side block with an optional header.
1869 * @param block_contents $bc HTML for the content
1870 * @param string $region the region the block is appearing in.
1871 * @return string the HTML to be output.
1873 public function block(block_contents $bc, $region) {
1874 $bc = clone($bc); // Avoid messing up the object passed in.
1875 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1876 $bc->collapsible = block_contents::NOT_HIDEABLE;
1879 $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1880 $context = new stdClass();
1881 $context->skipid = $bc->skipid;
1882 $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
1883 $context->dockable = $bc->dockable;
1884 $context->id = $id;
1885 $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1886 $context->skiptitle = strip_tags($bc->title);
1887 $context->showskiplink = !empty($context->skiptitle);
1888 $context->arialabel = $bc->arialabel;
1889 $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
1890 $context->class = $bc->attributes['class'];
1891 $context->type = $bc->attributes['data-block'];
1892 $context->title = $bc->title;
1893 $context->content = $bc->content;
1894 $context->annotation = $bc->annotation;
1895 $context->footer = $bc->footer;
1896 $context->hascontrols = !empty($bc->controls);
1897 if ($context->hascontrols) {
1898 $context->controls = $this->block_controls($bc->controls, $id);
1901 return $this->render_from_template('core/block', $context);
1905 * Render the contents of a block_list.
1907 * @param array $icons the icon for each item.
1908 * @param array $items the content of each item.
1909 * @return string HTML
1911 public function list_block_contents($icons, $items) {
1912 $row = 0;
1913 $lis = array();
1914 foreach ($items as $key => $string) {
1915 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1916 if (!empty($icons[$key])) { //test if the content has an assigned icon
1917 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1919 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1920 $item .= html_writer::end_tag('li');
1921 $lis[] = $item;
1922 $row = 1 - $row; // Flip even/odd.
1924 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1928 * Output all the blocks in a particular region.
1930 * @param string $region the name of a region on this page.
1931 * @param boolean $fakeblocksonly Output fake block only.
1932 * @return string the HTML to be output.
1934 public function blocks_for_region($region, $fakeblocksonly = false) {
1935 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1936 $lastblock = null;
1937 $zones = array();
1938 foreach ($blockcontents as $bc) {
1939 if ($bc instanceof block_contents) {
1940 $zones[] = $bc->title;
1943 $output = '';
1945 foreach ($blockcontents as $bc) {
1946 if ($bc instanceof block_contents) {
1947 if ($fakeblocksonly && !$bc->is_fake()) {
1948 // Skip rendering real blocks if we only want to show fake blocks.
1949 continue;
1951 $output .= $this->block($bc, $region);
1952 $lastblock = $bc->title;
1953 } else if ($bc instanceof block_move_target) {
1954 if (!$fakeblocksonly) {
1955 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1957 } else {
1958 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1961 return $output;
1965 * Output a place where the block that is currently being moved can be dropped.
1967 * @param block_move_target $target with the necessary details.
1968 * @param array $zones array of areas where the block can be moved to
1969 * @param string $previous the block located before the area currently being rendered.
1970 * @param string $region the name of the region
1971 * @return string the HTML to be output.
1973 public function block_move_target($target, $zones, $previous, $region) {
1974 if ($previous == null) {
1975 if (empty($zones)) {
1976 // There are no zones, probably because there are no blocks.
1977 $regions = $this->page->theme->get_all_block_regions();
1978 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1979 } else {
1980 $position = get_string('moveblockbefore', 'block', $zones[0]);
1982 } else {
1983 $position = get_string('moveblockafter', 'block', $previous);
1985 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1989 * Renders a special html link with attached action
1991 * Theme developers: DO NOT OVERRIDE! Please override function
1992 * {@link core_renderer::render_action_link()} instead.
1994 * @param string|moodle_url $url
1995 * @param string $text HTML fragment
1996 * @param component_action $action
1997 * @param array $attributes associative array of html link attributes + disabled
1998 * @param pix_icon optional pix icon to render with the link
1999 * @return string HTML fragment
2001 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
2002 if (!($url instanceof moodle_url)) {
2003 $url = new moodle_url($url);
2005 $link = new action_link($url, $text, $action, $attributes, $icon);
2007 return $this->render($link);
2011 * Renders an action_link object.
2013 * The provided link is renderer and the HTML returned. At the same time the
2014 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
2016 * @param action_link $link
2017 * @return string HTML fragment
2019 protected function render_action_link(action_link $link) {
2020 return $this->render_from_template('core/action_link', $link->export_for_template($this));
2024 * Renders an action_icon.
2026 * This function uses the {@link core_renderer::action_link()} method for the
2027 * most part. What it does different is prepare the icon as HTML and use it
2028 * as the link text.
2030 * Theme developers: If you want to change how action links and/or icons are rendered,
2031 * consider overriding function {@link core_renderer::render_action_link()} and
2032 * {@link core_renderer::render_pix_icon()}.
2034 * @param string|moodle_url $url A string URL or moodel_url
2035 * @param pix_icon $pixicon
2036 * @param component_action $action
2037 * @param array $attributes associative array of html link attributes + disabled
2038 * @param bool $linktext show title next to image in link
2039 * @return string HTML fragment
2041 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
2042 if (!($url instanceof moodle_url)) {
2043 $url = new moodle_url($url);
2045 $attributes = (array)$attributes;
2047 if (empty($attributes['class'])) {
2048 // let ppl override the class via $options
2049 $attributes['class'] = 'action-icon';
2052 $icon = $this->render($pixicon);
2054 if ($linktext) {
2055 $text = $pixicon->attributes['alt'];
2056 } else {
2057 $text = '';
2060 return $this->action_link($url, $text.$icon, $action, $attributes);
2064 * Print a message along with button choices for Continue/Cancel
2066 * If a string or moodle_url is given instead of a single_button, method defaults to post.
2068 * @param string $message The question to ask the user
2069 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
2070 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
2071 * @param array $displayoptions optional extra display options
2072 * @return string HTML fragment
2074 public function confirm($message, $continue, $cancel, array $displayoptions = []) {
2076 // Check existing displayoptions.
2077 $displayoptions['confirmtitle'] = $displayoptions['confirmtitle'] ?? get_string('confirm');
2078 $displayoptions['continuestr'] = $displayoptions['continuestr'] ?? get_string('continue');
2079 $displayoptions['cancelstr'] = $displayoptions['cancelstr'] ?? get_string('cancel');
2081 if ($continue instanceof single_button) {
2082 // Continue button should be primary if set to secondary type as it is the fefault.
2083 if ($continue->type === single_button::BUTTON_SECONDARY) {
2084 $continue->type = single_button::BUTTON_PRIMARY;
2086 } else if (is_string($continue)) {
2087 $continue = new single_button(new moodle_url($continue), $displayoptions['continuestr'], 'post',
2088 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
2089 } else if ($continue instanceof moodle_url) {
2090 $continue = new single_button($continue, $displayoptions['continuestr'], 'post',
2091 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
2092 } else {
2093 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2096 if ($cancel instanceof single_button) {
2097 // ok
2098 } else if (is_string($cancel)) {
2099 $cancel = new single_button(new moodle_url($cancel), $displayoptions['cancelstr'], 'get');
2100 } else if ($cancel instanceof moodle_url) {
2101 $cancel = new single_button($cancel, $displayoptions['cancelstr'], 'get');
2102 } else {
2103 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2106 $attributes = [
2107 'role'=>'alertdialog',
2108 'aria-labelledby'=>'modal-header',
2109 'aria-describedby'=>'modal-body',
2110 'aria-modal'=>'true'
2113 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
2114 $output .= $this->box_start('modal-content', 'modal-content');
2115 $output .= $this->box_start('modal-header px-3', 'modal-header');
2116 $output .= html_writer::tag('h4', $displayoptions['confirmtitle']);
2117 $output .= $this->box_end();
2118 $attributes = [
2119 'role'=>'alert',
2120 'data-aria-autofocus'=>'true'
2122 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
2123 $output .= html_writer::tag('p', $message);
2124 $output .= $this->box_end();
2125 $output .= $this->box_start('modal-footer', 'modal-footer');
2126 $output .= html_writer::tag('div', $this->render($cancel) . $this->render($continue), ['class' => 'buttons']);
2127 $output .= $this->box_end();
2128 $output .= $this->box_end();
2129 $output .= $this->box_end();
2130 return $output;
2134 * Returns a form with a single button.
2136 * Theme developers: DO NOT OVERRIDE! Please override function
2137 * {@link core_renderer::render_single_button()} instead.
2139 * @param string|moodle_url $url
2140 * @param string $label button text
2141 * @param string $method get or post submit method
2142 * @param array $options associative array {disabled, title, etc.}
2143 * @return string HTML fragment
2145 public function single_button($url, $label, $method='post', array $options=null) {
2146 if (!($url instanceof moodle_url)) {
2147 $url = new moodle_url($url);
2149 $button = new single_button($url, $label, $method);
2151 foreach ((array)$options as $key=>$value) {
2152 if (property_exists($button, $key)) {
2153 $button->$key = $value;
2154 } else {
2155 $button->set_attribute($key, $value);
2159 return $this->render($button);
2163 * Renders a single button widget.
2165 * This will return HTML to display a form containing a single button.
2167 * @param single_button $button
2168 * @return string HTML fragment
2170 protected function render_single_button(single_button $button) {
2171 return $this->render_from_template('core/single_button', $button->export_for_template($this));
2175 * Returns a form with a single select widget.
2177 * Theme developers: DO NOT OVERRIDE! Please override function
2178 * {@link core_renderer::render_single_select()} instead.
2180 * @param moodle_url $url form action target, includes hidden fields
2181 * @param string $name name of selection field - the changing parameter in url
2182 * @param array $options list of options
2183 * @param string $selected selected element
2184 * @param array $nothing
2185 * @param string $formid
2186 * @param array $attributes other attributes for the single select
2187 * @return string HTML fragment
2189 public function single_select($url, $name, array $options, $selected = '',
2190 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2191 if (!($url instanceof moodle_url)) {
2192 $url = new moodle_url($url);
2194 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2196 if (array_key_exists('label', $attributes)) {
2197 $select->set_label($attributes['label']);
2198 unset($attributes['label']);
2200 $select->attributes = $attributes;
2202 return $this->render($select);
2206 * Returns a dataformat selection and download form
2208 * @param string $label A text label
2209 * @param moodle_url|string $base The download page url
2210 * @param string $name The query param which will hold the type of the download
2211 * @param array $params Extra params sent to the download page
2212 * @return string HTML fragment
2214 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2216 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2217 $options = array();
2218 foreach ($formats as $format) {
2219 if ($format->is_enabled()) {
2220 $options[] = array(
2221 'value' => $format->name,
2222 'label' => get_string('dataformat', $format->component),
2226 $hiddenparams = array();
2227 foreach ($params as $key => $value) {
2228 $hiddenparams[] = array(
2229 'name' => $key,
2230 'value' => $value,
2233 $data = array(
2234 'label' => $label,
2235 'base' => $base,
2236 'name' => $name,
2237 'params' => $hiddenparams,
2238 'options' => $options,
2239 'sesskey' => sesskey(),
2240 'submit' => get_string('download'),
2243 return $this->render_from_template('core/dataformat_selector', $data);
2248 * Internal implementation of single_select rendering
2250 * @param single_select $select
2251 * @return string HTML fragment
2253 protected function render_single_select(single_select $select) {
2254 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2258 * Returns a form with a url select widget.
2260 * Theme developers: DO NOT OVERRIDE! Please override function
2261 * {@link core_renderer::render_url_select()} instead.
2263 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2264 * @param string $selected selected element
2265 * @param array $nothing
2266 * @param string $formid
2267 * @return string HTML fragment
2269 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2270 $select = new url_select($urls, $selected, $nothing, $formid);
2271 return $this->render($select);
2275 * Internal implementation of url_select rendering
2277 * @param url_select $select
2278 * @return string HTML fragment
2280 protected function render_url_select(url_select $select) {
2281 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2285 * Returns a string containing a link to the user documentation.
2286 * Also contains an icon by default. Shown to teachers and admin only.
2288 * @param string $path The page link after doc root and language, no leading slash.
2289 * @param string $text The text to be displayed for the link
2290 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2291 * @param array $attributes htm attributes
2292 * @return string
2294 public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
2295 global $CFG;
2297 $icon = $this->pix_icon('book', '', 'moodle', array('class' => 'iconhelp icon-pre', 'role' => 'presentation'));
2299 $attributes['href'] = new moodle_url(get_docs_url($path));
2300 $newwindowicon = '';
2301 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2302 $attributes['target'] = '_blank';
2303 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle',
2304 ['class' => 'fa fa-externallink fa-fw']);
2307 return html_writer::tag('a', $icon . $text . $newwindowicon, $attributes);
2311 * Return HTML for an image_icon.
2313 * Theme developers: DO NOT OVERRIDE! Please override function
2314 * {@link core_renderer::render_image_icon()} instead.
2316 * @param string $pix short pix name
2317 * @param string $alt mandatory alt attribute
2318 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2319 * @param array $attributes htm attributes
2320 * @return string HTML fragment
2322 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2323 $icon = new image_icon($pix, $alt, $component, $attributes);
2324 return $this->render($icon);
2328 * Renders a pix_icon widget and returns the HTML to display it.
2330 * @param image_icon $icon
2331 * @return string HTML fragment
2333 protected function render_image_icon(image_icon $icon) {
2334 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2335 return $system->render_pix_icon($this, $icon);
2339 * Return HTML for a pix_icon.
2341 * Theme developers: DO NOT OVERRIDE! Please override function
2342 * {@link core_renderer::render_pix_icon()} instead.
2344 * @param string $pix short pix name
2345 * @param string $alt mandatory alt attribute
2346 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2347 * @param array $attributes htm lattributes
2348 * @return string HTML fragment
2350 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2351 $icon = new pix_icon($pix, $alt, $component, $attributes);
2352 return $this->render($icon);
2356 * Renders a pix_icon widget and returns the HTML to display it.
2358 * @param pix_icon $icon
2359 * @return string HTML fragment
2361 protected function render_pix_icon(pix_icon $icon) {
2362 $system = \core\output\icon_system::instance();
2363 return $system->render_pix_icon($this, $icon);
2367 * Return HTML to display an emoticon icon.
2369 * @param pix_emoticon $emoticon
2370 * @return string HTML fragment
2372 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2373 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2374 return $system->render_pix_icon($this, $emoticon);
2378 * Produces the html that represents this rating in the UI
2380 * @param rating $rating the page object on which this rating will appear
2381 * @return string
2383 function render_rating(rating $rating) {
2384 global $CFG, $USER;
2386 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2387 return null;//ratings are turned off
2390 $ratingmanager = new rating_manager();
2391 // Initialise the JavaScript so ratings can be done by AJAX.
2392 $ratingmanager->initialise_rating_javascript($this->page);
2394 $strrate = get_string("rate", "rating");
2395 $ratinghtml = ''; //the string we'll return
2397 // permissions check - can they view the aggregate?
2398 if ($rating->user_can_view_aggregate()) {
2400 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2401 $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2402 $aggregatestr = $rating->get_aggregate_string();
2404 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2405 if ($rating->count > 0) {
2406 $countstr = "({$rating->count})";
2407 } else {
2408 $countstr = '-';
2410 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2412 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2414 $nonpopuplink = $rating->get_view_ratings_url();
2415 $popuplink = $rating->get_view_ratings_url(true);
2417 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2418 $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
2421 $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
2424 $formstart = null;
2425 // if the item doesn't belong to the current user, the user has permission to rate
2426 // and we're within the assessable period
2427 if ($rating->user_can_rate()) {
2429 $rateurl = $rating->get_rate_url();
2430 $inputs = $rateurl->params();
2432 //start the rating form
2433 $formattrs = array(
2434 'id' => "postrating{$rating->itemid}",
2435 'class' => 'postratingform',
2436 'method' => 'post',
2437 'action' => $rateurl->out_omit_querystring()
2439 $formstart = html_writer::start_tag('form', $formattrs);
2440 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2442 // add the hidden inputs
2443 foreach ($inputs as $name => $value) {
2444 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2445 $formstart .= html_writer::empty_tag('input', $attributes);
2448 if (empty($ratinghtml)) {
2449 $ratinghtml .= $strrate.': ';
2451 $ratinghtml = $formstart.$ratinghtml;
2453 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2454 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2455 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2456 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2458 //output submit button
2459 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2461 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2462 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2464 if (!$rating->settings->scale->isnumeric) {
2465 // If a global scale, try to find current course ID from the context
2466 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2467 $courseid = $coursecontext->instanceid;
2468 } else {
2469 $courseid = $rating->settings->scale->courseid;
2471 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2473 $ratinghtml .= html_writer::end_tag('span');
2474 $ratinghtml .= html_writer::end_tag('div');
2475 $ratinghtml .= html_writer::end_tag('form');
2478 return $ratinghtml;
2482 * Centered heading with attached help button (same title text)
2483 * and optional icon attached.
2485 * @param string $text A heading text
2486 * @param string $helpidentifier The keyword that defines a help page
2487 * @param string $component component name
2488 * @param string|moodle_url $icon
2489 * @param string $iconalt icon alt text
2490 * @param int $level The level of importance of the heading. Defaulting to 2
2491 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2492 * @return string HTML fragment
2494 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2495 $image = '';
2496 if ($icon) {
2497 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2500 $help = '';
2501 if ($helpidentifier) {
2502 $help = $this->help_icon($helpidentifier, $component);
2505 return $this->heading($image.$text.$help, $level, $classnames);
2509 * Returns HTML to display a help icon.
2511 * @deprecated since Moodle 2.0
2513 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2514 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2518 * Returns HTML to display a help icon.
2520 * Theme developers: DO NOT OVERRIDE! Please override function
2521 * {@link core_renderer::render_help_icon()} instead.
2523 * @param string $identifier The keyword that defines a help page
2524 * @param string $component component name
2525 * @param string|bool $linktext true means use $title as link text, string means link text value
2526 * @return string HTML fragment
2528 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2529 $icon = new help_icon($identifier, $component);
2530 $icon->diag_strings();
2531 if ($linktext === true) {
2532 $icon->linktext = get_string($icon->identifier, $icon->component);
2533 } else if (!empty($linktext)) {
2534 $icon->linktext = $linktext;
2536 return $this->render($icon);
2540 * Implementation of user image rendering.
2542 * @param help_icon $helpicon A help icon instance
2543 * @return string HTML fragment
2545 protected function render_help_icon(help_icon $helpicon) {
2546 $context = $helpicon->export_for_template($this);
2547 return $this->render_from_template('core/help_icon', $context);
2551 * Returns HTML to display a scale help icon.
2553 * @param int $courseid
2554 * @param stdClass $scale instance
2555 * @return string HTML fragment
2557 public function help_icon_scale($courseid, stdClass $scale) {
2558 global $CFG;
2560 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2562 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2564 $scaleid = abs($scale->id);
2566 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2567 $action = new popup_action('click', $link, 'ratingscale');
2569 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2573 * Creates and returns a spacer image with optional line break.
2575 * @param array $attributes Any HTML attributes to add to the spaced.
2576 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2577 * laxy do it with CSS which is a much better solution.
2578 * @return string HTML fragment
2580 public function spacer(array $attributes = null, $br = false) {
2581 $attributes = (array)$attributes;
2582 if (empty($attributes['width'])) {
2583 $attributes['width'] = 1;
2585 if (empty($attributes['height'])) {
2586 $attributes['height'] = 1;
2588 $attributes['class'] = 'spacer';
2590 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2592 if (!empty($br)) {
2593 $output .= '<br />';
2596 return $output;
2600 * Returns HTML to display the specified user's avatar.
2602 * User avatar may be obtained in two ways:
2603 * <pre>
2604 * // Option 1: (shortcut for simple cases, preferred way)
2605 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2606 * $OUTPUT->user_picture($user, array('popup'=>true));
2608 * // Option 2:
2609 * $userpic = new user_picture($user);
2610 * // Set properties of $userpic
2611 * $userpic->popup = true;
2612 * $OUTPUT->render($userpic);
2613 * </pre>
2615 * Theme developers: DO NOT OVERRIDE! Please override function
2616 * {@link core_renderer::render_user_picture()} instead.
2618 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2619 * If any of these are missing, the database is queried. Avoid this
2620 * if at all possible, particularly for reports. It is very bad for performance.
2621 * @param array $options associative array with user picture options, used only if not a user_picture object,
2622 * options are:
2623 * - courseid=$this->page->course->id (course id of user profile in link)
2624 * - size=35 (size of image)
2625 * - link=true (make image clickable - the link leads to user profile)
2626 * - popup=false (open in popup)
2627 * - alttext=true (add image alt attribute)
2628 * - class = image class attribute (default 'userpicture')
2629 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2630 * - includefullname=false (whether to include the user's full name together with the user picture)
2631 * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2632 * @return string HTML fragment
2634 public function user_picture(stdClass $user, array $options = null) {
2635 $userpicture = new user_picture($user);
2636 foreach ((array)$options as $key=>$value) {
2637 if (property_exists($userpicture, $key)) {
2638 $userpicture->$key = $value;
2641 return $this->render($userpicture);
2645 * Internal implementation of user image rendering.
2647 * @param user_picture $userpicture
2648 * @return string
2650 protected function render_user_picture(user_picture $userpicture) {
2651 global $CFG;
2653 $user = $userpicture->user;
2654 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
2656 $alt = '';
2657 if ($userpicture->alttext) {
2658 if (!empty($user->imagealt)) {
2659 $alt = $user->imagealt;
2663 if (empty($userpicture->size)) {
2664 $size = 35;
2665 } else if ($userpicture->size === true or $userpicture->size == 1) {
2666 $size = 100;
2667 } else {
2668 $size = $userpicture->size;
2671 $class = $userpicture->class;
2673 if ($user->picture == 0) {
2674 $class .= ' defaultuserpic';
2677 $src = $userpicture->get_url($this->page, $this);
2679 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2680 if (!$userpicture->visibletoscreenreaders) {
2681 $alt = '';
2683 $attributes['alt'] = $alt;
2685 if (!empty($alt)) {
2686 $attributes['title'] = $alt;
2689 // Get the image html output first, auto generated based on initials if one isn't already set.
2690 if ($user->picture == 0 && empty($CFG->enablegravatar) && !defined('BEHAT_SITE_RUNNING')) {
2691 $output = html_writer::tag('span', mb_substr($user->firstname, 0, 1) . mb_substr($user->lastname, 0, 1),
2692 ['class' => 'userinitials size-' . $size]);
2693 } else {
2694 $output = html_writer::empty_tag('img', $attributes);
2697 // Show fullname together with the picture when desired.
2698 if ($userpicture->includefullname) {
2699 $output .= fullname($userpicture->user, $canviewfullnames);
2702 if (empty($userpicture->courseid)) {
2703 $courseid = $this->page->course->id;
2704 } else {
2705 $courseid = $userpicture->courseid;
2707 if ($courseid == SITEID) {
2708 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2709 } else {
2710 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2713 // Then wrap it in link if needed. Also we don't wrap it in link if the link redirects to itself.
2714 if (!$userpicture->link ||
2715 ($this->page->has_set_url() && $this->page->url == $url)) { // Protect against unset page->url.
2716 return $output;
2719 $attributes = array('href' => $url, 'class' => 'd-inline-block aabtn');
2720 if (!$userpicture->visibletoscreenreaders) {
2721 $attributes['tabindex'] = '-1';
2722 $attributes['aria-hidden'] = 'true';
2725 if ($userpicture->popup) {
2726 $id = html_writer::random_id('userpicture');
2727 $attributes['id'] = $id;
2728 $this->add_action_handler(new popup_action('click', $url), $id);
2731 return html_writer::tag('a', $output, $attributes);
2735 * Internal implementation of file tree viewer items rendering.
2737 * @param array $dir
2738 * @return string
2740 public function htmllize_file_tree($dir) {
2741 if (empty($dir['subdirs']) and empty($dir['files'])) {
2742 return '';
2744 $result = '<ul>';
2745 foreach ($dir['subdirs'] as $subdir) {
2746 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2748 foreach ($dir['files'] as $file) {
2749 $filename = $file->get_filename();
2750 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2752 $result .= '</ul>';
2754 return $result;
2758 * Returns HTML to display the file picker
2760 * <pre>
2761 * $OUTPUT->file_picker($options);
2762 * </pre>
2764 * Theme developers: DO NOT OVERRIDE! Please override function
2765 * {@link core_renderer::render_file_picker()} instead.
2767 * @param stdClass $options file manager options
2768 * options are:
2769 * maxbytes=>-1,
2770 * itemid=>0,
2771 * client_id=>uniqid(),
2772 * acepted_types=>'*',
2773 * return_types=>FILE_INTERNAL,
2774 * context=>current page context
2775 * @return string HTML fragment
2777 public function file_picker($options) {
2778 $fp = new file_picker($options);
2779 return $this->render($fp);
2783 * Internal implementation of file picker rendering.
2785 * @param file_picker $fp
2786 * @return string
2788 public function render_file_picker(file_picker $fp) {
2789 $options = $fp->options;
2790 $client_id = $options->client_id;
2791 $strsaved = get_string('filesaved', 'repository');
2792 $straddfile = get_string('openpicker', 'repository');
2793 $strloading = get_string('loading', 'repository');
2794 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2795 $strdroptoupload = get_string('droptoupload', 'moodle');
2796 $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
2798 $currentfile = $options->currentfile;
2799 if (empty($currentfile)) {
2800 $currentfile = '';
2801 } else {
2802 $currentfile .= ' - ';
2804 if ($options->maxbytes) {
2805 $size = $options->maxbytes;
2806 } else {
2807 $size = get_max_upload_file_size();
2809 if ($size == -1) {
2810 $maxsize = '';
2811 } else {
2812 $maxsize = get_string('maxfilesize', 'moodle', display_size($size, 0));
2814 if ($options->buttonname) {
2815 $buttonname = ' name="' . $options->buttonname . '"';
2816 } else {
2817 $buttonname = '';
2819 $html = <<<EOD
2820 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2821 $iconprogress
2822 </div>
2823 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2824 <div>
2825 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2826 <span> $maxsize </span>
2827 </div>
2828 EOD;
2829 if ($options->env != 'url') {
2830 $html .= <<<EOD
2831 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2832 <div class="filepicker-filename">
2833 <div class="filepicker-container">$currentfile
2834 <div class="dndupload-message">$strdndenabled <br/>
2835 <div class="dndupload-arrow d-flex"><i class="fa fa-arrow-circle-o-down fa-3x m-auto"></i></div>
2836 </div>
2837 </div>
2838 <div class="dndupload-progressbars"></div>
2839 </div>
2840 <div>
2841 <div class="dndupload-target">{$strdroptoupload}<br/>
2842 <div class="dndupload-arrow d-flex"><i class="fa fa-arrow-circle-o-down fa-3x m-auto"></i></div>
2843 </div>
2844 </div>
2845 </div>
2846 EOD;
2848 $html .= '</div>';
2849 return $html;
2853 * @deprecated since Moodle 3.2
2855 public function update_module_button() {
2856 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2857 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2858 'Themes can choose to display the link in the buttons row consistently for all module types.');
2862 * Returns HTML to display a "Turn editing on/off" button in a form.
2864 * @param moodle_url $url The URL + params to send through when clicking the button
2865 * @param string $method
2866 * @return string HTML the button
2868 public function edit_button(moodle_url $url, string $method = 'post') {
2870 if ($this->page->theme->haseditswitch == true) {
2871 return;
2873 $url->param('sesskey', sesskey());
2874 if ($this->page->user_is_editing()) {
2875 $url->param('edit', 'off');
2876 $editstring = get_string('turneditingoff');
2877 } else {
2878 $url->param('edit', 'on');
2879 $editstring = get_string('turneditingon');
2882 return $this->single_button($url, $editstring, $method);
2886 * Create a navbar switch for toggling editing mode.
2888 * @return string Html containing the edit switch
2890 public function edit_switch() {
2891 if ($this->page->user_allowed_editing()) {
2893 $temp = (object) [
2894 'legacyseturl' => (new moodle_url('/editmode.php'))->out(false),
2895 'pagecontextid' => $this->page->context->id,
2896 'pageurl' => $this->page->url,
2897 'sesskey' => sesskey(),
2899 if ($this->page->user_is_editing()) {
2900 $temp->checked = true;
2902 return $this->render_from_template('core/editswitch', $temp);
2907 * Returns HTML to display a simple button to close a window
2909 * @param string $text The lang string for the button's label (already output from get_string())
2910 * @return string html fragment
2912 public function close_window_button($text='') {
2913 if (empty($text)) {
2914 $text = get_string('closewindow');
2916 $button = new single_button(new moodle_url('#'), $text, 'get');
2917 $button->add_action(new component_action('click', 'close_window'));
2919 return $this->container($this->render($button), 'closewindow');
2923 * Output an error message. By default wraps the error message in <span class="error">.
2924 * If the error message is blank, nothing is output.
2926 * @param string $message the error message.
2927 * @return string the HTML to output.
2929 public function error_text($message) {
2930 if (empty($message)) {
2931 return '';
2933 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2934 return html_writer::tag('span', $message, array('class' => 'error'));
2938 * Do not call this function directly.
2940 * To terminate the current script with a fatal error, throw an exception.
2941 * Doing this will then call this function to display the error, before terminating the execution.
2943 * @param string $message The message to output
2944 * @param string $moreinfourl URL where more info can be found about the error
2945 * @param string $link Link for the Continue button
2946 * @param array $backtrace The execution backtrace
2947 * @param string $debuginfo Debugging information
2948 * @return string the HTML to output.
2950 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2951 global $CFG;
2953 $output = '';
2954 $obbuffer = '';
2956 if ($this->has_started()) {
2957 // we can not always recover properly here, we have problems with output buffering,
2958 // html tables, etc.
2959 $output .= $this->opencontainers->pop_all_but_last();
2961 } else {
2962 // It is really bad if library code throws exception when output buffering is on,
2963 // because the buffered text would be printed before our start of page.
2964 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2965 error_reporting(0); // disable notices from gzip compression, etc.
2966 while (ob_get_level() > 0) {
2967 $buff = ob_get_clean();
2968 if ($buff === false) {
2969 break;
2971 $obbuffer .= $buff;
2973 error_reporting($CFG->debug);
2975 // Output not yet started.
2976 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2977 if (empty($_SERVER['HTTP_RANGE'])) {
2978 @header($protocol . ' 404 Not Found');
2979 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2980 // Coax iOS 10 into sending the session cookie.
2981 @header($protocol . ' 403 Forbidden');
2982 } else {
2983 // Must stop byteserving attempts somehow,
2984 // this is weird but Chrome PDF viewer can be stopped only with 407!
2985 @header($protocol . ' 407 Proxy Authentication Required');
2988 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2989 $this->page->set_url('/'); // no url
2990 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2991 $this->page->set_title(get_string('error'));
2992 $this->page->set_heading($this->page->course->fullname);
2993 // No need to display the activity header when encountering an error.
2994 $this->page->activityheader->disable();
2995 $output .= $this->header();
2998 $message = '<p class="errormessage">' . s($message) . '</p>'.
2999 '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
3000 get_string('moreinformation') . '</a></p>';
3001 if (empty($CFG->rolesactive)) {
3002 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
3003 //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.
3005 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
3007 if ($CFG->debugdeveloper) {
3008 $labelsep = get_string('labelsep', 'langconfig');
3009 if (!empty($debuginfo)) {
3010 $debuginfo = s($debuginfo); // removes all nasty JS
3011 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
3012 $label = get_string('debuginfo', 'debug') . $labelsep;
3013 $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
3015 if (!empty($backtrace)) {
3016 $label = get_string('stacktrace', 'debug') . $labelsep;
3017 $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
3019 if ($obbuffer !== '' ) {
3020 $label = get_string('outputbuffer', 'debug') . $labelsep;
3021 $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
3025 if (empty($CFG->rolesactive)) {
3026 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
3027 } else if (!empty($link)) {
3028 $output .= $this->continue_button($link);
3031 $output .= $this->footer();
3033 // Padding to encourage IE to display our error page, rather than its own.
3034 $output .= str_repeat(' ', 512);
3036 return $output;
3040 * Output a notification (that is, a status message about something that has just happened).
3042 * Note: \core\notification::add() may be more suitable for your usage.
3044 * @param string $message The message to print out.
3045 * @param ?string $type The type of notification. See constants on \core\output\notification.
3046 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
3047 * @return string the HTML to output.
3049 public function notification($message, $type = null, $closebutton = true) {
3050 $typemappings = [
3051 // Valid types.
3052 'success' => \core\output\notification::NOTIFY_SUCCESS,
3053 'info' => \core\output\notification::NOTIFY_INFO,
3054 'warning' => \core\output\notification::NOTIFY_WARNING,
3055 'error' => \core\output\notification::NOTIFY_ERROR,
3057 // Legacy types mapped to current types.
3058 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
3059 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
3060 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
3061 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
3062 'notifymessage' => \core\output\notification::NOTIFY_INFO,
3063 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
3064 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
3067 $extraclasses = [];
3069 if ($type) {
3070 if (strpos($type, ' ') === false) {
3071 // No spaces in the list of classes, therefore no need to loop over and determine the class.
3072 if (isset($typemappings[$type])) {
3073 $type = $typemappings[$type];
3074 } else {
3075 // The value provided did not match a known type. It must be an extra class.
3076 $extraclasses = [$type];
3078 } else {
3079 // Identify what type of notification this is.
3080 $classarray = explode(' ', self::prepare_classes($type));
3082 // Separate out the type of notification from the extra classes.
3083 foreach ($classarray as $class) {
3084 if (isset($typemappings[$class])) {
3085 $type = $typemappings[$class];
3086 } else {
3087 $extraclasses[] = $class;
3093 $notification = new \core\output\notification($message, $type, $closebutton);
3094 if (count($extraclasses)) {
3095 $notification->set_extra_classes($extraclasses);
3098 // Return the rendered template.
3099 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3103 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3105 public function notify_problem() {
3106 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
3107 'please use \core\notification::add(), or \core\output\notification as required.');
3111 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3113 public function notify_success() {
3114 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
3115 'please use \core\notification::add(), or \core\output\notification as required.');
3119 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3121 public function notify_message() {
3122 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
3123 'please use \core\notification::add(), or \core\output\notification as required.');
3127 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3129 public function notify_redirect() {
3130 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
3131 'please use \core\notification::add(), or \core\output\notification as required.');
3135 * Render a notification (that is, a status message about something that has
3136 * just happened).
3138 * @param \core\output\notification $notification the notification to print out
3139 * @return string the HTML to output.
3141 protected function render_notification(\core\output\notification $notification) {
3142 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3146 * Returns HTML to display a continue button that goes to a particular URL.
3148 * @param string|moodle_url $url The url the button goes to.
3149 * @return string the HTML to output.
3151 public function continue_button($url) {
3152 if (!($url instanceof moodle_url)) {
3153 $url = new moodle_url($url);
3155 $button = new single_button($url, get_string('continue'), 'get', single_button::BUTTON_PRIMARY);
3156 $button->class = 'continuebutton';
3158 return $this->render($button);
3162 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
3164 * Theme developers: DO NOT OVERRIDE! Please override function
3165 * {@link core_renderer::render_paging_bar()} instead.
3167 * @param int $totalcount The total number of entries available to be paged through
3168 * @param int $page The page you are currently viewing
3169 * @param int $perpage The number of entries that should be shown per page
3170 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3171 * @param string $pagevar name of page parameter that holds the page number
3172 * @return string the HTML to output.
3174 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3175 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3176 return $this->render($pb);
3180 * Returns HTML to display the paging bar.
3182 * @param paging_bar $pagingbar
3183 * @return string the HTML to output.
3185 protected function render_paging_bar(paging_bar $pagingbar) {
3186 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3187 $pagingbar->maxdisplay = 10;
3188 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3192 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3194 * @param string $current the currently selected letter.
3195 * @param string $class class name to add to this initial bar.
3196 * @param string $title the name to put in front of this initial bar.
3197 * @param string $urlvar URL parameter name for this initial.
3198 * @param string $url URL object.
3199 * @param array $alpha of letters in the alphabet.
3200 * @param bool $minirender Return a trimmed down view of the initials bar.
3201 * @return string the HTML to output.
3203 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null, bool $minirender = false) {
3204 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha, $minirender);
3205 return $this->render($ib);
3209 * Internal implementation of initials bar rendering.
3211 * @param initials_bar $initialsbar
3212 * @return string
3214 protected function render_initials_bar(initials_bar $initialsbar) {
3215 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3219 * Output the place a skip link goes to.
3221 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3222 * @return string the HTML to output.
3224 public function skip_link_target($id = null) {
3225 return html_writer::span('', '', array('id' => $id));
3229 * Outputs a heading
3231 * @param string $text The text of the heading
3232 * @param int $level The level of importance of the heading. Defaulting to 2
3233 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3234 * @param string $id An optional ID
3235 * @return string the HTML to output.
3237 public function heading($text, $level = 2, $classes = null, $id = null) {
3238 $level = (integer) $level;
3239 if ($level < 1 or $level > 6) {
3240 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3242 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3246 * Outputs a box.
3248 * @param string $contents The contents of the box
3249 * @param string $classes A space-separated list of CSS classes
3250 * @param string $id An optional ID
3251 * @param array $attributes An array of other attributes to give the box.
3252 * @return string the HTML to output.
3254 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3255 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3259 * Outputs the opening section of a box.
3261 * @param string $classes A space-separated list of CSS classes
3262 * @param string $id An optional ID
3263 * @param array $attributes An array of other attributes to give the box.
3264 * @return string the HTML to output.
3266 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3267 $this->opencontainers->push('box', html_writer::end_tag('div'));
3268 $attributes['id'] = $id;
3269 $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes);
3270 return html_writer::start_tag('div', $attributes);
3274 * Outputs the closing section of a box.
3276 * @return string the HTML to output.
3278 public function box_end() {
3279 return $this->opencontainers->pop('box');
3283 * Outputs a container.
3285 * @param string $contents The contents of the box
3286 * @param string $classes A space-separated list of CSS classes
3287 * @param string $id An optional ID
3288 * @return string the HTML to output.
3290 public function container($contents, $classes = null, $id = null) {
3291 return $this->container_start($classes, $id) . $contents . $this->container_end();
3295 * Outputs the opening section of a container.
3297 * @param string $classes A space-separated list of CSS classes
3298 * @param string $id An optional ID
3299 * @return string the HTML to output.
3301 public function container_start($classes = null, $id = null) {
3302 $this->opencontainers->push('container', html_writer::end_tag('div'));
3303 return html_writer::start_tag('div', array('id' => $id,
3304 'class' => renderer_base::prepare_classes($classes)));
3308 * Outputs the closing section of a container.
3310 * @return string the HTML to output.
3312 public function container_end() {
3313 return $this->opencontainers->pop('container');
3317 * Make nested HTML lists out of the items
3319 * The resulting list will look something like this:
3321 * <pre>
3322 * <<ul>>
3323 * <<li>><div class='tree_item parent'>(item contents)</div>
3324 * <<ul>
3325 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3326 * <</ul>>
3327 * <</li>>
3328 * <</ul>>
3329 * </pre>
3331 * @param array $items
3332 * @param array $attrs html attributes passed to the top ofs the list
3333 * @return string HTML
3335 public function tree_block_contents($items, $attrs = array()) {
3336 // exit if empty, we don't want an empty ul element
3337 if (empty($items)) {
3338 return '';
3340 // array of nested li elements
3341 $lis = array();
3342 foreach ($items as $item) {
3343 // this applies to the li item which contains all child lists too
3344 $content = $item->content($this);
3345 $liclasses = array($item->get_css_type());
3346 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3347 $liclasses[] = 'collapsed';
3349 if ($item->isactive === true) {
3350 $liclasses[] = 'current_branch';
3352 $liattr = array('class'=>join(' ',$liclasses));
3353 // class attribute on the div item which only contains the item content
3354 $divclasses = array('tree_item');
3355 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3356 $divclasses[] = 'branch';
3357 } else {
3358 $divclasses[] = 'leaf';
3360 if (!empty($item->classes) && count($item->classes)>0) {
3361 $divclasses[] = join(' ', $item->classes);
3363 $divattr = array('class'=>join(' ', $divclasses));
3364 if (!empty($item->id)) {
3365 $divattr['id'] = $item->id;
3367 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3368 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3369 $content = html_writer::empty_tag('hr') . $content;
3371 $content = html_writer::tag('li', $content, $liattr);
3372 $lis[] = $content;
3374 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3378 * Returns a search box.
3380 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3381 * @return string HTML with the search form hidden by default.
3383 public function search_box($id = false) {
3384 global $CFG;
3386 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3387 // result in an extra included file for each site, even the ones where global search
3388 // is disabled.
3389 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3390 return '';
3393 $data = [
3394 'action' => new moodle_url('/search/index.php'),
3395 'hiddenfields' => (object) ['name' => 'context', 'value' => $this->page->context->id],
3396 'inputname' => 'q',
3397 'searchstring' => get_string('search'),
3399 return $this->render_from_template('core/search_input_navbar', $data);
3403 * Allow plugins to provide some content to be rendered in the navbar.
3404 * The plugin must define a PLUGIN_render_navbar_output function that returns
3405 * the HTML they wish to add to the navbar.
3407 * @return string HTML for the navbar
3409 public function navbar_plugin_output() {
3410 $output = '';
3412 // Give subsystems an opportunity to inject extra html content. The callback
3413 // must always return a string containing valid html.
3414 foreach (\core_component::get_core_subsystems() as $name => $path) {
3415 if ($path) {
3416 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3420 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3421 foreach ($pluginsfunction as $plugintype => $plugins) {
3422 foreach ($plugins as $pluginfunction) {
3423 $output .= $pluginfunction($this);
3428 return $output;
3432 * Construct a user menu, returning HTML that can be echoed out by a
3433 * layout file.
3435 * @param stdClass $user A user object, usually $USER.
3436 * @param bool $withlinks true if a dropdown should be built.
3437 * @return string HTML fragment.
3439 public function user_menu($user = null, $withlinks = null) {
3440 global $USER, $CFG;
3441 require_once($CFG->dirroot . '/user/lib.php');
3443 if (is_null($user)) {
3444 $user = $USER;
3447 // Note: this behaviour is intended to match that of core_renderer::login_info,
3448 // but should not be considered to be good practice; layout options are
3449 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3450 if (is_null($withlinks)) {
3451 $withlinks = empty($this->page->layout_options['nologinlinks']);
3454 // Add a class for when $withlinks is false.
3455 $usermenuclasses = 'usermenu';
3456 if (!$withlinks) {
3457 $usermenuclasses .= ' withoutlinks';
3460 $returnstr = "";
3462 // If during initial install, return the empty return string.
3463 if (during_initial_install()) {
3464 return $returnstr;
3467 $loginpage = $this->is_login_page();
3468 $loginurl = get_login_url();
3470 // Get some navigation opts.
3471 $opts = user_get_user_navigation_info($user, $this->page);
3473 if (!empty($opts->unauthenticateduser)) {
3474 $returnstr = get_string($opts->unauthenticateduser['content'], 'moodle');
3475 // If not logged in, show the typical not-logged-in string.
3476 if (!$loginpage && (!$opts->unauthenticateduser['guest'] || $withlinks)) {
3477 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3480 return html_writer::div(
3481 html_writer::span(
3482 $returnstr,
3483 'login nav-link'
3485 $usermenuclasses
3489 $avatarclasses = "avatars";
3490 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3491 $usertextcontents = $opts->metadata['userfullname'];
3493 // Other user.
3494 if (!empty($opts->metadata['asotheruser'])) {
3495 $avatarcontents .= html_writer::span(
3496 $opts->metadata['realuseravatar'],
3497 'avatar realuser'
3499 $usertextcontents = $opts->metadata['realuserfullname'];
3500 $usertextcontents .= html_writer::tag(
3501 'span',
3502 get_string(
3503 'loggedinas',
3504 'moodle',
3505 html_writer::span(
3506 $opts->metadata['userfullname'],
3507 'value'
3510 array('class' => 'meta viewingas')
3514 // Role.
3515 if (!empty($opts->metadata['asotherrole'])) {
3516 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3517 $usertextcontents .= html_writer::span(
3518 $opts->metadata['rolename'],
3519 'meta role role-' . $role
3523 // User login failures.
3524 if (!empty($opts->metadata['userloginfail'])) {
3525 $usertextcontents .= html_writer::span(
3526 $opts->metadata['userloginfail'],
3527 'meta loginfailures'
3531 // MNet.
3532 if (!empty($opts->metadata['asmnetuser'])) {
3533 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3534 $usertextcontents .= html_writer::span(
3535 $opts->metadata['mnetidprovidername'],
3536 'meta mnet mnet-' . $mnet
3540 $returnstr .= html_writer::span(
3541 html_writer::span($usertextcontents, 'usertext mr-1') .
3542 html_writer::span($avatarcontents, $avatarclasses),
3543 'userbutton'
3546 // Create a divider (well, a filler).
3547 $divider = new action_menu_filler();
3548 $divider->primary = false;
3550 $am = new action_menu();
3551 $am->set_menu_trigger(
3552 $returnstr,
3553 'nav-link'
3555 $am->set_action_label(get_string('usermenu'));
3556 $am->set_nowrap_on_items();
3557 if ($withlinks) {
3558 $navitemcount = count($opts->navitems);
3559 $idx = 0;
3560 foreach ($opts->navitems as $key => $value) {
3562 switch ($value->itemtype) {
3563 case 'divider':
3564 // If the nav item is a divider, add one and skip link processing.
3565 $am->add($divider);
3566 break;
3568 case 'invalid':
3569 // Silently skip invalid entries (should we post a notification?).
3570 break;
3572 case 'link':
3573 // Process this as a link item.
3574 $pix = null;
3575 if (isset($value->pix) && !empty($value->pix)) {
3576 $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
3577 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3578 $value->title = html_writer::img(
3579 $value->imgsrc,
3580 $value->title,
3581 array('class' => 'iconsmall')
3582 ) . $value->title;
3585 $al = new action_menu_link_secondary(
3586 $value->url,
3587 $pix,
3588 $value->title,
3589 array('class' => 'icon')
3591 if (!empty($value->titleidentifier)) {
3592 $al->attributes['data-title'] = $value->titleidentifier;
3594 $am->add($al);
3595 break;
3598 $idx++;
3600 // Add dividers after the first item and before the last item.
3601 if ($idx == 1 || $idx == $navitemcount - 1) {
3602 $am->add($divider);
3607 return html_writer::div(
3608 $this->render($am),
3609 $usermenuclasses
3614 * Secure layout login info.
3616 * @return string
3618 public function secure_layout_login_info() {
3619 if (get_config('core', 'logininfoinsecurelayout')) {
3620 return $this->login_info(false);
3621 } else {
3622 return '';
3627 * Returns the language menu in the secure layout.
3629 * No custom menu items are passed though, such that it will render only the language selection.
3631 * @return string
3633 public function secure_layout_language_menu() {
3634 if (get_config('core', 'langmenuinsecurelayout')) {
3635 $custommenu = new custom_menu('', current_language());
3636 return $this->render_custom_menu($custommenu);
3637 } else {
3638 return '';
3643 * This renders the navbar.
3644 * Uses bootstrap compatible html.
3646 public function navbar() {
3647 return $this->render_from_template('core/navbar', $this->page->navbar);
3651 * Renders a breadcrumb navigation node object.
3653 * @param breadcrumb_navigation_node $item The navigation node to render.
3654 * @return string HTML fragment
3656 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3658 if ($item->action instanceof moodle_url) {
3659 $content = $item->get_content();
3660 $title = $item->get_title();
3661 $attributes = array();
3662 $attributes['itemprop'] = 'url';
3663 if ($title !== '') {
3664 $attributes['title'] = $title;
3666 if ($item->hidden) {
3667 $attributes['class'] = 'dimmed_text';
3669 if ($item->is_last()) {
3670 $attributes['aria-current'] = 'page';
3672 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3673 $content = html_writer::link($item->action, $content, $attributes);
3675 $attributes = array();
3676 $attributes['itemscope'] = '';
3677 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3678 $content = html_writer::tag('span', $content, $attributes);
3680 } else {
3681 $content = $this->render_navigation_node($item);
3683 return $content;
3687 * Renders a navigation node object.
3689 * @param navigation_node $item The navigation node to render.
3690 * @return string HTML fragment
3692 protected function render_navigation_node(navigation_node $item) {
3693 $content = $item->get_content();
3694 $title = $item->get_title();
3695 if ($item->icon instanceof renderable && !$item->hideicon) {
3696 $icon = $this->render($item->icon);
3697 $content = $icon.$content; // use CSS for spacing of icons
3699 if ($item->helpbutton !== null) {
3700 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3702 if ($content === '') {
3703 return '';
3705 if ($item->action instanceof action_link) {
3706 $link = $item->action;
3707 if ($item->hidden) {
3708 $link->add_class('dimmed');
3710 if (!empty($content)) {
3711 // Providing there is content we will use that for the link content.
3712 $link->text = $content;
3714 $content = $this->render($link);
3715 } else if ($item->action instanceof moodle_url) {
3716 $attributes = array();
3717 if ($title !== '') {
3718 $attributes['title'] = $title;
3720 if ($item->hidden) {
3721 $attributes['class'] = 'dimmed_text';
3723 $content = html_writer::link($item->action, $content, $attributes);
3725 } else if (is_string($item->action) || empty($item->action)) {
3726 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3727 if ($title !== '') {
3728 $attributes['title'] = $title;
3730 if ($item->hidden) {
3731 $attributes['class'] = 'dimmed_text';
3733 $content = html_writer::tag('span', $content, $attributes);
3735 return $content;
3739 * Accessibility: Right arrow-like character is
3740 * used in the breadcrumb trail, course navigation menu
3741 * (previous/next activity), calendar, and search forum block.
3742 * If the theme does not set characters, appropriate defaults
3743 * are set automatically. Please DO NOT
3744 * use &lt; &gt; &raquo; - these are confusing for blind users.
3746 * @return string
3748 public function rarrow() {
3749 return $this->page->theme->rarrow;
3753 * Accessibility: Left arrow-like character is
3754 * used in the breadcrumb trail, course navigation menu
3755 * (previous/next activity), calendar, and search forum block.
3756 * If the theme does not set characters, appropriate defaults
3757 * are set automatically. Please DO NOT
3758 * use &lt; &gt; &raquo; - these are confusing for blind users.
3760 * @return string
3762 public function larrow() {
3763 return $this->page->theme->larrow;
3767 * Accessibility: Up arrow-like character is used in
3768 * the book heirarchical navigation.
3769 * If the theme does not set characters, appropriate defaults
3770 * are set automatically. Please DO NOT
3771 * use ^ - this is confusing for blind users.
3773 * @return string
3775 public function uarrow() {
3776 return $this->page->theme->uarrow;
3780 * Accessibility: Down arrow-like character.
3781 * If the theme does not set characters, appropriate defaults
3782 * are set automatically.
3784 * @return string
3786 public function darrow() {
3787 return $this->page->theme->darrow;
3791 * Returns the custom menu if one has been set
3793 * A custom menu can be configured by browsing to
3794 * Settings: Administration > Appearance > Themes > Theme settings
3795 * and then configuring the custommenu config setting as described.
3797 * Theme developers: DO NOT OVERRIDE! Please override function
3798 * {@link core_renderer::render_custom_menu()} instead.
3800 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3801 * @return string
3803 public function custom_menu($custommenuitems = '') {
3804 global $CFG;
3806 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3807 $custommenuitems = $CFG->custommenuitems;
3809 $custommenu = new custom_menu($custommenuitems, current_language());
3810 return $this->render_custom_menu($custommenu);
3814 * We want to show the custom menus as a list of links in the footer on small screens.
3815 * Just return the menu object exported so we can render it differently.
3817 public function custom_menu_flat() {
3818 global $CFG;
3819 $custommenuitems = '';
3821 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3822 $custommenuitems = $CFG->custommenuitems;
3824 $custommenu = new custom_menu($custommenuitems, current_language());
3825 $langs = get_string_manager()->get_list_of_translations();
3826 $haslangmenu = $this->lang_menu() != '';
3828 if ($haslangmenu) {
3829 $strlang = get_string('language');
3830 $currentlang = current_language();
3831 if (isset($langs[$currentlang])) {
3832 $currentlang = $langs[$currentlang];
3833 } else {
3834 $currentlang = $strlang;
3836 $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3837 foreach ($langs as $langtype => $langname) {
3838 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3842 return $custommenu->export_for_template($this);
3846 * Renders a custom menu object (located in outputcomponents.php)
3848 * The custom menu this method produces makes use of the YUI3 menunav widget
3849 * and requires very specific html elements and classes.
3851 * @staticvar int $menucount
3852 * @param custom_menu $menu
3853 * @return string
3855 protected function render_custom_menu(custom_menu $menu) {
3856 global $CFG;
3858 $langs = get_string_manager()->get_list_of_translations();
3859 $haslangmenu = $this->lang_menu() != '';
3861 if (!$menu->has_children() && !$haslangmenu) {
3862 return '';
3865 if ($haslangmenu) {
3866 $strlang = get_string('language');
3867 $currentlang = current_language();
3868 if (isset($langs[$currentlang])) {
3869 $currentlangstr = $langs[$currentlang];
3870 } else {
3871 $currentlangstr = $strlang;
3873 $this->language = $menu->add($currentlangstr, new moodle_url('#'), $strlang, 10000);
3874 foreach ($langs as $langtype => $langname) {
3875 $attributes = [];
3876 // Set the lang attribute for languages different from the page's current language.
3877 if ($langtype !== $currentlang) {
3878 $attributes[] = [
3879 'key' => 'lang',
3880 'value' => get_html_lang_attribute_value($langtype),
3883 $this->language->add($langname, new moodle_url($this->page->url, ['lang' => $langtype]), null, null, $attributes);
3887 $content = '';
3888 foreach ($menu->get_children() as $item) {
3889 $context = $item->export_for_template($this);
3890 $content .= $this->render_from_template('core/custom_menu_item', $context);
3893 return $content;
3897 * Renders a custom menu node as part of a submenu
3899 * The custom menu this method produces makes use of the YUI3 menunav widget
3900 * and requires very specific html elements and classes.
3902 * @see core:renderer::render_custom_menu()
3904 * @staticvar int $submenucount
3905 * @param custom_menu_item $menunode
3906 * @return string
3908 protected function render_custom_menu_item(custom_menu_item $menunode) {
3909 // Required to ensure we get unique trackable id's
3910 static $submenucount = 0;
3911 if ($menunode->has_children()) {
3912 // If the child has menus render it as a sub menu
3913 $submenucount++;
3914 $content = html_writer::start_tag('li');
3915 if ($menunode->get_url() !== null) {
3916 $url = $menunode->get_url();
3917 } else {
3918 $url = '#cm_submenu_'.$submenucount;
3920 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3921 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3922 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3923 $content .= html_writer::start_tag('ul');
3924 foreach ($menunode->get_children() as $menunode) {
3925 $content .= $this->render_custom_menu_item($menunode);
3927 $content .= html_writer::end_tag('ul');
3928 $content .= html_writer::end_tag('div');
3929 $content .= html_writer::end_tag('div');
3930 $content .= html_writer::end_tag('li');
3931 } else {
3932 // The node doesn't have children so produce a final menuitem.
3933 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3934 $content = '';
3935 if (preg_match("/^#+$/", $menunode->get_text())) {
3937 // This is a divider.
3938 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3939 } else {
3940 $content = html_writer::start_tag(
3941 'li',
3942 array(
3943 'class' => 'yui3-menuitem'
3946 if ($menunode->get_url() !== null) {
3947 $url = $menunode->get_url();
3948 } else {
3949 $url = '#';
3951 $content .= html_writer::link(
3952 $url,
3953 $menunode->get_text(),
3954 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3957 $content .= html_writer::end_tag('li');
3959 // Return the sub menu
3960 return $content;
3964 * Renders theme links for switching between default and other themes.
3966 * @return string
3968 protected function theme_switch_links() {
3970 $actualdevice = core_useragent::get_device_type();
3971 $currentdevice = $this->page->devicetypeinuse;
3972 $switched = ($actualdevice != $currentdevice);
3974 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3975 // The user is using the a default device and hasn't switched so don't shown the switch
3976 // device links.
3977 return '';
3980 if ($switched) {
3981 $linktext = get_string('switchdevicerecommended');
3982 $devicetype = $actualdevice;
3983 } else {
3984 $linktext = get_string('switchdevicedefault');
3985 $devicetype = 'default';
3987 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3989 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3990 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3991 $content .= html_writer::end_tag('div');
3993 return $content;
3997 * Renders tabs
3999 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
4001 * Theme developers: In order to change how tabs are displayed please override functions
4002 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
4004 * @param array $tabs array of tabs, each of them may have it's own ->subtree
4005 * @param string|null $selected which tab to mark as selected, all parent tabs will
4006 * automatically be marked as activated
4007 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
4008 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
4009 * @return string
4011 public final function tabtree($tabs, $selected = null, $inactive = null) {
4012 return $this->render(new tabtree($tabs, $selected, $inactive));
4016 * Renders tabtree
4018 * @param tabtree $tabtree
4019 * @return string
4021 protected function render_tabtree(tabtree $tabtree) {
4022 if (empty($tabtree->subtree)) {
4023 return '';
4025 $data = $tabtree->export_for_template($this);
4026 return $this->render_from_template('core/tabtree', $data);
4030 * Renders tabobject (part of tabtree)
4032 * This function is called from {@link core_renderer::render_tabtree()}
4033 * and also it calls itself when printing the $tabobject subtree recursively.
4035 * Property $tabobject->level indicates the number of row of tabs.
4037 * @param tabobject $tabobject
4038 * @return string HTML fragment
4040 protected function render_tabobject(tabobject $tabobject) {
4041 $str = '';
4043 // Print name of the current tab.
4044 if ($tabobject instanceof tabtree) {
4045 // No name for tabtree root.
4046 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
4047 // Tab name without a link. The <a> tag is used for styling.
4048 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
4049 } else {
4050 // Tab name with a link.
4051 if (!($tabobject->link instanceof moodle_url)) {
4052 // backward compartibility when link was passed as quoted string
4053 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
4054 } else {
4055 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
4059 if (empty($tabobject->subtree)) {
4060 if ($tabobject->selected) {
4061 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
4063 return $str;
4066 // Print subtree.
4067 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
4068 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
4069 $cnt = 0;
4070 foreach ($tabobject->subtree as $tab) {
4071 $liclass = '';
4072 if (!$cnt) {
4073 $liclass .= ' first';
4075 if ($cnt == count($tabobject->subtree) - 1) {
4076 $liclass .= ' last';
4078 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
4079 $liclass .= ' onerow';
4082 if ($tab->selected) {
4083 $liclass .= ' here selected';
4084 } else if ($tab->activated) {
4085 $liclass .= ' here active';
4088 // This will recursively call function render_tabobject() for each item in subtree.
4089 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
4090 $cnt++;
4092 $str .= html_writer::end_tag('ul');
4095 return $str;
4099 * Get the HTML for blocks in the given region.
4101 * @since Moodle 2.5.1 2.6
4102 * @param string $region The region to get HTML for.
4103 * @param array $classes Wrapping tag classes.
4104 * @param string $tag Wrapping tag.
4105 * @param boolean $fakeblocksonly Include fake blocks only.
4106 * @return string HTML.
4108 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
4109 $displayregion = $this->page->apply_theme_region_manipulations($region);
4110 $classes = (array)$classes;
4111 $classes[] = 'block-region';
4112 $attributes = array(
4113 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
4114 'class' => join(' ', $classes),
4115 'data-blockregion' => $displayregion,
4116 'data-droptarget' => '1'
4118 if ($this->page->blocks->region_has_content($displayregion, $this)) {
4119 $content = $this->blocks_for_region($displayregion, $fakeblocksonly);
4120 } else {
4121 $content = '';
4123 return html_writer::tag($tag, $content, $attributes);
4127 * Renders a custom block region.
4129 * Use this method if you want to add an additional block region to the content of the page.
4130 * Please note this should only be used in special situations.
4131 * We want to leave the theme is control where ever possible!
4133 * This method must use the same method that the theme uses within its layout file.
4134 * As such it asks the theme what method it is using.
4135 * It can be one of two values, blocks or blocks_for_region (deprecated).
4137 * @param string $regionname The name of the custom region to add.
4138 * @return string HTML for the block region.
4140 public function custom_block_region($regionname) {
4141 if ($this->page->theme->get_block_render_method() === 'blocks') {
4142 return $this->blocks($regionname);
4143 } else {
4144 return $this->blocks_for_region($regionname);
4149 * Returns the CSS classes to apply to the body tag.
4151 * @since Moodle 2.5.1 2.6
4152 * @param array $additionalclasses Any additional classes to apply.
4153 * @return string
4155 public function body_css_classes(array $additionalclasses = array()) {
4156 return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses);
4160 * The ID attribute to apply to the body tag.
4162 * @since Moodle 2.5.1 2.6
4163 * @return string
4165 public function body_id() {
4166 return $this->page->bodyid;
4170 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4172 * @since Moodle 2.5.1 2.6
4173 * @param string|array $additionalclasses Any additional classes to give the body tag,
4174 * @return string
4176 public function body_attributes($additionalclasses = array()) {
4177 if (!is_array($additionalclasses)) {
4178 $additionalclasses = explode(' ', $additionalclasses);
4180 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4184 * Gets HTML for the page heading.
4186 * @since Moodle 2.5.1 2.6
4187 * @param string $tag The tag to encase the heading in. h1 by default.
4188 * @return string HTML.
4190 public function page_heading($tag = 'h1') {
4191 return html_writer::tag($tag, $this->page->heading);
4195 * Gets the HTML for the page heading button.
4197 * @since Moodle 2.5.1 2.6
4198 * @return string HTML.
4200 public function page_heading_button() {
4201 return $this->page->button;
4205 * Returns the Moodle docs link to use for this page.
4207 * @since Moodle 2.5.1 2.6
4208 * @param string $text
4209 * @return string
4211 public function page_doc_link($text = null) {
4212 if ($text === null) {
4213 $text = get_string('moodledocslink');
4215 $path = page_get_doc_link_path($this->page);
4216 if (!$path) {
4217 return '';
4219 return $this->doc_link($path, $text);
4223 * Returns the HTML for the site support email link
4225 * @param array $customattribs Array of custom attributes for the support email anchor tag.
4226 * @return string The html code for the support email link.
4228 public function supportemail(array $customattribs = []): string {
4229 global $CFG;
4231 // Do not provide a link to contact site support if it is unavailable to this user. This would be where the site has
4232 // disabled support, or limited it to authenticated users and the current user is a guest or not logged in.
4233 if (!isset($CFG->supportavailability) ||
4234 $CFG->supportavailability == CONTACT_SUPPORT_DISABLED ||
4235 ($CFG->supportavailability == CONTACT_SUPPORT_AUTHENTICATED && (!isloggedin() || isguestuser()))) {
4236 return '';
4239 $label = get_string('contactsitesupport', 'admin');
4240 $icon = $this->pix_icon('t/email', '');
4241 $content = $icon . $label;
4243 if (!empty($CFG->supportpage)) {
4244 $attributes = ['href' => $CFG->supportpage, 'target' => 'blank'];
4245 $content .= $this->pix_icon('i/externallink', '', 'moodle', ['class' => 'ml-1']);
4246 } else {
4247 $attributes = ['href' => $CFG->wwwroot . '/user/contactsitesupport.php'];
4250 $attributes += $customattribs;
4252 return html_writer::tag('a', $content, $attributes);
4256 * Returns the services and support link for the help pop-up.
4258 * @return string
4260 public function services_support_link(): string {
4261 global $CFG;
4263 if (during_initial_install() ||
4264 (isset($CFG->showservicesandsupportcontent) && $CFG->showservicesandsupportcontent == false) ||
4265 !is_siteadmin()) {
4266 return '';
4269 $liferingicon = $this->pix_icon('t/life-ring', '', 'moodle', ['class' => 'fa fa-life-ring']);
4270 $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle', ['class' => 'ml-1']);
4271 $link = !empty($CFG->servicespage)
4272 ? $CFG->servicespage
4273 : 'https://moodle.com/help/?utm_source=CTA-banner&utm_medium=platform&utm_campaign=name~Moodle4+cat~lms+mp~no';
4274 $content = $liferingicon . get_string('moodleservicesandsupport') . $newwindowicon;
4276 return html_writer::tag('a', $content, ['target' => '_blank', 'href' => $link]);
4280 * Helper function to decide whether to show the help popover header or not.
4282 * @return bool
4284 public function has_popover_links(): bool {
4285 return !empty($this->services_support_link()) || !empty($this->page_doc_link()) || !empty($this->supportemail());
4289 * Returns the page heading menu.
4291 * @since Moodle 2.5.1 2.6
4292 * @return string HTML.
4294 public function page_heading_menu() {
4295 return $this->page->headingmenu;
4299 * Returns the title to use on the page.
4301 * @since Moodle 2.5.1 2.6
4302 * @return string
4304 public function page_title() {
4305 return $this->page->title;
4309 * Returns the moodle_url for the favicon.
4311 * @since Moodle 2.5.1 2.6
4312 * @return moodle_url The moodle_url for the favicon
4314 public function favicon() {
4315 $logo = null;
4316 if (!during_initial_install()) {
4317 $logo = get_config('core_admin', 'favicon');
4319 if (empty($logo)) {
4320 return $this->image_url('favicon', 'theme');
4323 // Use $CFG->themerev to prevent browser caching when the file changes.
4324 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'favicon', '64x64/',
4325 theme_get_revision(), $logo);
4329 * Renders preferences groups.
4331 * @param preferences_groups $renderable The renderable
4332 * @return string The output.
4334 public function render_preferences_groups(preferences_groups $renderable) {
4335 return $this->render_from_template('core/preferences_groups', $renderable);
4339 * Renders preferences group.
4341 * @param preferences_group $renderable The renderable
4342 * @return string The output.
4344 public function render_preferences_group(preferences_group $renderable) {
4345 $html = '';
4346 $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4347 $html .= $this->heading($renderable->title, 3);
4348 $html .= html_writer::start_tag('ul');
4349 foreach ($renderable->nodes as $node) {
4350 if ($node->has_children()) {
4351 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4353 $html .= html_writer::tag('li', $this->render($node));
4355 $html .= html_writer::end_tag('ul');
4356 $html .= html_writer::end_tag('div');
4357 return $html;
4360 public function context_header($headerinfo = null, $headinglevel = 1) {
4361 global $DB, $USER, $CFG, $SITE;
4362 require_once($CFG->dirroot . '/user/lib.php');
4363 $context = $this->page->context;
4364 $heading = null;
4365 $imagedata = null;
4366 $subheader = null;
4367 $userbuttons = null;
4369 // Make sure to use the heading if it has been set.
4370 if (isset($headerinfo['heading'])) {
4371 $heading = $headerinfo['heading'];
4372 } else {
4373 $heading = $this->page->heading;
4376 // The user context currently has images and buttons. Other contexts may follow.
4377 if ((isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) && $this->page->pagetype !== 'my-index') {
4378 if (isset($headerinfo['user'])) {
4379 $user = $headerinfo['user'];
4380 } else {
4381 // Look up the user information if it is not supplied.
4382 $user = $DB->get_record('user', array('id' => $context->instanceid));
4385 // If the user context is set, then use that for capability checks.
4386 if (isset($headerinfo['usercontext'])) {
4387 $context = $headerinfo['usercontext'];
4390 // Only provide user information if the user is the current user, or a user which the current user can view.
4391 // When checking user_can_view_profile(), either:
4392 // If the page context is course, check the course context (from the page object) or;
4393 // If page context is NOT course, then check across all courses.
4394 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4396 if (user_can_view_profile($user, $course)) {
4397 // Use the user's full name if the heading isn't set.
4398 if (empty($heading)) {
4399 $heading = fullname($user);
4402 $imagedata = $this->user_picture($user, array('size' => 100));
4404 // Check to see if we should be displaying a message button.
4405 if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
4406 $userbuttons = array(
4407 'messages' => array(
4408 'buttontype' => 'message',
4409 'title' => get_string('message', 'message'),
4410 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4411 'image' => 'message',
4412 'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
4413 'page' => $this->page
4417 if ($USER->id != $user->id) {
4418 $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4419 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4420 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4421 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4422 $userbuttons['togglecontact'] = array(
4423 'buttontype' => 'togglecontact',
4424 'title' => get_string($contacttitle, 'message'),
4425 'url' => new moodle_url('/message/index.php', array(
4426 'user1' => $USER->id,
4427 'user2' => $user->id,
4428 $contacturlaction => $user->id,
4429 'sesskey' => sesskey())
4431 'image' => $contactimage,
4432 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4433 'page' => $this->page
4437 } else {
4438 $heading = null;
4443 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4444 return $this->render_context_header($contextheader);
4448 * Renders the skip links for the page.
4450 * @param array $links List of skip links.
4451 * @return string HTML for the skip links.
4453 public function render_skip_links($links) {
4454 $context = [ 'links' => []];
4456 foreach ($links as $url => $text) {
4457 $context['links'][] = [ 'url' => $url, 'text' => $text];
4460 return $this->render_from_template('core/skip_links', $context);
4464 * Renders the header bar.
4466 * @param context_header $contextheader Header bar object.
4467 * @return string HTML for the header bar.
4469 protected function render_context_header(context_header $contextheader) {
4471 // Generate the heading first and before everything else as we might have to do an early return.
4472 if (!isset($contextheader->heading)) {
4473 $heading = $this->heading($this->page->heading, $contextheader->headinglevel);
4474 } else {
4475 $heading = $this->heading($contextheader->heading, $contextheader->headinglevel);
4478 $showheader = empty($this->page->layout_options['nocontextheader']);
4479 if (!$showheader) {
4480 // Return the heading wrapped in an sr-only element so it is only visible to screen-readers.
4481 return html_writer::div($heading, 'sr-only');
4484 // All the html stuff goes here.
4485 $html = html_writer::start_div('page-context-header');
4487 // Image data.
4488 if (isset($contextheader->imagedata)) {
4489 // Header specific image.
4490 $html .= html_writer::div($contextheader->imagedata, 'page-header-image icon-size-7');
4493 // Headings.
4494 if (isset($contextheader->prefix)) {
4495 $prefix = html_writer::div($contextheader->prefix, 'text-muted');
4496 $heading = $prefix . $heading;
4498 $html .= html_writer::tag('div', $heading, array('class' => 'page-header-headings'));
4500 // Buttons.
4501 if (isset($contextheader->additionalbuttons)) {
4502 $html .= html_writer::start_div('btn-group header-button-group');
4503 foreach ($contextheader->additionalbuttons as $button) {
4504 if (!isset($button->page)) {
4505 // Include js for messaging.
4506 if ($button['buttontype'] === 'togglecontact') {
4507 \core_message\helper::togglecontact_requirejs();
4509 if ($button['buttontype'] === 'message') {
4510 \core_message\helper::messageuser_requirejs();
4512 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4513 'class' => 'iconsmall',
4514 'role' => 'presentation'
4516 $image .= html_writer::span($button['title'], 'header-button-title');
4517 } else {
4518 $image = html_writer::empty_tag('img', array(
4519 'src' => $button['formattedimage'],
4520 'role' => 'presentation'
4523 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4525 $html .= html_writer::end_div();
4527 $html .= html_writer::end_div();
4529 return $html;
4533 * Wrapper for header elements.
4535 * @return string HTML to display the main header.
4537 public function full_header() {
4538 $pagetype = $this->page->pagetype;
4539 $homepage = get_home_page();
4540 $homepagetype = null;
4541 // Add a special case since /my/courses is a part of the /my subsystem.
4542 if ($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES) {
4543 $homepagetype = 'my-index';
4544 } else if ($homepage == HOMEPAGE_SITE) {
4545 $homepagetype = 'site-index';
4547 if ($this->page->include_region_main_settings_in_header_actions() &&
4548 !$this->page->blocks->is_block_present('settings')) {
4549 // Only include the region main settings if the page has requested it and it doesn't already have
4550 // the settings block on it. The region main settings are included in the settings block and
4551 // duplicating the content causes behat failures.
4552 $this->page->add_header_action(html_writer::div(
4553 $this->region_main_settings_menu(),
4554 'd-print-none',
4555 ['id' => 'region-main-settings-menu']
4559 $header = new stdClass();
4560 $header->settingsmenu = $this->context_header_settings_menu();
4561 $header->contextheader = $this->context_header();
4562 $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
4563 $header->navbar = $this->navbar();
4564 $header->pageheadingbutton = $this->page_heading_button();
4565 $header->courseheader = $this->course_header();
4566 $header->headeractions = $this->page->get_header_actions();
4567 if (!empty($pagetype) && !empty($homepagetype) && $pagetype == $homepagetype) {
4568 $header->welcomemessage = \core_user::welcome_message();
4570 return $this->render_from_template('core/full_header', $header);
4574 * This is an optional menu that can be added to a layout by a theme. It contains the
4575 * menu for the course administration, only on the course main page.
4577 * @return string
4579 public function context_header_settings_menu() {
4580 $context = $this->page->context;
4581 $menu = new action_menu();
4583 $items = $this->page->navbar->get_items();
4584 $currentnode = end($items);
4586 $showcoursemenu = false;
4587 $showfrontpagemenu = false;
4588 $showusermenu = false;
4590 // We are on the course home page.
4591 if (($context->contextlevel == CONTEXT_COURSE) &&
4592 !empty($currentnode) &&
4593 ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
4594 $showcoursemenu = true;
4597 $courseformat = course_get_format($this->page->course);
4598 // This is a single activity course format, always show the course menu on the activity main page.
4599 if ($context->contextlevel == CONTEXT_MODULE &&
4600 !$courseformat->has_view_page()) {
4602 $this->page->navigation->initialise();
4603 $activenode = $this->page->navigation->find_active_node();
4604 // If the settings menu has been forced then show the menu.
4605 if ($this->page->is_settings_menu_forced()) {
4606 $showcoursemenu = true;
4607 } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
4608 $activenode->type == navigation_node::TYPE_RESOURCE)) {
4610 // We only want to show the menu on the first page of the activity. This means
4611 // the breadcrumb has no additional nodes.
4612 if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
4613 $showcoursemenu = true;
4618 // This is the site front page.
4619 if ($context->contextlevel == CONTEXT_COURSE &&
4620 !empty($currentnode) &&
4621 $currentnode->key === 'home') {
4622 $showfrontpagemenu = true;
4625 // This is the user profile page.
4626 if ($context->contextlevel == CONTEXT_USER &&
4627 !empty($currentnode) &&
4628 ($currentnode->key === 'myprofile')) {
4629 $showusermenu = true;
4632 if ($showfrontpagemenu) {
4633 $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
4634 if ($settingsnode) {
4635 // Build an action menu based on the visible nodes from this navigation tree.
4636 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4638 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4639 if ($skipped) {
4640 $text = get_string('morenavigationlinks');
4641 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4642 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4643 $menu->add_secondary_action($link);
4646 } else if ($showcoursemenu) {
4647 $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
4648 if ($settingsnode) {
4649 // Build an action menu based on the visible nodes from this navigation tree.
4650 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4652 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4653 if ($skipped) {
4654 $text = get_string('morenavigationlinks');
4655 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4656 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4657 $menu->add_secondary_action($link);
4660 } else if ($showusermenu) {
4661 // Get the course admin node from the settings navigation.
4662 $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
4663 if ($settingsnode) {
4664 // Build an action menu based on the visible nodes from this navigation tree.
4665 $this->build_action_menu_from_navigation($menu, $settingsnode);
4669 return $this->render($menu);
4673 * Take a node in the nav tree and make an action menu out of it.
4674 * The links are injected in the action menu.
4676 * @param action_menu $menu
4677 * @param navigation_node $node
4678 * @param boolean $indent
4679 * @param boolean $onlytopleafnodes
4680 * @return boolean nodesskipped - True if nodes were skipped in building the menu
4682 protected function build_action_menu_from_navigation(action_menu $menu,
4683 navigation_node $node,
4684 $indent = false,
4685 $onlytopleafnodes = false) {
4686 $skipped = false;
4687 // Build an action menu based on the visible nodes from this navigation tree.
4688 foreach ($node->children as $menuitem) {
4689 if ($menuitem->display) {
4690 if ($onlytopleafnodes && $menuitem->children->count()) {
4691 $skipped = true;
4692 continue;
4694 if ($menuitem->action) {
4695 if ($menuitem->action instanceof action_link) {
4696 $link = $menuitem->action;
4697 // Give preference to setting icon over action icon.
4698 if (!empty($menuitem->icon)) {
4699 $link->icon = $menuitem->icon;
4701 } else {
4702 $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
4704 } else {
4705 if ($onlytopleafnodes) {
4706 $skipped = true;
4707 continue;
4709 $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
4711 if ($indent) {
4712 $link->add_class('ml-4');
4714 if (!empty($menuitem->classes)) {
4715 $link->add_class(implode(" ", $menuitem->classes));
4718 $menu->add_secondary_action($link);
4719 $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
4722 return $skipped;
4726 * This is an optional menu that can be added to a layout by a theme. It contains the
4727 * menu for the most specific thing from the settings block. E.g. Module administration.
4729 * @return string
4731 public function region_main_settings_menu() {
4732 $context = $this->page->context;
4733 $menu = new action_menu();
4735 if ($context->contextlevel == CONTEXT_MODULE) {
4737 $this->page->navigation->initialise();
4738 $node = $this->page->navigation->find_active_node();
4739 $buildmenu = false;
4740 // If the settings menu has been forced then show the menu.
4741 if ($this->page->is_settings_menu_forced()) {
4742 $buildmenu = true;
4743 } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
4744 $node->type == navigation_node::TYPE_RESOURCE)) {
4746 $items = $this->page->navbar->get_items();
4747 $navbarnode = end($items);
4748 // We only want to show the menu on the first page of the activity. This means
4749 // the breadcrumb has no additional nodes.
4750 if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
4751 $buildmenu = true;
4754 if ($buildmenu) {
4755 // Get the course admin node from the settings navigation.
4756 $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
4757 if ($node) {
4758 // Build an action menu based on the visible nodes from this navigation tree.
4759 $this->build_action_menu_from_navigation($menu, $node);
4763 } else if ($context->contextlevel == CONTEXT_COURSECAT) {
4764 // For course category context, show category settings menu, if we're on the course category page.
4765 if ($this->page->pagetype === 'course-index-category') {
4766 $node = $this->page->settingsnav->find('categorysettings', navigation_node::TYPE_CONTAINER);
4767 if ($node) {
4768 // Build an action menu based on the visible nodes from this navigation tree.
4769 $this->build_action_menu_from_navigation($menu, $node);
4773 } else {
4774 $items = $this->page->navbar->get_items();
4775 $navbarnode = end($items);
4777 if ($navbarnode && ($navbarnode->key === 'participants')) {
4778 $node = $this->page->settingsnav->find('users', navigation_node::TYPE_CONTAINER);
4779 if ($node) {
4780 // Build an action menu based on the visible nodes from this navigation tree.
4781 $this->build_action_menu_from_navigation($menu, $node);
4786 return $this->render($menu);
4790 * Displays the list of tags associated with an entry
4792 * @param array $tags list of instances of core_tag or stdClass
4793 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4794 * to use default, set to '' (empty string) to omit the label completely
4795 * @param string $classes additional classes for the enclosing div element
4796 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4797 * will be appended to the end, JS will toggle the rest of the tags
4798 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4799 * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
4800 * @return string
4802 public function tag_list($tags, $label = null, $classes = '', $limit = 10,
4803 $pagecontext = null, $accesshidelabel = false) {
4804 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
4805 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4809 * Renders element for inline editing of any value
4811 * @param \core\output\inplace_editable $element
4812 * @return string
4814 public function render_inplace_editable(\core\output\inplace_editable $element) {
4815 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4819 * Renders a bar chart.
4821 * @param \core\chart_bar $chart The chart.
4822 * @return string
4824 public function render_chart_bar(\core\chart_bar $chart) {
4825 return $this->render_chart($chart);
4829 * Renders a line chart.
4831 * @param \core\chart_line $chart The chart.
4832 * @return string
4834 public function render_chart_line(\core\chart_line $chart) {
4835 return $this->render_chart($chart);
4839 * Renders a pie chart.
4841 * @param \core\chart_pie $chart The chart.
4842 * @return string
4844 public function render_chart_pie(\core\chart_pie $chart) {
4845 return $this->render_chart($chart);
4849 * Renders a chart.
4851 * @param \core\chart_base $chart The chart.
4852 * @param bool $withtable Whether to include a data table with the chart.
4853 * @return string
4855 public function render_chart(\core\chart_base $chart, $withtable = true) {
4856 $chartdata = json_encode($chart);
4857 return $this->render_from_template('core/chart', (object) [
4858 'chartdata' => $chartdata,
4859 'withtable' => $withtable
4864 * Renders the login form.
4866 * @param \core_auth\output\login $form The renderable.
4867 * @return string
4869 public function render_login(\core_auth\output\login $form) {
4870 global $CFG, $SITE;
4872 $context = $form->export_for_template($this);
4874 $context->errorformatted = $this->error_text($context->error);
4875 $url = $this->get_logo_url();
4876 if ($url) {
4877 $url = $url->out(false);
4879 $context->logourl = $url;
4880 $context->sitename = format_string($SITE->fullname, true,
4881 ['context' => context_course::instance(SITEID), "escape" => false]);
4883 return $this->render_from_template('core/loginform', $context);
4887 * Renders an mform element from a template.
4889 * @param HTML_QuickForm_element $element element
4890 * @param bool $required if input is required field
4891 * @param bool $advanced if input is an advanced field
4892 * @param string $error error message to display
4893 * @param bool $ingroup True if this element is rendered as part of a group
4894 * @return mixed string|bool
4896 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4897 $templatename = 'core_form/element-' . $element->getType();
4898 if ($ingroup) {
4899 $templatename .= "-inline";
4901 try {
4902 // We call this to generate a file not found exception if there is no template.
4903 // We don't want to call export_for_template if there is no template.
4904 core\output\mustache_template_finder::get_template_filepath($templatename);
4906 if ($element instanceof templatable) {
4907 $elementcontext = $element->export_for_template($this);
4909 $helpbutton = '';
4910 if (method_exists($element, 'getHelpButton')) {
4911 $helpbutton = $element->getHelpButton();
4913 $label = $element->getLabel();
4914 $text = '';
4915 if (method_exists($element, 'getText')) {
4916 // There currently exists code that adds a form element with an empty label.
4917 // If this is the case then set the label to the description.
4918 if (empty($label)) {
4919 $label = $element->getText();
4920 } else {
4921 $text = $element->getText();
4925 // Generate the form element wrapper ids and names to pass to the template.
4926 // This differs between group and non-group elements.
4927 if ($element->getType() === 'group') {
4928 // Group element.
4929 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
4930 $elementcontext['wrapperid'] = $elementcontext['id'];
4932 // Ensure group elements pass through the group name as the element name.
4933 $elementcontext['name'] = $elementcontext['groupname'];
4934 } else {
4935 // Non grouped element.
4936 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
4937 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
4940 $context = array(
4941 'element' => $elementcontext,
4942 'label' => $label,
4943 'text' => $text,
4944 'required' => $required,
4945 'advanced' => $advanced,
4946 'helpbutton' => $helpbutton,
4947 'error' => $error
4949 return $this->render_from_template($templatename, $context);
4951 } catch (Exception $e) {
4952 // No template for this element.
4953 return false;
4958 * Render the login signup form into a nice template for the theme.
4960 * @param mform $form
4961 * @return string
4963 public function render_login_signup_form($form) {
4964 global $SITE;
4966 $context = $form->export_for_template($this);
4967 $url = $this->get_logo_url();
4968 if ($url) {
4969 $url = $url->out(false);
4971 $context['logourl'] = $url;
4972 $context['sitename'] = format_string($SITE->fullname, true,
4973 ['context' => context_course::instance(SITEID), "escape" => false]);
4975 return $this->render_from_template('core/signup_form_layout', $context);
4979 * Render the verify age and location page into a nice template for the theme.
4981 * @param \core_auth\output\verify_age_location_page $page The renderable
4982 * @return string
4984 protected function render_verify_age_location_page($page) {
4985 $context = $page->export_for_template($this);
4987 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4991 * Render the digital minor contact information page into a nice template for the theme.
4993 * @param \core_auth\output\digital_minor_page $page The renderable
4994 * @return string
4996 protected function render_digital_minor_page($page) {
4997 $context = $page->export_for_template($this);
4999 return $this->render_from_template('core/auth_digital_minor_page', $context);
5003 * Renders a progress bar.
5005 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
5007 * @param progress_bar $bar The bar.
5008 * @return string HTML fragment
5010 public function render_progress_bar(progress_bar $bar) {
5011 $data = $bar->export_for_template($this);
5012 return $this->render_from_template('core/progress_bar', $data);
5016 * Renders an update to a progress bar.
5018 * Note: This does not cleanly map to a renderable class and should
5019 * never be used directly.
5021 * @param string $id
5022 * @param float $percent
5023 * @param string $msg Message
5024 * @param string $estimate time remaining message
5025 * @return string ascii fragment
5027 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
5028 return html_writer::script(js_writer::function_call('updateProgressBar', [$id, $percent, $msg, $estimate]));
5032 * Renders element for a toggle-all checkbox.
5034 * @param \core\output\checkbox_toggleall $element
5035 * @return string
5037 public function render_checkbox_toggleall(\core\output\checkbox_toggleall $element) {
5038 return $this->render_from_template($element->get_template(), $element->export_for_template($this));
5042 * Renders the tertiary nav for the participants page
5044 * @param object $course The course we are operating within
5045 * @param string|null $renderedbuttons Any additional buttons/content to be displayed in line with the nav
5046 * @return string
5048 public function render_participants_tertiary_nav(object $course, ?string $renderedbuttons = null) {
5049 $actionbar = new \core\output\participants_action_bar($course, $this->page, $renderedbuttons);
5050 $content = $this->render_from_template('core_course/participants_actionbar', $actionbar->export_for_template($this));
5051 return $content ?: "";
5055 * Renders release information in the footer popup
5056 * @return string Moodle release info.
5058 public function moodle_release() {
5059 global $CFG;
5060 if (!during_initial_install() && is_siteadmin()) {
5061 return $CFG->release;
5066 * Generate the add block button when editing mode is turned on and the user can edit blocks.
5068 * @param string $region where new blocks should be added.
5069 * @return string html for the add block button.
5071 public function addblockbutton($region = ''): string {
5072 $addblockbutton = '';
5073 $regions = $this->page->blocks->get_regions();
5074 if (count($regions) == 0) {
5075 return '';
5077 if (isset($this->page->theme->addblockposition) &&
5078 $this->page->user_is_editing() &&
5079 $this->page->user_can_edit_blocks() &&
5080 $this->page->pagelayout !== 'mycourses'
5082 $params = ['bui_addblock' => '', 'sesskey' => sesskey()];
5083 if (!empty($region)) {
5084 $params['bui_blockregion'] = $region;
5086 $url = new moodle_url($this->page->url, $params);
5087 $addblockbutton = $this->render_from_template('core/add_block_button',
5089 'link' => $url->out(false),
5090 'escapedlink' => "?{$url->get_query_string(false)}",
5091 'pagehash' => $this->page->get_edited_page_hash(),
5092 'blockregion' => $region,
5093 // The following parameters are not used since Moodle 4.2 but are
5094 // still passed for backward-compatibility.
5095 'pageType' => $this->page->pagetype,
5096 'pageLayout' => $this->page->pagelayout,
5097 'subPage' => $this->page->subpage,
5101 return $addblockbutton;
5106 * A renderer that generates output for command-line scripts.
5108 * The implementation of this renderer is probably incomplete.
5110 * @copyright 2009 Tim Hunt
5111 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5112 * @since Moodle 2.0
5113 * @package core
5114 * @category output
5116 class core_renderer_cli extends core_renderer {
5119 * @var array $progressmaximums stores the largest percentage for a progress bar.
5120 * @return string ascii fragment
5122 private $progressmaximums = [];
5125 * Returns the page header.
5127 * @return string HTML fragment
5129 public function header() {
5130 return $this->page->heading . "\n";
5134 * Renders a Check API result
5136 * To aid in CLI consistency this status is NOT translated and the visual
5137 * width is always exactly 10 chars.
5139 * @param core\check\result $result
5140 * @return string HTML fragment
5142 protected function render_check_result(core\check\result $result) {
5143 $status = $result->get_status();
5145 $labels = [
5146 core\check\result::NA => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' NA ',
5147 core\check\result::OK => ' ' . cli_ansi_format('<colour:green>') . ' OK ',
5148 core\check\result::INFO => ' ' . cli_ansi_format('<colour:blue>' ) . ' INFO ',
5149 core\check\result::UNKNOWN => ' ' . cli_ansi_format('<colour:darkGray>' ) . ' UNKNOWN ',
5150 core\check\result::WARNING => ' ' . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
5151 core\check\result::ERROR => ' ' . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
5152 core\check\result::CRITICAL => '' . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
5154 $string = $labels[$status] . cli_ansi_format('<colour:normal>');
5155 return $string;
5159 * Renders a Check API result
5161 * @param result $result
5162 * @return string fragment
5164 public function check_result(core\check\result $result) {
5165 return $this->render_check_result($result);
5169 * Renders a progress bar.
5171 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
5173 * @param progress_bar $bar The bar.
5174 * @return string ascii fragment
5176 public function render_progress_bar(progress_bar $bar) {
5177 global $CFG;
5179 $size = 55; // The width of the progress bar in chars.
5180 $ascii = "\n";
5182 if (stream_isatty(STDOUT)) {
5183 require_once($CFG->libdir.'/clilib.php');
5185 $ascii .= "[" . str_repeat(' ', $size) . "] 0% \n";
5186 return cli_ansi_format($ascii);
5189 $this->progressmaximums[$bar->get_id()] = 0;
5190 $ascii .= '[';
5191 return $ascii;
5195 * Renders an update to a progress bar.
5197 * Note: This does not cleanly map to a renderable class and should
5198 * never be used directly.
5200 * @param string $id
5201 * @param float $percent
5202 * @param string $msg Message
5203 * @param string $estimate time remaining message
5204 * @return string ascii fragment
5206 public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
5207 $size = 55; // The width of the progress bar in chars.
5208 $ascii = '';
5210 // If we are rendering to a terminal then we can safely use ansii codes
5211 // to move the cursor and redraw the complete progress bar each time
5212 // it is updated.
5213 if (stream_isatty(STDOUT)) {
5214 $colour = $percent == 100 ? 'green' : 'blue';
5216 $done = $percent * $size * 0.01;
5217 $whole = floor($done);
5218 $bar = "<colour:$colour>";
5219 $bar .= str_repeat('█', $whole);
5221 if ($whole < $size) {
5222 // By using unicode chars for partial blocks we can have higher
5223 // precision progress bar.
5224 $fraction = floor(($done - $whole) * 8);
5225 $bar .= core_text::substr(' ▏▎▍▌▋▊▉', $fraction, 1);
5227 // Fill the rest of the empty bar.
5228 $bar .= str_repeat(' ', $size - $whole - 1);
5231 $bar .= '<colour:normal>';
5233 if ($estimate) {
5234 $estimate = "- $estimate";
5237 $ascii .= '<cursor:up>';
5238 $ascii .= '<cursor:up>';
5239 $ascii .= sprintf("[$bar] %3.1f%% %-22s\n", $percent, $estimate);
5240 $ascii .= sprintf("%-80s\n", $msg);
5241 return cli_ansi_format($ascii);
5244 // If we are not rendering to a tty, ie when piped to another command
5245 // or on windows we need to progressively render the progress bar
5246 // which can only ever go forwards.
5247 $done = round($percent * $size * 0.01);
5248 $delta = max(0, $done - $this->progressmaximums[$id]);
5250 $ascii .= str_repeat('#', $delta);
5251 if ($percent >= 100 && $delta > 0) {
5252 $ascii .= sprintf("] %3.1f%%\n$msg\n", $percent);
5254 $this->progressmaximums[$id] += $delta;
5255 return $ascii;
5259 * Returns a template fragment representing a Heading.
5261 * @param string $text The text of the heading
5262 * @param int $level The level of importance of the heading
5263 * @param string $classes A space-separated list of CSS classes
5264 * @param string $id An optional ID
5265 * @return string A template fragment for a heading
5267 public function heading($text, $level = 2, $classes = 'main', $id = null) {
5268 $text .= "\n";
5269 switch ($level) {
5270 case 1:
5271 return '=>' . $text;
5272 case 2:
5273 return '-->' . $text;
5274 default:
5275 return $text;
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 $output = "!!! $message !!!\n";
5294 if ($CFG->debugdeveloper) {
5295 if (!empty($debuginfo)) {
5296 $output .= $this->notification($debuginfo, 'notifytiny');
5298 if (!empty($backtrace)) {
5299 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
5303 return $output;
5307 * Returns a template fragment representing a notification.
5309 * @param string $message The message to print out.
5310 * @param string $type The type of notification. See constants on \core\output\notification.
5311 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5312 * @return string A template fragment for a notification
5314 public function notification($message, $type = null, $closebutton = true) {
5315 $message = clean_text($message);
5316 if ($type === 'notifysuccess' || $type === 'success') {
5317 return "++ $message ++\n";
5319 return "!! $message !!\n";
5323 * There is no footer for a cli request, however we must override the
5324 * footer method to prevent the default footer.
5326 public function footer() {}
5329 * Render a notification (that is, a status message about something that has
5330 * just happened).
5332 * @param \core\output\notification $notification the notification to print out
5333 * @return string plain text output
5335 public function render_notification(\core\output\notification $notification) {
5336 return $this->notification($notification->get_message(), $notification->get_message_type());
5342 * A renderer that generates output for ajax scripts.
5344 * This renderer prevents accidental sends back only json
5345 * encoded error messages, all other output is ignored.
5347 * @copyright 2010 Petr Skoda
5348 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5349 * @since Moodle 2.0
5350 * @package core
5351 * @category output
5353 class core_renderer_ajax extends core_renderer {
5356 * Returns a template fragment representing a fatal error.
5358 * @param string $message The message to output
5359 * @param string $moreinfourl URL where more info can be found about the error
5360 * @param string $link Link for the Continue button
5361 * @param array $backtrace The execution backtrace
5362 * @param string $debuginfo Debugging information
5363 * @return string A template fragment for a fatal error
5365 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5366 global $CFG;
5368 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
5370 $e = new stdClass();
5371 $e->error = $message;
5372 $e->errorcode = $errorcode;
5373 $e->stacktrace = NULL;
5374 $e->debuginfo = NULL;
5375 $e->reproductionlink = NULL;
5376 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
5377 $link = (string) $link;
5378 if ($link) {
5379 $e->reproductionlink = $link;
5381 if (!empty($debuginfo)) {
5382 $e->debuginfo = $debuginfo;
5384 if (!empty($backtrace)) {
5385 $e->stacktrace = format_backtrace($backtrace, true);
5388 $this->header();
5389 return json_encode($e);
5393 * Used to display a notification.
5394 * For the AJAX notifications are discarded.
5396 * @param string $message The message to print out.
5397 * @param string $type The type of notification. See constants on \core\output\notification.
5398 * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5400 public function notification($message, $type = null, $closebutton = true) {
5404 * Used to display a redirection message.
5405 * AJAX redirections should not occur and as such redirection messages
5406 * are discarded.
5408 * @param moodle_url|string $encodedurl
5409 * @param string $message
5410 * @param int $delay
5411 * @param bool $debugdisableredirect
5412 * @param string $messagetype The type of notification to show the message in.
5413 * See constants on \core\output\notification.
5415 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
5416 $messagetype = \core\output\notification::NOTIFY_INFO) {}
5419 * Prepares the start of an AJAX output.
5421 public function header() {
5422 // unfortunately YUI iframe upload does not support application/json
5423 if (!empty($_FILES)) {
5424 @header('Content-type: text/plain; charset=utf-8');
5425 if (!core_useragent::supports_json_contenttype()) {
5426 @header('X-Content-Type-Options: nosniff');
5428 } else if (!core_useragent::supports_json_contenttype()) {
5429 @header('Content-type: text/plain; charset=utf-8');
5430 @header('X-Content-Type-Options: nosniff');
5431 } else {
5432 @header('Content-type: application/json; charset=utf-8');
5435 // Headers to make it not cacheable and json
5436 @header('Cache-Control: no-store, no-cache, must-revalidate');
5437 @header('Cache-Control: post-check=0, pre-check=0', false);
5438 @header('Pragma: no-cache');
5439 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
5440 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
5441 @header('Accept-Ranges: none');
5445 * There is no footer for an AJAX request, however we must override the
5446 * footer method to prevent the default footer.
5448 public function footer() {}
5451 * No need for headers in an AJAX request... this should never happen.
5452 * @param string $text
5453 * @param int $level
5454 * @param string $classes
5455 * @param string $id
5457 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
5463 * The maintenance renderer.
5465 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
5466 * is running a maintenance related task.
5467 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
5469 * @since Moodle 2.6
5470 * @package core
5471 * @category output
5472 * @copyright 2013 Sam Hemelryk
5473 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5475 class core_renderer_maintenance extends core_renderer {
5478 * Initialises the renderer instance.
5480 * @param moodle_page $page
5481 * @param string $target
5482 * @throws coding_exception
5484 public function __construct(moodle_page $page, $target) {
5485 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
5486 throw new coding_exception('Invalid request for the maintenance renderer.');
5488 parent::__construct($page, $target);
5492 * Does nothing. The maintenance renderer cannot produce blocks.
5494 * @param block_contents $bc
5495 * @param string $region
5496 * @return string
5498 public function block(block_contents $bc, $region) {
5499 return '';
5503 * Does nothing. The maintenance renderer cannot produce blocks.
5505 * @param string $region
5506 * @param array $classes
5507 * @param string $tag
5508 * @param boolean $fakeblocksonly
5509 * @return string
5511 public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
5512 return '';
5516 * Does nothing. The maintenance renderer cannot produce blocks.
5518 * @param string $region
5519 * @param boolean $fakeblocksonly Output fake block only.
5520 * @return string
5522 public function blocks_for_region($region, $fakeblocksonly = false) {
5523 return '';
5527 * Does nothing. The maintenance renderer cannot produce a course content header.
5529 * @param bool $onlyifnotcalledbefore
5530 * @return string
5532 public function course_content_header($onlyifnotcalledbefore = false) {
5533 return '';
5537 * Does nothing. The maintenance renderer cannot produce a course content footer.
5539 * @param bool $onlyifnotcalledbefore
5540 * @return string
5542 public function course_content_footer($onlyifnotcalledbefore = false) {
5543 return '';
5547 * Does nothing. The maintenance renderer cannot produce a course header.
5549 * @return string
5551 public function course_header() {
5552 return '';
5556 * Does nothing. The maintenance renderer cannot produce a course footer.
5558 * @return string
5560 public function course_footer() {
5561 return '';
5565 * Does nothing. The maintenance renderer cannot produce a custom menu.
5567 * @param string $custommenuitems
5568 * @return string
5570 public function custom_menu($custommenuitems = '') {
5571 return '';
5575 * Does nothing. The maintenance renderer cannot produce a file picker.
5577 * @param array $options
5578 * @return string
5580 public function file_picker($options) {
5581 return '';
5585 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
5587 * @param array $dir
5588 * @return string
5590 public function htmllize_file_tree($dir) {
5591 return '';
5596 * Overridden confirm message for upgrades.
5598 * @param string $message The question to ask the user
5599 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5600 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5601 * @param array $displayoptions optional extra display options
5602 * @return string HTML fragment
5604 public function confirm($message, $continue, $cancel, array $displayoptions = []) {
5605 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5606 // from any previous version of Moodle).
5607 if ($continue instanceof single_button) {
5608 $continue->type = single_button::BUTTON_PRIMARY;
5609 } else if (is_string($continue)) {
5610 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post',
5611 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
5612 } else if ($continue instanceof moodle_url) {
5613 $continue = new single_button($continue, get_string('continue'), 'post',
5614 $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
5615 } else {
5616 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5617 ' (string/moodle_url) or a single_button instance.');
5620 if ($cancel instanceof single_button) {
5621 $output = '';
5622 } else if (is_string($cancel)) {
5623 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5624 } else if ($cancel instanceof moodle_url) {
5625 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5626 } else {
5627 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5628 ' (string/moodle_url) or a single_button instance.');
5631 $output = $this->box_start('generalbox', 'notice');
5632 $output .= html_writer::tag('h4', get_string('confirm'));
5633 $output .= html_writer::tag('p', $message);
5634 $output .= html_writer::tag('div', $this->render($cancel) . $this->render($continue), ['class' => 'buttons']);
5635 $output .= $this->box_end();
5636 return $output;
5640 * Does nothing. The maintenance renderer does not support JS.
5642 * @param block_contents $bc
5644 public function init_block_hider_js(block_contents $bc) {
5645 // Does nothing.
5649 * Does nothing. The maintenance renderer cannot produce language menus.
5651 * @return string
5653 public function lang_menu() {
5654 return '';
5658 * Does nothing. The maintenance renderer has no need for login information.
5660 * @param null $withlinks
5661 * @return string
5663 public function login_info($withlinks = null) {
5664 return '';
5668 * Secure login info.
5670 * @return string
5672 public function secure_login_info() {
5673 return $this->login_info(false);
5677 * Does nothing. The maintenance renderer cannot produce user pictures.
5679 * @param stdClass $user
5680 * @param array $options
5681 * @return string
5683 public function user_picture(stdClass $user, array $options = null) {
5684 return '';