Merge branch 'MDL-67827-37' of git://github.com/andrewnicols/moodle into MOODLE_37_STABLE
[moodle.git] / lib / outputrenderers.php
blobb12c2e9e9dff00de049f3626377827cf07a9402e
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
21 * for an overview.
23 * Included in this file are the primary renderer classes:
24 * - renderer_base: The renderer outline class that all renderers
25 * should inherit from.
26 * - core_renderer: The standard HTML renderer.
27 * - core_renderer_cli: An adaption of the standard renderer for CLI scripts.
28 * - core_renderer_ajax: An adaption of the standard renderer for AJAX scripts.
29 * - plugin_renderer_base: A renderer class that should be extended by all
30 * plugin renderers.
32 * @package core
33 * @category output
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') || die();
40 /**
41 * Simple base class for Moodle renderers.
43 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
45 * Also has methods to facilitate generating HTML output.
47 * @copyright 2009 Tim Hunt
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 * @since Moodle 2.0
50 * @package core
51 * @category output
53 class renderer_base {
54 /**
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
59 /**
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
62 protected $page;
64 /**
65 * @var string The requested rendering target.
67 protected $target;
69 /**
70 * @var Mustache_Engine $mustache The mustache template compiler
72 private $mustache;
74 /**
75 * Return an instance of the mustache class.
77 * @since 2.9
78 * @return Mustache_Engine
80 protected function get_mustache() {
81 global $CFG;
83 if ($this->mustache === null) {
84 require_once("{$CFG->libdir}/filelib.php");
86 $themename = $this->page->theme->name;
87 $themerev = theme_get_revision();
89 // Create new localcache directory.
90 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
92 // Remove old localcache directories.
93 $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR);
94 foreach ($mustachecachedirs as $localcachedir) {
95 $cachedrev = [];
96 preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
97 $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
98 if ($cachedrev > 0 && $cachedrev < $themerev) {
99 fulldelete($localcachedir);
103 $loader = new \core\output\mustache_filesystem_loader();
104 $stringhelper = new \core\output\mustache_string_helper();
105 $quotehelper = new \core\output\mustache_quote_helper();
106 $jshelper = new \core\output\mustache_javascript_helper($this->page);
107 $pixhelper = new \core\output\mustache_pix_helper($this);
108 $shortentexthelper = new \core\output\mustache_shorten_text_helper();
109 $userdatehelper = new \core\output\mustache_user_date_helper();
111 // We only expose the variables that are exposed to JS templates.
112 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
114 $helpers = array('config' => $safeconfig,
115 'str' => array($stringhelper, 'str'),
116 'quote' => array($quotehelper, 'quote'),
117 'js' => array($jshelper, 'help'),
118 'pix' => array($pixhelper, 'pix'),
119 'shortentext' => array($shortentexthelper, 'shorten'),
120 'userdate' => array($userdatehelper, 'transform'),
123 $this->mustache = new \core\output\mustache_engine(array(
124 'cache' => $cachedir,
125 'escape' => 's',
126 'loader' => $loader,
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
131 // JS into the page.
132 'blacklistednestedhelpers' => ['js']));
136 return $this->mustache;
141 * Constructor
143 * The constructor takes two arguments. The first is the page that the renderer
144 * has been created to assist with, and the second is the target.
145 * The target is an additional identifier that can be used to load different
146 * renderers for different options.
148 * @param moodle_page $page the page we are doing output for.
149 * @param string $target one of rendering target constants
151 public function __construct(moodle_page $page, $target) {
152 $this->opencontainers = $page->opencontainers;
153 $this->page = $page;
154 $this->target = $target;
158 * Renders a template by name with the given context.
160 * The provided data needs to be array/stdClass made up of only simple types.
161 * Simple types are array,stdClass,bool,int,float,string
163 * @since 2.9
164 * @param array|stdClass $context Context containing data for the template.
165 * @return string|boolean
167 public function render_from_template($templatename, $context) {
168 static $templatecache = array();
169 $mustache = $this->get_mustache();
171 try {
172 // Grab a copy of the existing helper to be restored later.
173 $uniqidhelper = $mustache->getHelper('uniqid');
174 } catch (Mustache_Exception_UnknownHelperException $e) {
175 // Helper doesn't exist.
176 $uniqidhelper = null;
179 // Provide 1 random value that will not change within a template
180 // but will be different from template to template. This is useful for
181 // e.g. aria attributes that only work with id attributes and must be
182 // unique in a page.
183 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
184 if (isset($templatecache[$templatename])) {
185 $template = $templatecache[$templatename];
186 } else {
187 try {
188 $template = $mustache->loadTemplate($templatename);
189 $templatecache[$templatename] = $template;
190 } catch (Mustache_Exception_UnknownTemplateException $e) {
191 throw new moodle_exception('Unknown template: ' . $templatename);
195 $renderedtemplate = trim($template->render($context));
197 // If we had an existing uniqid helper then we need to restore it to allow
198 // handle nested calls of render_from_template.
199 if ($uniqidhelper) {
200 $mustache->addHelper('uniqid', $uniqidhelper);
203 return $renderedtemplate;
208 * Returns rendered widget.
210 * The provided widget needs to be an object that extends the renderable
211 * interface.
212 * If will then be rendered by a method based upon the classname for the widget.
213 * For instance a widget of class `crazywidget` will be rendered by a protected
214 * render_crazywidget method of this renderer.
215 * If no render_crazywidget method exists and crazywidget implements templatable,
216 * look for the 'crazywidget' template in the same component and render that.
218 * @param renderable $widget instance with renderable interface
219 * @return string
221 public function render(renderable $widget) {
222 $classparts = explode('\\', get_class($widget));
223 // Strip namespaces.
224 $classname = array_pop($classparts);
225 // Remove _renderable suffixes
226 $classname = preg_replace('/_renderable$/', '', $classname);
228 $rendermethod = 'render_'.$classname;
229 if (method_exists($this, $rendermethod)) {
230 return $this->$rendermethod($widget);
232 if ($widget instanceof templatable) {
233 $component = array_shift($classparts);
234 if (!$component) {
235 $component = 'core';
237 $template = $component . '/' . $classname;
238 $context = $widget->export_for_template($this);
239 return $this->render_from_template($template, $context);
241 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
245 * Adds a JS action for the element with the provided id.
247 * This method adds a JS event for the provided component action to the page
248 * and then returns the id that the event has been attached to.
249 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
251 * @param component_action $action
252 * @param string $id
253 * @return string id of element, either original submitted or random new if not supplied
255 public function add_action_handler(component_action $action, $id = null) {
256 if (!$id) {
257 $id = html_writer::random_id($action->event);
259 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
260 return $id;
264 * Returns true is output has already started, and false if not.
266 * @return boolean true if the header has been printed.
268 public function has_started() {
269 return $this->page->state >= moodle_page::STATE_IN_BODY;
273 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
275 * @param mixed $classes Space-separated string or array of classes
276 * @return string HTML class attribute value
278 public static function prepare_classes($classes) {
279 if (is_array($classes)) {
280 return implode(' ', array_unique($classes));
282 return $classes;
286 * Return the direct URL for an image from the pix folder.
288 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
290 * @deprecated since Moodle 3.3
291 * @param string $imagename the name of the icon.
292 * @param string $component specification of one plugin like in get_string()
293 * @return moodle_url
295 public function pix_url($imagename, $component = 'moodle') {
296 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
297 return $this->page->theme->image_url($imagename, $component);
301 * Return the moodle_url for an image.
303 * The exact image location and extension is determined
304 * automatically by searching for gif|png|jpg|jpeg, please
305 * note there can not be diferent images with the different
306 * extension. The imagename is for historical reasons
307 * a relative path name, it may be changed later for core
308 * images. It is recommended to not use subdirectories
309 * in plugin and theme pix directories.
311 * There are three types of images:
312 * 1/ theme images - stored in theme/mytheme/pix/,
313 * use component 'theme'
314 * 2/ core images - stored in /pix/,
315 * overridden via theme/mytheme/pix_core/
316 * 3/ plugin images - stored in mod/mymodule/pix,
317 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
318 * example: image_url('comment', 'mod_glossary')
320 * @param string $imagename the pathname of the image
321 * @param string $component full plugin name (aka component) or 'theme'
322 * @return moodle_url
324 public function image_url($imagename, $component = 'moodle') {
325 return $this->page->theme->image_url($imagename, $component);
329 * Return the site's logo URL, if any.
331 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
332 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
333 * @return moodle_url|false
335 public function get_logo_url($maxwidth = null, $maxheight = 200) {
336 global $CFG;
337 $logo = get_config('core_admin', 'logo');
338 if (empty($logo)) {
339 return false;
342 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
343 // It's not worth the overhead of detecting and serving 2 different images based on the device.
345 // Hide the requested size in the file path.
346 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
348 // Use $CFG->themerev to prevent browser caching when the file changes.
349 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
350 theme_get_revision(), $logo);
354 * Return the site's compact logo URL, if any.
356 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
357 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
358 * @return moodle_url|false
360 public function get_compact_logo_url($maxwidth = 100, $maxheight = 100) {
361 global $CFG;
362 $logo = get_config('core_admin', 'logocompact');
363 if (empty($logo)) {
364 return false;
367 // Hide the requested size in the file path.
368 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
370 // Use $CFG->themerev to prevent browser caching when the file changes.
371 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
372 theme_get_revision(), $logo);
376 * Whether we should display the logo in the navbar.
378 * We will when there are no main logos, and we have compact logo.
380 * @return bool
382 public function should_display_navbar_logo() {
383 $logo = $this->get_compact_logo_url();
384 return !empty($logo) && !$this->should_display_main_logo();
388 * Whether we should display the main logo.
390 * @param int $headinglevel
391 * @return bool
393 public function should_display_main_logo($headinglevel = 1) {
394 global $PAGE;
396 // Only render the logo if we're on the front page or login page and the we have a logo.
397 $logo = $this->get_logo_url();
398 if ($headinglevel == 1 && !empty($logo)) {
399 if ($PAGE->pagelayout == 'frontpage' || $PAGE->pagelayout == 'login') {
400 return true;
404 return false;
411 * Basis for all plugin renderers.
413 * @copyright Petr Skoda (skodak)
414 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
415 * @since Moodle 2.0
416 * @package core
417 * @category output
419 class plugin_renderer_base extends renderer_base {
422 * @var renderer_base|core_renderer A reference to the current renderer.
423 * The renderer provided here will be determined by the page but will in 90%
424 * of cases by the {@link core_renderer}
426 protected $output;
429 * Constructor method, calls the parent constructor
431 * @param moodle_page $page
432 * @param string $target one of rendering target constants
434 public function __construct(moodle_page $page, $target) {
435 if (empty($target) && $page->pagelayout === 'maintenance') {
436 // If the page is using the maintenance layout then we're going to force the target to maintenance.
437 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
438 // unavailable for this page layout.
439 $target = RENDERER_TARGET_MAINTENANCE;
441 $this->output = $page->get_renderer('core', null, $target);
442 parent::__construct($page, $target);
446 * Renders the provided widget and returns the HTML to display it.
448 * @param renderable $widget instance with renderable interface
449 * @return string
451 public function render(renderable $widget) {
452 $classname = get_class($widget);
453 // Strip namespaces.
454 $classname = preg_replace('/^.*\\\/', '', $classname);
455 // Keep a copy at this point, we may need to look for a deprecated method.
456 $deprecatedmethod = 'render_'.$classname;
457 // Remove _renderable suffixes
458 $classname = preg_replace('/_renderable$/', '', $classname);
460 $rendermethod = 'render_'.$classname;
461 if (method_exists($this, $rendermethod)) {
462 return $this->$rendermethod($widget);
464 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
465 // This is exactly where we don't want to be.
466 // If you have arrived here you have a renderable component within your plugin that has the name
467 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
468 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
469 // and the _renderable suffix now gets removed when looking for a render method.
470 // You need to change your renderers render_blah_renderable to render_blah.
471 // Until you do this it will not be possible for a theme to override the renderer to override your method.
472 // Please do it ASAP.
473 static $debugged = array();
474 if (!isset($debugged[$deprecatedmethod])) {
475 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
476 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
477 $debugged[$deprecatedmethod] = true;
479 return $this->$deprecatedmethod($widget);
481 // pass to core renderer if method not found here
482 return $this->output->render($widget);
486 * Magic method used to pass calls otherwise meant for the standard renderer
487 * to it to ensure we don't go causing unnecessary grief.
489 * @param string $method
490 * @param array $arguments
491 * @return mixed
493 public function __call($method, $arguments) {
494 if (method_exists('renderer_base', $method)) {
495 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
497 if (method_exists($this->output, $method)) {
498 return call_user_func_array(array($this->output, $method), $arguments);
499 } else {
500 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
507 * The standard implementation of the core_renderer interface.
509 * @copyright 2009 Tim Hunt
510 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
511 * @since Moodle 2.0
512 * @package core
513 * @category output
515 class core_renderer extends renderer_base {
517 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
518 * in layout files instead.
519 * @deprecated
520 * @var string used in {@link core_renderer::header()}.
522 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
525 * @var string Used to pass information from {@link core_renderer::doctype()} to
526 * {@link core_renderer::standard_head_html()}.
528 protected $contenttype;
531 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
532 * with {@link core_renderer::header()}.
534 protected $metarefreshtag = '';
537 * @var string Unique token for the closing HTML
539 protected $unique_end_html_token;
542 * @var string Unique token for performance information
544 protected $unique_performance_info_token;
547 * @var string Unique token for the main content.
549 protected $unique_main_content_token;
551 /** @var custom_menu_item language The language menu if created */
552 protected $language = null;
555 * Constructor
557 * @param moodle_page $page the page we are doing output for.
558 * @param string $target one of rendering target constants
560 public function __construct(moodle_page $page, $target) {
561 $this->opencontainers = $page->opencontainers;
562 $this->page = $page;
563 $this->target = $target;
565 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
566 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
567 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
571 * Get the DOCTYPE declaration that should be used with this page. Designed to
572 * be called in theme layout.php files.
574 * @return string the DOCTYPE declaration that should be used.
576 public function doctype() {
577 if ($this->page->theme->doctype === 'html5') {
578 $this->contenttype = 'text/html; charset=utf-8';
579 return "<!DOCTYPE html>\n";
581 } else if ($this->page->theme->doctype === 'xhtml5') {
582 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
583 return "<!DOCTYPE html>\n";
585 } else {
586 // legacy xhtml 1.0
587 $this->contenttype = 'text/html; charset=utf-8';
588 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
593 * The attributes that should be added to the <html> tag. Designed to
594 * be called in theme layout.php files.
596 * @return string HTML fragment.
598 public function htmlattributes() {
599 $return = get_html_lang(true);
600 $attributes = array();
601 if ($this->page->theme->doctype !== 'html5') {
602 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
605 // Give plugins an opportunity to add things like xml namespaces to the html element.
606 // This function should return an array of html attribute names => values.
607 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
608 foreach ($pluginswithfunction as $plugins) {
609 foreach ($plugins as $function) {
610 $newattrs = $function();
611 unset($newattrs['dir']);
612 unset($newattrs['lang']);
613 unset($newattrs['xmlns']);
614 unset($newattrs['xml:lang']);
615 $attributes += $newattrs;
619 foreach ($attributes as $key => $val) {
620 $val = s($val);
621 $return .= " $key=\"$val\"";
624 return $return;
628 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
629 * that should be included in the <head> tag. Designed to be called in theme
630 * layout.php files.
632 * @return string HTML fragment.
634 public function standard_head_html() {
635 global $CFG, $SESSION, $SITE, $PAGE;
637 // Before we output any content, we need to ensure that certain
638 // page components are set up.
640 // Blocks must be set up early as they may require javascript which
641 // has to be included in the page header before output is created.
642 foreach ($this->page->blocks->get_regions() as $region) {
643 $this->page->blocks->ensure_content_created($region, $this);
646 $output = '';
648 // Give plugins an opportunity to add any head elements. The callback
649 // must always return a string containing valid html head content.
650 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
651 foreach ($pluginswithfunction as $plugins) {
652 foreach ($plugins as $function) {
653 $output .= $function();
657 // Allow a url_rewrite plugin to setup any dynamic head content.
658 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
659 $class = $CFG->urlrewriteclass;
660 $output .= $class::html_head_setup();
663 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
664 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
665 // This is only set by the {@link redirect()} method
666 $output .= $this->metarefreshtag;
668 // Check if a periodic refresh delay has been set and make sure we arn't
669 // already meta refreshing
670 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
671 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
674 // Set up help link popups for all links with the helptooltip class
675 $this->page->requires->js_init_call('M.util.help_popups.setup');
677 $focus = $this->page->focuscontrol;
678 if (!empty($focus)) {
679 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
680 // This is a horrifically bad way to handle focus but it is passed in
681 // through messy formslib::moodleform
682 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
683 } else if (strpos($focus, '.')!==false) {
684 // Old style of focus, bad way to do it
685 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);
686 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
687 } else {
688 // Focus element with given id
689 $this->page->requires->js_function_call('focuscontrol', array($focus));
693 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
694 // any other custom CSS can not be overridden via themes and is highly discouraged
695 $urls = $this->page->theme->css_urls($this->page);
696 foreach ($urls as $url) {
697 $this->page->requires->css_theme($url);
700 // Get the theme javascript head and footer
701 if ($jsurl = $this->page->theme->javascript_url(true)) {
702 $this->page->requires->js($jsurl, true);
704 if ($jsurl = $this->page->theme->javascript_url(false)) {
705 $this->page->requires->js($jsurl);
708 // Get any HTML from the page_requirements_manager.
709 $output .= $this->page->requires->get_head_code($this->page, $this);
711 // List alternate versions.
712 foreach ($this->page->alternateversions as $type => $alt) {
713 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
714 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
717 // Add noindex tag if relevant page and setting applied.
718 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
719 $loginpages = array('login-index', 'login-signup');
720 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
721 if (!isset($CFG->additionalhtmlhead)) {
722 $CFG->additionalhtmlhead = '';
724 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
727 if (!empty($CFG->additionalhtmlhead)) {
728 $output .= "\n".$CFG->additionalhtmlhead;
731 if ($PAGE->pagelayout == 'frontpage') {
732 $summary = s(strip_tags(format_text($SITE->summary, FORMAT_HTML)));
733 if (!empty($summary)) {
734 $output .= "<meta name=\"description\" content=\"$summary\" />\n";
738 return $output;
742 * The standard tags (typically skip links) that should be output just inside
743 * the start of the <body> tag. Designed to be called in theme layout.php files.
745 * @return string HTML fragment.
747 public function standard_top_of_body_html() {
748 global $CFG;
749 $output = $this->page->requires->get_top_of_body_code($this);
750 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
751 $output .= "\n".$CFG->additionalhtmltopofbody;
754 // Give subsystems an opportunity to inject extra html content. The callback
755 // must always return a string containing valid html.
756 foreach (\core_component::get_core_subsystems() as $name => $path) {
757 if ($path) {
758 $output .= component_callback($name, 'before_standard_top_of_body_html', [], '');
762 // Give plugins an opportunity to inject extra html content. The callback
763 // must always return a string containing valid html.
764 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
765 foreach ($pluginswithfunction as $plugins) {
766 foreach ($plugins as $function) {
767 $output .= $function();
771 $output .= $this->maintenance_warning();
773 return $output;
777 * Scheduled maintenance warning message.
779 * Note: This is a nasty hack to display maintenance notice, this should be moved
780 * to some general notification area once we have it.
782 * @return string
784 public function maintenance_warning() {
785 global $CFG;
787 $output = '';
788 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
789 $timeleft = $CFG->maintenance_later - time();
790 // If timeleft less than 30 sec, set the class on block to error to highlight.
791 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
792 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-a-1 alert');
793 $a = new stdClass();
794 $a->hour = (int)($timeleft / 3600);
795 $a->min = (int)(($timeleft / 60) % 60);
796 $a->sec = (int)($timeleft % 60);
797 if ($a->hour > 0) {
798 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
799 } else {
800 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
803 $output .= $this->box_end();
804 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
805 array(array('timeleftinsec' => $timeleft)));
806 $this->page->requires->strings_for_js(
807 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
808 'admin');
810 return $output;
814 * The standard tags (typically performance information and validation links,
815 * if we are in developer debug mode) that should be output in the footer area
816 * of the page. Designed to be called in theme layout.php files.
818 * @return string HTML fragment.
820 public function standard_footer_html() {
821 global $CFG, $SCRIPT;
823 $output = '';
824 if (during_initial_install()) {
825 // Debugging info can not work before install is finished,
826 // in any case we do not want any links during installation!
827 return $output;
830 // Give plugins an opportunity to add any footer elements.
831 // The callback must always return a string containing valid html footer content.
832 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
833 foreach ($pluginswithfunction as $plugins) {
834 foreach ($plugins as $function) {
835 $output .= $function();
839 // This function is normally called from a layout.php file in {@link core_renderer::header()}
840 // but some of the content won't be known until later, so we return a placeholder
841 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
842 $output .= $this->unique_performance_info_token;
843 if ($this->page->devicetypeinuse == 'legacy') {
844 // The legacy theme is in use print the notification
845 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
848 // Get links to switch device types (only shown for users not on a default device)
849 $output .= $this->theme_switch_links();
851 if (!empty($CFG->debugpageinfo)) {
852 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
853 $this->page->debug_summary()) . '</div>';
855 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
856 // Add link to profiling report if necessary
857 if (function_exists('profiling_is_running') && profiling_is_running()) {
858 $txt = get_string('profiledscript', 'admin');
859 $title = get_string('profiledscriptview', 'admin');
860 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
861 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
862 $output .= '<div class="profilingfooter">' . $link . '</div>';
864 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
865 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
866 $output .= '<div class="purgecaches">' .
867 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
869 if (!empty($CFG->debugvalidators)) {
870 // NOTE: this is not a nice hack, $PAGE->url is not always accurate and $FULLME neither, it is not a bug if it fails. --skodak
871 $output .= '<div class="validators"><ul class="list-unstyled ml-1">
872 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
873 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
874 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&amp;warnp2n3e=1&amp;url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
875 </ul></div>';
877 return $output;
881 * Returns standard main content placeholder.
882 * Designed to be called in theme layout.php files.
884 * @return string HTML fragment.
886 public function main_content() {
887 // This is here because it is the only place we can inject the "main" role over the entire main content area
888 // without requiring all theme's to manually do it, and without creating yet another thing people need to
889 // remember in the theme.
890 // This is an unfortunate hack. DO NO EVER add anything more here.
891 // DO NOT add classes.
892 // DO NOT add an id.
893 return '<div role="main">'.$this->unique_main_content_token.'</div>';
897 * Returns standard navigation between activities in a course.
899 * @return string the navigation HTML.
901 public function activity_navigation() {
902 // First we should check if we want to add navigation.
903 $context = $this->page->context;
904 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
905 || $context->contextlevel != CONTEXT_MODULE) {
906 return '';
909 // If the activity is in stealth mode, show no links.
910 if ($this->page->cm->is_stealth()) {
911 return '';
914 // Get a list of all the activities in the course.
915 $course = $this->page->cm->get_course();
916 $modules = get_fast_modinfo($course->id)->get_cms();
918 // Put the modules into an array in order by the position they are shown in the course.
919 $mods = [];
920 $activitylist = [];
921 foreach ($modules as $module) {
922 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
923 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
924 continue;
926 $mods[$module->id] = $module;
928 // No need to add the current module to the list for the activity dropdown menu.
929 if ($module->id == $this->page->cm->id) {
930 continue;
932 // Module name.
933 $modname = $module->get_formatted_name();
934 // Display the hidden text if necessary.
935 if (!$module->visible) {
936 $modname .= ' ' . get_string('hiddenwithbrackets');
938 // Module URL.
939 $linkurl = new moodle_url($module->url, array('forceview' => 1));
940 // Add module URL (as key) and name (as value) to the activity list array.
941 $activitylist[$linkurl->out(false)] = $modname;
944 $nummods = count($mods);
946 // If there is only one mod then do nothing.
947 if ($nummods == 1) {
948 return '';
951 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
952 $modids = array_keys($mods);
954 // Get the position in the array of the course module we are viewing.
955 $position = array_search($this->page->cm->id, $modids);
957 $prevmod = null;
958 $nextmod = null;
960 // Check if we have a previous mod to show.
961 if ($position > 0) {
962 $prevmod = $mods[$modids[$position - 1]];
965 // Check if we have a next mod to show.
966 if ($position < ($nummods - 1)) {
967 $nextmod = $mods[$modids[$position + 1]];
970 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
971 $renderer = $this->page->get_renderer('core', 'course');
972 return $renderer->render($activitynav);
976 * The standard tags (typically script tags that are not needed earlier) that
977 * should be output after everything else. Designed to be called in theme layout.php files.
979 * @return string HTML fragment.
981 public function standard_end_of_body_html() {
982 global $CFG;
984 // This function is normally called from a layout.php file in {@link core_renderer::header()}
985 // but some of the content won't be known until later, so we return a placeholder
986 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
987 $output = '';
988 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
989 $output .= "\n".$CFG->additionalhtmlfooter;
991 $output .= $this->unique_end_html_token;
992 return $output;
996 * The standard HTML that should be output just before the <footer> tag.
997 * Designed to be called in theme layout.php files.
999 * @return string HTML fragment.
1001 public function standard_after_main_region_html() {
1002 global $CFG;
1003 $output = '';
1004 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlbottomofbody)) {
1005 $output .= "\n".$CFG->additionalhtmlbottomofbody;
1008 // Give subsystems an opportunity to inject extra html content. The callback
1009 // must always return a string containing valid html.
1010 foreach (\core_component::get_core_subsystems() as $name => $path) {
1011 if ($path) {
1012 $output .= component_callback($name, 'standard_after_main_region_html', [], '');
1016 // Give plugins an opportunity to inject extra html content. The callback
1017 // must always return a string containing valid html.
1018 $pluginswithfunction = get_plugins_with_function('standard_after_main_region_html', 'lib.php');
1019 foreach ($pluginswithfunction as $plugins) {
1020 foreach ($plugins as $function) {
1021 $output .= $function();
1025 return $output;
1029 * Return the standard string that says whether you are logged in (and switched
1030 * roles/logged in as another user).
1031 * @param bool $withlinks if false, then don't include any links in the HTML produced.
1032 * If not set, the default is the nologinlinks option from the theme config.php file,
1033 * and if that is not set, then links are included.
1034 * @return string HTML fragment.
1036 public function login_info($withlinks = null) {
1037 global $USER, $CFG, $DB, $SESSION;
1039 if (during_initial_install()) {
1040 return '';
1043 if (is_null($withlinks)) {
1044 $withlinks = empty($this->page->layout_options['nologinlinks']);
1047 $course = $this->page->course;
1048 if (\core\session\manager::is_loggedinas()) {
1049 $realuser = \core\session\manager::get_realuser();
1050 $fullname = fullname($realuser, true);
1051 if ($withlinks) {
1052 $loginastitle = get_string('loginas');
1053 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
1054 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
1055 } else {
1056 $realuserinfo = " [$fullname] ";
1058 } else {
1059 $realuserinfo = '';
1062 $loginpage = $this->is_login_page();
1063 $loginurl = get_login_url();
1065 if (empty($course->id)) {
1066 // $course->id is not defined during installation
1067 return '';
1068 } else if (isloggedin()) {
1069 $context = context_course::instance($course->id);
1071 $fullname = fullname($USER, true);
1072 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
1073 if ($withlinks) {
1074 $linktitle = get_string('viewprofile');
1075 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
1076 } else {
1077 $username = $fullname;
1079 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
1080 if ($withlinks) {
1081 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1082 } else {
1083 $username .= " from {$idprovider->name}";
1086 if (isguestuser()) {
1087 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1088 if (!$loginpage && $withlinks) {
1089 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1091 } else if (is_role_switched($course->id)) { // Has switched roles
1092 $rolename = '';
1093 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1094 $rolename = ': '.role_get_name($role, $context);
1096 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1097 if ($withlinks) {
1098 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1099 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1101 } else {
1102 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1103 if ($withlinks) {
1104 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1107 } else {
1108 $loggedinas = get_string('loggedinnot', 'moodle');
1109 if (!$loginpage && $withlinks) {
1110 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1114 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1116 if (isset($SESSION->justloggedin)) {
1117 unset($SESSION->justloggedin);
1118 if (!empty($CFG->displayloginfailures)) {
1119 if (!isguestuser()) {
1120 // Include this file only when required.
1121 require_once($CFG->dirroot . '/user/lib.php');
1122 if ($count = user_count_login_failures($USER)) {
1123 $loggedinas .= '<div class="loginfailures">';
1124 $a = new stdClass();
1125 $a->attempts = $count;
1126 $loggedinas .= get_string('failedloginattempts', '', $a);
1127 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1128 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1129 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1131 $loggedinas .= '</div>';
1137 return $loggedinas;
1141 * Check whether the current page is a login page.
1143 * @since Moodle 2.9
1144 * @return bool
1146 protected function is_login_page() {
1147 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1148 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1149 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1150 return in_array(
1151 $this->page->url->out_as_local_url(false, array()),
1152 array(
1153 '/login/index.php',
1154 '/login/forgot_password.php',
1160 * Return the 'back' link that normally appears in the footer.
1162 * @return string HTML fragment.
1164 public function home_link() {
1165 global $CFG, $SITE;
1167 if ($this->page->pagetype == 'site-index') {
1168 // Special case for site home page - please do not remove
1169 return '<div class="sitelink">' .
1170 '<a title="Moodle" href="http://moodle.org/">' .
1171 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1173 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1174 // Special case for during install/upgrade.
1175 return '<div class="sitelink">'.
1176 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1177 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1179 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1180 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1181 get_string('home') . '</a></div>';
1183 } else {
1184 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1185 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1190 * Redirects the user by any means possible given the current state
1192 * This function should not be called directly, it should always be called using
1193 * the redirect function in lib/weblib.php
1195 * The redirect function should really only be called before page output has started
1196 * however it will allow itself to be called during the state STATE_IN_BODY
1198 * @param string $encodedurl The URL to send to encoded if required
1199 * @param string $message The message to display to the user if any
1200 * @param int $delay The delay before redirecting a user, if $message has been
1201 * set this is a requirement and defaults to 3, set to 0 no delay
1202 * @param boolean $debugdisableredirect this redirect has been disabled for
1203 * debugging purposes. Display a message that explains, and don't
1204 * trigger the redirect.
1205 * @param string $messagetype The type of notification to show the message in.
1206 * See constants on \core\output\notification.
1207 * @return string The HTML to display to the user before dying, may contain
1208 * meta refresh, javascript refresh, and may have set header redirects
1210 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1211 $messagetype = \core\output\notification::NOTIFY_INFO) {
1212 global $CFG;
1213 $url = str_replace('&amp;', '&', $encodedurl);
1215 switch ($this->page->state) {
1216 case moodle_page::STATE_BEFORE_HEADER :
1217 // No output yet it is safe to delivery the full arsenal of redirect methods
1218 if (!$debugdisableredirect) {
1219 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1220 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1221 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1223 $output = $this->header();
1224 break;
1225 case moodle_page::STATE_PRINTING_HEADER :
1226 // We should hopefully never get here
1227 throw new coding_exception('You cannot redirect while printing the page header');
1228 break;
1229 case moodle_page::STATE_IN_BODY :
1230 // We really shouldn't be here but we can deal with this
1231 debugging("You should really redirect before you start page output");
1232 if (!$debugdisableredirect) {
1233 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1235 $output = $this->opencontainers->pop_all_but_last();
1236 break;
1237 case moodle_page::STATE_DONE :
1238 // Too late to be calling redirect now
1239 throw new coding_exception('You cannot redirect after the entire page has been generated');
1240 break;
1242 $output .= $this->notification($message, $messagetype);
1243 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1244 if ($debugdisableredirect) {
1245 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1247 $output .= $this->footer();
1248 return $output;
1252 * Start output by sending the HTTP headers, and printing the HTML <head>
1253 * and the start of the <body>.
1255 * To control what is printed, you should set properties on $PAGE. If you
1256 * are familiar with the old {@link print_header()} function from Moodle 1.9
1257 * you will find that there are properties on $PAGE that correspond to most
1258 * of the old parameters to could be passed to print_header.
1260 * Not that, in due course, the remaining $navigation, $menu parameters here
1261 * will be replaced by more properties of $PAGE, but that is still to do.
1263 * @return string HTML that you must output this, preferably immediately.
1265 public function header() {
1266 global $USER, $CFG, $SESSION;
1268 // Give plugins an opportunity touch things before the http headers are sent
1269 // such as adding additional headers. The return value is ignored.
1270 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1271 foreach ($pluginswithfunction as $plugins) {
1272 foreach ($plugins as $function) {
1273 $function();
1277 if (\core\session\manager::is_loggedinas()) {
1278 $this->page->add_body_class('userloggedinas');
1281 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1282 require_once($CFG->dirroot . '/user/lib.php');
1283 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1284 if ($count = user_count_login_failures($USER, false)) {
1285 $this->page->add_body_class('loginfailures');
1289 // If the user is logged in, and we're not in initial install,
1290 // check to see if the user is role-switched and add the appropriate
1291 // CSS class to the body element.
1292 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1293 $this->page->add_body_class('userswitchedrole');
1296 // Give themes a chance to init/alter the page object.
1297 $this->page->theme->init_page($this->page);
1299 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1301 // Find the appropriate page layout file, based on $this->page->pagelayout.
1302 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1303 // Render the layout using the layout file.
1304 $rendered = $this->render_page_layout($layoutfile);
1306 // Slice the rendered output into header and footer.
1307 $cutpos = strpos($rendered, $this->unique_main_content_token);
1308 if ($cutpos === false) {
1309 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1310 $token = self::MAIN_CONTENT_TOKEN;
1311 } else {
1312 $token = $this->unique_main_content_token;
1315 if ($cutpos === false) {
1316 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.');
1318 $header = substr($rendered, 0, $cutpos);
1319 $footer = substr($rendered, $cutpos + strlen($token));
1321 if (empty($this->contenttype)) {
1322 debugging('The page layout file did not call $OUTPUT->doctype()');
1323 $header = $this->doctype() . $header;
1326 // If this theme version is below 2.4 release and this is a course view page
1327 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1328 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1329 // check if course content header/footer have not been output during render of theme layout
1330 $coursecontentheader = $this->course_content_header(true);
1331 $coursecontentfooter = $this->course_content_footer(true);
1332 if (!empty($coursecontentheader)) {
1333 // display debug message and add header and footer right above and below main content
1334 // Please note that course header and footer (to be displayed above and below the whole page)
1335 // are not displayed in this case at all.
1336 // Besides the content header and footer are not displayed on any other course page
1337 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);
1338 $header .= $coursecontentheader;
1339 $footer = $coursecontentfooter. $footer;
1343 send_headers($this->contenttype, $this->page->cacheable);
1345 $this->opencontainers->push('header/footer', $footer);
1346 $this->page->set_state(moodle_page::STATE_IN_BODY);
1348 return $header . $this->skip_link_target('maincontent');
1352 * Renders and outputs the page layout file.
1354 * This is done by preparing the normal globals available to a script, and
1355 * then including the layout file provided by the current theme for the
1356 * requested layout.
1358 * @param string $layoutfile The name of the layout file
1359 * @return string HTML code
1361 protected function render_page_layout($layoutfile) {
1362 global $CFG, $SITE, $USER;
1363 // The next lines are a bit tricky. The point is, here we are in a method
1364 // of a renderer class, and this object may, or may not, be the same as
1365 // the global $OUTPUT object. When rendering the page layout file, we want to use
1366 // this object. However, people writing Moodle code expect the current
1367 // renderer to be called $OUTPUT, not $this, so define a variable called
1368 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1369 $OUTPUT = $this;
1370 $PAGE = $this->page;
1371 $COURSE = $this->page->course;
1373 ob_start();
1374 include($layoutfile);
1375 $rendered = ob_get_contents();
1376 ob_end_clean();
1377 return $rendered;
1381 * Outputs the page's footer
1383 * @return string HTML fragment
1385 public function footer() {
1386 global $CFG, $DB, $PAGE;
1388 // Give plugins an opportunity to touch the page before JS is finalized.
1389 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1390 foreach ($pluginswithfunction as $plugins) {
1391 foreach ($plugins as $function) {
1392 $function();
1396 $output = $this->container_end_all(true);
1398 $footer = $this->opencontainers->pop('header/footer');
1400 if (debugging() and $DB and $DB->is_transaction_started()) {
1401 // TODO: MDL-20625 print warning - transaction will be rolled back
1404 // Provide some performance info if required
1405 $performanceinfo = '';
1406 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1407 $perf = get_performance_info();
1408 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1409 $performanceinfo = $perf['html'];
1413 // We always want performance data when running a performance test, even if the user is redirected to another page.
1414 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1415 $footer = $this->unique_performance_info_token . $footer;
1417 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1419 // Only show notifications when we have a $PAGE context id.
1420 if (!empty($PAGE->context->id)) {
1421 $this->page->requires->js_call_amd('core/notification', 'init', array(
1422 $PAGE->context->id,
1423 \core\notification::fetch_as_array($this)
1426 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1428 $this->page->set_state(moodle_page::STATE_DONE);
1430 return $output . $footer;
1434 * Close all but the last open container. This is useful in places like error
1435 * handling, where you want to close all the open containers (apart from <body>)
1436 * before outputting the error message.
1438 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1439 * developer debug warning if it isn't.
1440 * @return string the HTML required to close any open containers inside <body>.
1442 public function container_end_all($shouldbenone = false) {
1443 return $this->opencontainers->pop_all_but_last($shouldbenone);
1447 * Returns course-specific information to be output immediately above content on any course page
1448 * (for the current course)
1450 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1451 * @return string
1453 public function course_content_header($onlyifnotcalledbefore = false) {
1454 global $CFG;
1455 static $functioncalled = false;
1456 if ($functioncalled && $onlyifnotcalledbefore) {
1457 // we have already output the content header
1458 return '';
1461 // Output any session notification.
1462 $notifications = \core\notification::fetch();
1464 $bodynotifications = '';
1465 foreach ($notifications as $notification) {
1466 $bodynotifications .= $this->render_from_template(
1467 $notification->get_template_name(),
1468 $notification->export_for_template($this)
1472 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1474 if ($this->page->course->id == SITEID) {
1475 // return immediately and do not include /course/lib.php if not necessary
1476 return $output;
1479 require_once($CFG->dirroot.'/course/lib.php');
1480 $functioncalled = true;
1481 $courseformat = course_get_format($this->page->course);
1482 if (($obj = $courseformat->course_content_header()) !== null) {
1483 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1485 return $output;
1489 * Returns course-specific information to be output immediately below content on any course page
1490 * (for the current course)
1492 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1493 * @return string
1495 public function course_content_footer($onlyifnotcalledbefore = false) {
1496 global $CFG;
1497 if ($this->page->course->id == SITEID) {
1498 // return immediately and do not include /course/lib.php if not necessary
1499 return '';
1501 static $functioncalled = false;
1502 if ($functioncalled && $onlyifnotcalledbefore) {
1503 // we have already output the content footer
1504 return '';
1506 $functioncalled = true;
1507 require_once($CFG->dirroot.'/course/lib.php');
1508 $courseformat = course_get_format($this->page->course);
1509 if (($obj = $courseformat->course_content_footer()) !== null) {
1510 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1512 return '';
1516 * Returns course-specific information to be output on any course page in the header area
1517 * (for the current course)
1519 * @return string
1521 public function course_header() {
1522 global $CFG;
1523 if ($this->page->course->id == SITEID) {
1524 // return immediately and do not include /course/lib.php if not necessary
1525 return '';
1527 require_once($CFG->dirroot.'/course/lib.php');
1528 $courseformat = course_get_format($this->page->course);
1529 if (($obj = $courseformat->course_header()) !== null) {
1530 return $courseformat->get_renderer($this->page)->render($obj);
1532 return '';
1536 * Returns course-specific information to be output on any course page in the footer area
1537 * (for the current course)
1539 * @return string
1541 public function course_footer() {
1542 global $CFG;
1543 if ($this->page->course->id == SITEID) {
1544 // return immediately and do not include /course/lib.php if not necessary
1545 return '';
1547 require_once($CFG->dirroot.'/course/lib.php');
1548 $courseformat = course_get_format($this->page->course);
1549 if (($obj = $courseformat->course_footer()) !== null) {
1550 return $courseformat->get_renderer($this->page)->render($obj);
1552 return '';
1556 * Get the course pattern datauri to show on a course card.
1558 * The datauri is an encoded svg that can be passed as a url.
1559 * @param int $id Id to use when generating the pattern
1560 * @return string datauri
1562 public function get_generated_image_for_id($id) {
1563 $color = $this->get_generated_color_for_id($id);
1564 $pattern = new \core_geopattern();
1565 $pattern->setColor($color);
1566 $pattern->patternbyid($id);
1567 return $pattern->datauri();
1571 * Get the course color to show on a course card.
1573 * @param int $id Id to use when generating the color.
1574 * @return string hex color code.
1576 public function get_generated_color_for_id($id) {
1577 // The colour palette is hardcoded for now. It would make sense to combine it with theme settings.
1578 $basecolors = ['#81ecec', '#74b9ff', '#a29bfe', '#dfe6e9', '#00b894',
1579 '#0984e3', '#b2bec3', '#fdcb6e', '#fd79a8', '#6c5ce7'];
1581 $color = $basecolors[$id % 10];
1582 return $color;
1586 * Returns lang menu or '', this method also checks forcing of languages in courses.
1588 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1590 * @return string The lang menu HTML or empty string
1592 public function lang_menu() {
1593 global $CFG;
1595 if (empty($CFG->langmenu)) {
1596 return '';
1599 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1600 // do not show lang menu if language forced
1601 return '';
1604 $currlang = current_language();
1605 $langs = get_string_manager()->get_list_of_translations();
1607 if (count($langs) < 2) {
1608 return '';
1611 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1612 $s->label = get_accesshide(get_string('language'));
1613 $s->class = 'langmenu';
1614 return $this->render($s);
1618 * Output the row of editing icons for a block, as defined by the controls array.
1620 * @param array $controls an array like {@link block_contents::$controls}.
1621 * @param string $blockid The ID given to the block.
1622 * @return string HTML fragment.
1624 public function block_controls($actions, $blockid = null) {
1625 global $CFG;
1626 if (empty($actions)) {
1627 return '';
1629 $menu = new action_menu($actions);
1630 if ($blockid !== null) {
1631 $menu->set_owner_selector('#'.$blockid);
1633 $menu->set_constraint('.block-region');
1634 $menu->attributes['class'] .= ' block-control-actions commands';
1635 return $this->render($menu);
1639 * Returns the HTML for a basic textarea field.
1641 * @param string $name Name to use for the textarea element
1642 * @param string $id The id to use fort he textarea element
1643 * @param string $value Initial content to display in the textarea
1644 * @param int $rows Number of rows to display
1645 * @param int $cols Number of columns to display
1646 * @return string the HTML to display
1648 public function print_textarea($name, $id, $value, $rows, $cols) {
1649 global $OUTPUT;
1651 editors_head_setup();
1652 $editor = editors_get_preferred_editor(FORMAT_HTML);
1653 $editor->set_text($value);
1654 $editor->use_editor($id, []);
1656 $context = [
1657 'id' => $id,
1658 'name' => $name,
1659 'value' => $value,
1660 'rows' => $rows,
1661 'cols' => $cols
1664 return $OUTPUT->render_from_template('core_form/editor_textarea', $context);
1668 * Renders an action menu component.
1670 * @param action_menu $menu
1671 * @return string HTML
1673 public function render_action_menu(action_menu $menu) {
1675 // We don't want the class icon there!
1676 foreach ($menu->get_secondary_actions() as $action) {
1677 if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1678 $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1682 if ($menu->is_empty()) {
1683 return '';
1685 $context = $menu->export_for_template($this);
1687 return $this->render_from_template('core/action_menu', $context);
1691 * Renders an action_menu_link item.
1693 * @param action_menu_link $action
1694 * @return string HTML fragment
1696 protected function render_action_menu_link(action_menu_link $action) {
1697 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1701 * Renders a primary action_menu_filler item.
1703 * @param action_menu_link_filler $action
1704 * @return string HTML fragment
1706 protected function render_action_menu_filler(action_menu_filler $action) {
1707 return html_writer::span('&nbsp;', 'filler');
1711 * Renders a primary action_menu_link item.
1713 * @param action_menu_link_primary $action
1714 * @return string HTML fragment
1716 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1717 return $this->render_action_menu_link($action);
1721 * Renders a secondary action_menu_link item.
1723 * @param action_menu_link_secondary $action
1724 * @return string HTML fragment
1726 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1727 return $this->render_action_menu_link($action);
1731 * Prints a nice side block with an optional header.
1733 * @param block_contents $bc HTML for the content
1734 * @param string $region the region the block is appearing in.
1735 * @return string the HTML to be output.
1737 public function block(block_contents $bc, $region) {
1738 $bc = clone($bc); // Avoid messing up the object passed in.
1739 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1740 $bc->collapsible = block_contents::NOT_HIDEABLE;
1743 $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1744 $context = new stdClass();
1745 $context->skipid = $bc->skipid;
1746 $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
1747 $context->dockable = $bc->dockable;
1748 $context->id = $id;
1749 $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1750 $context->skiptitle = strip_tags($bc->title);
1751 $context->showskiplink = !empty($context->skiptitle);
1752 $context->arialabel = $bc->arialabel;
1753 $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
1754 $context->class = $bc->attributes['class'];
1755 $context->type = $bc->attributes['data-block'];
1756 $context->title = $bc->title;
1757 $context->content = $bc->content;
1758 $context->annotation = $bc->annotation;
1759 $context->footer = $bc->footer;
1760 $context->hascontrols = !empty($bc->controls);
1761 if ($context->hascontrols) {
1762 $context->controls = $this->block_controls($bc->controls, $id);
1765 return $this->render_from_template('core/block', $context);
1769 * Render the contents of a block_list.
1771 * @param array $icons the icon for each item.
1772 * @param array $items the content of each item.
1773 * @return string HTML
1775 public function list_block_contents($icons, $items) {
1776 $row = 0;
1777 $lis = array();
1778 foreach ($items as $key => $string) {
1779 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1780 if (!empty($icons[$key])) { //test if the content has an assigned icon
1781 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1783 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1784 $item .= html_writer::end_tag('li');
1785 $lis[] = $item;
1786 $row = 1 - $row; // Flip even/odd.
1788 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1792 * Output all the blocks in a particular region.
1794 * @param string $region the name of a region on this page.
1795 * @return string the HTML to be output.
1797 public function blocks_for_region($region) {
1798 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1799 $blocks = $this->page->blocks->get_blocks_for_region($region);
1800 $lastblock = null;
1801 $zones = array();
1802 foreach ($blocks as $block) {
1803 $zones[] = $block->title;
1805 $output = '';
1807 foreach ($blockcontents as $bc) {
1808 if ($bc instanceof block_contents) {
1809 $output .= $this->block($bc, $region);
1810 $lastblock = $bc->title;
1811 } else if ($bc instanceof block_move_target) {
1812 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1813 } else {
1814 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1817 return $output;
1821 * Output a place where the block that is currently being moved can be dropped.
1823 * @param block_move_target $target with the necessary details.
1824 * @param array $zones array of areas where the block can be moved to
1825 * @param string $previous the block located before the area currently being rendered.
1826 * @param string $region the name of the region
1827 * @return string the HTML to be output.
1829 public function block_move_target($target, $zones, $previous, $region) {
1830 if ($previous == null) {
1831 if (empty($zones)) {
1832 // There are no zones, probably because there are no blocks.
1833 $regions = $this->page->theme->get_all_block_regions();
1834 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1835 } else {
1836 $position = get_string('moveblockbefore', 'block', $zones[0]);
1838 } else {
1839 $position = get_string('moveblockafter', 'block', $previous);
1841 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1845 * Renders a special html link with attached action
1847 * Theme developers: DO NOT OVERRIDE! Please override function
1848 * {@link core_renderer::render_action_link()} instead.
1850 * @param string|moodle_url $url
1851 * @param string $text HTML fragment
1852 * @param component_action $action
1853 * @param array $attributes associative array of html link attributes + disabled
1854 * @param pix_icon optional pix icon to render with the link
1855 * @return string HTML fragment
1857 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1858 if (!($url instanceof moodle_url)) {
1859 $url = new moodle_url($url);
1861 $link = new action_link($url, $text, $action, $attributes, $icon);
1863 return $this->render($link);
1867 * Renders an action_link object.
1869 * The provided link is renderer and the HTML returned. At the same time the
1870 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1872 * @param action_link $link
1873 * @return string HTML fragment
1875 protected function render_action_link(action_link $link) {
1876 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1880 * Renders an action_icon.
1882 * This function uses the {@link core_renderer::action_link()} method for the
1883 * most part. What it does different is prepare the icon as HTML and use it
1884 * as the link text.
1886 * Theme developers: If you want to change how action links and/or icons are rendered,
1887 * consider overriding function {@link core_renderer::render_action_link()} and
1888 * {@link core_renderer::render_pix_icon()}.
1890 * @param string|moodle_url $url A string URL or moodel_url
1891 * @param pix_icon $pixicon
1892 * @param component_action $action
1893 * @param array $attributes associative array of html link attributes + disabled
1894 * @param bool $linktext show title next to image in link
1895 * @return string HTML fragment
1897 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1898 if (!($url instanceof moodle_url)) {
1899 $url = new moodle_url($url);
1901 $attributes = (array)$attributes;
1903 if (empty($attributes['class'])) {
1904 // let ppl override the class via $options
1905 $attributes['class'] = 'action-icon';
1908 $icon = $this->render($pixicon);
1910 if ($linktext) {
1911 $text = $pixicon->attributes['alt'];
1912 } else {
1913 $text = '';
1916 return $this->action_link($url, $text.$icon, $action, $attributes);
1920 * Print a message along with button choices for Continue/Cancel
1922 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1924 * @param string $message The question to ask the user
1925 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1926 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1927 * @return string HTML fragment
1929 public function confirm($message, $continue, $cancel) {
1930 if ($continue instanceof single_button) {
1931 // ok
1932 $continue->primary = true;
1933 } else if (is_string($continue)) {
1934 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1935 } else if ($continue instanceof moodle_url) {
1936 $continue = new single_button($continue, get_string('continue'), 'post', true);
1937 } else {
1938 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1941 if ($cancel instanceof single_button) {
1942 // ok
1943 } else if (is_string($cancel)) {
1944 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1945 } else if ($cancel instanceof moodle_url) {
1946 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1947 } else {
1948 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1951 $attributes = [
1952 'role'=>'alertdialog',
1953 'aria-labelledby'=>'modal-header',
1954 'aria-describedby'=>'modal-body',
1955 'aria-modal'=>'true'
1958 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
1959 $output .= $this->box_start('modal-content', 'modal-content');
1960 $output .= $this->box_start('modal-header p-x-1', 'modal-header');
1961 $output .= html_writer::tag('h4', get_string('confirm'));
1962 $output .= $this->box_end();
1963 $attributes = [
1964 'role'=>'alert',
1965 'data-aria-autofocus'=>'true'
1967 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
1968 $output .= html_writer::tag('p', $message);
1969 $output .= $this->box_end();
1970 $output .= $this->box_start('modal-footer', 'modal-footer');
1971 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1972 $output .= $this->box_end();
1973 $output .= $this->box_end();
1974 $output .= $this->box_end();
1975 return $output;
1979 * Returns a form with a single button.
1981 * Theme developers: DO NOT OVERRIDE! Please override function
1982 * {@link core_renderer::render_single_button()} instead.
1984 * @param string|moodle_url $url
1985 * @param string $label button text
1986 * @param string $method get or post submit method
1987 * @param array $options associative array {disabled, title, etc.}
1988 * @return string HTML fragment
1990 public function single_button($url, $label, $method='post', array $options=null) {
1991 if (!($url instanceof moodle_url)) {
1992 $url = new moodle_url($url);
1994 $button = new single_button($url, $label, $method);
1996 foreach ((array)$options as $key=>$value) {
1997 if (array_key_exists($key, $button)) {
1998 $button->$key = $value;
2002 return $this->render($button);
2006 * Renders a single button widget.
2008 * This will return HTML to display a form containing a single button.
2010 * @param single_button $button
2011 * @return string HTML fragment
2013 protected function render_single_button(single_button $button) {
2014 return $this->render_from_template('core/single_button', $button->export_for_template($this));
2018 * Returns a form with a single select widget.
2020 * Theme developers: DO NOT OVERRIDE! Please override function
2021 * {@link core_renderer::render_single_select()} instead.
2023 * @param moodle_url $url form action target, includes hidden fields
2024 * @param string $name name of selection field - the changing parameter in url
2025 * @param array $options list of options
2026 * @param string $selected selected element
2027 * @param array $nothing
2028 * @param string $formid
2029 * @param array $attributes other attributes for the single select
2030 * @return string HTML fragment
2032 public function single_select($url, $name, array $options, $selected = '',
2033 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2034 if (!($url instanceof moodle_url)) {
2035 $url = new moodle_url($url);
2037 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2039 if (array_key_exists('label', $attributes)) {
2040 $select->set_label($attributes['label']);
2041 unset($attributes['label']);
2043 $select->attributes = $attributes;
2045 return $this->render($select);
2049 * Returns a dataformat selection and download form
2051 * @param string $label A text label
2052 * @param moodle_url|string $base The download page url
2053 * @param string $name The query param which will hold the type of the download
2054 * @param array $params Extra params sent to the download page
2055 * @return string HTML fragment
2057 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2059 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2060 $options = array();
2061 foreach ($formats as $format) {
2062 if ($format->is_enabled()) {
2063 $options[] = array(
2064 'value' => $format->name,
2065 'label' => get_string('dataformat', $format->component),
2069 $hiddenparams = array();
2070 foreach ($params as $key => $value) {
2071 $hiddenparams[] = array(
2072 'name' => $key,
2073 'value' => $value,
2076 $data = array(
2077 'label' => $label,
2078 'base' => $base,
2079 'name' => $name,
2080 'params' => $hiddenparams,
2081 'options' => $options,
2082 'sesskey' => sesskey(),
2083 'submit' => get_string('download'),
2086 return $this->render_from_template('core/dataformat_selector', $data);
2091 * Internal implementation of single_select rendering
2093 * @param single_select $select
2094 * @return string HTML fragment
2096 protected function render_single_select(single_select $select) {
2097 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2101 * Returns a form with a url select widget.
2103 * Theme developers: DO NOT OVERRIDE! Please override function
2104 * {@link core_renderer::render_url_select()} instead.
2106 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2107 * @param string $selected selected element
2108 * @param array $nothing
2109 * @param string $formid
2110 * @return string HTML fragment
2112 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2113 $select = new url_select($urls, $selected, $nothing, $formid);
2114 return $this->render($select);
2118 * Internal implementation of url_select rendering
2120 * @param url_select $select
2121 * @return string HTML fragment
2123 protected function render_url_select(url_select $select) {
2124 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2128 * Returns a string containing a link to the user documentation.
2129 * Also contains an icon by default. Shown to teachers and admin only.
2131 * @param string $path The page link after doc root and language, no leading slash.
2132 * @param string $text The text to be displayed for the link
2133 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2134 * @return string
2136 public function doc_link($path, $text = '', $forcepopup = false) {
2137 global $CFG;
2139 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2141 $url = new moodle_url(get_docs_url($path));
2143 $attributes = array('href'=>$url);
2144 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2145 $attributes['class'] = 'helplinkpopup';
2148 return html_writer::tag('a', $icon.$text, $attributes);
2152 * Return HTML for an image_icon.
2154 * Theme developers: DO NOT OVERRIDE! Please override function
2155 * {@link core_renderer::render_image_icon()} instead.
2157 * @param string $pix short pix name
2158 * @param string $alt mandatory alt attribute
2159 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2160 * @param array $attributes htm lattributes
2161 * @return string HTML fragment
2163 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2164 $icon = new image_icon($pix, $alt, $component, $attributes);
2165 return $this->render($icon);
2169 * Renders a pix_icon widget and returns the HTML to display it.
2171 * @param image_icon $icon
2172 * @return string HTML fragment
2174 protected function render_image_icon(image_icon $icon) {
2175 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2176 return $system->render_pix_icon($this, $icon);
2180 * Return HTML for a pix_icon.
2182 * Theme developers: DO NOT OVERRIDE! Please override function
2183 * {@link core_renderer::render_pix_icon()} instead.
2185 * @param string $pix short pix name
2186 * @param string $alt mandatory alt attribute
2187 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2188 * @param array $attributes htm lattributes
2189 * @return string HTML fragment
2191 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2192 $icon = new pix_icon($pix, $alt, $component, $attributes);
2193 return $this->render($icon);
2197 * Renders a pix_icon widget and returns the HTML to display it.
2199 * @param pix_icon $icon
2200 * @return string HTML fragment
2202 protected function render_pix_icon(pix_icon $icon) {
2203 $system = \core\output\icon_system::instance();
2204 return $system->render_pix_icon($this, $icon);
2208 * Return HTML to display an emoticon icon.
2210 * @param pix_emoticon $emoticon
2211 * @return string HTML fragment
2213 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2214 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2215 return $system->render_pix_icon($this, $emoticon);
2219 * Produces the html that represents this rating in the UI
2221 * @param rating $rating the page object on which this rating will appear
2222 * @return string
2224 function render_rating(rating $rating) {
2225 global $CFG, $USER;
2227 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2228 return null;//ratings are turned off
2231 $ratingmanager = new rating_manager();
2232 // Initialise the JavaScript so ratings can be done by AJAX.
2233 $ratingmanager->initialise_rating_javascript($this->page);
2235 $strrate = get_string("rate", "rating");
2236 $ratinghtml = ''; //the string we'll return
2238 // permissions check - can they view the aggregate?
2239 if ($rating->user_can_view_aggregate()) {
2241 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2242 $aggregatestr = $rating->get_aggregate_string();
2244 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2245 if ($rating->count > 0) {
2246 $countstr = "({$rating->count})";
2247 } else {
2248 $countstr = '-';
2250 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2252 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2253 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2255 $nonpopuplink = $rating->get_view_ratings_url();
2256 $popuplink = $rating->get_view_ratings_url(true);
2258 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2259 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2260 } else {
2261 $ratinghtml .= $aggregatehtml;
2265 $formstart = null;
2266 // if the item doesn't belong to the current user, the user has permission to rate
2267 // and we're within the assessable period
2268 if ($rating->user_can_rate()) {
2270 $rateurl = $rating->get_rate_url();
2271 $inputs = $rateurl->params();
2273 //start the rating form
2274 $formattrs = array(
2275 'id' => "postrating{$rating->itemid}",
2276 'class' => 'postratingform',
2277 'method' => 'post',
2278 'action' => $rateurl->out_omit_querystring()
2280 $formstart = html_writer::start_tag('form', $formattrs);
2281 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2283 // add the hidden inputs
2284 foreach ($inputs as $name => $value) {
2285 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2286 $formstart .= html_writer::empty_tag('input', $attributes);
2289 if (empty($ratinghtml)) {
2290 $ratinghtml .= $strrate.': ';
2292 $ratinghtml = $formstart.$ratinghtml;
2294 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2295 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2296 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2297 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2299 //output submit button
2300 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2302 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2303 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2305 if (!$rating->settings->scale->isnumeric) {
2306 // If a global scale, try to find current course ID from the context
2307 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2308 $courseid = $coursecontext->instanceid;
2309 } else {
2310 $courseid = $rating->settings->scale->courseid;
2312 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2314 $ratinghtml .= html_writer::end_tag('span');
2315 $ratinghtml .= html_writer::end_tag('div');
2316 $ratinghtml .= html_writer::end_tag('form');
2319 return $ratinghtml;
2323 * Centered heading with attached help button (same title text)
2324 * and optional icon attached.
2326 * @param string $text A heading text
2327 * @param string $helpidentifier The keyword that defines a help page
2328 * @param string $component component name
2329 * @param string|moodle_url $icon
2330 * @param string $iconalt icon alt text
2331 * @param int $level The level of importance of the heading. Defaulting to 2
2332 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2333 * @return string HTML fragment
2335 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2336 $image = '';
2337 if ($icon) {
2338 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2341 $help = '';
2342 if ($helpidentifier) {
2343 $help = $this->help_icon($helpidentifier, $component);
2346 return $this->heading($image.$text.$help, $level, $classnames);
2350 * Returns HTML to display a help icon.
2352 * @deprecated since Moodle 2.0
2354 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2355 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2359 * Returns HTML to display a help icon.
2361 * Theme developers: DO NOT OVERRIDE! Please override function
2362 * {@link core_renderer::render_help_icon()} instead.
2364 * @param string $identifier The keyword that defines a help page
2365 * @param string $component component name
2366 * @param string|bool $linktext true means use $title as link text, string means link text value
2367 * @return string HTML fragment
2369 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2370 $icon = new help_icon($identifier, $component);
2371 $icon->diag_strings();
2372 if ($linktext === true) {
2373 $icon->linktext = get_string($icon->identifier, $icon->component);
2374 } else if (!empty($linktext)) {
2375 $icon->linktext = $linktext;
2377 return $this->render($icon);
2381 * Implementation of user image rendering.
2383 * @param help_icon $helpicon A help icon instance
2384 * @return string HTML fragment
2386 protected function render_help_icon(help_icon $helpicon) {
2387 $context = $helpicon->export_for_template($this);
2388 return $this->render_from_template('core/help_icon', $context);
2392 * Returns HTML to display a scale help icon.
2394 * @param int $courseid
2395 * @param stdClass $scale instance
2396 * @return string HTML fragment
2398 public function help_icon_scale($courseid, stdClass $scale) {
2399 global $CFG;
2401 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2403 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2405 $scaleid = abs($scale->id);
2407 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2408 $action = new popup_action('click', $link, 'ratingscale');
2410 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2414 * Creates and returns a spacer image with optional line break.
2416 * @param array $attributes Any HTML attributes to add to the spaced.
2417 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2418 * laxy do it with CSS which is a much better solution.
2419 * @return string HTML fragment
2421 public function spacer(array $attributes = null, $br = false) {
2422 $attributes = (array)$attributes;
2423 if (empty($attributes['width'])) {
2424 $attributes['width'] = 1;
2426 if (empty($attributes['height'])) {
2427 $attributes['height'] = 1;
2429 $attributes['class'] = 'spacer';
2431 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2433 if (!empty($br)) {
2434 $output .= '<br />';
2437 return $output;
2441 * Returns HTML to display the specified user's avatar.
2443 * User avatar may be obtained in two ways:
2444 * <pre>
2445 * // Option 1: (shortcut for simple cases, preferred way)
2446 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2447 * $OUTPUT->user_picture($user, array('popup'=>true));
2449 * // Option 2:
2450 * $userpic = new user_picture($user);
2451 * // Set properties of $userpic
2452 * $userpic->popup = true;
2453 * $OUTPUT->render($userpic);
2454 * </pre>
2456 * Theme developers: DO NOT OVERRIDE! Please override function
2457 * {@link core_renderer::render_user_picture()} instead.
2459 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2460 * If any of these are missing, the database is queried. Avoid this
2461 * if at all possible, particularly for reports. It is very bad for performance.
2462 * @param array $options associative array with user picture options, used only if not a user_picture object,
2463 * options are:
2464 * - courseid=$this->page->course->id (course id of user profile in link)
2465 * - size=35 (size of image)
2466 * - link=true (make image clickable - the link leads to user profile)
2467 * - popup=false (open in popup)
2468 * - alttext=true (add image alt attribute)
2469 * - class = image class attribute (default 'userpicture')
2470 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2471 * - includefullname=false (whether to include the user's full name together with the user picture)
2472 * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2473 * @return string HTML fragment
2475 public function user_picture(stdClass $user, array $options = null) {
2476 $userpicture = new user_picture($user);
2477 foreach ((array)$options as $key=>$value) {
2478 if (array_key_exists($key, $userpicture)) {
2479 $userpicture->$key = $value;
2482 return $this->render($userpicture);
2486 * Internal implementation of user image rendering.
2488 * @param user_picture $userpicture
2489 * @return string
2491 protected function render_user_picture(user_picture $userpicture) {
2492 global $CFG, $DB;
2494 $user = $userpicture->user;
2495 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
2497 if ($userpicture->alttext) {
2498 if (!empty($user->imagealt)) {
2499 $alt = $user->imagealt;
2500 } else {
2501 $alt = get_string('pictureof', '', fullname($user, $canviewfullnames));
2503 } else {
2504 $alt = '';
2507 if (empty($userpicture->size)) {
2508 $size = 35;
2509 } else if ($userpicture->size === true or $userpicture->size == 1) {
2510 $size = 100;
2511 } else {
2512 $size = $userpicture->size;
2515 $class = $userpicture->class;
2517 if ($user->picture == 0) {
2518 $class .= ' defaultuserpic';
2521 $src = $userpicture->get_url($this->page, $this);
2523 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2524 if (!$userpicture->visibletoscreenreaders) {
2525 $attributes['role'] = 'presentation';
2526 $alt = '';
2527 $attributes['aria-hidden'] = 'true';
2530 if (!empty($alt)) {
2531 $attributes['alt'] = $alt;
2532 $attributes['title'] = $alt;
2535 // get the image html output fisrt
2536 $output = html_writer::empty_tag('img', $attributes);
2538 // Show fullname together with the picture when desired.
2539 if ($userpicture->includefullname) {
2540 $output .= fullname($userpicture->user, $canviewfullnames);
2543 // then wrap it in link if needed
2544 if (!$userpicture->link) {
2545 return $output;
2548 if (empty($userpicture->courseid)) {
2549 $courseid = $this->page->course->id;
2550 } else {
2551 $courseid = $userpicture->courseid;
2554 if ($courseid == SITEID) {
2555 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2556 } else {
2557 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2560 $attributes = array('href'=>$url);
2561 if (!$userpicture->visibletoscreenreaders) {
2562 $attributes['tabindex'] = '-1';
2563 $attributes['aria-hidden'] = 'true';
2566 if ($userpicture->popup) {
2567 $id = html_writer::random_id('userpicture');
2568 $attributes['id'] = $id;
2569 $this->add_action_handler(new popup_action('click', $url), $id);
2572 return html_writer::tag('a', $output, $attributes);
2576 * Internal implementation of file tree viewer items rendering.
2578 * @param array $dir
2579 * @return string
2581 public function htmllize_file_tree($dir) {
2582 if (empty($dir['subdirs']) and empty($dir['files'])) {
2583 return '';
2585 $result = '<ul>';
2586 foreach ($dir['subdirs'] as $subdir) {
2587 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2589 foreach ($dir['files'] as $file) {
2590 $filename = $file->get_filename();
2591 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2593 $result .= '</ul>';
2595 return $result;
2599 * Returns HTML to display the file picker
2601 * <pre>
2602 * $OUTPUT->file_picker($options);
2603 * </pre>
2605 * Theme developers: DO NOT OVERRIDE! Please override function
2606 * {@link core_renderer::render_file_picker()} instead.
2608 * @param array $options associative array with file manager options
2609 * options are:
2610 * maxbytes=>-1,
2611 * itemid=>0,
2612 * client_id=>uniqid(),
2613 * acepted_types=>'*',
2614 * return_types=>FILE_INTERNAL,
2615 * context=>$PAGE->context
2616 * @return string HTML fragment
2618 public function file_picker($options) {
2619 $fp = new file_picker($options);
2620 return $this->render($fp);
2624 * Internal implementation of file picker rendering.
2626 * @param file_picker $fp
2627 * @return string
2629 public function render_file_picker(file_picker $fp) {
2630 global $CFG, $OUTPUT, $USER;
2631 $options = $fp->options;
2632 $client_id = $options->client_id;
2633 $strsaved = get_string('filesaved', 'repository');
2634 $straddfile = get_string('openpicker', 'repository');
2635 $strloading = get_string('loading', 'repository');
2636 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2637 $strdroptoupload = get_string('droptoupload', 'moodle');
2638 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2640 $currentfile = $options->currentfile;
2641 if (empty($currentfile)) {
2642 $currentfile = '';
2643 } else {
2644 $currentfile .= ' - ';
2646 if ($options->maxbytes) {
2647 $size = $options->maxbytes;
2648 } else {
2649 $size = get_max_upload_file_size();
2651 if ($size == -1) {
2652 $maxsize = '';
2653 } else {
2654 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2656 if ($options->buttonname) {
2657 $buttonname = ' name="' . $options->buttonname . '"';
2658 } else {
2659 $buttonname = '';
2661 $html = <<<EOD
2662 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2663 $icon_progress
2664 </div>
2665 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2666 <div>
2667 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2668 <span> $maxsize </span>
2669 </div>
2670 EOD;
2671 if ($options->env != 'url') {
2672 $html .= <<<EOD
2673 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2674 <div class="filepicker-filename">
2675 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2676 <div class="dndupload-progressbars"></div>
2677 </div>
2678 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2679 </div>
2680 EOD;
2682 $html .= '</div>';
2683 return $html;
2687 * @deprecated since Moodle 3.2
2689 public function update_module_button() {
2690 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2691 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2692 'Themes can choose to display the link in the buttons row consistently for all module types.');
2696 * Returns HTML to display a "Turn editing on/off" button in a form.
2698 * @param moodle_url $url The URL + params to send through when clicking the button
2699 * @return string HTML the button
2701 public function edit_button(moodle_url $url) {
2703 $url->param('sesskey', sesskey());
2704 if ($this->page->user_is_editing()) {
2705 $url->param('edit', 'off');
2706 $editstring = get_string('turneditingoff');
2707 } else {
2708 $url->param('edit', 'on');
2709 $editstring = get_string('turneditingon');
2712 return $this->single_button($url, $editstring);
2716 * Returns HTML to display a simple button to close a window
2718 * @param string $text The lang string for the button's label (already output from get_string())
2719 * @return string html fragment
2721 public function close_window_button($text='') {
2722 if (empty($text)) {
2723 $text = get_string('closewindow');
2725 $button = new single_button(new moodle_url('#'), $text, 'get');
2726 $button->add_action(new component_action('click', 'close_window'));
2728 return $this->container($this->render($button), 'closewindow');
2732 * Output an error message. By default wraps the error message in <span class="error">.
2733 * If the error message is blank, nothing is output.
2735 * @param string $message the error message.
2736 * @return string the HTML to output.
2738 public function error_text($message) {
2739 if (empty($message)) {
2740 return '';
2742 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2743 return html_writer::tag('span', $message, array('class' => 'error'));
2747 * Do not call this function directly.
2749 * To terminate the current script with a fatal error, call the {@link print_error}
2750 * function, or throw an exception. Doing either of those things will then call this
2751 * function to display the error, before terminating the execution.
2753 * @param string $message The message to output
2754 * @param string $moreinfourl URL where more info can be found about the error
2755 * @param string $link Link for the Continue button
2756 * @param array $backtrace The execution backtrace
2757 * @param string $debuginfo Debugging information
2758 * @return string the HTML to output.
2760 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2761 global $CFG;
2763 $output = '';
2764 $obbuffer = '';
2766 if ($this->has_started()) {
2767 // we can not always recover properly here, we have problems with output buffering,
2768 // html tables, etc.
2769 $output .= $this->opencontainers->pop_all_but_last();
2771 } else {
2772 // It is really bad if library code throws exception when output buffering is on,
2773 // because the buffered text would be printed before our start of page.
2774 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2775 error_reporting(0); // disable notices from gzip compression, etc.
2776 while (ob_get_level() > 0) {
2777 $buff = ob_get_clean();
2778 if ($buff === false) {
2779 break;
2781 $obbuffer .= $buff;
2783 error_reporting($CFG->debug);
2785 // Output not yet started.
2786 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2787 if (empty($_SERVER['HTTP_RANGE'])) {
2788 @header($protocol . ' 404 Not Found');
2789 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2790 // Coax iOS 10 into sending the session cookie.
2791 @header($protocol . ' 403 Forbidden');
2792 } else {
2793 // Must stop byteserving attempts somehow,
2794 // this is weird but Chrome PDF viewer can be stopped only with 407!
2795 @header($protocol . ' 407 Proxy Authentication Required');
2798 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2799 $this->page->set_url('/'); // no url
2800 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2801 $this->page->set_title(get_string('error'));
2802 $this->page->set_heading($this->page->course->fullname);
2803 $output .= $this->header();
2806 $message = '<p class="errormessage">' . s($message) . '</p>'.
2807 '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
2808 get_string('moreinformation') . '</a></p>';
2809 if (empty($CFG->rolesactive)) {
2810 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2811 //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.
2813 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2815 if ($CFG->debugdeveloper) {
2816 if (!empty($debuginfo)) {
2817 $debuginfo = s($debuginfo); // removes all nasty JS
2818 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2819 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2821 if (!empty($backtrace)) {
2822 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2824 if ($obbuffer !== '' ) {
2825 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2829 if (empty($CFG->rolesactive)) {
2830 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2831 } else if (!empty($link)) {
2832 $output .= $this->continue_button($link);
2835 $output .= $this->footer();
2837 // Padding to encourage IE to display our error page, rather than its own.
2838 $output .= str_repeat(' ', 512);
2840 return $output;
2844 * Output a notification (that is, a status message about something that has just happened).
2846 * Note: \core\notification::add() may be more suitable for your usage.
2848 * @param string $message The message to print out.
2849 * @param string $type The type of notification. See constants on \core\output\notification.
2850 * @return string the HTML to output.
2852 public function notification($message, $type = null) {
2853 $typemappings = [
2854 // Valid types.
2855 'success' => \core\output\notification::NOTIFY_SUCCESS,
2856 'info' => \core\output\notification::NOTIFY_INFO,
2857 'warning' => \core\output\notification::NOTIFY_WARNING,
2858 'error' => \core\output\notification::NOTIFY_ERROR,
2860 // Legacy types mapped to current types.
2861 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2862 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2863 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2864 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2865 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2866 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2867 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2870 $extraclasses = [];
2872 if ($type) {
2873 if (strpos($type, ' ') === false) {
2874 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2875 if (isset($typemappings[$type])) {
2876 $type = $typemappings[$type];
2877 } else {
2878 // The value provided did not match a known type. It must be an extra class.
2879 $extraclasses = [$type];
2881 } else {
2882 // Identify what type of notification this is.
2883 $classarray = explode(' ', self::prepare_classes($type));
2885 // Separate out the type of notification from the extra classes.
2886 foreach ($classarray as $class) {
2887 if (isset($typemappings[$class])) {
2888 $type = $typemappings[$class];
2889 } else {
2890 $extraclasses[] = $class;
2896 $notification = new \core\output\notification($message, $type);
2897 if (count($extraclasses)) {
2898 $notification->set_extra_classes($extraclasses);
2901 // Return the rendered template.
2902 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2906 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2908 public function notify_problem() {
2909 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
2910 'please use \core\notification::add(), or \core\output\notification as required.');
2914 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2916 public function notify_success() {
2917 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
2918 'please use \core\notification::add(), or \core\output\notification as required.');
2922 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2924 public function notify_message() {
2925 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
2926 'please use \core\notification::add(), or \core\output\notification as required.');
2930 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2932 public function notify_redirect() {
2933 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
2934 'please use \core\notification::add(), or \core\output\notification as required.');
2938 * Render a notification (that is, a status message about something that has
2939 * just happened).
2941 * @param \core\output\notification $notification the notification to print out
2942 * @return string the HTML to output.
2944 protected function render_notification(\core\output\notification $notification) {
2945 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2949 * Returns HTML to display a continue button that goes to a particular URL.
2951 * @param string|moodle_url $url The url the button goes to.
2952 * @return string the HTML to output.
2954 public function continue_button($url) {
2955 if (!($url instanceof moodle_url)) {
2956 $url = new moodle_url($url);
2958 $button = new single_button($url, get_string('continue'), 'get', true);
2959 $button->class = 'continuebutton';
2961 return $this->render($button);
2965 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2967 * Theme developers: DO NOT OVERRIDE! Please override function
2968 * {@link core_renderer::render_paging_bar()} instead.
2970 * @param int $totalcount The total number of entries available to be paged through
2971 * @param int $page The page you are currently viewing
2972 * @param int $perpage The number of entries that should be shown per page
2973 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2974 * @param string $pagevar name of page parameter that holds the page number
2975 * @return string the HTML to output.
2977 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2978 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2979 return $this->render($pb);
2983 * Returns HTML to display the paging bar.
2985 * @param paging_bar $pagingbar
2986 * @return string the HTML to output.
2988 protected function render_paging_bar(paging_bar $pagingbar) {
2989 // Any more than 10 is not usable and causes weird wrapping of the pagination.
2990 $pagingbar->maxdisplay = 10;
2991 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
2995 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
2997 * @param string $current the currently selected letter.
2998 * @param string $class class name to add to this initial bar.
2999 * @param string $title the name to put in front of this initial bar.
3000 * @param string $urlvar URL parameter name for this initial.
3001 * @param string $url URL object.
3002 * @param array $alpha of letters in the alphabet.
3003 * @return string the HTML to output.
3005 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3006 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3007 return $this->render($ib);
3011 * Internal implementation of initials bar rendering.
3013 * @param initials_bar $initialsbar
3014 * @return string
3016 protected function render_initials_bar(initials_bar $initialsbar) {
3017 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3021 * Output the place a skip link goes to.
3023 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3024 * @return string the HTML to output.
3026 public function skip_link_target($id = null) {
3027 return html_writer::span('', '', array('id' => $id));
3031 * Outputs a heading
3033 * @param string $text The text of the heading
3034 * @param int $level The level of importance of the heading. Defaulting to 2
3035 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3036 * @param string $id An optional ID
3037 * @return string the HTML to output.
3039 public function heading($text, $level = 2, $classes = null, $id = null) {
3040 $level = (integer) $level;
3041 if ($level < 1 or $level > 6) {
3042 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3044 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3048 * Outputs a box.
3050 * @param string $contents The contents of the box
3051 * @param string $classes A space-separated list of CSS classes
3052 * @param string $id An optional ID
3053 * @param array $attributes An array of other attributes to give the box.
3054 * @return string the HTML to output.
3056 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3057 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3061 * Outputs the opening section of a box.
3063 * @param string $classes A space-separated list of CSS classes
3064 * @param string $id An optional ID
3065 * @param array $attributes An array of other attributes to give the box.
3066 * @return string the HTML to output.
3068 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3069 $this->opencontainers->push('box', html_writer::end_tag('div'));
3070 $attributes['id'] = $id;
3071 $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes);
3072 return html_writer::start_tag('div', $attributes);
3076 * Outputs the closing section of a box.
3078 * @return string the HTML to output.
3080 public function box_end() {
3081 return $this->opencontainers->pop('box');
3085 * Outputs a container.
3087 * @param string $contents The contents of the box
3088 * @param string $classes A space-separated list of CSS classes
3089 * @param string $id An optional ID
3090 * @return string the HTML to output.
3092 public function container($contents, $classes = null, $id = null) {
3093 return $this->container_start($classes, $id) . $contents . $this->container_end();
3097 * Outputs the opening section of a container.
3099 * @param string $classes A space-separated list of CSS classes
3100 * @param string $id An optional ID
3101 * @return string the HTML to output.
3103 public function container_start($classes = null, $id = null) {
3104 $this->opencontainers->push('container', html_writer::end_tag('div'));
3105 return html_writer::start_tag('div', array('id' => $id,
3106 'class' => renderer_base::prepare_classes($classes)));
3110 * Outputs the closing section of a container.
3112 * @return string the HTML to output.
3114 public function container_end() {
3115 return $this->opencontainers->pop('container');
3119 * Make nested HTML lists out of the items
3121 * The resulting list will look something like this:
3123 * <pre>
3124 * <<ul>>
3125 * <<li>><div class='tree_item parent'>(item contents)</div>
3126 * <<ul>
3127 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3128 * <</ul>>
3129 * <</li>>
3130 * <</ul>>
3131 * </pre>
3133 * @param array $items
3134 * @param array $attrs html attributes passed to the top ofs the list
3135 * @return string HTML
3137 public function tree_block_contents($items, $attrs = array()) {
3138 // exit if empty, we don't want an empty ul element
3139 if (empty($items)) {
3140 return '';
3142 // array of nested li elements
3143 $lis = array();
3144 foreach ($items as $item) {
3145 // this applies to the li item which contains all child lists too
3146 $content = $item->content($this);
3147 $liclasses = array($item->get_css_type());
3148 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3149 $liclasses[] = 'collapsed';
3151 if ($item->isactive === true) {
3152 $liclasses[] = 'current_branch';
3154 $liattr = array('class'=>join(' ',$liclasses));
3155 // class attribute on the div item which only contains the item content
3156 $divclasses = array('tree_item');
3157 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3158 $divclasses[] = 'branch';
3159 } else {
3160 $divclasses[] = 'leaf';
3162 if (!empty($item->classes) && count($item->classes)>0) {
3163 $divclasses[] = join(' ', $item->classes);
3165 $divattr = array('class'=>join(' ', $divclasses));
3166 if (!empty($item->id)) {
3167 $divattr['id'] = $item->id;
3169 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3170 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3171 $content = html_writer::empty_tag('hr') . $content;
3173 $content = html_writer::tag('li', $content, $liattr);
3174 $lis[] = $content;
3176 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3180 * Returns a search box.
3182 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3183 * @return string HTML with the search form hidden by default.
3185 public function search_box($id = false) {
3186 global $CFG;
3188 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3189 // result in an extra included file for each site, even the ones where global search
3190 // is disabled.
3191 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3192 return '';
3195 if ($id == false) {
3196 $id = uniqid();
3197 } else {
3198 // Needs to be cleaned, we use it for the input id.
3199 $id = clean_param($id, PARAM_ALPHANUMEXT);
3202 // JS to animate the form.
3203 $this->page->requires->js_call_amd('core/search-input', 'init', array($id));
3205 $searchicon = html_writer::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
3206 array('role' => 'button', 'tabindex' => 0));
3207 $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot . '/search/index.php');
3208 $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
3209 'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id, 'class' => 'form-control');
3211 $contents = html_writer::tag('label', get_string('enteryoursearchquery', 'search'),
3212 array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer::tag('input', '', $inputattrs);
3213 if ($this->page->context && $this->page->context->contextlevel !== CONTEXT_SYSTEM) {
3214 $contents .= html_writer::empty_tag('input', ['type' => 'hidden',
3215 'name' => 'context', 'value' => $this->page->context->id]);
3217 $searchinput = html_writer::tag('form', $contents, $formattrs);
3219 return html_writer::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper nav-link', 'id' => $id));
3223 * Allow plugins to provide some content to be rendered in the navbar.
3224 * The plugin must define a PLUGIN_render_navbar_output function that returns
3225 * the HTML they wish to add to the navbar.
3227 * @return string HTML for the navbar
3229 public function navbar_plugin_output() {
3230 $output = '';
3232 // Give subsystems an opportunity to inject extra html content. The callback
3233 // must always return a string containing valid html.
3234 foreach (\core_component::get_core_subsystems() as $name => $path) {
3235 if ($path) {
3236 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3240 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3241 foreach ($pluginsfunction as $plugintype => $plugins) {
3242 foreach ($plugins as $pluginfunction) {
3243 $output .= $pluginfunction($this);
3248 return $output;
3252 * Construct a user menu, returning HTML that can be echoed out by a
3253 * layout file.
3255 * @param stdClass $user A user object, usually $USER.
3256 * @param bool $withlinks true if a dropdown should be built.
3257 * @return string HTML fragment.
3259 public function user_menu($user = null, $withlinks = null) {
3260 global $USER, $CFG;
3261 require_once($CFG->dirroot . '/user/lib.php');
3263 if (is_null($user)) {
3264 $user = $USER;
3267 // Note: this behaviour is intended to match that of core_renderer::login_info,
3268 // but should not be considered to be good practice; layout options are
3269 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3270 if (is_null($withlinks)) {
3271 $withlinks = empty($this->page->layout_options['nologinlinks']);
3274 // Add a class for when $withlinks is false.
3275 $usermenuclasses = 'usermenu';
3276 if (!$withlinks) {
3277 $usermenuclasses .= ' withoutlinks';
3280 $returnstr = "";
3282 // If during initial install, return the empty return string.
3283 if (during_initial_install()) {
3284 return $returnstr;
3287 $loginpage = $this->is_login_page();
3288 $loginurl = get_login_url();
3289 // If not logged in, show the typical not-logged-in string.
3290 if (!isloggedin()) {
3291 $returnstr = get_string('loggedinnot', 'moodle');
3292 if (!$loginpage) {
3293 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3295 return html_writer::div(
3296 html_writer::span(
3297 $returnstr,
3298 'login'
3300 $usermenuclasses
3305 // If logged in as a guest user, show a string to that effect.
3306 if (isguestuser()) {
3307 $returnstr = get_string('loggedinasguest');
3308 if (!$loginpage && $withlinks) {
3309 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3312 return html_writer::div(
3313 html_writer::span(
3314 $returnstr,
3315 'login'
3317 $usermenuclasses
3321 // Get some navigation opts.
3322 $opts = user_get_user_navigation_info($user, $this->page);
3324 $avatarclasses = "avatars";
3325 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3326 $usertextcontents = $opts->metadata['userfullname'];
3328 // Other user.
3329 if (!empty($opts->metadata['asotheruser'])) {
3330 $avatarcontents .= html_writer::span(
3331 $opts->metadata['realuseravatar'],
3332 'avatar realuser'
3334 $usertextcontents = $opts->metadata['realuserfullname'];
3335 $usertextcontents .= html_writer::tag(
3336 'span',
3337 get_string(
3338 'loggedinas',
3339 'moodle',
3340 html_writer::span(
3341 $opts->metadata['userfullname'],
3342 'value'
3345 array('class' => 'meta viewingas')
3349 // Role.
3350 if (!empty($opts->metadata['asotherrole'])) {
3351 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3352 $usertextcontents .= html_writer::span(
3353 $opts->metadata['rolename'],
3354 'meta role role-' . $role
3358 // User login failures.
3359 if (!empty($opts->metadata['userloginfail'])) {
3360 $usertextcontents .= html_writer::span(
3361 $opts->metadata['userloginfail'],
3362 'meta loginfailures'
3366 // MNet.
3367 if (!empty($opts->metadata['asmnetuser'])) {
3368 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3369 $usertextcontents .= html_writer::span(
3370 $opts->metadata['mnetidprovidername'],
3371 'meta mnet mnet-' . $mnet
3375 $returnstr .= html_writer::span(
3376 html_writer::span($usertextcontents, 'usertext mr-1') .
3377 html_writer::span($avatarcontents, $avatarclasses),
3378 'userbutton'
3381 // Create a divider (well, a filler).
3382 $divider = new action_menu_filler();
3383 $divider->primary = false;
3385 $am = new action_menu();
3386 $am->set_menu_trigger(
3387 $returnstr
3389 $am->set_action_label(get_string('usermenu'));
3390 $am->set_alignment(action_menu::TR, action_menu::BR);
3391 $am->set_nowrap_on_items();
3392 if ($withlinks) {
3393 $navitemcount = count($opts->navitems);
3394 $idx = 0;
3395 foreach ($opts->navitems as $key => $value) {
3397 switch ($value->itemtype) {
3398 case 'divider':
3399 // If the nav item is a divider, add one and skip link processing.
3400 $am->add($divider);
3401 break;
3403 case 'invalid':
3404 // Silently skip invalid entries (should we post a notification?).
3405 break;
3407 case 'link':
3408 // Process this as a link item.
3409 $pix = null;
3410 if (isset($value->pix) && !empty($value->pix)) {
3411 $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
3412 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3413 $value->title = html_writer::img(
3414 $value->imgsrc,
3415 $value->title,
3416 array('class' => 'iconsmall')
3417 ) . $value->title;
3420 $al = new action_menu_link_secondary(
3421 $value->url,
3422 $pix,
3423 $value->title,
3424 array('class' => 'icon')
3426 if (!empty($value->titleidentifier)) {
3427 $al->attributes['data-title'] = $value->titleidentifier;
3429 $am->add($al);
3430 break;
3433 $idx++;
3435 // Add dividers after the first item and before the last item.
3436 if ($idx == 1 || $idx == $navitemcount - 1) {
3437 $am->add($divider);
3442 return html_writer::div(
3443 $this->render($am),
3444 $usermenuclasses
3449 * This renders the navbar.
3450 * Uses bootstrap compatible html.
3452 public function navbar() {
3453 return $this->render_from_template('core/navbar', $this->page->navbar);
3457 * Renders a breadcrumb navigation node object.
3459 * @param breadcrumb_navigation_node $item The navigation node to render.
3460 * @return string HTML fragment
3462 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3464 if ($item->action instanceof moodle_url) {
3465 $content = $item->get_content();
3466 $title = $item->get_title();
3467 $attributes = array();
3468 $attributes['itemprop'] = 'url';
3469 if ($title !== '') {
3470 $attributes['title'] = $title;
3472 if ($item->hidden) {
3473 $attributes['class'] = 'dimmed_text';
3475 if ($item->is_last()) {
3476 $attributes['aria-current'] = 'page';
3478 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3479 $content = html_writer::link($item->action, $content, $attributes);
3481 $attributes = array();
3482 $attributes['itemscope'] = '';
3483 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3484 $content = html_writer::tag('span', $content, $attributes);
3486 } else {
3487 $content = $this->render_navigation_node($item);
3489 return $content;
3493 * Renders a navigation node object.
3495 * @param navigation_node $item The navigation node to render.
3496 * @return string HTML fragment
3498 protected function render_navigation_node(navigation_node $item) {
3499 $content = $item->get_content();
3500 $title = $item->get_title();
3501 if ($item->icon instanceof renderable && !$item->hideicon) {
3502 $icon = $this->render($item->icon);
3503 $content = $icon.$content; // use CSS for spacing of icons
3505 if ($item->helpbutton !== null) {
3506 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3508 if ($content === '') {
3509 return '';
3511 if ($item->action instanceof action_link) {
3512 $link = $item->action;
3513 if ($item->hidden) {
3514 $link->add_class('dimmed');
3516 if (!empty($content)) {
3517 // Providing there is content we will use that for the link content.
3518 $link->text = $content;
3520 $content = $this->render($link);
3521 } else if ($item->action instanceof moodle_url) {
3522 $attributes = array();
3523 if ($title !== '') {
3524 $attributes['title'] = $title;
3526 if ($item->hidden) {
3527 $attributes['class'] = 'dimmed_text';
3529 $content = html_writer::link($item->action, $content, $attributes);
3531 } else if (is_string($item->action) || empty($item->action)) {
3532 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3533 if ($title !== '') {
3534 $attributes['title'] = $title;
3536 if ($item->hidden) {
3537 $attributes['class'] = 'dimmed_text';
3539 $content = html_writer::tag('span', $content, $attributes);
3541 return $content;
3545 * Accessibility: Right arrow-like character is
3546 * used in the breadcrumb trail, course navigation menu
3547 * (previous/next activity), calendar, and search forum block.
3548 * If the theme does not set characters, appropriate defaults
3549 * are set automatically. Please DO NOT
3550 * use &lt; &gt; &raquo; - these are confusing for blind users.
3552 * @return string
3554 public function rarrow() {
3555 return $this->page->theme->rarrow;
3559 * Accessibility: Left arrow-like character is
3560 * used in the breadcrumb trail, course navigation menu
3561 * (previous/next activity), calendar, and search forum block.
3562 * If the theme does not set characters, appropriate defaults
3563 * are set automatically. Please DO NOT
3564 * use &lt; &gt; &raquo; - these are confusing for blind users.
3566 * @return string
3568 public function larrow() {
3569 return $this->page->theme->larrow;
3573 * Accessibility: Up arrow-like character is used in
3574 * the book heirarchical navigation.
3575 * If the theme does not set characters, appropriate defaults
3576 * are set automatically. Please DO NOT
3577 * use ^ - this is confusing for blind users.
3579 * @return string
3581 public function uarrow() {
3582 return $this->page->theme->uarrow;
3586 * Accessibility: Down arrow-like character.
3587 * If the theme does not set characters, appropriate defaults
3588 * are set automatically.
3590 * @return string
3592 public function darrow() {
3593 return $this->page->theme->darrow;
3597 * Returns the custom menu if one has been set
3599 * A custom menu can be configured by browsing to
3600 * Settings: Administration > Appearance > Themes > Theme settings
3601 * and then configuring the custommenu config setting as described.
3603 * Theme developers: DO NOT OVERRIDE! Please override function
3604 * {@link core_renderer::render_custom_menu()} instead.
3606 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3607 * @return string
3609 public function custom_menu($custommenuitems = '') {
3610 global $CFG;
3612 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3613 $custommenuitems = $CFG->custommenuitems;
3615 $custommenu = new custom_menu($custommenuitems, current_language());
3616 return $this->render_custom_menu($custommenu);
3620 * We want to show the custom menus as a list of links in the footer on small screens.
3621 * Just return the menu object exported so we can render it differently.
3623 public function custom_menu_flat() {
3624 global $CFG;
3625 $custommenuitems = '';
3627 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3628 $custommenuitems = $CFG->custommenuitems;
3630 $custommenu = new custom_menu($custommenuitems, current_language());
3631 $langs = get_string_manager()->get_list_of_translations();
3632 $haslangmenu = $this->lang_menu() != '';
3634 if ($haslangmenu) {
3635 $strlang = get_string('language');
3636 $currentlang = current_language();
3637 if (isset($langs[$currentlang])) {
3638 $currentlang = $langs[$currentlang];
3639 } else {
3640 $currentlang = $strlang;
3642 $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3643 foreach ($langs as $langtype => $langname) {
3644 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3648 return $custommenu->export_for_template($this);
3652 * Renders a custom menu object (located in outputcomponents.php)
3654 * The custom menu this method produces makes use of the YUI3 menunav widget
3655 * and requires very specific html elements and classes.
3657 * @staticvar int $menucount
3658 * @param custom_menu $menu
3659 * @return string
3661 protected function render_custom_menu(custom_menu $menu) {
3662 global $CFG;
3664 $langs = get_string_manager()->get_list_of_translations();
3665 $haslangmenu = $this->lang_menu() != '';
3667 if (!$menu->has_children() && !$haslangmenu) {
3668 return '';
3671 if ($haslangmenu) {
3672 $strlang = get_string('language');
3673 $currentlang = current_language();
3674 if (isset($langs[$currentlang])) {
3675 $currentlang = $langs[$currentlang];
3676 } else {
3677 $currentlang = $strlang;
3679 $this->language = $menu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3680 foreach ($langs as $langtype => $langname) {
3681 $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3685 $content = '';
3686 foreach ($menu->get_children() as $item) {
3687 $context = $item->export_for_template($this);
3688 $content .= $this->render_from_template('core/custom_menu_item', $context);
3691 return $content;
3695 * Renders a custom menu node as part of a submenu
3697 * The custom menu this method produces makes use of the YUI3 menunav widget
3698 * and requires very specific html elements and classes.
3700 * @see core:renderer::render_custom_menu()
3702 * @staticvar int $submenucount
3703 * @param custom_menu_item $menunode
3704 * @return string
3706 protected function render_custom_menu_item(custom_menu_item $menunode) {
3707 // Required to ensure we get unique trackable id's
3708 static $submenucount = 0;
3709 if ($menunode->has_children()) {
3710 // If the child has menus render it as a sub menu
3711 $submenucount++;
3712 $content = html_writer::start_tag('li');
3713 if ($menunode->get_url() !== null) {
3714 $url = $menunode->get_url();
3715 } else {
3716 $url = '#cm_submenu_'.$submenucount;
3718 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3719 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3720 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3721 $content .= html_writer::start_tag('ul');
3722 foreach ($menunode->get_children() as $menunode) {
3723 $content .= $this->render_custom_menu_item($menunode);
3725 $content .= html_writer::end_tag('ul');
3726 $content .= html_writer::end_tag('div');
3727 $content .= html_writer::end_tag('div');
3728 $content .= html_writer::end_tag('li');
3729 } else {
3730 // The node doesn't have children so produce a final menuitem.
3731 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3732 $content = '';
3733 if (preg_match("/^#+$/", $menunode->get_text())) {
3735 // This is a divider.
3736 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3737 } else {
3738 $content = html_writer::start_tag(
3739 'li',
3740 array(
3741 'class' => 'yui3-menuitem'
3744 if ($menunode->get_url() !== null) {
3745 $url = $menunode->get_url();
3746 } else {
3747 $url = '#';
3749 $content .= html_writer::link(
3750 $url,
3751 $menunode->get_text(),
3752 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3755 $content .= html_writer::end_tag('li');
3757 // Return the sub menu
3758 return $content;
3762 * Renders theme links for switching between default and other themes.
3764 * @return string
3766 protected function theme_switch_links() {
3768 $actualdevice = core_useragent::get_device_type();
3769 $currentdevice = $this->page->devicetypeinuse;
3770 $switched = ($actualdevice != $currentdevice);
3772 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3773 // The user is using the a default device and hasn't switched so don't shown the switch
3774 // device links.
3775 return '';
3778 if ($switched) {
3779 $linktext = get_string('switchdevicerecommended');
3780 $devicetype = $actualdevice;
3781 } else {
3782 $linktext = get_string('switchdevicedefault');
3783 $devicetype = 'default';
3785 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3787 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3788 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3789 $content .= html_writer::end_tag('div');
3791 return $content;
3795 * Renders tabs
3797 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3799 * Theme developers: In order to change how tabs are displayed please override functions
3800 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3802 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3803 * @param string|null $selected which tab to mark as selected, all parent tabs will
3804 * automatically be marked as activated
3805 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3806 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3807 * @return string
3809 public final function tabtree($tabs, $selected = null, $inactive = null) {
3810 return $this->render(new tabtree($tabs, $selected, $inactive));
3814 * Renders tabtree
3816 * @param tabtree $tabtree
3817 * @return string
3819 protected function render_tabtree(tabtree $tabtree) {
3820 if (empty($tabtree->subtree)) {
3821 return '';
3823 $data = $tabtree->export_for_template($this);
3824 return $this->render_from_template('core/tabtree', $data);
3828 * Renders tabobject (part of tabtree)
3830 * This function is called from {@link core_renderer::render_tabtree()}
3831 * and also it calls itself when printing the $tabobject subtree recursively.
3833 * Property $tabobject->level indicates the number of row of tabs.
3835 * @param tabobject $tabobject
3836 * @return string HTML fragment
3838 protected function render_tabobject(tabobject $tabobject) {
3839 $str = '';
3841 // Print name of the current tab.
3842 if ($tabobject instanceof tabtree) {
3843 // No name for tabtree root.
3844 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3845 // Tab name without a link. The <a> tag is used for styling.
3846 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3847 } else {
3848 // Tab name with a link.
3849 if (!($tabobject->link instanceof moodle_url)) {
3850 // backward compartibility when link was passed as quoted string
3851 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3852 } else {
3853 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3857 if (empty($tabobject->subtree)) {
3858 if ($tabobject->selected) {
3859 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3861 return $str;
3864 // Print subtree.
3865 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
3866 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3867 $cnt = 0;
3868 foreach ($tabobject->subtree as $tab) {
3869 $liclass = '';
3870 if (!$cnt) {
3871 $liclass .= ' first';
3873 if ($cnt == count($tabobject->subtree) - 1) {
3874 $liclass .= ' last';
3876 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3877 $liclass .= ' onerow';
3880 if ($tab->selected) {
3881 $liclass .= ' here selected';
3882 } else if ($tab->activated) {
3883 $liclass .= ' here active';
3886 // This will recursively call function render_tabobject() for each item in subtree.
3887 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3888 $cnt++;
3890 $str .= html_writer::end_tag('ul');
3893 return $str;
3897 * Get the HTML for blocks in the given region.
3899 * @since Moodle 2.5.1 2.6
3900 * @param string $region The region to get HTML for.
3901 * @return string HTML.
3903 public function blocks($region, $classes = array(), $tag = 'aside') {
3904 $displayregion = $this->page->apply_theme_region_manipulations($region);
3905 $classes = (array)$classes;
3906 $classes[] = 'block-region';
3907 $attributes = array(
3908 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3909 'class' => join(' ', $classes),
3910 'data-blockregion' => $displayregion,
3911 'data-droptarget' => '1'
3913 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3914 $content = $this->blocks_for_region($displayregion);
3915 } else {
3916 $content = '';
3918 return html_writer::tag($tag, $content, $attributes);
3922 * Renders a custom block region.
3924 * Use this method if you want to add an additional block region to the content of the page.
3925 * Please note this should only be used in special situations.
3926 * We want to leave the theme is control where ever possible!
3928 * This method must use the same method that the theme uses within its layout file.
3929 * As such it asks the theme what method it is using.
3930 * It can be one of two values, blocks or blocks_for_region (deprecated).
3932 * @param string $regionname The name of the custom region to add.
3933 * @return string HTML for the block region.
3935 public function custom_block_region($regionname) {
3936 if ($this->page->theme->get_block_render_method() === 'blocks') {
3937 return $this->blocks($regionname);
3938 } else {
3939 return $this->blocks_for_region($regionname);
3944 * Returns the CSS classes to apply to the body tag.
3946 * @since Moodle 2.5.1 2.6
3947 * @param array $additionalclasses Any additional classes to apply.
3948 * @return string
3950 public function body_css_classes(array $additionalclasses = array()) {
3951 return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses);
3955 * The ID attribute to apply to the body tag.
3957 * @since Moodle 2.5.1 2.6
3958 * @return string
3960 public function body_id() {
3961 return $this->page->bodyid;
3965 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
3967 * @since Moodle 2.5.1 2.6
3968 * @param string|array $additionalclasses Any additional classes to give the body tag,
3969 * @return string
3971 public function body_attributes($additionalclasses = array()) {
3972 if (!is_array($additionalclasses)) {
3973 $additionalclasses = explode(' ', $additionalclasses);
3975 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
3979 * Gets HTML for the page heading.
3981 * @since Moodle 2.5.1 2.6
3982 * @param string $tag The tag to encase the heading in. h1 by default.
3983 * @return string HTML.
3985 public function page_heading($tag = 'h1') {
3986 return html_writer::tag($tag, $this->page->heading);
3990 * Gets the HTML for the page heading button.
3992 * @since Moodle 2.5.1 2.6
3993 * @return string HTML.
3995 public function page_heading_button() {
3996 return $this->page->button;
4000 * Returns the Moodle docs link to use for this page.
4002 * @since Moodle 2.5.1 2.6
4003 * @param string $text
4004 * @return string
4006 public function page_doc_link($text = null) {
4007 if ($text === null) {
4008 $text = get_string('moodledocslink');
4010 $path = page_get_doc_link_path($this->page);
4011 if (!$path) {
4012 return '';
4014 return $this->doc_link($path, $text);
4018 * Returns the page heading menu.
4020 * @since Moodle 2.5.1 2.6
4021 * @return string HTML.
4023 public function page_heading_menu() {
4024 return $this->page->headingmenu;
4028 * Returns the title to use on the page.
4030 * @since Moodle 2.5.1 2.6
4031 * @return string
4033 public function page_title() {
4034 return $this->page->title;
4038 * Returns the moodle_url for the favicon.
4040 * @since Moodle 2.5.1 2.6
4041 * @return moodle_url The moodle_url for the favicon
4043 public function favicon() {
4044 return $this->image_url('favicon', 'theme');
4048 * Renders preferences groups.
4050 * @param preferences_groups $renderable The renderable
4051 * @return string The output.
4053 public function render_preferences_groups(preferences_groups $renderable) {
4054 return $this->render_from_template('core/preferences_groups', $renderable);
4058 * Renders preferences group.
4060 * @param preferences_group $renderable The renderable
4061 * @return string The output.
4063 public function render_preferences_group(preferences_group $renderable) {
4064 $html = '';
4065 $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4066 $html .= $this->heading($renderable->title, 3);
4067 $html .= html_writer::start_tag('ul');
4068 foreach ($renderable->nodes as $node) {
4069 if ($node->has_children()) {
4070 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4072 $html .= html_writer::tag('li', $this->render($node));
4074 $html .= html_writer::end_tag('ul');
4075 $html .= html_writer::end_tag('div');
4076 return $html;
4079 public function context_header($headerinfo = null, $headinglevel = 1) {
4080 global $DB, $USER, $CFG, $SITE;
4081 require_once($CFG->dirroot . '/user/lib.php');
4082 $context = $this->page->context;
4083 $heading = null;
4084 $imagedata = null;
4085 $subheader = null;
4086 $userbuttons = null;
4088 if ($this->should_display_main_logo($headinglevel)) {
4089 $sitename = format_string($SITE->fullname, true, array('context' => context_course::instance(SITEID)));
4090 return html_writer::div(html_writer::empty_tag('img', [
4091 'src' => $this->get_logo_url(null, 150), 'alt' => $sitename, 'class' => 'img-fluid']), 'logo');
4094 // Make sure to use the heading if it has been set.
4095 if (isset($headerinfo['heading'])) {
4096 $heading = $headerinfo['heading'];
4099 // The user context currently has images and buttons. Other contexts may follow.
4100 if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
4101 if (isset($headerinfo['user'])) {
4102 $user = $headerinfo['user'];
4103 } else {
4104 // Look up the user information if it is not supplied.
4105 $user = $DB->get_record('user', array('id' => $context->instanceid));
4108 // If the user context is set, then use that for capability checks.
4109 if (isset($headerinfo['usercontext'])) {
4110 $context = $headerinfo['usercontext'];
4113 // Only provide user information if the user is the current user, or a user which the current user can view.
4114 // When checking user_can_view_profile(), either:
4115 // If the page context is course, check the course context (from the page object) or;
4116 // If page context is NOT course, then check across all courses.
4117 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4119 if (user_can_view_profile($user, $course)) {
4120 // Use the user's full name if the heading isn't set.
4121 if (!isset($heading)) {
4122 $heading = fullname($user);
4125 $imagedata = $this->user_picture($user, array('size' => 100));
4127 // Check to see if we should be displaying a message button.
4128 if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
4129 $userbuttons = array(
4130 'messages' => array(
4131 'buttontype' => 'message',
4132 'title' => get_string('message', 'message'),
4133 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4134 'image' => 'message',
4135 'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
4136 'page' => $this->page
4140 if ($USER->id != $user->id) {
4141 $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4142 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4143 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4144 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4145 $userbuttons['togglecontact'] = array(
4146 'buttontype' => 'togglecontact',
4147 'title' => get_string($contacttitle, 'message'),
4148 'url' => new moodle_url('/message/index.php', array(
4149 'user1' => $USER->id,
4150 'user2' => $user->id,
4151 $contacturlaction => $user->id,
4152 'sesskey' => sesskey())
4154 'image' => $contactimage,
4155 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4156 'page' => $this->page
4160 $this->page->requires->string_for_js('changesmadereallygoaway', 'moodle');
4162 } else {
4163 $heading = null;
4167 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4168 return $this->render_context_header($contextheader);
4172 * Renders the skip links for the page.
4174 * @param array $links List of skip links.
4175 * @return string HTML for the skip links.
4177 public function render_skip_links($links) {
4178 $context = [ 'links' => []];
4180 foreach ($links as $url => $text) {
4181 $context['links'][] = [ 'url' => $url, 'text' => $text];
4184 return $this->render_from_template('core/skip_links', $context);
4188 * Renders the header bar.
4190 * @param context_header $contextheader Header bar object.
4191 * @return string HTML for the header bar.
4193 protected function render_context_header(context_header $contextheader) {
4195 $showheader = empty($this->page->layout_options['nocontextheader']);
4196 if (!$showheader) {
4197 return '';
4200 // All the html stuff goes here.
4201 $html = html_writer::start_div('page-context-header');
4203 // Image data.
4204 if (isset($contextheader->imagedata)) {
4205 // Header specific image.
4206 $html .= html_writer::div($contextheader->imagedata, 'page-header-image');
4209 // Headings.
4210 if (!isset($contextheader->heading)) {
4211 $headings = $this->heading($this->page->heading, $contextheader->headinglevel);
4212 } else {
4213 $headings = $this->heading($contextheader->heading, $contextheader->headinglevel);
4216 $html .= html_writer::tag('div', $headings, array('class' => 'page-header-headings'));
4218 // Buttons.
4219 if (isset($contextheader->additionalbuttons)) {
4220 $html .= html_writer::start_div('btn-group header-button-group');
4221 foreach ($contextheader->additionalbuttons as $button) {
4222 if (!isset($button->page)) {
4223 // Include js for messaging.
4224 if ($button['buttontype'] === 'togglecontact') {
4225 \core_message\helper::togglecontact_requirejs();
4227 if ($button['buttontype'] === 'message') {
4228 \core_message\helper::messageuser_requirejs();
4230 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4231 'class' => 'iconsmall',
4232 'role' => 'presentation'
4234 $image .= html_writer::span($button['title'], 'header-button-title');
4235 } else {
4236 $image = html_writer::empty_tag('img', array(
4237 'src' => $button['formattedimage'],
4238 'role' => 'presentation'
4241 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4243 $html .= html_writer::end_div();
4245 $html .= html_writer::end_div();
4247 return $html;
4251 * Wrapper for header elements.
4253 * @return string HTML to display the main header.
4255 public function full_header() {
4256 global $PAGE;
4258 $header = new stdClass();
4259 $header->settingsmenu = $this->context_header_settings_menu();
4260 $header->contextheader = $this->context_header();
4261 $header->hasnavbar = empty($PAGE->layout_options['nonavbar']);
4262 $header->navbar = $this->navbar();
4263 $header->pageheadingbutton = $this->page_heading_button();
4264 $header->courseheader = $this->course_header();
4265 return $this->render_from_template('core/full_header', $header);
4269 * This is an optional menu that can be added to a layout by a theme. It contains the
4270 * menu for the course administration, only on the course main page.
4272 * @return string
4274 public function context_header_settings_menu() {
4275 $context = $this->page->context;
4276 $menu = new action_menu();
4278 $items = $this->page->navbar->get_items();
4279 $currentnode = end($items);
4281 $showcoursemenu = false;
4282 $showfrontpagemenu = false;
4283 $showusermenu = false;
4285 // We are on the course home page.
4286 if (($context->contextlevel == CONTEXT_COURSE) &&
4287 !empty($currentnode) &&
4288 ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
4289 $showcoursemenu = true;
4292 $courseformat = course_get_format($this->page->course);
4293 // This is a single activity course format, always show the course menu on the activity main page.
4294 if ($context->contextlevel == CONTEXT_MODULE &&
4295 !$courseformat->has_view_page()) {
4297 $this->page->navigation->initialise();
4298 $activenode = $this->page->navigation->find_active_node();
4299 // If the settings menu has been forced then show the menu.
4300 if ($this->page->is_settings_menu_forced()) {
4301 $showcoursemenu = true;
4302 } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
4303 $activenode->type == navigation_node::TYPE_RESOURCE)) {
4305 // We only want to show the menu on the first page of the activity. This means
4306 // the breadcrumb has no additional nodes.
4307 if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
4308 $showcoursemenu = true;
4313 // This is the site front page.
4314 if ($context->contextlevel == CONTEXT_COURSE &&
4315 !empty($currentnode) &&
4316 $currentnode->key === 'home') {
4317 $showfrontpagemenu = true;
4320 // This is the user profile page.
4321 if ($context->contextlevel == CONTEXT_USER &&
4322 !empty($currentnode) &&
4323 ($currentnode->key === 'myprofile')) {
4324 $showusermenu = true;
4327 if ($showfrontpagemenu) {
4328 $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
4329 if ($settingsnode) {
4330 // Build an action menu based on the visible nodes from this navigation tree.
4331 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4333 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4334 if ($skipped) {
4335 $text = get_string('morenavigationlinks');
4336 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4337 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4338 $menu->add_secondary_action($link);
4341 } else if ($showcoursemenu) {
4342 $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
4343 if ($settingsnode) {
4344 // Build an action menu based on the visible nodes from this navigation tree.
4345 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4347 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4348 if ($skipped) {
4349 $text = get_string('morenavigationlinks');
4350 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4351 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4352 $menu->add_secondary_action($link);
4355 } else if ($showusermenu) {
4356 // Get the course admin node from the settings navigation.
4357 $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
4358 if ($settingsnode) {
4359 // Build an action menu based on the visible nodes from this navigation tree.
4360 $this->build_action_menu_from_navigation($menu, $settingsnode);
4364 return $this->render($menu);
4368 * Take a node in the nav tree and make an action menu out of it.
4369 * The links are injected in the action menu.
4371 * @param action_menu $menu
4372 * @param navigation_node $node
4373 * @param boolean $indent
4374 * @param boolean $onlytopleafnodes
4375 * @return boolean nodesskipped - True if nodes were skipped in building the menu
4377 protected function build_action_menu_from_navigation(action_menu $menu,
4378 navigation_node $node,
4379 $indent = false,
4380 $onlytopleafnodes = false) {
4381 $skipped = false;
4382 // Build an action menu based on the visible nodes from this navigation tree.
4383 foreach ($node->children as $menuitem) {
4384 if ($menuitem->display) {
4385 if ($onlytopleafnodes && $menuitem->children->count()) {
4386 $skipped = true;
4387 continue;
4389 if ($menuitem->action) {
4390 if ($menuitem->action instanceof action_link) {
4391 $link = $menuitem->action;
4392 // Give preference to setting icon over action icon.
4393 if (!empty($menuitem->icon)) {
4394 $link->icon = $menuitem->icon;
4396 } else {
4397 $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
4399 } else {
4400 if ($onlytopleafnodes) {
4401 $skipped = true;
4402 continue;
4404 $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
4406 if ($indent) {
4407 $link->add_class('ml-4');
4409 if (!empty($menuitem->classes)) {
4410 $link->add_class(implode(" ", $menuitem->classes));
4413 $menu->add_secondary_action($link);
4414 $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
4417 return $skipped;
4421 * This is an optional menu that can be added to a layout by a theme. It contains the
4422 * menu for the most specific thing from the settings block. E.g. Module administration.
4424 * @return string
4426 public function region_main_settings_menu() {
4427 $context = $this->page->context;
4428 $menu = new action_menu();
4430 if ($context->contextlevel == CONTEXT_MODULE) {
4432 $this->page->navigation->initialise();
4433 $node = $this->page->navigation->find_active_node();
4434 $buildmenu = false;
4435 // If the settings menu has been forced then show the menu.
4436 if ($this->page->is_settings_menu_forced()) {
4437 $buildmenu = true;
4438 } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
4439 $node->type == navigation_node::TYPE_RESOURCE)) {
4441 $items = $this->page->navbar->get_items();
4442 $navbarnode = end($items);
4443 // We only want to show the menu on the first page of the activity. This means
4444 // the breadcrumb has no additional nodes.
4445 if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
4446 $buildmenu = true;
4449 if ($buildmenu) {
4450 // Get the course admin node from the settings navigation.
4451 $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
4452 if ($node) {
4453 // Build an action menu based on the visible nodes from this navigation tree.
4454 $this->build_action_menu_from_navigation($menu, $node);
4458 } else if ($context->contextlevel == CONTEXT_COURSECAT) {
4459 // For course category context, show category settings menu, if we're on the course category page.
4460 if ($this->page->pagetype === 'course-index-category') {
4461 $node = $this->page->settingsnav->find('categorysettings', navigation_node::TYPE_CONTAINER);
4462 if ($node) {
4463 // Build an action menu based on the visible nodes from this navigation tree.
4464 $this->build_action_menu_from_navigation($menu, $node);
4468 } else {
4469 $items = $this->page->navbar->get_items();
4470 $navbarnode = end($items);
4472 if ($navbarnode && ($navbarnode->key === 'participants')) {
4473 $node = $this->page->settingsnav->find('users', navigation_node::TYPE_CONTAINER);
4474 if ($node) {
4475 // Build an action menu based on the visible nodes from this navigation tree.
4476 $this->build_action_menu_from_navigation($menu, $node);
4481 return $this->render($menu);
4485 * Displays the list of tags associated with an entry
4487 * @param array $tags list of instances of core_tag or stdClass
4488 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4489 * to use default, set to '' (empty string) to omit the label completely
4490 * @param string $classes additional classes for the enclosing div element
4491 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4492 * will be appended to the end, JS will toggle the rest of the tags
4493 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4494 * @return string
4496 public function tag_list($tags, $label = null, $classes = '', $limit = 10, $pagecontext = null) {
4497 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext);
4498 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4502 * Renders element for inline editing of any value
4504 * @param \core\output\inplace_editable $element
4505 * @return string
4507 public function render_inplace_editable(\core\output\inplace_editable $element) {
4508 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4512 * Renders a bar chart.
4514 * @param \core\chart_bar $chart The chart.
4515 * @return string.
4517 public function render_chart_bar(\core\chart_bar $chart) {
4518 return $this->render_chart($chart);
4522 * Renders a line chart.
4524 * @param \core\chart_line $chart The chart.
4525 * @return string.
4527 public function render_chart_line(\core\chart_line $chart) {
4528 return $this->render_chart($chart);
4532 * Renders a pie chart.
4534 * @param \core\chart_pie $chart The chart.
4535 * @return string.
4537 public function render_chart_pie(\core\chart_pie $chart) {
4538 return $this->render_chart($chart);
4542 * Renders a chart.
4544 * @param \core\chart_base $chart The chart.
4545 * @param bool $withtable Whether to include a data table with the chart.
4546 * @return string.
4548 public function render_chart(\core\chart_base $chart, $withtable = true) {
4549 $chartdata = json_encode($chart);
4550 return $this->render_from_template('core/chart', (object) [
4551 'chartdata' => $chartdata,
4552 'withtable' => $withtable
4557 * Renders the login form.
4559 * @param \core_auth\output\login $form The renderable.
4560 * @return string
4562 public function render_login(\core_auth\output\login $form) {
4563 global $CFG, $SITE;
4565 $context = $form->export_for_template($this);
4567 // Override because rendering is not supported in template yet.
4568 if ($CFG->rememberusername == 0) {
4569 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabledonlysession');
4570 } else {
4571 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
4573 $context->errorformatted = $this->error_text($context->error);
4574 $url = $this->get_logo_url();
4575 if ($url) {
4576 $url = $url->out(false);
4578 $context->logourl = $url;
4579 $context->sitename = format_string($SITE->fullname, true,
4580 ['context' => context_course::instance(SITEID), "escape" => false]);
4582 return $this->render_from_template('core/loginform', $context);
4586 * Renders an mform element from a template.
4588 * @param HTML_QuickForm_element $element element
4589 * @param bool $required if input is required field
4590 * @param bool $advanced if input is an advanced field
4591 * @param string $error error message to display
4592 * @param bool $ingroup True if this element is rendered as part of a group
4593 * @return mixed string|bool
4595 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4596 $templatename = 'core_form/element-' . $element->getType();
4597 if ($ingroup) {
4598 $templatename .= "-inline";
4600 try {
4601 // We call this to generate a file not found exception if there is no template.
4602 // We don't want to call export_for_template if there is no template.
4603 core\output\mustache_template_finder::get_template_filepath($templatename);
4605 if ($element instanceof templatable) {
4606 $elementcontext = $element->export_for_template($this);
4608 $helpbutton = '';
4609 if (method_exists($element, 'getHelpButton')) {
4610 $helpbutton = $element->getHelpButton();
4612 $label = $element->getLabel();
4613 $text = '';
4614 if (method_exists($element, 'getText')) {
4615 // There currently exists code that adds a form element with an empty label.
4616 // If this is the case then set the label to the description.
4617 if (empty($label)) {
4618 $label = $element->getText();
4619 } else {
4620 $text = $element->getText();
4624 // Generate the form element wrapper ids and names to pass to the template.
4625 // This differs between group and non-group elements.
4626 if ($element->getType() === 'group') {
4627 // Group element.
4628 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
4629 $elementcontext['wrapperid'] = $elementcontext['id'];
4631 // Ensure group elements pass through the group name as the element name.
4632 $elementcontext['name'] = $elementcontext['groupname'];
4633 } else {
4634 // Non grouped element.
4635 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
4636 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
4639 $context = array(
4640 'element' => $elementcontext,
4641 'label' => $label,
4642 'text' => $text,
4643 'required' => $required,
4644 'advanced' => $advanced,
4645 'helpbutton' => $helpbutton,
4646 'error' => $error
4648 return $this->render_from_template($templatename, $context);
4650 } catch (Exception $e) {
4651 // No template for this element.
4652 return false;
4657 * Render the login signup form into a nice template for the theme.
4659 * @param mform $form
4660 * @return string
4662 public function render_login_signup_form($form) {
4663 global $SITE;
4665 $context = $form->export_for_template($this);
4666 $url = $this->get_logo_url();
4667 if ($url) {
4668 $url = $url->out(false);
4670 $context['logourl'] = $url;
4671 $context['sitename'] = format_string($SITE->fullname, true,
4672 ['context' => context_course::instance(SITEID), "escape" => false]);
4674 return $this->render_from_template('core/signup_form_layout', $context);
4678 * Render the verify age and location page into a nice template for the theme.
4680 * @param \core_auth\output\verify_age_location_page $page The renderable
4681 * @return string
4683 protected function render_verify_age_location_page($page) {
4684 $context = $page->export_for_template($this);
4686 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4690 * Render the digital minor contact information page into a nice template for the theme.
4692 * @param \core_auth\output\digital_minor_page $page The renderable
4693 * @return string
4695 protected function render_digital_minor_page($page) {
4696 $context = $page->export_for_template($this);
4698 return $this->render_from_template('core/auth_digital_minor_page', $context);
4702 * Renders a progress bar.
4704 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4706 * @param progress_bar $bar The bar.
4707 * @return string HTML fragment
4709 public function render_progress_bar(progress_bar $bar) {
4710 global $PAGE;
4711 $data = $bar->export_for_template($this);
4712 return $this->render_from_template('core/progress_bar', $data);
4717 * A renderer that generates output for command-line scripts.
4719 * The implementation of this renderer is probably incomplete.
4721 * @copyright 2009 Tim Hunt
4722 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4723 * @since Moodle 2.0
4724 * @package core
4725 * @category output
4727 class core_renderer_cli extends core_renderer {
4730 * Returns the page header.
4732 * @return string HTML fragment
4734 public function header() {
4735 return $this->page->heading . "\n";
4739 * Returns a template fragment representing a Heading.
4741 * @param string $text The text of the heading
4742 * @param int $level The level of importance of the heading
4743 * @param string $classes A space-separated list of CSS classes
4744 * @param string $id An optional ID
4745 * @return string A template fragment for a heading
4747 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4748 $text .= "\n";
4749 switch ($level) {
4750 case 1:
4751 return '=>' . $text;
4752 case 2:
4753 return '-->' . $text;
4754 default:
4755 return $text;
4760 * Returns a template fragment representing a fatal error.
4762 * @param string $message The message to output
4763 * @param string $moreinfourl URL where more info can be found about the error
4764 * @param string $link Link for the Continue button
4765 * @param array $backtrace The execution backtrace
4766 * @param string $debuginfo Debugging information
4767 * @return string A template fragment for a fatal error
4769 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4770 global $CFG;
4772 $output = "!!! $message !!!\n";
4774 if ($CFG->debugdeveloper) {
4775 if (!empty($debuginfo)) {
4776 $output .= $this->notification($debuginfo, 'notifytiny');
4778 if (!empty($backtrace)) {
4779 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
4783 return $output;
4787 * Returns a template fragment representing a notification.
4789 * @param string $message The message to print out.
4790 * @param string $type The type of notification. See constants on \core\output\notification.
4791 * @return string A template fragment for a notification
4793 public function notification($message, $type = null) {
4794 $message = clean_text($message);
4795 if ($type === 'notifysuccess' || $type === 'success') {
4796 return "++ $message ++\n";
4798 return "!! $message !!\n";
4802 * There is no footer for a cli request, however we must override the
4803 * footer method to prevent the default footer.
4805 public function footer() {}
4808 * Render a notification (that is, a status message about something that has
4809 * just happened).
4811 * @param \core\output\notification $notification the notification to print out
4812 * @return string plain text output
4814 public function render_notification(\core\output\notification $notification) {
4815 return $this->notification($notification->get_message(), $notification->get_message_type());
4821 * A renderer that generates output for ajax scripts.
4823 * This renderer prevents accidental sends back only json
4824 * encoded error messages, all other output is ignored.
4826 * @copyright 2010 Petr Skoda
4827 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4828 * @since Moodle 2.0
4829 * @package core
4830 * @category output
4832 class core_renderer_ajax extends core_renderer {
4835 * Returns a template fragment representing a fatal error.
4837 * @param string $message The message to output
4838 * @param string $moreinfourl URL where more info can be found about the error
4839 * @param string $link Link for the Continue button
4840 * @param array $backtrace The execution backtrace
4841 * @param string $debuginfo Debugging information
4842 * @return string A template fragment for a fatal error
4844 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4845 global $CFG;
4847 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
4849 $e = new stdClass();
4850 $e->error = $message;
4851 $e->errorcode = $errorcode;
4852 $e->stacktrace = NULL;
4853 $e->debuginfo = NULL;
4854 $e->reproductionlink = NULL;
4855 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
4856 $link = (string) $link;
4857 if ($link) {
4858 $e->reproductionlink = $link;
4860 if (!empty($debuginfo)) {
4861 $e->debuginfo = $debuginfo;
4863 if (!empty($backtrace)) {
4864 $e->stacktrace = format_backtrace($backtrace, true);
4867 $this->header();
4868 return json_encode($e);
4872 * Used to display a notification.
4873 * For the AJAX notifications are discarded.
4875 * @param string $message The message to print out.
4876 * @param string $type The type of notification. See constants on \core\output\notification.
4878 public function notification($message, $type = null) {}
4881 * Used to display a redirection message.
4882 * AJAX redirections should not occur and as such redirection messages
4883 * are discarded.
4885 * @param moodle_url|string $encodedurl
4886 * @param string $message
4887 * @param int $delay
4888 * @param bool $debugdisableredirect
4889 * @param string $messagetype The type of notification to show the message in.
4890 * See constants on \core\output\notification.
4892 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
4893 $messagetype = \core\output\notification::NOTIFY_INFO) {}
4896 * Prepares the start of an AJAX output.
4898 public function header() {
4899 // unfortunately YUI iframe upload does not support application/json
4900 if (!empty($_FILES)) {
4901 @header('Content-type: text/plain; charset=utf-8');
4902 if (!core_useragent::supports_json_contenttype()) {
4903 @header('X-Content-Type-Options: nosniff');
4905 } else if (!core_useragent::supports_json_contenttype()) {
4906 @header('Content-type: text/plain; charset=utf-8');
4907 @header('X-Content-Type-Options: nosniff');
4908 } else {
4909 @header('Content-type: application/json; charset=utf-8');
4912 // Headers to make it not cacheable and json
4913 @header('Cache-Control: no-store, no-cache, must-revalidate');
4914 @header('Cache-Control: post-check=0, pre-check=0', false);
4915 @header('Pragma: no-cache');
4916 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
4917 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
4918 @header('Accept-Ranges: none');
4922 * There is no footer for an AJAX request, however we must override the
4923 * footer method to prevent the default footer.
4925 public function footer() {}
4928 * No need for headers in an AJAX request... this should never happen.
4929 * @param string $text
4930 * @param int $level
4931 * @param string $classes
4932 * @param string $id
4934 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
4940 * The maintenance renderer.
4942 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
4943 * is running a maintenance related task.
4944 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
4946 * @since Moodle 2.6
4947 * @package core
4948 * @category output
4949 * @copyright 2013 Sam Hemelryk
4950 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4952 class core_renderer_maintenance extends core_renderer {
4955 * Initialises the renderer instance.
4957 * @param moodle_page $page
4958 * @param string $target
4959 * @throws coding_exception
4961 public function __construct(moodle_page $page, $target) {
4962 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
4963 throw new coding_exception('Invalid request for the maintenance renderer.');
4965 parent::__construct($page, $target);
4969 * Does nothing. The maintenance renderer cannot produce blocks.
4971 * @param block_contents $bc
4972 * @param string $region
4973 * @return string
4975 public function block(block_contents $bc, $region) {
4976 return '';
4980 * Does nothing. The maintenance renderer cannot produce blocks.
4982 * @param string $region
4983 * @param array $classes
4984 * @param string $tag
4985 * @return string
4987 public function blocks($region, $classes = array(), $tag = 'aside') {
4988 return '';
4992 * Does nothing. The maintenance renderer cannot produce blocks.
4994 * @param string $region
4995 * @return string
4997 public function blocks_for_region($region) {
4998 return '';
5002 * Does nothing. The maintenance renderer cannot produce a course content header.
5004 * @param bool $onlyifnotcalledbefore
5005 * @return string
5007 public function course_content_header($onlyifnotcalledbefore = false) {
5008 return '';
5012 * Does nothing. The maintenance renderer cannot produce a course content footer.
5014 * @param bool $onlyifnotcalledbefore
5015 * @return string
5017 public function course_content_footer($onlyifnotcalledbefore = false) {
5018 return '';
5022 * Does nothing. The maintenance renderer cannot produce a course header.
5024 * @return string
5026 public function course_header() {
5027 return '';
5031 * Does nothing. The maintenance renderer cannot produce a course footer.
5033 * @return string
5035 public function course_footer() {
5036 return '';
5040 * Does nothing. The maintenance renderer cannot produce a custom menu.
5042 * @param string $custommenuitems
5043 * @return string
5045 public function custom_menu($custommenuitems = '') {
5046 return '';
5050 * Does nothing. The maintenance renderer cannot produce a file picker.
5052 * @param array $options
5053 * @return string
5055 public function file_picker($options) {
5056 return '';
5060 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
5062 * @param array $dir
5063 * @return string
5065 public function htmllize_file_tree($dir) {
5066 return '';
5071 * Overridden confirm message for upgrades.
5073 * @param string $message The question to ask the user
5074 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5075 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5076 * @return string HTML fragment
5078 public function confirm($message, $continue, $cancel) {
5079 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5080 // from any previous version of Moodle).
5081 if ($continue instanceof single_button) {
5082 $continue->primary = true;
5083 } else if (is_string($continue)) {
5084 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
5085 } else if ($continue instanceof moodle_url) {
5086 $continue = new single_button($continue, get_string('continue'), 'post', true);
5087 } else {
5088 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5089 ' (string/moodle_url) or a single_button instance.');
5092 if ($cancel instanceof single_button) {
5093 $output = '';
5094 } else if (is_string($cancel)) {
5095 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5096 } else if ($cancel instanceof moodle_url) {
5097 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5098 } else {
5099 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5100 ' (string/moodle_url) or a single_button instance.');
5103 $output = $this->box_start('generalbox', 'notice');
5104 $output .= html_writer::tag('h4', get_string('confirm'));
5105 $output .= html_writer::tag('p', $message);
5106 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
5107 $output .= $this->box_end();
5108 return $output;
5112 * Does nothing. The maintenance renderer does not support JS.
5114 * @param block_contents $bc
5116 public function init_block_hider_js(block_contents $bc) {
5117 // Does nothing.
5121 * Does nothing. The maintenance renderer cannot produce language menus.
5123 * @return string
5125 public function lang_menu() {
5126 return '';
5130 * Does nothing. The maintenance renderer has no need for login information.
5132 * @param null $withlinks
5133 * @return string
5135 public function login_info($withlinks = null) {
5136 return '';
5140 * Secure login info.
5142 * @return string
5144 public function secure_login_info() {
5145 return $this->login_info(false);
5149 * Does nothing. The maintenance renderer cannot produce user pictures.
5151 * @param stdClass $user
5152 * @param array $options
5153 * @return string
5155 public function user_picture(stdClass $user, array $options = null) {
5156 return '';