2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
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
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') ||
die();
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
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
65 * @var string The requested rendering target.
70 * @var Mustache_Engine $mustache The mustache template compiler
75 * Return an instance of the mustache class.
78 * @return Mustache_Engine
80 protected function get_mustache() {
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) {
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 \core\output\
mustache_engine(array(
124 'cache' => $cachedir,
127 'helpers' => $helpers,
128 'pragmas' => [Mustache_Engine
::PRAGMA_BLOCKS
],
129 // Don't allow the JavaScript helper to be executed from within another
130 // helper. If it's allowed it can be used by users to inject malicious
132 'blacklistednestedhelpers' => ['js'],
133 // Disable lambda rendering - content in helpers is already rendered, no need to render it again.
134 'disable_lambda_rendering' => true,
139 return $this->mustache
;
146 * The constructor takes two arguments. The first is the page that the renderer
147 * has been created to assist with, and the second is the target.
148 * The target is an additional identifier that can be used to load different
149 * renderers for different options.
151 * @param moodle_page $page the page we are doing output for.
152 * @param string $target one of rendering target constants
154 public function __construct(moodle_page
$page, $target) {
155 $this->opencontainers
= $page->opencontainers
;
157 $this->target
= $target;
161 * Renders a template by name with the given context.
163 * The provided data needs to be array/stdClass made up of only simple types.
164 * Simple types are array,stdClass,bool,int,float,string
167 * @param array|stdClass $context Context containing data for the template.
168 * @return string|boolean
170 public function render_from_template($templatename, $context) {
171 static $templatecache = array();
172 $mustache = $this->get_mustache();
175 // Grab a copy of the existing helper to be restored later.
176 $uniqidhelper = $mustache->getHelper('uniqid');
177 } catch (Mustache_Exception_UnknownHelperException
$e) {
178 // Helper doesn't exist.
179 $uniqidhelper = null;
182 // Provide 1 random value that will not change within a template
183 // but will be different from template to template. This is useful for
184 // e.g. aria attributes that only work with id attributes and must be
186 $mustache->addHelper('uniqid', new \core\output\
mustache_uniqid_helper());
187 if (isset($templatecache[$templatename])) {
188 $template = $templatecache[$templatename];
191 $template = $mustache->loadTemplate($templatename);
192 $templatecache[$templatename] = $template;
193 } catch (Mustache_Exception_UnknownTemplateException
$e) {
194 throw new moodle_exception('Unknown template: ' . $templatename);
198 $renderedtemplate = trim($template->render($context));
200 // If we had an existing uniqid helper then we need to restore it to allow
201 // handle nested calls of render_from_template.
203 $mustache->addHelper('uniqid', $uniqidhelper);
206 return $renderedtemplate;
211 * Returns rendered widget.
213 * The provided widget needs to be an object that extends the renderable
215 * If will then be rendered by a method based upon the classname for the widget.
216 * For instance a widget of class `crazywidget` will be rendered by a protected
217 * render_crazywidget method of this renderer.
218 * If no render_crazywidget method exists and crazywidget implements templatable,
219 * look for the 'crazywidget' template in the same component and render that.
221 * @param renderable $widget instance with renderable interface
224 public function render(renderable
$widget) {
225 $classparts = explode('\\', get_class($widget));
227 $classname = array_pop($classparts);
228 // Remove _renderable suffixes
229 $classname = preg_replace('/_renderable$/', '', $classname);
231 $rendermethod = 'render_'.$classname;
232 if (method_exists($this, $rendermethod)) {
233 return $this->$rendermethod($widget);
235 if ($widget instanceof templatable
) {
236 $component = array_shift($classparts);
240 $template = $component . '/' . $classname;
241 $context = $widget->export_for_template($this);
242 return $this->render_from_template($template, $context);
244 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
248 * Adds a JS action for the element with the provided id.
250 * This method adds a JS event for the provided component action to the page
251 * and then returns the id that the event has been attached to.
252 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
254 * @param component_action $action
256 * @return string id of element, either original submitted or random new if not supplied
258 public function add_action_handler(component_action
$action, $id = null) {
260 $id = html_writer
::random_id($action->event
);
262 $this->page
->requires
->event_handler("#$id", $action->event
, $action->jsfunction
, $action->jsfunctionargs
);
267 * Returns true is output has already started, and false if not.
269 * @return boolean true if the header has been printed.
271 public function has_started() {
272 return $this->page
->state
>= moodle_page
::STATE_IN_BODY
;
276 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
278 * @param mixed $classes Space-separated string or array of classes
279 * @return string HTML class attribute value
281 public static function prepare_classes($classes) {
282 if (is_array($classes)) {
283 return implode(' ', array_unique($classes));
289 * Return the direct URL for an image from the pix folder.
291 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
293 * @deprecated since Moodle 3.3
294 * @param string $imagename the name of the icon.
295 * @param string $component specification of one plugin like in get_string()
298 public function pix_url($imagename, $component = 'moodle') {
299 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER
);
300 return $this->page
->theme
->image_url($imagename, $component);
304 * Return the moodle_url for an image.
306 * The exact image location and extension is determined
307 * automatically by searching for gif|png|jpg|jpeg, please
308 * note there can not be diferent images with the different
309 * extension. The imagename is for historical reasons
310 * a relative path name, it may be changed later for core
311 * images. It is recommended to not use subdirectories
312 * in plugin and theme pix directories.
314 * There are three types of images:
315 * 1/ theme images - stored in theme/mytheme/pix/,
316 * use component 'theme'
317 * 2/ core images - stored in /pix/,
318 * overridden via theme/mytheme/pix_core/
319 * 3/ plugin images - stored in mod/mymodule/pix,
320 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
321 * example: image_url('comment', 'mod_glossary')
323 * @param string $imagename the pathname of the image
324 * @param string $component full plugin name (aka component) or 'theme'
327 public function image_url($imagename, $component = 'moodle') {
328 return $this->page
->theme
->image_url($imagename, $component);
332 * Return the site's logo URL, if any.
334 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
335 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
336 * @return moodle_url|false
338 public function get_logo_url($maxwidth = null, $maxheight = 200) {
340 $logo = get_config('core_admin', 'logo');
345 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
346 // It's not worth the overhead of detecting and serving 2 different images based on the device.
348 // Hide the requested size in the file path.
349 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
351 // Use $CFG->themerev to prevent browser caching when the file changes.
352 return moodle_url
::make_pluginfile_url(context_system
::instance()->id
, 'core_admin', 'logo', $filepath,
353 theme_get_revision(), $logo);
357 * Return the site's compact logo URL, if any.
359 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
360 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
361 * @return moodle_url|false
363 public function get_compact_logo_url($maxwidth = 300, $maxheight = 300) {
365 $logo = get_config('core_admin', 'logocompact');
370 // Hide the requested size in the file path.
371 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
373 // Use $CFG->themerev to prevent browser caching when the file changes.
374 return moodle_url
::make_pluginfile_url(context_system
::instance()->id
, 'core_admin', 'logocompact', $filepath,
375 theme_get_revision(), $logo);
379 * Whether we should display the logo in the navbar.
381 * We will when there are no main logos, and we have compact logo.
385 public function should_display_navbar_logo() {
386 $logo = $this->get_compact_logo_url();
387 return !empty($logo) && !$this->should_display_main_logo();
391 * Whether we should display the main logo.
393 * @param int $headinglevel The heading level we want to check against.
396 public function should_display_main_logo($headinglevel = 1) {
398 // Only render the logo if we're on the front page or login page and the we have a logo.
399 $logo = $this->get_logo_url();
400 if ($headinglevel == 1 && !empty($logo)) {
401 if ($this->page
->pagelayout
== 'frontpage' ||
$this->page
->pagelayout
== 'login') {
413 * Basis for all plugin renderers.
415 * @copyright Petr Skoda (skodak)
416 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
421 class plugin_renderer_base
extends renderer_base
{
424 * @var renderer_base|core_renderer A reference to the current renderer.
425 * The renderer provided here will be determined by the page but will in 90%
426 * of cases by the {@link core_renderer}
431 * Constructor method, calls the parent constructor
433 * @param moodle_page $page
434 * @param string $target one of rendering target constants
436 public function __construct(moodle_page
$page, $target) {
437 if (empty($target) && $page->pagelayout
=== 'maintenance') {
438 // If the page is using the maintenance layout then we're going to force the target to maintenance.
439 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
440 // unavailable for this page layout.
441 $target = RENDERER_TARGET_MAINTENANCE
;
443 $this->output
= $page->get_renderer('core', null, $target);
444 parent
::__construct($page, $target);
448 * Renders the provided widget and returns the HTML to display it.
450 * @param renderable $widget instance with renderable interface
453 public function render(renderable
$widget) {
454 $classname = get_class($widget);
456 $classname = preg_replace('/^.*\\\/', '', $classname);
457 // Keep a copy at this point, we may need to look for a deprecated method.
458 $deprecatedmethod = 'render_'.$classname;
459 // Remove _renderable suffixes
460 $classname = preg_replace('/_renderable$/', '', $classname);
462 $rendermethod = 'render_'.$classname;
463 if (method_exists($this, $rendermethod)) {
464 return $this->$rendermethod($widget);
466 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
467 // This is exactly where we don't want to be.
468 // If you have arrived here you have a renderable component within your plugin that has the name
469 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
470 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
471 // and the _renderable suffix now gets removed when looking for a render method.
472 // You need to change your renderers render_blah_renderable to render_blah.
473 // Until you do this it will not be possible for a theme to override the renderer to override your method.
474 // Please do it ASAP.
475 static $debugged = array();
476 if (!isset($debugged[$deprecatedmethod])) {
477 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
478 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER
);
479 $debugged[$deprecatedmethod] = true;
481 return $this->$deprecatedmethod($widget);
483 // pass to core renderer if method not found here
484 return $this->output
->render($widget);
488 * Magic method used to pass calls otherwise meant for the standard renderer
489 * to it to ensure we don't go causing unnecessary grief.
491 * @param string $method
492 * @param array $arguments
495 public function __call($method, $arguments) {
496 if (method_exists('renderer_base', $method)) {
497 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
499 if (method_exists($this->output
, $method)) {
500 return call_user_func_array(array($this->output
, $method), $arguments);
502 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
509 * The standard implementation of the core_renderer interface.
511 * @copyright 2009 Tim Hunt
512 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
517 class core_renderer
extends renderer_base
{
519 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
520 * in layout files instead.
522 * @var string used in {@link core_renderer::header()}.
524 const MAIN_CONTENT_TOKEN
= '[MAIN CONTENT GOES HERE]';
527 * @var string Used to pass information from {@link core_renderer::doctype()} to
528 * {@link core_renderer::standard_head_html()}.
530 protected $contenttype;
533 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
534 * with {@link core_renderer::header()}.
536 protected $metarefreshtag = '';
539 * @var string Unique token for the closing HTML
541 protected $unique_end_html_token;
544 * @var string Unique token for performance information
546 protected $unique_performance_info_token;
549 * @var string Unique token for the main content.
551 protected $unique_main_content_token;
553 /** @var custom_menu_item language The language menu if created */
554 protected $language = null;
559 * @param moodle_page $page the page we are doing output for.
560 * @param string $target one of rendering target constants
562 public function __construct(moodle_page
$page, $target) {
563 $this->opencontainers
= $page->opencontainers
;
565 $this->target
= $target;
567 $this->unique_end_html_token
= '%%ENDHTML-'.sesskey().'%%';
568 $this->unique_performance_info_token
= '%%PERFORMANCEINFO-'.sesskey().'%%';
569 $this->unique_main_content_token
= '[MAIN CONTENT GOES HERE - '.sesskey().']';
573 * Get the DOCTYPE declaration that should be used with this page. Designed to
574 * be called in theme layout.php files.
576 * @return string the DOCTYPE declaration that should be used.
578 public function doctype() {
579 if ($this->page
->theme
->doctype
=== 'html5') {
580 $this->contenttype
= 'text/html; charset=utf-8';
581 return "<!DOCTYPE html>\n";
583 } else if ($this->page
->theme
->doctype
=== 'xhtml5') {
584 $this->contenttype
= 'application/xhtml+xml; charset=utf-8';
585 return "<!DOCTYPE html>\n";
589 $this->contenttype
= 'text/html; charset=utf-8';
590 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
595 * The attributes that should be added to the <html> tag. Designed to
596 * be called in theme layout.php files.
598 * @return string HTML fragment.
600 public function htmlattributes() {
601 $return = get_html_lang(true);
602 $attributes = array();
603 if ($this->page
->theme
->doctype
!== 'html5') {
604 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
607 // Give plugins an opportunity to add things like xml namespaces to the html element.
608 // This function should return an array of html attribute names => values.
609 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
610 foreach ($pluginswithfunction as $plugins) {
611 foreach ($plugins as $function) {
612 $newattrs = $function();
613 unset($newattrs['dir']);
614 unset($newattrs['lang']);
615 unset($newattrs['xmlns']);
616 unset($newattrs['xml:lang']);
617 $attributes +
= $newattrs;
621 foreach ($attributes as $key => $val) {
623 $return .= " $key=\"$val\"";
630 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
631 * that should be included in the <head> tag. Designed to be called in theme
634 * @return string HTML fragment.
636 public function standard_head_html() {
637 global $CFG, $SESSION, $SITE;
639 // Before we output any content, we need to ensure that certain
640 // page components are set up.
642 // Blocks must be set up early as they may require javascript which
643 // has to be included in the page header before output is created.
644 foreach ($this->page
->blocks
->get_regions() as $region) {
645 $this->page
->blocks
->ensure_content_created($region, $this);
650 // Give plugins an opportunity to add any head elements. The callback
651 // must always return a string containing valid html head content.
652 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
653 foreach ($pluginswithfunction as $plugins) {
654 foreach ($plugins as $function) {
655 $output .= $function();
659 // Allow a url_rewrite plugin to setup any dynamic head content.
660 if (isset($CFG->urlrewriteclass
) && !isset($CFG->upgraderunning
)) {
661 $class = $CFG->urlrewriteclass
;
662 $output .= $class::html_head_setup();
665 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
666 $output .= '<meta name="keywords" content="moodle, ' . $this->page
->title
. '" />' . "\n";
667 // This is only set by the {@link redirect()} method
668 $output .= $this->metarefreshtag
;
670 // Check if a periodic refresh delay has been set and make sure we arn't
671 // already meta refreshing
672 if ($this->metarefreshtag
=='' && $this->page
->periodicrefreshdelay
!==null) {
673 $output .= '<meta http-equiv="refresh" content="'.$this->page
->periodicrefreshdelay
.';url='.$this->page
->url
->out().'" />';
676 // Set up help link popups for all links with the helptooltip class
677 $this->page
->requires
->js_init_call('M.util.help_popups.setup');
679 $focus = $this->page
->focuscontrol
;
680 if (!empty($focus)) {
681 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
682 // This is a horrifically bad way to handle focus but it is passed in
683 // through messy formslib::moodleform
684 $this->page
->requires
->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
685 } else if (strpos($focus, '.')!==false) {
686 // Old style of focus, bad way to do it
687 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
);
688 $this->page
->requires
->js_function_call('old_onload_focus', explode('.', $focus, 2));
690 // Focus element with given id
691 $this->page
->requires
->js_function_call('focuscontrol', array($focus));
695 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
696 // any other custom CSS can not be overridden via themes and is highly discouraged
697 $urls = $this->page
->theme
->css_urls($this->page
);
698 foreach ($urls as $url) {
699 $this->page
->requires
->css_theme($url);
702 // Get the theme javascript head and footer
703 if ($jsurl = $this->page
->theme
->javascript_url(true)) {
704 $this->page
->requires
->js($jsurl, true);
706 if ($jsurl = $this->page
->theme
->javascript_url(false)) {
707 $this->page
->requires
->js($jsurl);
710 // Get any HTML from the page_requirements_manager.
711 $output .= $this->page
->requires
->get_head_code($this->page
, $this);
713 // List alternate versions.
714 foreach ($this->page
->alternateversions
as $type => $alt) {
715 $output .= html_writer
::empty_tag('link', array('rel' => 'alternate',
716 'type' => $type, 'title' => $alt->title
, 'href' => $alt->url
));
719 // Add noindex tag if relevant page and setting applied.
720 $allowindexing = isset($CFG->allowindexing
) ?
$CFG->allowindexing
: 0;
721 $loginpages = array('login-index', 'login-signup');
722 if ($allowindexing == 2 ||
($allowindexing == 0 && in_array($this->page
->pagetype
, $loginpages))) {
723 if (!isset($CFG->additionalhtmlhead
)) {
724 $CFG->additionalhtmlhead
= '';
726 $CFG->additionalhtmlhead
.= '<meta name="robots" content="noindex" />';
729 if (!empty($CFG->additionalhtmlhead
)) {
730 $output .= "\n".$CFG->additionalhtmlhead
;
733 if ($this->page
->pagelayout
== 'frontpage') {
734 $summary = s(strip_tags(format_text($SITE->summary
, FORMAT_HTML
)));
735 if (!empty($summary)) {
736 $output .= "<meta name=\"description\" content=\"$summary\" />\n";
744 * The standard tags (typically skip links) that should be output just inside
745 * the start of the <body> tag. Designed to be called in theme layout.php files.
747 * @return string HTML fragment.
749 public function standard_top_of_body_html() {
751 $output = $this->page
->requires
->get_top_of_body_code($this);
752 if ($this->page
->pagelayout
!== 'embedded' && !empty($CFG->additionalhtmltopofbody
)) {
753 $output .= "\n".$CFG->additionalhtmltopofbody
;
756 // Give subsystems an opportunity to inject extra html content. The callback
757 // must always return a string containing valid html.
758 foreach (\core_component
::get_core_subsystems() as $name => $path) {
760 $output .= component_callback($name, 'before_standard_top_of_body_html', [], '');
764 // Give plugins an opportunity to inject extra html content. The callback
765 // must always return a string containing valid html.
766 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
767 foreach ($pluginswithfunction as $plugins) {
768 foreach ($plugins as $function) {
769 $output .= $function();
773 $output .= $this->maintenance_warning();
779 * Scheduled maintenance warning message.
781 * Note: This is a nasty hack to display maintenance notice, this should be moved
782 * to some general notification area once we have it.
786 public function maintenance_warning() {
790 if (isset($CFG->maintenance_later
) and $CFG->maintenance_later
> time()) {
791 $timeleft = $CFG->maintenance_later
- time();
792 // If timeleft less than 30 sec, set the class on block to error to highlight.
793 $errorclass = ($timeleft < 30) ?
'alert-error alert-danger' : 'alert-warning';
794 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-a-1 alert');
796 $a->hour
= (int)($timeleft / 3600);
797 $a->min
= (int)(($timeleft / 60) %
60);
798 $a->sec
= (int)($timeleft %
60);
800 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
802 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
805 $output .= $this->box_end();
806 $this->page
->requires
->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
807 array(array('timeleftinsec' => $timeleft)));
808 $this->page
->requires
->strings_for_js(
809 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
816 * The standard tags (typically performance information and validation links,
817 * if we are in developer debug mode) that should be output in the footer area
818 * of the page. Designed to be called in theme layout.php files.
820 * @return string HTML fragment.
822 public function standard_footer_html() {
823 global $CFG, $SCRIPT;
826 if (during_initial_install()) {
827 // Debugging info can not work before install is finished,
828 // in any case we do not want any links during installation!
832 // Give plugins an opportunity to add any footer elements.
833 // The callback must always return a string containing valid html footer content.
834 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
835 foreach ($pluginswithfunction as $plugins) {
836 foreach ($plugins as $function) {
837 $output .= $function();
841 if (core_userfeedback
::can_give_feedback()) {
842 $output .= html_writer
::div(
843 $this->render_from_template('core/userfeedback_footer_link', ['url' => core_userfeedback
::make_link()->out(false)])
847 // This function is normally called from a layout.php file in {@link core_renderer::header()}
848 // but some of the content won't be known until later, so we return a placeholder
849 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
850 $output .= $this->unique_performance_info_token
;
851 if ($this->page
->devicetypeinuse
== 'legacy') {
852 // The legacy theme is in use print the notification
853 $output .= html_writer
::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
856 // Get links to switch device types (only shown for users not on a default device)
857 $output .= $this->theme_switch_links();
859 if (!empty($CFG->debugpageinfo
)) {
860 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
861 $this->page
->debug_summary()) . '</div>';
863 if (debugging(null, DEBUG_DEVELOPER
) and has_capability('moodle/site:config', context_system
::instance())) { // Only in developer mode
864 // Add link to profiling report if necessary
865 if (function_exists('profiling_is_running') && profiling_is_running()) {
866 $txt = get_string('profiledscript', 'admin');
867 $title = get_string('profiledscriptview', 'admin');
868 $url = $CFG->wwwroot
. '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
869 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
870 $output .= '<div class="profilingfooter">' . $link . '</div>';
872 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
873 'sesskey' => sesskey(), 'returnurl' => $this->page
->url
->out_as_local_url(false)));
874 $output .= '<div class="purgecaches">' .
875 html_writer
::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
877 if (!empty($CFG->debugvalidators
)) {
878 $siteurl = qualified_me();
879 $nuurl = new moodle_url('https://validator.w3.org/nu/', ['doc' => $siteurl, 'showsource' => 'yes']);
880 $waveurl = new moodle_url('https://wave.webaim.org/report#/' . urlencode($siteurl));
882 html_writer
::link($nuurl, get_string('validatehtml')),
883 html_writer
::link($waveurl, get_string('wcagcheck'))
885 $validatorlinkslist = html_writer
::alist($validatorlinks, ['class' => 'list-unstyled ml-1']);
886 $output .= html_writer
::div($validatorlinkslist, 'validators');
892 * Returns standard main content placeholder.
893 * Designed to be called in theme layout.php files.
895 * @return string HTML fragment.
897 public function main_content() {
898 // This is here because it is the only place we can inject the "main" role over the entire main content area
899 // without requiring all theme's to manually do it, and without creating yet another thing people need to
900 // remember in the theme.
901 // This is an unfortunate hack. DO NO EVER add anything more here.
902 // DO NOT add classes.
904 return '<div role="main">'.$this->unique_main_content_token
.'</div>';
908 * Returns standard navigation between activities in a course.
910 * @return string the navigation HTML.
912 public function activity_navigation() {
913 // First we should check if we want to add navigation.
914 $context = $this->page
->context
;
915 if (($this->page
->pagelayout
!== 'incourse' && $this->page
->pagelayout
!== 'frametop')
916 ||
$context->contextlevel
!= CONTEXT_MODULE
) {
920 // If the activity is in stealth mode, show no links.
921 if ($this->page
->cm
->is_stealth()) {
925 // Get a list of all the activities in the course.
926 $course = $this->page
->cm
->get_course();
927 $modules = get_fast_modinfo($course->id
)->get_cms();
929 // Put the modules into an array in order by the position they are shown in the course.
932 foreach ($modules as $module) {
933 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
934 if (!$module->uservisible ||
$module->is_stealth() ||
empty($module->url
)) {
937 $mods[$module->id
] = $module;
939 // No need to add the current module to the list for the activity dropdown menu.
940 if ($module->id
== $this->page
->cm
->id
) {
944 $modname = $module->get_formatted_name();
945 // Display the hidden text if necessary.
946 if (!$module->visible
) {
947 $modname .= ' ' . get_string('hiddenwithbrackets');
950 $linkurl = new moodle_url($module->url
, array('forceview' => 1));
951 // Add module URL (as key) and name (as value) to the activity list array.
952 $activitylist[$linkurl->out(false)] = $modname;
955 $nummods = count($mods);
957 // If there is only one mod then do nothing.
962 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
963 $modids = array_keys($mods);
965 // Get the position in the array of the course module we are viewing.
966 $position = array_search($this->page
->cm
->id
, $modids);
971 // Check if we have a previous mod to show.
973 $prevmod = $mods[$modids[$position - 1]];
976 // Check if we have a next mod to show.
977 if ($position < ($nummods - 1)) {
978 $nextmod = $mods[$modids[$position +
1]];
981 $activitynav = new \core_course\output\activity_navigation
($prevmod, $nextmod, $activitylist);
982 $renderer = $this->page
->get_renderer('core', 'course');
983 return $renderer->render($activitynav);
987 * The standard tags (typically script tags that are not needed earlier) that
988 * should be output after everything else. Designed to be called in theme layout.php files.
990 * @return string HTML fragment.
992 public function standard_end_of_body_html() {
995 // This function is normally called from a layout.php file in {@link core_renderer::header()}
996 // but some of the content won't be known until later, so we return a placeholder
997 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
999 if ($this->page
->pagelayout
!== 'embedded' && !empty($CFG->additionalhtmlfooter
)) {
1000 $output .= "\n".$CFG->additionalhtmlfooter
;
1002 $output .= $this->unique_end_html_token
;
1007 * The standard HTML that should be output just before the <footer> tag.
1008 * Designed to be called in theme layout.php files.
1010 * @return string HTML fragment.
1012 public function standard_after_main_region_html() {
1015 if ($this->page
->pagelayout
!== 'embedded' && !empty($CFG->additionalhtmlbottomofbody
)) {
1016 $output .= "\n".$CFG->additionalhtmlbottomofbody
;
1019 // Give subsystems an opportunity to inject extra html content. The callback
1020 // must always return a string containing valid html.
1021 foreach (\core_component
::get_core_subsystems() as $name => $path) {
1023 $output .= component_callback($name, 'standard_after_main_region_html', [], '');
1027 // Give plugins an opportunity to inject extra html content. The callback
1028 // must always return a string containing valid html.
1029 $pluginswithfunction = get_plugins_with_function('standard_after_main_region_html', 'lib.php');
1030 foreach ($pluginswithfunction as $plugins) {
1031 foreach ($plugins as $function) {
1032 $output .= $function();
1040 * Return the standard string that says whether you are logged in (and switched
1041 * roles/logged in as another user).
1042 * @param bool $withlinks if false, then don't include any links in the HTML produced.
1043 * If not set, the default is the nologinlinks option from the theme config.php file,
1044 * and if that is not set, then links are included.
1045 * @return string HTML fragment.
1047 public function login_info($withlinks = null) {
1048 global $USER, $CFG, $DB, $SESSION;
1050 if (during_initial_install()) {
1054 if (is_null($withlinks)) {
1055 $withlinks = empty($this->page
->layout_options
['nologinlinks']);
1058 $course = $this->page
->course
;
1059 if (\core\session\manager
::is_loggedinas()) {
1060 $realuser = \core\session\manager
::get_realuser();
1061 $fullname = fullname($realuser);
1063 $loginastitle = get_string('loginas');
1064 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&sesskey=".sesskey()."\"";
1065 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
1067 $realuserinfo = " [$fullname] ";
1073 $loginpage = $this->is_login_page();
1074 $loginurl = get_login_url();
1076 if (empty($course->id
)) {
1077 // $course->id is not defined during installation
1079 } else if (isloggedin()) {
1080 $context = context_course
::instance($course->id
);
1082 $fullname = fullname($USER);
1083 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
1085 $linktitle = get_string('viewprofile');
1086 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
1088 $username = $fullname;
1090 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid
))) {
1092 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1094 $username .= " from {$idprovider->name}";
1097 if (isguestuser()) {
1098 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1099 if (!$loginpage && $withlinks) {
1100 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1102 } else if (is_role_switched($course->id
)) { // Has switched roles
1104 if ($role = $DB->get_record('role', array('id'=>$USER->access
['rsw'][$context->path
]))) {
1105 $rolename = ': '.role_get_name($role, $context);
1107 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1109 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id
,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page
->url
->out_as_local_url(false)));
1110 $loggedinas .= ' ('.html_writer
::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1113 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1115 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1119 $loggedinas = get_string('loggedinnot', 'moodle');
1120 if (!$loginpage && $withlinks) {
1121 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1125 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1127 if (isset($SESSION->justloggedin
)) {
1128 unset($SESSION->justloggedin
);
1129 if (!empty($CFG->displayloginfailures
)) {
1130 if (!isguestuser()) {
1131 // Include this file only when required.
1132 require_once($CFG->dirroot
. '/user/lib.php');
1133 if ($count = user_count_login_failures($USER)) {
1134 $loggedinas .= '<div class="loginfailures">';
1135 $a = new stdClass();
1136 $a->attempts
= $count;
1137 $loggedinas .= get_string('failedloginattempts', '', $a);
1138 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system
::instance())) {
1139 $loggedinas .= ' ('.html_writer
::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1140 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1142 $loggedinas .= '</div>';
1152 * Check whether the current page is a login page.
1157 protected function is_login_page() {
1158 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1159 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1160 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1162 $this->page
->url
->out_as_local_url(false, array()),
1165 '/login/forgot_password.php',
1171 * Return the 'back' link that normally appears in the footer.
1173 * @return string HTML fragment.
1175 public function home_link() {
1178 if ($this->page
->pagetype
== 'site-index') {
1179 // Special case for site home page - please do not remove
1180 return '<div class="sitelink">' .
1181 '<a title="Moodle" class="d-inline-block aalink" href="http://moodle.org/">' .
1182 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1184 } else if (!empty($CFG->target_release
) && $CFG->target_release
!= $CFG->release
) {
1185 // Special case for during install/upgrade.
1186 return '<div class="sitelink">'.
1187 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1188 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1190 } else if ($this->page
->course
->id
== $SITE->id ||
strpos($this->page
->pagetype
, 'course-view') === 0) {
1191 return '<div class="homelink"><a href="' . $CFG->wwwroot
. '/">' .
1192 get_string('home') . '</a></div>';
1195 return '<div class="homelink"><a href="' . $CFG->wwwroot
. '/course/view.php?id=' . $this->page
->course
->id
. '">' .
1196 format_string($this->page
->course
->shortname
, true, array('context' => $this->page
->context
)) . '</a></div>';
1201 * Redirects the user by any means possible given the current state
1203 * This function should not be called directly, it should always be called using
1204 * the redirect function in lib/weblib.php
1206 * The redirect function should really only be called before page output has started
1207 * however it will allow itself to be called during the state STATE_IN_BODY
1209 * @param string $encodedurl The URL to send to encoded if required
1210 * @param string $message The message to display to the user if any
1211 * @param int $delay The delay before redirecting a user, if $message has been
1212 * set this is a requirement and defaults to 3, set to 0 no delay
1213 * @param boolean $debugdisableredirect this redirect has been disabled for
1214 * debugging purposes. Display a message that explains, and don't
1215 * trigger the redirect.
1216 * @param string $messagetype The type of notification to show the message in.
1217 * See constants on \core\output\notification.
1218 * @return string The HTML to display to the user before dying, may contain
1219 * meta refresh, javascript refresh, and may have set header redirects
1221 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1222 $messagetype = \core\output\notification
::NOTIFY_INFO
) {
1224 $url = str_replace('&', '&', $encodedurl);
1226 switch ($this->page
->state
) {
1227 case moodle_page
::STATE_BEFORE_HEADER
:
1228 // No output yet it is safe to delivery the full arsenal of redirect methods
1229 if (!$debugdisableredirect) {
1230 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1231 $this->metarefreshtag
= '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1232 $this->page
->requires
->js_function_call('document.location.replace', array($url), false, ($delay +
3));
1234 $output = $this->header();
1236 case moodle_page
::STATE_PRINTING_HEADER
:
1237 // We should hopefully never get here
1238 throw new coding_exception('You cannot redirect while printing the page header');
1240 case moodle_page
::STATE_IN_BODY
:
1241 // We really shouldn't be here but we can deal with this
1242 debugging("You should really redirect before you start page output");
1243 if (!$debugdisableredirect) {
1244 $this->page
->requires
->js_function_call('document.location.replace', array($url), false, $delay);
1246 $output = $this->opencontainers
->pop_all_but_last();
1248 case moodle_page
::STATE_DONE
:
1249 // Too late to be calling redirect now
1250 throw new coding_exception('You cannot redirect after the entire page has been generated');
1253 $output .= $this->notification($message, $messagetype);
1254 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1255 if ($debugdisableredirect) {
1256 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1258 $output .= $this->footer();
1263 * Start output by sending the HTTP headers, and printing the HTML <head>
1264 * and the start of the <body>.
1266 * To control what is printed, you should set properties on $PAGE.
1268 * @return string HTML that you must output this, preferably immediately.
1270 public function header() {
1271 global $USER, $CFG, $SESSION;
1273 // Give plugins an opportunity touch things before the http headers are sent
1274 // such as adding additional headers. The return value is ignored.
1275 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1276 foreach ($pluginswithfunction as $plugins) {
1277 foreach ($plugins as $function) {
1282 if (\core\session\manager
::is_loggedinas()) {
1283 $this->page
->add_body_class('userloggedinas');
1286 if (isset($SESSION->justloggedin
) && !empty($CFG->displayloginfailures
)) {
1287 require_once($CFG->dirroot
. '/user/lib.php');
1288 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1289 if ($count = user_count_login_failures($USER, false)) {
1290 $this->page
->add_body_class('loginfailures');
1294 // If the user is logged in, and we're not in initial install,
1295 // check to see if the user is role-switched and add the appropriate
1296 // CSS class to the body element.
1297 if (!during_initial_install() && isloggedin() && is_role_switched($this->page
->course
->id
)) {
1298 $this->page
->add_body_class('userswitchedrole');
1301 // Give themes a chance to init/alter the page object.
1302 $this->page
->theme
->init_page($this->page
);
1304 $this->page
->set_state(moodle_page
::STATE_PRINTING_HEADER
);
1306 // Find the appropriate page layout file, based on $this->page->pagelayout.
1307 $layoutfile = $this->page
->theme
->layout_file($this->page
->pagelayout
);
1308 // Render the layout using the layout file.
1309 $rendered = $this->render_page_layout($layoutfile);
1311 // Slice the rendered output into header and footer.
1312 $cutpos = strpos($rendered, $this->unique_main_content_token
);
1313 if ($cutpos === false) {
1314 $cutpos = strpos($rendered, self
::MAIN_CONTENT_TOKEN
);
1315 $token = self
::MAIN_CONTENT_TOKEN
;
1317 $token = $this->unique_main_content_token
;
1320 if ($cutpos === false) {
1321 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.');
1323 $header = substr($rendered, 0, $cutpos);
1324 $footer = substr($rendered, $cutpos +
strlen($token));
1326 if (empty($this->contenttype
)) {
1327 debugging('The page layout file did not call $OUTPUT->doctype()');
1328 $header = $this->doctype() . $header;
1331 // If this theme version is below 2.4 release and this is a course view page
1332 if ((!isset($this->page
->theme
->settings
->version
) ||
$this->page
->theme
->settings
->version
< 2012101500) &&
1333 $this->page
->pagelayout
=== 'course' && $this->page
->url
->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE
)) {
1334 // check if course content header/footer have not been output during render of theme layout
1335 $coursecontentheader = $this->course_content_header(true);
1336 $coursecontentfooter = $this->course_content_footer(true);
1337 if (!empty($coursecontentheader)) {
1338 // display debug message and add header and footer right above and below main content
1339 // Please note that course header and footer (to be displayed above and below the whole page)
1340 // are not displayed in this case at all.
1341 // Besides the content header and footer are not displayed on any other course page
1342 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
);
1343 $header .= $coursecontentheader;
1344 $footer = $coursecontentfooter. $footer;
1348 send_headers($this->contenttype
, $this->page
->cacheable
);
1350 $this->opencontainers
->push('header/footer', $footer);
1351 $this->page
->set_state(moodle_page
::STATE_IN_BODY
);
1353 return $header . $this->skip_link_target('maincontent');
1357 * Renders and outputs the page layout file.
1359 * This is done by preparing the normal globals available to a script, and
1360 * then including the layout file provided by the current theme for the
1363 * @param string $layoutfile The name of the layout file
1364 * @return string HTML code
1366 protected function render_page_layout($layoutfile) {
1367 global $CFG, $SITE, $USER;
1368 // The next lines are a bit tricky. The point is, here we are in a method
1369 // of a renderer class, and this object may, or may not, be the same as
1370 // the global $OUTPUT object. When rendering the page layout file, we want to use
1371 // this object. However, people writing Moodle code expect the current
1372 // renderer to be called $OUTPUT, not $this, so define a variable called
1373 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1375 $PAGE = $this->page
;
1376 $COURSE = $this->page
->course
;
1379 include($layoutfile);
1380 $rendered = ob_get_contents();
1386 * Outputs the page's footer
1388 * @return string HTML fragment
1390 public function footer() {
1393 // Give plugins an opportunity to touch the page before JS is finalized.
1394 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1395 foreach ($pluginswithfunction as $plugins) {
1396 foreach ($plugins as $function) {
1401 $output = $this->container_end_all(true);
1403 $footer = $this->opencontainers
->pop('header/footer');
1405 if (debugging() and $DB and $DB->is_transaction_started()) {
1406 // TODO: MDL-20625 print warning - transaction will be rolled back
1409 // Provide some performance info if required
1410 $performanceinfo = '';
1411 if (defined('MDL_PERF') ||
(!empty($CFG->perfdebug
) and $CFG->perfdebug
> 7)) {
1412 $perf = get_performance_info();
1413 if (defined('MDL_PERFTOFOOT') ||
debugging() ||
$CFG->perfdebug
> 7) {
1414 $performanceinfo = $perf['html'];
1418 // We always want performance data when running a performance test, even if the user is redirected to another page.
1419 if (MDL_PERF_TEST
&& strpos($footer, $this->unique_performance_info_token
) === false) {
1420 $footer = $this->unique_performance_info_token
. $footer;
1422 $footer = str_replace($this->unique_performance_info_token
, $performanceinfo, $footer);
1424 // Only show notifications when the current page has a context id.
1425 if (!empty($this->page
->context
->id
)) {
1426 $this->page
->requires
->js_call_amd('core/notification', 'init', array(
1427 $this->page
->context
->id
,
1428 \core\notification
::fetch_as_array($this),
1432 $footer = str_replace($this->unique_end_html_token
, $this->page
->requires
->get_end_code(), $footer);
1434 $this->page
->set_state(moodle_page
::STATE_DONE
);
1436 return $output . $footer;
1440 * Close all but the last open container. This is useful in places like error
1441 * handling, where you want to close all the open containers (apart from <body>)
1442 * before outputting the error message.
1444 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1445 * developer debug warning if it isn't.
1446 * @return string the HTML required to close any open containers inside <body>.
1448 public function container_end_all($shouldbenone = false) {
1449 return $this->opencontainers
->pop_all_but_last($shouldbenone);
1453 * Returns course-specific information to be output immediately above content on any course page
1454 * (for the current course)
1456 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1459 public function course_content_header($onlyifnotcalledbefore = false) {
1461 static $functioncalled = false;
1462 if ($functioncalled && $onlyifnotcalledbefore) {
1463 // we have already output the content header
1467 // Output any session notification.
1468 $notifications = \core\notification
::fetch();
1470 $bodynotifications = '';
1471 foreach ($notifications as $notification) {
1472 $bodynotifications .= $this->render_from_template(
1473 $notification->get_template_name(),
1474 $notification->export_for_template($this)
1478 $output = html_writer
::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1480 if ($this->page
->course
->id
== SITEID
) {
1481 // return immediately and do not include /course/lib.php if not necessary
1485 require_once($CFG->dirroot
.'/course/lib.php');
1486 $functioncalled = true;
1487 $courseformat = course_get_format($this->page
->course
);
1488 if (($obj = $courseformat->course_content_header()) !== null) {
1489 $output .= html_writer
::div($courseformat->get_renderer($this->page
)->render($obj), 'course-content-header');
1495 * Returns course-specific information to be output immediately below content on any course page
1496 * (for the current course)
1498 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1501 public function course_content_footer($onlyifnotcalledbefore = false) {
1503 if ($this->page
->course
->id
== SITEID
) {
1504 // return immediately and do not include /course/lib.php if not necessary
1507 static $functioncalled = false;
1508 if ($functioncalled && $onlyifnotcalledbefore) {
1509 // we have already output the content footer
1512 $functioncalled = true;
1513 require_once($CFG->dirroot
.'/course/lib.php');
1514 $courseformat = course_get_format($this->page
->course
);
1515 if (($obj = $courseformat->course_content_footer()) !== null) {
1516 return html_writer
::div($courseformat->get_renderer($this->page
)->render($obj), 'course-content-footer');
1522 * Returns course-specific information to be output on any course page in the header area
1523 * (for the current course)
1527 public function course_header() {
1529 if ($this->page
->course
->id
== SITEID
) {
1530 // return immediately and do not include /course/lib.php if not necessary
1533 require_once($CFG->dirroot
.'/course/lib.php');
1534 $courseformat = course_get_format($this->page
->course
);
1535 if (($obj = $courseformat->course_header()) !== null) {
1536 return $courseformat->get_renderer($this->page
)->render($obj);
1542 * Returns course-specific information to be output on any course page in the footer area
1543 * (for the current course)
1547 public function course_footer() {
1549 if ($this->page
->course
->id
== SITEID
) {
1550 // return immediately and do not include /course/lib.php if not necessary
1553 require_once($CFG->dirroot
.'/course/lib.php');
1554 $courseformat = course_get_format($this->page
->course
);
1555 if (($obj = $courseformat->course_footer()) !== null) {
1556 return $courseformat->get_renderer($this->page
)->render($obj);
1562 * Get the course pattern datauri to show on a course card.
1564 * The datauri is an encoded svg that can be passed as a url.
1565 * @param int $id Id to use when generating the pattern
1566 * @return string datauri
1568 public function get_generated_image_for_id($id) {
1569 $color = $this->get_generated_color_for_id($id);
1570 $pattern = new \
core_geopattern();
1571 $pattern->setColor($color);
1572 $pattern->patternbyid($id);
1573 return $pattern->datauri();
1577 * Get the course color to show on a course card.
1579 * @param int $id Id to use when generating the color.
1580 * @return string hex color code.
1582 public function get_generated_color_for_id($id) {
1583 $colornumbers = range(1, 10);
1585 foreach ($colornumbers as $number) {
1586 $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1589 $color = $basecolors[$id %
10];
1594 * Returns lang menu or '', this method also checks forcing of languages in courses.
1596 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1598 * @return string The lang menu HTML or empty string
1600 public function lang_menu() {
1603 if (empty($CFG->langmenu
)) {
1607 if ($this->page
->course
!= SITEID
and !empty($this->page
->course
->lang
)) {
1608 // do not show lang menu if language forced
1612 $currlang = current_language();
1613 $langs = get_string_manager()->get_list_of_translations();
1615 if (count($langs) < 2) {
1619 $s = new single_select($this->page
->url
, 'lang', $langs, $currlang, null);
1620 $s->label
= get_accesshide(get_string('language'));
1621 $s->class = 'langmenu';
1622 return $this->render($s);
1626 * Output the row of editing icons for a block, as defined by the controls array.
1628 * @param array $controls an array like {@link block_contents::$controls}.
1629 * @param string $blockid The ID given to the block.
1630 * @return string HTML fragment.
1632 public function block_controls($actions, $blockid = null) {
1634 if (empty($actions)) {
1637 $menu = new action_menu($actions);
1638 if ($blockid !== null) {
1639 $menu->set_owner_selector('#'.$blockid);
1641 $menu->set_constraint('.block-region');
1642 $menu->attributes
['class'] .= ' block-control-actions commands';
1643 return $this->render($menu);
1647 * Returns the HTML for a basic textarea field.
1649 * @param string $name Name to use for the textarea element
1650 * @param string $id The id to use fort he textarea element
1651 * @param string $value Initial content to display in the textarea
1652 * @param int $rows Number of rows to display
1653 * @param int $cols Number of columns to display
1654 * @return string the HTML to display
1656 public function print_textarea($name, $id, $value, $rows, $cols) {
1657 editors_head_setup();
1658 $editor = editors_get_preferred_editor(FORMAT_HTML
);
1659 $editor->set_text($value);
1660 $editor->use_editor($id, []);
1670 return $this->render_from_template('core_form/editor_textarea', $context);
1674 * Renders an action menu component.
1676 * @param action_menu $menu
1677 * @return string HTML
1679 public function render_action_menu(action_menu
$menu) {
1681 // We don't want the class icon there!
1682 foreach ($menu->get_secondary_actions() as $action) {
1683 if ($action instanceof \action_menu_link
&& $action->has_class('icon')) {
1684 $action->attributes
['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes
['class']);
1688 if ($menu->is_empty()) {
1691 $context = $menu->export_for_template($this);
1693 return $this->render_from_template('core/action_menu', $context);
1697 * Renders a Check API result
1699 * @param result $result
1700 * @return string HTML fragment
1702 protected function render_check_result(core\check\result
$result) {
1703 return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1707 * Renders a Check API result
1709 * @param result $result
1710 * @return string HTML fragment
1712 public function check_result(core\check\result
$result) {
1713 return $this->render_check_result($result);
1717 * Renders an action_menu_link item.
1719 * @param action_menu_link $action
1720 * @return string HTML fragment
1722 protected function render_action_menu_link(action_menu_link
$action) {
1723 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1727 * Renders a primary action_menu_filler item.
1729 * @param action_menu_link_filler $action
1730 * @return string HTML fragment
1732 protected function render_action_menu_filler(action_menu_filler
$action) {
1733 return html_writer
::span(' ', 'filler');
1737 * Renders a primary action_menu_link item.
1739 * @param action_menu_link_primary $action
1740 * @return string HTML fragment
1742 protected function render_action_menu_link_primary(action_menu_link_primary
$action) {
1743 return $this->render_action_menu_link($action);
1747 * Renders a secondary action_menu_link item.
1749 * @param action_menu_link_secondary $action
1750 * @return string HTML fragment
1752 protected function render_action_menu_link_secondary(action_menu_link_secondary
$action) {
1753 return $this->render_action_menu_link($action);
1757 * Prints a nice side block with an optional header.
1759 * @param block_contents $bc HTML for the content
1760 * @param string $region the region the block is appearing in.
1761 * @return string the HTML to be output.
1763 public function block(block_contents
$bc, $region) {
1764 $bc = clone($bc); // Avoid messing up the object passed in.
1765 if (empty($bc->blockinstanceid
) ||
!strip_tags($bc->title
)) {
1766 $bc->collapsible
= block_contents
::NOT_HIDEABLE
;
1769 $id = !empty($bc->attributes
['id']) ?
$bc->attributes
['id'] : uniqid('block-');
1770 $context = new stdClass();
1771 $context->skipid
= $bc->skipid
;
1772 $context->blockinstanceid
= $bc->blockinstanceid ?
: uniqid('fakeid-');
1773 $context->dockable
= $bc->dockable
;
1775 $context->hidden
= $bc->collapsible
== block_contents
::HIDDEN
;
1776 $context->skiptitle
= strip_tags($bc->title
);
1777 $context->showskiplink
= !empty($context->skiptitle
);
1778 $context->arialabel
= $bc->arialabel
;
1779 $context->ariarole
= !empty($bc->attributes
['role']) ?
$bc->attributes
['role'] : 'complementary';
1780 $context->class = $bc->attributes
['class'];
1781 $context->type
= $bc->attributes
['data-block'];
1782 $context->title
= $bc->title
;
1783 $context->content
= $bc->content
;
1784 $context->annotation
= $bc->annotation
;
1785 $context->footer
= $bc->footer
;
1786 $context->hascontrols
= !empty($bc->controls
);
1787 if ($context->hascontrols
) {
1788 $context->controls
= $this->block_controls($bc->controls
, $id);
1791 return $this->render_from_template('core/block', $context);
1795 * Render the contents of a block_list.
1797 * @param array $icons the icon for each item.
1798 * @param array $items the content of each item.
1799 * @return string HTML
1801 public function list_block_contents($icons, $items) {
1804 foreach ($items as $key => $string) {
1805 $item = html_writer
::start_tag('li', array('class' => 'r' . $row));
1806 if (!empty($icons[$key])) { //test if the content has an assigned icon
1807 $item .= html_writer
::tag('div', $icons[$key], array('class' => 'icon column c0'));
1809 $item .= html_writer
::tag('div', $string, array('class' => 'column c1'));
1810 $item .= html_writer
::end_tag('li');
1812 $row = 1 - $row; // Flip even/odd.
1814 return html_writer
::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1818 * Output all the blocks in a particular region.
1820 * @param string $region the name of a region on this page.
1821 * @return string the HTML to be output.
1823 public function blocks_for_region($region) {
1824 $blockcontents = $this->page
->blocks
->get_content_for_region($region, $this);
1825 $blocks = $this->page
->blocks
->get_blocks_for_region($region);
1828 foreach ($blocks as $block) {
1829 $zones[] = $block->title
;
1833 foreach ($blockcontents as $bc) {
1834 if ($bc instanceof block_contents
) {
1835 $output .= $this->block($bc, $region);
1836 $lastblock = $bc->title
;
1837 } else if ($bc instanceof block_move_target
) {
1838 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1840 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1847 * Output a place where the block that is currently being moved can be dropped.
1849 * @param block_move_target $target with the necessary details.
1850 * @param array $zones array of areas where the block can be moved to
1851 * @param string $previous the block located before the area currently being rendered.
1852 * @param string $region the name of the region
1853 * @return string the HTML to be output.
1855 public function block_move_target($target, $zones, $previous, $region) {
1856 if ($previous == null) {
1857 if (empty($zones)) {
1858 // There are no zones, probably because there are no blocks.
1859 $regions = $this->page
->theme
->get_all_block_regions();
1860 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1862 $position = get_string('moveblockbefore', 'block', $zones[0]);
1865 $position = get_string('moveblockafter', 'block', $previous);
1867 return html_writer
::tag('a', html_writer
::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url
, 'class' => 'blockmovetarget'));
1871 * Renders a special html link with attached action
1873 * Theme developers: DO NOT OVERRIDE! Please override function
1874 * {@link core_renderer::render_action_link()} instead.
1876 * @param string|moodle_url $url
1877 * @param string $text HTML fragment
1878 * @param component_action $action
1879 * @param array $attributes associative array of html link attributes + disabled
1880 * @param pix_icon optional pix icon to render with the link
1881 * @return string HTML fragment
1883 public function action_link($url, $text, component_action
$action = null, array $attributes = null, $icon = null) {
1884 if (!($url instanceof moodle_url
)) {
1885 $url = new moodle_url($url);
1887 $link = new action_link($url, $text, $action, $attributes, $icon);
1889 return $this->render($link);
1893 * Renders an action_link object.
1895 * The provided link is renderer and the HTML returned. At the same time the
1896 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1898 * @param action_link $link
1899 * @return string HTML fragment
1901 protected function render_action_link(action_link
$link) {
1902 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1906 * Renders an action_icon.
1908 * This function uses the {@link core_renderer::action_link()} method for the
1909 * most part. What it does different is prepare the icon as HTML and use it
1912 * Theme developers: If you want to change how action links and/or icons are rendered,
1913 * consider overriding function {@link core_renderer::render_action_link()} and
1914 * {@link core_renderer::render_pix_icon()}.
1916 * @param string|moodle_url $url A string URL or moodel_url
1917 * @param pix_icon $pixicon
1918 * @param component_action $action
1919 * @param array $attributes associative array of html link attributes + disabled
1920 * @param bool $linktext show title next to image in link
1921 * @return string HTML fragment
1923 public function action_icon($url, pix_icon
$pixicon, component_action
$action = null, array $attributes = null, $linktext=false) {
1924 if (!($url instanceof moodle_url
)) {
1925 $url = new moodle_url($url);
1927 $attributes = (array)$attributes;
1929 if (empty($attributes['class'])) {
1930 // let ppl override the class via $options
1931 $attributes['class'] = 'action-icon';
1934 $icon = $this->render($pixicon);
1937 $text = $pixicon->attributes
['alt'];
1942 return $this->action_link($url, $text.$icon, $action, $attributes);
1946 * Print a message along with button choices for Continue/Cancel
1948 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1950 * @param string $message The question to ask the user
1951 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1952 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1953 * @return string HTML fragment
1955 public function confirm($message, $continue, $cancel) {
1956 if ($continue instanceof single_button
) {
1958 $continue->primary
= true;
1959 } else if (is_string($continue)) {
1960 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1961 } else if ($continue instanceof moodle_url
) {
1962 $continue = new single_button($continue, get_string('continue'), 'post', true);
1964 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1967 if ($cancel instanceof single_button
) {
1969 } else if (is_string($cancel)) {
1970 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1971 } else if ($cancel instanceof moodle_url
) {
1972 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1974 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1978 'role'=>'alertdialog',
1979 'aria-labelledby'=>'modal-header',
1980 'aria-describedby'=>'modal-body',
1981 'aria-modal'=>'true'
1984 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
1985 $output .= $this->box_start('modal-content', 'modal-content');
1986 $output .= $this->box_start('modal-header p-x-1', 'modal-header');
1987 $output .= html_writer
::tag('h4', get_string('confirm'));
1988 $output .= $this->box_end();
1991 'data-aria-autofocus'=>'true'
1993 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
1994 $output .= html_writer
::tag('p', $message);
1995 $output .= $this->box_end();
1996 $output .= $this->box_start('modal-footer', 'modal-footer');
1997 $output .= html_writer
::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1998 $output .= $this->box_end();
1999 $output .= $this->box_end();
2000 $output .= $this->box_end();
2005 * Returns a form with a single button.
2007 * Theme developers: DO NOT OVERRIDE! Please override function
2008 * {@link core_renderer::render_single_button()} instead.
2010 * @param string|moodle_url $url
2011 * @param string $label button text
2012 * @param string $method get or post submit method
2013 * @param array $options associative array {disabled, title, etc.}
2014 * @return string HTML fragment
2016 public function single_button($url, $label, $method='post', array $options=null) {
2017 if (!($url instanceof moodle_url
)) {
2018 $url = new moodle_url($url);
2020 $button = new single_button($url, $label, $method);
2022 foreach ((array)$options as $key=>$value) {
2023 if (property_exists($button, $key)) {
2024 $button->$key = $value;
2026 $button->set_attribute($key, $value);
2030 return $this->render($button);
2034 * Renders a single button widget.
2036 * This will return HTML to display a form containing a single button.
2038 * @param single_button $button
2039 * @return string HTML fragment
2041 protected function render_single_button(single_button
$button) {
2042 return $this->render_from_template('core/single_button', $button->export_for_template($this));
2046 * Returns a form with a single select widget.
2048 * Theme developers: DO NOT OVERRIDE! Please override function
2049 * {@link core_renderer::render_single_select()} instead.
2051 * @param moodle_url $url form action target, includes hidden fields
2052 * @param string $name name of selection field - the changing parameter in url
2053 * @param array $options list of options
2054 * @param string $selected selected element
2055 * @param array $nothing
2056 * @param string $formid
2057 * @param array $attributes other attributes for the single select
2058 * @return string HTML fragment
2060 public function single_select($url, $name, array $options, $selected = '',
2061 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2062 if (!($url instanceof moodle_url
)) {
2063 $url = new moodle_url($url);
2065 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2067 if (array_key_exists('label', $attributes)) {
2068 $select->set_label($attributes['label']);
2069 unset($attributes['label']);
2071 $select->attributes
= $attributes;
2073 return $this->render($select);
2077 * Returns a dataformat selection and download form
2079 * @param string $label A text label
2080 * @param moodle_url|string $base The download page url
2081 * @param string $name The query param which will hold the type of the download
2082 * @param array $params Extra params sent to the download page
2083 * @return string HTML fragment
2085 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2087 $formats = core_plugin_manager
::instance()->get_plugins_of_type('dataformat');
2089 foreach ($formats as $format) {
2090 if ($format->is_enabled()) {
2092 'value' => $format->name
,
2093 'label' => get_string('dataformat', $format->component
),
2097 $hiddenparams = array();
2098 foreach ($params as $key => $value) {
2099 $hiddenparams[] = array(
2108 'params' => $hiddenparams,
2109 'options' => $options,
2110 'sesskey' => sesskey(),
2111 'submit' => get_string('download'),
2114 return $this->render_from_template('core/dataformat_selector', $data);
2119 * Internal implementation of single_select rendering
2121 * @param single_select $select
2122 * @return string HTML fragment
2124 protected function render_single_select(single_select
$select) {
2125 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2129 * Returns a form with a url select widget.
2131 * Theme developers: DO NOT OVERRIDE! Please override function
2132 * {@link core_renderer::render_url_select()} instead.
2134 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2135 * @param string $selected selected element
2136 * @param array $nothing
2137 * @param string $formid
2138 * @return string HTML fragment
2140 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2141 $select = new url_select($urls, $selected, $nothing, $formid);
2142 return $this->render($select);
2146 * Internal implementation of url_select rendering
2148 * @param url_select $select
2149 * @return string HTML fragment
2151 protected function render_url_select(url_select
$select) {
2152 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2156 * Returns a string containing a link to the user documentation.
2157 * Also contains an icon by default. Shown to teachers and admin only.
2159 * @param string $path The page link after doc root and language, no leading slash.
2160 * @param string $text The text to be displayed for the link
2161 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2162 * @param array $attributes htm attributes
2165 public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
2168 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2170 $attributes['href'] = new moodle_url(get_docs_url($path));
2171 if (!empty($CFG->doctonewwindow
) ||
$forcepopup) {
2172 $attributes['class'] = 'helplinkpopup';
2175 return html_writer
::tag('a', $icon.$text, $attributes);
2179 * Return HTML for an image_icon.
2181 * Theme developers: DO NOT OVERRIDE! Please override function
2182 * {@link core_renderer::render_image_icon()} instead.
2184 * @param string $pix short pix name
2185 * @param string $alt mandatory alt attribute
2186 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2187 * @param array $attributes htm attributes
2188 * @return string HTML fragment
2190 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2191 $icon = new image_icon($pix, $alt, $component, $attributes);
2192 return $this->render($icon);
2196 * Renders a pix_icon widget and returns the HTML to display it.
2198 * @param image_icon $icon
2199 * @return string HTML fragment
2201 protected function render_image_icon(image_icon
$icon) {
2202 $system = \core\output\icon_system
::instance(\core\output\icon_system
::STANDARD
);
2203 return $system->render_pix_icon($this, $icon);
2207 * Return HTML for a pix_icon.
2209 * Theme developers: DO NOT OVERRIDE! Please override function
2210 * {@link core_renderer::render_pix_icon()} instead.
2212 * @param string $pix short pix name
2213 * @param string $alt mandatory alt attribute
2214 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2215 * @param array $attributes htm lattributes
2216 * @return string HTML fragment
2218 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2219 $icon = new pix_icon($pix, $alt, $component, $attributes);
2220 return $this->render($icon);
2224 * Renders a pix_icon widget and returns the HTML to display it.
2226 * @param pix_icon $icon
2227 * @return string HTML fragment
2229 protected function render_pix_icon(pix_icon
$icon) {
2230 $system = \core\output\icon_system
::instance();
2231 return $system->render_pix_icon($this, $icon);
2235 * Return HTML to display an emoticon icon.
2237 * @param pix_emoticon $emoticon
2238 * @return string HTML fragment
2240 protected function render_pix_emoticon(pix_emoticon
$emoticon) {
2241 $system = \core\output\icon_system
::instance(\core\output\icon_system
::STANDARD
);
2242 return $system->render_pix_icon($this, $emoticon);
2246 * Produces the html that represents this rating in the UI
2248 * @param rating $rating the page object on which this rating will appear
2251 function render_rating(rating
$rating) {
2254 if ($rating->settings
->aggregationmethod
== RATING_AGGREGATE_NONE
) {
2255 return null;//ratings are turned off
2258 $ratingmanager = new rating_manager();
2259 // Initialise the JavaScript so ratings can be done by AJAX.
2260 $ratingmanager->initialise_rating_javascript($this->page
);
2262 $strrate = get_string("rate", "rating");
2263 $ratinghtml = ''; //the string we'll return
2265 // permissions check - can they view the aggregate?
2266 if ($rating->user_can_view_aggregate()) {
2268 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings
->aggregationmethod
);
2269 $aggregatelabel = html_writer
::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2270 $aggregatestr = $rating->get_aggregate_string();
2272 $aggregatehtml = html_writer
::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid
, 'class' => 'ratingaggregate')).' ';
2273 if ($rating->count
> 0) {
2274 $countstr = "({$rating->count})";
2278 $aggregatehtml .= html_writer
::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2280 if ($rating->settings
->permissions
->viewall
&& $rating->settings
->pluginpermissions
->viewall
) {
2282 $nonpopuplink = $rating->get_view_ratings_url();
2283 $popuplink = $rating->get_view_ratings_url(true);
2285 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2286 $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
2289 $ratinghtml .= html_writer
::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
2293 // if the item doesn't belong to the current user, the user has permission to rate
2294 // and we're within the assessable period
2295 if ($rating->user_can_rate()) {
2297 $rateurl = $rating->get_rate_url();
2298 $inputs = $rateurl->params();
2300 //start the rating form
2302 'id' => "postrating{$rating->itemid}",
2303 'class' => 'postratingform',
2305 'action' => $rateurl->out_omit_querystring()
2307 $formstart = html_writer
::start_tag('form', $formattrs);
2308 $formstart .= html_writer
::start_tag('div', array('class' => 'ratingform'));
2310 // add the hidden inputs
2311 foreach ($inputs as $name => $value) {
2312 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2313 $formstart .= html_writer
::empty_tag('input', $attributes);
2316 if (empty($ratinghtml)) {
2317 $ratinghtml .= $strrate.': ';
2319 $ratinghtml = $formstart.$ratinghtml;
2321 $scalearray = array(RATING_UNSET_RATING
=> $strrate.'...') +
$rating->settings
->scale
->scaleitems
;
2322 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid
);
2323 $ratinghtml .= html_writer
::label($rating->rating
, 'menurating'.$rating->itemid
, false, array('class' => 'accesshide'));
2324 $ratinghtml .= html_writer
::select($scalearray, 'rating', $rating->rating
, false, $scaleattrs);
2326 //output submit button
2327 $ratinghtml .= html_writer
::start_tag('span', array('class'=>"ratingsubmit"));
2329 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid
, 'value' => s(get_string('rate', 'rating')));
2330 $ratinghtml .= html_writer
::empty_tag('input', $attributes);
2332 if (!$rating->settings
->scale
->isnumeric
) {
2333 // If a global scale, try to find current course ID from the context
2334 if (empty($rating->settings
->scale
->courseid
) and $coursecontext = $rating->context
->get_course_context(false)) {
2335 $courseid = $coursecontext->instanceid
;
2337 $courseid = $rating->settings
->scale
->courseid
;
2339 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings
->scale
);
2341 $ratinghtml .= html_writer
::end_tag('span');
2342 $ratinghtml .= html_writer
::end_tag('div');
2343 $ratinghtml .= html_writer
::end_tag('form');
2350 * Centered heading with attached help button (same title text)
2351 * and optional icon attached.
2353 * @param string $text A heading text
2354 * @param string $helpidentifier The keyword that defines a help page
2355 * @param string $component component name
2356 * @param string|moodle_url $icon
2357 * @param string $iconalt icon alt text
2358 * @param int $level The level of importance of the heading. Defaulting to 2
2359 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2360 * @return string HTML fragment
2362 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2365 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2369 if ($helpidentifier) {
2370 $help = $this->help_icon($helpidentifier, $component);
2373 return $this->heading($image.$text.$help, $level, $classnames);
2377 * Returns HTML to display a help icon.
2379 * @deprecated since Moodle 2.0
2381 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2382 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2386 * Returns HTML to display a help icon.
2388 * Theme developers: DO NOT OVERRIDE! Please override function
2389 * {@link core_renderer::render_help_icon()} instead.
2391 * @param string $identifier The keyword that defines a help page
2392 * @param string $component component name
2393 * @param string|bool $linktext true means use $title as link text, string means link text value
2394 * @return string HTML fragment
2396 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2397 $icon = new help_icon($identifier, $component);
2398 $icon->diag_strings();
2399 if ($linktext === true) {
2400 $icon->linktext
= get_string($icon->identifier
, $icon->component
);
2401 } else if (!empty($linktext)) {
2402 $icon->linktext
= $linktext;
2404 return $this->render($icon);
2408 * Implementation of user image rendering.
2410 * @param help_icon $helpicon A help icon instance
2411 * @return string HTML fragment
2413 protected function render_help_icon(help_icon
$helpicon) {
2414 $context = $helpicon->export_for_template($this);
2415 return $this->render_from_template('core/help_icon', $context);
2419 * Returns HTML to display a scale help icon.
2421 * @param int $courseid
2422 * @param stdClass $scale instance
2423 * @return string HTML fragment
2425 public function help_icon_scale($courseid, stdClass
$scale) {
2428 $title = get_string('helpprefix2', '', $scale->name
) .' ('.get_string('newwindow').')';
2430 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2432 $scaleid = abs($scale->id
);
2434 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2435 $action = new popup_action('click', $link, 'ratingscale');
2437 return html_writer
::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2441 * Creates and returns a spacer image with optional line break.
2443 * @param array $attributes Any HTML attributes to add to the spaced.
2444 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2445 * laxy do it with CSS which is a much better solution.
2446 * @return string HTML fragment
2448 public function spacer(array $attributes = null, $br = false) {
2449 $attributes = (array)$attributes;
2450 if (empty($attributes['width'])) {
2451 $attributes['width'] = 1;
2453 if (empty($attributes['height'])) {
2454 $attributes['height'] = 1;
2456 $attributes['class'] = 'spacer';
2458 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2461 $output .= '<br />';
2468 * Returns HTML to display the specified user's avatar.
2470 * User avatar may be obtained in two ways:
2472 * // Option 1: (shortcut for simple cases, preferred way)
2473 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2474 * $OUTPUT->user_picture($user, array('popup'=>true));
2477 * $userpic = new user_picture($user);
2478 * // Set properties of $userpic
2479 * $userpic->popup = true;
2480 * $OUTPUT->render($userpic);
2483 * Theme developers: DO NOT OVERRIDE! Please override function
2484 * {@link core_renderer::render_user_picture()} instead.
2486 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2487 * If any of these are missing, the database is queried. Avoid this
2488 * if at all possible, particularly for reports. It is very bad for performance.
2489 * @param array $options associative array with user picture options, used only if not a user_picture object,
2491 * - courseid=$this->page->course->id (course id of user profile in link)
2492 * - size=35 (size of image)
2493 * - link=true (make image clickable - the link leads to user profile)
2494 * - popup=false (open in popup)
2495 * - alttext=true (add image alt attribute)
2496 * - class = image class attribute (default 'userpicture')
2497 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2498 * - includefullname=false (whether to include the user's full name together with the user picture)
2499 * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2500 * @return string HTML fragment
2502 public function user_picture(stdClass
$user, array $options = null) {
2503 $userpicture = new user_picture($user);
2504 foreach ((array)$options as $key=>$value) {
2505 if (property_exists($userpicture, $key)) {
2506 $userpicture->$key = $value;
2509 return $this->render($userpicture);
2513 * Internal implementation of user image rendering.
2515 * @param user_picture $userpicture
2518 protected function render_user_picture(user_picture
$userpicture) {
2519 $user = $userpicture->user
;
2520 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page
->context
);
2522 if ($userpicture->alttext
) {
2523 if (!empty($user->imagealt
)) {
2524 $alt = $user->imagealt
;
2526 $alt = get_string('pictureof', '', fullname($user, $canviewfullnames));
2532 if (empty($userpicture->size
)) {
2534 } else if ($userpicture->size
=== true or $userpicture->size
== 1) {
2537 $size = $userpicture->size
;
2540 $class = $userpicture->class;
2542 if ($user->picture
== 0) {
2543 $class .= ' defaultuserpic';
2546 $src = $userpicture->get_url($this->page
, $this);
2548 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2549 if (!$userpicture->visibletoscreenreaders
) {
2552 $attributes['alt'] = $alt;
2555 $attributes['title'] = $alt;
2558 // get the image html output fisrt
2559 $output = html_writer
::empty_tag('img', $attributes);
2561 // Show fullname together with the picture when desired.
2562 if ($userpicture->includefullname
) {
2563 $output .= fullname($userpicture->user
, $canviewfullnames);
2566 // then wrap it in link if needed
2567 if (!$userpicture->link
) {
2571 if (empty($userpicture->courseid
)) {
2572 $courseid = $this->page
->course
->id
;
2574 $courseid = $userpicture->courseid
;
2577 if ($courseid == SITEID
) {
2578 $url = new moodle_url('/user/profile.php', array('id' => $user->id
));
2580 $url = new moodle_url('/user/view.php', array('id' => $user->id
, 'course' => $courseid));
2583 $attributes = array('href' => $url, 'class' => 'd-inline-block aabtn');
2584 if (!$userpicture->visibletoscreenreaders
) {
2585 $attributes['tabindex'] = '-1';
2586 $attributes['aria-hidden'] = 'true';
2589 if ($userpicture->popup
) {
2590 $id = html_writer
::random_id('userpicture');
2591 $attributes['id'] = $id;
2592 $this->add_action_handler(new popup_action('click', $url), $id);
2595 return html_writer
::tag('a', $output, $attributes);
2599 * Internal implementation of file tree viewer items rendering.
2604 public function htmllize_file_tree($dir) {
2605 if (empty($dir['subdirs']) and empty($dir['files'])) {
2609 foreach ($dir['subdirs'] as $subdir) {
2610 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2612 foreach ($dir['files'] as $file) {
2613 $filename = $file->get_filename();
2614 $result .= '<li><span>'.html_writer
::link($file->fileurl
, $filename).'</span></li>';
2622 * Returns HTML to display the file picker
2625 * $OUTPUT->file_picker($options);
2628 * Theme developers: DO NOT OVERRIDE! Please override function
2629 * {@link core_renderer::render_file_picker()} instead.
2631 * @param array $options associative array with file manager options
2635 * client_id=>uniqid(),
2636 * acepted_types=>'*',
2637 * return_types=>FILE_INTERNAL,
2638 * context=>current page context
2639 * @return string HTML fragment
2641 public function file_picker($options) {
2642 $fp = new file_picker($options);
2643 return $this->render($fp);
2647 * Internal implementation of file picker rendering.
2649 * @param file_picker $fp
2652 public function render_file_picker(file_picker
$fp) {
2653 $options = $fp->options
;
2654 $client_id = $options->client_id
;
2655 $strsaved = get_string('filesaved', 'repository');
2656 $straddfile = get_string('openpicker', 'repository');
2657 $strloading = get_string('loading', 'repository');
2658 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2659 $strdroptoupload = get_string('droptoupload', 'moodle');
2660 $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
2662 $currentfile = $options->currentfile
;
2663 if (empty($currentfile)) {
2666 $currentfile .= ' - ';
2668 if ($options->maxbytes
) {
2669 $size = $options->maxbytes
;
2671 $size = get_max_upload_file_size();
2676 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2678 if ($options->buttonname
) {
2679 $buttonname = ' name="' . $options->buttonname
. '"';
2684 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2687 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2689 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2690 <span> $maxsize </span>
2693 if ($options->env
!= 'url') {
2695 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2696 <div class="filepicker-filename">
2697 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2698 <div class="dndupload-progressbars"></div>
2700 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2709 * @deprecated since Moodle 3.2
2711 public function update_module_button() {
2712 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2713 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2714 'Themes can choose to display the link in the buttons row consistently for all module types.');
2718 * Returns HTML to display a "Turn editing on/off" button in a form.
2720 * @param moodle_url $url The URL + params to send through when clicking the button
2721 * @return string HTML the button
2723 public function edit_button(moodle_url
$url) {
2725 $url->param('sesskey', sesskey());
2726 if ($this->page
->user_is_editing()) {
2727 $url->param('edit', 'off');
2728 $editstring = get_string('turneditingoff');
2730 $url->param('edit', 'on');
2731 $editstring = get_string('turneditingon');
2734 return $this->single_button($url, $editstring);
2738 * Returns HTML to display a simple button to close a window
2740 * @param string $text The lang string for the button's label (already output from get_string())
2741 * @return string html fragment
2743 public function close_window_button($text='') {
2745 $text = get_string('closewindow');
2747 $button = new single_button(new moodle_url('#'), $text, 'get');
2748 $button->add_action(new component_action('click', 'close_window'));
2750 return $this->container($this->render($button), 'closewindow');
2754 * Output an error message. By default wraps the error message in <span class="error">.
2755 * If the error message is blank, nothing is output.
2757 * @param string $message the error message.
2758 * @return string the HTML to output.
2760 public function error_text($message) {
2761 if (empty($message)) {
2764 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2765 return html_writer
::tag('span', $message, array('class' => 'error'));
2769 * Do not call this function directly.
2771 * To terminate the current script with a fatal error, call the {@link print_error}
2772 * function, or throw an exception. Doing either of those things will then call this
2773 * function to display the error, before terminating the execution.
2775 * @param string $message The message to output
2776 * @param string $moreinfourl URL where more info can be found about the error
2777 * @param string $link Link for the Continue button
2778 * @param array $backtrace The execution backtrace
2779 * @param string $debuginfo Debugging information
2780 * @return string the HTML to output.
2782 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2788 if ($this->has_started()) {
2789 // we can not always recover properly here, we have problems with output buffering,
2790 // html tables, etc.
2791 $output .= $this->opencontainers
->pop_all_but_last();
2794 // It is really bad if library code throws exception when output buffering is on,
2795 // because the buffered text would be printed before our start of page.
2796 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2797 error_reporting(0); // disable notices from gzip compression, etc.
2798 while (ob_get_level() > 0) {
2799 $buff = ob_get_clean();
2800 if ($buff === false) {
2805 error_reporting($CFG->debug
);
2807 // Output not yet started.
2808 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ?
$_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2809 if (empty($_SERVER['HTTP_RANGE'])) {
2810 @header
($protocol . ' 404 Not Found');
2811 } else if (core_useragent
::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2812 // Coax iOS 10 into sending the session cookie.
2813 @header
($protocol . ' 403 Forbidden');
2815 // Must stop byteserving attempts somehow,
2816 // this is weird but Chrome PDF viewer can be stopped only with 407!
2817 @header
($protocol . ' 407 Proxy Authentication Required');
2820 $this->page
->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2821 $this->page
->set_url('/'); // no url
2822 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2823 $this->page
->set_title(get_string('error'));
2824 $this->page
->set_heading($this->page
->course
->fullname
);
2825 $output .= $this->header();
2828 $message = '<p class="errormessage">' . s($message) . '</p>'.
2829 '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
2830 get_string('moreinformation') . '</a></p>';
2831 if (empty($CFG->rolesactive
)) {
2832 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2833 //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.
2835 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2837 if ($CFG->debugdeveloper
) {
2838 $labelsep = get_string('labelsep', 'langconfig');
2839 if (!empty($debuginfo)) {
2840 $debuginfo = s($debuginfo); // removes all nasty JS
2841 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2842 $label = get_string('debuginfo', 'debug') . $labelsep;
2843 $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
2845 if (!empty($backtrace)) {
2846 $label = get_string('stacktrace', 'debug') . $labelsep;
2847 $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
2849 if ($obbuffer !== '' ) {
2850 $label = get_string('outputbuffer', 'debug') . $labelsep;
2851 $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
2855 if (empty($CFG->rolesactive
)) {
2856 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2857 } else if (!empty($link)) {
2858 $output .= $this->continue_button($link);
2861 $output .= $this->footer();
2863 // Padding to encourage IE to display our error page, rather than its own.
2864 $output .= str_repeat(' ', 512);
2870 * Output a notification (that is, a status message about something that has just happened).
2872 * Note: \core\notification::add() may be more suitable for your usage.
2874 * @param string $message The message to print out.
2875 * @param string $type The type of notification. See constants on \core\output\notification.
2876 * @return string the HTML to output.
2878 public function notification($message, $type = null) {
2881 'success' => \core\output\notification
::NOTIFY_SUCCESS
,
2882 'info' => \core\output\notification
::NOTIFY_INFO
,
2883 'warning' => \core\output\notification
::NOTIFY_WARNING
,
2884 'error' => \core\output\notification
::NOTIFY_ERROR
,
2886 // Legacy types mapped to current types.
2887 'notifyproblem' => \core\output\notification
::NOTIFY_ERROR
,
2888 'notifytiny' => \core\output\notification
::NOTIFY_ERROR
,
2889 'notifyerror' => \core\output\notification
::NOTIFY_ERROR
,
2890 'notifysuccess' => \core\output\notification
::NOTIFY_SUCCESS
,
2891 'notifymessage' => \core\output\notification
::NOTIFY_INFO
,
2892 'notifyredirect' => \core\output\notification
::NOTIFY_INFO
,
2893 'redirectmessage' => \core\output\notification
::NOTIFY_INFO
,
2899 if (strpos($type, ' ') === false) {
2900 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2901 if (isset($typemappings[$type])) {
2902 $type = $typemappings[$type];
2904 // The value provided did not match a known type. It must be an extra class.
2905 $extraclasses = [$type];
2908 // Identify what type of notification this is.
2909 $classarray = explode(' ', self
::prepare_classes($type));
2911 // Separate out the type of notification from the extra classes.
2912 foreach ($classarray as $class) {
2913 if (isset($typemappings[$class])) {
2914 $type = $typemappings[$class];
2916 $extraclasses[] = $class;
2922 $notification = new \core\output\notification
($message, $type);
2923 if (count($extraclasses)) {
2924 $notification->set_extra_classes($extraclasses);
2927 // Return the rendered template.
2928 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2932 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2934 public function notify_problem() {
2935 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
2936 'please use \core\notification::add(), or \core\output\notification as required.');
2940 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2942 public function notify_success() {
2943 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
2944 'please use \core\notification::add(), or \core\output\notification as required.');
2948 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2950 public function notify_message() {
2951 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
2952 'please use \core\notification::add(), or \core\output\notification as required.');
2956 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2958 public function notify_redirect() {
2959 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
2960 'please use \core\notification::add(), or \core\output\notification as required.');
2964 * Render a notification (that is, a status message about something that has
2967 * @param \core\output\notification $notification the notification to print out
2968 * @return string the HTML to output.
2970 protected function render_notification(\core\output\notification
$notification) {
2971 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2975 * Returns HTML to display a continue button that goes to a particular URL.
2977 * @param string|moodle_url $url The url the button goes to.
2978 * @return string the HTML to output.
2980 public function continue_button($url) {
2981 if (!($url instanceof moodle_url
)) {
2982 $url = new moodle_url($url);
2984 $button = new single_button($url, get_string('continue'), 'get', true);
2985 $button->class = 'continuebutton';
2987 return $this->render($button);
2991 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2993 * Theme developers: DO NOT OVERRIDE! Please override function
2994 * {@link core_renderer::render_paging_bar()} instead.
2996 * @param int $totalcount The total number of entries available to be paged through
2997 * @param int $page The page you are currently viewing
2998 * @param int $perpage The number of entries that should be shown per page
2999 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3000 * @param string $pagevar name of page parameter that holds the page number
3001 * @return string the HTML to output.
3003 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3004 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3005 return $this->render($pb);
3009 * Returns HTML to display the paging bar.
3011 * @param paging_bar $pagingbar
3012 * @return string the HTML to output.
3014 protected function render_paging_bar(paging_bar
$pagingbar) {
3015 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3016 $pagingbar->maxdisplay
= 10;
3017 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3021 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3023 * @param string $current the currently selected letter.
3024 * @param string $class class name to add to this initial bar.
3025 * @param string $title the name to put in front of this initial bar.
3026 * @param string $urlvar URL parameter name for this initial.
3027 * @param string $url URL object.
3028 * @param array $alpha of letters in the alphabet.
3029 * @return string the HTML to output.
3031 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3032 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3033 return $this->render($ib);
3037 * Internal implementation of initials bar rendering.
3039 * @param initials_bar $initialsbar
3042 protected function render_initials_bar(initials_bar
$initialsbar) {
3043 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3047 * Output the place a skip link goes to.
3049 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3050 * @return string the HTML to output.
3052 public function skip_link_target($id = null) {
3053 return html_writer
::span('', '', array('id' => $id));
3059 * @param string $text The text of the heading
3060 * @param int $level The level of importance of the heading. Defaulting to 2
3061 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3062 * @param string $id An optional ID
3063 * @return string the HTML to output.
3065 public function heading($text, $level = 2, $classes = null, $id = null) {
3066 $level = (integer) $level;
3067 if ($level < 1 or $level > 6) {
3068 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3070 return html_writer
::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base
::prepare_classes($classes)));
3076 * @param string $contents The contents of the box
3077 * @param string $classes A space-separated list of CSS classes
3078 * @param string $id An optional ID
3079 * @param array $attributes An array of other attributes to give the box.
3080 * @return string the HTML to output.
3082 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3083 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3087 * Outputs the opening section of a box.
3089 * @param string $classes A space-separated list of CSS classes
3090 * @param string $id An optional ID
3091 * @param array $attributes An array of other attributes to give the box.
3092 * @return string the HTML to output.
3094 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3095 $this->opencontainers
->push('box', html_writer
::end_tag('div'));
3096 $attributes['id'] = $id;
3097 $attributes['class'] = 'box py-3 ' . renderer_base
::prepare_classes($classes);
3098 return html_writer
::start_tag('div', $attributes);
3102 * Outputs the closing section of a box.
3104 * @return string the HTML to output.
3106 public function box_end() {
3107 return $this->opencontainers
->pop('box');
3111 * Outputs a container.
3113 * @param string $contents The contents of the box
3114 * @param string $classes A space-separated list of CSS classes
3115 * @param string $id An optional ID
3116 * @return string the HTML to output.
3118 public function container($contents, $classes = null, $id = null) {
3119 return $this->container_start($classes, $id) . $contents . $this->container_end();
3123 * Outputs the opening section of a container.
3125 * @param string $classes A space-separated list of CSS classes
3126 * @param string $id An optional ID
3127 * @return string the HTML to output.
3129 public function container_start($classes = null, $id = null) {
3130 $this->opencontainers
->push('container', html_writer
::end_tag('div'));
3131 return html_writer
::start_tag('div', array('id' => $id,
3132 'class' => renderer_base
::prepare_classes($classes)));
3136 * Outputs the closing section of a container.
3138 * @return string the HTML to output.
3140 public function container_end() {
3141 return $this->opencontainers
->pop('container');
3145 * Make nested HTML lists out of the items
3147 * The resulting list will look something like this:
3151 * <<li>><div class='tree_item parent'>(item contents)</div>
3153 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3159 * @param array $items
3160 * @param array $attrs html attributes passed to the top ofs the list
3161 * @return string HTML
3163 public function tree_block_contents($items, $attrs = array()) {
3164 // exit if empty, we don't want an empty ul element
3165 if (empty($items)) {
3168 // array of nested li elements
3170 foreach ($items as $item) {
3171 // this applies to the li item which contains all child lists too
3172 $content = $item->content($this);
3173 $liclasses = array($item->get_css_type());
3174 if (!$item->forceopen ||
(!$item->forceopen
&& $item->collapse
) ||
($item->children
->count()==0 && $item->nodetype
==navigation_node
::NODETYPE_BRANCH
)) {
3175 $liclasses[] = 'collapsed';
3177 if ($item->isactive
=== true) {
3178 $liclasses[] = 'current_branch';
3180 $liattr = array('class'=>join(' ',$liclasses));
3181 // class attribute on the div item which only contains the item content
3182 $divclasses = array('tree_item');
3183 if ($item->children
->count()>0 ||
$item->nodetype
==navigation_node
::NODETYPE_BRANCH
) {
3184 $divclasses[] = 'branch';
3186 $divclasses[] = 'leaf';
3188 if (!empty($item->classes
) && count($item->classes
)>0) {
3189 $divclasses[] = join(' ', $item->classes
);
3191 $divattr = array('class'=>join(' ', $divclasses));
3192 if (!empty($item->id
)) {
3193 $divattr['id'] = $item->id
;
3195 $content = html_writer
::tag('p', $content, $divattr) . $this->tree_block_contents($item->children
);
3196 if (!empty($item->preceedwithhr
) && $item->preceedwithhr
===true) {
3197 $content = html_writer
::empty_tag('hr') . $content;
3199 $content = html_writer
::tag('li', $content, $liattr);
3202 return html_writer
::tag('ul', implode("\n", $lis), $attrs);
3206 * Returns a search box.
3208 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3209 * @return string HTML with the search form hidden by default.
3211 public function search_box($id = false) {
3214 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3215 // result in an extra included file for each site, even the ones where global search
3217 if (empty($CFG->enableglobalsearch
) ||
!has_capability('moodle/search:query', context_system
::instance())) {
3224 // Needs to be cleaned, we use it for the input id.
3225 $id = clean_param($id, PARAM_ALPHANUMEXT
);
3228 // JS to animate the form.
3229 $this->page
->requires
->js_call_amd('core/search-input', 'init', array($id));
3231 $searchicon = html_writer
::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
3232 array('role' => 'button', 'tabindex' => 0));
3233 $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot
. '/search/index.php');
3234 $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
3235 'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id, 'class' => 'form-control');
3237 $contents = html_writer
::tag('label', get_string('enteryoursearchquery', 'search'),
3238 array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer
::empty_tag('input', $inputattrs);
3239 if ($this->page
->context
&& $this->page
->context
->contextlevel
!== CONTEXT_SYSTEM
) {
3240 $contents .= html_writer
::empty_tag('input', ['type' => 'hidden',
3241 'name' => 'context', 'value' => $this->page
->context
->id
]);
3243 $searchinput = html_writer
::tag('form', $contents, $formattrs);
3245 return html_writer
::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper nav-link', 'id' => $id));
3249 * Allow plugins to provide some content to be rendered in the navbar.
3250 * The plugin must define a PLUGIN_render_navbar_output function that returns
3251 * the HTML they wish to add to the navbar.
3253 * @return string HTML for the navbar
3255 public function navbar_plugin_output() {
3258 // Give subsystems an opportunity to inject extra html content. The callback
3259 // must always return a string containing valid html.
3260 foreach (\core_component
::get_core_subsystems() as $name => $path) {
3262 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3266 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3267 foreach ($pluginsfunction as $plugintype => $plugins) {
3268 foreach ($plugins as $pluginfunction) {
3269 $output .= $pluginfunction($this);
3278 * Construct a user menu, returning HTML that can be echoed out by a
3281 * @param stdClass $user A user object, usually $USER.
3282 * @param bool $withlinks true if a dropdown should be built.
3283 * @return string HTML fragment.
3285 public function user_menu($user = null, $withlinks = null) {
3287 require_once($CFG->dirroot
. '/user/lib.php');
3289 if (is_null($user)) {
3293 // Note: this behaviour is intended to match that of core_renderer::login_info,
3294 // but should not be considered to be good practice; layout options are
3295 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3296 if (is_null($withlinks)) {
3297 $withlinks = empty($this->page
->layout_options
['nologinlinks']);
3300 // Add a class for when $withlinks is false.
3301 $usermenuclasses = 'usermenu';
3303 $usermenuclasses .= ' withoutlinks';
3308 // If during initial install, return the empty return string.
3309 if (during_initial_install()) {
3313 $loginpage = $this->is_login_page();
3314 $loginurl = get_login_url();
3315 // If not logged in, show the typical not-logged-in string.
3316 if (!isloggedin()) {
3317 $returnstr = get_string('loggedinnot', 'moodle');
3319 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3321 return html_writer
::div(
3331 // If logged in as a guest user, show a string to that effect.
3332 if (isguestuser()) {
3333 $returnstr = get_string('loggedinasguest');
3334 if (!$loginpage && $withlinks) {
3335 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3338 return html_writer
::div(
3347 // Get some navigation opts.
3348 $opts = user_get_user_navigation_info($user, $this->page
);
3350 $avatarclasses = "avatars";
3351 $avatarcontents = html_writer
::span($opts->metadata
['useravatar'], 'avatar current');
3352 $usertextcontents = $opts->metadata
['userfullname'];
3355 if (!empty($opts->metadata
['asotheruser'])) {
3356 $avatarcontents .= html_writer
::span(
3357 $opts->metadata
['realuseravatar'],
3360 $usertextcontents = $opts->metadata
['realuserfullname'];
3361 $usertextcontents .= html_writer
::tag(
3367 $opts->metadata
['userfullname'],
3371 array('class' => 'meta viewingas')
3376 if (!empty($opts->metadata
['asotherrole'])) {
3377 $role = core_text
::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata
['rolename'])));
3378 $usertextcontents .= html_writer
::span(
3379 $opts->metadata
['rolename'],
3380 'meta role role-' . $role
3384 // User login failures.
3385 if (!empty($opts->metadata
['userloginfail'])) {
3386 $usertextcontents .= html_writer
::span(
3387 $opts->metadata
['userloginfail'],
3388 'meta loginfailures'
3393 if (!empty($opts->metadata
['asmnetuser'])) {
3394 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata
['mnetidprovidername'])));
3395 $usertextcontents .= html_writer
::span(
3396 $opts->metadata
['mnetidprovidername'],
3397 'meta mnet mnet-' . $mnet
3401 $returnstr .= html_writer
::span(
3402 html_writer
::span($usertextcontents, 'usertext mr-1') .
3403 html_writer
::span($avatarcontents, $avatarclasses),
3407 // Create a divider (well, a filler).
3408 $divider = new action_menu_filler();
3409 $divider->primary
= false;
3411 $am = new action_menu();
3412 $am->set_menu_trigger(
3415 $am->set_action_label(get_string('usermenu'));
3416 $am->set_alignment(action_menu
::TR
, action_menu
::BR
);
3417 $am->set_nowrap_on_items();
3419 $navitemcount = count($opts->navitems
);
3421 foreach ($opts->navitems
as $key => $value) {
3423 switch ($value->itemtype
) {
3425 // If the nav item is a divider, add one and skip link processing.
3430 // Silently skip invalid entries (should we post a notification?).
3434 // Process this as a link item.
3436 if (isset($value->pix
) && !empty($value->pix
)) {
3437 $pix = new pix_icon($value->pix
, '', null, array('class' => 'iconsmall'));
3438 } else if (isset($value->imgsrc
) && !empty($value->imgsrc
)) {
3439 $value->title
= html_writer
::img(
3442 array('class' => 'iconsmall')
3446 $al = new action_menu_link_secondary(
3450 array('class' => 'icon')
3452 if (!empty($value->titleidentifier
)) {
3453 $al->attributes
['data-title'] = $value->titleidentifier
;
3461 // Add dividers after the first item and before the last item.
3462 if ($idx == 1 ||
$idx == $navitemcount - 1) {
3468 return html_writer
::div(
3475 * Secure layout login info.
3479 public function secure_layout_login_info() {
3480 if (get_config('core', 'logininfoinsecurelayout')) {
3481 return $this->login_info(false);
3488 * Returns the language menu in the secure layout.
3490 * No custom menu items are passed though, such that it will render only the language selection.
3494 public function secure_layout_language_menu() {
3495 if (get_config('core', 'langmenuinsecurelayout')) {
3496 $custommenu = new custom_menu('', current_language());
3497 return $this->render_custom_menu($custommenu);
3504 * This renders the navbar.
3505 * Uses bootstrap compatible html.
3507 public function navbar() {
3508 return $this->render_from_template('core/navbar', $this->page
->navbar
);
3512 * Renders a breadcrumb navigation node object.
3514 * @param breadcrumb_navigation_node $item The navigation node to render.
3515 * @return string HTML fragment
3517 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node
$item) {
3519 if ($item->action
instanceof moodle_url
) {
3520 $content = $item->get_content();
3521 $title = $item->get_title();
3522 $attributes = array();
3523 $attributes['itemprop'] = 'url';
3524 if ($title !== '') {
3525 $attributes['title'] = $title;
3527 if ($item->hidden
) {
3528 $attributes['class'] = 'dimmed_text';
3530 if ($item->is_last()) {
3531 $attributes['aria-current'] = 'page';
3533 $content = html_writer
::tag('span', $content, array('itemprop' => 'title'));
3534 $content = html_writer
::link($item->action
, $content, $attributes);
3536 $attributes = array();
3537 $attributes['itemscope'] = '';
3538 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3539 $content = html_writer
::tag('span', $content, $attributes);
3542 $content = $this->render_navigation_node($item);
3548 * Renders a navigation node object.
3550 * @param navigation_node $item The navigation node to render.
3551 * @return string HTML fragment
3553 protected function render_navigation_node(navigation_node
$item) {
3554 $content = $item->get_content();
3555 $title = $item->get_title();
3556 if ($item->icon
instanceof renderable
&& !$item->hideicon
) {
3557 $icon = $this->render($item->icon
);
3558 $content = $icon.$content; // use CSS for spacing of icons
3560 if ($item->helpbutton
!== null) {
3561 $content = trim($item->helpbutton
).html_writer
::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3563 if ($content === '') {
3566 if ($item->action
instanceof action_link
) {
3567 $link = $item->action
;
3568 if ($item->hidden
) {
3569 $link->add_class('dimmed');
3571 if (!empty($content)) {
3572 // Providing there is content we will use that for the link content.
3573 $link->text
= $content;
3575 $content = $this->render($link);
3576 } else if ($item->action
instanceof moodle_url
) {
3577 $attributes = array();
3578 if ($title !== '') {
3579 $attributes['title'] = $title;
3581 if ($item->hidden
) {
3582 $attributes['class'] = 'dimmed_text';
3584 $content = html_writer
::link($item->action
, $content, $attributes);
3586 } else if (is_string($item->action
) ||
empty($item->action
)) {
3587 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3588 if ($title !== '') {
3589 $attributes['title'] = $title;
3591 if ($item->hidden
) {
3592 $attributes['class'] = 'dimmed_text';
3594 $content = html_writer
::tag('span', $content, $attributes);
3600 * Accessibility: Right arrow-like character is
3601 * used in the breadcrumb trail, course navigation menu
3602 * (previous/next activity), calendar, and search forum block.
3603 * If the theme does not set characters, appropriate defaults
3604 * are set automatically. Please DO NOT
3605 * use < > » - these are confusing for blind users.
3609 public function rarrow() {
3610 return $this->page
->theme
->rarrow
;
3614 * Accessibility: Left arrow-like character is
3615 * used in the breadcrumb trail, course navigation menu
3616 * (previous/next activity), calendar, and search forum block.
3617 * If the theme does not set characters, appropriate defaults
3618 * are set automatically. Please DO NOT
3619 * use < > » - these are confusing for blind users.
3623 public function larrow() {
3624 return $this->page
->theme
->larrow
;
3628 * Accessibility: Up arrow-like character is used in
3629 * the book heirarchical navigation.
3630 * If the theme does not set characters, appropriate defaults
3631 * are set automatically. Please DO NOT
3632 * use ^ - this is confusing for blind users.
3636 public function uarrow() {
3637 return $this->page
->theme
->uarrow
;
3641 * Accessibility: Down arrow-like character.
3642 * If the theme does not set characters, appropriate defaults
3643 * are set automatically.
3647 public function darrow() {
3648 return $this->page
->theme
->darrow
;
3652 * Returns the custom menu if one has been set
3654 * A custom menu can be configured by browsing to
3655 * Settings: Administration > Appearance > Themes > Theme settings
3656 * and then configuring the custommenu config setting as described.
3658 * Theme developers: DO NOT OVERRIDE! Please override function
3659 * {@link core_renderer::render_custom_menu()} instead.
3661 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3664 public function custom_menu($custommenuitems = '') {
3667 if (empty($custommenuitems) && !empty($CFG->custommenuitems
)) {
3668 $custommenuitems = $CFG->custommenuitems
;
3670 $custommenu = new custom_menu($custommenuitems, current_language());
3671 return $this->render_custom_menu($custommenu);
3675 * We want to show the custom menus as a list of links in the footer on small screens.
3676 * Just return the menu object exported so we can render it differently.
3678 public function custom_menu_flat() {
3680 $custommenuitems = '';
3682 if (empty($custommenuitems) && !empty($CFG->custommenuitems
)) {
3683 $custommenuitems = $CFG->custommenuitems
;
3685 $custommenu = new custom_menu($custommenuitems, current_language());
3686 $langs = get_string_manager()->get_list_of_translations();
3687 $haslangmenu = $this->lang_menu() != '';
3690 $strlang = get_string('language');
3691 $currentlang = current_language();
3692 if (isset($langs[$currentlang])) {
3693 $currentlang = $langs[$currentlang];
3695 $currentlang = $strlang;
3697 $this->language
= $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3698 foreach ($langs as $langtype => $langname) {
3699 $this->language
->add($langname, new moodle_url($this->page
->url
, array('lang' => $langtype)), $langname);
3703 return $custommenu->export_for_template($this);
3707 * Renders a custom menu object (located in outputcomponents.php)
3709 * The custom menu this method produces makes use of the YUI3 menunav widget
3710 * and requires very specific html elements and classes.
3712 * @staticvar int $menucount
3713 * @param custom_menu $menu
3716 protected function render_custom_menu(custom_menu
$menu) {
3719 $langs = get_string_manager()->get_list_of_translations();
3720 $haslangmenu = $this->lang_menu() != '';
3722 if (!$menu->has_children() && !$haslangmenu) {
3727 $strlang = get_string('language');
3728 $currentlang = current_language();
3729 if (isset($langs[$currentlang])) {
3730 $currentlang = $langs[$currentlang];
3732 $currentlang = $strlang;
3734 $this->language
= $menu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3735 foreach ($langs as $langtype => $langname) {
3736 $this->language
->add($langname, new moodle_url($this->page
->url
, array('lang' => $langtype)), $langname);
3741 foreach ($menu->get_children() as $item) {
3742 $context = $item->export_for_template($this);
3743 $content .= $this->render_from_template('core/custom_menu_item', $context);
3750 * Renders a custom menu node as part of a submenu
3752 * The custom menu this method produces makes use of the YUI3 menunav widget
3753 * and requires very specific html elements and classes.
3755 * @see core:renderer::render_custom_menu()
3757 * @staticvar int $submenucount
3758 * @param custom_menu_item $menunode
3761 protected function render_custom_menu_item(custom_menu_item
$menunode) {
3762 // Required to ensure we get unique trackable id's
3763 static $submenucount = 0;
3764 if ($menunode->has_children()) {
3765 // If the child has menus render it as a sub menu
3767 $content = html_writer
::start_tag('li');
3768 if ($menunode->get_url() !== null) {
3769 $url = $menunode->get_url();
3771 $url = '#cm_submenu_'.$submenucount;
3773 $content .= html_writer
::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3774 $content .= html_writer
::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3775 $content .= html_writer
::start_tag('div', array('class'=>'yui3-menu-content'));
3776 $content .= html_writer
::start_tag('ul');
3777 foreach ($menunode->get_children() as $menunode) {
3778 $content .= $this->render_custom_menu_item($menunode);
3780 $content .= html_writer
::end_tag('ul');
3781 $content .= html_writer
::end_tag('div');
3782 $content .= html_writer
::end_tag('div');
3783 $content .= html_writer
::end_tag('li');
3785 // The node doesn't have children so produce a final menuitem.
3786 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3788 if (preg_match("/^#+$/", $menunode->get_text())) {
3790 // This is a divider.
3791 $content = html_writer
::start_tag('li', array('class' => 'yui3-menuitem divider'));
3793 $content = html_writer
::start_tag(
3796 'class' => 'yui3-menuitem'
3799 if ($menunode->get_url() !== null) {
3800 $url = $menunode->get_url();
3804 $content .= html_writer
::link(
3806 $menunode->get_text(),
3807 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3810 $content .= html_writer
::end_tag('li');
3812 // Return the sub menu
3817 * Renders theme links for switching between default and other themes.
3821 protected function theme_switch_links() {
3823 $actualdevice = core_useragent
::get_device_type();
3824 $currentdevice = $this->page
->devicetypeinuse
;
3825 $switched = ($actualdevice != $currentdevice);
3827 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3828 // The user is using the a default device and hasn't switched so don't shown the switch
3834 $linktext = get_string('switchdevicerecommended');
3835 $devicetype = $actualdevice;
3837 $linktext = get_string('switchdevicedefault');
3838 $devicetype = 'default';
3840 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page
->url
, 'device' => $devicetype, 'sesskey' => sesskey()));
3842 $content = html_writer
::start_tag('div', array('id' => 'theme_switch_link'));
3843 $content .= html_writer
::link($linkurl, $linktext, array('rel' => 'nofollow'));
3844 $content .= html_writer
::end_tag('div');
3852 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3854 * Theme developers: In order to change how tabs are displayed please override functions
3855 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3857 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3858 * @param string|null $selected which tab to mark as selected, all parent tabs will
3859 * automatically be marked as activated
3860 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3861 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3864 public final function tabtree($tabs, $selected = null, $inactive = null) {
3865 return $this->render(new tabtree($tabs, $selected, $inactive));
3871 * @param tabtree $tabtree
3874 protected function render_tabtree(tabtree
$tabtree) {
3875 if (empty($tabtree->subtree
)) {
3878 $data = $tabtree->export_for_template($this);
3879 return $this->render_from_template('core/tabtree', $data);
3883 * Renders tabobject (part of tabtree)
3885 * This function is called from {@link core_renderer::render_tabtree()}
3886 * and also it calls itself when printing the $tabobject subtree recursively.
3888 * Property $tabobject->level indicates the number of row of tabs.
3890 * @param tabobject $tabobject
3891 * @return string HTML fragment
3893 protected function render_tabobject(tabobject
$tabobject) {
3896 // Print name of the current tab.
3897 if ($tabobject instanceof tabtree
) {
3898 // No name for tabtree root.
3899 } else if ($tabobject->inactive ||
$tabobject->activated ||
($tabobject->selected
&& !$tabobject->linkedwhenselected
)) {
3900 // Tab name without a link. The <a> tag is used for styling.
3901 $str .= html_writer
::tag('a', html_writer
::span($tabobject->text
), array('class' => 'nolink moodle-has-zindex'));
3903 // Tab name with a link.
3904 if (!($tabobject->link
instanceof moodle_url
)) {
3905 // backward compartibility when link was passed as quoted string
3906 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3908 $str .= html_writer
::link($tabobject->link
, html_writer
::span($tabobject->text
), array('title' => $tabobject->title
));
3912 if (empty($tabobject->subtree
)) {
3913 if ($tabobject->selected
) {
3914 $str .= html_writer
::tag('div', ' ', array('class' => 'tabrow'. ($tabobject->level +
1). ' empty'));
3920 if ($tabobject->level
== 0 ||
$tabobject->selected ||
$tabobject->activated
) {
3921 $str .= html_writer
::start_tag('ul', array('class' => 'tabrow'. $tabobject->level
));
3923 foreach ($tabobject->subtree
as $tab) {
3926 $liclass .= ' first';
3928 if ($cnt == count($tabobject->subtree
) - 1) {
3929 $liclass .= ' last';
3931 if ((empty($tab->subtree
)) && (!empty($tab->selected
))) {
3932 $liclass .= ' onerow';
3935 if ($tab->selected
) {
3936 $liclass .= ' here selected';
3937 } else if ($tab->activated
) {
3938 $liclass .= ' here active';
3941 // This will recursively call function render_tabobject() for each item in subtree.
3942 $str .= html_writer
::tag('li', $this->render($tab), array('class' => trim($liclass)));
3945 $str .= html_writer
::end_tag('ul');
3952 * Get the HTML for blocks in the given region.
3954 * @since Moodle 2.5.1 2.6
3955 * @param string $region The region to get HTML for.
3956 * @return string HTML.
3958 public function blocks($region, $classes = array(), $tag = 'aside') {
3959 $displayregion = $this->page
->apply_theme_region_manipulations($region);
3960 $classes = (array)$classes;
3961 $classes[] = 'block-region';
3962 $attributes = array(
3963 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3964 'class' => join(' ', $classes),
3965 'data-blockregion' => $displayregion,
3966 'data-droptarget' => '1'
3968 if ($this->page
->blocks
->region_has_content($displayregion, $this)) {
3969 $content = $this->blocks_for_region($displayregion);
3973 return html_writer
::tag($tag, $content, $attributes);
3977 * Renders a custom block region.
3979 * Use this method if you want to add an additional block region to the content of the page.
3980 * Please note this should only be used in special situations.
3981 * We want to leave the theme is control where ever possible!
3983 * This method must use the same method that the theme uses within its layout file.
3984 * As such it asks the theme what method it is using.
3985 * It can be one of two values, blocks or blocks_for_region (deprecated).
3987 * @param string $regionname The name of the custom region to add.
3988 * @return string HTML for the block region.
3990 public function custom_block_region($regionname) {
3991 if ($this->page
->theme
->get_block_render_method() === 'blocks') {
3992 return $this->blocks($regionname);
3994 return $this->blocks_for_region($regionname);
3999 * Returns the CSS classes to apply to the body tag.
4001 * @since Moodle 2.5.1 2.6
4002 * @param array $additionalclasses Any additional classes to apply.
4005 public function body_css_classes(array $additionalclasses = array()) {
4006 return $this->page
->bodyclasses
. ' ' . implode(' ', $additionalclasses);
4010 * The ID attribute to apply to the body tag.
4012 * @since Moodle 2.5.1 2.6
4015 public function body_id() {
4016 return $this->page
->bodyid
;
4020 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4022 * @since Moodle 2.5.1 2.6
4023 * @param string|array $additionalclasses Any additional classes to give the body tag,
4026 public function body_attributes($additionalclasses = array()) {
4027 if (!is_array($additionalclasses)) {
4028 $additionalclasses = explode(' ', $additionalclasses);
4030 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4034 * Gets HTML for the page heading.
4036 * @since Moodle 2.5.1 2.6
4037 * @param string $tag The tag to encase the heading in. h1 by default.
4038 * @return string HTML.
4040 public function page_heading($tag = 'h1') {
4041 return html_writer
::tag($tag, $this->page
->heading
);
4045 * Gets the HTML for the page heading button.
4047 * @since Moodle 2.5.1 2.6
4048 * @return string HTML.
4050 public function page_heading_button() {
4051 return $this->page
->button
;
4055 * Returns the Moodle docs link to use for this page.
4057 * @since Moodle 2.5.1 2.6
4058 * @param string $text
4061 public function page_doc_link($text = null) {
4062 if ($text === null) {
4063 $text = get_string('moodledocslink');
4065 $path = page_get_doc_link_path($this->page
);
4069 return $this->doc_link($path, $text);
4073 * Returns the page heading menu.
4075 * @since Moodle 2.5.1 2.6
4076 * @return string HTML.
4078 public function page_heading_menu() {
4079 return $this->page
->headingmenu
;
4083 * Returns the title to use on the page.
4085 * @since Moodle 2.5.1 2.6
4088 public function page_title() {
4089 return $this->page
->title
;
4093 * Returns the moodle_url for the favicon.
4095 * @since Moodle 2.5.1 2.6
4096 * @return moodle_url The moodle_url for the favicon
4098 public function favicon() {
4099 return $this->image_url('favicon', 'theme');
4103 * Renders preferences groups.
4105 * @param preferences_groups $renderable The renderable
4106 * @return string The output.
4108 public function render_preferences_groups(preferences_groups
$renderable) {
4109 return $this->render_from_template('core/preferences_groups', $renderable);
4113 * Renders preferences group.
4115 * @param preferences_group $renderable The renderable
4116 * @return string The output.
4118 public function render_preferences_group(preferences_group
$renderable) {
4120 $html .= html_writer
::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4121 $html .= $this->heading($renderable->title
, 3);
4122 $html .= html_writer
::start_tag('ul');
4123 foreach ($renderable->nodes
as $node) {
4124 if ($node->has_children()) {
4125 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER
);
4127 $html .= html_writer
::tag('li', $this->render($node));
4129 $html .= html_writer
::end_tag('ul');
4130 $html .= html_writer
::end_tag('div');
4134 public function context_header($headerinfo = null, $headinglevel = 1) {
4135 global $DB, $USER, $CFG, $SITE;
4136 require_once($CFG->dirroot
. '/user/lib.php');
4137 $context = $this->page
->context
;
4141 $userbuttons = null;
4143 // Make sure to use the heading if it has been set.
4144 if (isset($headerinfo['heading'])) {
4145 $heading = $headerinfo['heading'];
4147 $heading = $this->page
->heading
;
4150 // The user context currently has images and buttons. Other contexts may follow.
4151 if (isset($headerinfo['user']) ||
$context->contextlevel
== CONTEXT_USER
) {
4152 if (isset($headerinfo['user'])) {
4153 $user = $headerinfo['user'];
4155 // Look up the user information if it is not supplied.
4156 $user = $DB->get_record('user', array('id' => $context->instanceid
));
4159 // If the user context is set, then use that for capability checks.
4160 if (isset($headerinfo['usercontext'])) {
4161 $context = $headerinfo['usercontext'];
4164 // Only provide user information if the user is the current user, or a user which the current user can view.
4165 // When checking user_can_view_profile(), either:
4166 // If the page context is course, check the course context (from the page object) or;
4167 // If page context is NOT course, then check across all courses.
4168 $course = ($this->page
->context
->contextlevel
== CONTEXT_COURSE
) ?
$this->page
->course
: null;
4170 if (user_can_view_profile($user, $course)) {
4171 // Use the user's full name if the heading isn't set.
4172 if (empty($heading)) {
4173 $heading = fullname($user);
4176 $imagedata = $this->user_picture($user, array('size' => 100));
4178 // Check to see if we should be displaying a message button.
4179 if (!empty($CFG->messaging
) && has_capability('moodle/site:sendmessage', $context)) {
4180 $userbuttons = array(
4181 'messages' => array(
4182 'buttontype' => 'message',
4183 'title' => get_string('message', 'message'),
4184 'url' => new moodle_url('/message/index.php', array('id' => $user->id
)),
4185 'image' => 'message',
4186 'linkattributes' => \core_message\helper
::messageuser_link_params($user->id
),
4187 'page' => $this->page
4191 if ($USER->id
!= $user->id
) {
4192 $iscontact = \core_message\api
::is_contact($USER->id
, $user->id
);
4193 $contacttitle = $iscontact ?
'removefromyourcontacts' : 'addtoyourcontacts';
4194 $contacturlaction = $iscontact ?
'removecontact' : 'addcontact';
4195 $contactimage = $iscontact ?
'removecontact' : 'addcontact';
4196 $userbuttons['togglecontact'] = array(
4197 'buttontype' => 'togglecontact',
4198 'title' => get_string($contacttitle, 'message'),
4199 'url' => new moodle_url('/message/index.php', array(
4200 'user1' => $USER->id
,
4201 'user2' => $user->id
,
4202 $contacturlaction => $user->id
,
4203 'sesskey' => sesskey())
4205 'image' => $contactimage,
4206 'linkattributes' => \core_message\helper
::togglecontact_link_params($user, $iscontact),
4207 'page' => $this->page
4211 $this->page
->requires
->string_for_js('changesmadereallygoaway', 'moodle');
4218 if ($this->should_display_main_logo($headinglevel)) {
4219 $sitename = format_string($SITE->fullname
, true, ['context' => context_course
::instance(SITEID
)]);
4221 $html = html_writer
::div(
4222 html_writer
::empty_tag('img', [
4223 'src' => $this->get_logo_url(null, 150),
4224 'alt' => get_string('logoof', '', $sitename),
4225 'class' => 'img-fluid'
4230 if (!isset($heading)) {
4231 $html .= $this->heading($this->page
->heading
, $headinglevel, 'sr-only');
4233 $html .= $this->heading($heading, $headinglevel, 'sr-only');
4238 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4239 return $this->render_context_header($contextheader);
4243 * Renders the skip links for the page.
4245 * @param array $links List of skip links.
4246 * @return string HTML for the skip links.
4248 public function render_skip_links($links) {
4249 $context = [ 'links' => []];
4251 foreach ($links as $url => $text) {
4252 $context['links'][] = [ 'url' => $url, 'text' => $text];
4255 return $this->render_from_template('core/skip_links', $context);
4259 * Renders the header bar.
4261 * @param context_header $contextheader Header bar object.
4262 * @return string HTML for the header bar.
4264 protected function render_context_header(context_header
$contextheader) {
4266 // Generate the heading first and before everything else as we might have to do an early return.
4267 if (!isset($contextheader->heading
)) {
4268 $heading = $this->heading($this->page
->heading
, $contextheader->headinglevel
);
4270 $heading = $this->heading($contextheader->heading
, $contextheader->headinglevel
);
4273 $showheader = empty($this->page
->layout_options
['nocontextheader']);
4275 // Return the heading wrapped in an sr-only element so it is only visible to screen-readers.
4276 return html_writer
::div($heading, 'sr-only');
4279 // All the html stuff goes here.
4280 $html = html_writer
::start_div('page-context-header');
4283 if (isset($contextheader->imagedata
)) {
4284 // Header specific image.
4285 $html .= html_writer
::div($contextheader->imagedata
, 'page-header-image');
4289 $html .= html_writer
::tag('div', $heading, array('class' => 'page-header-headings'));
4292 if (isset($contextheader->additionalbuttons
)) {
4293 $html .= html_writer
::start_div('btn-group header-button-group');
4294 foreach ($contextheader->additionalbuttons
as $button) {
4295 if (!isset($button->page
)) {
4296 // Include js for messaging.
4297 if ($button['buttontype'] === 'togglecontact') {
4298 \core_message\helper
::togglecontact_requirejs();
4300 if ($button['buttontype'] === 'message') {
4301 \core_message\helper
::messageuser_requirejs();
4303 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4304 'class' => 'iconsmall',
4305 'role' => 'presentation'
4307 $image .= html_writer
::span($button['title'], 'header-button-title');
4309 $image = html_writer
::empty_tag('img', array(
4310 'src' => $button['formattedimage'],
4311 'role' => 'presentation'
4314 $html .= html_writer
::link($button['url'], html_writer
::tag('span', $image), $button['linkattributes']);
4316 $html .= html_writer
::end_div();
4318 $html .= html_writer
::end_div();
4324 * Wrapper for header elements.
4326 * @return string HTML to display the main header.
4328 public function full_header() {
4330 if ($this->page
->include_region_main_settings_in_header_actions() &&
4331 !$this->page
->blocks
->is_block_present('settings')) {
4332 // Only include the region main settings if the page has requested it and it doesn't already have
4333 // the settings block on it. The region main settings are included in the settings block and
4334 // duplicating the content causes behat failures.
4335 $this->page
->add_header_action(html_writer
::div(
4336 $this->region_main_settings_menu(),
4338 ['id' => 'region-main-settings-menu']
4342 $header = new stdClass();
4343 $header->settingsmenu
= $this->context_header_settings_menu();
4344 $header->contextheader
= $this->context_header();
4345 $header->hasnavbar
= empty($this->page
->layout_options
['nonavbar']);
4346 $header->navbar
= $this->navbar();
4347 $header->pageheadingbutton
= $this->page_heading_button();
4348 $header->courseheader
= $this->course_header();
4349 $header->headeractions
= $this->page
->get_header_actions();
4350 return $this->render_from_template('core/full_header', $header);
4354 * This is an optional menu that can be added to a layout by a theme. It contains the
4355 * menu for the course administration, only on the course main page.
4359 public function context_header_settings_menu() {
4360 $context = $this->page
->context
;
4361 $menu = new action_menu();
4363 $items = $this->page
->navbar
->get_items();
4364 $currentnode = end($items);
4366 $showcoursemenu = false;
4367 $showfrontpagemenu = false;
4368 $showusermenu = false;
4370 // We are on the course home page.
4371 if (($context->contextlevel
== CONTEXT_COURSE
) &&
4372 !empty($currentnode) &&
4373 ($currentnode->type
== navigation_node
::TYPE_COURSE ||
$currentnode->type
== navigation_node
::TYPE_SECTION
)) {
4374 $showcoursemenu = true;
4377 $courseformat = course_get_format($this->page
->course
);
4378 // This is a single activity course format, always show the course menu on the activity main page.
4379 if ($context->contextlevel
== CONTEXT_MODULE
&&
4380 !$courseformat->has_view_page()) {
4382 $this->page
->navigation
->initialise();
4383 $activenode = $this->page
->navigation
->find_active_node();
4384 // If the settings menu has been forced then show the menu.
4385 if ($this->page
->is_settings_menu_forced()) {
4386 $showcoursemenu = true;
4387 } else if (!empty($activenode) && ($activenode->type
== navigation_node
::TYPE_ACTIVITY ||
4388 $activenode->type
== navigation_node
::TYPE_RESOURCE
)) {
4390 // We only want to show the menu on the first page of the activity. This means
4391 // the breadcrumb has no additional nodes.
4392 if ($currentnode && ($currentnode->key
== $activenode->key
&& $currentnode->type
== $activenode->type
)) {
4393 $showcoursemenu = true;
4398 // This is the site front page.
4399 if ($context->contextlevel
== CONTEXT_COURSE
&&
4400 !empty($currentnode) &&
4401 $currentnode->key
=== 'home') {
4402 $showfrontpagemenu = true;
4405 // This is the user profile page.
4406 if ($context->contextlevel
== CONTEXT_USER
&&
4407 !empty($currentnode) &&
4408 ($currentnode->key
=== 'myprofile')) {
4409 $showusermenu = true;
4412 if ($showfrontpagemenu) {
4413 $settingsnode = $this->page
->settingsnav
->find('frontpage', navigation_node
::TYPE_SETTING
);
4414 if ($settingsnode) {
4415 // Build an action menu based on the visible nodes from this navigation tree.
4416 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4418 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4420 $text = get_string('morenavigationlinks');
4421 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page
->course
->id
));
4422 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4423 $menu->add_secondary_action($link);
4426 } else if ($showcoursemenu) {
4427 $settingsnode = $this->page
->settingsnav
->find('courseadmin', navigation_node
::TYPE_COURSE
);
4428 if ($settingsnode) {
4429 // Build an action menu based on the visible nodes from this navigation tree.
4430 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4432 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4434 $text = get_string('morenavigationlinks');
4435 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page
->course
->id
));
4436 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4437 $menu->add_secondary_action($link);
4440 } else if ($showusermenu) {
4441 // Get the course admin node from the settings navigation.
4442 $settingsnode = $this->page
->settingsnav
->find('useraccount', navigation_node
::TYPE_CONTAINER
);
4443 if ($settingsnode) {
4444 // Build an action menu based on the visible nodes from this navigation tree.
4445 $this->build_action_menu_from_navigation($menu, $settingsnode);
4449 return $this->render($menu);
4453 * Take a node in the nav tree and make an action menu out of it.
4454 * The links are injected in the action menu.
4456 * @param action_menu $menu
4457 * @param navigation_node $node
4458 * @param boolean $indent
4459 * @param boolean $onlytopleafnodes
4460 * @return boolean nodesskipped - True if nodes were skipped in building the menu
4462 protected function build_action_menu_from_navigation(action_menu
$menu,
4463 navigation_node
$node,
4465 $onlytopleafnodes = false) {
4467 // Build an action menu based on the visible nodes from this navigation tree.
4468 foreach ($node->children
as $menuitem) {
4469 if ($menuitem->display
) {
4470 if ($onlytopleafnodes && $menuitem->children
->count()) {
4474 if ($menuitem->action
) {
4475 if ($menuitem->action
instanceof action_link
) {
4476 $link = $menuitem->action
;
4477 // Give preference to setting icon over action icon.
4478 if (!empty($menuitem->icon
)) {
4479 $link->icon
= $menuitem->icon
;
4482 $link = new action_link($menuitem->action
, $menuitem->text
, null, null, $menuitem->icon
);
4485 if ($onlytopleafnodes) {
4489 $link = new action_link(new moodle_url('#'), $menuitem->text
, null, ['disabled' => true], $menuitem->icon
);
4492 $link->add_class('ml-4');
4494 if (!empty($menuitem->classes
)) {
4495 $link->add_class(implode(" ", $menuitem->classes
));
4498 $menu->add_secondary_action($link);
4499 $skipped = $skipped ||
$this->build_action_menu_from_navigation($menu, $menuitem, true);
4506 * This is an optional menu that can be added to a layout by a theme. It contains the
4507 * menu for the most specific thing from the settings block. E.g. Module administration.
4511 public function region_main_settings_menu() {
4512 $context = $this->page
->context
;
4513 $menu = new action_menu();
4515 if ($context->contextlevel
== CONTEXT_MODULE
) {
4517 $this->page
->navigation
->initialise();
4518 $node = $this->page
->navigation
->find_active_node();
4520 // If the settings menu has been forced then show the menu.
4521 if ($this->page
->is_settings_menu_forced()) {
4523 } else if (!empty($node) && ($node->type
== navigation_node
::TYPE_ACTIVITY ||
4524 $node->type
== navigation_node
::TYPE_RESOURCE
)) {
4526 $items = $this->page
->navbar
->get_items();
4527 $navbarnode = end($items);
4528 // We only want to show the menu on the first page of the activity. This means
4529 // the breadcrumb has no additional nodes.
4530 if ($navbarnode && ($navbarnode->key
=== $node->key
&& $navbarnode->type
== $node->type
)) {
4535 // Get the course admin node from the settings navigation.
4536 $node = $this->page
->settingsnav
->find('modulesettings', navigation_node
::TYPE_SETTING
);
4538 // Build an action menu based on the visible nodes from this navigation tree.
4539 $this->build_action_menu_from_navigation($menu, $node);
4543 } else if ($context->contextlevel
== CONTEXT_COURSECAT
) {
4544 // For course category context, show category settings menu, if we're on the course category page.
4545 if ($this->page
->pagetype
=== 'course-index-category') {
4546 $node = $this->page
->settingsnav
->find('categorysettings', navigation_node
::TYPE_CONTAINER
);
4548 // Build an action menu based on the visible nodes from this navigation tree.
4549 $this->build_action_menu_from_navigation($menu, $node);
4554 $items = $this->page
->navbar
->get_items();
4555 $navbarnode = end($items);
4557 if ($navbarnode && ($navbarnode->key
=== 'participants')) {
4558 $node = $this->page
->settingsnav
->find('users', navigation_node
::TYPE_CONTAINER
);
4560 // Build an action menu based on the visible nodes from this navigation tree.
4561 $this->build_action_menu_from_navigation($menu, $node);
4566 return $this->render($menu);
4570 * Displays the list of tags associated with an entry
4572 * @param array $tags list of instances of core_tag or stdClass
4573 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4574 * to use default, set to '' (empty string) to omit the label completely
4575 * @param string $classes additional classes for the enclosing div element
4576 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4577 * will be appended to the end, JS will toggle the rest of the tags
4578 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4579 * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
4582 public function tag_list($tags, $label = null, $classes = '', $limit = 10,
4583 $pagecontext = null, $accesshidelabel = false) {
4584 $list = new \core_tag\output\taglist
($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
4585 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4589 * Renders element for inline editing of any value
4591 * @param \core\output\inplace_editable $element
4594 public function render_inplace_editable(\core\output\inplace_editable
$element) {
4595 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4599 * Renders a bar chart.
4601 * @param \core\chart_bar $chart The chart.
4604 public function render_chart_bar(\core\chart_bar
$chart) {
4605 return $this->render_chart($chart);
4609 * Renders a line chart.
4611 * @param \core\chart_line $chart The chart.
4614 public function render_chart_line(\core\chart_line
$chart) {
4615 return $this->render_chart($chart);
4619 * Renders a pie chart.
4621 * @param \core\chart_pie $chart The chart.
4624 public function render_chart_pie(\core\chart_pie
$chart) {
4625 return $this->render_chart($chart);
4631 * @param \core\chart_base $chart The chart.
4632 * @param bool $withtable Whether to include a data table with the chart.
4635 public function render_chart(\core\chart_base
$chart, $withtable = true) {
4636 $chartdata = json_encode($chart);
4637 return $this->render_from_template('core/chart', (object) [
4638 'chartdata' => $chartdata,
4639 'withtable' => $withtable
4644 * Renders the login form.
4646 * @param \core_auth\output\login $form The renderable.
4649 public function render_login(\core_auth\output\login
$form) {
4652 $context = $form->export_for_template($this);
4654 // Override because rendering is not supported in template yet.
4655 if ($CFG->rememberusername
== 0) {
4656 $context->cookieshelpiconformatted
= $this->help_icon('cookiesenabledonlysession');
4658 $context->cookieshelpiconformatted
= $this->help_icon('cookiesenabled');
4660 $context->errorformatted
= $this->error_text($context->error
);
4661 $url = $this->get_logo_url();
4663 $url = $url->out(false);
4665 $context->logourl
= $url;
4666 $context->sitename
= format_string($SITE->fullname
, true,
4667 ['context' => context_course
::instance(SITEID
), "escape" => false]);
4669 return $this->render_from_template('core/loginform', $context);
4673 * Renders an mform element from a template.
4675 * @param HTML_QuickForm_element $element element
4676 * @param bool $required if input is required field
4677 * @param bool $advanced if input is an advanced field
4678 * @param string $error error message to display
4679 * @param bool $ingroup True if this element is rendered as part of a group
4680 * @return mixed string|bool
4682 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4683 $templatename = 'core_form/element-' . $element->getType();
4685 $templatename .= "-inline";
4688 // We call this to generate a file not found exception if there is no template.
4689 // We don't want to call export_for_template if there is no template.
4690 core\output\mustache_template_finder
::get_template_filepath($templatename);
4692 if ($element instanceof templatable
) {
4693 $elementcontext = $element->export_for_template($this);
4696 if (method_exists($element, 'getHelpButton')) {
4697 $helpbutton = $element->getHelpButton();
4699 $label = $element->getLabel();
4701 if (method_exists($element, 'getText')) {
4702 // There currently exists code that adds a form element with an empty label.
4703 // If this is the case then set the label to the description.
4704 if (empty($label)) {
4705 $label = $element->getText();
4707 $text = $element->getText();
4711 // Generate the form element wrapper ids and names to pass to the template.
4712 // This differs between group and non-group elements.
4713 if ($element->getType() === 'group') {
4715 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
4716 $elementcontext['wrapperid'] = $elementcontext['id'];
4718 // Ensure group elements pass through the group name as the element name.
4719 $elementcontext['name'] = $elementcontext['groupname'];
4721 // Non grouped element.
4722 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
4723 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
4727 'element' => $elementcontext,
4730 'required' => $required,
4731 'advanced' => $advanced,
4732 'helpbutton' => $helpbutton,
4735 return $this->render_from_template($templatename, $context);
4737 } catch (Exception
$e) {
4738 // No template for this element.
4744 * Render the login signup form into a nice template for the theme.
4746 * @param mform $form
4749 public function render_login_signup_form($form) {
4752 $context = $form->export_for_template($this);
4753 $url = $this->get_logo_url();
4755 $url = $url->out(false);
4757 $context['logourl'] = $url;
4758 $context['sitename'] = format_string($SITE->fullname
, true,
4759 ['context' => context_course
::instance(SITEID
), "escape" => false]);
4761 return $this->render_from_template('core/signup_form_layout', $context);
4765 * Render the verify age and location page into a nice template for the theme.
4767 * @param \core_auth\output\verify_age_location_page $page The renderable
4770 protected function render_verify_age_location_page($page) {
4771 $context = $page->export_for_template($this);
4773 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4777 * Render the digital minor contact information page into a nice template for the theme.
4779 * @param \core_auth\output\digital_minor_page $page The renderable
4782 protected function render_digital_minor_page($page) {
4783 $context = $page->export_for_template($this);
4785 return $this->render_from_template('core/auth_digital_minor_page', $context);
4789 * Renders a progress bar.
4791 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4793 * @param progress_bar $bar The bar.
4794 * @return string HTML fragment
4796 public function render_progress_bar(progress_bar
$bar) {
4797 $data = $bar->export_for_template($this);
4798 return $this->render_from_template('core/progress_bar', $data);
4802 * Renders element for a toggle-all checkbox.
4804 * @param \core\output\checkbox_toggleall $element
4807 public function render_checkbox_toggleall(\core\output\checkbox_toggleall
$element) {
4808 return $this->render_from_template($element->get_template(), $element->export_for_template($this));
4813 * A renderer that generates output for command-line scripts.
4815 * The implementation of this renderer is probably incomplete.
4817 * @copyright 2009 Tim Hunt
4818 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4823 class core_renderer_cli
extends core_renderer
{
4826 * Returns the page header.
4828 * @return string HTML fragment
4830 public function header() {
4831 return $this->page
->heading
. "\n";
4835 * Renders a Check API result
4837 * To aid in CLI consistency this status is NOT translated and the visual
4838 * width is always exactly 10 chars.
4840 * @param result $result
4841 * @return string HTML fragment
4843 protected function render_check_result(core\check\result
$result) {
4844 $status = $result->get_status();
4847 core\check\result
::NA
=> ' ' . cli_ansi_format('<colour:gray>' ) . ' NA ',
4848 core\check\result
::OK
=> ' ' . cli_ansi_format('<colour:green>') . ' OK ',
4849 core\check\result
::INFO
=> ' ' . cli_ansi_format('<colour:blue>' ) . ' INFO ',
4850 core\check\result
::UNKNOWN
=> ' ' . cli_ansi_format('<colour:grey>' ) . ' UNKNOWN ',
4851 core\check\result
::WARNING
=> ' ' . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
4852 core\check\result
::ERROR
=> ' ' . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
4853 core\check\result
::CRITICAL
=> '' . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
4855 $string = $labels[$status] . cli_ansi_format('<colour:normal>');
4860 * Renders a Check API result
4862 * @param result $result
4863 * @return string fragment
4865 public function check_result(core\check\result
$result) {
4866 return $this->render_check_result($result);
4870 * Returns a template fragment representing a Heading.
4872 * @param string $text The text of the heading
4873 * @param int $level The level of importance of the heading
4874 * @param string $classes A space-separated list of CSS classes
4875 * @param string $id An optional ID
4876 * @return string A template fragment for a heading
4878 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4882 return '=>' . $text;
4884 return '-->' . $text;
4891 * Returns a template fragment representing a fatal error.
4893 * @param string $message The message to output
4894 * @param string $moreinfourl URL where more info can be found about the error
4895 * @param string $link Link for the Continue button
4896 * @param array $backtrace The execution backtrace
4897 * @param string $debuginfo Debugging information
4898 * @return string A template fragment for a fatal error
4900 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4903 $output = "!!! $message !!!\n";
4905 if ($CFG->debugdeveloper
) {
4906 if (!empty($debuginfo)) {
4907 $output .= $this->notification($debuginfo, 'notifytiny');
4909 if (!empty($backtrace)) {
4910 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
4918 * Returns a template fragment representing a notification.
4920 * @param string $message The message to print out.
4921 * @param string $type The type of notification. See constants on \core\output\notification.
4922 * @return string A template fragment for a notification
4924 public function notification($message, $type = null) {
4925 $message = clean_text($message);
4926 if ($type === 'notifysuccess' ||
$type === 'success') {
4927 return "++ $message ++\n";
4929 return "!! $message !!\n";
4933 * There is no footer for a cli request, however we must override the
4934 * footer method to prevent the default footer.
4936 public function footer() {}
4939 * Render a notification (that is, a status message about something that has
4942 * @param \core\output\notification $notification the notification to print out
4943 * @return string plain text output
4945 public function render_notification(\core\output\notification
$notification) {
4946 return $this->notification($notification->get_message(), $notification->get_message_type());
4952 * A renderer that generates output for ajax scripts.
4954 * This renderer prevents accidental sends back only json
4955 * encoded error messages, all other output is ignored.
4957 * @copyright 2010 Petr Skoda
4958 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4963 class core_renderer_ajax
extends core_renderer
{
4966 * Returns a template fragment representing a fatal error.
4968 * @param string $message The message to output
4969 * @param string $moreinfourl URL where more info can be found about the error
4970 * @param string $link Link for the Continue button
4971 * @param array $backtrace The execution backtrace
4972 * @param string $debuginfo Debugging information
4973 * @return string A template fragment for a fatal error
4975 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4978 $this->page
->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
4980 $e = new stdClass();
4981 $e->error
= $message;
4982 $e->errorcode
= $errorcode;
4983 $e->stacktrace
= NULL;
4984 $e->debuginfo
= NULL;
4985 $e->reproductionlink
= NULL;
4986 if (!empty($CFG->debug
) and $CFG->debug
>= DEBUG_DEVELOPER
) {
4987 $link = (string) $link;
4989 $e->reproductionlink
= $link;
4991 if (!empty($debuginfo)) {
4992 $e->debuginfo
= $debuginfo;
4994 if (!empty($backtrace)) {
4995 $e->stacktrace
= format_backtrace($backtrace, true);
4999 return json_encode($e);
5003 * Used to display a notification.
5004 * For the AJAX notifications are discarded.
5006 * @param string $message The message to print out.
5007 * @param string $type The type of notification. See constants on \core\output\notification.
5009 public function notification($message, $type = null) {}
5012 * Used to display a redirection message.
5013 * AJAX redirections should not occur and as such redirection messages
5016 * @param moodle_url|string $encodedurl
5017 * @param string $message
5019 * @param bool $debugdisableredirect
5020 * @param string $messagetype The type of notification to show the message in.
5021 * See constants on \core\output\notification.
5023 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
5024 $messagetype = \core\output\notification
::NOTIFY_INFO
) {}
5027 * Prepares the start of an AJAX output.
5029 public function header() {
5030 // unfortunately YUI iframe upload does not support application/json
5031 if (!empty($_FILES)) {
5032 @header
('Content-type: text/plain; charset=utf-8');
5033 if (!core_useragent
::supports_json_contenttype()) {
5034 @header
('X-Content-Type-Options: nosniff');
5036 } else if (!core_useragent
::supports_json_contenttype()) {
5037 @header
('Content-type: text/plain; charset=utf-8');
5038 @header
('X-Content-Type-Options: nosniff');
5040 @header
('Content-type: application/json; charset=utf-8');
5043 // Headers to make it not cacheable and json
5044 @header
('Cache-Control: no-store, no-cache, must-revalidate');
5045 @header
('Cache-Control: post-check=0, pre-check=0', false);
5046 @header
('Pragma: no-cache');
5047 @header
('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
5048 @header
('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
5049 @header
('Accept-Ranges: none');
5053 * There is no footer for an AJAX request, however we must override the
5054 * footer method to prevent the default footer.
5056 public function footer() {}
5059 * No need for headers in an AJAX request... this should never happen.
5060 * @param string $text
5062 * @param string $classes
5065 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
5071 * The maintenance renderer.
5073 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
5074 * is running a maintenance related task.
5075 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
5080 * @copyright 2013 Sam Hemelryk
5081 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5083 class core_renderer_maintenance
extends core_renderer
{
5086 * Initialises the renderer instance.
5088 * @param moodle_page $page
5089 * @param string $target
5090 * @throws coding_exception
5092 public function __construct(moodle_page
$page, $target) {
5093 if ($target !== RENDERER_TARGET_MAINTENANCE ||
$page->pagelayout
!== 'maintenance') {
5094 throw new coding_exception('Invalid request for the maintenance renderer.');
5096 parent
::__construct($page, $target);
5100 * Does nothing. The maintenance renderer cannot produce blocks.
5102 * @param block_contents $bc
5103 * @param string $region
5106 public function block(block_contents
$bc, $region) {
5111 * Does nothing. The maintenance renderer cannot produce blocks.
5113 * @param string $region
5114 * @param array $classes
5115 * @param string $tag
5118 public function blocks($region, $classes = array(), $tag = 'aside') {
5123 * Does nothing. The maintenance renderer cannot produce blocks.
5125 * @param string $region
5128 public function blocks_for_region($region) {
5133 * Does nothing. The maintenance renderer cannot produce a course content header.
5135 * @param bool $onlyifnotcalledbefore
5138 public function course_content_header($onlyifnotcalledbefore = false) {
5143 * Does nothing. The maintenance renderer cannot produce a course content footer.
5145 * @param bool $onlyifnotcalledbefore
5148 public function course_content_footer($onlyifnotcalledbefore = false) {
5153 * Does nothing. The maintenance renderer cannot produce a course header.
5157 public function course_header() {
5162 * Does nothing. The maintenance renderer cannot produce a course footer.
5166 public function course_footer() {
5171 * Does nothing. The maintenance renderer cannot produce a custom menu.
5173 * @param string $custommenuitems
5176 public function custom_menu($custommenuitems = '') {
5181 * Does nothing. The maintenance renderer cannot produce a file picker.
5183 * @param array $options
5186 public function file_picker($options) {
5191 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
5196 public function htmllize_file_tree($dir) {
5202 * Overridden confirm message for upgrades.
5204 * @param string $message The question to ask the user
5205 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5206 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5207 * @return string HTML fragment
5209 public function confirm($message, $continue, $cancel) {
5210 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5211 // from any previous version of Moodle).
5212 if ($continue instanceof single_button
) {
5213 $continue->primary
= true;
5214 } else if (is_string($continue)) {
5215 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
5216 } else if ($continue instanceof moodle_url
) {
5217 $continue = new single_button($continue, get_string('continue'), 'post', true);
5219 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5220 ' (string/moodle_url) or a single_button instance.');
5223 if ($cancel instanceof single_button
) {
5225 } else if (is_string($cancel)) {
5226 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5227 } else if ($cancel instanceof moodle_url
) {
5228 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5230 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5231 ' (string/moodle_url) or a single_button instance.');
5234 $output = $this->box_start('generalbox', 'notice');
5235 $output .= html_writer
::tag('h4', get_string('confirm'));
5236 $output .= html_writer
::tag('p', $message);
5237 $output .= html_writer
::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
5238 $output .= $this->box_end();
5243 * Does nothing. The maintenance renderer does not support JS.
5245 * @param block_contents $bc
5247 public function init_block_hider_js(block_contents
$bc) {
5252 * Does nothing. The maintenance renderer cannot produce language menus.
5256 public function lang_menu() {
5261 * Does nothing. The maintenance renderer has no need for login information.
5263 * @param null $withlinks
5266 public function login_info($withlinks = null) {
5271 * Secure login info.
5275 public function secure_login_info() {
5276 return $this->login_info(false);
5280 * Does nothing. The maintenance renderer cannot produce user pictures.
5282 * @param stdClass $user
5283 * @param array $options
5286 public function user_picture(stdClass
$user, array $options = null) {