MDL-65087 message: add button role to action links on bootstrapbase
[moodle.git] / lib / outputrenderers.php
blobd698ed6cdb056fcb2034f7a6ead01732efab3e42
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 defined('MOODLE_INTERNAL') || die();
40 /**
41 * Simple base class for Moodle renderers.
43 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
45 * Also has methods to facilitate generating HTML output.
47 * @copyright 2009 Tim Hunt
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 * @since Moodle 2.0
50 * @package core
51 * @category output
53 class renderer_base {
54 /**
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
59 /**
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
62 protected $page;
64 /**
65 * @var string The requested rendering target.
67 protected $target;
69 /**
70 * @var Mustache_Engine $mustache The mustache template compiler
72 private $mustache;
74 /**
75 * Return an instance of the mustache class.
77 * @since 2.9
78 * @return Mustache_Engine
80 protected function get_mustache() {
81 global $CFG;
83 if ($this->mustache === null) {
84 require_once("{$CFG->libdir}/filelib.php");
86 $themename = $this->page->theme->name;
87 $themerev = theme_get_revision();
89 // Create new localcache directory.
90 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
92 // Remove old localcache directories.
93 $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR);
94 foreach ($mustachecachedirs as $localcachedir) {
95 $cachedrev = [];
96 preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
97 $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
98 if ($cachedrev > 0 && $cachedrev < $themerev) {
99 fulldelete($localcachedir);
103 $loader = new \core\output\mustache_filesystem_loader();
104 $stringhelper = new \core\output\mustache_string_helper();
105 $quotehelper = new \core\output\mustache_quote_helper();
106 $jshelper = new \core\output\mustache_javascript_helper($this->page);
107 $pixhelper = new \core\output\mustache_pix_helper($this);
108 $shortentexthelper = new \core\output\mustache_shorten_text_helper();
109 $userdatehelper = new \core\output\mustache_user_date_helper();
111 // We only expose the variables that are exposed to JS templates.
112 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
114 $helpers = array('config' => $safeconfig,
115 'str' => array($stringhelper, 'str'),
116 'quote' => array($quotehelper, 'quote'),
117 'js' => array($jshelper, 'help'),
118 'pix' => array($pixhelper, 'pix'),
119 'shortentext' => array($shortentexthelper, 'shorten'),
120 'userdate' => array($userdatehelper, 'transform'),
123 $this->mustache = new Mustache_Engine(array(
124 'cache' => $cachedir,
125 'escape' => 's',
126 'loader' => $loader,
127 'helpers' => $helpers,
128 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS]));
132 return $this->mustache;
137 * Constructor
139 * The constructor takes two arguments. The first is the page that the renderer
140 * has been created to assist with, and the second is the target.
141 * The target is an additional identifier that can be used to load different
142 * renderers for different options.
144 * @param moodle_page $page the page we are doing output for.
145 * @param string $target one of rendering target constants
147 public function __construct(moodle_page $page, $target) {
148 $this->opencontainers = $page->opencontainers;
149 $this->page = $page;
150 $this->target = $target;
154 * Renders a template by name with the given context.
156 * The provided data needs to be array/stdClass made up of only simple types.
157 * Simple types are array,stdClass,bool,int,float,string
159 * @since 2.9
160 * @param array|stdClass $context Context containing data for the template.
161 * @return string|boolean
163 public function render_from_template($templatename, $context) {
164 static $templatecache = array();
165 $mustache = $this->get_mustache();
167 try {
168 // Grab a copy of the existing helper to be restored later.
169 $uniqidhelper = $mustache->getHelper('uniqid');
170 } catch (Mustache_Exception_UnknownHelperException $e) {
171 // Helper doesn't exist.
172 $uniqidhelper = null;
175 // Provide 1 random value that will not change within a template
176 // but will be different from template to template. This is useful for
177 // e.g. aria attributes that only work with id attributes and must be
178 // unique in a page.
179 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
180 if (isset($templatecache[$templatename])) {
181 $template = $templatecache[$templatename];
182 } else {
183 try {
184 $template = $mustache->loadTemplate($templatename);
185 $templatecache[$templatename] = $template;
186 } catch (Mustache_Exception_UnknownTemplateException $e) {
187 throw new moodle_exception('Unknown template: ' . $templatename);
191 $renderedtemplate = trim($template->render($context));
193 // If we had an existing uniqid helper then we need to restore it to allow
194 // handle nested calls of render_from_template.
195 if ($uniqidhelper) {
196 $mustache->addHelper('uniqid', $uniqidhelper);
199 return $renderedtemplate;
204 * Returns rendered widget.
206 * The provided widget needs to be an object that extends the renderable
207 * interface.
208 * If will then be rendered by a method based upon the classname for the widget.
209 * For instance a widget of class `crazywidget` will be rendered by a protected
210 * render_crazywidget method of this renderer.
211 * If no render_crazywidget method exists and crazywidget implements templatable,
212 * look for the 'crazywidget' template in the same component and render that.
214 * @param renderable $widget instance with renderable interface
215 * @return string
217 public function render(renderable $widget) {
218 $classparts = explode('\\', get_class($widget));
219 // Strip namespaces.
220 $classname = array_pop($classparts);
221 // Remove _renderable suffixes
222 $classname = preg_replace('/_renderable$/', '', $classname);
224 $rendermethod = 'render_'.$classname;
225 if (method_exists($this, $rendermethod)) {
226 return $this->$rendermethod($widget);
228 if ($widget instanceof templatable) {
229 $component = array_shift($classparts);
230 if (!$component) {
231 $component = 'core';
233 $template = $component . '/' . $classname;
234 $context = $widget->export_for_template($this);
235 return $this->render_from_template($template, $context);
237 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
241 * Adds a JS action for the element with the provided id.
243 * This method adds a JS event for the provided component action to the page
244 * and then returns the id that the event has been attached to.
245 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
247 * @param component_action $action
248 * @param string $id
249 * @return string id of element, either original submitted or random new if not supplied
251 public function add_action_handler(component_action $action, $id = null) {
252 if (!$id) {
253 $id = html_writer::random_id($action->event);
255 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
256 return $id;
260 * Returns true is output has already started, and false if not.
262 * @return boolean true if the header has been printed.
264 public function has_started() {
265 return $this->page->state >= moodle_page::STATE_IN_BODY;
269 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
271 * @param mixed $classes Space-separated string or array of classes
272 * @return string HTML class attribute value
274 public static function prepare_classes($classes) {
275 if (is_array($classes)) {
276 return implode(' ', array_unique($classes));
278 return $classes;
282 * Return the direct URL for an image from the pix folder.
284 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
286 * @deprecated since Moodle 3.3
287 * @param string $imagename the name of the icon.
288 * @param string $component specification of one plugin like in get_string()
289 * @return moodle_url
291 public function pix_url($imagename, $component = 'moodle') {
292 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
293 return $this->page->theme->image_url($imagename, $component);
297 * Return the moodle_url for an image.
299 * The exact image location and extension is determined
300 * automatically by searching for gif|png|jpg|jpeg, please
301 * note there can not be diferent images with the different
302 * extension. The imagename is for historical reasons
303 * a relative path name, it may be changed later for core
304 * images. It is recommended to not use subdirectories
305 * in plugin and theme pix directories.
307 * There are three types of images:
308 * 1/ theme images - stored in theme/mytheme/pix/,
309 * use component 'theme'
310 * 2/ core images - stored in /pix/,
311 * overridden via theme/mytheme/pix_core/
312 * 3/ plugin images - stored in mod/mymodule/pix,
313 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
314 * example: image_url('comment', 'mod_glossary')
316 * @param string $imagename the pathname of the image
317 * @param string $component full plugin name (aka component) or 'theme'
318 * @return moodle_url
320 public function image_url($imagename, $component = 'moodle') {
321 return $this->page->theme->image_url($imagename, $component);
325 * Return the site's logo URL, if any.
327 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
328 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
329 * @return moodle_url|false
331 public function get_logo_url($maxwidth = null, $maxheight = 200) {
332 global $CFG;
333 $logo = get_config('core_admin', 'logo');
334 if (empty($logo)) {
335 return false;
338 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
339 // It's not worth the overhead of detecting and serving 2 different images based on the device.
341 // Hide the requested size in the file path.
342 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
344 // Use $CFG->themerev to prevent browser caching when the file changes.
345 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
346 theme_get_revision(), $logo);
350 * Return the site's compact logo URL, if any.
352 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
353 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
354 * @return moodle_url|false
356 public function get_compact_logo_url($maxwidth = 100, $maxheight = 100) {
357 global $CFG;
358 $logo = get_config('core_admin', 'logocompact');
359 if (empty($logo)) {
360 return false;
363 // Hide the requested size in the file path.
364 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
366 // Use $CFG->themerev to prevent browser caching when the file changes.
367 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
368 theme_get_revision(), $logo);
375 * Basis for all plugin renderers.
377 * @copyright Petr Skoda (skodak)
378 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
379 * @since Moodle 2.0
380 * @package core
381 * @category output
383 class plugin_renderer_base extends renderer_base {
386 * @var renderer_base|core_renderer A reference to the current renderer.
387 * The renderer provided here will be determined by the page but will in 90%
388 * of cases by the {@link core_renderer}
390 protected $output;
393 * Constructor method, calls the parent constructor
395 * @param moodle_page $page
396 * @param string $target one of rendering target constants
398 public function __construct(moodle_page $page, $target) {
399 if (empty($target) && $page->pagelayout === 'maintenance') {
400 // If the page is using the maintenance layout then we're going to force the target to maintenance.
401 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
402 // unavailable for this page layout.
403 $target = RENDERER_TARGET_MAINTENANCE;
405 $this->output = $page->get_renderer('core', null, $target);
406 parent::__construct($page, $target);
410 * Renders the provided widget and returns the HTML to display it.
412 * @param renderable $widget instance with renderable interface
413 * @return string
415 public function render(renderable $widget) {
416 $classname = get_class($widget);
417 // Strip namespaces.
418 $classname = preg_replace('/^.*\\\/', '', $classname);
419 // Keep a copy at this point, we may need to look for a deprecated method.
420 $deprecatedmethod = 'render_'.$classname;
421 // Remove _renderable suffixes
422 $classname = preg_replace('/_renderable$/', '', $classname);
424 $rendermethod = 'render_'.$classname;
425 if (method_exists($this, $rendermethod)) {
426 return $this->$rendermethod($widget);
428 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
429 // This is exactly where we don't want to be.
430 // If you have arrived here you have a renderable component within your plugin that has the name
431 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
432 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
433 // and the _renderable suffix now gets removed when looking for a render method.
434 // You need to change your renderers render_blah_renderable to render_blah.
435 // Until you do this it will not be possible for a theme to override the renderer to override your method.
436 // Please do it ASAP.
437 static $debugged = array();
438 if (!isset($debugged[$deprecatedmethod])) {
439 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
440 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
441 $debugged[$deprecatedmethod] = true;
443 return $this->$deprecatedmethod($widget);
445 // pass to core renderer if method not found here
446 return $this->output->render($widget);
450 * Magic method used to pass calls otherwise meant for the standard renderer
451 * to it to ensure we don't go causing unnecessary grief.
453 * @param string $method
454 * @param array $arguments
455 * @return mixed
457 public function __call($method, $arguments) {
458 if (method_exists('renderer_base', $method)) {
459 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
461 if (method_exists($this->output, $method)) {
462 return call_user_func_array(array($this->output, $method), $arguments);
463 } else {
464 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
471 * The standard implementation of the core_renderer interface.
473 * @copyright 2009 Tim Hunt
474 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
475 * @since Moodle 2.0
476 * @package core
477 * @category output
479 class core_renderer extends renderer_base {
481 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
482 * in layout files instead.
483 * @deprecated
484 * @var string used in {@link core_renderer::header()}.
486 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
489 * @var string Used to pass information from {@link core_renderer::doctype()} to
490 * {@link core_renderer::standard_head_html()}.
492 protected $contenttype;
495 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
496 * with {@link core_renderer::header()}.
498 protected $metarefreshtag = '';
501 * @var string Unique token for the closing HTML
503 protected $unique_end_html_token;
506 * @var string Unique token for performance information
508 protected $unique_performance_info_token;
511 * @var string Unique token for the main content.
513 protected $unique_main_content_token;
516 * Constructor
518 * @param moodle_page $page the page we are doing output for.
519 * @param string $target one of rendering target constants
521 public function __construct(moodle_page $page, $target) {
522 $this->opencontainers = $page->opencontainers;
523 $this->page = $page;
524 $this->target = $target;
526 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
527 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
528 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
532 * Get the DOCTYPE declaration that should be used with this page. Designed to
533 * be called in theme layout.php files.
535 * @return string the DOCTYPE declaration that should be used.
537 public function doctype() {
538 if ($this->page->theme->doctype === 'html5') {
539 $this->contenttype = 'text/html; charset=utf-8';
540 return "<!DOCTYPE html>\n";
542 } else if ($this->page->theme->doctype === 'xhtml5') {
543 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
544 return "<!DOCTYPE html>\n";
546 } else {
547 // legacy xhtml 1.0
548 $this->contenttype = 'text/html; charset=utf-8';
549 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
554 * The attributes that should be added to the <html> tag. Designed to
555 * be called in theme layout.php files.
557 * @return string HTML fragment.
559 public function htmlattributes() {
560 $return = get_html_lang(true);
561 $attributes = array();
562 if ($this->page->theme->doctype !== 'html5') {
563 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
566 // Give plugins an opportunity to add things like xml namespaces to the html element.
567 // This function should return an array of html attribute names => values.
568 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
569 foreach ($pluginswithfunction as $plugins) {
570 foreach ($plugins as $function) {
571 $newattrs = $function();
572 unset($newattrs['dir']);
573 unset($newattrs['lang']);
574 unset($newattrs['xmlns']);
575 unset($newattrs['xml:lang']);
576 $attributes += $newattrs;
580 foreach ($attributes as $key => $val) {
581 $val = s($val);
582 $return .= " $key=\"$val\"";
585 return $return;
589 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
590 * that should be included in the <head> tag. Designed to be called in theme
591 * layout.php files.
593 * @return string HTML fragment.
595 public function standard_head_html() {
596 global $CFG, $SESSION;
598 // Before we output any content, we need to ensure that certain
599 // page components are set up.
601 // Blocks must be set up early as they may require javascript which
602 // has to be included in the page header before output is created.
603 foreach ($this->page->blocks->get_regions() as $region) {
604 $this->page->blocks->ensure_content_created($region, $this);
607 $output = '';
609 // Give plugins an opportunity to add any head elements. The callback
610 // must always return a string containing valid html head content.
611 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
612 foreach ($pluginswithfunction as $plugins) {
613 foreach ($plugins as $function) {
614 $output .= $function();
618 // Allow a url_rewrite plugin to setup any dynamic head content.
619 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
620 $class = $CFG->urlrewriteclass;
621 $output .= $class::html_head_setup();
624 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
625 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
626 // This is only set by the {@link redirect()} method
627 $output .= $this->metarefreshtag;
629 // Check if a periodic refresh delay has been set and make sure we arn't
630 // already meta refreshing
631 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
632 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
635 // Set up help link popups for all links with the helptooltip class
636 $this->page->requires->js_init_call('M.util.help_popups.setup');
638 $focus = $this->page->focuscontrol;
639 if (!empty($focus)) {
640 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
641 // This is a horrifically bad way to handle focus but it is passed in
642 // through messy formslib::moodleform
643 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
644 } else if (strpos($focus, '.')!==false) {
645 // Old style of focus, bad way to do it
646 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);
647 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
648 } else {
649 // Focus element with given id
650 $this->page->requires->js_function_call('focuscontrol', array($focus));
654 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
655 // any other custom CSS can not be overridden via themes and is highly discouraged
656 $urls = $this->page->theme->css_urls($this->page);
657 foreach ($urls as $url) {
658 $this->page->requires->css_theme($url);
661 // Get the theme javascript head and footer
662 if ($jsurl = $this->page->theme->javascript_url(true)) {
663 $this->page->requires->js($jsurl, true);
665 if ($jsurl = $this->page->theme->javascript_url(false)) {
666 $this->page->requires->js($jsurl);
669 // Get any HTML from the page_requirements_manager.
670 $output .= $this->page->requires->get_head_code($this->page, $this);
672 // List alternate versions.
673 foreach ($this->page->alternateversions as $type => $alt) {
674 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
675 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
678 // Add noindex tag if relevant page and setting applied.
679 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
680 $loginpages = array('login-index', 'login-signup');
681 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
682 if (!isset($CFG->additionalhtmlhead)) {
683 $CFG->additionalhtmlhead = '';
685 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
688 if (!empty($CFG->additionalhtmlhead)) {
689 $output .= "\n".$CFG->additionalhtmlhead;
692 return $output;
696 * The standard tags (typically skip links) that should be output just inside
697 * the start of the <body> tag. Designed to be called in theme layout.php files.
699 * @return string HTML fragment.
701 public function standard_top_of_body_html() {
702 global $CFG;
703 $output = $this->page->requires->get_top_of_body_code($this);
704 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
705 $output .= "\n".$CFG->additionalhtmltopofbody;
708 // Give subsystems an opportunity to inject extra html content. The callback
709 // must always return a string containing valid html.
710 foreach (\core_component::get_core_subsystems() as $name => $path) {
711 if ($path) {
712 $output .= component_callback($name, 'before_standard_top_of_body_html', [], '');
716 // Give plugins an opportunity to inject extra html content. The callback
717 // must always return a string containing valid html.
718 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
719 foreach ($pluginswithfunction as $plugins) {
720 foreach ($plugins as $function) {
721 $output .= $function();
725 $output .= $this->maintenance_warning();
727 return $output;
731 * Scheduled maintenance warning message.
733 * Note: This is a nasty hack to display maintenance notice, this should be moved
734 * to some general notification area once we have it.
736 * @return string
738 public function maintenance_warning() {
739 global $CFG;
741 $output = '';
742 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
743 $timeleft = $CFG->maintenance_later - time();
744 // If timeleft less than 30 sec, set the class on block to error to highlight.
745 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
746 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-a-1 alert');
747 $a = new stdClass();
748 $a->hour = (int)($timeleft / 3600);
749 $a->min = (int)(($timeleft / 60) % 60);
750 $a->sec = (int)($timeleft % 60);
751 if ($a->hour > 0) {
752 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
753 } else {
754 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
757 $output .= $this->box_end();
758 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
759 array(array('timeleftinsec' => $timeleft)));
760 $this->page->requires->strings_for_js(
761 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
762 'admin');
764 return $output;
768 * The standard tags (typically performance information and validation links,
769 * if we are in developer debug mode) that should be output in the footer area
770 * of the page. Designed to be called in theme layout.php files.
772 * @return string HTML fragment.
774 public function standard_footer_html() {
775 global $CFG, $SCRIPT;
777 $output = '';
778 if (during_initial_install()) {
779 // Debugging info can not work before install is finished,
780 // in any case we do not want any links during installation!
781 return $output;
784 // Give plugins an opportunity to add any footer elements.
785 // The callback must always return a string containing valid html footer content.
786 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
787 foreach ($pluginswithfunction as $plugins) {
788 foreach ($plugins as $function) {
789 $output .= $function();
793 // This function is normally called from a layout.php file in {@link core_renderer::header()}
794 // but some of the content won't be known until later, so we return a placeholder
795 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
796 $output .= $this->unique_performance_info_token;
797 if ($this->page->devicetypeinuse == 'legacy') {
798 // The legacy theme is in use print the notification
799 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
802 // Get links to switch device types (only shown for users not on a default device)
803 $output .= $this->theme_switch_links();
805 if (!empty($CFG->debugpageinfo)) {
806 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
807 $this->page->debug_summary()) . '</div>';
809 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
810 // Add link to profiling report if necessary
811 if (function_exists('profiling_is_running') && profiling_is_running()) {
812 $txt = get_string('profiledscript', 'admin');
813 $title = get_string('profiledscriptview', 'admin');
814 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
815 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
816 $output .= '<div class="profilingfooter">' . $link . '</div>';
818 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
819 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
820 $output .= '<div class="purgecaches">' .
821 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
823 if (!empty($CFG->debugvalidators)) {
824 // NOTE: this is not a nice hack, $PAGE->url is not always accurate and $FULLME neither, it is not a bug if it fails. --skodak
825 $output .= '<div class="validators"><ul class="list-unstyled m-l-1">
826 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
827 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
828 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&amp;warnp2n3e=1&amp;url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
829 </ul></div>';
831 return $output;
835 * Returns standard main content placeholder.
836 * Designed to be called in theme layout.php files.
838 * @return string HTML fragment.
840 public function main_content() {
841 // This is here because it is the only place we can inject the "main" role over the entire main content area
842 // without requiring all theme's to manually do it, and without creating yet another thing people need to
843 // remember in the theme.
844 // This is an unfortunate hack. DO NO EVER add anything more here.
845 // DO NOT add classes.
846 // DO NOT add an id.
847 return '<div role="main">'.$this->unique_main_content_token.'</div>';
851 * Returns standard navigation between activities in a course.
853 * @return string the navigation HTML.
855 public function activity_navigation() {
856 // First we should check if we want to add navigation.
857 $context = $this->page->context;
858 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
859 || $context->contextlevel != CONTEXT_MODULE) {
860 return '';
863 // If the activity is in stealth mode, show no links.
864 if ($this->page->cm->is_stealth()) {
865 return '';
868 // Get a list of all the activities in the course.
869 $course = $this->page->cm->get_course();
870 $modules = get_fast_modinfo($course->id)->get_cms();
872 // Put the modules into an array in order by the position they are shown in the course.
873 $mods = [];
874 $activitylist = [];
875 foreach ($modules as $module) {
876 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
877 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
878 continue;
880 $mods[$module->id] = $module;
882 // No need to add the current module to the list for the activity dropdown menu.
883 if ($module->id == $this->page->cm->id) {
884 continue;
886 // Module name.
887 $modname = $module->get_formatted_name();
888 // Display the hidden text if necessary.
889 if (!$module->visible) {
890 $modname .= ' ' . get_string('hiddenwithbrackets');
892 // Module URL.
893 $linkurl = new moodle_url($module->url, array('forceview' => 1));
894 // Add module URL (as key) and name (as value) to the activity list array.
895 $activitylist[$linkurl->out(false)] = $modname;
898 $nummods = count($mods);
900 // If there is only one mod then do nothing.
901 if ($nummods == 1) {
902 return '';
905 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
906 $modids = array_keys($mods);
908 // Get the position in the array of the course module we are viewing.
909 $position = array_search($this->page->cm->id, $modids);
911 $prevmod = null;
912 $nextmod = null;
914 // Check if we have a previous mod to show.
915 if ($position > 0) {
916 $prevmod = $mods[$modids[$position - 1]];
919 // Check if we have a next mod to show.
920 if ($position < ($nummods - 1)) {
921 $nextmod = $mods[$modids[$position + 1]];
924 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
925 $renderer = $this->page->get_renderer('core', 'course');
926 return $renderer->render($activitynav);
930 * The standard tags (typically script tags that are not needed earlier) that
931 * should be output after everything else. Designed to be called in theme layout.php files.
933 * @return string HTML fragment.
935 public function standard_end_of_body_html() {
936 global $CFG;
938 // This function is normally called from a layout.php file in {@link core_renderer::header()}
939 // but some of the content won't be known until later, so we return a placeholder
940 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
941 $output = '';
942 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
943 $output .= "\n".$CFG->additionalhtmlfooter;
945 $output .= $this->unique_end_html_token;
946 return $output;
950 * The standard HTML that should be output just before the <footer> tag.
951 * Designed to be called in theme layout.php files.
953 * @return string HTML fragment.
955 public function standard_after_main_region_html() {
956 global $CFG;
957 $output = '';
958 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlbottomofbody)) {
959 $output .= "\n".$CFG->additionalhtmlbottomofbody;
962 // Give subsystems an opportunity to inject extra html content. The callback
963 // must always return a string containing valid html.
964 foreach (\core_component::get_core_subsystems() as $name => $path) {
965 if ($path) {
966 $output .= component_callback($name, 'standard_after_main_region_html', [], '');
970 // Give plugins an opportunity to inject extra html content. The callback
971 // must always return a string containing valid html.
972 $pluginswithfunction = get_plugins_with_function('standard_after_main_region_html', 'lib.php');
973 foreach ($pluginswithfunction as $plugins) {
974 foreach ($plugins as $function) {
975 $output .= $function();
979 return $output;
983 * Return the standard string that says whether you are logged in (and switched
984 * roles/logged in as another user).
985 * @param bool $withlinks if false, then don't include any links in the HTML produced.
986 * If not set, the default is the nologinlinks option from the theme config.php file,
987 * and if that is not set, then links are included.
988 * @return string HTML fragment.
990 public function login_info($withlinks = null) {
991 global $USER, $CFG, $DB, $SESSION;
993 if (during_initial_install()) {
994 return '';
997 if (is_null($withlinks)) {
998 $withlinks = empty($this->page->layout_options['nologinlinks']);
1001 $course = $this->page->course;
1002 if (\core\session\manager::is_loggedinas()) {
1003 $realuser = \core\session\manager::get_realuser();
1004 $fullname = fullname($realuser, true);
1005 if ($withlinks) {
1006 $loginastitle = get_string('loginas');
1007 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
1008 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
1009 } else {
1010 $realuserinfo = " [$fullname] ";
1012 } else {
1013 $realuserinfo = '';
1016 $loginpage = $this->is_login_page();
1017 $loginurl = get_login_url();
1019 if (empty($course->id)) {
1020 // $course->id is not defined during installation
1021 return '';
1022 } else if (isloggedin()) {
1023 $context = context_course::instance($course->id);
1025 $fullname = fullname($USER, true);
1026 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
1027 if ($withlinks) {
1028 $linktitle = get_string('viewprofile');
1029 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
1030 } else {
1031 $username = $fullname;
1033 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
1034 if ($withlinks) {
1035 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1036 } else {
1037 $username .= " from {$idprovider->name}";
1040 if (isguestuser()) {
1041 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1042 if (!$loginpage && $withlinks) {
1043 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1045 } else if (is_role_switched($course->id)) { // Has switched roles
1046 $rolename = '';
1047 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1048 $rolename = ': '.role_get_name($role, $context);
1050 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1051 if ($withlinks) {
1052 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1053 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1055 } else {
1056 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1057 if ($withlinks) {
1058 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1061 } else {
1062 $loggedinas = get_string('loggedinnot', 'moodle');
1063 if (!$loginpage && $withlinks) {
1064 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1068 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1070 if (isset($SESSION->justloggedin)) {
1071 unset($SESSION->justloggedin);
1072 if (!empty($CFG->displayloginfailures)) {
1073 if (!isguestuser()) {
1074 // Include this file only when required.
1075 require_once($CFG->dirroot . '/user/lib.php');
1076 if ($count = user_count_login_failures($USER)) {
1077 $loggedinas .= '<div class="loginfailures">';
1078 $a = new stdClass();
1079 $a->attempts = $count;
1080 $loggedinas .= get_string('failedloginattempts', '', $a);
1081 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1082 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1083 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1085 $loggedinas .= '</div>';
1091 return $loggedinas;
1095 * Check whether the current page is a login page.
1097 * @since Moodle 2.9
1098 * @return bool
1100 protected function is_login_page() {
1101 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1102 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1103 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1104 return in_array(
1105 $this->page->url->out_as_local_url(false, array()),
1106 array(
1107 '/login/index.php',
1108 '/login/forgot_password.php',
1114 * Return the 'back' link that normally appears in the footer.
1116 * @return string HTML fragment.
1118 public function home_link() {
1119 global $CFG, $SITE;
1121 if ($this->page->pagetype == 'site-index') {
1122 // Special case for site home page - please do not remove
1123 return '<div class="sitelink">' .
1124 '<a title="Moodle" href="http://moodle.org/">' .
1125 '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1127 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1128 // Special case for during install/upgrade.
1129 return '<div class="sitelink">'.
1130 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1131 '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1133 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1134 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1135 get_string('home') . '</a></div>';
1137 } else {
1138 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1139 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1144 * Redirects the user by any means possible given the current state
1146 * This function should not be called directly, it should always be called using
1147 * the redirect function in lib/weblib.php
1149 * The redirect function should really only be called before page output has started
1150 * however it will allow itself to be called during the state STATE_IN_BODY
1152 * @param string $encodedurl The URL to send to encoded if required
1153 * @param string $message The message to display to the user if any
1154 * @param int $delay The delay before redirecting a user, if $message has been
1155 * set this is a requirement and defaults to 3, set to 0 no delay
1156 * @param boolean $debugdisableredirect this redirect has been disabled for
1157 * debugging purposes. Display a message that explains, and don't
1158 * trigger the redirect.
1159 * @param string $messagetype The type of notification to show the message in.
1160 * See constants on \core\output\notification.
1161 * @return string The HTML to display to the user before dying, may contain
1162 * meta refresh, javascript refresh, and may have set header redirects
1164 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1165 $messagetype = \core\output\notification::NOTIFY_INFO) {
1166 global $CFG;
1167 $url = str_replace('&amp;', '&', $encodedurl);
1169 switch ($this->page->state) {
1170 case moodle_page::STATE_BEFORE_HEADER :
1171 // No output yet it is safe to delivery the full arsenal of redirect methods
1172 if (!$debugdisableredirect) {
1173 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1174 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1175 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1177 $output = $this->header();
1178 break;
1179 case moodle_page::STATE_PRINTING_HEADER :
1180 // We should hopefully never get here
1181 throw new coding_exception('You cannot redirect while printing the page header');
1182 break;
1183 case moodle_page::STATE_IN_BODY :
1184 // We really shouldn't be here but we can deal with this
1185 debugging("You should really redirect before you start page output");
1186 if (!$debugdisableredirect) {
1187 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1189 $output = $this->opencontainers->pop_all_but_last();
1190 break;
1191 case moodle_page::STATE_DONE :
1192 // Too late to be calling redirect now
1193 throw new coding_exception('You cannot redirect after the entire page has been generated');
1194 break;
1196 $output .= $this->notification($message, $messagetype);
1197 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1198 if ($debugdisableredirect) {
1199 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1201 $output .= $this->footer();
1202 return $output;
1206 * Start output by sending the HTTP headers, and printing the HTML <head>
1207 * and the start of the <body>.
1209 * To control what is printed, you should set properties on $PAGE. If you
1210 * are familiar with the old {@link print_header()} function from Moodle 1.9
1211 * you will find that there are properties on $PAGE that correspond to most
1212 * of the old parameters to could be passed to print_header.
1214 * Not that, in due course, the remaining $navigation, $menu parameters here
1215 * will be replaced by more properties of $PAGE, but that is still to do.
1217 * @return string HTML that you must output this, preferably immediately.
1219 public function header() {
1220 global $USER, $CFG, $SESSION;
1222 // Give plugins an opportunity touch things before the http headers are sent
1223 // such as adding additional headers. The return value is ignored.
1224 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1225 foreach ($pluginswithfunction as $plugins) {
1226 foreach ($plugins as $function) {
1227 $function();
1231 if (\core\session\manager::is_loggedinas()) {
1232 $this->page->add_body_class('userloggedinas');
1235 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1236 require_once($CFG->dirroot . '/user/lib.php');
1237 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1238 if ($count = user_count_login_failures($USER, false)) {
1239 $this->page->add_body_class('loginfailures');
1243 // If the user is logged in, and we're not in initial install,
1244 // check to see if the user is role-switched and add the appropriate
1245 // CSS class to the body element.
1246 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1247 $this->page->add_body_class('userswitchedrole');
1250 // Give themes a chance to init/alter the page object.
1251 $this->page->theme->init_page($this->page);
1253 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1255 // Find the appropriate page layout file, based on $this->page->pagelayout.
1256 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1257 // Render the layout using the layout file.
1258 $rendered = $this->render_page_layout($layoutfile);
1260 // Slice the rendered output into header and footer.
1261 $cutpos = strpos($rendered, $this->unique_main_content_token);
1262 if ($cutpos === false) {
1263 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1264 $token = self::MAIN_CONTENT_TOKEN;
1265 } else {
1266 $token = $this->unique_main_content_token;
1269 if ($cutpos === false) {
1270 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.');
1272 $header = substr($rendered, 0, $cutpos);
1273 $footer = substr($rendered, $cutpos + strlen($token));
1275 if (empty($this->contenttype)) {
1276 debugging('The page layout file did not call $OUTPUT->doctype()');
1277 $header = $this->doctype() . $header;
1280 // If this theme version is below 2.4 release and this is a course view page
1281 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1282 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1283 // check if course content header/footer have not been output during render of theme layout
1284 $coursecontentheader = $this->course_content_header(true);
1285 $coursecontentfooter = $this->course_content_footer(true);
1286 if (!empty($coursecontentheader)) {
1287 // display debug message and add header and footer right above and below main content
1288 // Please note that course header and footer (to be displayed above and below the whole page)
1289 // are not displayed in this case at all.
1290 // Besides the content header and footer are not displayed on any other course page
1291 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);
1292 $header .= $coursecontentheader;
1293 $footer = $coursecontentfooter. $footer;
1297 send_headers($this->contenttype, $this->page->cacheable);
1299 $this->opencontainers->push('header/footer', $footer);
1300 $this->page->set_state(moodle_page::STATE_IN_BODY);
1302 return $header . $this->skip_link_target('maincontent');
1306 * Renders and outputs the page layout file.
1308 * This is done by preparing the normal globals available to a script, and
1309 * then including the layout file provided by the current theme for the
1310 * requested layout.
1312 * @param string $layoutfile The name of the layout file
1313 * @return string HTML code
1315 protected function render_page_layout($layoutfile) {
1316 global $CFG, $SITE, $USER;
1317 // The next lines are a bit tricky. The point is, here we are in a method
1318 // of a renderer class, and this object may, or may not, be the same as
1319 // the global $OUTPUT object. When rendering the page layout file, we want to use
1320 // this object. However, people writing Moodle code expect the current
1321 // renderer to be called $OUTPUT, not $this, so define a variable called
1322 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1323 $OUTPUT = $this;
1324 $PAGE = $this->page;
1325 $COURSE = $this->page->course;
1327 ob_start();
1328 include($layoutfile);
1329 $rendered = ob_get_contents();
1330 ob_end_clean();
1331 return $rendered;
1335 * Outputs the page's footer
1337 * @return string HTML fragment
1339 public function footer() {
1340 global $CFG, $DB, $PAGE;
1342 // Give plugins an opportunity to touch the page before JS is finalized.
1343 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1344 foreach ($pluginswithfunction as $plugins) {
1345 foreach ($plugins as $function) {
1346 $function();
1350 $output = $this->container_end_all(true);
1352 $footer = $this->opencontainers->pop('header/footer');
1354 if (debugging() and $DB and $DB->is_transaction_started()) {
1355 // TODO: MDL-20625 print warning - transaction will be rolled back
1358 // Provide some performance info if required
1359 $performanceinfo = '';
1360 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1361 $perf = get_performance_info();
1362 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1363 $performanceinfo = $perf['html'];
1367 // We always want performance data when running a performance test, even if the user is redirected to another page.
1368 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1369 $footer = $this->unique_performance_info_token . $footer;
1371 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1373 // Only show notifications when we have a $PAGE context id.
1374 if (!empty($PAGE->context->id)) {
1375 $this->page->requires->js_call_amd('core/notification', 'init', array(
1376 $PAGE->context->id,
1377 \core\notification::fetch_as_array($this)
1380 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1382 $this->page->set_state(moodle_page::STATE_DONE);
1384 return $output . $footer;
1388 * Close all but the last open container. This is useful in places like error
1389 * handling, where you want to close all the open containers (apart from <body>)
1390 * before outputting the error message.
1392 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1393 * developer debug warning if it isn't.
1394 * @return string the HTML required to close any open containers inside <body>.
1396 public function container_end_all($shouldbenone = false) {
1397 return $this->opencontainers->pop_all_but_last($shouldbenone);
1401 * Returns course-specific information to be output immediately above content on any course page
1402 * (for the current course)
1404 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1405 * @return string
1407 public function course_content_header($onlyifnotcalledbefore = false) {
1408 global $CFG;
1409 static $functioncalled = false;
1410 if ($functioncalled && $onlyifnotcalledbefore) {
1411 // we have already output the content header
1412 return '';
1415 // Output any session notification.
1416 $notifications = \core\notification::fetch();
1418 $bodynotifications = '';
1419 foreach ($notifications as $notification) {
1420 $bodynotifications .= $this->render_from_template(
1421 $notification->get_template_name(),
1422 $notification->export_for_template($this)
1426 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1428 if ($this->page->course->id == SITEID) {
1429 // return immediately and do not include /course/lib.php if not necessary
1430 return $output;
1433 require_once($CFG->dirroot.'/course/lib.php');
1434 $functioncalled = true;
1435 $courseformat = course_get_format($this->page->course);
1436 if (($obj = $courseformat->course_content_header()) !== null) {
1437 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1439 return $output;
1443 * Returns course-specific information to be output immediately below content on any course page
1444 * (for the current course)
1446 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1447 * @return string
1449 public function course_content_footer($onlyifnotcalledbefore = false) {
1450 global $CFG;
1451 if ($this->page->course->id == SITEID) {
1452 // return immediately and do not include /course/lib.php if not necessary
1453 return '';
1455 static $functioncalled = false;
1456 if ($functioncalled && $onlyifnotcalledbefore) {
1457 // we have already output the content footer
1458 return '';
1460 $functioncalled = true;
1461 require_once($CFG->dirroot.'/course/lib.php');
1462 $courseformat = course_get_format($this->page->course);
1463 if (($obj = $courseformat->course_content_footer()) !== null) {
1464 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1466 return '';
1470 * Returns course-specific information to be output on any course page in the header area
1471 * (for the current course)
1473 * @return string
1475 public function course_header() {
1476 global $CFG;
1477 if ($this->page->course->id == SITEID) {
1478 // return immediately and do not include /course/lib.php if not necessary
1479 return '';
1481 require_once($CFG->dirroot.'/course/lib.php');
1482 $courseformat = course_get_format($this->page->course);
1483 if (($obj = $courseformat->course_header()) !== null) {
1484 return $courseformat->get_renderer($this->page)->render($obj);
1486 return '';
1490 * Returns course-specific information to be output on any course page in the footer area
1491 * (for the current course)
1493 * @return string
1495 public function course_footer() {
1496 global $CFG;
1497 if ($this->page->course->id == SITEID) {
1498 // return immediately and do not include /course/lib.php if not necessary
1499 return '';
1501 require_once($CFG->dirroot.'/course/lib.php');
1502 $courseformat = course_get_format($this->page->course);
1503 if (($obj = $courseformat->course_footer()) !== null) {
1504 return $courseformat->get_renderer($this->page)->render($obj);
1506 return '';
1510 * Returns lang menu or '', this method also checks forcing of languages in courses.
1512 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1514 * @return string The lang menu HTML or empty string
1516 public function lang_menu() {
1517 global $CFG;
1519 if (empty($CFG->langmenu)) {
1520 return '';
1523 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1524 // do not show lang menu if language forced
1525 return '';
1528 $currlang = current_language();
1529 $langs = get_string_manager()->get_list_of_translations();
1531 if (count($langs) < 2) {
1532 return '';
1535 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1536 $s->label = get_accesshide(get_string('language'));
1537 $s->class = 'langmenu';
1538 return $this->render($s);
1542 * Output the row of editing icons for a block, as defined by the controls array.
1544 * @param array $controls an array like {@link block_contents::$controls}.
1545 * @param string $blockid The ID given to the block.
1546 * @return string HTML fragment.
1548 public function block_controls($actions, $blockid = null) {
1549 global $CFG;
1550 if (empty($actions)) {
1551 return '';
1553 $menu = new action_menu($actions);
1554 if ($blockid !== null) {
1555 $menu->set_owner_selector('#'.$blockid);
1557 $menu->set_constraint('.block-region');
1558 $menu->attributes['class'] .= ' block-control-actions commands';
1559 return $this->render($menu);
1563 * Returns the HTML for a basic textarea field.
1565 * @param string $name Name to use for the textarea element
1566 * @param string $id The id to use fort he textarea element
1567 * @param string $value Initial content to display in the textarea
1568 * @param int $rows Number of rows to display
1569 * @param int $cols Number of columns to display
1570 * @return string the HTML to display
1572 public function print_textarea($name, $id, $value, $rows, $cols) {
1573 global $OUTPUT;
1575 editors_head_setup();
1576 $editor = editors_get_preferred_editor(FORMAT_HTML);
1577 $editor->set_text($value);
1578 $editor->use_editor($id, []);
1580 $context = [
1581 'id' => $id,
1582 'name' => $name,
1583 'value' => $value,
1584 'rows' => $rows,
1585 'cols' => $cols
1588 return $OUTPUT->render_from_template('core_form/editor_textarea', $context);
1592 * Renders an action menu component.
1594 * ARIA references:
1595 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1596 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1598 * @param action_menu $menu
1599 * @return string HTML
1601 public function render_action_menu(action_menu $menu) {
1602 $context = $menu->export_for_template($this);
1603 return $this->render_from_template('core/action_menu', $context);
1607 * Renders an action_menu_link item.
1609 * @param action_menu_link $action
1610 * @return string HTML fragment
1612 protected function render_action_menu_link(action_menu_link $action) {
1613 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1617 * Renders a primary action_menu_filler item.
1619 * @param action_menu_link_filler $action
1620 * @return string HTML fragment
1622 protected function render_action_menu_filler(action_menu_filler $action) {
1623 return html_writer::span('&nbsp;', 'filler');
1627 * Renders a primary action_menu_link item.
1629 * @param action_menu_link_primary $action
1630 * @return string HTML fragment
1632 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1633 return $this->render_action_menu_link($action);
1637 * Renders a secondary action_menu_link item.
1639 * @param action_menu_link_secondary $action
1640 * @return string HTML fragment
1642 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1643 return $this->render_action_menu_link($action);
1647 * Prints a nice side block with an optional header.
1649 * The content is described
1650 * by a {@link core_renderer::block_contents} object.
1652 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1653 * <div class="header"></div>
1654 * <div class="content">
1655 * ...CONTENT...
1656 * <div class="footer">
1657 * </div>
1658 * </div>
1659 * <div class="annotation">
1660 * </div>
1661 * </div>
1663 * @param block_contents $bc HTML for the content
1664 * @param string $region the region the block is appearing in.
1665 * @return string the HTML to be output.
1667 public function block(block_contents $bc, $region) {
1668 $bc = clone($bc); // Avoid messing up the object passed in.
1669 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1670 $bc->collapsible = block_contents::NOT_HIDEABLE;
1672 if (!empty($bc->blockinstanceid)) {
1673 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1675 $skiptitle = strip_tags($bc->title);
1676 if ($bc->blockinstanceid && !empty($skiptitle)) {
1677 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1678 } else if (!empty($bc->arialabel)) {
1679 $bc->attributes['aria-label'] = $bc->arialabel;
1681 if ($bc->dockable) {
1682 $bc->attributes['data-dockable'] = 1;
1684 if ($bc->collapsible == block_contents::HIDDEN) {
1685 $bc->add_class('hidden');
1687 if (!empty($bc->controls)) {
1688 $bc->add_class('block_with_controls');
1692 if (empty($skiptitle)) {
1693 $output = '';
1694 $skipdest = '';
1695 } else {
1696 $output = html_writer::link('#sb-'.$bc->skipid, get_string('skipa', 'access', $skiptitle),
1697 array('class' => 'skip skip-block', 'id' => 'fsb-' . $bc->skipid));
1698 $skipdest = html_writer::span('', 'skip-block-to',
1699 array('id' => 'sb-' . $bc->skipid));
1702 $output .= html_writer::start_tag('div', $bc->attributes);
1704 $output .= $this->block_header($bc);
1705 $output .= $this->block_content($bc);
1707 $output .= html_writer::end_tag('div');
1709 $output .= $this->block_annotation($bc);
1711 $output .= $skipdest;
1713 $this->init_block_hider_js($bc);
1714 return $output;
1718 * Produces a header for a block
1720 * @param block_contents $bc
1721 * @return string
1723 protected function block_header(block_contents $bc) {
1725 $title = '';
1726 if ($bc->title) {
1727 $attributes = array();
1728 if ($bc->blockinstanceid) {
1729 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1731 $title = html_writer::tag('h2', $bc->title, $attributes);
1734 $blockid = null;
1735 if (isset($bc->attributes['id'])) {
1736 $blockid = $bc->attributes['id'];
1738 $controlshtml = $this->block_controls($bc->controls, $blockid);
1740 $output = '';
1741 if ($title || $controlshtml) {
1742 $output .= html_writer::tag('div', html_writer::tag('div', html_writer::tag('div', '', array('class'=>'block_action')). $title . $controlshtml, array('class' => 'title')), array('class' => 'header'));
1744 return $output;
1748 * Produces the content area for a block
1750 * @param block_contents $bc
1751 * @return string
1753 protected function block_content(block_contents $bc) {
1754 $output = html_writer::start_tag('div', array('class' => 'content'));
1755 if (!$bc->title && !$this->block_controls($bc->controls)) {
1756 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1758 $output .= $bc->content;
1759 $output .= $this->block_footer($bc);
1760 $output .= html_writer::end_tag('div');
1762 return $output;
1766 * Produces the footer for a block
1768 * @param block_contents $bc
1769 * @return string
1771 protected function block_footer(block_contents $bc) {
1772 $output = '';
1773 if ($bc->footer) {
1774 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1776 return $output;
1780 * Produces the annotation for a block
1782 * @param block_contents $bc
1783 * @return string
1785 protected function block_annotation(block_contents $bc) {
1786 $output = '';
1787 if ($bc->annotation) {
1788 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1790 return $output;
1794 * Calls the JS require function to hide a block.
1796 * @param block_contents $bc A block_contents object
1798 protected function init_block_hider_js(block_contents $bc) {
1799 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1800 $config = new stdClass;
1801 $config->id = $bc->attributes['id'];
1802 $config->title = strip_tags($bc->title);
1803 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1804 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1805 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1807 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1808 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1813 * Render the contents of a block_list.
1815 * @param array $icons the icon for each item.
1816 * @param array $items the content of each item.
1817 * @return string HTML
1819 public function list_block_contents($icons, $items) {
1820 $row = 0;
1821 $lis = array();
1822 foreach ($items as $key => $string) {
1823 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1824 if (!empty($icons[$key])) { //test if the content has an assigned icon
1825 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1827 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1828 $item .= html_writer::end_tag('li');
1829 $lis[] = $item;
1830 $row = 1 - $row; // Flip even/odd.
1832 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1836 * Output all the blocks in a particular region.
1838 * @param string $region the name of a region on this page.
1839 * @return string the HTML to be output.
1841 public function blocks_for_region($region) {
1842 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1843 $blocks = $this->page->blocks->get_blocks_for_region($region);
1844 $lastblock = null;
1845 $zones = array();
1846 foreach ($blocks as $block) {
1847 $zones[] = $block->title;
1849 $output = '';
1851 foreach ($blockcontents as $bc) {
1852 if ($bc instanceof block_contents) {
1853 $output .= $this->block($bc, $region);
1854 $lastblock = $bc->title;
1855 } else if ($bc instanceof block_move_target) {
1856 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1857 } else {
1858 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1861 return $output;
1865 * Output a place where the block that is currently being moved can be dropped.
1867 * @param block_move_target $target with the necessary details.
1868 * @param array $zones array of areas where the block can be moved to
1869 * @param string $previous the block located before the area currently being rendered.
1870 * @param string $region the name of the region
1871 * @return string the HTML to be output.
1873 public function block_move_target($target, $zones, $previous, $region) {
1874 if ($previous == null) {
1875 if (empty($zones)) {
1876 // There are no zones, probably because there are no blocks.
1877 $regions = $this->page->theme->get_all_block_regions();
1878 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1879 } else {
1880 $position = get_string('moveblockbefore', 'block', $zones[0]);
1882 } else {
1883 $position = get_string('moveblockafter', 'block', $previous);
1885 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1889 * Renders a special html link with attached action
1891 * Theme developers: DO NOT OVERRIDE! Please override function
1892 * {@link core_renderer::render_action_link()} instead.
1894 * @param string|moodle_url $url
1895 * @param string $text HTML fragment
1896 * @param component_action $action
1897 * @param array $attributes associative array of html link attributes + disabled
1898 * @param pix_icon optional pix icon to render with the link
1899 * @return string HTML fragment
1901 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1902 if (!($url instanceof moodle_url)) {
1903 $url = new moodle_url($url);
1905 $link = new action_link($url, $text, $action, $attributes, $icon);
1907 return $this->render($link);
1911 * Renders an action_link object.
1913 * The provided link is renderer and the HTML returned. At the same time the
1914 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1916 * @param action_link $link
1917 * @return string HTML fragment
1919 protected function render_action_link(action_link $link) {
1920 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1924 * Renders an action_icon.
1926 * This function uses the {@link core_renderer::action_link()} method for the
1927 * most part. What it does different is prepare the icon as HTML and use it
1928 * as the link text.
1930 * Theme developers: If you want to change how action links and/or icons are rendered,
1931 * consider overriding function {@link core_renderer::render_action_link()} and
1932 * {@link core_renderer::render_pix_icon()}.
1934 * @param string|moodle_url $url A string URL or moodel_url
1935 * @param pix_icon $pixicon
1936 * @param component_action $action
1937 * @param array $attributes associative array of html link attributes + disabled
1938 * @param bool $linktext show title next to image in link
1939 * @return string HTML fragment
1941 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1942 if (!($url instanceof moodle_url)) {
1943 $url = new moodle_url($url);
1945 $attributes = (array)$attributes;
1947 if (empty($attributes['class'])) {
1948 // let ppl override the class via $options
1949 $attributes['class'] = 'action-icon';
1952 $icon = $this->render($pixicon);
1954 if ($linktext) {
1955 $text = $pixicon->attributes['alt'];
1956 } else {
1957 $text = '';
1960 return $this->action_link($url, $text.$icon, $action, $attributes);
1964 * Print a message along with button choices for Continue/Cancel
1966 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1968 * @param string $message The question to ask the user
1969 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1970 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1971 * @return string HTML fragment
1973 public function confirm($message, $continue, $cancel) {
1974 if ($continue instanceof single_button) {
1975 // ok
1976 $continue->primary = true;
1977 } else if (is_string($continue)) {
1978 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1979 } else if ($continue instanceof moodle_url) {
1980 $continue = new single_button($continue, get_string('continue'), 'post', true);
1981 } else {
1982 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1985 if ($cancel instanceof single_button) {
1986 // ok
1987 } else if (is_string($cancel)) {
1988 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1989 } else if ($cancel instanceof moodle_url) {
1990 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1991 } else {
1992 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1995 $attributes = [
1996 'role'=>'alertdialog',
1997 'aria-labelledby'=>'modal-header',
1998 'aria-describedby'=>'modal-body',
1999 'aria-modal'=>'true'
2002 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
2003 $output .= $this->box_start('modal-content', 'modal-content');
2004 $output .= $this->box_start('modal-header p-x-1', 'modal-header');
2005 $output .= html_writer::tag('h4', get_string('confirm'));
2006 $output .= $this->box_end();
2007 $attributes = [
2008 'role'=>'alert',
2009 'data-aria-autofocus'=>'true'
2011 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
2012 $output .= html_writer::tag('p', $message);
2013 $output .= $this->box_end();
2014 $output .= $this->box_start('modal-footer', 'modal-footer');
2015 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
2016 $output .= $this->box_end();
2017 $output .= $this->box_end();
2018 $output .= $this->box_end();
2019 return $output;
2023 * Returns a form with a single button.
2025 * Theme developers: DO NOT OVERRIDE! Please override function
2026 * {@link core_renderer::render_single_button()} instead.
2028 * @param string|moodle_url $url
2029 * @param string $label button text
2030 * @param string $method get or post submit method
2031 * @param array $options associative array {disabled, title, etc.}
2032 * @return string HTML fragment
2034 public function single_button($url, $label, $method='post', array $options=null) {
2035 if (!($url instanceof moodle_url)) {
2036 $url = new moodle_url($url);
2038 $button = new single_button($url, $label, $method);
2040 foreach ((array)$options as $key=>$value) {
2041 if (array_key_exists($key, $button)) {
2042 $button->$key = $value;
2046 return $this->render($button);
2050 * Renders a single button widget.
2052 * This will return HTML to display a form containing a single button.
2054 * @param single_button $button
2055 * @return string HTML fragment
2057 protected function render_single_button(single_button $button) {
2058 $attributes = array('type' => 'submit',
2059 'value' => $button->label,
2060 'disabled' => $button->disabled ? 'disabled' : null,
2061 'title' => $button->tooltip);
2063 if ($button->actions) {
2064 $id = html_writer::random_id('single_button');
2065 $attributes['id'] = $id;
2066 foreach ($button->actions as $action) {
2067 $this->add_action_handler($action, $id);
2071 // first the input element
2072 $output = html_writer::empty_tag('input', $attributes);
2074 // then hidden fields
2075 $params = $button->url->params();
2076 if ($button->method === 'post') {
2077 $params['sesskey'] = sesskey();
2079 foreach ($params as $var => $val) {
2080 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
2083 // then div wrapper for xhtml strictness
2084 $output = html_writer::tag('div', $output);
2086 // now the form itself around it
2087 if ($button->method === 'get') {
2088 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
2089 } else {
2090 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
2092 if ($url === '') {
2093 $url = '#'; // there has to be always some action
2095 $attributes = array('method' => $button->method,
2096 'action' => $url,
2097 'id' => $button->formid);
2098 $output = html_writer::tag('form', $output, $attributes);
2100 // and finally one more wrapper with class
2101 return html_writer::tag('div', $output, array('class' => $button->class));
2105 * Returns a form with a single select widget.
2107 * Theme developers: DO NOT OVERRIDE! Please override function
2108 * {@link core_renderer::render_single_select()} instead.
2110 * @param moodle_url $url form action target, includes hidden fields
2111 * @param string $name name of selection field - the changing parameter in url
2112 * @param array $options list of options
2113 * @param string $selected selected element
2114 * @param array $nothing
2115 * @param string $formid
2116 * @param array $attributes other attributes for the single select
2117 * @return string HTML fragment
2119 public function single_select($url, $name, array $options, $selected = '',
2120 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2121 if (!($url instanceof moodle_url)) {
2122 $url = new moodle_url($url);
2124 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2126 if (array_key_exists('label', $attributes)) {
2127 $select->set_label($attributes['label']);
2128 unset($attributes['label']);
2130 $select->attributes = $attributes;
2132 return $this->render($select);
2136 * Returns a dataformat selection and download form
2138 * @param string $label A text label
2139 * @param moodle_url|string $base The download page url
2140 * @param string $name The query param which will hold the type of the download
2141 * @param array $params Extra params sent to the download page
2142 * @return string HTML fragment
2144 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2146 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2147 $options = array();
2148 foreach ($formats as $format) {
2149 if ($format->is_enabled()) {
2150 $options[] = array(
2151 'value' => $format->name,
2152 'label' => get_string('dataformat', $format->component),
2156 $hiddenparams = array();
2157 foreach ($params as $key => $value) {
2158 $hiddenparams[] = array(
2159 'name' => $key,
2160 'value' => $value,
2163 $data = array(
2164 'label' => $label,
2165 'base' => $base,
2166 'name' => $name,
2167 'params' => $hiddenparams,
2168 'options' => $options,
2169 'sesskey' => sesskey(),
2170 'submit' => get_string('download'),
2173 return $this->render_from_template('core/dataformat_selector', $data);
2178 * Internal implementation of single_select rendering
2180 * @param single_select $select
2181 * @return string HTML fragment
2183 protected function render_single_select(single_select $select) {
2184 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2188 * Returns a form with a url select widget.
2190 * Theme developers: DO NOT OVERRIDE! Please override function
2191 * {@link core_renderer::render_url_select()} instead.
2193 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2194 * @param string $selected selected element
2195 * @param array $nothing
2196 * @param string $formid
2197 * @return string HTML fragment
2199 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2200 $select = new url_select($urls, $selected, $nothing, $formid);
2201 return $this->render($select);
2205 * Internal implementation of url_select rendering
2207 * @param url_select $select
2208 * @return string HTML fragment
2210 protected function render_url_select(url_select $select) {
2211 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2215 * Returns a string containing a link to the user documentation.
2216 * Also contains an icon by default. Shown to teachers and admin only.
2218 * @param string $path The page link after doc root and language, no leading slash.
2219 * @param string $text The text to be displayed for the link
2220 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2221 * @return string
2223 public function doc_link($path, $text = '', $forcepopup = false) {
2224 global $CFG;
2226 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2228 $url = new moodle_url(get_docs_url($path));
2230 $attributes = array('href'=>$url);
2231 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2232 $attributes['class'] = 'helplinkpopup';
2235 return html_writer::tag('a', $icon.$text, $attributes);
2239 * Return HTML for an image_icon.
2241 * Theme developers: DO NOT OVERRIDE! Please override function
2242 * {@link core_renderer::render_image_icon()} instead.
2244 * @param string $pix short pix name
2245 * @param string $alt mandatory alt attribute
2246 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2247 * @param array $attributes htm lattributes
2248 * @return string HTML fragment
2250 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2251 $icon = new image_icon($pix, $alt, $component, $attributes);
2252 return $this->render($icon);
2256 * Renders a pix_icon widget and returns the HTML to display it.
2258 * @param image_icon $icon
2259 * @return string HTML fragment
2261 protected function render_image_icon(image_icon $icon) {
2262 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2263 return $system->render_pix_icon($this, $icon);
2267 * Return HTML for a pix_icon.
2269 * Theme developers: DO NOT OVERRIDE! Please override function
2270 * {@link core_renderer::render_pix_icon()} instead.
2272 * @param string $pix short pix name
2273 * @param string $alt mandatory alt attribute
2274 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2275 * @param array $attributes htm lattributes
2276 * @return string HTML fragment
2278 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2279 $icon = new pix_icon($pix, $alt, $component, $attributes);
2280 return $this->render($icon);
2284 * Renders a pix_icon widget and returns the HTML to display it.
2286 * @param pix_icon $icon
2287 * @return string HTML fragment
2289 protected function render_pix_icon(pix_icon $icon) {
2290 $system = \core\output\icon_system::instance();
2291 return $system->render_pix_icon($this, $icon);
2295 * Return HTML to display an emoticon icon.
2297 * @param pix_emoticon $emoticon
2298 * @return string HTML fragment
2300 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2301 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2302 return $system->render_pix_icon($this, $emoticon);
2306 * Produces the html that represents this rating in the UI
2308 * @param rating $rating the page object on which this rating will appear
2309 * @return string
2311 function render_rating(rating $rating) {
2312 global $CFG, $USER;
2314 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2315 return null;//ratings are turned off
2318 $ratingmanager = new rating_manager();
2319 // Initialise the JavaScript so ratings can be done by AJAX.
2320 $ratingmanager->initialise_rating_javascript($this->page);
2322 $strrate = get_string("rate", "rating");
2323 $ratinghtml = ''; //the string we'll return
2325 // permissions check - can they view the aggregate?
2326 if ($rating->user_can_view_aggregate()) {
2328 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2329 $aggregatestr = $rating->get_aggregate_string();
2331 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2332 if ($rating->count > 0) {
2333 $countstr = "({$rating->count})";
2334 } else {
2335 $countstr = '-';
2337 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2339 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2340 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2342 $nonpopuplink = $rating->get_view_ratings_url();
2343 $popuplink = $rating->get_view_ratings_url(true);
2345 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2346 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2347 } else {
2348 $ratinghtml .= $aggregatehtml;
2352 $formstart = null;
2353 // if the item doesn't belong to the current user, the user has permission to rate
2354 // and we're within the assessable period
2355 if ($rating->user_can_rate()) {
2357 $rateurl = $rating->get_rate_url();
2358 $inputs = $rateurl->params();
2360 //start the rating form
2361 $formattrs = array(
2362 'id' => "postrating{$rating->itemid}",
2363 'class' => 'postratingform',
2364 'method' => 'post',
2365 'action' => $rateurl->out_omit_querystring()
2367 $formstart = html_writer::start_tag('form', $formattrs);
2368 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2370 // add the hidden inputs
2371 foreach ($inputs as $name => $value) {
2372 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2373 $formstart .= html_writer::empty_tag('input', $attributes);
2376 if (empty($ratinghtml)) {
2377 $ratinghtml .= $strrate.': ';
2379 $ratinghtml = $formstart.$ratinghtml;
2381 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2382 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2383 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2384 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2386 //output submit button
2387 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2389 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2390 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2392 if (!$rating->settings->scale->isnumeric) {
2393 // If a global scale, try to find current course ID from the context
2394 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2395 $courseid = $coursecontext->instanceid;
2396 } else {
2397 $courseid = $rating->settings->scale->courseid;
2399 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2401 $ratinghtml .= html_writer::end_tag('span');
2402 $ratinghtml .= html_writer::end_tag('div');
2403 $ratinghtml .= html_writer::end_tag('form');
2406 return $ratinghtml;
2410 * Centered heading with attached help button (same title text)
2411 * and optional icon attached.
2413 * @param string $text A heading text
2414 * @param string $helpidentifier The keyword that defines a help page
2415 * @param string $component component name
2416 * @param string|moodle_url $icon
2417 * @param string $iconalt icon alt text
2418 * @param int $level The level of importance of the heading. Defaulting to 2
2419 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2420 * @return string HTML fragment
2422 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2423 $image = '';
2424 if ($icon) {
2425 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2428 $help = '';
2429 if ($helpidentifier) {
2430 $help = $this->help_icon($helpidentifier, $component);
2433 return $this->heading($image.$text.$help, $level, $classnames);
2437 * Returns HTML to display a help icon.
2439 * @deprecated since Moodle 2.0
2441 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2442 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2446 * Returns HTML to display a help icon.
2448 * Theme developers: DO NOT OVERRIDE! Please override function
2449 * {@link core_renderer::render_help_icon()} instead.
2451 * @param string $identifier The keyword that defines a help page
2452 * @param string $component component name
2453 * @param string|bool $linktext true means use $title as link text, string means link text value
2454 * @return string HTML fragment
2456 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2457 $icon = new help_icon($identifier, $component);
2458 $icon->diag_strings();
2459 if ($linktext === true) {
2460 $icon->linktext = get_string($icon->identifier, $icon->component);
2461 } else if (!empty($linktext)) {
2462 $icon->linktext = $linktext;
2464 return $this->render($icon);
2468 * Implementation of user image rendering.
2470 * @param help_icon $helpicon A help icon instance
2471 * @return string HTML fragment
2473 protected function render_help_icon(help_icon $helpicon) {
2474 return $this->render_from_template('core/help_icon', $helpicon->export_for_template($this));
2478 * Returns HTML to display a scale help icon.
2480 * @param int $courseid
2481 * @param stdClass $scale instance
2482 * @return string HTML fragment
2484 public function help_icon_scale($courseid, stdClass $scale) {
2485 global $CFG;
2487 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2489 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2491 $scaleid = abs($scale->id);
2493 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2494 $action = new popup_action('click', $link, 'ratingscale');
2496 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2500 * Creates and returns a spacer image with optional line break.
2502 * @param array $attributes Any HTML attributes to add to the spaced.
2503 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2504 * laxy do it with CSS which is a much better solution.
2505 * @return string HTML fragment
2507 public function spacer(array $attributes = null, $br = false) {
2508 $attributes = (array)$attributes;
2509 if (empty($attributes['width'])) {
2510 $attributes['width'] = 1;
2512 if (empty($attributes['height'])) {
2513 $attributes['height'] = 1;
2515 $attributes['class'] = 'spacer';
2517 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2519 if (!empty($br)) {
2520 $output .= '<br />';
2523 return $output;
2527 * Returns HTML to display the specified user's avatar.
2529 * User avatar may be obtained in two ways:
2530 * <pre>
2531 * // Option 1: (shortcut for simple cases, preferred way)
2532 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2533 * $OUTPUT->user_picture($user, array('popup'=>true));
2535 * // Option 2:
2536 * $userpic = new user_picture($user);
2537 * // Set properties of $userpic
2538 * $userpic->popup = true;
2539 * $OUTPUT->render($userpic);
2540 * </pre>
2542 * Theme developers: DO NOT OVERRIDE! Please override function
2543 * {@link core_renderer::render_user_picture()} instead.
2545 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2546 * If any of these are missing, the database is queried. Avoid this
2547 * if at all possible, particularly for reports. It is very bad for performance.
2548 * @param array $options associative array with user picture options, used only if not a user_picture object,
2549 * options are:
2550 * - courseid=$this->page->course->id (course id of user profile in link)
2551 * - size=35 (size of image)
2552 * - link=true (make image clickable - the link leads to user profile)
2553 * - popup=false (open in popup)
2554 * - alttext=true (add image alt attribute)
2555 * - class = image class attribute (default 'userpicture')
2556 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2557 * - includefullname=false (whether to include the user's full name together with the user picture)
2558 * - includetoken = false
2559 * @return string HTML fragment
2561 public function user_picture(stdClass $user, array $options = null) {
2562 $userpicture = new user_picture($user);
2563 foreach ((array)$options as $key=>$value) {
2564 if (array_key_exists($key, $userpicture)) {
2565 $userpicture->$key = $value;
2568 return $this->render($userpicture);
2572 * Internal implementation of user image rendering.
2574 * @param user_picture $userpicture
2575 * @return string
2577 protected function render_user_picture(user_picture $userpicture) {
2578 global $CFG, $DB;
2580 $user = $userpicture->user;
2581 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
2583 if ($userpicture->alttext) {
2584 if (!empty($user->imagealt)) {
2585 $alt = $user->imagealt;
2586 } else {
2587 $alt = get_string('pictureof', '', fullname($user, $canviewfullnames));
2589 } else {
2590 $alt = '';
2593 if (empty($userpicture->size)) {
2594 $size = 35;
2595 } else if ($userpicture->size === true or $userpicture->size == 1) {
2596 $size = 100;
2597 } else {
2598 $size = $userpicture->size;
2601 $class = $userpicture->class;
2603 if ($user->picture == 0) {
2604 $class .= ' defaultuserpic';
2607 $src = $userpicture->get_url($this->page, $this);
2609 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2610 if (!$userpicture->visibletoscreenreaders) {
2611 $attributes['role'] = 'presentation';
2612 $alt = '';
2613 $attributes['aria-hidden'] = 'true';
2616 if (!empty($alt)) {
2617 $attributes['alt'] = $alt;
2618 $attributes['title'] = $alt;
2621 // get the image html output fisrt
2622 $output = html_writer::empty_tag('img', $attributes);
2624 // Show fullname together with the picture when desired.
2625 if ($userpicture->includefullname) {
2626 $output .= fullname($userpicture->user, $canviewfullnames);
2629 // then wrap it in link if needed
2630 if (!$userpicture->link) {
2631 return $output;
2634 if (empty($userpicture->courseid)) {
2635 $courseid = $this->page->course->id;
2636 } else {
2637 $courseid = $userpicture->courseid;
2640 if ($courseid == SITEID) {
2641 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2642 } else {
2643 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2646 $attributes = array('href'=>$url);
2647 if (!$userpicture->visibletoscreenreaders) {
2648 $attributes['tabindex'] = '-1';
2649 $attributes['aria-hidden'] = 'true';
2652 if ($userpicture->popup) {
2653 $id = html_writer::random_id('userpicture');
2654 $attributes['id'] = $id;
2655 $this->add_action_handler(new popup_action('click', $url), $id);
2658 return html_writer::tag('a', $output, $attributes);
2662 * Internal implementation of file tree viewer items rendering.
2664 * @param array $dir
2665 * @return string
2667 public function htmllize_file_tree($dir) {
2668 if (empty($dir['subdirs']) and empty($dir['files'])) {
2669 return '';
2671 $result = '<ul>';
2672 foreach ($dir['subdirs'] as $subdir) {
2673 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2675 foreach ($dir['files'] as $file) {
2676 $filename = $file->get_filename();
2677 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2679 $result .= '</ul>';
2681 return $result;
2685 * Returns HTML to display the file picker
2687 * <pre>
2688 * $OUTPUT->file_picker($options);
2689 * </pre>
2691 * Theme developers: DO NOT OVERRIDE! Please override function
2692 * {@link core_renderer::render_file_picker()} instead.
2694 * @param array $options associative array with file manager options
2695 * options are:
2696 * maxbytes=>-1,
2697 * itemid=>0,
2698 * client_id=>uniqid(),
2699 * acepted_types=>'*',
2700 * return_types=>FILE_INTERNAL,
2701 * context=>$PAGE->context
2702 * @return string HTML fragment
2704 public function file_picker($options) {
2705 $fp = new file_picker($options);
2706 return $this->render($fp);
2710 * Internal implementation of file picker rendering.
2712 * @param file_picker $fp
2713 * @return string
2715 public function render_file_picker(file_picker $fp) {
2716 global $CFG, $OUTPUT, $USER;
2717 $options = $fp->options;
2718 $client_id = $options->client_id;
2719 $strsaved = get_string('filesaved', 'repository');
2720 $straddfile = get_string('openpicker', 'repository');
2721 $strloading = get_string('loading', 'repository');
2722 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2723 $strdroptoupload = get_string('droptoupload', 'moodle');
2724 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2726 $currentfile = $options->currentfile;
2727 if (empty($currentfile)) {
2728 $currentfile = '';
2729 } else {
2730 $currentfile .= ' - ';
2732 if ($options->maxbytes) {
2733 $size = $options->maxbytes;
2734 } else {
2735 $size = get_max_upload_file_size();
2737 if ($size == -1) {
2738 $maxsize = '';
2739 } else {
2740 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2742 if ($options->buttonname) {
2743 $buttonname = ' name="' . $options->buttonname . '"';
2744 } else {
2745 $buttonname = '';
2747 $html = <<<EOD
2748 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2749 $icon_progress
2750 </div>
2751 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2752 <div>
2753 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2754 <span> $maxsize </span>
2755 </div>
2756 EOD;
2757 if ($options->env != 'url') {
2758 $html .= <<<EOD
2759 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2760 <div class="filepicker-filename">
2761 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2762 <div class="dndupload-progressbars"></div>
2763 </div>
2764 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2765 </div>
2766 EOD;
2768 $html .= '</div>';
2769 return $html;
2773 * @deprecated since Moodle 3.2
2775 public function update_module_button() {
2776 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2777 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2778 'Themes can choose to display the link in the buttons row consistently for all module types.');
2782 * Returns HTML to display a "Turn editing on/off" button in a form.
2784 * @param moodle_url $url The URL + params to send through when clicking the button
2785 * @return string HTML the button
2787 public function edit_button(moodle_url $url) {
2789 $url->param('sesskey', sesskey());
2790 if ($this->page->user_is_editing()) {
2791 $url->param('edit', 'off');
2792 $editstring = get_string('turneditingoff');
2793 } else {
2794 $url->param('edit', 'on');
2795 $editstring = get_string('turneditingon');
2798 return $this->single_button($url, $editstring);
2802 * Returns HTML to display a simple button to close a window
2804 * @param string $text The lang string for the button's label (already output from get_string())
2805 * @return string html fragment
2807 public function close_window_button($text='') {
2808 if (empty($text)) {
2809 $text = get_string('closewindow');
2811 $button = new single_button(new moodle_url('#'), $text, 'get');
2812 $button->add_action(new component_action('click', 'close_window'));
2814 return $this->container($this->render($button), 'closewindow');
2818 * Output an error message. By default wraps the error message in <span class="error">.
2819 * If the error message is blank, nothing is output.
2821 * @param string $message the error message.
2822 * @return string the HTML to output.
2824 public function error_text($message) {
2825 if (empty($message)) {
2826 return '';
2828 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2829 return html_writer::tag('span', $message, array('class' => 'error'));
2833 * Do not call this function directly.
2835 * To terminate the current script with a fatal error, call the {@link print_error}
2836 * function, or throw an exception. Doing either of those things will then call this
2837 * function to display the error, before terminating the execution.
2839 * @param string $message The message to output
2840 * @param string $moreinfourl URL where more info can be found about the error
2841 * @param string $link Link for the Continue button
2842 * @param array $backtrace The execution backtrace
2843 * @param string $debuginfo Debugging information
2844 * @return string the HTML to output.
2846 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2847 global $CFG;
2849 $output = '';
2850 $obbuffer = '';
2852 if ($this->has_started()) {
2853 // we can not always recover properly here, we have problems with output buffering,
2854 // html tables, etc.
2855 $output .= $this->opencontainers->pop_all_but_last();
2857 } else {
2858 // It is really bad if library code throws exception when output buffering is on,
2859 // because the buffered text would be printed before our start of page.
2860 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2861 error_reporting(0); // disable notices from gzip compression, etc.
2862 while (ob_get_level() > 0) {
2863 $buff = ob_get_clean();
2864 if ($buff === false) {
2865 break;
2867 $obbuffer .= $buff;
2869 error_reporting($CFG->debug);
2871 // Output not yet started.
2872 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2873 if (empty($_SERVER['HTTP_RANGE'])) {
2874 @header($protocol . ' 404 Not Found');
2875 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2876 // Coax iOS 10 into sending the session cookie.
2877 @header($protocol . ' 403 Forbidden');
2878 } else {
2879 // Must stop byteserving attempts somehow,
2880 // this is weird but Chrome PDF viewer can be stopped only with 407!
2881 @header($protocol . ' 407 Proxy Authentication Required');
2884 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2885 $this->page->set_url('/'); // no url
2886 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2887 $this->page->set_title(get_string('error'));
2888 $this->page->set_heading($this->page->course->fullname);
2889 $output .= $this->header();
2892 $message = '<p class="errormessage">' . $message . '</p>'.
2893 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2894 get_string('moreinformation') . '</a></p>';
2895 if (empty($CFG->rolesactive)) {
2896 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2897 //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.
2899 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2901 if ($CFG->debugdeveloper) {
2902 if (!empty($debuginfo)) {
2903 $debuginfo = s($debuginfo); // removes all nasty JS
2904 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2905 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2907 if (!empty($backtrace)) {
2908 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2910 if ($obbuffer !== '' ) {
2911 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2915 if (empty($CFG->rolesactive)) {
2916 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2917 } else if (!empty($link)) {
2918 $output .= $this->continue_button($link);
2921 $output .= $this->footer();
2923 // Padding to encourage IE to display our error page, rather than its own.
2924 $output .= str_repeat(' ', 512);
2926 return $output;
2930 * Output a notification (that is, a status message about something that has just happened).
2932 * Note: \core\notification::add() may be more suitable for your usage.
2934 * @param string $message The message to print out.
2935 * @param string $type The type of notification. See constants on \core\output\notification.
2936 * @return string the HTML to output.
2938 public function notification($message, $type = null) {
2939 $typemappings = [
2940 // Valid types.
2941 'success' => \core\output\notification::NOTIFY_SUCCESS,
2942 'info' => \core\output\notification::NOTIFY_INFO,
2943 'warning' => \core\output\notification::NOTIFY_WARNING,
2944 'error' => \core\output\notification::NOTIFY_ERROR,
2946 // Legacy types mapped to current types.
2947 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2948 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2949 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2950 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2951 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2952 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2953 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2956 $extraclasses = [];
2958 if ($type) {
2959 if (strpos($type, ' ') === false) {
2960 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2961 if (isset($typemappings[$type])) {
2962 $type = $typemappings[$type];
2963 } else {
2964 // The value provided did not match a known type. It must be an extra class.
2965 $extraclasses = [$type];
2967 } else {
2968 // Identify what type of notification this is.
2969 $classarray = explode(' ', self::prepare_classes($type));
2971 // Separate out the type of notification from the extra classes.
2972 foreach ($classarray as $class) {
2973 if (isset($typemappings[$class])) {
2974 $type = $typemappings[$class];
2975 } else {
2976 $extraclasses[] = $class;
2982 $notification = new \core\output\notification($message, $type);
2983 if (count($extraclasses)) {
2984 $notification->set_extra_classes($extraclasses);
2987 // Return the rendered template.
2988 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2992 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2994 public function notify_problem() {
2995 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
2996 'please use \core\notification::add(), or \core\output\notification as required.');
3000 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3002 public function notify_success() {
3003 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
3004 'please use \core\notification::add(), or \core\output\notification as required.');
3008 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3010 public function notify_message() {
3011 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
3012 'please use \core\notification::add(), or \core\output\notification as required.');
3016 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3018 public function notify_redirect() {
3019 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
3020 'please use \core\notification::add(), or \core\output\notification as required.');
3024 * Render a notification (that is, a status message about something that has
3025 * just happened).
3027 * @param \core\output\notification $notification the notification to print out
3028 * @return string the HTML to output.
3030 protected function render_notification(\core\output\notification $notification) {
3031 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3035 * Returns HTML to display a continue button that goes to a particular URL.
3037 * @param string|moodle_url $url The url the button goes to.
3038 * @return string the HTML to output.
3040 public function continue_button($url) {
3041 if (!($url instanceof moodle_url)) {
3042 $url = new moodle_url($url);
3044 $button = new single_button($url, get_string('continue'), 'get', true);
3045 $button->class = 'continuebutton';
3047 return $this->render($button);
3051 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
3053 * Theme developers: DO NOT OVERRIDE! Please override function
3054 * {@link core_renderer::render_paging_bar()} instead.
3056 * @param int $totalcount The total number of entries available to be paged through
3057 * @param int $page The page you are currently viewing
3058 * @param int $perpage The number of entries that should be shown per page
3059 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3060 * @param string $pagevar name of page parameter that holds the page number
3061 * @return string the HTML to output.
3063 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3064 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3065 return $this->render($pb);
3069 * Returns HTML to display the paging bar.
3071 * @param paging_bar $pagingbar
3072 * @return string the HTML to output.
3074 protected function render_paging_bar(paging_bar $pagingbar) {
3075 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3076 $pagingbar->maxdisplay = 10;
3077 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3081 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3083 * @param string $current the currently selected letter.
3084 * @param string $class class name to add to this initial bar.
3085 * @param string $title the name to put in front of this initial bar.
3086 * @param string $urlvar URL parameter name for this initial.
3087 * @param string $url URL object.
3088 * @param array $alpha of letters in the alphabet.
3089 * @return string the HTML to output.
3091 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3092 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3093 return $this->render($ib);
3097 * Internal implementation of initials bar rendering.
3099 * @param initials_bar $initialsbar
3100 * @return string
3102 protected function render_initials_bar(initials_bar $initialsbar) {
3103 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3107 * Output the place a skip link goes to.
3109 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3110 * @return string the HTML to output.
3112 public function skip_link_target($id = null) {
3113 return html_writer::span('', '', array('id' => $id));
3117 * Outputs a heading
3119 * @param string $text The text of the heading
3120 * @param int $level The level of importance of the heading. Defaulting to 2
3121 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3122 * @param string $id An optional ID
3123 * @return string the HTML to output.
3125 public function heading($text, $level = 2, $classes = null, $id = null) {
3126 $level = (integer) $level;
3127 if ($level < 1 or $level > 6) {
3128 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3130 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3134 * Outputs a box.
3136 * @param string $contents The contents of the box
3137 * @param string $classes A space-separated list of CSS classes
3138 * @param string $id An optional ID
3139 * @param array $attributes An array of other attributes to give the box.
3140 * @return string the HTML to output.
3142 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3143 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3147 * Outputs the opening section of a box.
3149 * @param string $classes A space-separated list of CSS classes
3150 * @param string $id An optional ID
3151 * @param array $attributes An array of other attributes to give the box.
3152 * @return string the HTML to output.
3154 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3155 $this->opencontainers->push('box', html_writer::end_tag('div'));
3156 $attributes['id'] = $id;
3157 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
3158 return html_writer::start_tag('div', $attributes);
3162 * Outputs the closing section of a box.
3164 * @return string the HTML to output.
3166 public function box_end() {
3167 return $this->opencontainers->pop('box');
3171 * Outputs a container.
3173 * @param string $contents The contents of the box
3174 * @param string $classes A space-separated list of CSS classes
3175 * @param string $id An optional ID
3176 * @return string the HTML to output.
3178 public function container($contents, $classes = null, $id = null) {
3179 return $this->container_start($classes, $id) . $contents . $this->container_end();
3183 * Outputs the opening section of a container.
3185 * @param string $classes A space-separated list of CSS classes
3186 * @param string $id An optional ID
3187 * @return string the HTML to output.
3189 public function container_start($classes = null, $id = null) {
3190 $this->opencontainers->push('container', html_writer::end_tag('div'));
3191 return html_writer::start_tag('div', array('id' => $id,
3192 'class' => renderer_base::prepare_classes($classes)));
3196 * Outputs the closing section of a container.
3198 * @return string the HTML to output.
3200 public function container_end() {
3201 return $this->opencontainers->pop('container');
3205 * Make nested HTML lists out of the items
3207 * The resulting list will look something like this:
3209 * <pre>
3210 * <<ul>>
3211 * <<li>><div class='tree_item parent'>(item contents)</div>
3212 * <<ul>
3213 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3214 * <</ul>>
3215 * <</li>>
3216 * <</ul>>
3217 * </pre>
3219 * @param array $items
3220 * @param array $attrs html attributes passed to the top ofs the list
3221 * @return string HTML
3223 public function tree_block_contents($items, $attrs = array()) {
3224 // exit if empty, we don't want an empty ul element
3225 if (empty($items)) {
3226 return '';
3228 // array of nested li elements
3229 $lis = array();
3230 foreach ($items as $item) {
3231 // this applies to the li item which contains all child lists too
3232 $content = $item->content($this);
3233 $liclasses = array($item->get_css_type());
3234 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3235 $liclasses[] = 'collapsed';
3237 if ($item->isactive === true) {
3238 $liclasses[] = 'current_branch';
3240 $liattr = array('class'=>join(' ',$liclasses));
3241 // class attribute on the div item which only contains the item content
3242 $divclasses = array('tree_item');
3243 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3244 $divclasses[] = 'branch';
3245 } else {
3246 $divclasses[] = 'leaf';
3248 if (!empty($item->classes) && count($item->classes)>0) {
3249 $divclasses[] = join(' ', $item->classes);
3251 $divattr = array('class'=>join(' ', $divclasses));
3252 if (!empty($item->id)) {
3253 $divattr['id'] = $item->id;
3255 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3256 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3257 $content = html_writer::empty_tag('hr') . $content;
3259 $content = html_writer::tag('li', $content, $liattr);
3260 $lis[] = $content;
3262 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3266 * Returns a search box.
3268 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3269 * @return string HTML with the search form hidden by default.
3271 public function search_box($id = false) {
3272 global $CFG;
3274 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3275 // result in an extra included file for each site, even the ones where global search
3276 // is disabled.
3277 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3278 return '';
3281 if ($id == false) {
3282 $id = uniqid();
3283 } else {
3284 // Needs to be cleaned, we use it for the input id.
3285 $id = clean_param($id, PARAM_ALPHANUMEXT);
3288 // JS to animate the form.
3289 $this->page->requires->js_call_amd('core/search-input', 'init', array($id));
3291 $searchicon = html_writer::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
3292 array('role' => 'button', 'tabindex' => 0));
3293 $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot . '/search/index.php');
3294 $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
3295 'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id, 'class' => 'form-control');
3297 $contents = html_writer::tag('label', get_string('enteryoursearchquery', 'search'),
3298 array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer::tag('input', '', $inputattrs);
3299 if ($this->page->context && $this->page->context->contextlevel !== CONTEXT_SYSTEM) {
3300 $contents .= html_writer::empty_tag('input', ['type' => 'hidden',
3301 'name' => 'context', 'value' => $this->page->context->id]);
3303 $searchinput = html_writer::tag('form', $contents, $formattrs);
3305 return html_writer::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper nav-link', 'id' => $id));
3309 * Allow plugins to provide some content to be rendered in the navbar.
3310 * The plugin must define a PLUGIN_render_navbar_output function that returns
3311 * the HTML they wish to add to the navbar.
3313 * @return string HTML for the navbar
3315 public function navbar_plugin_output() {
3316 $output = '';
3318 // Give subsystems an opportunity to inject extra html content. The callback
3319 // must always return a string containing valid html.
3320 foreach (\core_component::get_core_subsystems() as $name => $path) {
3321 if ($path) {
3322 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3326 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3327 foreach ($pluginsfunction as $plugintype => $plugins) {
3328 foreach ($plugins as $pluginfunction) {
3329 $output .= $pluginfunction($this);
3334 return $output;
3338 * Construct a user menu, returning HTML that can be echoed out by a
3339 * layout file.
3341 * @param stdClass $user A user object, usually $USER.
3342 * @param bool $withlinks true if a dropdown should be built.
3343 * @return string HTML fragment.
3345 public function user_menu($user = null, $withlinks = null) {
3346 global $USER, $CFG;
3347 require_once($CFG->dirroot . '/user/lib.php');
3349 if (is_null($user)) {
3350 $user = $USER;
3353 // Note: this behaviour is intended to match that of core_renderer::login_info,
3354 // but should not be considered to be good practice; layout options are
3355 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3356 if (is_null($withlinks)) {
3357 $withlinks = empty($this->page->layout_options['nologinlinks']);
3360 // Add a class for when $withlinks is false.
3361 $usermenuclasses = 'usermenu';
3362 if (!$withlinks) {
3363 $usermenuclasses .= ' withoutlinks';
3366 $returnstr = "";
3368 // If during initial install, return the empty return string.
3369 if (during_initial_install()) {
3370 return $returnstr;
3373 $loginpage = $this->is_login_page();
3374 $loginurl = get_login_url();
3375 // If not logged in, show the typical not-logged-in string.
3376 if (!isloggedin()) {
3377 $returnstr = get_string('loggedinnot', 'moodle');
3378 if (!$loginpage) {
3379 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3381 return html_writer::div(
3382 html_writer::span(
3383 $returnstr,
3384 'login'
3386 $usermenuclasses
3391 // If logged in as a guest user, show a string to that effect.
3392 if (isguestuser()) {
3393 $returnstr = get_string('loggedinasguest');
3394 if (!$loginpage && $withlinks) {
3395 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3398 return html_writer::div(
3399 html_writer::span(
3400 $returnstr,
3401 'login'
3403 $usermenuclasses
3407 // Get some navigation opts.
3408 $opts = user_get_user_navigation_info($user, $this->page);
3410 $avatarclasses = "avatars";
3411 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3412 $usertextcontents = $opts->metadata['userfullname'];
3414 // Other user.
3415 if (!empty($opts->metadata['asotheruser'])) {
3416 $avatarcontents .= html_writer::span(
3417 $opts->metadata['realuseravatar'],
3418 'avatar realuser'
3420 $usertextcontents = $opts->metadata['realuserfullname'];
3421 $usertextcontents .= html_writer::tag(
3422 'span',
3423 get_string(
3424 'loggedinas',
3425 'moodle',
3426 html_writer::span(
3427 $opts->metadata['userfullname'],
3428 'value'
3431 array('class' => 'meta viewingas')
3435 // Role.
3436 if (!empty($opts->metadata['asotherrole'])) {
3437 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3438 $usertextcontents .= html_writer::span(
3439 $opts->metadata['rolename'],
3440 'meta role role-' . $role
3444 // User login failures.
3445 if (!empty($opts->metadata['userloginfail'])) {
3446 $usertextcontents .= html_writer::span(
3447 $opts->metadata['userloginfail'],
3448 'meta loginfailures'
3452 // MNet.
3453 if (!empty($opts->metadata['asmnetuser'])) {
3454 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3455 $usertextcontents .= html_writer::span(
3456 $opts->metadata['mnetidprovidername'],
3457 'meta mnet mnet-' . $mnet
3461 $returnstr .= html_writer::span(
3462 html_writer::span($usertextcontents, 'usertext mr-1') .
3463 html_writer::span($avatarcontents, $avatarclasses),
3464 'userbutton'
3467 // Create a divider (well, a filler).
3468 $divider = new action_menu_filler();
3469 $divider->primary = false;
3471 $am = new action_menu();
3472 $am->set_menu_trigger(
3473 $returnstr
3475 $am->set_action_label(get_string('usermenu'));
3476 $am->set_alignment(action_menu::TR, action_menu::BR);
3477 $am->set_nowrap_on_items();
3478 if ($withlinks) {
3479 $navitemcount = count($opts->navitems);
3480 $idx = 0;
3481 foreach ($opts->navitems as $key => $value) {
3483 switch ($value->itemtype) {
3484 case 'divider':
3485 // If the nav item is a divider, add one and skip link processing.
3486 $am->add($divider);
3487 break;
3489 case 'invalid':
3490 // Silently skip invalid entries (should we post a notification?).
3491 break;
3493 case 'link':
3494 // Process this as a link item.
3495 $pix = null;
3496 if (isset($value->pix) && !empty($value->pix)) {
3497 $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
3498 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3499 $value->title = html_writer::img(
3500 $value->imgsrc,
3501 $value->title,
3502 array('class' => 'iconsmall')
3503 ) . $value->title;
3506 $al = new action_menu_link_secondary(
3507 $value->url,
3508 $pix,
3509 $value->title,
3510 array('class' => 'icon')
3512 if (!empty($value->titleidentifier)) {
3513 $al->attributes['data-title'] = $value->titleidentifier;
3515 $am->add($al);
3516 break;
3519 $idx++;
3521 // Add dividers after the first item and before the last item.
3522 if ($idx == 1 || $idx == $navitemcount - 1) {
3523 $am->add($divider);
3528 return html_writer::div(
3529 $this->render($am),
3530 $usermenuclasses
3535 * Return the navbar content so that it can be echoed out by the layout
3537 * @return string XHTML navbar
3539 public function navbar() {
3540 $items = $this->page->navbar->get_items();
3541 $itemcount = count($items);
3542 if ($itemcount === 0) {
3543 return '';
3546 $htmlblocks = array();
3547 // Iterate the navarray and display each node
3548 $separator = get_separator();
3549 for ($i=0;$i < $itemcount;$i++) {
3550 $item = $items[$i];
3551 $item->hideicon = true;
3552 if ($i===0) {
3553 $content = html_writer::tag('li', $this->render($item));
3554 } else {
3555 $content = html_writer::tag('li', $separator.$this->render($item));
3557 $htmlblocks[] = $content;
3560 //accessibility: heading for navbar list (MDL-20446)
3561 $navbarcontent = html_writer::tag('span', get_string('pagepath'),
3562 array('class' => 'accesshide', 'id' => 'navbar-label'));
3563 $navbarcontent .= html_writer::tag('nav',
3564 html_writer::tag('ul', join('', $htmlblocks)),
3565 array('aria-labelledby' => 'navbar-label'));
3566 // XHTML
3567 return $navbarcontent;
3571 * Renders a breadcrumb navigation node object.
3573 * @param breadcrumb_navigation_node $item The navigation node to render.
3574 * @return string HTML fragment
3576 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3578 if ($item->action instanceof moodle_url) {
3579 $content = $item->get_content();
3580 $title = $item->get_title();
3581 $attributes = array();
3582 $attributes['itemprop'] = 'url';
3583 if ($title !== '') {
3584 $attributes['title'] = $title;
3586 if ($item->hidden) {
3587 $attributes['class'] = 'dimmed_text';
3589 if ($item->is_last()) {
3590 $attributes['aria-current'] = 'page';
3592 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3593 $content = html_writer::link($item->action, $content, $attributes);
3595 $attributes = array();
3596 $attributes['itemscope'] = '';
3597 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3598 $content = html_writer::tag('span', $content, $attributes);
3600 } else {
3601 $content = $this->render_navigation_node($item);
3603 return $content;
3607 * Renders a navigation node object.
3609 * @param navigation_node $item The navigation node to render.
3610 * @return string HTML fragment
3612 protected function render_navigation_node(navigation_node $item) {
3613 $content = $item->get_content();
3614 $title = $item->get_title();
3615 if ($item->icon instanceof renderable && !$item->hideicon) {
3616 $icon = $this->render($item->icon);
3617 $content = $icon.$content; // use CSS for spacing of icons
3619 if ($item->helpbutton !== null) {
3620 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3622 if ($content === '') {
3623 return '';
3625 if ($item->action instanceof action_link) {
3626 $link = $item->action;
3627 if ($item->hidden) {
3628 $link->add_class('dimmed');
3630 if (!empty($content)) {
3631 // Providing there is content we will use that for the link content.
3632 $link->text = $content;
3634 $content = $this->render($link);
3635 } else if ($item->action instanceof moodle_url) {
3636 $attributes = array();
3637 if ($title !== '') {
3638 $attributes['title'] = $title;
3640 if ($item->hidden) {
3641 $attributes['class'] = 'dimmed_text';
3643 $content = html_writer::link($item->action, $content, $attributes);
3645 } else if (is_string($item->action) || empty($item->action)) {
3646 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3647 if ($title !== '') {
3648 $attributes['title'] = $title;
3650 if ($item->hidden) {
3651 $attributes['class'] = 'dimmed_text';
3653 $content = html_writer::tag('span', $content, $attributes);
3655 return $content;
3659 * Accessibility: Right arrow-like character is
3660 * used in the breadcrumb trail, course navigation menu
3661 * (previous/next activity), calendar, and search forum block.
3662 * If the theme does not set characters, appropriate defaults
3663 * are set automatically. Please DO NOT
3664 * use &lt; &gt; &raquo; - these are confusing for blind users.
3666 * @return string
3668 public function rarrow() {
3669 return $this->page->theme->rarrow;
3673 * Accessibility: Left arrow-like character is
3674 * used in the breadcrumb trail, course navigation menu
3675 * (previous/next activity), calendar, and search forum block.
3676 * If the theme does not set characters, appropriate defaults
3677 * are set automatically. Please DO NOT
3678 * use &lt; &gt; &raquo; - these are confusing for blind users.
3680 * @return string
3682 public function larrow() {
3683 return $this->page->theme->larrow;
3687 * Accessibility: Up arrow-like character is used in
3688 * the book heirarchical navigation.
3689 * If the theme does not set characters, appropriate defaults
3690 * are set automatically. Please DO NOT
3691 * use ^ - this is confusing for blind users.
3693 * @return string
3695 public function uarrow() {
3696 return $this->page->theme->uarrow;
3700 * Accessibility: Down arrow-like character.
3701 * If the theme does not set characters, appropriate defaults
3702 * are set automatically.
3704 * @return string
3706 public function darrow() {
3707 return $this->page->theme->darrow;
3711 * Returns the custom menu if one has been set
3713 * A custom menu can be configured by browsing to
3714 * Settings: Administration > Appearance > Themes > Theme settings
3715 * and then configuring the custommenu config setting as described.
3717 * Theme developers: DO NOT OVERRIDE! Please override function
3718 * {@link core_renderer::render_custom_menu()} instead.
3720 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3721 * @return string
3723 public function custom_menu($custommenuitems = '') {
3724 global $CFG;
3725 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3726 $custommenuitems = $CFG->custommenuitems;
3728 if (empty($custommenuitems)) {
3729 return '';
3731 $custommenu = new custom_menu($custommenuitems, current_language());
3732 return $this->render($custommenu);
3736 * Renders a custom menu object (located in outputcomponents.php)
3738 * The custom menu this method produces makes use of the YUI3 menunav widget
3739 * and requires very specific html elements and classes.
3741 * @staticvar int $menucount
3742 * @param custom_menu $menu
3743 * @return string
3745 protected function render_custom_menu(custom_menu $menu) {
3746 static $menucount = 0;
3747 // If the menu has no children return an empty string
3748 if (!$menu->has_children()) {
3749 return '';
3751 // Increment the menu count. This is used for ID's that get worked with
3752 // in JavaScript as is essential
3753 $menucount++;
3754 // Initialise this custom menu (the custom menu object is contained in javascript-static
3755 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
3756 $jscode = "(function(){{$jscode}})";
3757 $this->page->requires->yui_module('node-menunav', $jscode);
3758 // Build the root nodes as required by YUI
3759 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
3760 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3761 $content .= html_writer::start_tag('ul');
3762 // Render each child
3763 foreach ($menu->get_children() as $item) {
3764 $content .= $this->render_custom_menu_item($item);
3766 // Close the open tags
3767 $content .= html_writer::end_tag('ul');
3768 $content .= html_writer::end_tag('div');
3769 $content .= html_writer::end_tag('div');
3770 // Return the custom menu
3771 return $content;
3775 * Renders a custom menu node as part of a submenu
3777 * The custom menu this method produces makes use of the YUI3 menunav widget
3778 * and requires very specific html elements and classes.
3780 * @see core:renderer::render_custom_menu()
3782 * @staticvar int $submenucount
3783 * @param custom_menu_item $menunode
3784 * @return string
3786 protected function render_custom_menu_item(custom_menu_item $menunode) {
3787 // Required to ensure we get unique trackable id's
3788 static $submenucount = 0;
3789 if ($menunode->has_children()) {
3790 // If the child has menus render it as a sub menu
3791 $submenucount++;
3792 $content = html_writer::start_tag('li');
3793 if ($menunode->get_url() !== null) {
3794 $url = $menunode->get_url();
3795 } else {
3796 $url = '#cm_submenu_'.$submenucount;
3798 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3799 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3800 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3801 $content .= html_writer::start_tag('ul');
3802 foreach ($menunode->get_children() as $menunode) {
3803 $content .= $this->render_custom_menu_item($menunode);
3805 $content .= html_writer::end_tag('ul');
3806 $content .= html_writer::end_tag('div');
3807 $content .= html_writer::end_tag('div');
3808 $content .= html_writer::end_tag('li');
3809 } else {
3810 // The node doesn't have children so produce a final menuitem.
3811 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3812 $content = '';
3813 if (preg_match("/^#+$/", $menunode->get_text())) {
3815 // This is a divider.
3816 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3817 } else {
3818 $content = html_writer::start_tag(
3819 'li',
3820 array(
3821 'class' => 'yui3-menuitem'
3824 if ($menunode->get_url() !== null) {
3825 $url = $menunode->get_url();
3826 } else {
3827 $url = '#';
3829 $content .= html_writer::link(
3830 $url,
3831 $menunode->get_text(),
3832 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3835 $content .= html_writer::end_tag('li');
3837 // Return the sub menu
3838 return $content;
3842 * Renders theme links for switching between default and other themes.
3844 * @return string
3846 protected function theme_switch_links() {
3848 $actualdevice = core_useragent::get_device_type();
3849 $currentdevice = $this->page->devicetypeinuse;
3850 $switched = ($actualdevice != $currentdevice);
3852 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3853 // The user is using the a default device and hasn't switched so don't shown the switch
3854 // device links.
3855 return '';
3858 if ($switched) {
3859 $linktext = get_string('switchdevicerecommended');
3860 $devicetype = $actualdevice;
3861 } else {
3862 $linktext = get_string('switchdevicedefault');
3863 $devicetype = 'default';
3865 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3867 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3868 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3869 $content .= html_writer::end_tag('div');
3871 return $content;
3875 * Renders tabs
3877 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3879 * Theme developers: In order to change how tabs are displayed please override functions
3880 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3882 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3883 * @param string|null $selected which tab to mark as selected, all parent tabs will
3884 * automatically be marked as activated
3885 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3886 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3887 * @return string
3889 public final function tabtree($tabs, $selected = null, $inactive = null) {
3890 return $this->render(new tabtree($tabs, $selected, $inactive));
3894 * Renders tabtree
3896 * @param tabtree $tabtree
3897 * @return string
3899 protected function render_tabtree(tabtree $tabtree) {
3900 if (empty($tabtree->subtree)) {
3901 return '';
3903 $str = '';
3904 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
3905 $str .= $this->render_tabobject($tabtree);
3906 $str .= html_writer::end_tag('div').
3907 html_writer::tag('div', ' ', array('class' => 'clearer'));
3908 return $str;
3912 * Renders tabobject (part of tabtree)
3914 * This function is called from {@link core_renderer::render_tabtree()}
3915 * and also it calls itself when printing the $tabobject subtree recursively.
3917 * Property $tabobject->level indicates the number of row of tabs.
3919 * @param tabobject $tabobject
3920 * @return string HTML fragment
3922 protected function render_tabobject(tabobject $tabobject) {
3923 $str = '';
3925 // Print name of the current tab.
3926 if ($tabobject instanceof tabtree) {
3927 // No name for tabtree root.
3928 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3929 // Tab name without a link. The <a> tag is used for styling.
3930 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3931 } else {
3932 // Tab name with a link.
3933 if (!($tabobject->link instanceof moodle_url)) {
3934 // backward compartibility when link was passed as quoted string
3935 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3936 } else {
3937 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3941 if (empty($tabobject->subtree)) {
3942 if ($tabobject->selected) {
3943 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3945 return $str;
3948 // Print subtree.
3949 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
3950 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3951 $cnt = 0;
3952 foreach ($tabobject->subtree as $tab) {
3953 $liclass = '';
3954 if (!$cnt) {
3955 $liclass .= ' first';
3957 if ($cnt == count($tabobject->subtree) - 1) {
3958 $liclass .= ' last';
3960 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3961 $liclass .= ' onerow';
3964 if ($tab->selected) {
3965 $liclass .= ' here selected';
3966 } else if ($tab->activated) {
3967 $liclass .= ' here active';
3970 // This will recursively call function render_tabobject() for each item in subtree.
3971 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3972 $cnt++;
3974 $str .= html_writer::end_tag('ul');
3977 return $str;
3981 * Get the HTML for blocks in the given region.
3983 * @since Moodle 2.5.1 2.6
3984 * @param string $region The region to get HTML for.
3985 * @return string HTML.
3987 public function blocks($region, $classes = array(), $tag = 'aside') {
3988 $displayregion = $this->page->apply_theme_region_manipulations($region);
3989 $classes = (array)$classes;
3990 $classes[] = 'block-region';
3991 $attributes = array(
3992 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3993 'class' => join(' ', $classes),
3994 'data-blockregion' => $displayregion,
3995 'data-droptarget' => '1'
3997 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3998 $content = $this->blocks_for_region($displayregion);
3999 } else {
4000 $content = '';
4002 return html_writer::tag($tag, $content, $attributes);
4006 * Renders a custom block region.
4008 * Use this method if you want to add an additional block region to the content of the page.
4009 * Please note this should only be used in special situations.
4010 * We want to leave the theme is control where ever possible!
4012 * This method must use the same method that the theme uses within its layout file.
4013 * As such it asks the theme what method it is using.
4014 * It can be one of two values, blocks or blocks_for_region (deprecated).
4016 * @param string $regionname The name of the custom region to add.
4017 * @return string HTML for the block region.
4019 public function custom_block_region($regionname) {
4020 if ($this->page->theme->get_block_render_method() === 'blocks') {
4021 return $this->blocks($regionname);
4022 } else {
4023 return $this->blocks_for_region($regionname);
4028 * Returns the CSS classes to apply to the body tag.
4030 * @since Moodle 2.5.1 2.6
4031 * @param array $additionalclasses Any additional classes to apply.
4032 * @return string
4034 public function body_css_classes(array $additionalclasses = array()) {
4035 // Add a class for each block region on the page.
4036 // We use the block manager here because the theme object makes get_string calls.
4037 $usedregions = array();
4038 foreach ($this->page->blocks->get_regions() as $region) {
4039 $additionalclasses[] = 'has-region-'.$region;
4040 if ($this->page->blocks->region_has_content($region, $this)) {
4041 $additionalclasses[] = 'used-region-'.$region;
4042 $usedregions[] = $region;
4043 } else {
4044 $additionalclasses[] = 'empty-region-'.$region;
4046 if ($this->page->blocks->region_completely_docked($region, $this)) {
4047 $additionalclasses[] = 'docked-region-'.$region;
4050 if (!$usedregions) {
4051 // No regions means there is only content, add 'content-only' class.
4052 $additionalclasses[] = 'content-only';
4053 } else if (count($usedregions) === 1) {
4054 // Add the -only class for the only used region.
4055 $region = array_shift($usedregions);
4056 $additionalclasses[] = $region . '-only';
4058 foreach ($this->page->layout_options as $option => $value) {
4059 if ($value) {
4060 $additionalclasses[] = 'layout-option-'.$option;
4063 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
4064 return $css;
4068 * The ID attribute to apply to the body tag.
4070 * @since Moodle 2.5.1 2.6
4071 * @return string
4073 public function body_id() {
4074 return $this->page->bodyid;
4078 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4080 * @since Moodle 2.5.1 2.6
4081 * @param string|array $additionalclasses Any additional classes to give the body tag,
4082 * @return string
4084 public function body_attributes($additionalclasses = array()) {
4085 if (!is_array($additionalclasses)) {
4086 $additionalclasses = explode(' ', $additionalclasses);
4088 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4092 * Gets HTML for the page heading.
4094 * @since Moodle 2.5.1 2.6
4095 * @param string $tag The tag to encase the heading in. h1 by default.
4096 * @return string HTML.
4098 public function page_heading($tag = 'h1') {
4099 return html_writer::tag($tag, $this->page->heading);
4103 * Gets the HTML for the page heading button.
4105 * @since Moodle 2.5.1 2.6
4106 * @return string HTML.
4108 public function page_heading_button() {
4109 return $this->page->button;
4113 * Returns the Moodle docs link to use for this page.
4115 * @since Moodle 2.5.1 2.6
4116 * @param string $text
4117 * @return string
4119 public function page_doc_link($text = null) {
4120 if ($text === null) {
4121 $text = get_string('moodledocslink');
4123 $path = page_get_doc_link_path($this->page);
4124 if (!$path) {
4125 return '';
4127 return $this->doc_link($path, $text);
4131 * Returns the page heading menu.
4133 * @since Moodle 2.5.1 2.6
4134 * @return string HTML.
4136 public function page_heading_menu() {
4137 return $this->page->headingmenu;
4141 * Returns the title to use on the page.
4143 * @since Moodle 2.5.1 2.6
4144 * @return string
4146 public function page_title() {
4147 return $this->page->title;
4151 * Returns the URL for the favicon.
4153 * @since Moodle 2.5.1 2.6
4154 * @return string The favicon URL
4156 public function favicon() {
4157 return $this->image_url('favicon', 'theme');
4161 * Renders preferences groups.
4163 * @param preferences_groups $renderable The renderable
4164 * @return string The output.
4166 public function render_preferences_groups(preferences_groups $renderable) {
4167 $html = '';
4168 $html .= html_writer::start_div('row-fluid');
4169 $html .= html_writer::start_tag('div', array('class' => 'span12 preferences-groups'));
4170 $i = 0;
4171 $open = false;
4172 foreach ($renderable->groups as $group) {
4173 if ($i == 0 || $i % 3 == 0) {
4174 if ($open) {
4175 $html .= html_writer::end_tag('div');
4177 $html .= html_writer::start_tag('div', array('class' => 'row-fluid'));
4178 $open = true;
4180 $html .= $this->render($group);
4181 $i++;
4184 $html .= html_writer::end_tag('div');
4186 $html .= html_writer::end_tag('ul');
4187 $html .= html_writer::end_tag('div');
4188 $html .= html_writer::end_div();
4189 return $html;
4193 * Renders preferences group.
4195 * @param preferences_group $renderable The renderable
4196 * @return string The output.
4198 public function render_preferences_group(preferences_group $renderable) {
4199 $html = '';
4200 $html .= html_writer::start_tag('div', array('class' => 'span4 preferences-group'));
4201 $html .= $this->heading($renderable->title, 3);
4202 $html .= html_writer::start_tag('ul');
4203 foreach ($renderable->nodes as $node) {
4204 if ($node->has_children()) {
4205 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4207 $html .= html_writer::tag('li', $this->render($node));
4209 $html .= html_writer::end_tag('ul');
4210 $html .= html_writer::end_tag('div');
4211 return $html;
4214 public function context_header($headerinfo = null, $headinglevel = 1) {
4215 global $DB, $USER, $CFG;
4216 require_once($CFG->dirroot . '/user/lib.php');
4217 $context = $this->page->context;
4218 $heading = null;
4219 $imagedata = null;
4220 $subheader = null;
4221 $userbuttons = null;
4222 // Make sure to use the heading if it has been set.
4223 if (isset($headerinfo['heading'])) {
4224 $heading = $headerinfo['heading'];
4227 // The user context currently has images and buttons. Other contexts may follow.
4228 if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
4229 if (isset($headerinfo['user'])) {
4230 $user = $headerinfo['user'];
4231 } else {
4232 // Look up the user information if it is not supplied.
4233 $user = $DB->get_record('user', array('id' => $context->instanceid));
4236 // If the user context is set, then use that for capability checks.
4237 if (isset($headerinfo['usercontext'])) {
4238 $context = $headerinfo['usercontext'];
4241 // Only provide user information if the user is the current user, or a user which the current user can view.
4242 // When checking user_can_view_profile(), either:
4243 // If the page context is course, check the course context (from the page object) or;
4244 // If page context is NOT course, then check across all courses.
4245 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4247 if (user_can_view_profile($user, $course)) {
4248 // Use the user's full name if the heading isn't set.
4249 if (!isset($heading)) {
4250 $heading = fullname($user);
4253 $imagedata = $this->user_picture($user, array('size' => 100));
4255 // Check to see if we should be displaying a message button.
4256 if (!empty($CFG->messaging) && $USER->id != $user->id && has_capability('moodle/site:sendmessage', $context)) {
4257 $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4258 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4259 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4260 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4261 $userbuttons = array(
4262 'messages' => array(
4263 'buttontype' => 'message',
4264 'title' => get_string('message', 'message'),
4265 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4266 'image' => 'message',
4267 'linkattributes' => array('role' => 'button'),
4268 'page' => $this->page
4270 'togglecontact' => array(
4271 'buttontype' => 'togglecontact',
4272 'title' => get_string($contacttitle, 'message'),
4273 'url' => new moodle_url('/message/index.php', array(
4274 'user1' => $USER->id,
4275 'user2' => $user->id,
4276 $contacturlaction => $user->id,
4277 'sesskey' => sesskey())
4279 'image' => $contactimage,
4280 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4281 'page' => $this->page
4285 $this->page->requires->string_for_js('changesmadereallygoaway', 'moodle');
4287 } else {
4288 $heading = null;
4292 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4293 return $this->render_context_header($contextheader);
4297 * Renders the skip links for the page.
4299 * @param array $links List of skip links.
4300 * @return string HTML for the skip links.
4302 public function render_skip_links($links) {
4303 $context = [ 'links' => []];
4305 foreach ($links as $url => $text) {
4306 $context['links'][] = [ 'url' => $url, 'text' => $text];
4309 return $this->render_from_template('core/skip_links', $context);
4313 * Renders the header bar.
4315 * @param context_header $contextheader Header bar object.
4316 * @return string HTML for the header bar.
4318 protected function render_context_header(context_header $contextheader) {
4320 $showheader = empty($this->page->layout_options['nocontextheader']);
4321 if (!$showheader) {
4322 return '';
4325 // All the html stuff goes here.
4326 $html = html_writer::start_div('page-context-header');
4328 // Image data.
4329 if (isset($contextheader->imagedata)) {
4330 // Header specific image.
4331 $html .= html_writer::div($contextheader->imagedata, 'page-header-image');
4334 // Headings.
4335 if (!isset($contextheader->heading)) {
4336 $headings = $this->heading($this->page->heading, $contextheader->headinglevel);
4337 } else {
4338 $headings = $this->heading($contextheader->heading, $contextheader->headinglevel);
4341 $html .= html_writer::tag('div', $headings, array('class' => 'page-header-headings'));
4343 // Buttons.
4344 if (isset($contextheader->additionalbuttons)) {
4345 $html .= html_writer::start_div('btn-group header-button-group');
4346 foreach ($contextheader->additionalbuttons as $button) {
4347 if (!isset($button->page)) {
4348 // Include js for messaging.
4349 if ($button['buttontype'] === 'togglecontact') {
4350 \core_message\helper::togglecontact_requirejs();
4352 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4353 'class' => 'iconsmall',
4354 'role' => 'presentation'
4356 $image .= html_writer::span($button['title'], 'header-button-title');
4357 } else {
4358 $image = html_writer::empty_tag('img', array(
4359 'src' => $button['formattedimage'],
4360 'role' => 'presentation'
4363 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4365 $html .= html_writer::end_div();
4367 $html .= html_writer::end_div();
4369 return $html;
4373 * Wrapper for header elements.
4375 * @return string HTML to display the main header.
4377 public function full_header() {
4378 $html = html_writer::start_tag('header', array('id' => 'page-header', 'class' => 'clearfix'));
4379 $html .= $this->context_header();
4380 $html .= html_writer::start_div('clearfix', array('id' => 'page-navbar'));
4381 $html .= html_writer::tag('div', $this->navbar(), array('class' => 'breadcrumb-nav'));
4382 $html .= html_writer::div($this->page_heading_button(), 'breadcrumb-button');
4383 $html .= html_writer::end_div();
4384 $html .= html_writer::tag('div', $this->course_header(), array('id' => 'course-header'));
4385 $html .= html_writer::end_tag('header');
4386 return $html;
4390 * Displays the list of tags associated with an entry
4392 * @param array $tags list of instances of core_tag or stdClass
4393 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4394 * to use default, set to '' (empty string) to omit the label completely
4395 * @param string $classes additional classes for the enclosing div element
4396 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4397 * will be appended to the end, JS will toggle the rest of the tags
4398 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4399 * @return string
4401 public function tag_list($tags, $label = null, $classes = '', $limit = 10, $pagecontext = null) {
4402 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext);
4403 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4407 * Renders element for inline editing of any value
4409 * @param \core\output\inplace_editable $element
4410 * @return string
4412 public function render_inplace_editable(\core\output\inplace_editable $element) {
4413 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4417 * Renders a bar chart.
4419 * @param \core\chart_bar $chart The chart.
4420 * @return string.
4422 public function render_chart_bar(\core\chart_bar $chart) {
4423 return $this->render_chart($chart);
4427 * Renders a line chart.
4429 * @param \core\chart_line $chart The chart.
4430 * @return string.
4432 public function render_chart_line(\core\chart_line $chart) {
4433 return $this->render_chart($chart);
4437 * Renders a pie chart.
4439 * @param \core\chart_pie $chart The chart.
4440 * @return string.
4442 public function render_chart_pie(\core\chart_pie $chart) {
4443 return $this->render_chart($chart);
4447 * Renders a chart.
4449 * @param \core\chart_base $chart The chart.
4450 * @param bool $withtable Whether to include a data table with the chart.
4451 * @return string.
4453 public function render_chart(\core\chart_base $chart, $withtable = true) {
4454 $chartdata = json_encode($chart);
4455 return $this->render_from_template('core/chart', (object) [
4456 'chartdata' => $chartdata,
4457 'withtable' => $withtable
4462 * Renders the login form.
4464 * @param \core_auth\output\login $form The renderable.
4465 * @return string
4467 public function render_login(\core_auth\output\login $form) {
4468 global $CFG;
4470 $context = $form->export_for_template($this);
4472 // Override because rendering is not supported in template yet.
4473 if ($CFG->rememberusername == 0) {
4474 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabledonlysession');
4475 } else {
4476 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
4478 $context->errorformatted = $this->error_text($context->error);
4480 return $this->render_from_template('core/loginform', $context);
4484 * Renders an mform element from a template.
4486 * @param HTML_QuickForm_element $element element
4487 * @param bool $required if input is required field
4488 * @param bool $advanced if input is an advanced field
4489 * @param string $error error message to display
4490 * @param bool $ingroup True if this element is rendered as part of a group
4491 * @return mixed string|bool
4493 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4494 $templatename = 'core_form/element-' . $element->getType();
4495 if ($ingroup) {
4496 $templatename .= "-inline";
4498 try {
4499 // We call this to generate a file not found exception if there is no template.
4500 // We don't want to call export_for_template if there is no template.
4501 core\output\mustache_template_finder::get_template_filepath($templatename);
4503 if ($element instanceof templatable) {
4504 $elementcontext = $element->export_for_template($this);
4506 $helpbutton = '';
4507 if (method_exists($element, 'getHelpButton')) {
4508 $helpbutton = $element->getHelpButton();
4510 $label = $element->getLabel();
4511 $text = '';
4512 if (method_exists($element, 'getText')) {
4513 // There currently exists code that adds a form element with an empty label.
4514 // If this is the case then set the label to the description.
4515 if (empty($label)) {
4516 $label = $element->getText();
4517 } else {
4518 $text = $element->getText();
4522 // Generate the form element wrapper ids and names to pass to the template.
4523 // This differs between group and non-group elements.
4524 if ($element->getType() === 'group') {
4525 // Group element.
4526 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
4527 $elementcontext['wrapperid'] = $elementcontext['id'];
4529 // Ensure group elements pass through the group name as the element name so the id_error_{{element.name}} is
4530 // properly set in the template.
4531 $elementcontext['name'] = $elementcontext['groupname'];
4532 } else {
4533 // Non grouped element.
4534 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
4535 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
4538 $context = array(
4539 'element' => $elementcontext,
4540 'label' => $label,
4541 'text' => $text,
4542 'required' => $required,
4543 'advanced' => $advanced,
4544 'helpbutton' => $helpbutton,
4545 'error' => $error
4547 return $this->render_from_template($templatename, $context);
4549 } catch (Exception $e) {
4550 // No template for this element.
4551 return false;
4556 * Render the login signup form into a nice template for the theme.
4558 * @param mform $form
4559 * @return string
4561 public function render_login_signup_form($form) {
4562 $context = $form->export_for_template($this);
4564 return $this->render_from_template('core/signup_form_layout', $context);
4568 * Render the verify age and location page into a nice template for the theme.
4570 * @param \core_auth\output\verify_age_location_page $page The renderable
4571 * @return string
4573 protected function render_verify_age_location_page($page) {
4574 $context = $page->export_for_template($this);
4576 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4580 * Render the digital minor contact information page into a nice template for the theme.
4582 * @param \core_auth\output\digital_minor_page $page The renderable
4583 * @return string
4585 protected function render_digital_minor_page($page) {
4586 $context = $page->export_for_template($this);
4588 return $this->render_from_template('core/auth_digital_minor_page', $context);
4592 * Renders a progress bar.
4594 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4596 * @param progress_bar $bar The bar.
4597 * @return string HTML fragment
4599 public function render_progress_bar(progress_bar $bar) {
4600 global $PAGE;
4601 $data = $bar->export_for_template($this);
4602 return $this->render_from_template('core/progress_bar', $data);
4607 * A renderer that generates output for command-line scripts.
4609 * The implementation of this renderer is probably incomplete.
4611 * @copyright 2009 Tim Hunt
4612 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4613 * @since Moodle 2.0
4614 * @package core
4615 * @category output
4617 class core_renderer_cli extends core_renderer {
4620 * Returns the page header.
4622 * @return string HTML fragment
4624 public function header() {
4625 return $this->page->heading . "\n";
4629 * Returns a template fragment representing a Heading.
4631 * @param string $text The text of the heading
4632 * @param int $level The level of importance of the heading
4633 * @param string $classes A space-separated list of CSS classes
4634 * @param string $id An optional ID
4635 * @return string A template fragment for a heading
4637 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4638 $text .= "\n";
4639 switch ($level) {
4640 case 1:
4641 return '=>' . $text;
4642 case 2:
4643 return '-->' . $text;
4644 default:
4645 return $text;
4650 * Returns a template fragment representing a fatal error.
4652 * @param string $message The message to output
4653 * @param string $moreinfourl URL where more info can be found about the error
4654 * @param string $link Link for the Continue button
4655 * @param array $backtrace The execution backtrace
4656 * @param string $debuginfo Debugging information
4657 * @return string A template fragment for a fatal error
4659 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4660 global $CFG;
4662 $output = "!!! $message !!!\n";
4664 if ($CFG->debugdeveloper) {
4665 if (!empty($debuginfo)) {
4666 $output .= $this->notification($debuginfo, 'notifytiny');
4668 if (!empty($backtrace)) {
4669 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
4673 return $output;
4677 * Returns a template fragment representing a notification.
4679 * @param string $message The message to print out.
4680 * @param string $type The type of notification. See constants on \core\output\notification.
4681 * @return string A template fragment for a notification
4683 public function notification($message, $type = null) {
4684 $message = clean_text($message);
4685 if ($type === 'notifysuccess' || $type === 'success') {
4686 return "++ $message ++\n";
4688 return "!! $message !!\n";
4692 * There is no footer for a cli request, however we must override the
4693 * footer method to prevent the default footer.
4695 public function footer() {}
4698 * Render a notification (that is, a status message about something that has
4699 * just happened).
4701 * @param \core\output\notification $notification the notification to print out
4702 * @return string plain text output
4704 public function render_notification(\core\output\notification $notification) {
4705 return $this->notification($notification->get_message(), $notification->get_message_type());
4711 * A renderer that generates output for ajax scripts.
4713 * This renderer prevents accidental sends back only json
4714 * encoded error messages, all other output is ignored.
4716 * @copyright 2010 Petr Skoda
4717 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4718 * @since Moodle 2.0
4719 * @package core
4720 * @category output
4722 class core_renderer_ajax extends core_renderer {
4725 * Returns a template fragment representing a fatal error.
4727 * @param string $message The message to output
4728 * @param string $moreinfourl URL where more info can be found about the error
4729 * @param string $link Link for the Continue button
4730 * @param array $backtrace The execution backtrace
4731 * @param string $debuginfo Debugging information
4732 * @return string A template fragment for a fatal error
4734 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4735 global $CFG;
4737 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
4739 $e = new stdClass();
4740 $e->error = $message;
4741 $e->errorcode = $errorcode;
4742 $e->stacktrace = NULL;
4743 $e->debuginfo = NULL;
4744 $e->reproductionlink = NULL;
4745 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
4746 $link = (string) $link;
4747 if ($link) {
4748 $e->reproductionlink = $link;
4750 if (!empty($debuginfo)) {
4751 $e->debuginfo = $debuginfo;
4753 if (!empty($backtrace)) {
4754 $e->stacktrace = format_backtrace($backtrace, true);
4757 $this->header();
4758 return json_encode($e);
4762 * Used to display a notification.
4763 * For the AJAX notifications are discarded.
4765 * @param string $message The message to print out.
4766 * @param string $type The type of notification. See constants on \core\output\notification.
4768 public function notification($message, $type = null) {}
4771 * Used to display a redirection message.
4772 * AJAX redirections should not occur and as such redirection messages
4773 * are discarded.
4775 * @param moodle_url|string $encodedurl
4776 * @param string $message
4777 * @param int $delay
4778 * @param bool $debugdisableredirect
4779 * @param string $messagetype The type of notification to show the message in.
4780 * See constants on \core\output\notification.
4782 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
4783 $messagetype = \core\output\notification::NOTIFY_INFO) {}
4786 * Prepares the start of an AJAX output.
4788 public function header() {
4789 // unfortunately YUI iframe upload does not support application/json
4790 if (!empty($_FILES)) {
4791 @header('Content-type: text/plain; charset=utf-8');
4792 if (!core_useragent::supports_json_contenttype()) {
4793 @header('X-Content-Type-Options: nosniff');
4795 } else if (!core_useragent::supports_json_contenttype()) {
4796 @header('Content-type: text/plain; charset=utf-8');
4797 @header('X-Content-Type-Options: nosniff');
4798 } else {
4799 @header('Content-type: application/json; charset=utf-8');
4802 // Headers to make it not cacheable and json
4803 @header('Cache-Control: no-store, no-cache, must-revalidate');
4804 @header('Cache-Control: post-check=0, pre-check=0', false);
4805 @header('Pragma: no-cache');
4806 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
4807 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
4808 @header('Accept-Ranges: none');
4812 * There is no footer for an AJAX request, however we must override the
4813 * footer method to prevent the default footer.
4815 public function footer() {}
4818 * No need for headers in an AJAX request... this should never happen.
4819 * @param string $text
4820 * @param int $level
4821 * @param string $classes
4822 * @param string $id
4824 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
4830 * The maintenance renderer.
4832 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
4833 * is running a maintenance related task.
4834 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
4836 * @since Moodle 2.6
4837 * @package core
4838 * @category output
4839 * @copyright 2013 Sam Hemelryk
4840 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4842 class core_renderer_maintenance extends core_renderer {
4845 * Initialises the renderer instance.
4846 * @param moodle_page $page
4847 * @param string $target
4848 * @throws coding_exception
4850 public function __construct(moodle_page $page, $target) {
4851 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
4852 throw new coding_exception('Invalid request for the maintenance renderer.');
4854 parent::__construct($page, $target);
4858 * Does nothing. The maintenance renderer cannot produce blocks.
4860 * @param block_contents $bc
4861 * @param string $region
4862 * @return string
4864 public function block(block_contents $bc, $region) {
4865 // Computer says no blocks.
4866 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4867 return '';
4871 * Does nothing. The maintenance renderer cannot produce blocks.
4873 * @param string $region
4874 * @param array $classes
4875 * @param string $tag
4876 * @return string
4878 public function blocks($region, $classes = array(), $tag = 'aside') {
4879 // Computer says no blocks.
4880 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4881 return '';
4885 * Does nothing. The maintenance renderer cannot produce blocks.
4887 * @param string $region
4888 * @return string
4890 public function blocks_for_region($region) {
4891 // Computer says no blocks for region.
4892 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4893 return '';
4897 * Does nothing. The maintenance renderer cannot produce a course content header.
4899 * @param bool $onlyifnotcalledbefore
4900 * @return string
4902 public function course_content_header($onlyifnotcalledbefore = false) {
4903 // Computer says no course content header.
4904 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4905 return '';
4909 * Does nothing. The maintenance renderer cannot produce a course content footer.
4911 * @param bool $onlyifnotcalledbefore
4912 * @return string
4914 public function course_content_footer($onlyifnotcalledbefore = false) {
4915 // Computer says no course content footer.
4916 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4917 return '';
4921 * Does nothing. The maintenance renderer cannot produce a course header.
4923 * @return string
4925 public function course_header() {
4926 // Computer says no course header.
4927 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4928 return '';
4932 * Does nothing. The maintenance renderer cannot produce a course footer.
4934 * @return string
4936 public function course_footer() {
4937 // Computer says no course footer.
4938 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4939 return '';
4943 * Does nothing. The maintenance renderer cannot produce a custom menu.
4945 * @param string $custommenuitems
4946 * @return string
4948 public function custom_menu($custommenuitems = '') {
4949 // Computer says no custom menu.
4950 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4951 return '';
4955 * Does nothing. The maintenance renderer cannot produce a file picker.
4957 * @param array $options
4958 * @return string
4960 public function file_picker($options) {
4961 // Computer says no file picker.
4962 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4963 return '';
4967 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
4969 * @param array $dir
4970 * @return string
4972 public function htmllize_file_tree($dir) {
4973 // Hell no we don't want no htmllized file tree.
4974 // Also why on earth is this function on the core renderer???
4975 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4976 return '';
4981 * Overridden confirm message for upgrades.
4983 * @param string $message The question to ask the user
4984 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
4985 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
4986 * @return string HTML fragment
4988 public function confirm($message, $continue, $cancel) {
4989 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
4990 // from any previous version of Moodle).
4991 if ($continue instanceof single_button) {
4992 $continue->primary = true;
4993 } else if (is_string($continue)) {
4994 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
4995 } else if ($continue instanceof moodle_url) {
4996 $continue = new single_button($continue, get_string('continue'), 'post', true);
4997 } else {
4998 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
4999 ' (string/moodle_url) or a single_button instance.');
5002 if ($cancel instanceof single_button) {
5003 $output = '';
5004 } else if (is_string($cancel)) {
5005 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5006 } else if ($cancel instanceof moodle_url) {
5007 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5008 } else {
5009 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5010 ' (string/moodle_url) or a single_button instance.');
5013 $output = $this->box_start('generalbox', 'notice');
5014 $output .= html_writer::tag('h4', get_string('confirm'));
5015 $output .= html_writer::tag('p', $message);
5016 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
5017 $output .= $this->box_end();
5018 return $output;
5022 * Does nothing. The maintenance renderer does not support JS.
5024 * @param block_contents $bc
5026 public function init_block_hider_js(block_contents $bc) {
5027 // Computer says no JavaScript.
5028 // Do nothing, ridiculous method.
5032 * Does nothing. The maintenance renderer cannot produce language menus.
5034 * @return string
5036 public function lang_menu() {
5037 // Computer says no lang menu.
5038 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5039 return '';
5043 * Does nothing. The maintenance renderer has no need for login information.
5045 * @param null $withlinks
5046 * @return string
5048 public function login_info($withlinks = null) {
5049 // Computer says no login info.
5050 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5051 return '';
5055 * Does nothing. The maintenance renderer cannot produce user pictures.
5057 * @param stdClass $user
5058 * @param array $options
5059 * @return string
5061 public function user_picture(stdClass $user, array $options = null) {
5062 // Computer says no user pictures.
5063 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5064 return '';