Merge branch 'MDL-64012' of https://github.com/timhunt/moodle
[moodle.git] / lib / outputrenderers.php
blob5e60efd74fbd2bd3a7dabf5ef0cb8f581d4251c2
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', context_system::instance());
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, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2610 if (!$userpicture->visibletoscreenreaders) {
2611 $attributes['role'] = 'presentation';
2614 // get the image html output fisrt
2615 $output = html_writer::empty_tag('img', $attributes);
2617 // Show fullname together with the picture when desired.
2618 if ($userpicture->includefullname) {
2619 $output .= fullname($userpicture->user, $canviewfullnames);
2622 // then wrap it in link if needed
2623 if (!$userpicture->link) {
2624 return $output;
2627 if (empty($userpicture->courseid)) {
2628 $courseid = $this->page->course->id;
2629 } else {
2630 $courseid = $userpicture->courseid;
2633 if ($courseid == SITEID) {
2634 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2635 } else {
2636 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2639 $attributes = array('href'=>$url);
2640 if (!$userpicture->visibletoscreenreaders) {
2641 $attributes['tabindex'] = '-1';
2642 $attributes['aria-hidden'] = 'true';
2645 if ($userpicture->popup) {
2646 $id = html_writer::random_id('userpicture');
2647 $attributes['id'] = $id;
2648 $this->add_action_handler(new popup_action('click', $url), $id);
2651 return html_writer::tag('a', $output, $attributes);
2655 * Internal implementation of file tree viewer items rendering.
2657 * @param array $dir
2658 * @return string
2660 public function htmllize_file_tree($dir) {
2661 if (empty($dir['subdirs']) and empty($dir['files'])) {
2662 return '';
2664 $result = '<ul>';
2665 foreach ($dir['subdirs'] as $subdir) {
2666 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2668 foreach ($dir['files'] as $file) {
2669 $filename = $file->get_filename();
2670 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2672 $result .= '</ul>';
2674 return $result;
2678 * Returns HTML to display the file picker
2680 * <pre>
2681 * $OUTPUT->file_picker($options);
2682 * </pre>
2684 * Theme developers: DO NOT OVERRIDE! Please override function
2685 * {@link core_renderer::render_file_picker()} instead.
2687 * @param array $options associative array with file manager options
2688 * options are:
2689 * maxbytes=>-1,
2690 * itemid=>0,
2691 * client_id=>uniqid(),
2692 * acepted_types=>'*',
2693 * return_types=>FILE_INTERNAL,
2694 * context=>$PAGE->context
2695 * @return string HTML fragment
2697 public function file_picker($options) {
2698 $fp = new file_picker($options);
2699 return $this->render($fp);
2703 * Internal implementation of file picker rendering.
2705 * @param file_picker $fp
2706 * @return string
2708 public function render_file_picker(file_picker $fp) {
2709 global $CFG, $OUTPUT, $USER;
2710 $options = $fp->options;
2711 $client_id = $options->client_id;
2712 $strsaved = get_string('filesaved', 'repository');
2713 $straddfile = get_string('openpicker', 'repository');
2714 $strloading = get_string('loading', 'repository');
2715 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2716 $strdroptoupload = get_string('droptoupload', 'moodle');
2717 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2719 $currentfile = $options->currentfile;
2720 if (empty($currentfile)) {
2721 $currentfile = '';
2722 } else {
2723 $currentfile .= ' - ';
2725 if ($options->maxbytes) {
2726 $size = $options->maxbytes;
2727 } else {
2728 $size = get_max_upload_file_size();
2730 if ($size == -1) {
2731 $maxsize = '';
2732 } else {
2733 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2735 if ($options->buttonname) {
2736 $buttonname = ' name="' . $options->buttonname . '"';
2737 } else {
2738 $buttonname = '';
2740 $html = <<<EOD
2741 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2742 $icon_progress
2743 </div>
2744 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2745 <div>
2746 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2747 <span> $maxsize </span>
2748 </div>
2749 EOD;
2750 if ($options->env != 'url') {
2751 $html .= <<<EOD
2752 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2753 <div class="filepicker-filename">
2754 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2755 <div class="dndupload-progressbars"></div>
2756 </div>
2757 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2758 </div>
2759 EOD;
2761 $html .= '</div>';
2762 return $html;
2766 * @deprecated since Moodle 3.2
2768 public function update_module_button() {
2769 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2770 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2771 'Themes can choose to display the link in the buttons row consistently for all module types.');
2775 * Returns HTML to display a "Turn editing on/off" button in a form.
2777 * @param moodle_url $url The URL + params to send through when clicking the button
2778 * @return string HTML the button
2780 public function edit_button(moodle_url $url) {
2782 $url->param('sesskey', sesskey());
2783 if ($this->page->user_is_editing()) {
2784 $url->param('edit', 'off');
2785 $editstring = get_string('turneditingoff');
2786 } else {
2787 $url->param('edit', 'on');
2788 $editstring = get_string('turneditingon');
2791 return $this->single_button($url, $editstring);
2795 * Returns HTML to display a simple button to close a window
2797 * @param string $text The lang string for the button's label (already output from get_string())
2798 * @return string html fragment
2800 public function close_window_button($text='') {
2801 if (empty($text)) {
2802 $text = get_string('closewindow');
2804 $button = new single_button(new moodle_url('#'), $text, 'get');
2805 $button->add_action(new component_action('click', 'close_window'));
2807 return $this->container($this->render($button), 'closewindow');
2811 * Output an error message. By default wraps the error message in <span class="error">.
2812 * If the error message is blank, nothing is output.
2814 * @param string $message the error message.
2815 * @return string the HTML to output.
2817 public function error_text($message) {
2818 if (empty($message)) {
2819 return '';
2821 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2822 return html_writer::tag('span', $message, array('class' => 'error'));
2826 * Do not call this function directly.
2828 * To terminate the current script with a fatal error, call the {@link print_error}
2829 * function, or throw an exception. Doing either of those things will then call this
2830 * function to display the error, before terminating the execution.
2832 * @param string $message The message to output
2833 * @param string $moreinfourl URL where more info can be found about the error
2834 * @param string $link Link for the Continue button
2835 * @param array $backtrace The execution backtrace
2836 * @param string $debuginfo Debugging information
2837 * @return string the HTML to output.
2839 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2840 global $CFG;
2842 $output = '';
2843 $obbuffer = '';
2845 if ($this->has_started()) {
2846 // we can not always recover properly here, we have problems with output buffering,
2847 // html tables, etc.
2848 $output .= $this->opencontainers->pop_all_but_last();
2850 } else {
2851 // It is really bad if library code throws exception when output buffering is on,
2852 // because the buffered text would be printed before our start of page.
2853 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2854 error_reporting(0); // disable notices from gzip compression, etc.
2855 while (ob_get_level() > 0) {
2856 $buff = ob_get_clean();
2857 if ($buff === false) {
2858 break;
2860 $obbuffer .= $buff;
2862 error_reporting($CFG->debug);
2864 // Output not yet started.
2865 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2866 if (empty($_SERVER['HTTP_RANGE'])) {
2867 @header($protocol . ' 404 Not Found');
2868 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2869 // Coax iOS 10 into sending the session cookie.
2870 @header($protocol . ' 403 Forbidden');
2871 } else {
2872 // Must stop byteserving attempts somehow,
2873 // this is weird but Chrome PDF viewer can be stopped only with 407!
2874 @header($protocol . ' 407 Proxy Authentication Required');
2877 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2878 $this->page->set_url('/'); // no url
2879 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2880 $this->page->set_title(get_string('error'));
2881 $this->page->set_heading($this->page->course->fullname);
2882 $output .= $this->header();
2885 $message = '<p class="errormessage">' . $message . '</p>'.
2886 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2887 get_string('moreinformation') . '</a></p>';
2888 if (empty($CFG->rolesactive)) {
2889 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2890 //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.
2892 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2894 if ($CFG->debugdeveloper) {
2895 if (!empty($debuginfo)) {
2896 $debuginfo = s($debuginfo); // removes all nasty JS
2897 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2898 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2900 if (!empty($backtrace)) {
2901 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2903 if ($obbuffer !== '' ) {
2904 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2908 if (empty($CFG->rolesactive)) {
2909 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2910 } else if (!empty($link)) {
2911 $output .= $this->continue_button($link);
2914 $output .= $this->footer();
2916 // Padding to encourage IE to display our error page, rather than its own.
2917 $output .= str_repeat(' ', 512);
2919 return $output;
2923 * Output a notification (that is, a status message about something that has just happened).
2925 * Note: \core\notification::add() may be more suitable for your usage.
2927 * @param string $message The message to print out.
2928 * @param string $type The type of notification. See constants on \core\output\notification.
2929 * @return string the HTML to output.
2931 public function notification($message, $type = null) {
2932 $typemappings = [
2933 // Valid types.
2934 'success' => \core\output\notification::NOTIFY_SUCCESS,
2935 'info' => \core\output\notification::NOTIFY_INFO,
2936 'warning' => \core\output\notification::NOTIFY_WARNING,
2937 'error' => \core\output\notification::NOTIFY_ERROR,
2939 // Legacy types mapped to current types.
2940 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2941 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2942 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2943 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2944 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2945 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2946 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2949 $extraclasses = [];
2951 if ($type) {
2952 if (strpos($type, ' ') === false) {
2953 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2954 if (isset($typemappings[$type])) {
2955 $type = $typemappings[$type];
2956 } else {
2957 // The value provided did not match a known type. It must be an extra class.
2958 $extraclasses = [$type];
2960 } else {
2961 // Identify what type of notification this is.
2962 $classarray = explode(' ', self::prepare_classes($type));
2964 // Separate out the type of notification from the extra classes.
2965 foreach ($classarray as $class) {
2966 if (isset($typemappings[$class])) {
2967 $type = $typemappings[$class];
2968 } else {
2969 $extraclasses[] = $class;
2975 $notification = new \core\output\notification($message, $type);
2976 if (count($extraclasses)) {
2977 $notification->set_extra_classes($extraclasses);
2980 // Return the rendered template.
2981 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2985 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2987 public function notify_problem() {
2988 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
2989 'please use \core\notification::add(), or \core\output\notification as required.');
2993 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2995 public function notify_success() {
2996 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
2997 'please use \core\notification::add(), or \core\output\notification as required.');
3001 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3003 public function notify_message() {
3004 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
3005 'please use \core\notification::add(), or \core\output\notification as required.');
3009 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3011 public function notify_redirect() {
3012 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
3013 'please use \core\notification::add(), or \core\output\notification as required.');
3017 * Render a notification (that is, a status message about something that has
3018 * just happened).
3020 * @param \core\output\notification $notification the notification to print out
3021 * @return string the HTML to output.
3023 protected function render_notification(\core\output\notification $notification) {
3024 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3028 * Returns HTML to display a continue button that goes to a particular URL.
3030 * @param string|moodle_url $url The url the button goes to.
3031 * @return string the HTML to output.
3033 public function continue_button($url) {
3034 if (!($url instanceof moodle_url)) {
3035 $url = new moodle_url($url);
3037 $button = new single_button($url, get_string('continue'), 'get', true);
3038 $button->class = 'continuebutton';
3040 return $this->render($button);
3044 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
3046 * Theme developers: DO NOT OVERRIDE! Please override function
3047 * {@link core_renderer::render_paging_bar()} instead.
3049 * @param int $totalcount The total number of entries available to be paged through
3050 * @param int $page The page you are currently viewing
3051 * @param int $perpage The number of entries that should be shown per page
3052 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3053 * @param string $pagevar name of page parameter that holds the page number
3054 * @return string the HTML to output.
3056 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3057 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3058 return $this->render($pb);
3062 * Returns HTML to display the paging bar.
3064 * @param paging_bar $pagingbar
3065 * @return string the HTML to output.
3067 protected function render_paging_bar(paging_bar $pagingbar) {
3068 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3069 $pagingbar->maxdisplay = 10;
3070 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3074 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3076 * @param string $current the currently selected letter.
3077 * @param string $class class name to add to this initial bar.
3078 * @param string $title the name to put in front of this initial bar.
3079 * @param string $urlvar URL parameter name for this initial.
3080 * @param string $url URL object.
3081 * @param array $alpha of letters in the alphabet.
3082 * @return string the HTML to output.
3084 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3085 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3086 return $this->render($ib);
3090 * Internal implementation of initials bar rendering.
3092 * @param initials_bar $initialsbar
3093 * @return string
3095 protected function render_initials_bar(initials_bar $initialsbar) {
3096 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3100 * Output the place a skip link goes to.
3102 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3103 * @return string the HTML to output.
3105 public function skip_link_target($id = null) {
3106 return html_writer::span('', '', array('id' => $id));
3110 * Outputs a heading
3112 * @param string $text The text of the heading
3113 * @param int $level The level of importance of the heading. Defaulting to 2
3114 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3115 * @param string $id An optional ID
3116 * @return string the HTML to output.
3118 public function heading($text, $level = 2, $classes = null, $id = null) {
3119 $level = (integer) $level;
3120 if ($level < 1 or $level > 6) {
3121 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3123 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3127 * Outputs a box.
3129 * @param string $contents The contents of the box
3130 * @param string $classes A space-separated list of CSS classes
3131 * @param string $id An optional ID
3132 * @param array $attributes An array of other attributes to give the box.
3133 * @return string the HTML to output.
3135 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3136 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3140 * Outputs the opening section of a box.
3142 * @param string $classes A space-separated list of CSS classes
3143 * @param string $id An optional ID
3144 * @param array $attributes An array of other attributes to give the box.
3145 * @return string the HTML to output.
3147 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3148 $this->opencontainers->push('box', html_writer::end_tag('div'));
3149 $attributes['id'] = $id;
3150 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
3151 return html_writer::start_tag('div', $attributes);
3155 * Outputs the closing section of a box.
3157 * @return string the HTML to output.
3159 public function box_end() {
3160 return $this->opencontainers->pop('box');
3164 * Outputs a container.
3166 * @param string $contents The contents of the box
3167 * @param string $classes A space-separated list of CSS classes
3168 * @param string $id An optional ID
3169 * @return string the HTML to output.
3171 public function container($contents, $classes = null, $id = null) {
3172 return $this->container_start($classes, $id) . $contents . $this->container_end();
3176 * Outputs the opening section of a container.
3178 * @param string $classes A space-separated list of CSS classes
3179 * @param string $id An optional ID
3180 * @return string the HTML to output.
3182 public function container_start($classes = null, $id = null) {
3183 $this->opencontainers->push('container', html_writer::end_tag('div'));
3184 return html_writer::start_tag('div', array('id' => $id,
3185 'class' => renderer_base::prepare_classes($classes)));
3189 * Outputs the closing section of a container.
3191 * @return string the HTML to output.
3193 public function container_end() {
3194 return $this->opencontainers->pop('container');
3198 * Make nested HTML lists out of the items
3200 * The resulting list will look something like this:
3202 * <pre>
3203 * <<ul>>
3204 * <<li>><div class='tree_item parent'>(item contents)</div>
3205 * <<ul>
3206 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3207 * <</ul>>
3208 * <</li>>
3209 * <</ul>>
3210 * </pre>
3212 * @param array $items
3213 * @param array $attrs html attributes passed to the top ofs the list
3214 * @return string HTML
3216 public function tree_block_contents($items, $attrs = array()) {
3217 // exit if empty, we don't want an empty ul element
3218 if (empty($items)) {
3219 return '';
3221 // array of nested li elements
3222 $lis = array();
3223 foreach ($items as $item) {
3224 // this applies to the li item which contains all child lists too
3225 $content = $item->content($this);
3226 $liclasses = array($item->get_css_type());
3227 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3228 $liclasses[] = 'collapsed';
3230 if ($item->isactive === true) {
3231 $liclasses[] = 'current_branch';
3233 $liattr = array('class'=>join(' ',$liclasses));
3234 // class attribute on the div item which only contains the item content
3235 $divclasses = array('tree_item');
3236 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3237 $divclasses[] = 'branch';
3238 } else {
3239 $divclasses[] = 'leaf';
3241 if (!empty($item->classes) && count($item->classes)>0) {
3242 $divclasses[] = join(' ', $item->classes);
3244 $divattr = array('class'=>join(' ', $divclasses));
3245 if (!empty($item->id)) {
3246 $divattr['id'] = $item->id;
3248 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3249 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3250 $content = html_writer::empty_tag('hr') . $content;
3252 $content = html_writer::tag('li', $content, $liattr);
3253 $lis[] = $content;
3255 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3259 * Returns a search box.
3261 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3262 * @return string HTML with the search form hidden by default.
3264 public function search_box($id = false) {
3265 global $CFG;
3267 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3268 // result in an extra included file for each site, even the ones where global search
3269 // is disabled.
3270 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3271 return '';
3274 if ($id == false) {
3275 $id = uniqid();
3276 } else {
3277 // Needs to be cleaned, we use it for the input id.
3278 $id = clean_param($id, PARAM_ALPHANUMEXT);
3281 // JS to animate the form.
3282 $this->page->requires->js_call_amd('core/search-input', 'init', array($id));
3284 $searchicon = html_writer::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
3285 array('role' => 'button', 'tabindex' => 0));
3286 $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot . '/search/index.php');
3287 $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
3288 'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id, 'class' => 'form-control');
3290 $contents = html_writer::tag('label', get_string('enteryoursearchquery', 'search'),
3291 array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer::tag('input', '', $inputattrs);
3292 if ($this->page->context && $this->page->context->contextlevel !== CONTEXT_SYSTEM) {
3293 $contents .= html_writer::empty_tag('input', ['type' => 'hidden',
3294 'name' => 'context', 'value' => $this->page->context->id]);
3296 $searchinput = html_writer::tag('form', $contents, $formattrs);
3298 return html_writer::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper nav-link', 'id' => $id));
3302 * Allow plugins to provide some content to be rendered in the navbar.
3303 * The plugin must define a PLUGIN_render_navbar_output function that returns
3304 * the HTML they wish to add to the navbar.
3306 * @return string HTML for the navbar
3308 public function navbar_plugin_output() {
3309 $output = '';
3311 // Give subsystems an opportunity to inject extra html content. The callback
3312 // must always return a string containing valid html.
3313 foreach (\core_component::get_core_subsystems() as $name => $path) {
3314 if ($path) {
3315 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3319 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3320 foreach ($pluginsfunction as $plugintype => $plugins) {
3321 foreach ($plugins as $pluginfunction) {
3322 $output .= $pluginfunction($this);
3327 return $output;
3331 * Construct a user menu, returning HTML that can be echoed out by a
3332 * layout file.
3334 * @param stdClass $user A user object, usually $USER.
3335 * @param bool $withlinks true if a dropdown should be built.
3336 * @return string HTML fragment.
3338 public function user_menu($user = null, $withlinks = null) {
3339 global $USER, $CFG;
3340 require_once($CFG->dirroot . '/user/lib.php');
3342 if (is_null($user)) {
3343 $user = $USER;
3346 // Note: this behaviour is intended to match that of core_renderer::login_info,
3347 // but should not be considered to be good practice; layout options are
3348 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3349 if (is_null($withlinks)) {
3350 $withlinks = empty($this->page->layout_options['nologinlinks']);
3353 // Add a class for when $withlinks is false.
3354 $usermenuclasses = 'usermenu';
3355 if (!$withlinks) {
3356 $usermenuclasses .= ' withoutlinks';
3359 $returnstr = "";
3361 // If during initial install, return the empty return string.
3362 if (during_initial_install()) {
3363 return $returnstr;
3366 $loginpage = $this->is_login_page();
3367 $loginurl = get_login_url();
3368 // If not logged in, show the typical not-logged-in string.
3369 if (!isloggedin()) {
3370 $returnstr = get_string('loggedinnot', 'moodle');
3371 if (!$loginpage) {
3372 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3374 return html_writer::div(
3375 html_writer::span(
3376 $returnstr,
3377 'login'
3379 $usermenuclasses
3384 // If logged in as a guest user, show a string to that effect.
3385 if (isguestuser()) {
3386 $returnstr = get_string('loggedinasguest');
3387 if (!$loginpage && $withlinks) {
3388 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3391 return html_writer::div(
3392 html_writer::span(
3393 $returnstr,
3394 'login'
3396 $usermenuclasses
3400 // Get some navigation opts.
3401 $opts = user_get_user_navigation_info($user, $this->page);
3403 $avatarclasses = "avatars";
3404 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3405 $usertextcontents = $opts->metadata['userfullname'];
3407 // Other user.
3408 if (!empty($opts->metadata['asotheruser'])) {
3409 $avatarcontents .= html_writer::span(
3410 $opts->metadata['realuseravatar'],
3411 'avatar realuser'
3413 $usertextcontents = $opts->metadata['realuserfullname'];
3414 $usertextcontents .= html_writer::tag(
3415 'span',
3416 get_string(
3417 'loggedinas',
3418 'moodle',
3419 html_writer::span(
3420 $opts->metadata['userfullname'],
3421 'value'
3424 array('class' => 'meta viewingas')
3428 // Role.
3429 if (!empty($opts->metadata['asotherrole'])) {
3430 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3431 $usertextcontents .= html_writer::span(
3432 $opts->metadata['rolename'],
3433 'meta role role-' . $role
3437 // User login failures.
3438 if (!empty($opts->metadata['userloginfail'])) {
3439 $usertextcontents .= html_writer::span(
3440 $opts->metadata['userloginfail'],
3441 'meta loginfailures'
3445 // MNet.
3446 if (!empty($opts->metadata['asmnetuser'])) {
3447 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3448 $usertextcontents .= html_writer::span(
3449 $opts->metadata['mnetidprovidername'],
3450 'meta mnet mnet-' . $mnet
3454 $returnstr .= html_writer::span(
3455 html_writer::span($usertextcontents, 'usertext mr-1') .
3456 html_writer::span($avatarcontents, $avatarclasses),
3457 'userbutton'
3460 // Create a divider (well, a filler).
3461 $divider = new action_menu_filler();
3462 $divider->primary = false;
3464 $am = new action_menu();
3465 $am->set_menu_trigger(
3466 $returnstr
3468 $am->set_action_label(get_string('usermenu'));
3469 $am->set_alignment(action_menu::TR, action_menu::BR);
3470 $am->set_nowrap_on_items();
3471 if ($withlinks) {
3472 $navitemcount = count($opts->navitems);
3473 $idx = 0;
3474 foreach ($opts->navitems as $key => $value) {
3476 switch ($value->itemtype) {
3477 case 'divider':
3478 // If the nav item is a divider, add one and skip link processing.
3479 $am->add($divider);
3480 break;
3482 case 'invalid':
3483 // Silently skip invalid entries (should we post a notification?).
3484 break;
3486 case 'link':
3487 // Process this as a link item.
3488 $pix = null;
3489 if (isset($value->pix) && !empty($value->pix)) {
3490 $pix = new pix_icon($value->pix, $value->title, null, array('class' => 'iconsmall'));
3491 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3492 $value->title = html_writer::img(
3493 $value->imgsrc,
3494 $value->title,
3495 array('class' => 'iconsmall')
3496 ) . $value->title;
3499 $al = new action_menu_link_secondary(
3500 $value->url,
3501 $pix,
3502 $value->title,
3503 array('class' => 'icon')
3505 if (!empty($value->titleidentifier)) {
3506 $al->attributes['data-title'] = $value->titleidentifier;
3508 $am->add($al);
3509 break;
3512 $idx++;
3514 // Add dividers after the first item and before the last item.
3515 if ($idx == 1 || $idx == $navitemcount - 1) {
3516 $am->add($divider);
3521 return html_writer::div(
3522 $this->render($am),
3523 $usermenuclasses
3528 * Return the navbar content so that it can be echoed out by the layout
3530 * @return string XHTML navbar
3532 public function navbar() {
3533 $items = $this->page->navbar->get_items();
3534 $itemcount = count($items);
3535 if ($itemcount === 0) {
3536 return '';
3539 $htmlblocks = array();
3540 // Iterate the navarray and display each node
3541 $separator = get_separator();
3542 for ($i=0;$i < $itemcount;$i++) {
3543 $item = $items[$i];
3544 $item->hideicon = true;
3545 if ($i===0) {
3546 $content = html_writer::tag('li', $this->render($item));
3547 } else {
3548 $content = html_writer::tag('li', $separator.$this->render($item));
3550 $htmlblocks[] = $content;
3553 //accessibility: heading for navbar list (MDL-20446)
3554 $navbarcontent = html_writer::tag('span', get_string('pagepath'),
3555 array('class' => 'accesshide', 'id' => 'navbar-label'));
3556 $navbarcontent .= html_writer::tag('nav',
3557 html_writer::tag('ul', join('', $htmlblocks)),
3558 array('aria-labelledby' => 'navbar-label'));
3559 // XHTML
3560 return $navbarcontent;
3564 * Renders a breadcrumb navigation node object.
3566 * @param breadcrumb_navigation_node $item The navigation node to render.
3567 * @return string HTML fragment
3569 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3571 if ($item->action instanceof moodle_url) {
3572 $content = $item->get_content();
3573 $title = $item->get_title();
3574 $attributes = array();
3575 $attributes['itemprop'] = 'url';
3576 if ($title !== '') {
3577 $attributes['title'] = $title;
3579 if ($item->hidden) {
3580 $attributes['class'] = 'dimmed_text';
3582 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3583 $content = html_writer::link($item->action, $content, $attributes);
3585 $attributes = array();
3586 $attributes['itemscope'] = '';
3587 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3588 $content = html_writer::tag('span', $content, $attributes);
3590 } else {
3591 $content = $this->render_navigation_node($item);
3593 return $content;
3597 * Renders a navigation node object.
3599 * @param navigation_node $item The navigation node to render.
3600 * @return string HTML fragment
3602 protected function render_navigation_node(navigation_node $item) {
3603 $content = $item->get_content();
3604 $title = $item->get_title();
3605 if ($item->icon instanceof renderable && !$item->hideicon) {
3606 $icon = $this->render($item->icon);
3607 $content = $icon.$content; // use CSS for spacing of icons
3609 if ($item->helpbutton !== null) {
3610 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3612 if ($content === '') {
3613 return '';
3615 if ($item->action instanceof action_link) {
3616 $link = $item->action;
3617 if ($item->hidden) {
3618 $link->add_class('dimmed');
3620 if (!empty($content)) {
3621 // Providing there is content we will use that for the link content.
3622 $link->text = $content;
3624 $content = $this->render($link);
3625 } else if ($item->action instanceof moodle_url) {
3626 $attributes = array();
3627 if ($title !== '') {
3628 $attributes['title'] = $title;
3630 if ($item->hidden) {
3631 $attributes['class'] = 'dimmed_text';
3633 $content = html_writer::link($item->action, $content, $attributes);
3635 } else if (is_string($item->action) || empty($item->action)) {
3636 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3637 if ($title !== '') {
3638 $attributes['title'] = $title;
3640 if ($item->hidden) {
3641 $attributes['class'] = 'dimmed_text';
3643 $content = html_writer::tag('span', $content, $attributes);
3645 return $content;
3649 * Accessibility: Right arrow-like character is
3650 * used in the breadcrumb trail, course navigation menu
3651 * (previous/next activity), calendar, and search forum block.
3652 * If the theme does not set characters, appropriate defaults
3653 * are set automatically. Please DO NOT
3654 * use &lt; &gt; &raquo; - these are confusing for blind users.
3656 * @return string
3658 public function rarrow() {
3659 return $this->page->theme->rarrow;
3663 * Accessibility: Left arrow-like character is
3664 * used in the breadcrumb trail, course navigation menu
3665 * (previous/next activity), calendar, and search forum block.
3666 * If the theme does not set characters, appropriate defaults
3667 * are set automatically. Please DO NOT
3668 * use &lt; &gt; &raquo; - these are confusing for blind users.
3670 * @return string
3672 public function larrow() {
3673 return $this->page->theme->larrow;
3677 * Accessibility: Up arrow-like character is used in
3678 * the book heirarchical navigation.
3679 * If the theme does not set characters, appropriate defaults
3680 * are set automatically. Please DO NOT
3681 * use ^ - this is confusing for blind users.
3683 * @return string
3685 public function uarrow() {
3686 return $this->page->theme->uarrow;
3690 * Accessibility: Down arrow-like character.
3691 * If the theme does not set characters, appropriate defaults
3692 * are set automatically.
3694 * @return string
3696 public function darrow() {
3697 return $this->page->theme->darrow;
3701 * Returns the custom menu if one has been set
3703 * A custom menu can be configured by browsing to
3704 * Settings: Administration > Appearance > Themes > Theme settings
3705 * and then configuring the custommenu config setting as described.
3707 * Theme developers: DO NOT OVERRIDE! Please override function
3708 * {@link core_renderer::render_custom_menu()} instead.
3710 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3711 * @return string
3713 public function custom_menu($custommenuitems = '') {
3714 global $CFG;
3715 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3716 $custommenuitems = $CFG->custommenuitems;
3718 if (empty($custommenuitems)) {
3719 return '';
3721 $custommenu = new custom_menu($custommenuitems, current_language());
3722 return $this->render($custommenu);
3726 * Renders a custom menu object (located in outputcomponents.php)
3728 * The custom menu this method produces makes use of the YUI3 menunav widget
3729 * and requires very specific html elements and classes.
3731 * @staticvar int $menucount
3732 * @param custom_menu $menu
3733 * @return string
3735 protected function render_custom_menu(custom_menu $menu) {
3736 static $menucount = 0;
3737 // If the menu has no children return an empty string
3738 if (!$menu->has_children()) {
3739 return '';
3741 // Increment the menu count. This is used for ID's that get worked with
3742 // in JavaScript as is essential
3743 $menucount++;
3744 // Initialise this custom menu (the custom menu object is contained in javascript-static
3745 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
3746 $jscode = "(function(){{$jscode}})";
3747 $this->page->requires->yui_module('node-menunav', $jscode);
3748 // Build the root nodes as required by YUI
3749 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
3750 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3751 $content .= html_writer::start_tag('ul');
3752 // Render each child
3753 foreach ($menu->get_children() as $item) {
3754 $content .= $this->render_custom_menu_item($item);
3756 // Close the open tags
3757 $content .= html_writer::end_tag('ul');
3758 $content .= html_writer::end_tag('div');
3759 $content .= html_writer::end_tag('div');
3760 // Return the custom menu
3761 return $content;
3765 * Renders a custom menu node as part of a submenu
3767 * The custom menu this method produces makes use of the YUI3 menunav widget
3768 * and requires very specific html elements and classes.
3770 * @see core:renderer::render_custom_menu()
3772 * @staticvar int $submenucount
3773 * @param custom_menu_item $menunode
3774 * @return string
3776 protected function render_custom_menu_item(custom_menu_item $menunode) {
3777 // Required to ensure we get unique trackable id's
3778 static $submenucount = 0;
3779 if ($menunode->has_children()) {
3780 // If the child has menus render it as a sub menu
3781 $submenucount++;
3782 $content = html_writer::start_tag('li');
3783 if ($menunode->get_url() !== null) {
3784 $url = $menunode->get_url();
3785 } else {
3786 $url = '#cm_submenu_'.$submenucount;
3788 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3789 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3790 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3791 $content .= html_writer::start_tag('ul');
3792 foreach ($menunode->get_children() as $menunode) {
3793 $content .= $this->render_custom_menu_item($menunode);
3795 $content .= html_writer::end_tag('ul');
3796 $content .= html_writer::end_tag('div');
3797 $content .= html_writer::end_tag('div');
3798 $content .= html_writer::end_tag('li');
3799 } else {
3800 // The node doesn't have children so produce a final menuitem.
3801 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3802 $content = '';
3803 if (preg_match("/^#+$/", $menunode->get_text())) {
3805 // This is a divider.
3806 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3807 } else {
3808 $content = html_writer::start_tag(
3809 'li',
3810 array(
3811 'class' => 'yui3-menuitem'
3814 if ($menunode->get_url() !== null) {
3815 $url = $menunode->get_url();
3816 } else {
3817 $url = '#';
3819 $content .= html_writer::link(
3820 $url,
3821 $menunode->get_text(),
3822 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3825 $content .= html_writer::end_tag('li');
3827 // Return the sub menu
3828 return $content;
3832 * Renders theme links for switching between default and other themes.
3834 * @return string
3836 protected function theme_switch_links() {
3838 $actualdevice = core_useragent::get_device_type();
3839 $currentdevice = $this->page->devicetypeinuse;
3840 $switched = ($actualdevice != $currentdevice);
3842 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3843 // The user is using the a default device and hasn't switched so don't shown the switch
3844 // device links.
3845 return '';
3848 if ($switched) {
3849 $linktext = get_string('switchdevicerecommended');
3850 $devicetype = $actualdevice;
3851 } else {
3852 $linktext = get_string('switchdevicedefault');
3853 $devicetype = 'default';
3855 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3857 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3858 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3859 $content .= html_writer::end_tag('div');
3861 return $content;
3865 * Renders tabs
3867 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3869 * Theme developers: In order to change how tabs are displayed please override functions
3870 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3872 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3873 * @param string|null $selected which tab to mark as selected, all parent tabs will
3874 * automatically be marked as activated
3875 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3876 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3877 * @return string
3879 public final function tabtree($tabs, $selected = null, $inactive = null) {
3880 return $this->render(new tabtree($tabs, $selected, $inactive));
3884 * Renders tabtree
3886 * @param tabtree $tabtree
3887 * @return string
3889 protected function render_tabtree(tabtree $tabtree) {
3890 if (empty($tabtree->subtree)) {
3891 return '';
3893 $str = '';
3894 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
3895 $str .= $this->render_tabobject($tabtree);
3896 $str .= html_writer::end_tag('div').
3897 html_writer::tag('div', ' ', array('class' => 'clearer'));
3898 return $str;
3902 * Renders tabobject (part of tabtree)
3904 * This function is called from {@link core_renderer::render_tabtree()}
3905 * and also it calls itself when printing the $tabobject subtree recursively.
3907 * Property $tabobject->level indicates the number of row of tabs.
3909 * @param tabobject $tabobject
3910 * @return string HTML fragment
3912 protected function render_tabobject(tabobject $tabobject) {
3913 $str = '';
3915 // Print name of the current tab.
3916 if ($tabobject instanceof tabtree) {
3917 // No name for tabtree root.
3918 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3919 // Tab name without a link. The <a> tag is used for styling.
3920 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3921 } else {
3922 // Tab name with a link.
3923 if (!($tabobject->link instanceof moodle_url)) {
3924 // backward compartibility when link was passed as quoted string
3925 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3926 } else {
3927 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3931 if (empty($tabobject->subtree)) {
3932 if ($tabobject->selected) {
3933 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3935 return $str;
3938 // Print subtree.
3939 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
3940 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3941 $cnt = 0;
3942 foreach ($tabobject->subtree as $tab) {
3943 $liclass = '';
3944 if (!$cnt) {
3945 $liclass .= ' first';
3947 if ($cnt == count($tabobject->subtree) - 1) {
3948 $liclass .= ' last';
3950 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3951 $liclass .= ' onerow';
3954 if ($tab->selected) {
3955 $liclass .= ' here selected';
3956 } else if ($tab->activated) {
3957 $liclass .= ' here active';
3960 // This will recursively call function render_tabobject() for each item in subtree.
3961 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3962 $cnt++;
3964 $str .= html_writer::end_tag('ul');
3967 return $str;
3971 * Get the HTML for blocks in the given region.
3973 * @since Moodle 2.5.1 2.6
3974 * @param string $region The region to get HTML for.
3975 * @return string HTML.
3977 public function blocks($region, $classes = array(), $tag = 'aside') {
3978 $displayregion = $this->page->apply_theme_region_manipulations($region);
3979 $classes = (array)$classes;
3980 $classes[] = 'block-region';
3981 $attributes = array(
3982 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3983 'class' => join(' ', $classes),
3984 'data-blockregion' => $displayregion,
3985 'data-droptarget' => '1'
3987 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3988 $content = $this->blocks_for_region($displayregion);
3989 } else {
3990 $content = '';
3992 return html_writer::tag($tag, $content, $attributes);
3996 * Renders a custom block region.
3998 * Use this method if you want to add an additional block region to the content of the page.
3999 * Please note this should only be used in special situations.
4000 * We want to leave the theme is control where ever possible!
4002 * This method must use the same method that the theme uses within its layout file.
4003 * As such it asks the theme what method it is using.
4004 * It can be one of two values, blocks or blocks_for_region (deprecated).
4006 * @param string $regionname The name of the custom region to add.
4007 * @return string HTML for the block region.
4009 public function custom_block_region($regionname) {
4010 if ($this->page->theme->get_block_render_method() === 'blocks') {
4011 return $this->blocks($regionname);
4012 } else {
4013 return $this->blocks_for_region($regionname);
4018 * Returns the CSS classes to apply to the body tag.
4020 * @since Moodle 2.5.1 2.6
4021 * @param array $additionalclasses Any additional classes to apply.
4022 * @return string
4024 public function body_css_classes(array $additionalclasses = array()) {
4025 // Add a class for each block region on the page.
4026 // We use the block manager here because the theme object makes get_string calls.
4027 $usedregions = array();
4028 foreach ($this->page->blocks->get_regions() as $region) {
4029 $additionalclasses[] = 'has-region-'.$region;
4030 if ($this->page->blocks->region_has_content($region, $this)) {
4031 $additionalclasses[] = 'used-region-'.$region;
4032 $usedregions[] = $region;
4033 } else {
4034 $additionalclasses[] = 'empty-region-'.$region;
4036 if ($this->page->blocks->region_completely_docked($region, $this)) {
4037 $additionalclasses[] = 'docked-region-'.$region;
4040 if (!$usedregions) {
4041 // No regions means there is only content, add 'content-only' class.
4042 $additionalclasses[] = 'content-only';
4043 } else if (count($usedregions) === 1) {
4044 // Add the -only class for the only used region.
4045 $region = array_shift($usedregions);
4046 $additionalclasses[] = $region . '-only';
4048 foreach ($this->page->layout_options as $option => $value) {
4049 if ($value) {
4050 $additionalclasses[] = 'layout-option-'.$option;
4053 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
4054 return $css;
4058 * The ID attribute to apply to the body tag.
4060 * @since Moodle 2.5.1 2.6
4061 * @return string
4063 public function body_id() {
4064 return $this->page->bodyid;
4068 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4070 * @since Moodle 2.5.1 2.6
4071 * @param string|array $additionalclasses Any additional classes to give the body tag,
4072 * @return string
4074 public function body_attributes($additionalclasses = array()) {
4075 if (!is_array($additionalclasses)) {
4076 $additionalclasses = explode(' ', $additionalclasses);
4078 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4082 * Gets HTML for the page heading.
4084 * @since Moodle 2.5.1 2.6
4085 * @param string $tag The tag to encase the heading in. h1 by default.
4086 * @return string HTML.
4088 public function page_heading($tag = 'h1') {
4089 return html_writer::tag($tag, $this->page->heading);
4093 * Gets the HTML for the page heading button.
4095 * @since Moodle 2.5.1 2.6
4096 * @return string HTML.
4098 public function page_heading_button() {
4099 return $this->page->button;
4103 * Returns the Moodle docs link to use for this page.
4105 * @since Moodle 2.5.1 2.6
4106 * @param string $text
4107 * @return string
4109 public function page_doc_link($text = null) {
4110 if ($text === null) {
4111 $text = get_string('moodledocslink');
4113 $path = page_get_doc_link_path($this->page);
4114 if (!$path) {
4115 return '';
4117 return $this->doc_link($path, $text);
4121 * Returns the page heading menu.
4123 * @since Moodle 2.5.1 2.6
4124 * @return string HTML.
4126 public function page_heading_menu() {
4127 return $this->page->headingmenu;
4131 * Returns the title to use on the page.
4133 * @since Moodle 2.5.1 2.6
4134 * @return string
4136 public function page_title() {
4137 return $this->page->title;
4141 * Returns the URL for the favicon.
4143 * @since Moodle 2.5.1 2.6
4144 * @return string The favicon URL
4146 public function favicon() {
4147 return $this->image_url('favicon', 'theme');
4151 * Renders preferences groups.
4153 * @param preferences_groups $renderable The renderable
4154 * @return string The output.
4156 public function render_preferences_groups(preferences_groups $renderable) {
4157 $html = '';
4158 $html .= html_writer::start_div('row-fluid');
4159 $html .= html_writer::start_tag('div', array('class' => 'span12 preferences-groups'));
4160 $i = 0;
4161 $open = false;
4162 foreach ($renderable->groups as $group) {
4163 if ($i == 0 || $i % 3 == 0) {
4164 if ($open) {
4165 $html .= html_writer::end_tag('div');
4167 $html .= html_writer::start_tag('div', array('class' => 'row-fluid'));
4168 $open = true;
4170 $html .= $this->render($group);
4171 $i++;
4174 $html .= html_writer::end_tag('div');
4176 $html .= html_writer::end_tag('ul');
4177 $html .= html_writer::end_tag('div');
4178 $html .= html_writer::end_div();
4179 return $html;
4183 * Renders preferences group.
4185 * @param preferences_group $renderable The renderable
4186 * @return string The output.
4188 public function render_preferences_group(preferences_group $renderable) {
4189 $html = '';
4190 $html .= html_writer::start_tag('div', array('class' => 'span4 preferences-group'));
4191 $html .= $this->heading($renderable->title, 3);
4192 $html .= html_writer::start_tag('ul');
4193 foreach ($renderable->nodes as $node) {
4194 if ($node->has_children()) {
4195 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4197 $html .= html_writer::tag('li', $this->render($node));
4199 $html .= html_writer::end_tag('ul');
4200 $html .= html_writer::end_tag('div');
4201 return $html;
4204 public function context_header($headerinfo = null, $headinglevel = 1) {
4205 global $DB, $USER, $CFG;
4206 require_once($CFG->dirroot . '/user/lib.php');
4207 $context = $this->page->context;
4208 $heading = null;
4209 $imagedata = null;
4210 $subheader = null;
4211 $userbuttons = null;
4212 // Make sure to use the heading if it has been set.
4213 if (isset($headerinfo['heading'])) {
4214 $heading = $headerinfo['heading'];
4217 // The user context currently has images and buttons. Other contexts may follow.
4218 if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
4219 if (isset($headerinfo['user'])) {
4220 $user = $headerinfo['user'];
4221 } else {
4222 // Look up the user information if it is not supplied.
4223 $user = $DB->get_record('user', array('id' => $context->instanceid));
4226 // If the user context is set, then use that for capability checks.
4227 if (isset($headerinfo['usercontext'])) {
4228 $context = $headerinfo['usercontext'];
4231 // Only provide user information if the user is the current user, or a user which the current user can view.
4232 // When checking user_can_view_profile(), either:
4233 // If the page context is course, check the course context (from the page object) or;
4234 // If page context is NOT course, then check across all courses.
4235 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4237 if (user_can_view_profile($user, $course)) {
4238 // Use the user's full name if the heading isn't set.
4239 if (!isset($heading)) {
4240 $heading = fullname($user);
4243 $imagedata = $this->user_picture($user, array('size' => 100));
4245 // Check to see if we should be displaying a message button.
4246 if (!empty($CFG->messaging) && $USER->id != $user->id && has_capability('moodle/site:sendmessage', $context)) {
4247 $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4248 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4249 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4250 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4251 $userbuttons = array(
4252 'messages' => array(
4253 'buttontype' => 'message',
4254 'title' => get_string('message', 'message'),
4255 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4256 'image' => 'message',
4257 'linkattributes' => array('role' => 'button'),
4258 'page' => $this->page
4260 'togglecontact' => array(
4261 'buttontype' => 'togglecontact',
4262 'title' => get_string($contacttitle, 'message'),
4263 'url' => new moodle_url('/message/index.php', array(
4264 'user1' => $USER->id,
4265 'user2' => $user->id,
4266 $contacturlaction => $user->id,
4267 'sesskey' => sesskey())
4269 'image' => $contactimage,
4270 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4271 'page' => $this->page
4275 $this->page->requires->string_for_js('changesmadereallygoaway', 'moodle');
4277 } else {
4278 $heading = null;
4282 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4283 return $this->render_context_header($contextheader);
4287 * Renders the skip links for the page.
4289 * @param array $links List of skip links.
4290 * @return string HTML for the skip links.
4292 public function render_skip_links($links) {
4293 $context = [ 'links' => []];
4295 foreach ($links as $url => $text) {
4296 $context['links'][] = [ 'url' => $url, 'text' => $text];
4299 return $this->render_from_template('core/skip_links', $context);
4303 * Renders the header bar.
4305 * @param context_header $contextheader Header bar object.
4306 * @return string HTML for the header bar.
4308 protected function render_context_header(context_header $contextheader) {
4310 $showheader = empty($this->page->layout_options['nocontextheader']);
4311 if (!$showheader) {
4312 return '';
4315 // All the html stuff goes here.
4316 $html = html_writer::start_div('page-context-header');
4318 // Image data.
4319 if (isset($contextheader->imagedata)) {
4320 // Header specific image.
4321 $html .= html_writer::div($contextheader->imagedata, 'page-header-image');
4324 // Headings.
4325 if (!isset($contextheader->heading)) {
4326 $headings = $this->heading($this->page->heading, $contextheader->headinglevel);
4327 } else {
4328 $headings = $this->heading($contextheader->heading, $contextheader->headinglevel);
4331 $html .= html_writer::tag('div', $headings, array('class' => 'page-header-headings'));
4333 // Buttons.
4334 if (isset($contextheader->additionalbuttons)) {
4335 $html .= html_writer::start_div('btn-group header-button-group');
4336 foreach ($contextheader->additionalbuttons as $button) {
4337 if (!isset($button->page)) {
4338 // Include js for messaging.
4339 if ($button['buttontype'] === 'togglecontact') {
4340 \core_message\helper::togglecontact_requirejs();
4342 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4343 'class' => 'iconsmall',
4344 'role' => 'presentation'
4346 $image .= html_writer::span($button['title'], 'header-button-title');
4347 } else {
4348 $image = html_writer::empty_tag('img', array(
4349 'src' => $button['formattedimage'],
4350 'role' => 'presentation'
4353 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4355 $html .= html_writer::end_div();
4357 $html .= html_writer::end_div();
4359 return $html;
4363 * Wrapper for header elements.
4365 * @return string HTML to display the main header.
4367 public function full_header() {
4368 $html = html_writer::start_tag('header', array('id' => 'page-header', 'class' => 'clearfix'));
4369 $html .= $this->context_header();
4370 $html .= html_writer::start_div('clearfix', array('id' => 'page-navbar'));
4371 $html .= html_writer::tag('div', $this->navbar(), array('class' => 'breadcrumb-nav'));
4372 $html .= html_writer::div($this->page_heading_button(), 'breadcrumb-button');
4373 $html .= html_writer::end_div();
4374 $html .= html_writer::tag('div', $this->course_header(), array('id' => 'course-header'));
4375 $html .= html_writer::end_tag('header');
4376 return $html;
4380 * Displays the list of tags associated with an entry
4382 * @param array $tags list of instances of core_tag or stdClass
4383 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4384 * to use default, set to '' (empty string) to omit the label completely
4385 * @param string $classes additional classes for the enclosing div element
4386 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4387 * will be appended to the end, JS will toggle the rest of the tags
4388 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4389 * @return string
4391 public function tag_list($tags, $label = null, $classes = '', $limit = 10, $pagecontext = null) {
4392 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext);
4393 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4397 * Renders element for inline editing of any value
4399 * @param \core\output\inplace_editable $element
4400 * @return string
4402 public function render_inplace_editable(\core\output\inplace_editable $element) {
4403 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4407 * Renders a bar chart.
4409 * @param \core\chart_bar $chart The chart.
4410 * @return string.
4412 public function render_chart_bar(\core\chart_bar $chart) {
4413 return $this->render_chart($chart);
4417 * Renders a line chart.
4419 * @param \core\chart_line $chart The chart.
4420 * @return string.
4422 public function render_chart_line(\core\chart_line $chart) {
4423 return $this->render_chart($chart);
4427 * Renders a pie chart.
4429 * @param \core\chart_pie $chart The chart.
4430 * @return string.
4432 public function render_chart_pie(\core\chart_pie $chart) {
4433 return $this->render_chart($chart);
4437 * Renders a chart.
4439 * @param \core\chart_base $chart The chart.
4440 * @param bool $withtable Whether to include a data table with the chart.
4441 * @return string.
4443 public function render_chart(\core\chart_base $chart, $withtable = true) {
4444 $chartdata = json_encode($chart);
4445 return $this->render_from_template('core/chart', (object) [
4446 'chartdata' => $chartdata,
4447 'withtable' => $withtable
4452 * Renders the login form.
4454 * @param \core_auth\output\login $form The renderable.
4455 * @return string
4457 public function render_login(\core_auth\output\login $form) {
4458 global $CFG;
4460 $context = $form->export_for_template($this);
4462 // Override because rendering is not supported in template yet.
4463 if ($CFG->rememberusername == 0) {
4464 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabledonlysession');
4465 } else {
4466 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
4468 $context->errorformatted = $this->error_text($context->error);
4470 return $this->render_from_template('core/loginform', $context);
4474 * Renders an mform element from a template.
4476 * @param HTML_QuickForm_element $element element
4477 * @param bool $required if input is required field
4478 * @param bool $advanced if input is an advanced field
4479 * @param string $error error message to display
4480 * @param bool $ingroup True if this element is rendered as part of a group
4481 * @return mixed string|bool
4483 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4484 $templatename = 'core_form/element-' . $element->getType();
4485 if ($ingroup) {
4486 $templatename .= "-inline";
4488 try {
4489 // We call this to generate a file not found exception if there is no template.
4490 // We don't want to call export_for_template if there is no template.
4491 core\output\mustache_template_finder::get_template_filepath($templatename);
4493 if ($element instanceof templatable) {
4494 $elementcontext = $element->export_for_template($this);
4496 $helpbutton = '';
4497 if (method_exists($element, 'getHelpButton')) {
4498 $helpbutton = $element->getHelpButton();
4500 $label = $element->getLabel();
4501 $text = '';
4502 if (method_exists($element, 'getText')) {
4503 // There currently exists code that adds a form element with an empty label.
4504 // If this is the case then set the label to the description.
4505 if (empty($label)) {
4506 $label = $element->getText();
4507 } else {
4508 $text = $element->getText();
4512 $context = array(
4513 'element' => $elementcontext,
4514 'label' => $label,
4515 'text' => $text,
4516 'required' => $required,
4517 'advanced' => $advanced,
4518 'helpbutton' => $helpbutton,
4519 'error' => $error
4521 return $this->render_from_template($templatename, $context);
4523 } catch (Exception $e) {
4524 // No template for this element.
4525 return false;
4530 * Render the login signup form into a nice template for the theme.
4532 * @param mform $form
4533 * @return string
4535 public function render_login_signup_form($form) {
4536 $context = $form->export_for_template($this);
4538 return $this->render_from_template('core/signup_form_layout', $context);
4542 * Render the verify age and location page into a nice template for the theme.
4544 * @param \core_auth\output\verify_age_location_page $page The renderable
4545 * @return string
4547 protected function render_verify_age_location_page($page) {
4548 $context = $page->export_for_template($this);
4550 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4554 * Render the digital minor contact information page into a nice template for the theme.
4556 * @param \core_auth\output\digital_minor_page $page The renderable
4557 * @return string
4559 protected function render_digital_minor_page($page) {
4560 $context = $page->export_for_template($this);
4562 return $this->render_from_template('core/auth_digital_minor_page', $context);
4566 * Renders a progress bar.
4568 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4570 * @param progress_bar $bar The bar.
4571 * @return string HTML fragment
4573 public function render_progress_bar(progress_bar $bar) {
4574 global $PAGE;
4575 $data = $bar->export_for_template($this);
4576 return $this->render_from_template('core/progress_bar', $data);
4581 * A renderer that generates output for command-line scripts.
4583 * The implementation of this renderer is probably incomplete.
4585 * @copyright 2009 Tim Hunt
4586 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4587 * @since Moodle 2.0
4588 * @package core
4589 * @category output
4591 class core_renderer_cli extends core_renderer {
4594 * Returns the page header.
4596 * @return string HTML fragment
4598 public function header() {
4599 return $this->page->heading . "\n";
4603 * Returns a template fragment representing a Heading.
4605 * @param string $text The text of the heading
4606 * @param int $level The level of importance of the heading
4607 * @param string $classes A space-separated list of CSS classes
4608 * @param string $id An optional ID
4609 * @return string A template fragment for a heading
4611 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4612 $text .= "\n";
4613 switch ($level) {
4614 case 1:
4615 return '=>' . $text;
4616 case 2:
4617 return '-->' . $text;
4618 default:
4619 return $text;
4624 * Returns a template fragment representing a fatal error.
4626 * @param string $message The message to output
4627 * @param string $moreinfourl URL where more info can be found about the error
4628 * @param string $link Link for the Continue button
4629 * @param array $backtrace The execution backtrace
4630 * @param string $debuginfo Debugging information
4631 * @return string A template fragment for a fatal error
4633 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4634 global $CFG;
4636 $output = "!!! $message !!!\n";
4638 if ($CFG->debugdeveloper) {
4639 if (!empty($debuginfo)) {
4640 $output .= $this->notification($debuginfo, 'notifytiny');
4642 if (!empty($backtrace)) {
4643 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
4647 return $output;
4651 * Returns a template fragment representing a notification.
4653 * @param string $message The message to print out.
4654 * @param string $type The type of notification. See constants on \core\output\notification.
4655 * @return string A template fragment for a notification
4657 public function notification($message, $type = null) {
4658 $message = clean_text($message);
4659 if ($type === 'notifysuccess' || $type === 'success') {
4660 return "++ $message ++\n";
4662 return "!! $message !!\n";
4666 * There is no footer for a cli request, however we must override the
4667 * footer method to prevent the default footer.
4669 public function footer() {}
4672 * Render a notification (that is, a status message about something that has
4673 * just happened).
4675 * @param \core\output\notification $notification the notification to print out
4676 * @return string plain text output
4678 public function render_notification(\core\output\notification $notification) {
4679 return $this->notification($notification->get_message(), $notification->get_message_type());
4685 * A renderer that generates output for ajax scripts.
4687 * This renderer prevents accidental sends back only json
4688 * encoded error messages, all other output is ignored.
4690 * @copyright 2010 Petr Skoda
4691 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4692 * @since Moodle 2.0
4693 * @package core
4694 * @category output
4696 class core_renderer_ajax extends core_renderer {
4699 * Returns a template fragment representing a fatal error.
4701 * @param string $message The message to output
4702 * @param string $moreinfourl URL where more info can be found about the error
4703 * @param string $link Link for the Continue button
4704 * @param array $backtrace The execution backtrace
4705 * @param string $debuginfo Debugging information
4706 * @return string A template fragment for a fatal error
4708 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4709 global $CFG;
4711 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
4713 $e = new stdClass();
4714 $e->error = $message;
4715 $e->errorcode = $errorcode;
4716 $e->stacktrace = NULL;
4717 $e->debuginfo = NULL;
4718 $e->reproductionlink = NULL;
4719 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
4720 $link = (string) $link;
4721 if ($link) {
4722 $e->reproductionlink = $link;
4724 if (!empty($debuginfo)) {
4725 $e->debuginfo = $debuginfo;
4727 if (!empty($backtrace)) {
4728 $e->stacktrace = format_backtrace($backtrace, true);
4731 $this->header();
4732 return json_encode($e);
4736 * Used to display a notification.
4737 * For the AJAX notifications are discarded.
4739 * @param string $message The message to print out.
4740 * @param string $type The type of notification. See constants on \core\output\notification.
4742 public function notification($message, $type = null) {}
4745 * Used to display a redirection message.
4746 * AJAX redirections should not occur and as such redirection messages
4747 * are discarded.
4749 * @param moodle_url|string $encodedurl
4750 * @param string $message
4751 * @param int $delay
4752 * @param bool $debugdisableredirect
4753 * @param string $messagetype The type of notification to show the message in.
4754 * See constants on \core\output\notification.
4756 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
4757 $messagetype = \core\output\notification::NOTIFY_INFO) {}
4760 * Prepares the start of an AJAX output.
4762 public function header() {
4763 // unfortunately YUI iframe upload does not support application/json
4764 if (!empty($_FILES)) {
4765 @header('Content-type: text/plain; charset=utf-8');
4766 if (!core_useragent::supports_json_contenttype()) {
4767 @header('X-Content-Type-Options: nosniff');
4769 } else if (!core_useragent::supports_json_contenttype()) {
4770 @header('Content-type: text/plain; charset=utf-8');
4771 @header('X-Content-Type-Options: nosniff');
4772 } else {
4773 @header('Content-type: application/json; charset=utf-8');
4776 // Headers to make it not cacheable and json
4777 @header('Cache-Control: no-store, no-cache, must-revalidate');
4778 @header('Cache-Control: post-check=0, pre-check=0', false);
4779 @header('Pragma: no-cache');
4780 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
4781 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
4782 @header('Accept-Ranges: none');
4786 * There is no footer for an AJAX request, however we must override the
4787 * footer method to prevent the default footer.
4789 public function footer() {}
4792 * No need for headers in an AJAX request... this should never happen.
4793 * @param string $text
4794 * @param int $level
4795 * @param string $classes
4796 * @param string $id
4798 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
4804 * The maintenance renderer.
4806 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
4807 * is running a maintenance related task.
4808 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
4810 * @since Moodle 2.6
4811 * @package core
4812 * @category output
4813 * @copyright 2013 Sam Hemelryk
4814 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4816 class core_renderer_maintenance extends core_renderer {
4819 * Initialises the renderer instance.
4820 * @param moodle_page $page
4821 * @param string $target
4822 * @throws coding_exception
4824 public function __construct(moodle_page $page, $target) {
4825 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
4826 throw new coding_exception('Invalid request for the maintenance renderer.');
4828 parent::__construct($page, $target);
4832 * Does nothing. The maintenance renderer cannot produce blocks.
4834 * @param block_contents $bc
4835 * @param string $region
4836 * @return string
4838 public function block(block_contents $bc, $region) {
4839 // Computer says no blocks.
4840 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4841 return '';
4845 * Does nothing. The maintenance renderer cannot produce blocks.
4847 * @param string $region
4848 * @param array $classes
4849 * @param string $tag
4850 * @return string
4852 public function blocks($region, $classes = array(), $tag = 'aside') {
4853 // Computer says no blocks.
4854 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4855 return '';
4859 * Does nothing. The maintenance renderer cannot produce blocks.
4861 * @param string $region
4862 * @return string
4864 public function blocks_for_region($region) {
4865 // Computer says no blocks for region.
4866 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4867 return '';
4871 * Does nothing. The maintenance renderer cannot produce a course content header.
4873 * @param bool $onlyifnotcalledbefore
4874 * @return string
4876 public function course_content_header($onlyifnotcalledbefore = false) {
4877 // Computer says no course content header.
4878 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4879 return '';
4883 * Does nothing. The maintenance renderer cannot produce a course content footer.
4885 * @param bool $onlyifnotcalledbefore
4886 * @return string
4888 public function course_content_footer($onlyifnotcalledbefore = false) {
4889 // Computer says no course content footer.
4890 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4891 return '';
4895 * Does nothing. The maintenance renderer cannot produce a course header.
4897 * @return string
4899 public function course_header() {
4900 // Computer says no course header.
4901 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4902 return '';
4906 * Does nothing. The maintenance renderer cannot produce a course footer.
4908 * @return string
4910 public function course_footer() {
4911 // Computer says no course footer.
4912 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4913 return '';
4917 * Does nothing. The maintenance renderer cannot produce a custom menu.
4919 * @param string $custommenuitems
4920 * @return string
4922 public function custom_menu($custommenuitems = '') {
4923 // Computer says no custom menu.
4924 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4925 return '';
4929 * Does nothing. The maintenance renderer cannot produce a file picker.
4931 * @param array $options
4932 * @return string
4934 public function file_picker($options) {
4935 // Computer says no file picker.
4936 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4937 return '';
4941 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
4943 * @param array $dir
4944 * @return string
4946 public function htmllize_file_tree($dir) {
4947 // Hell no we don't want no htmllized file tree.
4948 // Also why on earth is this function on the core renderer???
4949 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4950 return '';
4955 * Overridden confirm message for upgrades.
4957 * @param string $message The question to ask the user
4958 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
4959 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
4960 * @return string HTML fragment
4962 public function confirm($message, $continue, $cancel) {
4963 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
4964 // from any previous version of Moodle).
4965 if ($continue instanceof single_button) {
4966 $continue->primary = true;
4967 } else if (is_string($continue)) {
4968 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
4969 } else if ($continue instanceof moodle_url) {
4970 $continue = new single_button($continue, get_string('continue'), 'post', true);
4971 } else {
4972 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
4973 ' (string/moodle_url) or a single_button instance.');
4976 if ($cancel instanceof single_button) {
4977 $output = '';
4978 } else if (is_string($cancel)) {
4979 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
4980 } else if ($cancel instanceof moodle_url) {
4981 $cancel = new single_button($cancel, get_string('cancel'), 'get');
4982 } else {
4983 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
4984 ' (string/moodle_url) or a single_button instance.');
4987 $output = $this->box_start('generalbox', 'notice');
4988 $output .= html_writer::tag('h4', get_string('confirm'));
4989 $output .= html_writer::tag('p', $message);
4990 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
4991 $output .= $this->box_end();
4992 return $output;
4996 * Does nothing. The maintenance renderer does not support JS.
4998 * @param block_contents $bc
5000 public function init_block_hider_js(block_contents $bc) {
5001 // Computer says no JavaScript.
5002 // Do nothing, ridiculous method.
5006 * Does nothing. The maintenance renderer cannot produce language menus.
5008 * @return string
5010 public function lang_menu() {
5011 // Computer says no lang menu.
5012 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5013 return '';
5017 * Does nothing. The maintenance renderer has no need for login information.
5019 * @param null $withlinks
5020 * @return string
5022 public function login_info($withlinks = null) {
5023 // Computer says no login info.
5024 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5025 return '';
5029 * Does nothing. The maintenance renderer cannot produce user pictures.
5031 * @param stdClass $user
5032 * @param array $options
5033 * @return string
5035 public function user_picture(stdClass $user, array $options = null) {
5036 // Computer says no user pictures.
5037 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5038 return '';