MDL-63303 message: add functions to message_repository.js
[moodle.git] / lib / outputrenderers.php
blobd7399fd54fe7ef93fd2e63ac6cf283a1da319da7
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 * Return the standard string that says whether you are logged in (and switched
951 * roles/logged in as another user).
952 * @param bool $withlinks if false, then don't include any links in the HTML produced.
953 * If not set, the default is the nologinlinks option from the theme config.php file,
954 * and if that is not set, then links are included.
955 * @return string HTML fragment.
957 public function login_info($withlinks = null) {
958 global $USER, $CFG, $DB, $SESSION;
960 if (during_initial_install()) {
961 return '';
964 if (is_null($withlinks)) {
965 $withlinks = empty($this->page->layout_options['nologinlinks']);
968 $course = $this->page->course;
969 if (\core\session\manager::is_loggedinas()) {
970 $realuser = \core\session\manager::get_realuser();
971 $fullname = fullname($realuser, true);
972 if ($withlinks) {
973 $loginastitle = get_string('loginas');
974 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
975 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
976 } else {
977 $realuserinfo = " [$fullname] ";
979 } else {
980 $realuserinfo = '';
983 $loginpage = $this->is_login_page();
984 $loginurl = get_login_url();
986 if (empty($course->id)) {
987 // $course->id is not defined during installation
988 return '';
989 } else if (isloggedin()) {
990 $context = context_course::instance($course->id);
992 $fullname = fullname($USER, true);
993 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
994 if ($withlinks) {
995 $linktitle = get_string('viewprofile');
996 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
997 } else {
998 $username = $fullname;
1000 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
1001 if ($withlinks) {
1002 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1003 } else {
1004 $username .= " from {$idprovider->name}";
1007 if (isguestuser()) {
1008 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1009 if (!$loginpage && $withlinks) {
1010 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1012 } else if (is_role_switched($course->id)) { // Has switched roles
1013 $rolename = '';
1014 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1015 $rolename = ': '.role_get_name($role, $context);
1017 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1018 if ($withlinks) {
1019 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1020 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1022 } else {
1023 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1024 if ($withlinks) {
1025 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1028 } else {
1029 $loggedinas = get_string('loggedinnot', 'moodle');
1030 if (!$loginpage && $withlinks) {
1031 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1035 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1037 if (isset($SESSION->justloggedin)) {
1038 unset($SESSION->justloggedin);
1039 if (!empty($CFG->displayloginfailures)) {
1040 if (!isguestuser()) {
1041 // Include this file only when required.
1042 require_once($CFG->dirroot . '/user/lib.php');
1043 if ($count = user_count_login_failures($USER)) {
1044 $loggedinas .= '<div class="loginfailures">';
1045 $a = new stdClass();
1046 $a->attempts = $count;
1047 $loggedinas .= get_string('failedloginattempts', '', $a);
1048 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1049 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1050 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1052 $loggedinas .= '</div>';
1058 return $loggedinas;
1062 * Check whether the current page is a login page.
1064 * @since Moodle 2.9
1065 * @return bool
1067 protected function is_login_page() {
1068 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1069 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1070 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1071 return in_array(
1072 $this->page->url->out_as_local_url(false, array()),
1073 array(
1074 '/login/index.php',
1075 '/login/forgot_password.php',
1081 * Return the 'back' link that normally appears in the footer.
1083 * @return string HTML fragment.
1085 public function home_link() {
1086 global $CFG, $SITE;
1088 if ($this->page->pagetype == 'site-index') {
1089 // Special case for site home page - please do not remove
1090 return '<div class="sitelink">' .
1091 '<a title="Moodle" href="http://moodle.org/">' .
1092 '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1094 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1095 // Special case for during install/upgrade.
1096 return '<div class="sitelink">'.
1097 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1098 '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1100 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1101 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1102 get_string('home') . '</a></div>';
1104 } else {
1105 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1106 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1111 * Redirects the user by any means possible given the current state
1113 * This function should not be called directly, it should always be called using
1114 * the redirect function in lib/weblib.php
1116 * The redirect function should really only be called before page output has started
1117 * however it will allow itself to be called during the state STATE_IN_BODY
1119 * @param string $encodedurl The URL to send to encoded if required
1120 * @param string $message The message to display to the user if any
1121 * @param int $delay The delay before redirecting a user, if $message has been
1122 * set this is a requirement and defaults to 3, set to 0 no delay
1123 * @param boolean $debugdisableredirect this redirect has been disabled for
1124 * debugging purposes. Display a message that explains, and don't
1125 * trigger the redirect.
1126 * @param string $messagetype The type of notification to show the message in.
1127 * See constants on \core\output\notification.
1128 * @return string The HTML to display to the user before dying, may contain
1129 * meta refresh, javascript refresh, and may have set header redirects
1131 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1132 $messagetype = \core\output\notification::NOTIFY_INFO) {
1133 global $CFG;
1134 $url = str_replace('&amp;', '&', $encodedurl);
1136 switch ($this->page->state) {
1137 case moodle_page::STATE_BEFORE_HEADER :
1138 // No output yet it is safe to delivery the full arsenal of redirect methods
1139 if (!$debugdisableredirect) {
1140 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1141 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1142 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1144 $output = $this->header();
1145 break;
1146 case moodle_page::STATE_PRINTING_HEADER :
1147 // We should hopefully never get here
1148 throw new coding_exception('You cannot redirect while printing the page header');
1149 break;
1150 case moodle_page::STATE_IN_BODY :
1151 // We really shouldn't be here but we can deal with this
1152 debugging("You should really redirect before you start page output");
1153 if (!$debugdisableredirect) {
1154 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1156 $output = $this->opencontainers->pop_all_but_last();
1157 break;
1158 case moodle_page::STATE_DONE :
1159 // Too late to be calling redirect now
1160 throw new coding_exception('You cannot redirect after the entire page has been generated');
1161 break;
1163 $output .= $this->notification($message, $messagetype);
1164 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1165 if ($debugdisableredirect) {
1166 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1168 $output .= $this->footer();
1169 return $output;
1173 * Start output by sending the HTTP headers, and printing the HTML <head>
1174 * and the start of the <body>.
1176 * To control what is printed, you should set properties on $PAGE. If you
1177 * are familiar with the old {@link print_header()} function from Moodle 1.9
1178 * you will find that there are properties on $PAGE that correspond to most
1179 * of the old parameters to could be passed to print_header.
1181 * Not that, in due course, the remaining $navigation, $menu parameters here
1182 * will be replaced by more properties of $PAGE, but that is still to do.
1184 * @return string HTML that you must output this, preferably immediately.
1186 public function header() {
1187 global $USER, $CFG, $SESSION;
1189 // Give plugins an opportunity touch things before the http headers are sent
1190 // such as adding additional headers. The return value is ignored.
1191 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1192 foreach ($pluginswithfunction as $plugins) {
1193 foreach ($plugins as $function) {
1194 $function();
1198 if (\core\session\manager::is_loggedinas()) {
1199 $this->page->add_body_class('userloggedinas');
1202 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1203 require_once($CFG->dirroot . '/user/lib.php');
1204 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1205 if ($count = user_count_login_failures($USER, false)) {
1206 $this->page->add_body_class('loginfailures');
1210 // If the user is logged in, and we're not in initial install,
1211 // check to see if the user is role-switched and add the appropriate
1212 // CSS class to the body element.
1213 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1214 $this->page->add_body_class('userswitchedrole');
1217 // Give themes a chance to init/alter the page object.
1218 $this->page->theme->init_page($this->page);
1220 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1222 // Find the appropriate page layout file, based on $this->page->pagelayout.
1223 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1224 // Render the layout using the layout file.
1225 $rendered = $this->render_page_layout($layoutfile);
1227 // Slice the rendered output into header and footer.
1228 $cutpos = strpos($rendered, $this->unique_main_content_token);
1229 if ($cutpos === false) {
1230 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1231 $token = self::MAIN_CONTENT_TOKEN;
1232 } else {
1233 $token = $this->unique_main_content_token;
1236 if ($cutpos === false) {
1237 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.');
1239 $header = substr($rendered, 0, $cutpos);
1240 $footer = substr($rendered, $cutpos + strlen($token));
1242 if (empty($this->contenttype)) {
1243 debugging('The page layout file did not call $OUTPUT->doctype()');
1244 $header = $this->doctype() . $header;
1247 // If this theme version is below 2.4 release and this is a course view page
1248 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1249 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1250 // check if course content header/footer have not been output during render of theme layout
1251 $coursecontentheader = $this->course_content_header(true);
1252 $coursecontentfooter = $this->course_content_footer(true);
1253 if (!empty($coursecontentheader)) {
1254 // display debug message and add header and footer right above and below main content
1255 // Please note that course header and footer (to be displayed above and below the whole page)
1256 // are not displayed in this case at all.
1257 // Besides the content header and footer are not displayed on any other course page
1258 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);
1259 $header .= $coursecontentheader;
1260 $footer = $coursecontentfooter. $footer;
1264 send_headers($this->contenttype, $this->page->cacheable);
1266 $this->opencontainers->push('header/footer', $footer);
1267 $this->page->set_state(moodle_page::STATE_IN_BODY);
1269 return $header . $this->skip_link_target('maincontent');
1273 * Renders and outputs the page layout file.
1275 * This is done by preparing the normal globals available to a script, and
1276 * then including the layout file provided by the current theme for the
1277 * requested layout.
1279 * @param string $layoutfile The name of the layout file
1280 * @return string HTML code
1282 protected function render_page_layout($layoutfile) {
1283 global $CFG, $SITE, $USER;
1284 // The next lines are a bit tricky. The point is, here we are in a method
1285 // of a renderer class, and this object may, or may not, be the same as
1286 // the global $OUTPUT object. When rendering the page layout file, we want to use
1287 // this object. However, people writing Moodle code expect the current
1288 // renderer to be called $OUTPUT, not $this, so define a variable called
1289 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1290 $OUTPUT = $this;
1291 $PAGE = $this->page;
1292 $COURSE = $this->page->course;
1294 ob_start();
1295 include($layoutfile);
1296 $rendered = ob_get_contents();
1297 ob_end_clean();
1298 return $rendered;
1302 * Outputs the page's footer
1304 * @return string HTML fragment
1306 public function footer() {
1307 global $CFG, $DB, $PAGE;
1309 // Give plugins an opportunity to touch the page before JS is finalized.
1310 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1311 foreach ($pluginswithfunction as $plugins) {
1312 foreach ($plugins as $function) {
1313 $function();
1317 $output = $this->container_end_all(true);
1319 $footer = $this->opencontainers->pop('header/footer');
1321 if (debugging() and $DB and $DB->is_transaction_started()) {
1322 // TODO: MDL-20625 print warning - transaction will be rolled back
1325 // Provide some performance info if required
1326 $performanceinfo = '';
1327 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1328 $perf = get_performance_info();
1329 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1330 $performanceinfo = $perf['html'];
1334 // We always want performance data when running a performance test, even if the user is redirected to another page.
1335 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1336 $footer = $this->unique_performance_info_token . $footer;
1338 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1340 // Only show notifications when we have a $PAGE context id.
1341 if (!empty($PAGE->context->id)) {
1342 $this->page->requires->js_call_amd('core/notification', 'init', array(
1343 $PAGE->context->id,
1344 \core\notification::fetch_as_array($this)
1347 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1349 $this->page->set_state(moodle_page::STATE_DONE);
1351 return $output . $footer;
1355 * Close all but the last open container. This is useful in places like error
1356 * handling, where you want to close all the open containers (apart from <body>)
1357 * before outputting the error message.
1359 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1360 * developer debug warning if it isn't.
1361 * @return string the HTML required to close any open containers inside <body>.
1363 public function container_end_all($shouldbenone = false) {
1364 return $this->opencontainers->pop_all_but_last($shouldbenone);
1368 * Returns course-specific information to be output immediately above content on any course page
1369 * (for the current course)
1371 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1372 * @return string
1374 public function course_content_header($onlyifnotcalledbefore = false) {
1375 global $CFG;
1376 static $functioncalled = false;
1377 if ($functioncalled && $onlyifnotcalledbefore) {
1378 // we have already output the content header
1379 return '';
1382 // Output any session notification.
1383 $notifications = \core\notification::fetch();
1385 $bodynotifications = '';
1386 foreach ($notifications as $notification) {
1387 $bodynotifications .= $this->render_from_template(
1388 $notification->get_template_name(),
1389 $notification->export_for_template($this)
1393 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1395 if ($this->page->course->id == SITEID) {
1396 // return immediately and do not include /course/lib.php if not necessary
1397 return $output;
1400 require_once($CFG->dirroot.'/course/lib.php');
1401 $functioncalled = true;
1402 $courseformat = course_get_format($this->page->course);
1403 if (($obj = $courseformat->course_content_header()) !== null) {
1404 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1406 return $output;
1410 * Returns course-specific information to be output immediately below content on any course page
1411 * (for the current course)
1413 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1414 * @return string
1416 public function course_content_footer($onlyifnotcalledbefore = false) {
1417 global $CFG;
1418 if ($this->page->course->id == SITEID) {
1419 // return immediately and do not include /course/lib.php if not necessary
1420 return '';
1422 static $functioncalled = false;
1423 if ($functioncalled && $onlyifnotcalledbefore) {
1424 // we have already output the content footer
1425 return '';
1427 $functioncalled = true;
1428 require_once($CFG->dirroot.'/course/lib.php');
1429 $courseformat = course_get_format($this->page->course);
1430 if (($obj = $courseformat->course_content_footer()) !== null) {
1431 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1433 return '';
1437 * Returns course-specific information to be output on any course page in the header area
1438 * (for the current course)
1440 * @return string
1442 public function course_header() {
1443 global $CFG;
1444 if ($this->page->course->id == SITEID) {
1445 // return immediately and do not include /course/lib.php if not necessary
1446 return '';
1448 require_once($CFG->dirroot.'/course/lib.php');
1449 $courseformat = course_get_format($this->page->course);
1450 if (($obj = $courseformat->course_header()) !== null) {
1451 return $courseformat->get_renderer($this->page)->render($obj);
1453 return '';
1457 * Returns course-specific information to be output on any course page in the footer area
1458 * (for the current course)
1460 * @return string
1462 public function course_footer() {
1463 global $CFG;
1464 if ($this->page->course->id == SITEID) {
1465 // return immediately and do not include /course/lib.php if not necessary
1466 return '';
1468 require_once($CFG->dirroot.'/course/lib.php');
1469 $courseformat = course_get_format($this->page->course);
1470 if (($obj = $courseformat->course_footer()) !== null) {
1471 return $courseformat->get_renderer($this->page)->render($obj);
1473 return '';
1477 * Returns lang menu or '', this method also checks forcing of languages in courses.
1479 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1481 * @return string The lang menu HTML or empty string
1483 public function lang_menu() {
1484 global $CFG;
1486 if (empty($CFG->langmenu)) {
1487 return '';
1490 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1491 // do not show lang menu if language forced
1492 return '';
1495 $currlang = current_language();
1496 $langs = get_string_manager()->get_list_of_translations();
1498 if (count($langs) < 2) {
1499 return '';
1502 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1503 $s->label = get_accesshide(get_string('language'));
1504 $s->class = 'langmenu';
1505 return $this->render($s);
1509 * Output the row of editing icons for a block, as defined by the controls array.
1511 * @param array $controls an array like {@link block_contents::$controls}.
1512 * @param string $blockid The ID given to the block.
1513 * @return string HTML fragment.
1515 public function block_controls($actions, $blockid = null) {
1516 global $CFG;
1517 if (empty($actions)) {
1518 return '';
1520 $menu = new action_menu($actions);
1521 if ($blockid !== null) {
1522 $menu->set_owner_selector('#'.$blockid);
1524 $menu->set_constraint('.block-region');
1525 $menu->attributes['class'] .= ' block-control-actions commands';
1526 return $this->render($menu);
1530 * Returns the HTML for a basic textarea field.
1532 * @param string $name Name to use for the textarea element
1533 * @param string $id The id to use fort he textarea element
1534 * @param string $value Initial content to display in the textarea
1535 * @param int $rows Number of rows to display
1536 * @param int $cols Number of columns to display
1537 * @return string the HTML to display
1539 public function print_textarea($name, $id, $value, $rows, $cols) {
1540 global $OUTPUT;
1542 editors_head_setup();
1543 $editor = editors_get_preferred_editor(FORMAT_HTML);
1544 $editor->set_text($value);
1545 $editor->use_editor($id, []);
1547 $context = [
1548 'id' => $id,
1549 'name' => $name,
1550 'value' => $value,
1551 'rows' => $rows,
1552 'cols' => $cols
1555 return $OUTPUT->render_from_template('core_form/editor_textarea', $context);
1559 * Renders an action menu component.
1561 * ARIA references:
1562 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1563 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1565 * @param action_menu $menu
1566 * @return string HTML
1568 public function render_action_menu(action_menu $menu) {
1569 $context = $menu->export_for_template($this);
1570 return $this->render_from_template('core/action_menu', $context);
1574 * Renders an action_menu_link item.
1576 * @param action_menu_link $action
1577 * @return string HTML fragment
1579 protected function render_action_menu_link(action_menu_link $action) {
1580 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1584 * Renders a primary action_menu_filler item.
1586 * @param action_menu_link_filler $action
1587 * @return string HTML fragment
1589 protected function render_action_menu_filler(action_menu_filler $action) {
1590 return html_writer::span('&nbsp;', 'filler');
1594 * Renders a primary action_menu_link item.
1596 * @param action_menu_link_primary $action
1597 * @return string HTML fragment
1599 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1600 return $this->render_action_menu_link($action);
1604 * Renders a secondary action_menu_link item.
1606 * @param action_menu_link_secondary $action
1607 * @return string HTML fragment
1609 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1610 return $this->render_action_menu_link($action);
1614 * Prints a nice side block with an optional header.
1616 * The content is described
1617 * by a {@link core_renderer::block_contents} object.
1619 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1620 * <div class="header"></div>
1621 * <div class="content">
1622 * ...CONTENT...
1623 * <div class="footer">
1624 * </div>
1625 * </div>
1626 * <div class="annotation">
1627 * </div>
1628 * </div>
1630 * @param block_contents $bc HTML for the content
1631 * @param string $region the region the block is appearing in.
1632 * @return string the HTML to be output.
1634 public function block(block_contents $bc, $region) {
1635 $bc = clone($bc); // Avoid messing up the object passed in.
1636 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1637 $bc->collapsible = block_contents::NOT_HIDEABLE;
1639 if (!empty($bc->blockinstanceid)) {
1640 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1642 $skiptitle = strip_tags($bc->title);
1643 if ($bc->blockinstanceid && !empty($skiptitle)) {
1644 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1645 } else if (!empty($bc->arialabel)) {
1646 $bc->attributes['aria-label'] = $bc->arialabel;
1648 if ($bc->dockable) {
1649 $bc->attributes['data-dockable'] = 1;
1651 if ($bc->collapsible == block_contents::HIDDEN) {
1652 $bc->add_class('hidden');
1654 if (!empty($bc->controls)) {
1655 $bc->add_class('block_with_controls');
1659 if (empty($skiptitle)) {
1660 $output = '';
1661 $skipdest = '';
1662 } else {
1663 $output = html_writer::link('#sb-'.$bc->skipid, get_string('skipa', 'access', $skiptitle),
1664 array('class' => 'skip skip-block', 'id' => 'fsb-' . $bc->skipid));
1665 $skipdest = html_writer::span('', 'skip-block-to',
1666 array('id' => 'sb-' . $bc->skipid));
1669 $output .= html_writer::start_tag('div', $bc->attributes);
1671 $output .= $this->block_header($bc);
1672 $output .= $this->block_content($bc);
1674 $output .= html_writer::end_tag('div');
1676 $output .= $this->block_annotation($bc);
1678 $output .= $skipdest;
1680 $this->init_block_hider_js($bc);
1681 return $output;
1685 * Produces a header for a block
1687 * @param block_contents $bc
1688 * @return string
1690 protected function block_header(block_contents $bc) {
1692 $title = '';
1693 if ($bc->title) {
1694 $attributes = array();
1695 if ($bc->blockinstanceid) {
1696 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1698 $title = html_writer::tag('h2', $bc->title, $attributes);
1701 $blockid = null;
1702 if (isset($bc->attributes['id'])) {
1703 $blockid = $bc->attributes['id'];
1705 $controlshtml = $this->block_controls($bc->controls, $blockid);
1707 $output = '';
1708 if ($title || $controlshtml) {
1709 $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'));
1711 return $output;
1715 * Produces the content area for a block
1717 * @param block_contents $bc
1718 * @return string
1720 protected function block_content(block_contents $bc) {
1721 $output = html_writer::start_tag('div', array('class' => 'content'));
1722 if (!$bc->title && !$this->block_controls($bc->controls)) {
1723 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1725 $output .= $bc->content;
1726 $output .= $this->block_footer($bc);
1727 $output .= html_writer::end_tag('div');
1729 return $output;
1733 * Produces the footer for a block
1735 * @param block_contents $bc
1736 * @return string
1738 protected function block_footer(block_contents $bc) {
1739 $output = '';
1740 if ($bc->footer) {
1741 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1743 return $output;
1747 * Produces the annotation for a block
1749 * @param block_contents $bc
1750 * @return string
1752 protected function block_annotation(block_contents $bc) {
1753 $output = '';
1754 if ($bc->annotation) {
1755 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1757 return $output;
1761 * Calls the JS require function to hide a block.
1763 * @param block_contents $bc A block_contents object
1765 protected function init_block_hider_js(block_contents $bc) {
1766 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1767 $config = new stdClass;
1768 $config->id = $bc->attributes['id'];
1769 $config->title = strip_tags($bc->title);
1770 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1771 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1772 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1774 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1775 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1780 * Render the contents of a block_list.
1782 * @param array $icons the icon for each item.
1783 * @param array $items the content of each item.
1784 * @return string HTML
1786 public function list_block_contents($icons, $items) {
1787 $row = 0;
1788 $lis = array();
1789 foreach ($items as $key => $string) {
1790 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1791 if (!empty($icons[$key])) { //test if the content has an assigned icon
1792 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1794 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1795 $item .= html_writer::end_tag('li');
1796 $lis[] = $item;
1797 $row = 1 - $row; // Flip even/odd.
1799 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1803 * Output all the blocks in a particular region.
1805 * @param string $region the name of a region on this page.
1806 * @return string the HTML to be output.
1808 public function blocks_for_region($region) {
1809 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1810 $blocks = $this->page->blocks->get_blocks_for_region($region);
1811 $lastblock = null;
1812 $zones = array();
1813 foreach ($blocks as $block) {
1814 $zones[] = $block->title;
1816 $output = '';
1818 foreach ($blockcontents as $bc) {
1819 if ($bc instanceof block_contents) {
1820 $output .= $this->block($bc, $region);
1821 $lastblock = $bc->title;
1822 } else if ($bc instanceof block_move_target) {
1823 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1824 } else {
1825 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1828 return $output;
1832 * Output a place where the block that is currently being moved can be dropped.
1834 * @param block_move_target $target with the necessary details.
1835 * @param array $zones array of areas where the block can be moved to
1836 * @param string $previous the block located before the area currently being rendered.
1837 * @param string $region the name of the region
1838 * @return string the HTML to be output.
1840 public function block_move_target($target, $zones, $previous, $region) {
1841 if ($previous == null) {
1842 if (empty($zones)) {
1843 // There are no zones, probably because there are no blocks.
1844 $regions = $this->page->theme->get_all_block_regions();
1845 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1846 } else {
1847 $position = get_string('moveblockbefore', 'block', $zones[0]);
1849 } else {
1850 $position = get_string('moveblockafter', 'block', $previous);
1852 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1856 * Renders a special html link with attached action
1858 * Theme developers: DO NOT OVERRIDE! Please override function
1859 * {@link core_renderer::render_action_link()} instead.
1861 * @param string|moodle_url $url
1862 * @param string $text HTML fragment
1863 * @param component_action $action
1864 * @param array $attributes associative array of html link attributes + disabled
1865 * @param pix_icon optional pix icon to render with the link
1866 * @return string HTML fragment
1868 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1869 if (!($url instanceof moodle_url)) {
1870 $url = new moodle_url($url);
1872 $link = new action_link($url, $text, $action, $attributes, $icon);
1874 return $this->render($link);
1878 * Renders an action_link object.
1880 * The provided link is renderer and the HTML returned. At the same time the
1881 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1883 * @param action_link $link
1884 * @return string HTML fragment
1886 protected function render_action_link(action_link $link) {
1887 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1891 * Renders an action_icon.
1893 * This function uses the {@link core_renderer::action_link()} method for the
1894 * most part. What it does different is prepare the icon as HTML and use it
1895 * as the link text.
1897 * Theme developers: If you want to change how action links and/or icons are rendered,
1898 * consider overriding function {@link core_renderer::render_action_link()} and
1899 * {@link core_renderer::render_pix_icon()}.
1901 * @param string|moodle_url $url A string URL or moodel_url
1902 * @param pix_icon $pixicon
1903 * @param component_action $action
1904 * @param array $attributes associative array of html link attributes + disabled
1905 * @param bool $linktext show title next to image in link
1906 * @return string HTML fragment
1908 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1909 if (!($url instanceof moodle_url)) {
1910 $url = new moodle_url($url);
1912 $attributes = (array)$attributes;
1914 if (empty($attributes['class'])) {
1915 // let ppl override the class via $options
1916 $attributes['class'] = 'action-icon';
1919 $icon = $this->render($pixicon);
1921 if ($linktext) {
1922 $text = $pixicon->attributes['alt'];
1923 } else {
1924 $text = '';
1927 return $this->action_link($url, $text.$icon, $action, $attributes);
1931 * Print a message along with button choices for Continue/Cancel
1933 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1935 * @param string $message The question to ask the user
1936 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1937 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1938 * @return string HTML fragment
1940 public function confirm($message, $continue, $cancel) {
1941 if ($continue instanceof single_button) {
1942 // ok
1943 $continue->primary = true;
1944 } else if (is_string($continue)) {
1945 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1946 } else if ($continue instanceof moodle_url) {
1947 $continue = new single_button($continue, get_string('continue'), 'post', true);
1948 } else {
1949 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1952 if ($cancel instanceof single_button) {
1953 // ok
1954 } else if (is_string($cancel)) {
1955 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1956 } else if ($cancel instanceof moodle_url) {
1957 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1958 } else {
1959 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1962 $attributes = [
1963 'role'=>'alertdialog',
1964 'aria-labelledby'=>'modal-header',
1965 'aria-describedby'=>'modal-body',
1966 'aria-modal'=>'true'
1969 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
1970 $output .= $this->box_start('modal-content', 'modal-content');
1971 $output .= $this->box_start('modal-header p-x-1', 'modal-header');
1972 $output .= html_writer::tag('h4', get_string('confirm'));
1973 $output .= $this->box_end();
1974 $attributes = [
1975 'role'=>'alert',
1976 'data-aria-autofocus'=>'true'
1978 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
1979 $output .= html_writer::tag('p', $message);
1980 $output .= $this->box_end();
1981 $output .= $this->box_start('modal-footer', 'modal-footer');
1982 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1983 $output .= $this->box_end();
1984 $output .= $this->box_end();
1985 $output .= $this->box_end();
1986 return $output;
1990 * Returns a form with a single button.
1992 * Theme developers: DO NOT OVERRIDE! Please override function
1993 * {@link core_renderer::render_single_button()} instead.
1995 * @param string|moodle_url $url
1996 * @param string $label button text
1997 * @param string $method get or post submit method
1998 * @param array $options associative array {disabled, title, etc.}
1999 * @return string HTML fragment
2001 public function single_button($url, $label, $method='post', array $options=null) {
2002 if (!($url instanceof moodle_url)) {
2003 $url = new moodle_url($url);
2005 $button = new single_button($url, $label, $method);
2007 foreach ((array)$options as $key=>$value) {
2008 if (array_key_exists($key, $button)) {
2009 $button->$key = $value;
2013 return $this->render($button);
2017 * Renders a single button widget.
2019 * This will return HTML to display a form containing a single button.
2021 * @param single_button $button
2022 * @return string HTML fragment
2024 protected function render_single_button(single_button $button) {
2025 $attributes = array('type' => 'submit',
2026 'value' => $button->label,
2027 'disabled' => $button->disabled ? 'disabled' : null,
2028 'title' => $button->tooltip);
2030 if ($button->actions) {
2031 $id = html_writer::random_id('single_button');
2032 $attributes['id'] = $id;
2033 foreach ($button->actions as $action) {
2034 $this->add_action_handler($action, $id);
2038 // first the input element
2039 $output = html_writer::empty_tag('input', $attributes);
2041 // then hidden fields
2042 $params = $button->url->params();
2043 if ($button->method === 'post') {
2044 $params['sesskey'] = sesskey();
2046 foreach ($params as $var => $val) {
2047 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
2050 // then div wrapper for xhtml strictness
2051 $output = html_writer::tag('div', $output);
2053 // now the form itself around it
2054 if ($button->method === 'get') {
2055 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
2056 } else {
2057 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
2059 if ($url === '') {
2060 $url = '#'; // there has to be always some action
2062 $attributes = array('method' => $button->method,
2063 'action' => $url,
2064 'id' => $button->formid);
2065 $output = html_writer::tag('form', $output, $attributes);
2067 // and finally one more wrapper with class
2068 return html_writer::tag('div', $output, array('class' => $button->class));
2072 * Returns a form with a single select widget.
2074 * Theme developers: DO NOT OVERRIDE! Please override function
2075 * {@link core_renderer::render_single_select()} instead.
2077 * @param moodle_url $url form action target, includes hidden fields
2078 * @param string $name name of selection field - the changing parameter in url
2079 * @param array $options list of options
2080 * @param string $selected selected element
2081 * @param array $nothing
2082 * @param string $formid
2083 * @param array $attributes other attributes for the single select
2084 * @return string HTML fragment
2086 public function single_select($url, $name, array $options, $selected = '',
2087 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2088 if (!($url instanceof moodle_url)) {
2089 $url = new moodle_url($url);
2091 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2093 if (array_key_exists('label', $attributes)) {
2094 $select->set_label($attributes['label']);
2095 unset($attributes['label']);
2097 $select->attributes = $attributes;
2099 return $this->render($select);
2103 * Returns a dataformat selection and download form
2105 * @param string $label A text label
2106 * @param moodle_url|string $base The download page url
2107 * @param string $name The query param which will hold the type of the download
2108 * @param array $params Extra params sent to the download page
2109 * @return string HTML fragment
2111 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2113 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2114 $options = array();
2115 foreach ($formats as $format) {
2116 if ($format->is_enabled()) {
2117 $options[] = array(
2118 'value' => $format->name,
2119 'label' => get_string('dataformat', $format->component),
2123 $hiddenparams = array();
2124 foreach ($params as $key => $value) {
2125 $hiddenparams[] = array(
2126 'name' => $key,
2127 'value' => $value,
2130 $data = array(
2131 'label' => $label,
2132 'base' => $base,
2133 'name' => $name,
2134 'params' => $hiddenparams,
2135 'options' => $options,
2136 'sesskey' => sesskey(),
2137 'submit' => get_string('download'),
2140 return $this->render_from_template('core/dataformat_selector', $data);
2145 * Internal implementation of single_select rendering
2147 * @param single_select $select
2148 * @return string HTML fragment
2150 protected function render_single_select(single_select $select) {
2151 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2155 * Returns a form with a url select widget.
2157 * Theme developers: DO NOT OVERRIDE! Please override function
2158 * {@link core_renderer::render_url_select()} instead.
2160 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2161 * @param string $selected selected element
2162 * @param array $nothing
2163 * @param string $formid
2164 * @return string HTML fragment
2166 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2167 $select = new url_select($urls, $selected, $nothing, $formid);
2168 return $this->render($select);
2172 * Internal implementation of url_select rendering
2174 * @param url_select $select
2175 * @return string HTML fragment
2177 protected function render_url_select(url_select $select) {
2178 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2182 * Returns a string containing a link to the user documentation.
2183 * Also contains an icon by default. Shown to teachers and admin only.
2185 * @param string $path The page link after doc root and language, no leading slash.
2186 * @param string $text The text to be displayed for the link
2187 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2188 * @return string
2190 public function doc_link($path, $text = '', $forcepopup = false) {
2191 global $CFG;
2193 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2195 $url = new moodle_url(get_docs_url($path));
2197 $attributes = array('href'=>$url);
2198 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2199 $attributes['class'] = 'helplinkpopup';
2202 return html_writer::tag('a', $icon.$text, $attributes);
2206 * Return HTML for an image_icon.
2208 * Theme developers: DO NOT OVERRIDE! Please override function
2209 * {@link core_renderer::render_image_icon()} instead.
2211 * @param string $pix short pix name
2212 * @param string $alt mandatory alt attribute
2213 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2214 * @param array $attributes htm lattributes
2215 * @return string HTML fragment
2217 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2218 $icon = new image_icon($pix, $alt, $component, $attributes);
2219 return $this->render($icon);
2223 * Renders a pix_icon widget and returns the HTML to display it.
2225 * @param image_icon $icon
2226 * @return string HTML fragment
2228 protected function render_image_icon(image_icon $icon) {
2229 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2230 return $system->render_pix_icon($this, $icon);
2234 * Return HTML for a pix_icon.
2236 * Theme developers: DO NOT OVERRIDE! Please override function
2237 * {@link core_renderer::render_pix_icon()} instead.
2239 * @param string $pix short pix name
2240 * @param string $alt mandatory alt attribute
2241 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2242 * @param array $attributes htm lattributes
2243 * @return string HTML fragment
2245 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2246 $icon = new pix_icon($pix, $alt, $component, $attributes);
2247 return $this->render($icon);
2251 * Renders a pix_icon widget and returns the HTML to display it.
2253 * @param pix_icon $icon
2254 * @return string HTML fragment
2256 protected function render_pix_icon(pix_icon $icon) {
2257 $system = \core\output\icon_system::instance();
2258 return $system->render_pix_icon($this, $icon);
2262 * Return HTML to display an emoticon icon.
2264 * @param pix_emoticon $emoticon
2265 * @return string HTML fragment
2267 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2268 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2269 return $system->render_pix_icon($this, $emoticon);
2273 * Produces the html that represents this rating in the UI
2275 * @param rating $rating the page object on which this rating will appear
2276 * @return string
2278 function render_rating(rating $rating) {
2279 global $CFG, $USER;
2281 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2282 return null;//ratings are turned off
2285 $ratingmanager = new rating_manager();
2286 // Initialise the JavaScript so ratings can be done by AJAX.
2287 $ratingmanager->initialise_rating_javascript($this->page);
2289 $strrate = get_string("rate", "rating");
2290 $ratinghtml = ''; //the string we'll return
2292 // permissions check - can they view the aggregate?
2293 if ($rating->user_can_view_aggregate()) {
2295 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2296 $aggregatestr = $rating->get_aggregate_string();
2298 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2299 if ($rating->count > 0) {
2300 $countstr = "({$rating->count})";
2301 } else {
2302 $countstr = '-';
2304 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2306 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2307 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2309 $nonpopuplink = $rating->get_view_ratings_url();
2310 $popuplink = $rating->get_view_ratings_url(true);
2312 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2313 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2314 } else {
2315 $ratinghtml .= $aggregatehtml;
2319 $formstart = null;
2320 // if the item doesn't belong to the current user, the user has permission to rate
2321 // and we're within the assessable period
2322 if ($rating->user_can_rate()) {
2324 $rateurl = $rating->get_rate_url();
2325 $inputs = $rateurl->params();
2327 //start the rating form
2328 $formattrs = array(
2329 'id' => "postrating{$rating->itemid}",
2330 'class' => 'postratingform',
2331 'method' => 'post',
2332 'action' => $rateurl->out_omit_querystring()
2334 $formstart = html_writer::start_tag('form', $formattrs);
2335 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2337 // add the hidden inputs
2338 foreach ($inputs as $name => $value) {
2339 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2340 $formstart .= html_writer::empty_tag('input', $attributes);
2343 if (empty($ratinghtml)) {
2344 $ratinghtml .= $strrate.': ';
2346 $ratinghtml = $formstart.$ratinghtml;
2348 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2349 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2350 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2351 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2353 //output submit button
2354 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2356 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2357 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2359 if (!$rating->settings->scale->isnumeric) {
2360 // If a global scale, try to find current course ID from the context
2361 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2362 $courseid = $coursecontext->instanceid;
2363 } else {
2364 $courseid = $rating->settings->scale->courseid;
2366 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2368 $ratinghtml .= html_writer::end_tag('span');
2369 $ratinghtml .= html_writer::end_tag('div');
2370 $ratinghtml .= html_writer::end_tag('form');
2373 return $ratinghtml;
2377 * Centered heading with attached help button (same title text)
2378 * and optional icon attached.
2380 * @param string $text A heading text
2381 * @param string $helpidentifier The keyword that defines a help page
2382 * @param string $component component name
2383 * @param string|moodle_url $icon
2384 * @param string $iconalt icon alt text
2385 * @param int $level The level of importance of the heading. Defaulting to 2
2386 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2387 * @return string HTML fragment
2389 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2390 $image = '';
2391 if ($icon) {
2392 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2395 $help = '';
2396 if ($helpidentifier) {
2397 $help = $this->help_icon($helpidentifier, $component);
2400 return $this->heading($image.$text.$help, $level, $classnames);
2404 * Returns HTML to display a help icon.
2406 * @deprecated since Moodle 2.0
2408 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2409 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2413 * Returns HTML to display a help icon.
2415 * Theme developers: DO NOT OVERRIDE! Please override function
2416 * {@link core_renderer::render_help_icon()} instead.
2418 * @param string $identifier The keyword that defines a help page
2419 * @param string $component component name
2420 * @param string|bool $linktext true means use $title as link text, string means link text value
2421 * @return string HTML fragment
2423 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2424 $icon = new help_icon($identifier, $component);
2425 $icon->diag_strings();
2426 if ($linktext === true) {
2427 $icon->linktext = get_string($icon->identifier, $icon->component);
2428 } else if (!empty($linktext)) {
2429 $icon->linktext = $linktext;
2431 return $this->render($icon);
2435 * Implementation of user image rendering.
2437 * @param help_icon $helpicon A help icon instance
2438 * @return string HTML fragment
2440 protected function render_help_icon(help_icon $helpicon) {
2441 return $this->render_from_template('core/help_icon', $helpicon->export_for_template($this));
2445 * Returns HTML to display a scale help icon.
2447 * @param int $courseid
2448 * @param stdClass $scale instance
2449 * @return string HTML fragment
2451 public function help_icon_scale($courseid, stdClass $scale) {
2452 global $CFG;
2454 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2456 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2458 $scaleid = abs($scale->id);
2460 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2461 $action = new popup_action('click', $link, 'ratingscale');
2463 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2467 * Creates and returns a spacer image with optional line break.
2469 * @param array $attributes Any HTML attributes to add to the spaced.
2470 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2471 * laxy do it with CSS which is a much better solution.
2472 * @return string HTML fragment
2474 public function spacer(array $attributes = null, $br = false) {
2475 $attributes = (array)$attributes;
2476 if (empty($attributes['width'])) {
2477 $attributes['width'] = 1;
2479 if (empty($attributes['height'])) {
2480 $attributes['height'] = 1;
2482 $attributes['class'] = 'spacer';
2484 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2486 if (!empty($br)) {
2487 $output .= '<br />';
2490 return $output;
2494 * Returns HTML to display the specified user's avatar.
2496 * User avatar may be obtained in two ways:
2497 * <pre>
2498 * // Option 1: (shortcut for simple cases, preferred way)
2499 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2500 * $OUTPUT->user_picture($user, array('popup'=>true));
2502 * // Option 2:
2503 * $userpic = new user_picture($user);
2504 * // Set properties of $userpic
2505 * $userpic->popup = true;
2506 * $OUTPUT->render($userpic);
2507 * </pre>
2509 * Theme developers: DO NOT OVERRIDE! Please override function
2510 * {@link core_renderer::render_user_picture()} instead.
2512 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2513 * If any of these are missing, the database is queried. Avoid this
2514 * if at all possible, particularly for reports. It is very bad for performance.
2515 * @param array $options associative array with user picture options, used only if not a user_picture object,
2516 * options are:
2517 * - courseid=$this->page->course->id (course id of user profile in link)
2518 * - size=35 (size of image)
2519 * - link=true (make image clickable - the link leads to user profile)
2520 * - popup=false (open in popup)
2521 * - alttext=true (add image alt attribute)
2522 * - class = image class attribute (default 'userpicture')
2523 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2524 * - includefullname=false (whether to include the user's full name together with the user picture)
2525 * - includetoken = false
2526 * @return string HTML fragment
2528 public function user_picture(stdClass $user, array $options = null) {
2529 $userpicture = new user_picture($user);
2530 foreach ((array)$options as $key=>$value) {
2531 if (array_key_exists($key, $userpicture)) {
2532 $userpicture->$key = $value;
2535 return $this->render($userpicture);
2539 * Internal implementation of user image rendering.
2541 * @param user_picture $userpicture
2542 * @return string
2544 protected function render_user_picture(user_picture $userpicture) {
2545 global $CFG, $DB;
2547 $user = $userpicture->user;
2548 $canviewfullnames = has_capability('moodle/site:viewfullnames', context_system::instance());
2550 if ($userpicture->alttext) {
2551 if (!empty($user->imagealt)) {
2552 $alt = $user->imagealt;
2553 } else {
2554 $alt = get_string('pictureof', '', fullname($user, $canviewfullnames));
2556 } else {
2557 $alt = '';
2560 if (empty($userpicture->size)) {
2561 $size = 35;
2562 } else if ($userpicture->size === true or $userpicture->size == 1) {
2563 $size = 100;
2564 } else {
2565 $size = $userpicture->size;
2568 $class = $userpicture->class;
2570 if ($user->picture == 0) {
2571 $class .= ' defaultuserpic';
2574 $src = $userpicture->get_url($this->page, $this);
2576 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2577 if (!$userpicture->visibletoscreenreaders) {
2578 $attributes['role'] = 'presentation';
2581 // get the image html output fisrt
2582 $output = html_writer::empty_tag('img', $attributes);
2584 // Show fullname together with the picture when desired.
2585 if ($userpicture->includefullname) {
2586 $output .= fullname($userpicture->user, $canviewfullnames);
2589 // then wrap it in link if needed
2590 if (!$userpicture->link) {
2591 return $output;
2594 if (empty($userpicture->courseid)) {
2595 $courseid = $this->page->course->id;
2596 } else {
2597 $courseid = $userpicture->courseid;
2600 if ($courseid == SITEID) {
2601 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2602 } else {
2603 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2606 $attributes = array('href'=>$url);
2607 if (!$userpicture->visibletoscreenreaders) {
2608 $attributes['tabindex'] = '-1';
2609 $attributes['aria-hidden'] = 'true';
2612 if ($userpicture->popup) {
2613 $id = html_writer::random_id('userpicture');
2614 $attributes['id'] = $id;
2615 $this->add_action_handler(new popup_action('click', $url), $id);
2618 return html_writer::tag('a', $output, $attributes);
2622 * Internal implementation of file tree viewer items rendering.
2624 * @param array $dir
2625 * @return string
2627 public function htmllize_file_tree($dir) {
2628 if (empty($dir['subdirs']) and empty($dir['files'])) {
2629 return '';
2631 $result = '<ul>';
2632 foreach ($dir['subdirs'] as $subdir) {
2633 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2635 foreach ($dir['files'] as $file) {
2636 $filename = $file->get_filename();
2637 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2639 $result .= '</ul>';
2641 return $result;
2645 * Returns HTML to display the file picker
2647 * <pre>
2648 * $OUTPUT->file_picker($options);
2649 * </pre>
2651 * Theme developers: DO NOT OVERRIDE! Please override function
2652 * {@link core_renderer::render_file_picker()} instead.
2654 * @param array $options associative array with file manager options
2655 * options are:
2656 * maxbytes=>-1,
2657 * itemid=>0,
2658 * client_id=>uniqid(),
2659 * acepted_types=>'*',
2660 * return_types=>FILE_INTERNAL,
2661 * context=>$PAGE->context
2662 * @return string HTML fragment
2664 public function file_picker($options) {
2665 $fp = new file_picker($options);
2666 return $this->render($fp);
2670 * Internal implementation of file picker rendering.
2672 * @param file_picker $fp
2673 * @return string
2675 public function render_file_picker(file_picker $fp) {
2676 global $CFG, $OUTPUT, $USER;
2677 $options = $fp->options;
2678 $client_id = $options->client_id;
2679 $strsaved = get_string('filesaved', 'repository');
2680 $straddfile = get_string('openpicker', 'repository');
2681 $strloading = get_string('loading', 'repository');
2682 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2683 $strdroptoupload = get_string('droptoupload', 'moodle');
2684 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2686 $currentfile = $options->currentfile;
2687 if (empty($currentfile)) {
2688 $currentfile = '';
2689 } else {
2690 $currentfile .= ' - ';
2692 if ($options->maxbytes) {
2693 $size = $options->maxbytes;
2694 } else {
2695 $size = get_max_upload_file_size();
2697 if ($size == -1) {
2698 $maxsize = '';
2699 } else {
2700 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2702 if ($options->buttonname) {
2703 $buttonname = ' name="' . $options->buttonname . '"';
2704 } else {
2705 $buttonname = '';
2707 $html = <<<EOD
2708 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2709 $icon_progress
2710 </div>
2711 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2712 <div>
2713 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2714 <span> $maxsize </span>
2715 </div>
2716 EOD;
2717 if ($options->env != 'url') {
2718 $html .= <<<EOD
2719 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2720 <div class="filepicker-filename">
2721 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2722 <div class="dndupload-progressbars"></div>
2723 </div>
2724 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2725 </div>
2726 EOD;
2728 $html .= '</div>';
2729 return $html;
2733 * @deprecated since Moodle 3.2
2735 public function update_module_button() {
2736 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2737 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2738 'Themes can choose to display the link in the buttons row consistently for all module types.');
2742 * Returns HTML to display a "Turn editing on/off" button in a form.
2744 * @param moodle_url $url The URL + params to send through when clicking the button
2745 * @return string HTML the button
2747 public function edit_button(moodle_url $url) {
2749 $url->param('sesskey', sesskey());
2750 if ($this->page->user_is_editing()) {
2751 $url->param('edit', 'off');
2752 $editstring = get_string('turneditingoff');
2753 } else {
2754 $url->param('edit', 'on');
2755 $editstring = get_string('turneditingon');
2758 return $this->single_button($url, $editstring);
2762 * Returns HTML to display a simple button to close a window
2764 * @param string $text The lang string for the button's label (already output from get_string())
2765 * @return string html fragment
2767 public function close_window_button($text='') {
2768 if (empty($text)) {
2769 $text = get_string('closewindow');
2771 $button = new single_button(new moodle_url('#'), $text, 'get');
2772 $button->add_action(new component_action('click', 'close_window'));
2774 return $this->container($this->render($button), 'closewindow');
2778 * Output an error message. By default wraps the error message in <span class="error">.
2779 * If the error message is blank, nothing is output.
2781 * @param string $message the error message.
2782 * @return string the HTML to output.
2784 public function error_text($message) {
2785 if (empty($message)) {
2786 return '';
2788 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2789 return html_writer::tag('span', $message, array('class' => 'error'));
2793 * Do not call this function directly.
2795 * To terminate the current script with a fatal error, call the {@link print_error}
2796 * function, or throw an exception. Doing either of those things will then call this
2797 * function to display the error, before terminating the execution.
2799 * @param string $message The message to output
2800 * @param string $moreinfourl URL where more info can be found about the error
2801 * @param string $link Link for the Continue button
2802 * @param array $backtrace The execution backtrace
2803 * @param string $debuginfo Debugging information
2804 * @return string the HTML to output.
2806 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2807 global $CFG;
2809 $output = '';
2810 $obbuffer = '';
2812 if ($this->has_started()) {
2813 // we can not always recover properly here, we have problems with output buffering,
2814 // html tables, etc.
2815 $output .= $this->opencontainers->pop_all_but_last();
2817 } else {
2818 // It is really bad if library code throws exception when output buffering is on,
2819 // because the buffered text would be printed before our start of page.
2820 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2821 error_reporting(0); // disable notices from gzip compression, etc.
2822 while (ob_get_level() > 0) {
2823 $buff = ob_get_clean();
2824 if ($buff === false) {
2825 break;
2827 $obbuffer .= $buff;
2829 error_reporting($CFG->debug);
2831 // Output not yet started.
2832 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2833 if (empty($_SERVER['HTTP_RANGE'])) {
2834 @header($protocol . ' 404 Not Found');
2835 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2836 // Coax iOS 10 into sending the session cookie.
2837 @header($protocol . ' 403 Forbidden');
2838 } else {
2839 // Must stop byteserving attempts somehow,
2840 // this is weird but Chrome PDF viewer can be stopped only with 407!
2841 @header($protocol . ' 407 Proxy Authentication Required');
2844 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2845 $this->page->set_url('/'); // no url
2846 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2847 $this->page->set_title(get_string('error'));
2848 $this->page->set_heading($this->page->course->fullname);
2849 $output .= $this->header();
2852 $message = '<p class="errormessage">' . $message . '</p>'.
2853 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2854 get_string('moreinformation') . '</a></p>';
2855 if (empty($CFG->rolesactive)) {
2856 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2857 //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.
2859 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2861 if ($CFG->debugdeveloper) {
2862 if (!empty($debuginfo)) {
2863 $debuginfo = s($debuginfo); // removes all nasty JS
2864 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2865 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2867 if (!empty($backtrace)) {
2868 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2870 if ($obbuffer !== '' ) {
2871 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2875 if (empty($CFG->rolesactive)) {
2876 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2877 } else if (!empty($link)) {
2878 $output .= $this->continue_button($link);
2881 $output .= $this->footer();
2883 // Padding to encourage IE to display our error page, rather than its own.
2884 $output .= str_repeat(' ', 512);
2886 return $output;
2890 * Output a notification (that is, a status message about something that has just happened).
2892 * Note: \core\notification::add() may be more suitable for your usage.
2894 * @param string $message The message to print out.
2895 * @param string $type The type of notification. See constants on \core\output\notification.
2896 * @return string the HTML to output.
2898 public function notification($message, $type = null) {
2899 $typemappings = [
2900 // Valid types.
2901 'success' => \core\output\notification::NOTIFY_SUCCESS,
2902 'info' => \core\output\notification::NOTIFY_INFO,
2903 'warning' => \core\output\notification::NOTIFY_WARNING,
2904 'error' => \core\output\notification::NOTIFY_ERROR,
2906 // Legacy types mapped to current types.
2907 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2908 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2909 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2910 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2911 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2912 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2913 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2916 $extraclasses = [];
2918 if ($type) {
2919 if (strpos($type, ' ') === false) {
2920 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2921 if (isset($typemappings[$type])) {
2922 $type = $typemappings[$type];
2923 } else {
2924 // The value provided did not match a known type. It must be an extra class.
2925 $extraclasses = [$type];
2927 } else {
2928 // Identify what type of notification this is.
2929 $classarray = explode(' ', self::prepare_classes($type));
2931 // Separate out the type of notification from the extra classes.
2932 foreach ($classarray as $class) {
2933 if (isset($typemappings[$class])) {
2934 $type = $typemappings[$class];
2935 } else {
2936 $extraclasses[] = $class;
2942 $notification = new \core\output\notification($message, $type);
2943 if (count($extraclasses)) {
2944 $notification->set_extra_classes($extraclasses);
2947 // Return the rendered template.
2948 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2952 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2954 public function notify_problem() {
2955 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
2956 'please use \core\notification::add(), or \core\output\notification as required.');
2960 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2962 public function notify_success() {
2963 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
2964 'please use \core\notification::add(), or \core\output\notification as required.');
2968 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2970 public function notify_message() {
2971 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
2972 'please use \core\notification::add(), or \core\output\notification as required.');
2976 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2978 public function notify_redirect() {
2979 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
2980 'please use \core\notification::add(), or \core\output\notification as required.');
2984 * Render a notification (that is, a status message about something that has
2985 * just happened).
2987 * @param \core\output\notification $notification the notification to print out
2988 * @return string the HTML to output.
2990 protected function render_notification(\core\output\notification $notification) {
2991 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2995 * Returns HTML to display a continue button that goes to a particular URL.
2997 * @param string|moodle_url $url The url the button goes to.
2998 * @return string the HTML to output.
3000 public function continue_button($url) {
3001 if (!($url instanceof moodle_url)) {
3002 $url = new moodle_url($url);
3004 $button = new single_button($url, get_string('continue'), 'get', true);
3005 $button->class = 'continuebutton';
3007 return $this->render($button);
3011 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
3013 * Theme developers: DO NOT OVERRIDE! Please override function
3014 * {@link core_renderer::render_paging_bar()} instead.
3016 * @param int $totalcount The total number of entries available to be paged through
3017 * @param int $page The page you are currently viewing
3018 * @param int $perpage The number of entries that should be shown per page
3019 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3020 * @param string $pagevar name of page parameter that holds the page number
3021 * @return string the HTML to output.
3023 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3024 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3025 return $this->render($pb);
3029 * Returns HTML to display the paging bar.
3031 * @param paging_bar $pagingbar
3032 * @return string the HTML to output.
3034 protected function render_paging_bar(paging_bar $pagingbar) {
3035 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3036 $pagingbar->maxdisplay = 10;
3037 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3041 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3043 * @param string $current the currently selected letter.
3044 * @param string $class class name to add to this initial bar.
3045 * @param string $title the name to put in front of this initial bar.
3046 * @param string $urlvar URL parameter name for this initial.
3047 * @param string $url URL object.
3048 * @param array $alpha of letters in the alphabet.
3049 * @return string the HTML to output.
3051 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3052 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3053 return $this->render($ib);
3057 * Internal implementation of initials bar rendering.
3059 * @param initials_bar $initialsbar
3060 * @return string
3062 protected function render_initials_bar(initials_bar $initialsbar) {
3063 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3067 * Output the place a skip link goes to.
3069 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3070 * @return string the HTML to output.
3072 public function skip_link_target($id = null) {
3073 return html_writer::span('', '', array('id' => $id));
3077 * Outputs a heading
3079 * @param string $text The text of the heading
3080 * @param int $level The level of importance of the heading. Defaulting to 2
3081 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3082 * @param string $id An optional ID
3083 * @return string the HTML to output.
3085 public function heading($text, $level = 2, $classes = null, $id = null) {
3086 $level = (integer) $level;
3087 if ($level < 1 or $level > 6) {
3088 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3090 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3094 * Outputs a box.
3096 * @param string $contents The contents of the box
3097 * @param string $classes A space-separated list of CSS classes
3098 * @param string $id An optional ID
3099 * @param array $attributes An array of other attributes to give the box.
3100 * @return string the HTML to output.
3102 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3103 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3107 * Outputs the opening section of a box.
3109 * @param string $classes A space-separated list of CSS classes
3110 * @param string $id An optional ID
3111 * @param array $attributes An array of other attributes to give the box.
3112 * @return string the HTML to output.
3114 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3115 $this->opencontainers->push('box', html_writer::end_tag('div'));
3116 $attributes['id'] = $id;
3117 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
3118 return html_writer::start_tag('div', $attributes);
3122 * Outputs the closing section of a box.
3124 * @return string the HTML to output.
3126 public function box_end() {
3127 return $this->opencontainers->pop('box');
3131 * Outputs a container.
3133 * @param string $contents The contents of the box
3134 * @param string $classes A space-separated list of CSS classes
3135 * @param string $id An optional ID
3136 * @return string the HTML to output.
3138 public function container($contents, $classes = null, $id = null) {
3139 return $this->container_start($classes, $id) . $contents . $this->container_end();
3143 * Outputs the opening section of a container.
3145 * @param string $classes A space-separated list of CSS classes
3146 * @param string $id An optional ID
3147 * @return string the HTML to output.
3149 public function container_start($classes = null, $id = null) {
3150 $this->opencontainers->push('container', html_writer::end_tag('div'));
3151 return html_writer::start_tag('div', array('id' => $id,
3152 'class' => renderer_base::prepare_classes($classes)));
3156 * Outputs the closing section of a container.
3158 * @return string the HTML to output.
3160 public function container_end() {
3161 return $this->opencontainers->pop('container');
3165 * Make nested HTML lists out of the items
3167 * The resulting list will look something like this:
3169 * <pre>
3170 * <<ul>>
3171 * <<li>><div class='tree_item parent'>(item contents)</div>
3172 * <<ul>
3173 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3174 * <</ul>>
3175 * <</li>>
3176 * <</ul>>
3177 * </pre>
3179 * @param array $items
3180 * @param array $attrs html attributes passed to the top ofs the list
3181 * @return string HTML
3183 public function tree_block_contents($items, $attrs = array()) {
3184 // exit if empty, we don't want an empty ul element
3185 if (empty($items)) {
3186 return '';
3188 // array of nested li elements
3189 $lis = array();
3190 foreach ($items as $item) {
3191 // this applies to the li item which contains all child lists too
3192 $content = $item->content($this);
3193 $liclasses = array($item->get_css_type());
3194 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3195 $liclasses[] = 'collapsed';
3197 if ($item->isactive === true) {
3198 $liclasses[] = 'current_branch';
3200 $liattr = array('class'=>join(' ',$liclasses));
3201 // class attribute on the div item which only contains the item content
3202 $divclasses = array('tree_item');
3203 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3204 $divclasses[] = 'branch';
3205 } else {
3206 $divclasses[] = 'leaf';
3208 if (!empty($item->classes) && count($item->classes)>0) {
3209 $divclasses[] = join(' ', $item->classes);
3211 $divattr = array('class'=>join(' ', $divclasses));
3212 if (!empty($item->id)) {
3213 $divattr['id'] = $item->id;
3215 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3216 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3217 $content = html_writer::empty_tag('hr') . $content;
3219 $content = html_writer::tag('li', $content, $liattr);
3220 $lis[] = $content;
3222 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3226 * Returns a search box.
3228 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3229 * @return string HTML with the search form hidden by default.
3231 public function search_box($id = false) {
3232 global $CFG;
3234 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3235 // result in an extra included file for each site, even the ones where global search
3236 // is disabled.
3237 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3238 return '';
3241 if ($id == false) {
3242 $id = uniqid();
3243 } else {
3244 // Needs to be cleaned, we use it for the input id.
3245 $id = clean_param($id, PARAM_ALPHANUMEXT);
3248 // JS to animate the form.
3249 $this->page->requires->js_call_amd('core/search-input', 'init', array($id));
3251 $searchicon = html_writer::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
3252 array('role' => 'button', 'tabindex' => 0));
3253 $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot . '/search/index.php');
3254 $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
3255 'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id, 'class' => 'form-control');
3257 $contents = html_writer::tag('label', get_string('enteryoursearchquery', 'search'),
3258 array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer::tag('input', '', $inputattrs);
3259 if ($this->page->context && $this->page->context->contextlevel !== CONTEXT_SYSTEM) {
3260 $contents .= html_writer::empty_tag('input', ['type' => 'hidden',
3261 'name' => 'context', 'value' => $this->page->context->id]);
3263 $searchinput = html_writer::tag('form', $contents, $formattrs);
3265 return html_writer::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper nav-link', 'id' => $id));
3269 * Allow plugins to provide some content to be rendered in the navbar.
3270 * The plugin must define a PLUGIN_render_navbar_output function that returns
3271 * the HTML they wish to add to the navbar.
3273 * @return string HTML for the navbar
3275 public function navbar_plugin_output() {
3276 $output = '';
3278 // Give subsystems an opportunity to inject extra html content. The callback
3279 // must always return a string containing valid html.
3280 foreach (\core_component::get_core_subsystems() as $name => $path) {
3281 if ($path) {
3282 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3286 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3287 foreach ($pluginsfunction as $plugintype => $plugins) {
3288 foreach ($plugins as $pluginfunction) {
3289 $output .= $pluginfunction($this);
3294 return $output;
3298 * Construct a user menu, returning HTML that can be echoed out by a
3299 * layout file.
3301 * @param stdClass $user A user object, usually $USER.
3302 * @param bool $withlinks true if a dropdown should be built.
3303 * @return string HTML fragment.
3305 public function user_menu($user = null, $withlinks = null) {
3306 global $USER, $CFG;
3307 require_once($CFG->dirroot . '/user/lib.php');
3309 if (is_null($user)) {
3310 $user = $USER;
3313 // Note: this behaviour is intended to match that of core_renderer::login_info,
3314 // but should not be considered to be good practice; layout options are
3315 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3316 if (is_null($withlinks)) {
3317 $withlinks = empty($this->page->layout_options['nologinlinks']);
3320 // Add a class for when $withlinks is false.
3321 $usermenuclasses = 'usermenu';
3322 if (!$withlinks) {
3323 $usermenuclasses .= ' withoutlinks';
3326 $returnstr = "";
3328 // If during initial install, return the empty return string.
3329 if (during_initial_install()) {
3330 return $returnstr;
3333 $loginpage = $this->is_login_page();
3334 $loginurl = get_login_url();
3335 // If not logged in, show the typical not-logged-in string.
3336 if (!isloggedin()) {
3337 $returnstr = get_string('loggedinnot', 'moodle');
3338 if (!$loginpage) {
3339 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3341 return html_writer::div(
3342 html_writer::span(
3343 $returnstr,
3344 'login'
3346 $usermenuclasses
3351 // If logged in as a guest user, show a string to that effect.
3352 if (isguestuser()) {
3353 $returnstr = get_string('loggedinasguest');
3354 if (!$loginpage && $withlinks) {
3355 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3358 return html_writer::div(
3359 html_writer::span(
3360 $returnstr,
3361 'login'
3363 $usermenuclasses
3367 // Get some navigation opts.
3368 $opts = user_get_user_navigation_info($user, $this->page);
3370 $avatarclasses = "avatars";
3371 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3372 $usertextcontents = $opts->metadata['userfullname'];
3374 // Other user.
3375 if (!empty($opts->metadata['asotheruser'])) {
3376 $avatarcontents .= html_writer::span(
3377 $opts->metadata['realuseravatar'],
3378 'avatar realuser'
3380 $usertextcontents = $opts->metadata['realuserfullname'];
3381 $usertextcontents .= html_writer::tag(
3382 'span',
3383 get_string(
3384 'loggedinas',
3385 'moodle',
3386 html_writer::span(
3387 $opts->metadata['userfullname'],
3388 'value'
3391 array('class' => 'meta viewingas')
3395 // Role.
3396 if (!empty($opts->metadata['asotherrole'])) {
3397 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3398 $usertextcontents .= html_writer::span(
3399 $opts->metadata['rolename'],
3400 'meta role role-' . $role
3404 // User login failures.
3405 if (!empty($opts->metadata['userloginfail'])) {
3406 $usertextcontents .= html_writer::span(
3407 $opts->metadata['userloginfail'],
3408 'meta loginfailures'
3412 // MNet.
3413 if (!empty($opts->metadata['asmnetuser'])) {
3414 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3415 $usertextcontents .= html_writer::span(
3416 $opts->metadata['mnetidprovidername'],
3417 'meta mnet mnet-' . $mnet
3421 $returnstr .= html_writer::span(
3422 html_writer::span($usertextcontents, 'usertext mr-1') .
3423 html_writer::span($avatarcontents, $avatarclasses),
3424 'userbutton'
3427 // Create a divider (well, a filler).
3428 $divider = new action_menu_filler();
3429 $divider->primary = false;
3431 $am = new action_menu();
3432 $am->set_menu_trigger(
3433 $returnstr
3435 $am->set_action_label(get_string('usermenu'));
3436 $am->set_alignment(action_menu::TR, action_menu::BR);
3437 $am->set_nowrap_on_items();
3438 if ($withlinks) {
3439 $navitemcount = count($opts->navitems);
3440 $idx = 0;
3441 foreach ($opts->navitems as $key => $value) {
3443 switch ($value->itemtype) {
3444 case 'divider':
3445 // If the nav item is a divider, add one and skip link processing.
3446 $am->add($divider);
3447 break;
3449 case 'invalid':
3450 // Silently skip invalid entries (should we post a notification?).
3451 break;
3453 case 'link':
3454 // Process this as a link item.
3455 $pix = null;
3456 if (isset($value->pix) && !empty($value->pix)) {
3457 $pix = new pix_icon($value->pix, $value->title, null, array('class' => 'iconsmall'));
3458 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3459 $value->title = html_writer::img(
3460 $value->imgsrc,
3461 $value->title,
3462 array('class' => 'iconsmall')
3463 ) . $value->title;
3466 $al = new action_menu_link_secondary(
3467 $value->url,
3468 $pix,
3469 $value->title,
3470 array('class' => 'icon')
3472 if (!empty($value->titleidentifier)) {
3473 $al->attributes['data-title'] = $value->titleidentifier;
3475 $am->add($al);
3476 break;
3479 $idx++;
3481 // Add dividers after the first item and before the last item.
3482 if ($idx == 1 || $idx == $navitemcount - 1) {
3483 $am->add($divider);
3488 return html_writer::div(
3489 $this->render($am),
3490 $usermenuclasses
3495 * Return the navbar content so that it can be echoed out by the layout
3497 * @return string XHTML navbar
3499 public function navbar() {
3500 $items = $this->page->navbar->get_items();
3501 $itemcount = count($items);
3502 if ($itemcount === 0) {
3503 return '';
3506 $htmlblocks = array();
3507 // Iterate the navarray and display each node
3508 $separator = get_separator();
3509 for ($i=0;$i < $itemcount;$i++) {
3510 $item = $items[$i];
3511 $item->hideicon = true;
3512 if ($i===0) {
3513 $content = html_writer::tag('li', $this->render($item));
3514 } else {
3515 $content = html_writer::tag('li', $separator.$this->render($item));
3517 $htmlblocks[] = $content;
3520 //accessibility: heading for navbar list (MDL-20446)
3521 $navbarcontent = html_writer::tag('span', get_string('pagepath'),
3522 array('class' => 'accesshide', 'id' => 'navbar-label'));
3523 $navbarcontent .= html_writer::tag('nav',
3524 html_writer::tag('ul', join('', $htmlblocks)),
3525 array('aria-labelledby' => 'navbar-label'));
3526 // XHTML
3527 return $navbarcontent;
3531 * Renders a breadcrumb navigation node object.
3533 * @param breadcrumb_navigation_node $item The navigation node to render.
3534 * @return string HTML fragment
3536 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3538 if ($item->action instanceof moodle_url) {
3539 $content = $item->get_content();
3540 $title = $item->get_title();
3541 $attributes = array();
3542 $attributes['itemprop'] = 'url';
3543 if ($title !== '') {
3544 $attributes['title'] = $title;
3546 if ($item->hidden) {
3547 $attributes['class'] = 'dimmed_text';
3549 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3550 $content = html_writer::link($item->action, $content, $attributes);
3552 $attributes = array();
3553 $attributes['itemscope'] = '';
3554 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3555 $content = html_writer::tag('span', $content, $attributes);
3557 } else {
3558 $content = $this->render_navigation_node($item);
3560 return $content;
3564 * Renders a navigation node object.
3566 * @param navigation_node $item The navigation node to render.
3567 * @return string HTML fragment
3569 protected function render_navigation_node(navigation_node $item) {
3570 $content = $item->get_content();
3571 $title = $item->get_title();
3572 if ($item->icon instanceof renderable && !$item->hideicon) {
3573 $icon = $this->render($item->icon);
3574 $content = $icon.$content; // use CSS for spacing of icons
3576 if ($item->helpbutton !== null) {
3577 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3579 if ($content === '') {
3580 return '';
3582 if ($item->action instanceof action_link) {
3583 $link = $item->action;
3584 if ($item->hidden) {
3585 $link->add_class('dimmed');
3587 if (!empty($content)) {
3588 // Providing there is content we will use that for the link content.
3589 $link->text = $content;
3591 $content = $this->render($link);
3592 } else if ($item->action instanceof moodle_url) {
3593 $attributes = array();
3594 if ($title !== '') {
3595 $attributes['title'] = $title;
3597 if ($item->hidden) {
3598 $attributes['class'] = 'dimmed_text';
3600 $content = html_writer::link($item->action, $content, $attributes);
3602 } else if (is_string($item->action) || empty($item->action)) {
3603 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3604 if ($title !== '') {
3605 $attributes['title'] = $title;
3607 if ($item->hidden) {
3608 $attributes['class'] = 'dimmed_text';
3610 $content = html_writer::tag('span', $content, $attributes);
3612 return $content;
3616 * Accessibility: Right arrow-like character is
3617 * used in the breadcrumb trail, course navigation menu
3618 * (previous/next activity), calendar, and search forum block.
3619 * If the theme does not set characters, appropriate defaults
3620 * are set automatically. Please DO NOT
3621 * use &lt; &gt; &raquo; - these are confusing for blind users.
3623 * @return string
3625 public function rarrow() {
3626 return $this->page->theme->rarrow;
3630 * Accessibility: Left arrow-like character is
3631 * used in the breadcrumb trail, course navigation menu
3632 * (previous/next activity), calendar, and search forum block.
3633 * If the theme does not set characters, appropriate defaults
3634 * are set automatically. Please DO NOT
3635 * use &lt; &gt; &raquo; - these are confusing for blind users.
3637 * @return string
3639 public function larrow() {
3640 return $this->page->theme->larrow;
3644 * Accessibility: Up arrow-like character is used in
3645 * the book heirarchical navigation.
3646 * If the theme does not set characters, appropriate defaults
3647 * are set automatically. Please DO NOT
3648 * use ^ - this is confusing for blind users.
3650 * @return string
3652 public function uarrow() {
3653 return $this->page->theme->uarrow;
3657 * Accessibility: Down arrow-like character.
3658 * If the theme does not set characters, appropriate defaults
3659 * are set automatically.
3661 * @return string
3663 public function darrow() {
3664 return $this->page->theme->darrow;
3668 * Returns the custom menu if one has been set
3670 * A custom menu can be configured by browsing to
3671 * Settings: Administration > Appearance > Themes > Theme settings
3672 * and then configuring the custommenu config setting as described.
3674 * Theme developers: DO NOT OVERRIDE! Please override function
3675 * {@link core_renderer::render_custom_menu()} instead.
3677 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3678 * @return string
3680 public function custom_menu($custommenuitems = '') {
3681 global $CFG;
3682 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3683 $custommenuitems = $CFG->custommenuitems;
3685 if (empty($custommenuitems)) {
3686 return '';
3688 $custommenu = new custom_menu($custommenuitems, current_language());
3689 return $this->render($custommenu);
3693 * Renders a custom menu object (located in outputcomponents.php)
3695 * The custom menu this method produces makes use of the YUI3 menunav widget
3696 * and requires very specific html elements and classes.
3698 * @staticvar int $menucount
3699 * @param custom_menu $menu
3700 * @return string
3702 protected function render_custom_menu(custom_menu $menu) {
3703 static $menucount = 0;
3704 // If the menu has no children return an empty string
3705 if (!$menu->has_children()) {
3706 return '';
3708 // Increment the menu count. This is used for ID's that get worked with
3709 // in JavaScript as is essential
3710 $menucount++;
3711 // Initialise this custom menu (the custom menu object is contained in javascript-static
3712 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
3713 $jscode = "(function(){{$jscode}})";
3714 $this->page->requires->yui_module('node-menunav', $jscode);
3715 // Build the root nodes as required by YUI
3716 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
3717 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3718 $content .= html_writer::start_tag('ul');
3719 // Render each child
3720 foreach ($menu->get_children() as $item) {
3721 $content .= $this->render_custom_menu_item($item);
3723 // Close the open tags
3724 $content .= html_writer::end_tag('ul');
3725 $content .= html_writer::end_tag('div');
3726 $content .= html_writer::end_tag('div');
3727 // Return the custom menu
3728 return $content;
3732 * Renders a custom menu node as part of a submenu
3734 * The custom menu this method produces makes use of the YUI3 menunav widget
3735 * and requires very specific html elements and classes.
3737 * @see core:renderer::render_custom_menu()
3739 * @staticvar int $submenucount
3740 * @param custom_menu_item $menunode
3741 * @return string
3743 protected function render_custom_menu_item(custom_menu_item $menunode) {
3744 // Required to ensure we get unique trackable id's
3745 static $submenucount = 0;
3746 if ($menunode->has_children()) {
3747 // If the child has menus render it as a sub menu
3748 $submenucount++;
3749 $content = html_writer::start_tag('li');
3750 if ($menunode->get_url() !== null) {
3751 $url = $menunode->get_url();
3752 } else {
3753 $url = '#cm_submenu_'.$submenucount;
3755 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3756 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3757 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3758 $content .= html_writer::start_tag('ul');
3759 foreach ($menunode->get_children() as $menunode) {
3760 $content .= $this->render_custom_menu_item($menunode);
3762 $content .= html_writer::end_tag('ul');
3763 $content .= html_writer::end_tag('div');
3764 $content .= html_writer::end_tag('div');
3765 $content .= html_writer::end_tag('li');
3766 } else {
3767 // The node doesn't have children so produce a final menuitem.
3768 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3769 $content = '';
3770 if (preg_match("/^#+$/", $menunode->get_text())) {
3772 // This is a divider.
3773 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3774 } else {
3775 $content = html_writer::start_tag(
3776 'li',
3777 array(
3778 'class' => 'yui3-menuitem'
3781 if ($menunode->get_url() !== null) {
3782 $url = $menunode->get_url();
3783 } else {
3784 $url = '#';
3786 $content .= html_writer::link(
3787 $url,
3788 $menunode->get_text(),
3789 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3792 $content .= html_writer::end_tag('li');
3794 // Return the sub menu
3795 return $content;
3799 * Renders theme links for switching between default and other themes.
3801 * @return string
3803 protected function theme_switch_links() {
3805 $actualdevice = core_useragent::get_device_type();
3806 $currentdevice = $this->page->devicetypeinuse;
3807 $switched = ($actualdevice != $currentdevice);
3809 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3810 // The user is using the a default device and hasn't switched so don't shown the switch
3811 // device links.
3812 return '';
3815 if ($switched) {
3816 $linktext = get_string('switchdevicerecommended');
3817 $devicetype = $actualdevice;
3818 } else {
3819 $linktext = get_string('switchdevicedefault');
3820 $devicetype = 'default';
3822 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3824 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3825 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3826 $content .= html_writer::end_tag('div');
3828 return $content;
3832 * Renders tabs
3834 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3836 * Theme developers: In order to change how tabs are displayed please override functions
3837 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3839 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3840 * @param string|null $selected which tab to mark as selected, all parent tabs will
3841 * automatically be marked as activated
3842 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3843 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3844 * @return string
3846 public final function tabtree($tabs, $selected = null, $inactive = null) {
3847 return $this->render(new tabtree($tabs, $selected, $inactive));
3851 * Renders tabtree
3853 * @param tabtree $tabtree
3854 * @return string
3856 protected function render_tabtree(tabtree $tabtree) {
3857 if (empty($tabtree->subtree)) {
3858 return '';
3860 $str = '';
3861 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
3862 $str .= $this->render_tabobject($tabtree);
3863 $str .= html_writer::end_tag('div').
3864 html_writer::tag('div', ' ', array('class' => 'clearer'));
3865 return $str;
3869 * Renders tabobject (part of tabtree)
3871 * This function is called from {@link core_renderer::render_tabtree()}
3872 * and also it calls itself when printing the $tabobject subtree recursively.
3874 * Property $tabobject->level indicates the number of row of tabs.
3876 * @param tabobject $tabobject
3877 * @return string HTML fragment
3879 protected function render_tabobject(tabobject $tabobject) {
3880 $str = '';
3882 // Print name of the current tab.
3883 if ($tabobject instanceof tabtree) {
3884 // No name for tabtree root.
3885 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3886 // Tab name without a link. The <a> tag is used for styling.
3887 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3888 } else {
3889 // Tab name with a link.
3890 if (!($tabobject->link instanceof moodle_url)) {
3891 // backward compartibility when link was passed as quoted string
3892 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3893 } else {
3894 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3898 if (empty($tabobject->subtree)) {
3899 if ($tabobject->selected) {
3900 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3902 return $str;
3905 // Print subtree.
3906 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
3907 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3908 $cnt = 0;
3909 foreach ($tabobject->subtree as $tab) {
3910 $liclass = '';
3911 if (!$cnt) {
3912 $liclass .= ' first';
3914 if ($cnt == count($tabobject->subtree) - 1) {
3915 $liclass .= ' last';
3917 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3918 $liclass .= ' onerow';
3921 if ($tab->selected) {
3922 $liclass .= ' here selected';
3923 } else if ($tab->activated) {
3924 $liclass .= ' here active';
3927 // This will recursively call function render_tabobject() for each item in subtree.
3928 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3929 $cnt++;
3931 $str .= html_writer::end_tag('ul');
3934 return $str;
3938 * Get the HTML for blocks in the given region.
3940 * @since Moodle 2.5.1 2.6
3941 * @param string $region The region to get HTML for.
3942 * @return string HTML.
3944 public function blocks($region, $classes = array(), $tag = 'aside') {
3945 $displayregion = $this->page->apply_theme_region_manipulations($region);
3946 $classes = (array)$classes;
3947 $classes[] = 'block-region';
3948 $attributes = array(
3949 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3950 'class' => join(' ', $classes),
3951 'data-blockregion' => $displayregion,
3952 'data-droptarget' => '1'
3954 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3955 $content = $this->blocks_for_region($displayregion);
3956 } else {
3957 $content = '';
3959 return html_writer::tag($tag, $content, $attributes);
3963 * Renders a custom block region.
3965 * Use this method if you want to add an additional block region to the content of the page.
3966 * Please note this should only be used in special situations.
3967 * We want to leave the theme is control where ever possible!
3969 * This method must use the same method that the theme uses within its layout file.
3970 * As such it asks the theme what method it is using.
3971 * It can be one of two values, blocks or blocks_for_region (deprecated).
3973 * @param string $regionname The name of the custom region to add.
3974 * @return string HTML for the block region.
3976 public function custom_block_region($regionname) {
3977 if ($this->page->theme->get_block_render_method() === 'blocks') {
3978 return $this->blocks($regionname);
3979 } else {
3980 return $this->blocks_for_region($regionname);
3985 * Returns the CSS classes to apply to the body tag.
3987 * @since Moodle 2.5.1 2.6
3988 * @param array $additionalclasses Any additional classes to apply.
3989 * @return string
3991 public function body_css_classes(array $additionalclasses = array()) {
3992 // Add a class for each block region on the page.
3993 // We use the block manager here because the theme object makes get_string calls.
3994 $usedregions = array();
3995 foreach ($this->page->blocks->get_regions() as $region) {
3996 $additionalclasses[] = 'has-region-'.$region;
3997 if ($this->page->blocks->region_has_content($region, $this)) {
3998 $additionalclasses[] = 'used-region-'.$region;
3999 $usedregions[] = $region;
4000 } else {
4001 $additionalclasses[] = 'empty-region-'.$region;
4003 if ($this->page->blocks->region_completely_docked($region, $this)) {
4004 $additionalclasses[] = 'docked-region-'.$region;
4007 if (!$usedregions) {
4008 // No regions means there is only content, add 'content-only' class.
4009 $additionalclasses[] = 'content-only';
4010 } else if (count($usedregions) === 1) {
4011 // Add the -only class for the only used region.
4012 $region = array_shift($usedregions);
4013 $additionalclasses[] = $region . '-only';
4015 foreach ($this->page->layout_options as $option => $value) {
4016 if ($value) {
4017 $additionalclasses[] = 'layout-option-'.$option;
4020 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
4021 return $css;
4025 * The ID attribute to apply to the body tag.
4027 * @since Moodle 2.5.1 2.6
4028 * @return string
4030 public function body_id() {
4031 return $this->page->bodyid;
4035 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4037 * @since Moodle 2.5.1 2.6
4038 * @param string|array $additionalclasses Any additional classes to give the body tag,
4039 * @return string
4041 public function body_attributes($additionalclasses = array()) {
4042 if (!is_array($additionalclasses)) {
4043 $additionalclasses = explode(' ', $additionalclasses);
4045 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4049 * Gets HTML for the page heading.
4051 * @since Moodle 2.5.1 2.6
4052 * @param string $tag The tag to encase the heading in. h1 by default.
4053 * @return string HTML.
4055 public function page_heading($tag = 'h1') {
4056 return html_writer::tag($tag, $this->page->heading);
4060 * Gets the HTML for the page heading button.
4062 * @since Moodle 2.5.1 2.6
4063 * @return string HTML.
4065 public function page_heading_button() {
4066 return $this->page->button;
4070 * Returns the Moodle docs link to use for this page.
4072 * @since Moodle 2.5.1 2.6
4073 * @param string $text
4074 * @return string
4076 public function page_doc_link($text = null) {
4077 if ($text === null) {
4078 $text = get_string('moodledocslink');
4080 $path = page_get_doc_link_path($this->page);
4081 if (!$path) {
4082 return '';
4084 return $this->doc_link($path, $text);
4088 * Returns the page heading menu.
4090 * @since Moodle 2.5.1 2.6
4091 * @return string HTML.
4093 public function page_heading_menu() {
4094 return $this->page->headingmenu;
4098 * Returns the title to use on the page.
4100 * @since Moodle 2.5.1 2.6
4101 * @return string
4103 public function page_title() {
4104 return $this->page->title;
4108 * Returns the URL for the favicon.
4110 * @since Moodle 2.5.1 2.6
4111 * @return string The favicon URL
4113 public function favicon() {
4114 return $this->image_url('favicon', 'theme');
4118 * Renders preferences groups.
4120 * @param preferences_groups $renderable The renderable
4121 * @return string The output.
4123 public function render_preferences_groups(preferences_groups $renderable) {
4124 $html = '';
4125 $html .= html_writer::start_div('row-fluid');
4126 $html .= html_writer::start_tag('div', array('class' => 'span12 preferences-groups'));
4127 $i = 0;
4128 $open = false;
4129 foreach ($renderable->groups as $group) {
4130 if ($i == 0 || $i % 3 == 0) {
4131 if ($open) {
4132 $html .= html_writer::end_tag('div');
4134 $html .= html_writer::start_tag('div', array('class' => 'row-fluid'));
4135 $open = true;
4137 $html .= $this->render($group);
4138 $i++;
4141 $html .= html_writer::end_tag('div');
4143 $html .= html_writer::end_tag('ul');
4144 $html .= html_writer::end_tag('div');
4145 $html .= html_writer::end_div();
4146 return $html;
4150 * Renders preferences group.
4152 * @param preferences_group $renderable The renderable
4153 * @return string The output.
4155 public function render_preferences_group(preferences_group $renderable) {
4156 $html = '';
4157 $html .= html_writer::start_tag('div', array('class' => 'span4 preferences-group'));
4158 $html .= $this->heading($renderable->title, 3);
4159 $html .= html_writer::start_tag('ul');
4160 foreach ($renderable->nodes as $node) {
4161 if ($node->has_children()) {
4162 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4164 $html .= html_writer::tag('li', $this->render($node));
4166 $html .= html_writer::end_tag('ul');
4167 $html .= html_writer::end_tag('div');
4168 return $html;
4171 public function context_header($headerinfo = null, $headinglevel = 1) {
4172 global $DB, $USER, $CFG;
4173 require_once($CFG->dirroot . '/user/lib.php');
4174 $context = $this->page->context;
4175 $heading = null;
4176 $imagedata = null;
4177 $subheader = null;
4178 $userbuttons = null;
4179 // Make sure to use the heading if it has been set.
4180 if (isset($headerinfo['heading'])) {
4181 $heading = $headerinfo['heading'];
4184 // The user context currently has images and buttons. Other contexts may follow.
4185 if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
4186 if (isset($headerinfo['user'])) {
4187 $user = $headerinfo['user'];
4188 } else {
4189 // Look up the user information if it is not supplied.
4190 $user = $DB->get_record('user', array('id' => $context->instanceid));
4193 // If the user context is set, then use that for capability checks.
4194 if (isset($headerinfo['usercontext'])) {
4195 $context = $headerinfo['usercontext'];
4198 // Only provide user information if the user is the current user, or a user which the current user can view.
4199 // When checking user_can_view_profile(), either:
4200 // If the page context is course, check the course context (from the page object) or;
4201 // If page context is NOT course, then check across all courses.
4202 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4204 if (user_can_view_profile($user, $course)) {
4205 // Use the user's full name if the heading isn't set.
4206 if (!isset($heading)) {
4207 $heading = fullname($user);
4210 $imagedata = $this->user_picture($user, array('size' => 100));
4212 // Check to see if we should be displaying a message button.
4213 if (!empty($CFG->messaging) && $USER->id != $user->id && has_capability('moodle/site:sendmessage', $context)) {
4214 $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4215 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4216 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4217 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4218 $userbuttons = array(
4219 'messages' => array(
4220 'buttontype' => 'message',
4221 'title' => get_string('message', 'message'),
4222 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4223 'image' => 'message',
4224 'linkattributes' => array('role' => 'button'),
4225 'page' => $this->page
4227 'togglecontact' => array(
4228 'buttontype' => 'togglecontact',
4229 'title' => get_string($contacttitle, 'message'),
4230 'url' => new moodle_url('/message/index.php', array(
4231 'user1' => $USER->id,
4232 'user2' => $user->id,
4233 $contacturlaction => $user->id,
4234 'sesskey' => sesskey())
4236 'image' => $contactimage,
4237 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4238 'page' => $this->page
4242 $this->page->requires->string_for_js('changesmadereallygoaway', 'moodle');
4244 } else {
4245 $heading = null;
4249 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4250 return $this->render_context_header($contextheader);
4254 * Renders the skip links for the page.
4256 * @param array $links List of skip links.
4257 * @return string HTML for the skip links.
4259 public function render_skip_links($links) {
4260 $context = [ 'links' => []];
4262 foreach ($links as $url => $text) {
4263 $context['links'][] = [ 'url' => $url, 'text' => $text];
4266 return $this->render_from_template('core/skip_links', $context);
4270 * Renders the header bar.
4272 * @param context_header $contextheader Header bar object.
4273 * @return string HTML for the header bar.
4275 protected function render_context_header(context_header $contextheader) {
4277 $showheader = empty($this->page->layout_options['nocontextheader']);
4278 if (!$showheader) {
4279 return '';
4282 // All the html stuff goes here.
4283 $html = html_writer::start_div('page-context-header');
4285 // Image data.
4286 if (isset($contextheader->imagedata)) {
4287 // Header specific image.
4288 $html .= html_writer::div($contextheader->imagedata, 'page-header-image');
4291 // Headings.
4292 if (!isset($contextheader->heading)) {
4293 $headings = $this->heading($this->page->heading, $contextheader->headinglevel);
4294 } else {
4295 $headings = $this->heading($contextheader->heading, $contextheader->headinglevel);
4298 $html .= html_writer::tag('div', $headings, array('class' => 'page-header-headings'));
4300 // Buttons.
4301 if (isset($contextheader->additionalbuttons)) {
4302 $html .= html_writer::start_div('btn-group header-button-group');
4303 foreach ($contextheader->additionalbuttons as $button) {
4304 if (!isset($button->page)) {
4305 // Include js for messaging.
4306 if ($button['buttontype'] === 'togglecontact') {
4307 \core_message\helper::togglecontact_requirejs();
4309 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4310 'class' => 'iconsmall',
4311 'role' => 'presentation'
4313 $image .= html_writer::span($button['title'], 'header-button-title');
4314 } else {
4315 $image = html_writer::empty_tag('img', array(
4316 'src' => $button['formattedimage'],
4317 'role' => 'presentation'
4320 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4322 $html .= html_writer::end_div();
4324 $html .= html_writer::end_div();
4326 return $html;
4330 * Wrapper for header elements.
4332 * @return string HTML to display the main header.
4334 public function full_header() {
4335 $html = html_writer::start_tag('header', array('id' => 'page-header', 'class' => 'clearfix'));
4336 $html .= $this->context_header();
4337 $html .= html_writer::start_div('clearfix', array('id' => 'page-navbar'));
4338 $html .= html_writer::tag('div', $this->navbar(), array('class' => 'breadcrumb-nav'));
4339 $html .= html_writer::div($this->page_heading_button(), 'breadcrumb-button');
4340 $html .= html_writer::end_div();
4341 $html .= html_writer::tag('div', $this->course_header(), array('id' => 'course-header'));
4342 $html .= html_writer::end_tag('header');
4343 return $html;
4347 * Displays the list of tags associated with an entry
4349 * @param array $tags list of instances of core_tag or stdClass
4350 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4351 * to use default, set to '' (empty string) to omit the label completely
4352 * @param string $classes additional classes for the enclosing div element
4353 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4354 * will be appended to the end, JS will toggle the rest of the tags
4355 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4356 * @return string
4358 public function tag_list($tags, $label = null, $classes = '', $limit = 10, $pagecontext = null) {
4359 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext);
4360 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4364 * Renders element for inline editing of any value
4366 * @param \core\output\inplace_editable $element
4367 * @return string
4369 public function render_inplace_editable(\core\output\inplace_editable $element) {
4370 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4374 * Renders a bar chart.
4376 * @param \core\chart_bar $chart The chart.
4377 * @return string.
4379 public function render_chart_bar(\core\chart_bar $chart) {
4380 return $this->render_chart($chart);
4384 * Renders a line chart.
4386 * @param \core\chart_line $chart The chart.
4387 * @return string.
4389 public function render_chart_line(\core\chart_line $chart) {
4390 return $this->render_chart($chart);
4394 * Renders a pie chart.
4396 * @param \core\chart_pie $chart The chart.
4397 * @return string.
4399 public function render_chart_pie(\core\chart_pie $chart) {
4400 return $this->render_chart($chart);
4404 * Renders a chart.
4406 * @param \core\chart_base $chart The chart.
4407 * @param bool $withtable Whether to include a data table with the chart.
4408 * @return string.
4410 public function render_chart(\core\chart_base $chart, $withtable = true) {
4411 $chartdata = json_encode($chart);
4412 return $this->render_from_template('core/chart', (object) [
4413 'chartdata' => $chartdata,
4414 'withtable' => $withtable
4419 * Renders the login form.
4421 * @param \core_auth\output\login $form The renderable.
4422 * @return string
4424 public function render_login(\core_auth\output\login $form) {
4425 global $CFG;
4427 $context = $form->export_for_template($this);
4429 // Override because rendering is not supported in template yet.
4430 if ($CFG->rememberusername == 0) {
4431 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabledonlysession');
4432 } else {
4433 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
4435 $context->errorformatted = $this->error_text($context->error);
4437 return $this->render_from_template('core/loginform', $context);
4441 * Renders an mform element from a template.
4443 * @param HTML_QuickForm_element $element element
4444 * @param bool $required if input is required field
4445 * @param bool $advanced if input is an advanced field
4446 * @param string $error error message to display
4447 * @param bool $ingroup True if this element is rendered as part of a group
4448 * @return mixed string|bool
4450 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4451 $templatename = 'core_form/element-' . $element->getType();
4452 if ($ingroup) {
4453 $templatename .= "-inline";
4455 try {
4456 // We call this to generate a file not found exception if there is no template.
4457 // We don't want to call export_for_template if there is no template.
4458 core\output\mustache_template_finder::get_template_filepath($templatename);
4460 if ($element instanceof templatable) {
4461 $elementcontext = $element->export_for_template($this);
4463 $helpbutton = '';
4464 if (method_exists($element, 'getHelpButton')) {
4465 $helpbutton = $element->getHelpButton();
4467 $label = $element->getLabel();
4468 $text = '';
4469 if (method_exists($element, 'getText')) {
4470 // There currently exists code that adds a form element with an empty label.
4471 // If this is the case then set the label to the description.
4472 if (empty($label)) {
4473 $label = $element->getText();
4474 } else {
4475 $text = $element->getText();
4479 $context = array(
4480 'element' => $elementcontext,
4481 'label' => $label,
4482 'text' => $text,
4483 'required' => $required,
4484 'advanced' => $advanced,
4485 'helpbutton' => $helpbutton,
4486 'error' => $error
4488 return $this->render_from_template($templatename, $context);
4490 } catch (Exception $e) {
4491 // No template for this element.
4492 return false;
4497 * Render the login signup form into a nice template for the theme.
4499 * @param mform $form
4500 * @return string
4502 public function render_login_signup_form($form) {
4503 $context = $form->export_for_template($this);
4505 return $this->render_from_template('core/signup_form_layout', $context);
4509 * Render the verify age and location page into a nice template for the theme.
4511 * @param \core_auth\output\verify_age_location_page $page The renderable
4512 * @return string
4514 protected function render_verify_age_location_page($page) {
4515 $context = $page->export_for_template($this);
4517 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4521 * Render the digital minor contact information page into a nice template for the theme.
4523 * @param \core_auth\output\digital_minor_page $page The renderable
4524 * @return string
4526 protected function render_digital_minor_page($page) {
4527 $context = $page->export_for_template($this);
4529 return $this->render_from_template('core/auth_digital_minor_page', $context);
4533 * Renders a progress bar.
4535 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4537 * @param progress_bar $bar The bar.
4538 * @return string HTML fragment
4540 public function render_progress_bar(progress_bar $bar) {
4541 global $PAGE;
4542 $data = $bar->export_for_template($this);
4543 return $this->render_from_template('core/progress_bar', $data);
4548 * A renderer that generates output for command-line scripts.
4550 * The implementation of this renderer is probably incomplete.
4552 * @copyright 2009 Tim Hunt
4553 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4554 * @since Moodle 2.0
4555 * @package core
4556 * @category output
4558 class core_renderer_cli extends core_renderer {
4561 * Returns the page header.
4563 * @return string HTML fragment
4565 public function header() {
4566 return $this->page->heading . "\n";
4570 * Returns a template fragment representing a Heading.
4572 * @param string $text The text of the heading
4573 * @param int $level The level of importance of the heading
4574 * @param string $classes A space-separated list of CSS classes
4575 * @param string $id An optional ID
4576 * @return string A template fragment for a heading
4578 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4579 $text .= "\n";
4580 switch ($level) {
4581 case 1:
4582 return '=>' . $text;
4583 case 2:
4584 return '-->' . $text;
4585 default:
4586 return $text;
4591 * Returns a template fragment representing a fatal error.
4593 * @param string $message The message to output
4594 * @param string $moreinfourl URL where more info can be found about the error
4595 * @param string $link Link for the Continue button
4596 * @param array $backtrace The execution backtrace
4597 * @param string $debuginfo Debugging information
4598 * @return string A template fragment for a fatal error
4600 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4601 global $CFG;
4603 $output = "!!! $message !!!\n";
4605 if ($CFG->debugdeveloper) {
4606 if (!empty($debuginfo)) {
4607 $output .= $this->notification($debuginfo, 'notifytiny');
4609 if (!empty($backtrace)) {
4610 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
4614 return $output;
4618 * Returns a template fragment representing a notification.
4620 * @param string $message The message to print out.
4621 * @param string $type The type of notification. See constants on \core\output\notification.
4622 * @return string A template fragment for a notification
4624 public function notification($message, $type = null) {
4625 $message = clean_text($message);
4626 if ($type === 'notifysuccess' || $type === 'success') {
4627 return "++ $message ++\n";
4629 return "!! $message !!\n";
4633 * There is no footer for a cli request, however we must override the
4634 * footer method to prevent the default footer.
4636 public function footer() {}
4639 * Render a notification (that is, a status message about something that has
4640 * just happened).
4642 * @param \core\output\notification $notification the notification to print out
4643 * @return string plain text output
4645 public function render_notification(\core\output\notification $notification) {
4646 return $this->notification($notification->get_message(), $notification->get_message_type());
4652 * A renderer that generates output for ajax scripts.
4654 * This renderer prevents accidental sends back only json
4655 * encoded error messages, all other output is ignored.
4657 * @copyright 2010 Petr Skoda
4658 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4659 * @since Moodle 2.0
4660 * @package core
4661 * @category output
4663 class core_renderer_ajax extends core_renderer {
4666 * Returns a template fragment representing a fatal error.
4668 * @param string $message The message to output
4669 * @param string $moreinfourl URL where more info can be found about the error
4670 * @param string $link Link for the Continue button
4671 * @param array $backtrace The execution backtrace
4672 * @param string $debuginfo Debugging information
4673 * @return string A template fragment for a fatal error
4675 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4676 global $CFG;
4678 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
4680 $e = new stdClass();
4681 $e->error = $message;
4682 $e->errorcode = $errorcode;
4683 $e->stacktrace = NULL;
4684 $e->debuginfo = NULL;
4685 $e->reproductionlink = NULL;
4686 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
4687 $link = (string) $link;
4688 if ($link) {
4689 $e->reproductionlink = $link;
4691 if (!empty($debuginfo)) {
4692 $e->debuginfo = $debuginfo;
4694 if (!empty($backtrace)) {
4695 $e->stacktrace = format_backtrace($backtrace, true);
4698 $this->header();
4699 return json_encode($e);
4703 * Used to display a notification.
4704 * For the AJAX notifications are discarded.
4706 * @param string $message The message to print out.
4707 * @param string $type The type of notification. See constants on \core\output\notification.
4709 public function notification($message, $type = null) {}
4712 * Used to display a redirection message.
4713 * AJAX redirections should not occur and as such redirection messages
4714 * are discarded.
4716 * @param moodle_url|string $encodedurl
4717 * @param string $message
4718 * @param int $delay
4719 * @param bool $debugdisableredirect
4720 * @param string $messagetype The type of notification to show the message in.
4721 * See constants on \core\output\notification.
4723 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
4724 $messagetype = \core\output\notification::NOTIFY_INFO) {}
4727 * Prepares the start of an AJAX output.
4729 public function header() {
4730 // unfortunately YUI iframe upload does not support application/json
4731 if (!empty($_FILES)) {
4732 @header('Content-type: text/plain; charset=utf-8');
4733 if (!core_useragent::supports_json_contenttype()) {
4734 @header('X-Content-Type-Options: nosniff');
4736 } else if (!core_useragent::supports_json_contenttype()) {
4737 @header('Content-type: text/plain; charset=utf-8');
4738 @header('X-Content-Type-Options: nosniff');
4739 } else {
4740 @header('Content-type: application/json; charset=utf-8');
4743 // Headers to make it not cacheable and json
4744 @header('Cache-Control: no-store, no-cache, must-revalidate');
4745 @header('Cache-Control: post-check=0, pre-check=0', false);
4746 @header('Pragma: no-cache');
4747 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
4748 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
4749 @header('Accept-Ranges: none');
4753 * There is no footer for an AJAX request, however we must override the
4754 * footer method to prevent the default footer.
4756 public function footer() {}
4759 * No need for headers in an AJAX request... this should never happen.
4760 * @param string $text
4761 * @param int $level
4762 * @param string $classes
4763 * @param string $id
4765 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
4771 * The maintenance renderer.
4773 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
4774 * is running a maintenance related task.
4775 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
4777 * @since Moodle 2.6
4778 * @package core
4779 * @category output
4780 * @copyright 2013 Sam Hemelryk
4781 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4783 class core_renderer_maintenance extends core_renderer {
4786 * Initialises the renderer instance.
4787 * @param moodle_page $page
4788 * @param string $target
4789 * @throws coding_exception
4791 public function __construct(moodle_page $page, $target) {
4792 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
4793 throw new coding_exception('Invalid request for the maintenance renderer.');
4795 parent::__construct($page, $target);
4799 * Does nothing. The maintenance renderer cannot produce blocks.
4801 * @param block_contents $bc
4802 * @param string $region
4803 * @return string
4805 public function block(block_contents $bc, $region) {
4806 // Computer says no blocks.
4807 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4808 return '';
4812 * Does nothing. The maintenance renderer cannot produce blocks.
4814 * @param string $region
4815 * @param array $classes
4816 * @param string $tag
4817 * @return string
4819 public function blocks($region, $classes = array(), $tag = 'aside') {
4820 // Computer says no blocks.
4821 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4822 return '';
4826 * Does nothing. The maintenance renderer cannot produce blocks.
4828 * @param string $region
4829 * @return string
4831 public function blocks_for_region($region) {
4832 // Computer says no blocks for region.
4833 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4834 return '';
4838 * Does nothing. The maintenance renderer cannot produce a course content header.
4840 * @param bool $onlyifnotcalledbefore
4841 * @return string
4843 public function course_content_header($onlyifnotcalledbefore = false) {
4844 // Computer says no course content header.
4845 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4846 return '';
4850 * Does nothing. The maintenance renderer cannot produce a course content footer.
4852 * @param bool $onlyifnotcalledbefore
4853 * @return string
4855 public function course_content_footer($onlyifnotcalledbefore = false) {
4856 // Computer says no course content footer.
4857 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4858 return '';
4862 * Does nothing. The maintenance renderer cannot produce a course header.
4864 * @return string
4866 public function course_header() {
4867 // Computer says no course header.
4868 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4869 return '';
4873 * Does nothing. The maintenance renderer cannot produce a course footer.
4875 * @return string
4877 public function course_footer() {
4878 // Computer says no course footer.
4879 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4880 return '';
4884 * Does nothing. The maintenance renderer cannot produce a custom menu.
4886 * @param string $custommenuitems
4887 * @return string
4889 public function custom_menu($custommenuitems = '') {
4890 // Computer says no custom menu.
4891 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4892 return '';
4896 * Does nothing. The maintenance renderer cannot produce a file picker.
4898 * @param array $options
4899 * @return string
4901 public function file_picker($options) {
4902 // Computer says no file picker.
4903 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4904 return '';
4908 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
4910 * @param array $dir
4911 * @return string
4913 public function htmllize_file_tree($dir) {
4914 // Hell no we don't want no htmllized file tree.
4915 // Also why on earth is this function on the core renderer???
4916 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4917 return '';
4922 * Overridden confirm message for upgrades.
4924 * @param string $message The question to ask the user
4925 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
4926 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
4927 * @return string HTML fragment
4929 public function confirm($message, $continue, $cancel) {
4930 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
4931 // from any previous version of Moodle).
4932 if ($continue instanceof single_button) {
4933 $continue->primary = true;
4934 } else if (is_string($continue)) {
4935 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
4936 } else if ($continue instanceof moodle_url) {
4937 $continue = new single_button($continue, get_string('continue'), 'post', true);
4938 } else {
4939 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
4940 ' (string/moodle_url) or a single_button instance.');
4943 if ($cancel instanceof single_button) {
4944 $output = '';
4945 } else if (is_string($cancel)) {
4946 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
4947 } else if ($cancel instanceof moodle_url) {
4948 $cancel = new single_button($cancel, get_string('cancel'), 'get');
4949 } else {
4950 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
4951 ' (string/moodle_url) or a single_button instance.');
4954 $output = $this->box_start('generalbox', 'notice');
4955 $output .= html_writer::tag('h4', get_string('confirm'));
4956 $output .= html_writer::tag('p', $message);
4957 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
4958 $output .= $this->box_end();
4959 return $output;
4963 * Does nothing. The maintenance renderer does not support JS.
4965 * @param block_contents $bc
4967 public function init_block_hider_js(block_contents $bc) {
4968 // Computer says no JavaScript.
4969 // Do nothing, ridiculous method.
4973 * Does nothing. The maintenance renderer cannot produce language menus.
4975 * @return string
4977 public function lang_menu() {
4978 // Computer says no lang menu.
4979 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4980 return '';
4984 * Does nothing. The maintenance renderer has no need for login information.
4986 * @param null $withlinks
4987 * @return string
4989 public function login_info($withlinks = null) {
4990 // Computer says no login info.
4991 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4992 return '';
4996 * Does nothing. The maintenance renderer cannot produce user pictures.
4998 * @param stdClass $user
4999 * @param array $options
5000 * @return string
5002 public function user_picture(stdClass $user, array $options = null) {
5003 // Computer says no user pictures.
5004 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5005 return '';