Merge branch 'MDL-61578-master' of git://github.com/mickhawkins/moodle
[moodle.git] / lib / outputrenderers.php
blob47d87283a0659efc3f462414225f189ba308ba1c
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
21 * for an overview.
23 * Included in this file are the primary renderer classes:
24 * - renderer_base: The renderer outline class that all renderers
25 * should inherit from.
26 * - core_renderer: The standard HTML renderer.
27 * - core_renderer_cli: An adaption of the standard renderer for CLI scripts.
28 * - core_renderer_ajax: An adaption of the standard renderer for AJAX scripts.
29 * - plugin_renderer_base: A renderer class that should be extended by all
30 * plugin renderers.
32 * @package core
33 * @category output
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') || die();
40 /**
41 * Simple base class for Moodle renderers.
43 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
45 * Also has methods to facilitate generating HTML output.
47 * @copyright 2009 Tim Hunt
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 * @since Moodle 2.0
50 * @package core
51 * @category output
53 class renderer_base {
54 /**
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
59 /**
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
62 protected $page;
64 /**
65 * @var string The requested rendering target.
67 protected $target;
69 /**
70 * @var Mustache_Engine $mustache The mustache template compiler
72 private $mustache;
74 /**
75 * Return an instance of the mustache class.
77 * @since 2.9
78 * @return Mustache_Engine
80 protected function get_mustache() {
81 global $CFG;
83 if ($this->mustache === null) {
84 require_once("{$CFG->libdir}/filelib.php");
86 $themename = $this->page->theme->name;
87 $themerev = theme_get_revision();
89 // Create new localcache directory.
90 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
92 // Remove old localcache directories.
93 $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR);
94 foreach ($mustachecachedirs as $localcachedir) {
95 $cachedrev = [];
96 preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
97 $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
98 if ($cachedrev > 0 && $cachedrev < $themerev) {
99 fulldelete($localcachedir);
103 $loader = new \core\output\mustache_filesystem_loader();
104 $stringhelper = new \core\output\mustache_string_helper();
105 $quotehelper = new \core\output\mustache_quote_helper();
106 $jshelper = new \core\output\mustache_javascript_helper($this->page);
107 $pixhelper = new \core\output\mustache_pix_helper($this);
108 $shortentexthelper = new \core\output\mustache_shorten_text_helper();
109 $userdatehelper = new \core\output\mustache_user_date_helper();
111 // We only expose the variables that are exposed to JS templates.
112 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
114 $helpers = array('config' => $safeconfig,
115 'str' => array($stringhelper, 'str'),
116 'quote' => array($quotehelper, 'quote'),
117 'js' => array($jshelper, 'help'),
118 'pix' => array($pixhelper, 'pix'),
119 'shortentext' => array($shortentexthelper, 'shorten'),
120 'userdate' => array($userdatehelper, 'transform'),
123 $this->mustache = new Mustache_Engine(array(
124 'cache' => $cachedir,
125 'escape' => 's',
126 'loader' => $loader,
127 'helpers' => $helpers,
128 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS]));
132 return $this->mustache;
137 * Constructor
139 * The constructor takes two arguments. The first is the page that the renderer
140 * has been created to assist with, and the second is the target.
141 * The target is an additional identifier that can be used to load different
142 * renderers for different options.
144 * @param moodle_page $page the page we are doing output for.
145 * @param string $target one of rendering target constants
147 public function __construct(moodle_page $page, $target) {
148 $this->opencontainers = $page->opencontainers;
149 $this->page = $page;
150 $this->target = $target;
154 * Renders a template by name with the given context.
156 * The provided data needs to be array/stdClass made up of only simple types.
157 * Simple types are array,stdClass,bool,int,float,string
159 * @since 2.9
160 * @param array|stdClass $context Context containing data for the template.
161 * @return string|boolean
163 public function render_from_template($templatename, $context) {
164 static $templatecache = array();
165 $mustache = $this->get_mustache();
167 try {
168 // Grab a copy of the existing helper to be restored later.
169 $uniqidhelper = $mustache->getHelper('uniqid');
170 } catch (Mustache_Exception_UnknownHelperException $e) {
171 // Helper doesn't exist.
172 $uniqidhelper = null;
175 // Provide 1 random value that will not change within a template
176 // but will be different from template to template. This is useful for
177 // e.g. aria attributes that only work with id attributes and must be
178 // unique in a page.
179 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
180 if (isset($templatecache[$templatename])) {
181 $template = $templatecache[$templatename];
182 } else {
183 try {
184 $template = $mustache->loadTemplate($templatename);
185 $templatecache[$templatename] = $template;
186 } catch (Mustache_Exception_UnknownTemplateException $e) {
187 throw new moodle_exception('Unknown template: ' . $templatename);
191 $renderedtemplate = trim($template->render($context));
193 // If we had an existing uniqid helper then we need to restore it to allow
194 // handle nested calls of render_from_template.
195 if ($uniqidhelper) {
196 $mustache->addHelper('uniqid', $uniqidhelper);
199 return $renderedtemplate;
204 * Returns rendered widget.
206 * The provided widget needs to be an object that extends the renderable
207 * interface.
208 * If will then be rendered by a method based upon the classname for the widget.
209 * For instance a widget of class `crazywidget` will be rendered by a protected
210 * render_crazywidget method of this renderer.
211 * If no render_crazywidget method exists and crazywidget implements templatable,
212 * look for the 'crazywidget' template in the same component and render that.
214 * @param renderable $widget instance with renderable interface
215 * @return string
217 public function render(renderable $widget) {
218 $classparts = explode('\\', get_class($widget));
219 // Strip namespaces.
220 $classname = array_pop($classparts);
221 // Remove _renderable suffixes
222 $classname = preg_replace('/_renderable$/', '', $classname);
224 $rendermethod = 'render_'.$classname;
225 if (method_exists($this, $rendermethod)) {
226 return $this->$rendermethod($widget);
228 if ($widget instanceof templatable) {
229 $component = array_shift($classparts);
230 if (!$component) {
231 $component = 'core';
233 $template = $component . '/' . $classname;
234 $context = $widget->export_for_template($this);
235 return $this->render_from_template($template, $context);
237 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
241 * Adds a JS action for the element with the provided id.
243 * This method adds a JS event for the provided component action to the page
244 * and then returns the id that the event has been attached to.
245 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
247 * @param component_action $action
248 * @param string $id
249 * @return string id of element, either original submitted or random new if not supplied
251 public function add_action_handler(component_action $action, $id = null) {
252 if (!$id) {
253 $id = html_writer::random_id($action->event);
255 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
256 return $id;
260 * Returns true is output has already started, and false if not.
262 * @return boolean true if the header has been printed.
264 public function has_started() {
265 return $this->page->state >= moodle_page::STATE_IN_BODY;
269 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
271 * @param mixed $classes Space-separated string or array of classes
272 * @return string HTML class attribute value
274 public static function prepare_classes($classes) {
275 if (is_array($classes)) {
276 return implode(' ', array_unique($classes));
278 return $classes;
282 * Return the direct URL for an image from the pix folder.
284 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
286 * @deprecated since Moodle 3.3
287 * @param string $imagename the name of the icon.
288 * @param string $component specification of one plugin like in get_string()
289 * @return moodle_url
291 public function pix_url($imagename, $component = 'moodle') {
292 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
293 return $this->page->theme->image_url($imagename, $component);
297 * Return the moodle_url for an image.
299 * The exact image location and extension is determined
300 * automatically by searching for gif|png|jpg|jpeg, please
301 * note there can not be diferent images with the different
302 * extension. The imagename is for historical reasons
303 * a relative path name, it may be changed later for core
304 * images. It is recommended to not use subdirectories
305 * in plugin and theme pix directories.
307 * There are three types of images:
308 * 1/ theme images - stored in theme/mytheme/pix/,
309 * use component 'theme'
310 * 2/ core images - stored in /pix/,
311 * overridden via theme/mytheme/pix_core/
312 * 3/ plugin images - stored in mod/mymodule/pix,
313 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
314 * example: image_url('comment', 'mod_glossary')
316 * @param string $imagename the pathname of the image
317 * @param string $component full plugin name (aka component) or 'theme'
318 * @return moodle_url
320 public function image_url($imagename, $component = 'moodle') {
321 return $this->page->theme->image_url($imagename, $component);
325 * Return the site's logo URL, if any.
327 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
328 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
329 * @return moodle_url|false
331 public function get_logo_url($maxwidth = null, $maxheight = 200) {
332 global $CFG;
333 $logo = get_config('core_admin', 'logo');
334 if (empty($logo)) {
335 return false;
338 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
339 // It's not worth the overhead of detecting and serving 2 different images based on the device.
341 // Hide the requested size in the file path.
342 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
344 // Use $CFG->themerev to prevent browser caching when the file changes.
345 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
346 theme_get_revision(), $logo);
350 * Return the site's compact logo URL, if any.
352 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
353 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
354 * @return moodle_url|false
356 public function get_compact_logo_url($maxwidth = 100, $maxheight = 100) {
357 global $CFG;
358 $logo = get_config('core_admin', 'logocompact');
359 if (empty($logo)) {
360 return false;
363 // Hide the requested size in the file path.
364 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
366 // Use $CFG->themerev to prevent browser caching when the file changes.
367 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
368 theme_get_revision(), $logo);
375 * Basis for all plugin renderers.
377 * @copyright Petr Skoda (skodak)
378 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
379 * @since Moodle 2.0
380 * @package core
381 * @category output
383 class plugin_renderer_base extends renderer_base {
386 * @var renderer_base|core_renderer A reference to the current renderer.
387 * The renderer provided here will be determined by the page but will in 90%
388 * of cases by the {@link core_renderer}
390 protected $output;
393 * Constructor method, calls the parent constructor
395 * @param moodle_page $page
396 * @param string $target one of rendering target constants
398 public function __construct(moodle_page $page, $target) {
399 if (empty($target) && $page->pagelayout === 'maintenance') {
400 // If the page is using the maintenance layout then we're going to force the target to maintenance.
401 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
402 // unavailable for this page layout.
403 $target = RENDERER_TARGET_MAINTENANCE;
405 $this->output = $page->get_renderer('core', null, $target);
406 parent::__construct($page, $target);
410 * Renders the provided widget and returns the HTML to display it.
412 * @param renderable $widget instance with renderable interface
413 * @return string
415 public function render(renderable $widget) {
416 $classname = get_class($widget);
417 // Strip namespaces.
418 $classname = preg_replace('/^.*\\\/', '', $classname);
419 // Keep a copy at this point, we may need to look for a deprecated method.
420 $deprecatedmethod = 'render_'.$classname;
421 // Remove _renderable suffixes
422 $classname = preg_replace('/_renderable$/', '', $classname);
424 $rendermethod = 'render_'.$classname;
425 if (method_exists($this, $rendermethod)) {
426 return $this->$rendermethod($widget);
428 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
429 // This is exactly where we don't want to be.
430 // If you have arrived here you have a renderable component within your plugin that has the name
431 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
432 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
433 // and the _renderable suffix now gets removed when looking for a render method.
434 // You need to change your renderers render_blah_renderable to render_blah.
435 // Until you do this it will not be possible for a theme to override the renderer to override your method.
436 // Please do it ASAP.
437 static $debugged = array();
438 if (!isset($debugged[$deprecatedmethod])) {
439 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
440 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
441 $debugged[$deprecatedmethod] = true;
443 return $this->$deprecatedmethod($widget);
445 // pass to core renderer if method not found here
446 return $this->output->render($widget);
450 * Magic method used to pass calls otherwise meant for the standard renderer
451 * to it to ensure we don't go causing unnecessary grief.
453 * @param string $method
454 * @param array $arguments
455 * @return mixed
457 public function __call($method, $arguments) {
458 if (method_exists('renderer_base', $method)) {
459 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
461 if (method_exists($this->output, $method)) {
462 return call_user_func_array(array($this->output, $method), $arguments);
463 } else {
464 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
471 * The standard implementation of the core_renderer interface.
473 * @copyright 2009 Tim Hunt
474 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
475 * @since Moodle 2.0
476 * @package core
477 * @category output
479 class core_renderer extends renderer_base {
481 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
482 * in layout files instead.
483 * @deprecated
484 * @var string used in {@link core_renderer::header()}.
486 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
489 * @var string Used to pass information from {@link core_renderer::doctype()} to
490 * {@link core_renderer::standard_head_html()}.
492 protected $contenttype;
495 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
496 * with {@link core_renderer::header()}.
498 protected $metarefreshtag = '';
501 * @var string Unique token for the closing HTML
503 protected $unique_end_html_token;
506 * @var string Unique token for performance information
508 protected $unique_performance_info_token;
511 * @var string Unique token for the main content.
513 protected $unique_main_content_token;
516 * Constructor
518 * @param moodle_page $page the page we are doing output for.
519 * @param string $target one of rendering target constants
521 public function __construct(moodle_page $page, $target) {
522 $this->opencontainers = $page->opencontainers;
523 $this->page = $page;
524 $this->target = $target;
526 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
527 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
528 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
532 * Get the DOCTYPE declaration that should be used with this page. Designed to
533 * be called in theme layout.php files.
535 * @return string the DOCTYPE declaration that should be used.
537 public function doctype() {
538 if ($this->page->theme->doctype === 'html5') {
539 $this->contenttype = 'text/html; charset=utf-8';
540 return "<!DOCTYPE html>\n";
542 } else if ($this->page->theme->doctype === 'xhtml5') {
543 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
544 return "<!DOCTYPE html>\n";
546 } else {
547 // legacy xhtml 1.0
548 $this->contenttype = 'text/html; charset=utf-8';
549 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
554 * The attributes that should be added to the <html> tag. Designed to
555 * be called in theme layout.php files.
557 * @return string HTML fragment.
559 public function htmlattributes() {
560 $return = get_html_lang(true);
561 $attributes = array();
562 if ($this->page->theme->doctype !== 'html5') {
563 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
566 // Give plugins an opportunity to add things like xml namespaces to the html element.
567 // This function should return an array of html attribute names => values.
568 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
569 foreach ($pluginswithfunction as $plugins) {
570 foreach ($plugins as $function) {
571 $newattrs = $function();
572 unset($newattrs['dir']);
573 unset($newattrs['lang']);
574 unset($newattrs['xmlns']);
575 unset($newattrs['xml:lang']);
576 $attributes += $newattrs;
580 foreach ($attributes as $key => $val) {
581 $val = s($val);
582 $return .= " $key=\"$val\"";
585 return $return;
589 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
590 * that should be included in the <head> tag. Designed to be called in theme
591 * layout.php files.
593 * @return string HTML fragment.
595 public function standard_head_html() {
596 global $CFG, $SESSION;
598 // Before we output any content, we need to ensure that certain
599 // page components are set up.
601 // Blocks must be set up early as they may require javascript which
602 // has to be included in the page header before output is created.
603 foreach ($this->page->blocks->get_regions() as $region) {
604 $this->page->blocks->ensure_content_created($region, $this);
607 $output = '';
609 // Give plugins an opportunity to add any head elements. The callback
610 // must always return a string containing valid html head content.
611 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
612 foreach ($pluginswithfunction as $plugins) {
613 foreach ($plugins as $function) {
614 $output .= $function();
618 // Allow a url_rewrite plugin to setup any dynamic head content.
619 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
620 $class = $CFG->urlrewriteclass;
621 $output .= $class::html_head_setup();
624 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
625 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
626 // This is only set by the {@link redirect()} method
627 $output .= $this->metarefreshtag;
629 // Check if a periodic refresh delay has been set and make sure we arn't
630 // already meta refreshing
631 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
632 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
635 // Set up help link popups for all links with the helptooltip class
636 $this->page->requires->js_init_call('M.util.help_popups.setup');
638 $focus = $this->page->focuscontrol;
639 if (!empty($focus)) {
640 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
641 // This is a horrifically bad way to handle focus but it is passed in
642 // through messy formslib::moodleform
643 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
644 } else if (strpos($focus, '.')!==false) {
645 // Old style of focus, bad way to do it
646 debugging('This code is using the old style focus event, Please update this code to focus on an element id or the moodleform focus method.', DEBUG_DEVELOPER);
647 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
648 } else {
649 // Focus element with given id
650 $this->page->requires->js_function_call('focuscontrol', array($focus));
654 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
655 // any other custom CSS can not be overridden via themes and is highly discouraged
656 $urls = $this->page->theme->css_urls($this->page);
657 foreach ($urls as $url) {
658 $this->page->requires->css_theme($url);
661 // Get the theme javascript head and footer
662 if ($jsurl = $this->page->theme->javascript_url(true)) {
663 $this->page->requires->js($jsurl, true);
665 if ($jsurl = $this->page->theme->javascript_url(false)) {
666 $this->page->requires->js($jsurl);
669 // Get any HTML from the page_requirements_manager.
670 $output .= $this->page->requires->get_head_code($this->page, $this);
672 // List alternate versions.
673 foreach ($this->page->alternateversions as $type => $alt) {
674 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
675 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
678 // Add noindex tag if relevant page and setting applied.
679 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
680 $loginpages = array('login-index', 'login-signup');
681 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
682 if (!isset($CFG->additionalhtmlhead)) {
683 $CFG->additionalhtmlhead = '';
685 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
688 if (!empty($CFG->additionalhtmlhead)) {
689 $output .= "\n".$CFG->additionalhtmlhead;
692 return $output;
696 * The standard tags (typically skip links) that should be output just inside
697 * the start of the <body> tag. Designed to be called in theme layout.php files.
699 * @return string HTML fragment.
701 public function standard_top_of_body_html() {
702 global $CFG;
703 $output = $this->page->requires->get_top_of_body_code($this);
704 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
705 $output .= "\n".$CFG->additionalhtmltopofbody;
708 // Give plugins an opportunity to inject extra html content. The callback
709 // must always return a string containing valid html.
710 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
711 foreach ($pluginswithfunction as $plugins) {
712 foreach ($plugins as $function) {
713 $output .= $function();
717 $output .= $this->maintenance_warning();
719 return $output;
723 * Scheduled maintenance warning message.
725 * Note: This is a nasty hack to display maintenance notice, this should be moved
726 * to some general notification area once we have it.
728 * @return string
730 public function maintenance_warning() {
731 global $CFG;
733 $output = '';
734 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
735 $timeleft = $CFG->maintenance_later - time();
736 // If timeleft less than 30 sec, set the class on block to error to highlight.
737 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
738 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-a-1 alert');
739 $a = new stdClass();
740 $a->hour = (int)($timeleft / 3600);
741 $a->min = (int)(($timeleft / 60) % 60);
742 $a->sec = (int)($timeleft % 60);
743 if ($a->hour > 0) {
744 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
745 } else {
746 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
749 $output .= $this->box_end();
750 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
751 array(array('timeleftinsec' => $timeleft)));
752 $this->page->requires->strings_for_js(
753 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
754 'admin');
756 return $output;
760 * The standard tags (typically performance information and validation links,
761 * if we are in developer debug mode) that should be output in the footer area
762 * of the page. Designed to be called in theme layout.php files.
764 * @return string HTML fragment.
766 public function standard_footer_html() {
767 global $CFG, $SCRIPT;
769 $output = '';
770 if (during_initial_install()) {
771 // Debugging info can not work before install is finished,
772 // in any case we do not want any links during installation!
773 return $output;
776 // Give plugins an opportunity to add any footer elements.
777 // The callback must always return a string containing valid html footer content.
778 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
779 foreach ($pluginswithfunction as $plugins) {
780 foreach ($plugins as $function) {
781 $output .= $function();
785 // This function is normally called from a layout.php file in {@link core_renderer::header()}
786 // but some of the content won't be known until later, so we return a placeholder
787 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
788 $output .= $this->unique_performance_info_token;
789 if ($this->page->devicetypeinuse == 'legacy') {
790 // The legacy theme is in use print the notification
791 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
794 // Get links to switch device types (only shown for users not on a default device)
795 $output .= $this->theme_switch_links();
797 if (!empty($CFG->debugpageinfo)) {
798 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
799 $this->page->debug_summary()) . '</div>';
801 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
802 // Add link to profiling report if necessary
803 if (function_exists('profiling_is_running') && profiling_is_running()) {
804 $txt = get_string('profiledscript', 'admin');
805 $title = get_string('profiledscriptview', 'admin');
806 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
807 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
808 $output .= '<div class="profilingfooter">' . $link . '</div>';
810 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
811 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
812 $output .= '<div class="purgecaches">' .
813 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
815 if (!empty($CFG->debugvalidators)) {
816 // 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
817 $output .= '<div class="validators"><ul class="list-unstyled m-l-1">
818 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
819 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
820 <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>
821 </ul></div>';
823 return $output;
827 * Returns standard main content placeholder.
828 * Designed to be called in theme layout.php files.
830 * @return string HTML fragment.
832 public function main_content() {
833 // This is here because it is the only place we can inject the "main" role over the entire main content area
834 // without requiring all theme's to manually do it, and without creating yet another thing people need to
835 // remember in the theme.
836 // This is an unfortunate hack. DO NO EVER add anything more here.
837 // DO NOT add classes.
838 // DO NOT add an id.
839 return '<div role="main">'.$this->unique_main_content_token.'</div>';
843 * Returns standard navigation between activities in a course.
845 * @return string the navigation HTML.
847 public function activity_navigation() {
848 // First we should check if we want to add navigation.
849 $context = $this->page->context;
850 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
851 || $context->contextlevel != CONTEXT_MODULE) {
852 return '';
855 // If the activity is in stealth mode, show no links.
856 if ($this->page->cm->is_stealth()) {
857 return '';
860 // Get a list of all the activities in the course.
861 $course = $this->page->cm->get_course();
862 $modules = get_fast_modinfo($course->id)->get_cms();
864 // Put the modules into an array in order by the position they are shown in the course.
865 $mods = [];
866 $activitylist = [];
867 foreach ($modules as $module) {
868 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
869 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
870 continue;
872 $mods[$module->id] = $module;
874 // No need to add the current module to the list for the activity dropdown menu.
875 if ($module->id == $this->page->cm->id) {
876 continue;
878 // Module name.
879 $modname = $module->get_formatted_name();
880 // Display the hidden text if necessary.
881 if (!$module->visible) {
882 $modname .= ' ' . get_string('hiddenwithbrackets');
884 // Module URL.
885 $linkurl = new moodle_url($module->url, array('forceview' => 1));
886 // Add module URL (as key) and name (as value) to the activity list array.
887 $activitylist[$linkurl->out(false)] = $modname;
890 $nummods = count($mods);
892 // If there is only one mod then do nothing.
893 if ($nummods == 1) {
894 return '';
897 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
898 $modids = array_keys($mods);
900 // Get the position in the array of the course module we are viewing.
901 $position = array_search($this->page->cm->id, $modids);
903 $prevmod = null;
904 $nextmod = null;
906 // Check if we have a previous mod to show.
907 if ($position > 0) {
908 $prevmod = $mods[$modids[$position - 1]];
911 // Check if we have a next mod to show.
912 if ($position < ($nummods - 1)) {
913 $nextmod = $mods[$modids[$position + 1]];
916 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
917 $renderer = $this->page->get_renderer('core', 'course');
918 return $renderer->render($activitynav);
922 * The standard tags (typically script tags that are not needed earlier) that
923 * should be output after everything else. Designed to be called in theme layout.php files.
925 * @return string HTML fragment.
927 public function standard_end_of_body_html() {
928 global $CFG;
930 // This function is normally called from a layout.php file in {@link core_renderer::header()}
931 // but some of the content won't be known until later, so we return a placeholder
932 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
933 $output = '';
934 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
935 $output .= "\n".$CFG->additionalhtmlfooter;
937 $output .= $this->unique_end_html_token;
938 return $output;
942 * Return the standard string that says whether you are logged in (and switched
943 * roles/logged in as another user).
944 * @param bool $withlinks if false, then don't include any links in the HTML produced.
945 * If not set, the default is the nologinlinks option from the theme config.php file,
946 * and if that is not set, then links are included.
947 * @return string HTML fragment.
949 public function login_info($withlinks = null) {
950 global $USER, $CFG, $DB, $SESSION;
952 if (during_initial_install()) {
953 return '';
956 if (is_null($withlinks)) {
957 $withlinks = empty($this->page->layout_options['nologinlinks']);
960 $course = $this->page->course;
961 if (\core\session\manager::is_loggedinas()) {
962 $realuser = \core\session\manager::get_realuser();
963 $fullname = fullname($realuser, true);
964 if ($withlinks) {
965 $loginastitle = get_string('loginas');
966 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
967 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
968 } else {
969 $realuserinfo = " [$fullname] ";
971 } else {
972 $realuserinfo = '';
975 $loginpage = $this->is_login_page();
976 $loginurl = get_login_url();
978 if (empty($course->id)) {
979 // $course->id is not defined during installation
980 return '';
981 } else if (isloggedin()) {
982 $context = context_course::instance($course->id);
984 $fullname = fullname($USER, true);
985 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
986 if ($withlinks) {
987 $linktitle = get_string('viewprofile');
988 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
989 } else {
990 $username = $fullname;
992 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
993 if ($withlinks) {
994 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
995 } else {
996 $username .= " from {$idprovider->name}";
999 if (isguestuser()) {
1000 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1001 if (!$loginpage && $withlinks) {
1002 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1004 } else if (is_role_switched($course->id)) { // Has switched roles
1005 $rolename = '';
1006 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1007 $rolename = ': '.role_get_name($role, $context);
1009 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1010 if ($withlinks) {
1011 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1012 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1014 } else {
1015 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1016 if ($withlinks) {
1017 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1020 } else {
1021 $loggedinas = get_string('loggedinnot', 'moodle');
1022 if (!$loginpage && $withlinks) {
1023 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1027 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1029 if (isset($SESSION->justloggedin)) {
1030 unset($SESSION->justloggedin);
1031 if (!empty($CFG->displayloginfailures)) {
1032 if (!isguestuser()) {
1033 // Include this file only when required.
1034 require_once($CFG->dirroot . '/user/lib.php');
1035 if ($count = user_count_login_failures($USER)) {
1036 $loggedinas .= '<div class="loginfailures">';
1037 $a = new stdClass();
1038 $a->attempts = $count;
1039 $loggedinas .= get_string('failedloginattempts', '', $a);
1040 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1041 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1042 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1044 $loggedinas .= '</div>';
1050 return $loggedinas;
1054 * Check whether the current page is a login page.
1056 * @since Moodle 2.9
1057 * @return bool
1059 protected function is_login_page() {
1060 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1061 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1062 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1063 return in_array(
1064 $this->page->url->out_as_local_url(false, array()),
1065 array(
1066 '/login/index.php',
1067 '/login/forgot_password.php',
1073 * Return the 'back' link that normally appears in the footer.
1075 * @return string HTML fragment.
1077 public function home_link() {
1078 global $CFG, $SITE;
1080 if ($this->page->pagetype == 'site-index') {
1081 // Special case for site home page - please do not remove
1082 return '<div class="sitelink">' .
1083 '<a title="Moodle" href="http://moodle.org/">' .
1084 '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1086 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1087 // Special case for during install/upgrade.
1088 return '<div class="sitelink">'.
1089 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1090 '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1092 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1093 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1094 get_string('home') . '</a></div>';
1096 } else {
1097 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1098 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1103 * Redirects the user by any means possible given the current state
1105 * This function should not be called directly, it should always be called using
1106 * the redirect function in lib/weblib.php
1108 * The redirect function should really only be called before page output has started
1109 * however it will allow itself to be called during the state STATE_IN_BODY
1111 * @param string $encodedurl The URL to send to encoded if required
1112 * @param string $message The message to display to the user if any
1113 * @param int $delay The delay before redirecting a user, if $message has been
1114 * set this is a requirement and defaults to 3, set to 0 no delay
1115 * @param boolean $debugdisableredirect this redirect has been disabled for
1116 * debugging purposes. Display a message that explains, and don't
1117 * trigger the redirect.
1118 * @param string $messagetype The type of notification to show the message in.
1119 * See constants on \core\output\notification.
1120 * @return string The HTML to display to the user before dying, may contain
1121 * meta refresh, javascript refresh, and may have set header redirects
1123 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1124 $messagetype = \core\output\notification::NOTIFY_INFO) {
1125 global $CFG;
1126 $url = str_replace('&amp;', '&', $encodedurl);
1128 switch ($this->page->state) {
1129 case moodle_page::STATE_BEFORE_HEADER :
1130 // No output yet it is safe to delivery the full arsenal of redirect methods
1131 if (!$debugdisableredirect) {
1132 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1133 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1134 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1136 $output = $this->header();
1137 break;
1138 case moodle_page::STATE_PRINTING_HEADER :
1139 // We should hopefully never get here
1140 throw new coding_exception('You cannot redirect while printing the page header');
1141 break;
1142 case moodle_page::STATE_IN_BODY :
1143 // We really shouldn't be here but we can deal with this
1144 debugging("You should really redirect before you start page output");
1145 if (!$debugdisableredirect) {
1146 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1148 $output = $this->opencontainers->pop_all_but_last();
1149 break;
1150 case moodle_page::STATE_DONE :
1151 // Too late to be calling redirect now
1152 throw new coding_exception('You cannot redirect after the entire page has been generated');
1153 break;
1155 $output .= $this->notification($message, $messagetype);
1156 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1157 if ($debugdisableredirect) {
1158 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1160 $output .= $this->footer();
1161 return $output;
1165 * Start output by sending the HTTP headers, and printing the HTML <head>
1166 * and the start of the <body>.
1168 * To control what is printed, you should set properties on $PAGE. If you
1169 * are familiar with the old {@link print_header()} function from Moodle 1.9
1170 * you will find that there are properties on $PAGE that correspond to most
1171 * of the old parameters to could be passed to print_header.
1173 * Not that, in due course, the remaining $navigation, $menu parameters here
1174 * will be replaced by more properties of $PAGE, but that is still to do.
1176 * @return string HTML that you must output this, preferably immediately.
1178 public function header() {
1179 global $USER, $CFG, $SESSION;
1181 // Give plugins an opportunity touch things before the http headers are sent
1182 // such as adding additional headers. The return value is ignored.
1183 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1184 foreach ($pluginswithfunction as $plugins) {
1185 foreach ($plugins as $function) {
1186 $function();
1190 if (\core\session\manager::is_loggedinas()) {
1191 $this->page->add_body_class('userloggedinas');
1194 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1195 require_once($CFG->dirroot . '/user/lib.php');
1196 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1197 if ($count = user_count_login_failures($USER, false)) {
1198 $this->page->add_body_class('loginfailures');
1202 // If the user is logged in, and we're not in initial install,
1203 // check to see if the user is role-switched and add the appropriate
1204 // CSS class to the body element.
1205 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1206 $this->page->add_body_class('userswitchedrole');
1209 // Give themes a chance to init/alter the page object.
1210 $this->page->theme->init_page($this->page);
1212 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1214 // Find the appropriate page layout file, based on $this->page->pagelayout.
1215 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1216 // Render the layout using the layout file.
1217 $rendered = $this->render_page_layout($layoutfile);
1219 // Slice the rendered output into header and footer.
1220 $cutpos = strpos($rendered, $this->unique_main_content_token);
1221 if ($cutpos === false) {
1222 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1223 $token = self::MAIN_CONTENT_TOKEN;
1224 } else {
1225 $token = $this->unique_main_content_token;
1228 if ($cutpos === false) {
1229 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.');
1231 $header = substr($rendered, 0, $cutpos);
1232 $footer = substr($rendered, $cutpos + strlen($token));
1234 if (empty($this->contenttype)) {
1235 debugging('The page layout file did not call $OUTPUT->doctype()');
1236 $header = $this->doctype() . $header;
1239 // If this theme version is below 2.4 release and this is a course view page
1240 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1241 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1242 // check if course content header/footer have not been output during render of theme layout
1243 $coursecontentheader = $this->course_content_header(true);
1244 $coursecontentfooter = $this->course_content_footer(true);
1245 if (!empty($coursecontentheader)) {
1246 // display debug message and add header and footer right above and below main content
1247 // Please note that course header and footer (to be displayed above and below the whole page)
1248 // are not displayed in this case at all.
1249 // Besides the content header and footer are not displayed on any other course page
1250 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);
1251 $header .= $coursecontentheader;
1252 $footer = $coursecontentfooter. $footer;
1256 send_headers($this->contenttype, $this->page->cacheable);
1258 $this->opencontainers->push('header/footer', $footer);
1259 $this->page->set_state(moodle_page::STATE_IN_BODY);
1261 return $header . $this->skip_link_target('maincontent');
1265 * Renders and outputs the page layout file.
1267 * This is done by preparing the normal globals available to a script, and
1268 * then including the layout file provided by the current theme for the
1269 * requested layout.
1271 * @param string $layoutfile The name of the layout file
1272 * @return string HTML code
1274 protected function render_page_layout($layoutfile) {
1275 global $CFG, $SITE, $USER;
1276 // The next lines are a bit tricky. The point is, here we are in a method
1277 // of a renderer class, and this object may, or may not, be the same as
1278 // the global $OUTPUT object. When rendering the page layout file, we want to use
1279 // this object. However, people writing Moodle code expect the current
1280 // renderer to be called $OUTPUT, not $this, so define a variable called
1281 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1282 $OUTPUT = $this;
1283 $PAGE = $this->page;
1284 $COURSE = $this->page->course;
1286 ob_start();
1287 include($layoutfile);
1288 $rendered = ob_get_contents();
1289 ob_end_clean();
1290 return $rendered;
1294 * Outputs the page's footer
1296 * @return string HTML fragment
1298 public function footer() {
1299 global $CFG, $DB, $PAGE;
1301 // Give plugins an opportunity to touch the page before JS is finalized.
1302 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1303 foreach ($pluginswithfunction as $plugins) {
1304 foreach ($plugins as $function) {
1305 $function();
1309 $output = $this->container_end_all(true);
1311 $footer = $this->opencontainers->pop('header/footer');
1313 if (debugging() and $DB and $DB->is_transaction_started()) {
1314 // TODO: MDL-20625 print warning - transaction will be rolled back
1317 // Provide some performance info if required
1318 $performanceinfo = '';
1319 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1320 $perf = get_performance_info();
1321 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1322 $performanceinfo = $perf['html'];
1326 // We always want performance data when running a performance test, even if the user is redirected to another page.
1327 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1328 $footer = $this->unique_performance_info_token . $footer;
1330 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1332 // Only show notifications when we have a $PAGE context id.
1333 if (!empty($PAGE->context->id)) {
1334 $this->page->requires->js_call_amd('core/notification', 'init', array(
1335 $PAGE->context->id,
1336 \core\notification::fetch_as_array($this)
1339 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1341 $this->page->set_state(moodle_page::STATE_DONE);
1343 return $output . $footer;
1347 * Close all but the last open container. This is useful in places like error
1348 * handling, where you want to close all the open containers (apart from <body>)
1349 * before outputting the error message.
1351 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1352 * developer debug warning if it isn't.
1353 * @return string the HTML required to close any open containers inside <body>.
1355 public function container_end_all($shouldbenone = false) {
1356 return $this->opencontainers->pop_all_but_last($shouldbenone);
1360 * Returns course-specific information to be output immediately above content on any course page
1361 * (for the current course)
1363 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1364 * @return string
1366 public function course_content_header($onlyifnotcalledbefore = false) {
1367 global $CFG;
1368 static $functioncalled = false;
1369 if ($functioncalled && $onlyifnotcalledbefore) {
1370 // we have already output the content header
1371 return '';
1374 // Output any session notification.
1375 $notifications = \core\notification::fetch();
1377 $bodynotifications = '';
1378 foreach ($notifications as $notification) {
1379 $bodynotifications .= $this->render_from_template(
1380 $notification->get_template_name(),
1381 $notification->export_for_template($this)
1385 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1387 if ($this->page->course->id == SITEID) {
1388 // return immediately and do not include /course/lib.php if not necessary
1389 return $output;
1392 require_once($CFG->dirroot.'/course/lib.php');
1393 $functioncalled = true;
1394 $courseformat = course_get_format($this->page->course);
1395 if (($obj = $courseformat->course_content_header()) !== null) {
1396 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1398 return $output;
1402 * Returns course-specific information to be output immediately below content on any course page
1403 * (for the current course)
1405 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1406 * @return string
1408 public function course_content_footer($onlyifnotcalledbefore = false) {
1409 global $CFG;
1410 if ($this->page->course->id == SITEID) {
1411 // return immediately and do not include /course/lib.php if not necessary
1412 return '';
1414 static $functioncalled = false;
1415 if ($functioncalled && $onlyifnotcalledbefore) {
1416 // we have already output the content footer
1417 return '';
1419 $functioncalled = true;
1420 require_once($CFG->dirroot.'/course/lib.php');
1421 $courseformat = course_get_format($this->page->course);
1422 if (($obj = $courseformat->course_content_footer()) !== null) {
1423 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1425 return '';
1429 * Returns course-specific information to be output on any course page in the header area
1430 * (for the current course)
1432 * @return string
1434 public function course_header() {
1435 global $CFG;
1436 if ($this->page->course->id == SITEID) {
1437 // return immediately and do not include /course/lib.php if not necessary
1438 return '';
1440 require_once($CFG->dirroot.'/course/lib.php');
1441 $courseformat = course_get_format($this->page->course);
1442 if (($obj = $courseformat->course_header()) !== null) {
1443 return $courseformat->get_renderer($this->page)->render($obj);
1445 return '';
1449 * Returns course-specific information to be output on any course page in the footer area
1450 * (for the current course)
1452 * @return string
1454 public function course_footer() {
1455 global $CFG;
1456 if ($this->page->course->id == SITEID) {
1457 // return immediately and do not include /course/lib.php if not necessary
1458 return '';
1460 require_once($CFG->dirroot.'/course/lib.php');
1461 $courseformat = course_get_format($this->page->course);
1462 if (($obj = $courseformat->course_footer()) !== null) {
1463 return $courseformat->get_renderer($this->page)->render($obj);
1465 return '';
1469 * Returns lang menu or '', this method also checks forcing of languages in courses.
1471 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1473 * @return string The lang menu HTML or empty string
1475 public function lang_menu() {
1476 global $CFG;
1478 if (empty($CFG->langmenu)) {
1479 return '';
1482 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1483 // do not show lang menu if language forced
1484 return '';
1487 $currlang = current_language();
1488 $langs = get_string_manager()->get_list_of_translations();
1490 if (count($langs) < 2) {
1491 return '';
1494 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1495 $s->label = get_accesshide(get_string('language'));
1496 $s->class = 'langmenu';
1497 return $this->render($s);
1501 * Output the row of editing icons for a block, as defined by the controls array.
1503 * @param array $controls an array like {@link block_contents::$controls}.
1504 * @param string $blockid The ID given to the block.
1505 * @return string HTML fragment.
1507 public function block_controls($actions, $blockid = null) {
1508 global $CFG;
1509 if (empty($actions)) {
1510 return '';
1512 $menu = new action_menu($actions);
1513 if ($blockid !== null) {
1514 $menu->set_owner_selector('#'.$blockid);
1516 $menu->set_constraint('.block-region');
1517 $menu->attributes['class'] .= ' block-control-actions commands';
1518 return $this->render($menu);
1522 * Renders an action menu component.
1524 * ARIA references:
1525 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1526 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1528 * @param action_menu $menu
1529 * @return string HTML
1531 public function render_action_menu(action_menu $menu) {
1532 $context = $menu->export_for_template($this);
1533 return $this->render_from_template('core/action_menu', $context);
1537 * Renders an action_menu_link item.
1539 * @param action_menu_link $action
1540 * @return string HTML fragment
1542 protected function render_action_menu_link(action_menu_link $action) {
1543 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1547 * Renders a primary action_menu_filler item.
1549 * @param action_menu_link_filler $action
1550 * @return string HTML fragment
1552 protected function render_action_menu_filler(action_menu_filler $action) {
1553 return html_writer::span('&nbsp;', 'filler');
1557 * Renders a primary action_menu_link item.
1559 * @param action_menu_link_primary $action
1560 * @return string HTML fragment
1562 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1563 return $this->render_action_menu_link($action);
1567 * Renders a secondary action_menu_link item.
1569 * @param action_menu_link_secondary $action
1570 * @return string HTML fragment
1572 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1573 return $this->render_action_menu_link($action);
1577 * Prints a nice side block with an optional header.
1579 * The content is described
1580 * by a {@link core_renderer::block_contents} object.
1582 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1583 * <div class="header"></div>
1584 * <div class="content">
1585 * ...CONTENT...
1586 * <div class="footer">
1587 * </div>
1588 * </div>
1589 * <div class="annotation">
1590 * </div>
1591 * </div>
1593 * @param block_contents $bc HTML for the content
1594 * @param string $region the region the block is appearing in.
1595 * @return string the HTML to be output.
1597 public function block(block_contents $bc, $region) {
1598 $bc = clone($bc); // Avoid messing up the object passed in.
1599 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1600 $bc->collapsible = block_contents::NOT_HIDEABLE;
1602 if (!empty($bc->blockinstanceid)) {
1603 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1605 $skiptitle = strip_tags($bc->title);
1606 if ($bc->blockinstanceid && !empty($skiptitle)) {
1607 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1608 } else if (!empty($bc->arialabel)) {
1609 $bc->attributes['aria-label'] = $bc->arialabel;
1611 if ($bc->dockable) {
1612 $bc->attributes['data-dockable'] = 1;
1614 if ($bc->collapsible == block_contents::HIDDEN) {
1615 $bc->add_class('hidden');
1617 if (!empty($bc->controls)) {
1618 $bc->add_class('block_with_controls');
1622 if (empty($skiptitle)) {
1623 $output = '';
1624 $skipdest = '';
1625 } else {
1626 $output = html_writer::link('#sb-'.$bc->skipid, get_string('skipa', 'access', $skiptitle),
1627 array('class' => 'skip skip-block', 'id' => 'fsb-' . $bc->skipid));
1628 $skipdest = html_writer::span('', 'skip-block-to',
1629 array('id' => 'sb-' . $bc->skipid));
1632 $output .= html_writer::start_tag('div', $bc->attributes);
1634 $output .= $this->block_header($bc);
1635 $output .= $this->block_content($bc);
1637 $output .= html_writer::end_tag('div');
1639 $output .= $this->block_annotation($bc);
1641 $output .= $skipdest;
1643 $this->init_block_hider_js($bc);
1644 return $output;
1648 * Produces a header for a block
1650 * @param block_contents $bc
1651 * @return string
1653 protected function block_header(block_contents $bc) {
1655 $title = '';
1656 if ($bc->title) {
1657 $attributes = array();
1658 if ($bc->blockinstanceid) {
1659 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1661 $title = html_writer::tag('h2', $bc->title, $attributes);
1664 $blockid = null;
1665 if (isset($bc->attributes['id'])) {
1666 $blockid = $bc->attributes['id'];
1668 $controlshtml = $this->block_controls($bc->controls, $blockid);
1670 $output = '';
1671 if ($title || $controlshtml) {
1672 $output .= html_writer::tag('div', html_writer::tag('div', html_writer::tag('div', '', array('class'=>'block_action')). $title . $controlshtml, array('class' => 'title')), array('class' => 'header'));
1674 return $output;
1678 * Produces the content area for a block
1680 * @param block_contents $bc
1681 * @return string
1683 protected function block_content(block_contents $bc) {
1684 $output = html_writer::start_tag('div', array('class' => 'content'));
1685 if (!$bc->title && !$this->block_controls($bc->controls)) {
1686 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1688 $output .= $bc->content;
1689 $output .= $this->block_footer($bc);
1690 $output .= html_writer::end_tag('div');
1692 return $output;
1696 * Produces the footer for a block
1698 * @param block_contents $bc
1699 * @return string
1701 protected function block_footer(block_contents $bc) {
1702 $output = '';
1703 if ($bc->footer) {
1704 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1706 return $output;
1710 * Produces the annotation for a block
1712 * @param block_contents $bc
1713 * @return string
1715 protected function block_annotation(block_contents $bc) {
1716 $output = '';
1717 if ($bc->annotation) {
1718 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1720 return $output;
1724 * Calls the JS require function to hide a block.
1726 * @param block_contents $bc A block_contents object
1728 protected function init_block_hider_js(block_contents $bc) {
1729 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1730 $config = new stdClass;
1731 $config->id = $bc->attributes['id'];
1732 $config->title = strip_tags($bc->title);
1733 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1734 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1735 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1737 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1738 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1743 * Render the contents of a block_list.
1745 * @param array $icons the icon for each item.
1746 * @param array $items the content of each item.
1747 * @return string HTML
1749 public function list_block_contents($icons, $items) {
1750 $row = 0;
1751 $lis = array();
1752 foreach ($items as $key => $string) {
1753 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1754 if (!empty($icons[$key])) { //test if the content has an assigned icon
1755 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1757 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1758 $item .= html_writer::end_tag('li');
1759 $lis[] = $item;
1760 $row = 1 - $row; // Flip even/odd.
1762 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1766 * Output all the blocks in a particular region.
1768 * @param string $region the name of a region on this page.
1769 * @return string the HTML to be output.
1771 public function blocks_for_region($region) {
1772 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1773 $blocks = $this->page->blocks->get_blocks_for_region($region);
1774 $lastblock = null;
1775 $zones = array();
1776 foreach ($blocks as $block) {
1777 $zones[] = $block->title;
1779 $output = '';
1781 foreach ($blockcontents as $bc) {
1782 if ($bc instanceof block_contents) {
1783 $output .= $this->block($bc, $region);
1784 $lastblock = $bc->title;
1785 } else if ($bc instanceof block_move_target) {
1786 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1787 } else {
1788 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1791 return $output;
1795 * Output a place where the block that is currently being moved can be dropped.
1797 * @param block_move_target $target with the necessary details.
1798 * @param array $zones array of areas where the block can be moved to
1799 * @param string $previous the block located before the area currently being rendered.
1800 * @param string $region the name of the region
1801 * @return string the HTML to be output.
1803 public function block_move_target($target, $zones, $previous, $region) {
1804 if ($previous == null) {
1805 if (empty($zones)) {
1806 // There are no zones, probably because there are no blocks.
1807 $regions = $this->page->theme->get_all_block_regions();
1808 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1809 } else {
1810 $position = get_string('moveblockbefore', 'block', $zones[0]);
1812 } else {
1813 $position = get_string('moveblockafter', 'block', $previous);
1815 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1819 * Renders a special html link with attached action
1821 * Theme developers: DO NOT OVERRIDE! Please override function
1822 * {@link core_renderer::render_action_link()} instead.
1824 * @param string|moodle_url $url
1825 * @param string $text HTML fragment
1826 * @param component_action $action
1827 * @param array $attributes associative array of html link attributes + disabled
1828 * @param pix_icon optional pix icon to render with the link
1829 * @return string HTML fragment
1831 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1832 if (!($url instanceof moodle_url)) {
1833 $url = new moodle_url($url);
1835 $link = new action_link($url, $text, $action, $attributes, $icon);
1837 return $this->render($link);
1841 * Renders an action_link object.
1843 * The provided link is renderer and the HTML returned. At the same time the
1844 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1846 * @param action_link $link
1847 * @return string HTML fragment
1849 protected function render_action_link(action_link $link) {
1850 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1854 * Renders an action_icon.
1856 * This function uses the {@link core_renderer::action_link()} method for the
1857 * most part. What it does different is prepare the icon as HTML and use it
1858 * as the link text.
1860 * Theme developers: If you want to change how action links and/or icons are rendered,
1861 * consider overriding function {@link core_renderer::render_action_link()} and
1862 * {@link core_renderer::render_pix_icon()}.
1864 * @param string|moodle_url $url A string URL or moodel_url
1865 * @param pix_icon $pixicon
1866 * @param component_action $action
1867 * @param array $attributes associative array of html link attributes + disabled
1868 * @param bool $linktext show title next to image in link
1869 * @return string HTML fragment
1871 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1872 if (!($url instanceof moodle_url)) {
1873 $url = new moodle_url($url);
1875 $attributes = (array)$attributes;
1877 if (empty($attributes['class'])) {
1878 // let ppl override the class via $options
1879 $attributes['class'] = 'action-icon';
1882 $icon = $this->render($pixicon);
1884 if ($linktext) {
1885 $text = $pixicon->attributes['alt'];
1886 } else {
1887 $text = '';
1890 return $this->action_link($url, $text.$icon, $action, $attributes);
1894 * Print a message along with button choices for Continue/Cancel
1896 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1898 * @param string $message The question to ask the user
1899 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1900 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1901 * @return string HTML fragment
1903 public function confirm($message, $continue, $cancel) {
1904 if ($continue instanceof single_button) {
1905 // ok
1906 $continue->primary = true;
1907 } else if (is_string($continue)) {
1908 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1909 } else if ($continue instanceof moodle_url) {
1910 $continue = new single_button($continue, get_string('continue'), 'post', true);
1911 } else {
1912 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1915 if ($cancel instanceof single_button) {
1916 // ok
1917 } else if (is_string($cancel)) {
1918 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1919 } else if ($cancel instanceof moodle_url) {
1920 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1921 } else {
1922 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1925 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice');
1926 $output .= $this->box_start('modal-content', 'modal-content');
1927 $output .= $this->box_start('modal-header p-x-1', 'modal-header');
1928 $output .= html_writer::tag('h4', get_string('confirm'));
1929 $output .= $this->box_end();
1930 $output .= $this->box_start('modal-body', 'modal-body');
1931 $output .= html_writer::tag('p', $message);
1932 $output .= $this->box_end();
1933 $output .= $this->box_start('modal-footer', 'modal-footer');
1934 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1935 $output .= $this->box_end();
1936 $output .= $this->box_end();
1937 $output .= $this->box_end();
1938 return $output;
1942 * Returns a form with a single button.
1944 * Theme developers: DO NOT OVERRIDE! Please override function
1945 * {@link core_renderer::render_single_button()} instead.
1947 * @param string|moodle_url $url
1948 * @param string $label button text
1949 * @param string $method get or post submit method
1950 * @param array $options associative array {disabled, title, etc.}
1951 * @return string HTML fragment
1953 public function single_button($url, $label, $method='post', array $options=null) {
1954 if (!($url instanceof moodle_url)) {
1955 $url = new moodle_url($url);
1957 $button = new single_button($url, $label, $method);
1959 foreach ((array)$options as $key=>$value) {
1960 if (array_key_exists($key, $button)) {
1961 $button->$key = $value;
1965 return $this->render($button);
1969 * Renders a single button widget.
1971 * This will return HTML to display a form containing a single button.
1973 * @param single_button $button
1974 * @return string HTML fragment
1976 protected function render_single_button(single_button $button) {
1977 $attributes = array('type' => 'submit',
1978 'value' => $button->label,
1979 'disabled' => $button->disabled ? 'disabled' : null,
1980 'title' => $button->tooltip);
1982 if ($button->actions) {
1983 $id = html_writer::random_id('single_button');
1984 $attributes['id'] = $id;
1985 foreach ($button->actions as $action) {
1986 $this->add_action_handler($action, $id);
1990 // first the input element
1991 $output = html_writer::empty_tag('input', $attributes);
1993 // then hidden fields
1994 $params = $button->url->params();
1995 if ($button->method === 'post') {
1996 $params['sesskey'] = sesskey();
1998 foreach ($params as $var => $val) {
1999 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
2002 // then div wrapper for xhtml strictness
2003 $output = html_writer::tag('div', $output);
2005 // now the form itself around it
2006 if ($button->method === 'get') {
2007 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
2008 } else {
2009 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
2011 if ($url === '') {
2012 $url = '#'; // there has to be always some action
2014 $attributes = array('method' => $button->method,
2015 'action' => $url,
2016 'id' => $button->formid);
2017 $output = html_writer::tag('form', $output, $attributes);
2019 // and finally one more wrapper with class
2020 return html_writer::tag('div', $output, array('class' => $button->class));
2024 * Returns a form with a single select widget.
2026 * Theme developers: DO NOT OVERRIDE! Please override function
2027 * {@link core_renderer::render_single_select()} instead.
2029 * @param moodle_url $url form action target, includes hidden fields
2030 * @param string $name name of selection field - the changing parameter in url
2031 * @param array $options list of options
2032 * @param string $selected selected element
2033 * @param array $nothing
2034 * @param string $formid
2035 * @param array $attributes other attributes for the single select
2036 * @return string HTML fragment
2038 public function single_select($url, $name, array $options, $selected = '',
2039 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2040 if (!($url instanceof moodle_url)) {
2041 $url = new moodle_url($url);
2043 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2045 if (array_key_exists('label', $attributes)) {
2046 $select->set_label($attributes['label']);
2047 unset($attributes['label']);
2049 $select->attributes = $attributes;
2051 return $this->render($select);
2055 * Returns a dataformat selection and download form
2057 * @param string $label A text label
2058 * @param moodle_url|string $base The download page url
2059 * @param string $name The query param which will hold the type of the download
2060 * @param array $params Extra params sent to the download page
2061 * @return string HTML fragment
2063 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2065 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2066 $options = array();
2067 foreach ($formats as $format) {
2068 if ($format->is_enabled()) {
2069 $options[] = array(
2070 'value' => $format->name,
2071 'label' => get_string('dataformat', $format->component),
2075 $hiddenparams = array();
2076 foreach ($params as $key => $value) {
2077 $hiddenparams[] = array(
2078 'name' => $key,
2079 'value' => $value,
2082 $data = array(
2083 'label' => $label,
2084 'base' => $base,
2085 'name' => $name,
2086 'params' => $hiddenparams,
2087 'options' => $options,
2088 'sesskey' => sesskey(),
2089 'submit' => get_string('download'),
2092 return $this->render_from_template('core/dataformat_selector', $data);
2097 * Internal implementation of single_select rendering
2099 * @param single_select $select
2100 * @return string HTML fragment
2102 protected function render_single_select(single_select $select) {
2103 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2107 * Returns a form with a url select widget.
2109 * Theme developers: DO NOT OVERRIDE! Please override function
2110 * {@link core_renderer::render_url_select()} instead.
2112 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2113 * @param string $selected selected element
2114 * @param array $nothing
2115 * @param string $formid
2116 * @return string HTML fragment
2118 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2119 $select = new url_select($urls, $selected, $nothing, $formid);
2120 return $this->render($select);
2124 * Internal implementation of url_select rendering
2126 * @param url_select $select
2127 * @return string HTML fragment
2129 protected function render_url_select(url_select $select) {
2130 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2134 * Returns a string containing a link to the user documentation.
2135 * Also contains an icon by default. Shown to teachers and admin only.
2137 * @param string $path The page link after doc root and language, no leading slash.
2138 * @param string $text The text to be displayed for the link
2139 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2140 * @return string
2142 public function doc_link($path, $text = '', $forcepopup = false) {
2143 global $CFG;
2145 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2147 $url = new moodle_url(get_docs_url($path));
2149 $attributes = array('href'=>$url);
2150 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2151 $attributes['class'] = 'helplinkpopup';
2154 return html_writer::tag('a', $icon.$text, $attributes);
2158 * Return HTML for an image_icon.
2160 * Theme developers: DO NOT OVERRIDE! Please override function
2161 * {@link core_renderer::render_image_icon()} instead.
2163 * @param string $pix short pix name
2164 * @param string $alt mandatory alt attribute
2165 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2166 * @param array $attributes htm lattributes
2167 * @return string HTML fragment
2169 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2170 $icon = new image_icon($pix, $alt, $component, $attributes);
2171 return $this->render($icon);
2175 * Renders a pix_icon widget and returns the HTML to display it.
2177 * @param image_icon $icon
2178 * @return string HTML fragment
2180 protected function render_image_icon(image_icon $icon) {
2181 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2182 return $system->render_pix_icon($this, $icon);
2186 * Return HTML for a pix_icon.
2188 * Theme developers: DO NOT OVERRIDE! Please override function
2189 * {@link core_renderer::render_pix_icon()} instead.
2191 * @param string $pix short pix name
2192 * @param string $alt mandatory alt attribute
2193 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2194 * @param array $attributes htm lattributes
2195 * @return string HTML fragment
2197 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2198 $icon = new pix_icon($pix, $alt, $component, $attributes);
2199 return $this->render($icon);
2203 * Renders a pix_icon widget and returns the HTML to display it.
2205 * @param pix_icon $icon
2206 * @return string HTML fragment
2208 protected function render_pix_icon(pix_icon $icon) {
2209 $system = \core\output\icon_system::instance();
2210 return $system->render_pix_icon($this, $icon);
2214 * Return HTML to display an emoticon icon.
2216 * @param pix_emoticon $emoticon
2217 * @return string HTML fragment
2219 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2220 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2221 return $system->render_pix_icon($this, $emoticon);
2225 * Produces the html that represents this rating in the UI
2227 * @param rating $rating the page object on which this rating will appear
2228 * @return string
2230 function render_rating(rating $rating) {
2231 global $CFG, $USER;
2233 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2234 return null;//ratings are turned off
2237 $ratingmanager = new rating_manager();
2238 // Initialise the JavaScript so ratings can be done by AJAX.
2239 $ratingmanager->initialise_rating_javascript($this->page);
2241 $strrate = get_string("rate", "rating");
2242 $ratinghtml = ''; //the string we'll return
2244 // permissions check - can they view the aggregate?
2245 if ($rating->user_can_view_aggregate()) {
2247 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2248 $aggregatestr = $rating->get_aggregate_string();
2250 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2251 if ($rating->count > 0) {
2252 $countstr = "({$rating->count})";
2253 } else {
2254 $countstr = '-';
2256 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2258 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2259 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2261 $nonpopuplink = $rating->get_view_ratings_url();
2262 $popuplink = $rating->get_view_ratings_url(true);
2264 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2265 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2266 } else {
2267 $ratinghtml .= $aggregatehtml;
2271 $formstart = null;
2272 // if the item doesn't belong to the current user, the user has permission to rate
2273 // and we're within the assessable period
2274 if ($rating->user_can_rate()) {
2276 $rateurl = $rating->get_rate_url();
2277 $inputs = $rateurl->params();
2279 //start the rating form
2280 $formattrs = array(
2281 'id' => "postrating{$rating->itemid}",
2282 'class' => 'postratingform',
2283 'method' => 'post',
2284 'action' => $rateurl->out_omit_querystring()
2286 $formstart = html_writer::start_tag('form', $formattrs);
2287 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2289 // add the hidden inputs
2290 foreach ($inputs as $name => $value) {
2291 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2292 $formstart .= html_writer::empty_tag('input', $attributes);
2295 if (empty($ratinghtml)) {
2296 $ratinghtml .= $strrate.': ';
2298 $ratinghtml = $formstart.$ratinghtml;
2300 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2301 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2302 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2303 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2305 //output submit button
2306 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2308 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2309 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2311 if (!$rating->settings->scale->isnumeric) {
2312 // If a global scale, try to find current course ID from the context
2313 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2314 $courseid = $coursecontext->instanceid;
2315 } else {
2316 $courseid = $rating->settings->scale->courseid;
2318 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2320 $ratinghtml .= html_writer::end_tag('span');
2321 $ratinghtml .= html_writer::end_tag('div');
2322 $ratinghtml .= html_writer::end_tag('form');
2325 return $ratinghtml;
2329 * Centered heading with attached help button (same title text)
2330 * and optional icon attached.
2332 * @param string $text A heading text
2333 * @param string $helpidentifier The keyword that defines a help page
2334 * @param string $component component name
2335 * @param string|moodle_url $icon
2336 * @param string $iconalt icon alt text
2337 * @param int $level The level of importance of the heading. Defaulting to 2
2338 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2339 * @return string HTML fragment
2341 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2342 $image = '';
2343 if ($icon) {
2344 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2347 $help = '';
2348 if ($helpidentifier) {
2349 $help = $this->help_icon($helpidentifier, $component);
2352 return $this->heading($image.$text.$help, $level, $classnames);
2356 * Returns HTML to display a help icon.
2358 * @deprecated since Moodle 2.0
2360 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2361 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2365 * Returns HTML to display a help icon.
2367 * Theme developers: DO NOT OVERRIDE! Please override function
2368 * {@link core_renderer::render_help_icon()} instead.
2370 * @param string $identifier The keyword that defines a help page
2371 * @param string $component component name
2372 * @param string|bool $linktext true means use $title as link text, string means link text value
2373 * @return string HTML fragment
2375 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2376 $icon = new help_icon($identifier, $component);
2377 $icon->diag_strings();
2378 if ($linktext === true) {
2379 $icon->linktext = get_string($icon->identifier, $icon->component);
2380 } else if (!empty($linktext)) {
2381 $icon->linktext = $linktext;
2383 return $this->render($icon);
2387 * Implementation of user image rendering.
2389 * @param help_icon $helpicon A help icon instance
2390 * @return string HTML fragment
2392 protected function render_help_icon(help_icon $helpicon) {
2393 return $this->render_from_template('core/help_icon', $helpicon->export_for_template($this));
2397 * Returns HTML to display a scale help icon.
2399 * @param int $courseid
2400 * @param stdClass $scale instance
2401 * @return string HTML fragment
2403 public function help_icon_scale($courseid, stdClass $scale) {
2404 global $CFG;
2406 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2408 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2410 $scaleid = abs($scale->id);
2412 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2413 $action = new popup_action('click', $link, 'ratingscale');
2415 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2419 * Creates and returns a spacer image with optional line break.
2421 * @param array $attributes Any HTML attributes to add to the spaced.
2422 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2423 * laxy do it with CSS which is a much better solution.
2424 * @return string HTML fragment
2426 public function spacer(array $attributes = null, $br = false) {
2427 $attributes = (array)$attributes;
2428 if (empty($attributes['width'])) {
2429 $attributes['width'] = 1;
2431 if (empty($attributes['height'])) {
2432 $attributes['height'] = 1;
2434 $attributes['class'] = 'spacer';
2436 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2438 if (!empty($br)) {
2439 $output .= '<br />';
2442 return $output;
2446 * Returns HTML to display the specified user's avatar.
2448 * User avatar may be obtained in two ways:
2449 * <pre>
2450 * // Option 1: (shortcut for simple cases, preferred way)
2451 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2452 * $OUTPUT->user_picture($user, array('popup'=>true));
2454 * // Option 2:
2455 * $userpic = new user_picture($user);
2456 * // Set properties of $userpic
2457 * $userpic->popup = true;
2458 * $OUTPUT->render($userpic);
2459 * </pre>
2461 * Theme developers: DO NOT OVERRIDE! Please override function
2462 * {@link core_renderer::render_user_picture()} instead.
2464 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2465 * If any of these are missing, the database is queried. Avoid this
2466 * if at all possible, particularly for reports. It is very bad for performance.
2467 * @param array $options associative array with user picture options, used only if not a user_picture object,
2468 * options are:
2469 * - courseid=$this->page->course->id (course id of user profile in link)
2470 * - size=35 (size of image)
2471 * - link=true (make image clickable - the link leads to user profile)
2472 * - popup=false (open in popup)
2473 * - alttext=true (add image alt attribute)
2474 * - class = image class attribute (default 'userpicture')
2475 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2476 * - includefullname=false (whether to include the user's full name together with the user picture)
2477 * @return string HTML fragment
2479 public function user_picture(stdClass $user, array $options = null) {
2480 $userpicture = new user_picture($user);
2481 foreach ((array)$options as $key=>$value) {
2482 if (array_key_exists($key, $userpicture)) {
2483 $userpicture->$key = $value;
2486 return $this->render($userpicture);
2490 * Internal implementation of user image rendering.
2492 * @param user_picture $userpicture
2493 * @return string
2495 protected function render_user_picture(user_picture $userpicture) {
2496 global $CFG, $DB;
2498 $user = $userpicture->user;
2500 if ($userpicture->alttext) {
2501 if (!empty($user->imagealt)) {
2502 $alt = $user->imagealt;
2503 } else {
2504 $alt = get_string('pictureof', '', fullname($user));
2506 } else {
2507 $alt = '';
2510 if (empty($userpicture->size)) {
2511 $size = 35;
2512 } else if ($userpicture->size === true or $userpicture->size == 1) {
2513 $size = 100;
2514 } else {
2515 $size = $userpicture->size;
2518 $class = $userpicture->class;
2520 if ($user->picture == 0) {
2521 $class .= ' defaultuserpic';
2524 $src = $userpicture->get_url($this->page, $this);
2526 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2527 if (!$userpicture->visibletoscreenreaders) {
2528 $attributes['role'] = 'presentation';
2531 // get the image html output fisrt
2532 $output = html_writer::empty_tag('img', $attributes);
2534 // Show fullname together with the picture when desired.
2535 if ($userpicture->includefullname) {
2536 $output .= fullname($userpicture->user);
2539 // then wrap it in link if needed
2540 if (!$userpicture->link) {
2541 return $output;
2544 if (empty($userpicture->courseid)) {
2545 $courseid = $this->page->course->id;
2546 } else {
2547 $courseid = $userpicture->courseid;
2550 if ($courseid == SITEID) {
2551 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2552 } else {
2553 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2556 $attributes = array('href'=>$url);
2557 if (!$userpicture->visibletoscreenreaders) {
2558 $attributes['tabindex'] = '-1';
2559 $attributes['aria-hidden'] = 'true';
2562 if ($userpicture->popup) {
2563 $id = html_writer::random_id('userpicture');
2564 $attributes['id'] = $id;
2565 $this->add_action_handler(new popup_action('click', $url), $id);
2568 return html_writer::tag('a', $output, $attributes);
2572 * Internal implementation of file tree viewer items rendering.
2574 * @param array $dir
2575 * @return string
2577 public function htmllize_file_tree($dir) {
2578 if (empty($dir['subdirs']) and empty($dir['files'])) {
2579 return '';
2581 $result = '<ul>';
2582 foreach ($dir['subdirs'] as $subdir) {
2583 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2585 foreach ($dir['files'] as $file) {
2586 $filename = $file->get_filename();
2587 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2589 $result .= '</ul>';
2591 return $result;
2595 * Returns HTML to display the file picker
2597 * <pre>
2598 * $OUTPUT->file_picker($options);
2599 * </pre>
2601 * Theme developers: DO NOT OVERRIDE! Please override function
2602 * {@link core_renderer::render_file_picker()} instead.
2604 * @param array $options associative array with file manager options
2605 * options are:
2606 * maxbytes=>-1,
2607 * itemid=>0,
2608 * client_id=>uniqid(),
2609 * acepted_types=>'*',
2610 * return_types=>FILE_INTERNAL,
2611 * context=>$PAGE->context
2612 * @return string HTML fragment
2614 public function file_picker($options) {
2615 $fp = new file_picker($options);
2616 return $this->render($fp);
2620 * Internal implementation of file picker rendering.
2622 * @param file_picker $fp
2623 * @return string
2625 public function render_file_picker(file_picker $fp) {
2626 global $CFG, $OUTPUT, $USER;
2627 $options = $fp->options;
2628 $client_id = $options->client_id;
2629 $strsaved = get_string('filesaved', 'repository');
2630 $straddfile = get_string('openpicker', 'repository');
2631 $strloading = get_string('loading', 'repository');
2632 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2633 $strdroptoupload = get_string('droptoupload', 'moodle');
2634 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2636 $currentfile = $options->currentfile;
2637 if (empty($currentfile)) {
2638 $currentfile = '';
2639 } else {
2640 $currentfile .= ' - ';
2642 if ($options->maxbytes) {
2643 $size = $options->maxbytes;
2644 } else {
2645 $size = get_max_upload_file_size();
2647 if ($size == -1) {
2648 $maxsize = '';
2649 } else {
2650 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2652 if ($options->buttonname) {
2653 $buttonname = ' name="' . $options->buttonname . '"';
2654 } else {
2655 $buttonname = '';
2657 $html = <<<EOD
2658 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2659 $icon_progress
2660 </div>
2661 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2662 <div>
2663 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2664 <span> $maxsize </span>
2665 </div>
2666 EOD;
2667 if ($options->env != 'url') {
2668 $html .= <<<EOD
2669 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2670 <div class="filepicker-filename">
2671 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2672 <div class="dndupload-progressbars"></div>
2673 </div>
2674 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2675 </div>
2676 EOD;
2678 $html .= '</div>';
2679 return $html;
2683 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2685 * @deprecated since Moodle 3.2
2687 * @param string $cmid the course_module id.
2688 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2689 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2691 public function update_module_button($cmid, $modulename) {
2692 global $CFG;
2694 debugging('core_renderer::update_module_button() has been deprecated and should not be used anymore. Activity modules ' .
2695 'should not add the edit module button, the link is already available in the Administration block. Themes can choose ' .
2696 'to display the link in the buttons row consistently for all module types.', DEBUG_DEVELOPER);
2698 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2699 $modulename = get_string('modulename', $modulename);
2700 $string = get_string('updatethis', '', $modulename);
2701 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2702 return $this->single_button($url, $string);
2703 } else {
2704 return '';
2709 * Returns HTML to display a "Turn editing on/off" button in a form.
2711 * @param moodle_url $url The URL + params to send through when clicking the button
2712 * @return string HTML the button
2714 public function edit_button(moodle_url $url) {
2716 $url->param('sesskey', sesskey());
2717 if ($this->page->user_is_editing()) {
2718 $url->param('edit', 'off');
2719 $editstring = get_string('turneditingoff');
2720 } else {
2721 $url->param('edit', 'on');
2722 $editstring = get_string('turneditingon');
2725 return $this->single_button($url, $editstring);
2729 * Returns HTML to display a simple button to close a window
2731 * @param string $text The lang string for the button's label (already output from get_string())
2732 * @return string html fragment
2734 public function close_window_button($text='') {
2735 if (empty($text)) {
2736 $text = get_string('closewindow');
2738 $button = new single_button(new moodle_url('#'), $text, 'get');
2739 $button->add_action(new component_action('click', 'close_window'));
2741 return $this->container($this->render($button), 'closewindow');
2745 * Output an error message. By default wraps the error message in <span class="error">.
2746 * If the error message is blank, nothing is output.
2748 * @param string $message the error message.
2749 * @return string the HTML to output.
2751 public function error_text($message) {
2752 if (empty($message)) {
2753 return '';
2755 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2756 return html_writer::tag('span', $message, array('class' => 'error'));
2760 * Do not call this function directly.
2762 * To terminate the current script with a fatal error, call the {@link print_error}
2763 * function, or throw an exception. Doing either of those things will then call this
2764 * function to display the error, before terminating the execution.
2766 * @param string $message The message to output
2767 * @param string $moreinfourl URL where more info can be found about the error
2768 * @param string $link Link for the Continue button
2769 * @param array $backtrace The execution backtrace
2770 * @param string $debuginfo Debugging information
2771 * @return string the HTML to output.
2773 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2774 global $CFG;
2776 $output = '';
2777 $obbuffer = '';
2779 if ($this->has_started()) {
2780 // we can not always recover properly here, we have problems with output buffering,
2781 // html tables, etc.
2782 $output .= $this->opencontainers->pop_all_but_last();
2784 } else {
2785 // It is really bad if library code throws exception when output buffering is on,
2786 // because the buffered text would be printed before our start of page.
2787 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2788 error_reporting(0); // disable notices from gzip compression, etc.
2789 while (ob_get_level() > 0) {
2790 $buff = ob_get_clean();
2791 if ($buff === false) {
2792 break;
2794 $obbuffer .= $buff;
2796 error_reporting($CFG->debug);
2798 // Output not yet started.
2799 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2800 if (empty($_SERVER['HTTP_RANGE'])) {
2801 @header($protocol . ' 404 Not Found');
2802 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2803 // Coax iOS 10 into sending the session cookie.
2804 @header($protocol . ' 403 Forbidden');
2805 } else {
2806 // Must stop byteserving attempts somehow,
2807 // this is weird but Chrome PDF viewer can be stopped only with 407!
2808 @header($protocol . ' 407 Proxy Authentication Required');
2811 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2812 $this->page->set_url('/'); // no url
2813 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2814 $this->page->set_title(get_string('error'));
2815 $this->page->set_heading($this->page->course->fullname);
2816 $output .= $this->header();
2819 $message = '<p class="errormessage">' . $message . '</p>'.
2820 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2821 get_string('moreinformation') . '</a></p>';
2822 if (empty($CFG->rolesactive)) {
2823 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2824 //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.
2826 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2828 if ($CFG->debugdeveloper) {
2829 if (!empty($debuginfo)) {
2830 $debuginfo = s($debuginfo); // removes all nasty JS
2831 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2832 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2834 if (!empty($backtrace)) {
2835 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2837 if ($obbuffer !== '' ) {
2838 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2842 if (empty($CFG->rolesactive)) {
2843 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2844 } else if (!empty($link)) {
2845 $output .= $this->continue_button($link);
2848 $output .= $this->footer();
2850 // Padding to encourage IE to display our error page, rather than its own.
2851 $output .= str_repeat(' ', 512);
2853 return $output;
2857 * Output a notification (that is, a status message about something that has just happened).
2859 * Note: \core\notification::add() may be more suitable for your usage.
2861 * @param string $message The message to print out.
2862 * @param string $type The type of notification. See constants on \core\output\notification.
2863 * @return string the HTML to output.
2865 public function notification($message, $type = null) {
2866 $typemappings = [
2867 // Valid types.
2868 'success' => \core\output\notification::NOTIFY_SUCCESS,
2869 'info' => \core\output\notification::NOTIFY_INFO,
2870 'warning' => \core\output\notification::NOTIFY_WARNING,
2871 'error' => \core\output\notification::NOTIFY_ERROR,
2873 // Legacy types mapped to current types.
2874 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2875 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2876 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2877 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2878 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2879 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2880 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2883 $extraclasses = [];
2885 if ($type) {
2886 if (strpos($type, ' ') === false) {
2887 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2888 if (isset($typemappings[$type])) {
2889 $type = $typemappings[$type];
2890 } else {
2891 // The value provided did not match a known type. It must be an extra class.
2892 $extraclasses = [$type];
2894 } else {
2895 // Identify what type of notification this is.
2896 $classarray = explode(' ', self::prepare_classes($type));
2898 // Separate out the type of notification from the extra classes.
2899 foreach ($classarray as $class) {
2900 if (isset($typemappings[$class])) {
2901 $type = $typemappings[$class];
2902 } else {
2903 $extraclasses[] = $class;
2909 $notification = new \core\output\notification($message, $type);
2910 if (count($extraclasses)) {
2911 $notification->set_extra_classes($extraclasses);
2914 // Return the rendered template.
2915 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2919 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2921 public function notify_problem() {
2922 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
2923 'please use \core\notification::add(), or \core\output\notification as required.');
2927 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2929 public function notify_success() {
2930 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
2931 'please use \core\notification::add(), or \core\output\notification as required.');
2935 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2937 public function notify_message() {
2938 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
2939 'please use \core\notification::add(), or \core\output\notification as required.');
2943 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2945 public function notify_redirect() {
2946 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
2947 'please use \core\notification::add(), or \core\output\notification as required.');
2951 * Render a notification (that is, a status message about something that has
2952 * just happened).
2954 * @param \core\output\notification $notification the notification to print out
2955 * @return string the HTML to output.
2957 protected function render_notification(\core\output\notification $notification) {
2958 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2962 * Returns HTML to display a continue button that goes to a particular URL.
2964 * @param string|moodle_url $url The url the button goes to.
2965 * @return string the HTML to output.
2967 public function continue_button($url) {
2968 if (!($url instanceof moodle_url)) {
2969 $url = new moodle_url($url);
2971 $button = new single_button($url, get_string('continue'), 'get', true);
2972 $button->class = 'continuebutton';
2974 return $this->render($button);
2978 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2980 * Theme developers: DO NOT OVERRIDE! Please override function
2981 * {@link core_renderer::render_paging_bar()} instead.
2983 * @param int $totalcount The total number of entries available to be paged through
2984 * @param int $page The page you are currently viewing
2985 * @param int $perpage The number of entries that should be shown per page
2986 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2987 * @param string $pagevar name of page parameter that holds the page number
2988 * @return string the HTML to output.
2990 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2991 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2992 return $this->render($pb);
2996 * Internal implementation of paging bar rendering.
2998 * @param paging_bar $pagingbar
2999 * @return string
3001 protected function render_paging_bar(paging_bar $pagingbar) {
3002 $output = '';
3003 $pagingbar = clone($pagingbar);
3004 $pagingbar->prepare($this, $this->page, $this->target);
3006 if ($pagingbar->totalcount > $pagingbar->perpage) {
3007 $output .= get_string('page') . ':';
3009 if (!empty($pagingbar->previouslink)) {
3010 $output .= ' (' . $pagingbar->previouslink . ') ';
3013 if (!empty($pagingbar->firstlink)) {
3014 $output .= ' ' . $pagingbar->firstlink . ' ...';
3017 foreach ($pagingbar->pagelinks as $link) {
3018 $output .= " $link";
3021 if (!empty($pagingbar->lastlink)) {
3022 $output .= ' ... ' . $pagingbar->lastlink . ' ';
3025 if (!empty($pagingbar->nextlink)) {
3026 $output .= ' (' . $pagingbar->nextlink . ')';
3030 return html_writer::tag('div', $output, array('class' => 'paging'));
3034 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3036 * @param string $current the currently selected letter.
3037 * @param string $class class name to add to this initial bar.
3038 * @param string $title the name to put in front of this initial bar.
3039 * @param string $urlvar URL parameter name for this initial.
3040 * @param string $url URL object.
3041 * @param array $alpha of letters in the alphabet.
3042 * @return string the HTML to output.
3044 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3045 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3046 return $this->render($ib);
3050 * Internal implementation of initials bar rendering.
3052 * @param initials_bar $initialsbar
3053 * @return string
3055 protected function render_initials_bar(initials_bar $initialsbar) {
3056 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3060 * Output the place a skip link goes to.
3062 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3063 * @return string the HTML to output.
3065 public function skip_link_target($id = null) {
3066 return html_writer::span('', '', array('id' => $id));
3070 * Outputs a heading
3072 * @param string $text The text of the heading
3073 * @param int $level The level of importance of the heading. Defaulting to 2
3074 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3075 * @param string $id An optional ID
3076 * @return string the HTML to output.
3078 public function heading($text, $level = 2, $classes = null, $id = null) {
3079 $level = (integer) $level;
3080 if ($level < 1 or $level > 6) {
3081 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3083 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3087 * Outputs a box.
3089 * @param string $contents The contents of the box
3090 * @param string $classes A space-separated list of CSS classes
3091 * @param string $id An optional ID
3092 * @param array $attributes An array of other attributes to give the box.
3093 * @return string the HTML to output.
3095 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3096 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3100 * Outputs the opening section of a box.
3102 * @param string $classes A space-separated list of CSS classes
3103 * @param string $id An optional ID
3104 * @param array $attributes An array of other attributes to give the box.
3105 * @return string the HTML to output.
3107 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3108 $this->opencontainers->push('box', html_writer::end_tag('div'));
3109 $attributes['id'] = $id;
3110 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
3111 return html_writer::start_tag('div', $attributes);
3115 * Outputs the closing section of a box.
3117 * @return string the HTML to output.
3119 public function box_end() {
3120 return $this->opencontainers->pop('box');
3124 * Outputs a container.
3126 * @param string $contents The contents of the box
3127 * @param string $classes A space-separated list of CSS classes
3128 * @param string $id An optional ID
3129 * @return string the HTML to output.
3131 public function container($contents, $classes = null, $id = null) {
3132 return $this->container_start($classes, $id) . $contents . $this->container_end();
3136 * Outputs the opening section of a container.
3138 * @param string $classes A space-separated list of CSS classes
3139 * @param string $id An optional ID
3140 * @return string the HTML to output.
3142 public function container_start($classes = null, $id = null) {
3143 $this->opencontainers->push('container', html_writer::end_tag('div'));
3144 return html_writer::start_tag('div', array('id' => $id,
3145 'class' => renderer_base::prepare_classes($classes)));
3149 * Outputs the closing section of a container.
3151 * @return string the HTML to output.
3153 public function container_end() {
3154 return $this->opencontainers->pop('container');
3158 * Make nested HTML lists out of the items
3160 * The resulting list will look something like this:
3162 * <pre>
3163 * <<ul>>
3164 * <<li>><div class='tree_item parent'>(item contents)</div>
3165 * <<ul>
3166 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3167 * <</ul>>
3168 * <</li>>
3169 * <</ul>>
3170 * </pre>
3172 * @param array $items
3173 * @param array $attrs html attributes passed to the top ofs the list
3174 * @return string HTML
3176 public function tree_block_contents($items, $attrs = array()) {
3177 // exit if empty, we don't want an empty ul element
3178 if (empty($items)) {
3179 return '';
3181 // array of nested li elements
3182 $lis = array();
3183 foreach ($items as $item) {
3184 // this applies to the li item which contains all child lists too
3185 $content = $item->content($this);
3186 $liclasses = array($item->get_css_type());
3187 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3188 $liclasses[] = 'collapsed';
3190 if ($item->isactive === true) {
3191 $liclasses[] = 'current_branch';
3193 $liattr = array('class'=>join(' ',$liclasses));
3194 // class attribute on the div item which only contains the item content
3195 $divclasses = array('tree_item');
3196 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3197 $divclasses[] = 'branch';
3198 } else {
3199 $divclasses[] = 'leaf';
3201 if (!empty($item->classes) && count($item->classes)>0) {
3202 $divclasses[] = join(' ', $item->classes);
3204 $divattr = array('class'=>join(' ', $divclasses));
3205 if (!empty($item->id)) {
3206 $divattr['id'] = $item->id;
3208 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3209 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3210 $content = html_writer::empty_tag('hr') . $content;
3212 $content = html_writer::tag('li', $content, $liattr);
3213 $lis[] = $content;
3215 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3219 * Returns a search box.
3221 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3222 * @return string HTML with the search form hidden by default.
3224 public function search_box($id = false) {
3225 global $CFG;
3227 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3228 // result in an extra included file for each site, even the ones where global search
3229 // is disabled.
3230 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3231 return '';
3234 if ($id == false) {
3235 $id = uniqid();
3236 } else {
3237 // Needs to be cleaned, we use it for the input id.
3238 $id = clean_param($id, PARAM_ALPHANUMEXT);
3241 // JS to animate the form.
3242 $this->page->requires->js_call_amd('core/search-input', 'init', array($id));
3244 $searchicon = html_writer::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
3245 array('role' => 'button', 'tabindex' => 0));
3246 $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot . '/search/index.php');
3247 $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
3248 'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id, 'class' => 'form-control');
3250 $contents = html_writer::tag('label', get_string('enteryoursearchquery', 'search'),
3251 array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer::tag('input', '', $inputattrs);
3252 if ($this->page->context && $this->page->context->contextlevel !== CONTEXT_SYSTEM) {
3253 $contents .= html_writer::empty_tag('input', ['type' => 'hidden',
3254 'name' => 'context', 'value' => $this->page->context->id]);
3256 $searchinput = html_writer::tag('form', $contents, $formattrs);
3258 return html_writer::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper nav-link', 'id' => $id));
3262 * Allow plugins to provide some content to be rendered in the navbar.
3263 * The plugin must define a PLUGIN_render_navbar_output function that returns
3264 * the HTML they wish to add to the navbar.
3266 * @return string HTML for the navbar
3268 public function navbar_plugin_output() {
3269 $output = '';
3271 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3272 foreach ($pluginsfunction as $plugintype => $plugins) {
3273 foreach ($plugins as $pluginfunction) {
3274 $output .= $pluginfunction($this);
3279 return $output;
3283 * Construct a user menu, returning HTML that can be echoed out by a
3284 * layout file.
3286 * @param stdClass $user A user object, usually $USER.
3287 * @param bool $withlinks true if a dropdown should be built.
3288 * @return string HTML fragment.
3290 public function user_menu($user = null, $withlinks = null) {
3291 global $USER, $CFG;
3292 require_once($CFG->dirroot . '/user/lib.php');
3294 if (is_null($user)) {
3295 $user = $USER;
3298 // Note: this behaviour is intended to match that of core_renderer::login_info,
3299 // but should not be considered to be good practice; layout options are
3300 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3301 if (is_null($withlinks)) {
3302 $withlinks = empty($this->page->layout_options['nologinlinks']);
3305 // Add a class for when $withlinks is false.
3306 $usermenuclasses = 'usermenu';
3307 if (!$withlinks) {
3308 $usermenuclasses .= ' withoutlinks';
3311 $returnstr = "";
3313 // If during initial install, return the empty return string.
3314 if (during_initial_install()) {
3315 return $returnstr;
3318 $loginpage = $this->is_login_page();
3319 $loginurl = get_login_url();
3320 // If not logged in, show the typical not-logged-in string.
3321 if (!isloggedin()) {
3322 $returnstr = get_string('loggedinnot', 'moodle');
3323 if (!$loginpage) {
3324 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3326 return html_writer::div(
3327 html_writer::span(
3328 $returnstr,
3329 'login'
3331 $usermenuclasses
3336 // If logged in as a guest user, show a string to that effect.
3337 if (isguestuser()) {
3338 $returnstr = get_string('loggedinasguest');
3339 if (!$loginpage && $withlinks) {
3340 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3343 return html_writer::div(
3344 html_writer::span(
3345 $returnstr,
3346 'login'
3348 $usermenuclasses
3352 // Get some navigation opts.
3353 $opts = user_get_user_navigation_info($user, $this->page);
3355 $avatarclasses = "avatars";
3356 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3357 $usertextcontents = $opts->metadata['userfullname'];
3359 // Other user.
3360 if (!empty($opts->metadata['asotheruser'])) {
3361 $avatarcontents .= html_writer::span(
3362 $opts->metadata['realuseravatar'],
3363 'avatar realuser'
3365 $usertextcontents = $opts->metadata['realuserfullname'];
3366 $usertextcontents .= html_writer::tag(
3367 'span',
3368 get_string(
3369 'loggedinas',
3370 'moodle',
3371 html_writer::span(
3372 $opts->metadata['userfullname'],
3373 'value'
3376 array('class' => 'meta viewingas')
3380 // Role.
3381 if (!empty($opts->metadata['asotherrole'])) {
3382 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3383 $usertextcontents .= html_writer::span(
3384 $opts->metadata['rolename'],
3385 'meta role role-' . $role
3389 // User login failures.
3390 if (!empty($opts->metadata['userloginfail'])) {
3391 $usertextcontents .= html_writer::span(
3392 $opts->metadata['userloginfail'],
3393 'meta loginfailures'
3397 // MNet.
3398 if (!empty($opts->metadata['asmnetuser'])) {
3399 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3400 $usertextcontents .= html_writer::span(
3401 $opts->metadata['mnetidprovidername'],
3402 'meta mnet mnet-' . $mnet
3406 $returnstr .= html_writer::span(
3407 html_writer::span($usertextcontents, 'usertext mr-1') .
3408 html_writer::span($avatarcontents, $avatarclasses),
3409 'userbutton'
3412 // Create a divider (well, a filler).
3413 $divider = new action_menu_filler();
3414 $divider->primary = false;
3416 $am = new action_menu();
3417 $am->set_menu_trigger(
3418 $returnstr
3420 $am->set_alignment(action_menu::TR, action_menu::BR);
3421 $am->set_nowrap_on_items();
3422 if ($withlinks) {
3423 $navitemcount = count($opts->navitems);
3424 $idx = 0;
3425 foreach ($opts->navitems as $key => $value) {
3427 switch ($value->itemtype) {
3428 case 'divider':
3429 // If the nav item is a divider, add one and skip link processing.
3430 $am->add($divider);
3431 break;
3433 case 'invalid':
3434 // Silently skip invalid entries (should we post a notification?).
3435 break;
3437 case 'link':
3438 // Process this as a link item.
3439 $pix = null;
3440 if (isset($value->pix) && !empty($value->pix)) {
3441 $pix = new pix_icon($value->pix, $value->title, null, array('class' => 'iconsmall'));
3442 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3443 $value->title = html_writer::img(
3444 $value->imgsrc,
3445 $value->title,
3446 array('class' => 'iconsmall')
3447 ) . $value->title;
3450 $al = new action_menu_link_secondary(
3451 $value->url,
3452 $pix,
3453 $value->title,
3454 array('class' => 'icon')
3456 if (!empty($value->titleidentifier)) {
3457 $al->attributes['data-title'] = $value->titleidentifier;
3459 $am->add($al);
3460 break;
3463 $idx++;
3465 // Add dividers after the first item and before the last item.
3466 if ($idx == 1 || $idx == $navitemcount - 1) {
3467 $am->add($divider);
3472 return html_writer::div(
3473 $this->render($am),
3474 $usermenuclasses
3479 * Return the navbar content so that it can be echoed out by the layout
3481 * @return string XHTML navbar
3483 public function navbar() {
3484 $items = $this->page->navbar->get_items();
3485 $itemcount = count($items);
3486 if ($itemcount === 0) {
3487 return '';
3490 $htmlblocks = array();
3491 // Iterate the navarray and display each node
3492 $separator = get_separator();
3493 for ($i=0;$i < $itemcount;$i++) {
3494 $item = $items[$i];
3495 $item->hideicon = true;
3496 if ($i===0) {
3497 $content = html_writer::tag('li', $this->render($item));
3498 } else {
3499 $content = html_writer::tag('li', $separator.$this->render($item));
3501 $htmlblocks[] = $content;
3504 //accessibility: heading for navbar list (MDL-20446)
3505 $navbarcontent = html_writer::tag('span', get_string('pagepath'),
3506 array('class' => 'accesshide', 'id' => 'navbar-label'));
3507 $navbarcontent .= html_writer::tag('nav',
3508 html_writer::tag('ul', join('', $htmlblocks)),
3509 array('aria-labelledby' => 'navbar-label'));
3510 // XHTML
3511 return $navbarcontent;
3515 * Renders a breadcrumb navigation node object.
3517 * @param breadcrumb_navigation_node $item The navigation node to render.
3518 * @return string HTML fragment
3520 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3522 if ($item->action instanceof moodle_url) {
3523 $content = $item->get_content();
3524 $title = $item->get_title();
3525 $attributes = array();
3526 $attributes['itemprop'] = 'url';
3527 if ($title !== '') {
3528 $attributes['title'] = $title;
3530 if ($item->hidden) {
3531 $attributes['class'] = 'dimmed_text';
3533 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3534 $content = html_writer::link($item->action, $content, $attributes);
3536 $attributes = array();
3537 $attributes['itemscope'] = '';
3538 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3539 $content = html_writer::tag('span', $content, $attributes);
3541 } else {
3542 $content = $this->render_navigation_node($item);
3544 return $content;
3548 * Renders a navigation node object.
3550 * @param navigation_node $item The navigation node to render.
3551 * @return string HTML fragment
3553 protected function render_navigation_node(navigation_node $item) {
3554 $content = $item->get_content();
3555 $title = $item->get_title();
3556 if ($item->icon instanceof renderable && !$item->hideicon) {
3557 $icon = $this->render($item->icon);
3558 $content = $icon.$content; // use CSS for spacing of icons
3560 if ($item->helpbutton !== null) {
3561 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3563 if ($content === '') {
3564 return '';
3566 if ($item->action instanceof action_link) {
3567 $link = $item->action;
3568 if ($item->hidden) {
3569 $link->add_class('dimmed');
3571 if (!empty($content)) {
3572 // Providing there is content we will use that for the link content.
3573 $link->text = $content;
3575 $content = $this->render($link);
3576 } else if ($item->action instanceof moodle_url) {
3577 $attributes = array();
3578 if ($title !== '') {
3579 $attributes['title'] = $title;
3581 if ($item->hidden) {
3582 $attributes['class'] = 'dimmed_text';
3584 $content = html_writer::link($item->action, $content, $attributes);
3586 } else if (is_string($item->action) || empty($item->action)) {
3587 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3588 if ($title !== '') {
3589 $attributes['title'] = $title;
3591 if ($item->hidden) {
3592 $attributes['class'] = 'dimmed_text';
3594 $content = html_writer::tag('span', $content, $attributes);
3596 return $content;
3600 * Accessibility: Right arrow-like character is
3601 * used in the breadcrumb trail, course navigation menu
3602 * (previous/next activity), calendar, and search forum block.
3603 * If the theme does not set characters, appropriate defaults
3604 * are set automatically. Please DO NOT
3605 * use &lt; &gt; &raquo; - these are confusing for blind users.
3607 * @return string
3609 public function rarrow() {
3610 return $this->page->theme->rarrow;
3614 * Accessibility: Left arrow-like character is
3615 * used in the breadcrumb trail, course navigation menu
3616 * (previous/next activity), calendar, and search forum block.
3617 * If the theme does not set characters, appropriate defaults
3618 * are set automatically. Please DO NOT
3619 * use &lt; &gt; &raquo; - these are confusing for blind users.
3621 * @return string
3623 public function larrow() {
3624 return $this->page->theme->larrow;
3628 * Accessibility: Up arrow-like character is used in
3629 * the book heirarchical navigation.
3630 * If the theme does not set characters, appropriate defaults
3631 * are set automatically. Please DO NOT
3632 * use ^ - this is confusing for blind users.
3634 * @return string
3636 public function uarrow() {
3637 return $this->page->theme->uarrow;
3641 * Accessibility: Down arrow-like character.
3642 * If the theme does not set characters, appropriate defaults
3643 * are set automatically.
3645 * @return string
3647 public function darrow() {
3648 return $this->page->theme->darrow;
3652 * Returns the custom menu if one has been set
3654 * A custom menu can be configured by browsing to
3655 * Settings: Administration > Appearance > Themes > Theme settings
3656 * and then configuring the custommenu config setting as described.
3658 * Theme developers: DO NOT OVERRIDE! Please override function
3659 * {@link core_renderer::render_custom_menu()} instead.
3661 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3662 * @return string
3664 public function custom_menu($custommenuitems = '') {
3665 global $CFG;
3666 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3667 $custommenuitems = $CFG->custommenuitems;
3669 if (empty($custommenuitems)) {
3670 return '';
3672 $custommenu = new custom_menu($custommenuitems, current_language());
3673 return $this->render($custommenu);
3677 * Renders a custom menu object (located in outputcomponents.php)
3679 * The custom menu this method produces makes use of the YUI3 menunav widget
3680 * and requires very specific html elements and classes.
3682 * @staticvar int $menucount
3683 * @param custom_menu $menu
3684 * @return string
3686 protected function render_custom_menu(custom_menu $menu) {
3687 static $menucount = 0;
3688 // If the menu has no children return an empty string
3689 if (!$menu->has_children()) {
3690 return '';
3692 // Increment the menu count. This is used for ID's that get worked with
3693 // in JavaScript as is essential
3694 $menucount++;
3695 // Initialise this custom menu (the custom menu object is contained in javascript-static
3696 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
3697 $jscode = "(function(){{$jscode}})";
3698 $this->page->requires->yui_module('node-menunav', $jscode);
3699 // Build the root nodes as required by YUI
3700 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
3701 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3702 $content .= html_writer::start_tag('ul');
3703 // Render each child
3704 foreach ($menu->get_children() as $item) {
3705 $content .= $this->render_custom_menu_item($item);
3707 // Close the open tags
3708 $content .= html_writer::end_tag('ul');
3709 $content .= html_writer::end_tag('div');
3710 $content .= html_writer::end_tag('div');
3711 // Return the custom menu
3712 return $content;
3716 * Renders a custom menu node as part of a submenu
3718 * The custom menu this method produces makes use of the YUI3 menunav widget
3719 * and requires very specific html elements and classes.
3721 * @see core:renderer::render_custom_menu()
3723 * @staticvar int $submenucount
3724 * @param custom_menu_item $menunode
3725 * @return string
3727 protected function render_custom_menu_item(custom_menu_item $menunode) {
3728 // Required to ensure we get unique trackable id's
3729 static $submenucount = 0;
3730 if ($menunode->has_children()) {
3731 // If the child has menus render it as a sub menu
3732 $submenucount++;
3733 $content = html_writer::start_tag('li');
3734 if ($menunode->get_url() !== null) {
3735 $url = $menunode->get_url();
3736 } else {
3737 $url = '#cm_submenu_'.$submenucount;
3739 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3740 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3741 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3742 $content .= html_writer::start_tag('ul');
3743 foreach ($menunode->get_children() as $menunode) {
3744 $content .= $this->render_custom_menu_item($menunode);
3746 $content .= html_writer::end_tag('ul');
3747 $content .= html_writer::end_tag('div');
3748 $content .= html_writer::end_tag('div');
3749 $content .= html_writer::end_tag('li');
3750 } else {
3751 // The node doesn't have children so produce a final menuitem.
3752 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3753 $content = '';
3754 if (preg_match("/^#+$/", $menunode->get_text())) {
3756 // This is a divider.
3757 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3758 } else {
3759 $content = html_writer::start_tag(
3760 'li',
3761 array(
3762 'class' => 'yui3-menuitem'
3765 if ($menunode->get_url() !== null) {
3766 $url = $menunode->get_url();
3767 } else {
3768 $url = '#';
3770 $content .= html_writer::link(
3771 $url,
3772 $menunode->get_text(),
3773 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3776 $content .= html_writer::end_tag('li');
3778 // Return the sub menu
3779 return $content;
3783 * Renders theme links for switching between default and other themes.
3785 * @return string
3787 protected function theme_switch_links() {
3789 $actualdevice = core_useragent::get_device_type();
3790 $currentdevice = $this->page->devicetypeinuse;
3791 $switched = ($actualdevice != $currentdevice);
3793 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3794 // The user is using the a default device and hasn't switched so don't shown the switch
3795 // device links.
3796 return '';
3799 if ($switched) {
3800 $linktext = get_string('switchdevicerecommended');
3801 $devicetype = $actualdevice;
3802 } else {
3803 $linktext = get_string('switchdevicedefault');
3804 $devicetype = 'default';
3806 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3808 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3809 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3810 $content .= html_writer::end_tag('div');
3812 return $content;
3816 * Renders tabs
3818 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3820 * Theme developers: In order to change how tabs are displayed please override functions
3821 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3823 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3824 * @param string|null $selected which tab to mark as selected, all parent tabs will
3825 * automatically be marked as activated
3826 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3827 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3828 * @return string
3830 public final function tabtree($tabs, $selected = null, $inactive = null) {
3831 return $this->render(new tabtree($tabs, $selected, $inactive));
3835 * Renders tabtree
3837 * @param tabtree $tabtree
3838 * @return string
3840 protected function render_tabtree(tabtree $tabtree) {
3841 if (empty($tabtree->subtree)) {
3842 return '';
3844 $str = '';
3845 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
3846 $str .= $this->render_tabobject($tabtree);
3847 $str .= html_writer::end_tag('div').
3848 html_writer::tag('div', ' ', array('class' => 'clearer'));
3849 return $str;
3853 * Renders tabobject (part of tabtree)
3855 * This function is called from {@link core_renderer::render_tabtree()}
3856 * and also it calls itself when printing the $tabobject subtree recursively.
3858 * Property $tabobject->level indicates the number of row of tabs.
3860 * @param tabobject $tabobject
3861 * @return string HTML fragment
3863 protected function render_tabobject(tabobject $tabobject) {
3864 $str = '';
3866 // Print name of the current tab.
3867 if ($tabobject instanceof tabtree) {
3868 // No name for tabtree root.
3869 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3870 // Tab name without a link. The <a> tag is used for styling.
3871 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3872 } else {
3873 // Tab name with a link.
3874 if (!($tabobject->link instanceof moodle_url)) {
3875 // backward compartibility when link was passed as quoted string
3876 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3877 } else {
3878 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3882 if (empty($tabobject->subtree)) {
3883 if ($tabobject->selected) {
3884 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3886 return $str;
3889 // Print subtree.
3890 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
3891 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3892 $cnt = 0;
3893 foreach ($tabobject->subtree as $tab) {
3894 $liclass = '';
3895 if (!$cnt) {
3896 $liclass .= ' first';
3898 if ($cnt == count($tabobject->subtree) - 1) {
3899 $liclass .= ' last';
3901 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3902 $liclass .= ' onerow';
3905 if ($tab->selected) {
3906 $liclass .= ' here selected';
3907 } else if ($tab->activated) {
3908 $liclass .= ' here active';
3911 // This will recursively call function render_tabobject() for each item in subtree.
3912 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3913 $cnt++;
3915 $str .= html_writer::end_tag('ul');
3918 return $str;
3922 * Get the HTML for blocks in the given region.
3924 * @since Moodle 2.5.1 2.6
3925 * @param string $region The region to get HTML for.
3926 * @return string HTML.
3928 public function blocks($region, $classes = array(), $tag = 'aside') {
3929 $displayregion = $this->page->apply_theme_region_manipulations($region);
3930 $classes = (array)$classes;
3931 $classes[] = 'block-region';
3932 $attributes = array(
3933 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3934 'class' => join(' ', $classes),
3935 'data-blockregion' => $displayregion,
3936 'data-droptarget' => '1'
3938 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3939 $content = $this->blocks_for_region($displayregion);
3940 } else {
3941 $content = '';
3943 return html_writer::tag($tag, $content, $attributes);
3947 * Renders a custom block region.
3949 * Use this method if you want to add an additional block region to the content of the page.
3950 * Please note this should only be used in special situations.
3951 * We want to leave the theme is control where ever possible!
3953 * This method must use the same method that the theme uses within its layout file.
3954 * As such it asks the theme what method it is using.
3955 * It can be one of two values, blocks or blocks_for_region (deprecated).
3957 * @param string $regionname The name of the custom region to add.
3958 * @return string HTML for the block region.
3960 public function custom_block_region($regionname) {
3961 if ($this->page->theme->get_block_render_method() === 'blocks') {
3962 return $this->blocks($regionname);
3963 } else {
3964 return $this->blocks_for_region($regionname);
3969 * Returns the CSS classes to apply to the body tag.
3971 * @since Moodle 2.5.1 2.6
3972 * @param array $additionalclasses Any additional classes to apply.
3973 * @return string
3975 public function body_css_classes(array $additionalclasses = array()) {
3976 // Add a class for each block region on the page.
3977 // We use the block manager here because the theme object makes get_string calls.
3978 $usedregions = array();
3979 foreach ($this->page->blocks->get_regions() as $region) {
3980 $additionalclasses[] = 'has-region-'.$region;
3981 if ($this->page->blocks->region_has_content($region, $this)) {
3982 $additionalclasses[] = 'used-region-'.$region;
3983 $usedregions[] = $region;
3984 } else {
3985 $additionalclasses[] = 'empty-region-'.$region;
3987 if ($this->page->blocks->region_completely_docked($region, $this)) {
3988 $additionalclasses[] = 'docked-region-'.$region;
3991 if (!$usedregions) {
3992 // No regions means there is only content, add 'content-only' class.
3993 $additionalclasses[] = 'content-only';
3994 } else if (count($usedregions) === 1) {
3995 // Add the -only class for the only used region.
3996 $region = array_shift($usedregions);
3997 $additionalclasses[] = $region . '-only';
3999 foreach ($this->page->layout_options as $option => $value) {
4000 if ($value) {
4001 $additionalclasses[] = 'layout-option-'.$option;
4004 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
4005 return $css;
4009 * The ID attribute to apply to the body tag.
4011 * @since Moodle 2.5.1 2.6
4012 * @return string
4014 public function body_id() {
4015 return $this->page->bodyid;
4019 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4021 * @since Moodle 2.5.1 2.6
4022 * @param string|array $additionalclasses Any additional classes to give the body tag,
4023 * @return string
4025 public function body_attributes($additionalclasses = array()) {
4026 if (!is_array($additionalclasses)) {
4027 $additionalclasses = explode(' ', $additionalclasses);
4029 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4033 * Gets HTML for the page heading.
4035 * @since Moodle 2.5.1 2.6
4036 * @param string $tag The tag to encase the heading in. h1 by default.
4037 * @return string HTML.
4039 public function page_heading($tag = 'h1') {
4040 return html_writer::tag($tag, $this->page->heading);
4044 * Gets the HTML for the page heading button.
4046 * @since Moodle 2.5.1 2.6
4047 * @return string HTML.
4049 public function page_heading_button() {
4050 return $this->page->button;
4054 * Returns the Moodle docs link to use for this page.
4056 * @since Moodle 2.5.1 2.6
4057 * @param string $text
4058 * @return string
4060 public function page_doc_link($text = null) {
4061 if ($text === null) {
4062 $text = get_string('moodledocslink');
4064 $path = page_get_doc_link_path($this->page);
4065 if (!$path) {
4066 return '';
4068 return $this->doc_link($path, $text);
4072 * Returns the page heading menu.
4074 * @since Moodle 2.5.1 2.6
4075 * @return string HTML.
4077 public function page_heading_menu() {
4078 return $this->page->headingmenu;
4082 * Returns the title to use on the page.
4084 * @since Moodle 2.5.1 2.6
4085 * @return string
4087 public function page_title() {
4088 return $this->page->title;
4092 * Returns the URL for the favicon.
4094 * @since Moodle 2.5.1 2.6
4095 * @return string The favicon URL
4097 public function favicon() {
4098 return $this->image_url('favicon', 'theme');
4102 * Renders preferences groups.
4104 * @param preferences_groups $renderable The renderable
4105 * @return string The output.
4107 public function render_preferences_groups(preferences_groups $renderable) {
4108 $html = '';
4109 $html .= html_writer::start_div('row-fluid');
4110 $html .= html_writer::start_tag('div', array('class' => 'span12 preferences-groups'));
4111 $i = 0;
4112 $open = false;
4113 foreach ($renderable->groups as $group) {
4114 if ($i == 0 || $i % 3 == 0) {
4115 if ($open) {
4116 $html .= html_writer::end_tag('div');
4118 $html .= html_writer::start_tag('div', array('class' => 'row-fluid'));
4119 $open = true;
4121 $html .= $this->render($group);
4122 $i++;
4125 $html .= html_writer::end_tag('div');
4127 $html .= html_writer::end_tag('ul');
4128 $html .= html_writer::end_tag('div');
4129 $html .= html_writer::end_div();
4130 return $html;
4134 * Renders preferences group.
4136 * @param preferences_group $renderable The renderable
4137 * @return string The output.
4139 public function render_preferences_group(preferences_group $renderable) {
4140 $html = '';
4141 $html .= html_writer::start_tag('div', array('class' => 'span4 preferences-group'));
4142 $html .= $this->heading($renderable->title, 3);
4143 $html .= html_writer::start_tag('ul');
4144 foreach ($renderable->nodes as $node) {
4145 if ($node->has_children()) {
4146 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4148 $html .= html_writer::tag('li', $this->render($node));
4150 $html .= html_writer::end_tag('ul');
4151 $html .= html_writer::end_tag('div');
4152 return $html;
4155 public function context_header($headerinfo = null, $headinglevel = 1) {
4156 global $DB, $USER, $CFG;
4157 require_once($CFG->dirroot . '/user/lib.php');
4158 $context = $this->page->context;
4159 $heading = null;
4160 $imagedata = null;
4161 $subheader = null;
4162 $userbuttons = null;
4163 // Make sure to use the heading if it has been set.
4164 if (isset($headerinfo['heading'])) {
4165 $heading = $headerinfo['heading'];
4167 // The user context currently has images and buttons. Other contexts may follow.
4168 if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
4169 if (isset($headerinfo['user'])) {
4170 $user = $headerinfo['user'];
4171 } else {
4172 // Look up the user information if it is not supplied.
4173 $user = $DB->get_record('user', array('id' => $context->instanceid));
4176 // If the user context is set, then use that for capability checks.
4177 if (isset($headerinfo['usercontext'])) {
4178 $context = $headerinfo['usercontext'];
4181 // Only provide user information if the user is the current user, or a user which the current user can view.
4182 // When checking user_can_view_profile(), either:
4183 // If the page context is course, check the course context (from the page object) or;
4184 // If page context is NOT course, then check across all courses.
4185 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4187 if (user_can_view_profile($user, $course)) {
4188 // Use the user's full name if the heading isn't set.
4189 if (!isset($heading)) {
4190 $heading = fullname($user);
4193 $imagedata = $this->user_picture($user, array('size' => 100));
4195 // Check to see if we should be displaying a message button.
4196 if (!empty($CFG->messaging) && $USER->id != $user->id && has_capability('moodle/site:sendmessage', $context)) {
4197 $iscontact = !empty(message_get_contact($user->id));
4198 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4199 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4200 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4201 $userbuttons = array(
4202 'messages' => array(
4203 'buttontype' => 'message',
4204 'title' => get_string('message', 'message'),
4205 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4206 'image' => 'message',
4207 'linkattributes' => array('role' => 'button'),
4208 'page' => $this->page
4210 'togglecontact' => array(
4211 'buttontype' => 'togglecontact',
4212 'title' => get_string($contacttitle, 'message'),
4213 'url' => new moodle_url('/message/index.php', array(
4214 'user1' => $USER->id,
4215 'user2' => $user->id,
4216 $contacturlaction => $user->id,
4217 'sesskey' => sesskey())
4219 'image' => $contactimage,
4220 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4221 'page' => $this->page
4225 $this->page->requires->string_for_js('changesmadereallygoaway', 'moodle');
4227 } else {
4228 $heading = null;
4232 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4233 return $this->render_context_header($contextheader);
4237 * Renders the skip links for the page.
4239 * @param array $links List of skip links.
4240 * @return string HTML for the skip links.
4242 public function render_skip_links($links) {
4243 $context = [ 'links' => []];
4245 foreach ($links as $url => $text) {
4246 $context['links'][] = [ 'url' => $url, 'text' => $text];
4249 return $this->render_from_template('core/skip_links', $context);
4253 * Renders the header bar.
4255 * @param context_header $contextheader Header bar object.
4256 * @return string HTML for the header bar.
4258 protected function render_context_header(context_header $contextheader) {
4260 // All the html stuff goes here.
4261 $html = html_writer::start_div('page-context-header');
4263 // Image data.
4264 if (isset($contextheader->imagedata)) {
4265 // Header specific image.
4266 $html .= html_writer::div($contextheader->imagedata, 'page-header-image');
4269 // Headings.
4270 if (!isset($contextheader->heading)) {
4271 $headings = $this->heading($this->page->heading, $contextheader->headinglevel);
4272 } else {
4273 $headings = $this->heading($contextheader->heading, $contextheader->headinglevel);
4276 $html .= html_writer::tag('div', $headings, array('class' => 'page-header-headings'));
4278 // Buttons.
4279 if (isset($contextheader->additionalbuttons)) {
4280 $html .= html_writer::start_div('btn-group header-button-group');
4281 foreach ($contextheader->additionalbuttons as $button) {
4282 if (!isset($button->page)) {
4283 // Include js for messaging.
4284 if ($button['buttontype'] === 'togglecontact') {
4285 \core_message\helper::togglecontact_requirejs();
4287 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4288 'class' => 'iconsmall',
4289 'role' => 'presentation'
4291 $image .= html_writer::span($button['title'], 'header-button-title');
4292 } else {
4293 $image = html_writer::empty_tag('img', array(
4294 'src' => $button['formattedimage'],
4295 'role' => 'presentation'
4298 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4300 $html .= html_writer::end_div();
4302 $html .= html_writer::end_div();
4304 return $html;
4308 * Wrapper for header elements.
4310 * @return string HTML to display the main header.
4312 public function full_header() {
4313 $html = html_writer::start_tag('header', array('id' => 'page-header', 'class' => 'clearfix'));
4314 $html .= $this->context_header();
4315 $html .= html_writer::start_div('clearfix', array('id' => 'page-navbar'));
4316 $html .= html_writer::tag('div', $this->navbar(), array('class' => 'breadcrumb-nav'));
4317 $html .= html_writer::div($this->page_heading_button(), 'breadcrumb-button');
4318 $html .= html_writer::end_div();
4319 $html .= html_writer::tag('div', $this->course_header(), array('id' => 'course-header'));
4320 $html .= html_writer::end_tag('header');
4321 return $html;
4325 * Displays the list of tags associated with an entry
4327 * @param array $tags list of instances of core_tag or stdClass
4328 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4329 * to use default, set to '' (empty string) to omit the label completely
4330 * @param string $classes additional classes for the enclosing div element
4331 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4332 * will be appended to the end, JS will toggle the rest of the tags
4333 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4334 * @return string
4336 public function tag_list($tags, $label = null, $classes = '', $limit = 10, $pagecontext = null) {
4337 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext);
4338 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4342 * Renders element for inline editing of any value
4344 * @param \core\output\inplace_editable $element
4345 * @return string
4347 public function render_inplace_editable(\core\output\inplace_editable $element) {
4348 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4352 * Renders a bar chart.
4354 * @param \core\chart_bar $chart The chart.
4355 * @return string.
4357 public function render_chart_bar(\core\chart_bar $chart) {
4358 return $this->render_chart($chart);
4362 * Renders a line chart.
4364 * @param \core\chart_line $chart The chart.
4365 * @return string.
4367 public function render_chart_line(\core\chart_line $chart) {
4368 return $this->render_chart($chart);
4372 * Renders a pie chart.
4374 * @param \core\chart_pie $chart The chart.
4375 * @return string.
4377 public function render_chart_pie(\core\chart_pie $chart) {
4378 return $this->render_chart($chart);
4382 * Renders a chart.
4384 * @param \core\chart_base $chart The chart.
4385 * @param bool $withtable Whether to include a data table with the chart.
4386 * @return string.
4388 public function render_chart(\core\chart_base $chart, $withtable = true) {
4389 $chartdata = json_encode($chart);
4390 return $this->render_from_template('core/chart', (object) [
4391 'chartdata' => $chartdata,
4392 'withtable' => $withtable
4397 * Renders the login form.
4399 * @param \core_auth\output\login $form The renderable.
4400 * @return string
4402 public function render_login(\core_auth\output\login $form) {
4403 $context = $form->export_for_template($this);
4405 // Override because rendering is not supported in template yet.
4406 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
4407 $context->errorformatted = $this->error_text($context->error);
4409 return $this->render_from_template('core/loginform', $context);
4413 * Renders an mform element from a template.
4415 * @param HTML_QuickForm_element $element element
4416 * @param bool $required if input is required field
4417 * @param bool $advanced if input is an advanced field
4418 * @param string $error error message to display
4419 * @param bool $ingroup True if this element is rendered as part of a group
4420 * @return mixed string|bool
4422 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4423 $templatename = 'core_form/element-' . $element->getType();
4424 if ($ingroup) {
4425 $templatename .= "-inline";
4427 try {
4428 // We call this to generate a file not found exception if there is no template.
4429 // We don't want to call export_for_template if there is no template.
4430 core\output\mustache_template_finder::get_template_filepath($templatename);
4432 if ($element instanceof templatable) {
4433 $elementcontext = $element->export_for_template($this);
4435 $helpbutton = '';
4436 if (method_exists($element, 'getHelpButton')) {
4437 $helpbutton = $element->getHelpButton();
4439 $label = $element->getLabel();
4440 $text = '';
4441 if (method_exists($element, 'getText')) {
4442 // There currently exists code that adds a form element with an empty label.
4443 // If this is the case then set the label to the description.
4444 if (empty($label)) {
4445 $label = $element->getText();
4446 } else {
4447 $text = $element->getText();
4451 $context = array(
4452 'element' => $elementcontext,
4453 'label' => $label,
4454 'text' => $text,
4455 'required' => $required,
4456 'advanced' => $advanced,
4457 'helpbutton' => $helpbutton,
4458 'error' => $error
4460 return $this->render_from_template($templatename, $context);
4462 } catch (Exception $e) {
4463 // No template for this element.
4464 return false;
4469 * Render the login signup form into a nice template for the theme.
4471 * @param mform $form
4472 * @return string
4474 public function render_login_signup_form($form) {
4475 $context = $form->export_for_template($this);
4477 return $this->render_from_template('core/signup_form_layout', $context);
4481 * Render the verify age and location page into a nice template for the theme.
4483 * @param \core_auth\output\verify_age_location_page $page The renderable
4484 * @return string
4486 protected function render_verify_age_location_page($page) {
4487 $context = $page->export_for_template($this);
4489 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4493 * Render the digital minor contact information page into a nice template for the theme.
4495 * @param \core_auth\output\digital_minor_page $page The renderable
4496 * @return string
4498 protected function render_digital_minor_page($page) {
4499 $context = $page->export_for_template($this);
4501 return $this->render_from_template('core/auth_digital_minor_page', $context);
4505 * Renders a progress bar.
4507 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4509 * @param progress_bar $bar The bar.
4510 * @return string HTML fragment
4512 public function render_progress_bar(progress_bar $bar) {
4513 global $PAGE;
4514 $data = $bar->export_for_template($this);
4515 return $this->render_from_template('core/progress_bar', $data);
4520 * A renderer that generates output for command-line scripts.
4522 * The implementation of this renderer is probably incomplete.
4524 * @copyright 2009 Tim Hunt
4525 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4526 * @since Moodle 2.0
4527 * @package core
4528 * @category output
4530 class core_renderer_cli extends core_renderer {
4533 * Returns the page header.
4535 * @return string HTML fragment
4537 public function header() {
4538 return $this->page->heading . "\n";
4542 * Returns a template fragment representing a Heading.
4544 * @param string $text The text of the heading
4545 * @param int $level The level of importance of the heading
4546 * @param string $classes A space-separated list of CSS classes
4547 * @param string $id An optional ID
4548 * @return string A template fragment for a heading
4550 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4551 $text .= "\n";
4552 switch ($level) {
4553 case 1:
4554 return '=>' . $text;
4555 case 2:
4556 return '-->' . $text;
4557 default:
4558 return $text;
4563 * Returns a template fragment representing a fatal error.
4565 * @param string $message The message to output
4566 * @param string $moreinfourl URL where more info can be found about the error
4567 * @param string $link Link for the Continue button
4568 * @param array $backtrace The execution backtrace
4569 * @param string $debuginfo Debugging information
4570 * @return string A template fragment for a fatal error
4572 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4573 global $CFG;
4575 $output = "!!! $message !!!\n";
4577 if ($CFG->debugdeveloper) {
4578 if (!empty($debuginfo)) {
4579 $output .= $this->notification($debuginfo, 'notifytiny');
4581 if (!empty($backtrace)) {
4582 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
4586 return $output;
4590 * Returns a template fragment representing a notification.
4592 * @param string $message The message to print out.
4593 * @param string $type The type of notification. See constants on \core\output\notification.
4594 * @return string A template fragment for a notification
4596 public function notification($message, $type = null) {
4597 $message = clean_text($message);
4598 if ($type === 'notifysuccess' || $type === 'success') {
4599 return "++ $message ++\n";
4601 return "!! $message !!\n";
4605 * There is no footer for a cli request, however we must override the
4606 * footer method to prevent the default footer.
4608 public function footer() {}
4611 * Render a notification (that is, a status message about something that has
4612 * just happened).
4614 * @param \core\output\notification $notification the notification to print out
4615 * @return string plain text output
4617 public function render_notification(\core\output\notification $notification) {
4618 return $this->notification($notification->get_message(), $notification->get_message_type());
4624 * A renderer that generates output for ajax scripts.
4626 * This renderer prevents accidental sends back only json
4627 * encoded error messages, all other output is ignored.
4629 * @copyright 2010 Petr Skoda
4630 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4631 * @since Moodle 2.0
4632 * @package core
4633 * @category output
4635 class core_renderer_ajax extends core_renderer {
4638 * Returns a template fragment representing a fatal error.
4640 * @param string $message The message to output
4641 * @param string $moreinfourl URL where more info can be found about the error
4642 * @param string $link Link for the Continue button
4643 * @param array $backtrace The execution backtrace
4644 * @param string $debuginfo Debugging information
4645 * @return string A template fragment for a fatal error
4647 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4648 global $CFG;
4650 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
4652 $e = new stdClass();
4653 $e->error = $message;
4654 $e->errorcode = $errorcode;
4655 $e->stacktrace = NULL;
4656 $e->debuginfo = NULL;
4657 $e->reproductionlink = NULL;
4658 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
4659 $link = (string) $link;
4660 if ($link) {
4661 $e->reproductionlink = $link;
4663 if (!empty($debuginfo)) {
4664 $e->debuginfo = $debuginfo;
4666 if (!empty($backtrace)) {
4667 $e->stacktrace = format_backtrace($backtrace, true);
4670 $this->header();
4671 return json_encode($e);
4675 * Used to display a notification.
4676 * For the AJAX notifications are discarded.
4678 * @param string $message The message to print out.
4679 * @param string $type The type of notification. See constants on \core\output\notification.
4681 public function notification($message, $type = null) {}
4684 * Used to display a redirection message.
4685 * AJAX redirections should not occur and as such redirection messages
4686 * are discarded.
4688 * @param moodle_url|string $encodedurl
4689 * @param string $message
4690 * @param int $delay
4691 * @param bool $debugdisableredirect
4692 * @param string $messagetype The type of notification to show the message in.
4693 * See constants on \core\output\notification.
4695 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
4696 $messagetype = \core\output\notification::NOTIFY_INFO) {}
4699 * Prepares the start of an AJAX output.
4701 public function header() {
4702 // unfortunately YUI iframe upload does not support application/json
4703 if (!empty($_FILES)) {
4704 @header('Content-type: text/plain; charset=utf-8');
4705 if (!core_useragent::supports_json_contenttype()) {
4706 @header('X-Content-Type-Options: nosniff');
4708 } else if (!core_useragent::supports_json_contenttype()) {
4709 @header('Content-type: text/plain; charset=utf-8');
4710 @header('X-Content-Type-Options: nosniff');
4711 } else {
4712 @header('Content-type: application/json; charset=utf-8');
4715 // Headers to make it not cacheable and json
4716 @header('Cache-Control: no-store, no-cache, must-revalidate');
4717 @header('Cache-Control: post-check=0, pre-check=0', false);
4718 @header('Pragma: no-cache');
4719 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
4720 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
4721 @header('Accept-Ranges: none');
4725 * There is no footer for an AJAX request, however we must override the
4726 * footer method to prevent the default footer.
4728 public function footer() {}
4731 * No need for headers in an AJAX request... this should never happen.
4732 * @param string $text
4733 * @param int $level
4734 * @param string $classes
4735 * @param string $id
4737 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
4742 * Renderer for media files.
4744 * Used in file resources, media filter, and any other places that need to
4745 * output embedded media.
4747 * @deprecated since Moodle 3.2
4748 * @copyright 2011 The Open University
4749 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4751 class core_media_renderer extends plugin_renderer_base {
4752 /** @var array Array of available 'player' objects */
4753 private $players;
4754 /** @var string Regex pattern for links which may contain embeddable content */
4755 private $embeddablemarkers;
4758 * Constructor
4760 * This is needed in the constructor (not later) so that you can use the
4761 * constants and static functions that are defined in core_media class
4762 * before you call renderer functions.
4764 public function __construct() {
4765 debugging('Class core_media_renderer is deprecated, please use core_media_manager::instance()', DEBUG_DEVELOPER);
4769 * Renders a media file (audio or video) using suitable embedded player.
4771 * See embed_alternatives function for full description of parameters.
4772 * This function calls through to that one.
4774 * When using this function you can also specify width and height in the
4775 * URL by including ?d=100x100 at the end. If specified in the URL, this
4776 * will override the $width and $height parameters.
4778 * @param moodle_url $url Full URL of media file
4779 * @param string $name Optional user-readable name to display in download link
4780 * @param int $width Width in pixels (optional)
4781 * @param int $height Height in pixels (optional)
4782 * @param array $options Array of key/value pairs
4783 * @return string HTML content of embed
4785 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
4786 $options = array()) {
4787 return core_media_manager::instance()->embed_url($url, $name, $width, $height, $options);
4791 * Renders media files (audio or video) using suitable embedded player.
4792 * The list of URLs should be alternative versions of the same content in
4793 * multiple formats. If there is only one format it should have a single
4794 * entry.
4796 * If the media files are not in a supported format, this will give students
4797 * a download link to each format. The download link uses the filename
4798 * unless you supply the optional name parameter.
4800 * Width and height are optional. If specified, these are suggested sizes
4801 * and should be the exact values supplied by the user, if they come from
4802 * user input. These will be treated as relating to the size of the video
4803 * content, not including any player control bar.
4805 * For audio files, height will be ignored. For video files, a few formats
4806 * work if you specify only width, but in general if you specify width
4807 * you must specify height as well.
4809 * The $options array is passed through to the core_media_player classes
4810 * that render the object tag. The keys can contain values from
4811 * core_media::OPTION_xx.
4813 * @param array $alternatives Array of moodle_url to media files
4814 * @param string $name Optional user-readable name to display in download link
4815 * @param int $width Width in pixels (optional)
4816 * @param int $height Height in pixels (optional)
4817 * @param array $options Array of key/value pairs
4818 * @return string HTML content of embed
4820 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
4821 $options = array()) {
4822 return core_media_manager::instance()->embed_alternatives($alternatives, $name, $width, $height, $options);
4826 * Checks whether a file can be embedded. If this returns true you will get
4827 * an embedded player; if this returns false, you will just get a download
4828 * link.
4830 * This is a wrapper for can_embed_urls.
4832 * @param moodle_url $url URL of media file
4833 * @param array $options Options (same as when embedding)
4834 * @return bool True if file can be embedded
4836 public function can_embed_url(moodle_url $url, $options = array()) {
4837 return core_media_manager::instance()->can_embed_url($url, $options);
4841 * Checks whether a file can be embedded. If this returns true you will get
4842 * an embedded player; if this returns false, you will just get a download
4843 * link.
4845 * @param array $urls URL of media file and any alternatives (moodle_url)
4846 * @param array $options Options (same as when embedding)
4847 * @return bool True if file can be embedded
4849 public function can_embed_urls(array $urls, $options = array()) {
4850 return core_media_manager::instance()->can_embed_urls($urls, $options);
4854 * Obtains a list of markers that can be used in a regular expression when
4855 * searching for URLs that can be embedded by any player type.
4857 * This string is used to improve peformance of regex matching by ensuring
4858 * that the (presumably C) regex code can do a quick keyword check on the
4859 * URL part of a link to see if it matches one of these, rather than having
4860 * to go into PHP code for every single link to see if it can be embedded.
4862 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
4864 public function get_embeddable_markers() {
4865 return core_media_manager::instance()->get_embeddable_markers();
4870 * The maintenance renderer.
4872 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
4873 * is running a maintenance related task.
4874 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
4876 * @since Moodle 2.6
4877 * @package core
4878 * @category output
4879 * @copyright 2013 Sam Hemelryk
4880 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4882 class core_renderer_maintenance extends core_renderer {
4885 * Initialises the renderer instance.
4886 * @param moodle_page $page
4887 * @param string $target
4888 * @throws coding_exception
4890 public function __construct(moodle_page $page, $target) {
4891 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
4892 throw new coding_exception('Invalid request for the maintenance renderer.');
4894 parent::__construct($page, $target);
4898 * Does nothing. The maintenance renderer cannot produce blocks.
4900 * @param block_contents $bc
4901 * @param string $region
4902 * @return string
4904 public function block(block_contents $bc, $region) {
4905 // Computer says no blocks.
4906 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4907 return '';
4911 * Does nothing. The maintenance renderer cannot produce blocks.
4913 * @param string $region
4914 * @param array $classes
4915 * @param string $tag
4916 * @return string
4918 public function blocks($region, $classes = array(), $tag = 'aside') {
4919 // Computer says no blocks.
4920 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4921 return '';
4925 * Does nothing. The maintenance renderer cannot produce blocks.
4927 * @param string $region
4928 * @return string
4930 public function blocks_for_region($region) {
4931 // Computer says no blocks for region.
4932 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4933 return '';
4937 * Does nothing. The maintenance renderer cannot produce a course content header.
4939 * @param bool $onlyifnotcalledbefore
4940 * @return string
4942 public function course_content_header($onlyifnotcalledbefore = false) {
4943 // Computer says no course content header.
4944 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4945 return '';
4949 * Does nothing. The maintenance renderer cannot produce a course content footer.
4951 * @param bool $onlyifnotcalledbefore
4952 * @return string
4954 public function course_content_footer($onlyifnotcalledbefore = false) {
4955 // Computer says no course content footer.
4956 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4957 return '';
4961 * Does nothing. The maintenance renderer cannot produce a course header.
4963 * @return string
4965 public function course_header() {
4966 // Computer says no course header.
4967 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4968 return '';
4972 * Does nothing. The maintenance renderer cannot produce a course footer.
4974 * @return string
4976 public function course_footer() {
4977 // Computer says no course footer.
4978 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4979 return '';
4983 * Does nothing. The maintenance renderer cannot produce a custom menu.
4985 * @param string $custommenuitems
4986 * @return string
4988 public function custom_menu($custommenuitems = '') {
4989 // Computer says no custom menu.
4990 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4991 return '';
4995 * Does nothing. The maintenance renderer cannot produce a file picker.
4997 * @param array $options
4998 * @return string
5000 public function file_picker($options) {
5001 // Computer says no file picker.
5002 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5003 return '';
5007 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
5009 * @param array $dir
5010 * @return string
5012 public function htmllize_file_tree($dir) {
5013 // Hell no we don't want no htmllized file tree.
5014 // Also why on earth is this function on the core renderer???
5015 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5016 return '';
5021 * Overridden confirm message for upgrades.
5023 * @param string $message The question to ask the user
5024 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5025 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5026 * @return string HTML fragment
5028 public function confirm($message, $continue, $cancel) {
5029 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5030 // from any previous version of Moodle).
5031 if ($continue instanceof single_button) {
5032 $continue->primary = true;
5033 } else if (is_string($continue)) {
5034 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
5035 } else if ($continue instanceof moodle_url) {
5036 $continue = new single_button($continue, get_string('continue'), 'post', true);
5037 } else {
5038 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5039 ' (string/moodle_url) or a single_button instance.');
5042 if ($cancel instanceof single_button) {
5043 $output = '';
5044 } else if (is_string($cancel)) {
5045 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5046 } else if ($cancel instanceof moodle_url) {
5047 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5048 } else {
5049 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5050 ' (string/moodle_url) or a single_button instance.');
5053 $output = $this->box_start('generalbox', 'notice');
5054 $output .= html_writer::tag('h4', get_string('confirm'));
5055 $output .= html_writer::tag('p', $message);
5056 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
5057 $output .= $this->box_end();
5058 return $output;
5062 * Does nothing. The maintenance renderer does not support JS.
5064 * @param block_contents $bc
5066 public function init_block_hider_js(block_contents $bc) {
5067 // Computer says no JavaScript.
5068 // Do nothing, ridiculous method.
5072 * Does nothing. The maintenance renderer cannot produce language menus.
5074 * @return string
5076 public function lang_menu() {
5077 // Computer says no lang menu.
5078 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5079 return '';
5083 * Does nothing. The maintenance renderer has no need for login information.
5085 * @param null $withlinks
5086 * @return string
5088 public function login_info($withlinks = null) {
5089 // Computer says no login info.
5090 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5091 return '';
5095 * Does nothing. The maintenance renderer cannot produce user pictures.
5097 * @param stdClass $user
5098 * @param array $options
5099 * @return string
5101 public function user_picture(stdClass $user, array $options = null) {
5102 // Computer says no user pictures.
5103 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5104 return '';