Merge branch 'wip-MDL-62796-master' of git://github.com/marinaglancy/moodle
[moodle.git] / lib / outputrenderers.php
blob24330ac9593d8c07402934f3bc8656ff456bcfc2
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 $themename = $this->page->theme->name;
85 $themerev = theme_get_revision();
87 // Create new localcache directory.
88 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
90 // Remove old localcache directories.
91 $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR);
92 foreach ($mustachecachedirs as $localcachedir) {
93 $cachedrev = [];
94 preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
95 $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
96 if ($cachedrev > 0 && $cachedrev < $themerev) {
97 fulldelete($localcachedir);
101 $loader = new \core\output\mustache_filesystem_loader();
102 $stringhelper = new \core\output\mustache_string_helper();
103 $quotehelper = new \core\output\mustache_quote_helper();
104 $jshelper = new \core\output\mustache_javascript_helper($this->page);
105 $pixhelper = new \core\output\mustache_pix_helper($this);
106 $shortentexthelper = new \core\output\mustache_shorten_text_helper();
107 $userdatehelper = new \core\output\mustache_user_date_helper();
109 // We only expose the variables that are exposed to JS templates.
110 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
112 $helpers = array('config' => $safeconfig,
113 'str' => array($stringhelper, 'str'),
114 'quote' => array($quotehelper, 'quote'),
115 'js' => array($jshelper, 'help'),
116 'pix' => array($pixhelper, 'pix'),
117 'shortentext' => array($shortentexthelper, 'shorten'),
118 'userdate' => array($userdatehelper, 'transform'),
121 $this->mustache = new Mustache_Engine(array(
122 'cache' => $cachedir,
123 'escape' => 's',
124 'loader' => $loader,
125 'helpers' => $helpers,
126 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS]));
130 return $this->mustache;
135 * Constructor
137 * The constructor takes two arguments. The first is the page that the renderer
138 * has been created to assist with, and the second is the target.
139 * The target is an additional identifier that can be used to load different
140 * renderers for different options.
142 * @param moodle_page $page the page we are doing output for.
143 * @param string $target one of rendering target constants
145 public function __construct(moodle_page $page, $target) {
146 $this->opencontainers = $page->opencontainers;
147 $this->page = $page;
148 $this->target = $target;
152 * Renders a template by name with the given context.
154 * The provided data needs to be array/stdClass made up of only simple types.
155 * Simple types are array,stdClass,bool,int,float,string
157 * @since 2.9
158 * @param array|stdClass $context Context containing data for the template.
159 * @return string|boolean
161 public function render_from_template($templatename, $context) {
162 static $templatecache = array();
163 $mustache = $this->get_mustache();
165 try {
166 // Grab a copy of the existing helper to be restored later.
167 $uniqidhelper = $mustache->getHelper('uniqid');
168 } catch (Mustache_Exception_UnknownHelperException $e) {
169 // Helper doesn't exist.
170 $uniqidhelper = null;
173 // Provide 1 random value that will not change within a template
174 // but will be different from template to template. This is useful for
175 // e.g. aria attributes that only work with id attributes and must be
176 // unique in a page.
177 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
178 if (isset($templatecache[$templatename])) {
179 $template = $templatecache[$templatename];
180 } else {
181 try {
182 $template = $mustache->loadTemplate($templatename);
183 $templatecache[$templatename] = $template;
184 } catch (Mustache_Exception_UnknownTemplateException $e) {
185 throw new moodle_exception('Unknown template: ' . $templatename);
189 $renderedtemplate = trim($template->render($context));
191 // If we had an existing uniqid helper then we need to restore it to allow
192 // handle nested calls of render_from_template.
193 if ($uniqidhelper) {
194 $mustache->addHelper('uniqid', $uniqidhelper);
197 return $renderedtemplate;
202 * Returns rendered widget.
204 * The provided widget needs to be an object that extends the renderable
205 * interface.
206 * If will then be rendered by a method based upon the classname for the widget.
207 * For instance a widget of class `crazywidget` will be rendered by a protected
208 * render_crazywidget method of this renderer.
209 * If no render_crazywidget method exists and crazywidget implements templatable,
210 * look for the 'crazywidget' template in the same component and render that.
212 * @param renderable $widget instance with renderable interface
213 * @return string
215 public function render(renderable $widget) {
216 $classparts = explode('\\', get_class($widget));
217 // Strip namespaces.
218 $classname = array_pop($classparts);
219 // Remove _renderable suffixes
220 $classname = preg_replace('/_renderable$/', '', $classname);
222 $rendermethod = 'render_'.$classname;
223 if (method_exists($this, $rendermethod)) {
224 return $this->$rendermethod($widget);
226 if ($widget instanceof templatable) {
227 $component = array_shift($classparts);
228 if (!$component) {
229 $component = 'core';
231 $template = $component . '/' . $classname;
232 $context = $widget->export_for_template($this);
233 return $this->render_from_template($template, $context);
235 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
239 * Adds a JS action for the element with the provided id.
241 * This method adds a JS event for the provided component action to the page
242 * and then returns the id that the event has been attached to.
243 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
245 * @param component_action $action
246 * @param string $id
247 * @return string id of element, either original submitted or random new if not supplied
249 public function add_action_handler(component_action $action, $id = null) {
250 if (!$id) {
251 $id = html_writer::random_id($action->event);
253 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
254 return $id;
258 * Returns true is output has already started, and false if not.
260 * @return boolean true if the header has been printed.
262 public function has_started() {
263 return $this->page->state >= moodle_page::STATE_IN_BODY;
267 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
269 * @param mixed $classes Space-separated string or array of classes
270 * @return string HTML class attribute value
272 public static function prepare_classes($classes) {
273 if (is_array($classes)) {
274 return implode(' ', array_unique($classes));
276 return $classes;
280 * Return the direct URL for an image from the pix folder.
282 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
284 * @deprecated since Moodle 3.3
285 * @param string $imagename the name of the icon.
286 * @param string $component specification of one plugin like in get_string()
287 * @return moodle_url
289 public function pix_url($imagename, $component = 'moodle') {
290 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
291 return $this->page->theme->image_url($imagename, $component);
295 * Return the moodle_url for an image.
297 * The exact image location and extension is determined
298 * automatically by searching for gif|png|jpg|jpeg, please
299 * note there can not be diferent images with the different
300 * extension. The imagename is for historical reasons
301 * a relative path name, it may be changed later for core
302 * images. It is recommended to not use subdirectories
303 * in plugin and theme pix directories.
305 * There are three types of images:
306 * 1/ theme images - stored in theme/mytheme/pix/,
307 * use component 'theme'
308 * 2/ core images - stored in /pix/,
309 * overridden via theme/mytheme/pix_core/
310 * 3/ plugin images - stored in mod/mymodule/pix,
311 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
312 * example: image_url('comment', 'mod_glossary')
314 * @param string $imagename the pathname of the image
315 * @param string $component full plugin name (aka component) or 'theme'
316 * @return moodle_url
318 public function image_url($imagename, $component = 'moodle') {
319 return $this->page->theme->image_url($imagename, $component);
323 * Return the site's logo URL, if any.
325 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
326 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
327 * @return moodle_url|false
329 public function get_logo_url($maxwidth = null, $maxheight = 200) {
330 global $CFG;
331 $logo = get_config('core_admin', 'logo');
332 if (empty($logo)) {
333 return false;
336 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
337 // It's not worth the overhead of detecting and serving 2 different images based on the device.
339 // Hide the requested size in the file path.
340 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
342 // Use $CFG->themerev to prevent browser caching when the file changes.
343 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
344 theme_get_revision(), $logo);
348 * Return the site's compact logo URL, if any.
350 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
351 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
352 * @return moodle_url|false
354 public function get_compact_logo_url($maxwidth = 100, $maxheight = 100) {
355 global $CFG;
356 $logo = get_config('core_admin', 'logocompact');
357 if (empty($logo)) {
358 return false;
361 // Hide the requested size in the file path.
362 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
364 // Use $CFG->themerev to prevent browser caching when the file changes.
365 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
366 theme_get_revision(), $logo);
373 * Basis for all plugin renderers.
375 * @copyright Petr Skoda (skodak)
376 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
377 * @since Moodle 2.0
378 * @package core
379 * @category output
381 class plugin_renderer_base extends renderer_base {
384 * @var renderer_base|core_renderer A reference to the current renderer.
385 * The renderer provided here will be determined by the page but will in 90%
386 * of cases by the {@link core_renderer}
388 protected $output;
391 * Constructor method, calls the parent constructor
393 * @param moodle_page $page
394 * @param string $target one of rendering target constants
396 public function __construct(moodle_page $page, $target) {
397 if (empty($target) && $page->pagelayout === 'maintenance') {
398 // If the page is using the maintenance layout then we're going to force the target to maintenance.
399 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
400 // unavailable for this page layout.
401 $target = RENDERER_TARGET_MAINTENANCE;
403 $this->output = $page->get_renderer('core', null, $target);
404 parent::__construct($page, $target);
408 * Renders the provided widget and returns the HTML to display it.
410 * @param renderable $widget instance with renderable interface
411 * @return string
413 public function render(renderable $widget) {
414 $classname = get_class($widget);
415 // Strip namespaces.
416 $classname = preg_replace('/^.*\\\/', '', $classname);
417 // Keep a copy at this point, we may need to look for a deprecated method.
418 $deprecatedmethod = 'render_'.$classname;
419 // Remove _renderable suffixes
420 $classname = preg_replace('/_renderable$/', '', $classname);
422 $rendermethod = 'render_'.$classname;
423 if (method_exists($this, $rendermethod)) {
424 return $this->$rendermethod($widget);
426 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
427 // This is exactly where we don't want to be.
428 // If you have arrived here you have a renderable component within your plugin that has the name
429 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
430 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
431 // and the _renderable suffix now gets removed when looking for a render method.
432 // You need to change your renderers render_blah_renderable to render_blah.
433 // Until you do this it will not be possible for a theme to override the renderer to override your method.
434 // Please do it ASAP.
435 static $debugged = array();
436 if (!isset($debugged[$deprecatedmethod])) {
437 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
438 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
439 $debugged[$deprecatedmethod] = true;
441 return $this->$deprecatedmethod($widget);
443 // pass to core renderer if method not found here
444 return $this->output->render($widget);
448 * Magic method used to pass calls otherwise meant for the standard renderer
449 * to it to ensure we don't go causing unnecessary grief.
451 * @param string $method
452 * @param array $arguments
453 * @return mixed
455 public function __call($method, $arguments) {
456 if (method_exists('renderer_base', $method)) {
457 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
459 if (method_exists($this->output, $method)) {
460 return call_user_func_array(array($this->output, $method), $arguments);
461 } else {
462 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
469 * The standard implementation of the core_renderer interface.
471 * @copyright 2009 Tim Hunt
472 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
473 * @since Moodle 2.0
474 * @package core
475 * @category output
477 class core_renderer extends renderer_base {
479 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
480 * in layout files instead.
481 * @deprecated
482 * @var string used in {@link core_renderer::header()}.
484 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
487 * @var string Used to pass information from {@link core_renderer::doctype()} to
488 * {@link core_renderer::standard_head_html()}.
490 protected $contenttype;
493 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
494 * with {@link core_renderer::header()}.
496 protected $metarefreshtag = '';
499 * @var string Unique token for the closing HTML
501 protected $unique_end_html_token;
504 * @var string Unique token for performance information
506 protected $unique_performance_info_token;
509 * @var string Unique token for the main content.
511 protected $unique_main_content_token;
514 * Constructor
516 * @param moodle_page $page the page we are doing output for.
517 * @param string $target one of rendering target constants
519 public function __construct(moodle_page $page, $target) {
520 $this->opencontainers = $page->opencontainers;
521 $this->page = $page;
522 $this->target = $target;
524 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
525 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
526 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
530 * Get the DOCTYPE declaration that should be used with this page. Designed to
531 * be called in theme layout.php files.
533 * @return string the DOCTYPE declaration that should be used.
535 public function doctype() {
536 if ($this->page->theme->doctype === 'html5') {
537 $this->contenttype = 'text/html; charset=utf-8';
538 return "<!DOCTYPE html>\n";
540 } else if ($this->page->theme->doctype === 'xhtml5') {
541 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
542 return "<!DOCTYPE html>\n";
544 } else {
545 // legacy xhtml 1.0
546 $this->contenttype = 'text/html; charset=utf-8';
547 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
552 * The attributes that should be added to the <html> tag. Designed to
553 * be called in theme layout.php files.
555 * @return string HTML fragment.
557 public function htmlattributes() {
558 $return = get_html_lang(true);
559 $attributes = array();
560 if ($this->page->theme->doctype !== 'html5') {
561 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
564 // Give plugins an opportunity to add things like xml namespaces to the html element.
565 // This function should return an array of html attribute names => values.
566 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
567 foreach ($pluginswithfunction as $plugins) {
568 foreach ($plugins as $function) {
569 $newattrs = $function();
570 unset($newattrs['dir']);
571 unset($newattrs['lang']);
572 unset($newattrs['xmlns']);
573 unset($newattrs['xml:lang']);
574 $attributes += $newattrs;
578 foreach ($attributes as $key => $val) {
579 $val = s($val);
580 $return .= " $key=\"$val\"";
583 return $return;
587 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
588 * that should be included in the <head> tag. Designed to be called in theme
589 * layout.php files.
591 * @return string HTML fragment.
593 public function standard_head_html() {
594 global $CFG, $SESSION;
596 // Before we output any content, we need to ensure that certain
597 // page components are set up.
599 // Blocks must be set up early as they may require javascript which
600 // has to be included in the page header before output is created.
601 foreach ($this->page->blocks->get_regions() as $region) {
602 $this->page->blocks->ensure_content_created($region, $this);
605 $output = '';
607 // Give plugins an opportunity to add any head elements. The callback
608 // must always return a string containing valid html head content.
609 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
610 foreach ($pluginswithfunction as $plugins) {
611 foreach ($plugins as $function) {
612 $output .= $function();
616 // Allow a url_rewrite plugin to setup any dynamic head content.
617 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
618 $class = $CFG->urlrewriteclass;
619 $output .= $class::html_head_setup();
622 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
623 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
624 // This is only set by the {@link redirect()} method
625 $output .= $this->metarefreshtag;
627 // Check if a periodic refresh delay has been set and make sure we arn't
628 // already meta refreshing
629 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
630 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
633 // Set up help link popups for all links with the helptooltip class
634 $this->page->requires->js_init_call('M.util.help_popups.setup');
636 $focus = $this->page->focuscontrol;
637 if (!empty($focus)) {
638 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
639 // This is a horrifically bad way to handle focus but it is passed in
640 // through messy formslib::moodleform
641 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
642 } else if (strpos($focus, '.')!==false) {
643 // Old style of focus, bad way to do it
644 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);
645 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
646 } else {
647 // Focus element with given id
648 $this->page->requires->js_function_call('focuscontrol', array($focus));
652 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
653 // any other custom CSS can not be overridden via themes and is highly discouraged
654 $urls = $this->page->theme->css_urls($this->page);
655 foreach ($urls as $url) {
656 $this->page->requires->css_theme($url);
659 // Get the theme javascript head and footer
660 if ($jsurl = $this->page->theme->javascript_url(true)) {
661 $this->page->requires->js($jsurl, true);
663 if ($jsurl = $this->page->theme->javascript_url(false)) {
664 $this->page->requires->js($jsurl);
667 // Get any HTML from the page_requirements_manager.
668 $output .= $this->page->requires->get_head_code($this->page, $this);
670 // List alternate versions.
671 foreach ($this->page->alternateversions as $type => $alt) {
672 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
673 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
676 // Add noindex tag if relevant page and setting applied.
677 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
678 $loginpages = array('login-index', 'login-signup');
679 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
680 if (!isset($CFG->additionalhtmlhead)) {
681 $CFG->additionalhtmlhead = '';
683 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
686 if (!empty($CFG->additionalhtmlhead)) {
687 $output .= "\n".$CFG->additionalhtmlhead;
690 return $output;
694 * The standard tags (typically skip links) that should be output just inside
695 * the start of the <body> tag. Designed to be called in theme layout.php files.
697 * @return string HTML fragment.
699 public function standard_top_of_body_html() {
700 global $CFG;
701 $output = $this->page->requires->get_top_of_body_code($this);
702 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
703 $output .= "\n".$CFG->additionalhtmltopofbody;
706 // Give plugins an opportunity to inject extra html content. The callback
707 // must always return a string containing valid html.
708 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
709 foreach ($pluginswithfunction as $plugins) {
710 foreach ($plugins as $function) {
711 $output .= $function();
715 $output .= $this->maintenance_warning();
717 return $output;
721 * Scheduled maintenance warning message.
723 * Note: This is a nasty hack to display maintenance notice, this should be moved
724 * to some general notification area once we have it.
726 * @return string
728 public function maintenance_warning() {
729 global $CFG;
731 $output = '';
732 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
733 $timeleft = $CFG->maintenance_later - time();
734 // If timeleft less than 30 sec, set the class on block to error to highlight.
735 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
736 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-a-1 alert');
737 $a = new stdClass();
738 $a->hour = (int)($timeleft / 3600);
739 $a->min = (int)(($timeleft / 60) % 60);
740 $a->sec = (int)($timeleft % 60);
741 if ($a->hour > 0) {
742 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
743 } else {
744 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
747 $output .= $this->box_end();
748 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
749 array(array('timeleftinsec' => $timeleft)));
750 $this->page->requires->strings_for_js(
751 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
752 'admin');
754 return $output;
758 * The standard tags (typically performance information and validation links,
759 * if we are in developer debug mode) that should be output in the footer area
760 * of the page. Designed to be called in theme layout.php files.
762 * @return string HTML fragment.
764 public function standard_footer_html() {
765 global $CFG, $SCRIPT;
767 $output = '';
768 if (during_initial_install()) {
769 // Debugging info can not work before install is finished,
770 // in any case we do not want any links during installation!
771 return $output;
774 // Give plugins an opportunity to add any footer elements.
775 // The callback must always return a string containing valid html footer content.
776 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
777 foreach ($pluginswithfunction as $plugins) {
778 foreach ($plugins as $function) {
779 $output .= $function();
783 // This function is normally called from a layout.php file in {@link core_renderer::header()}
784 // but some of the content won't be known until later, so we return a placeholder
785 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
786 $output .= $this->unique_performance_info_token;
787 if ($this->page->devicetypeinuse == 'legacy') {
788 // The legacy theme is in use print the notification
789 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
792 // Get links to switch device types (only shown for users not on a default device)
793 $output .= $this->theme_switch_links();
795 if (!empty($CFG->debugpageinfo)) {
796 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
797 $this->page->debug_summary()) . '</div>';
799 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
800 // Add link to profiling report if necessary
801 if (function_exists('profiling_is_running') && profiling_is_running()) {
802 $txt = get_string('profiledscript', 'admin');
803 $title = get_string('profiledscriptview', 'admin');
804 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
805 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
806 $output .= '<div class="profilingfooter">' . $link . '</div>';
808 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
809 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
810 $output .= '<div class="purgecaches">' .
811 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
813 if (!empty($CFG->debugvalidators)) {
814 // 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
815 $output .= '<div class="validators"><ul class="list-unstyled m-l-1">
816 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
817 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
818 <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>
819 </ul></div>';
821 return $output;
825 * Returns standard main content placeholder.
826 * Designed to be called in theme layout.php files.
828 * @return string HTML fragment.
830 public function main_content() {
831 // This is here because it is the only place we can inject the "main" role over the entire main content area
832 // without requiring all theme's to manually do it, and without creating yet another thing people need to
833 // remember in the theme.
834 // This is an unfortunate hack. DO NO EVER add anything more here.
835 // DO NOT add classes.
836 // DO NOT add an id.
837 return '<div role="main">'.$this->unique_main_content_token.'</div>';
841 * Returns standard navigation between activities in a course.
843 * @return string the navigation HTML.
845 public function activity_navigation() {
846 // First we should check if we want to add navigation.
847 $context = $this->page->context;
848 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
849 || $context->contextlevel != CONTEXT_MODULE) {
850 return '';
853 // If the activity is in stealth mode, show no links.
854 if ($this->page->cm->is_stealth()) {
855 return '';
858 // Get a list of all the activities in the course.
859 $course = $this->page->cm->get_course();
860 $modules = get_fast_modinfo($course->id)->get_cms();
862 // Put the modules into an array in order by the position they are shown in the course.
863 $mods = [];
864 $activitylist = [];
865 foreach ($modules as $module) {
866 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
867 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
868 continue;
870 $mods[$module->id] = $module;
872 // No need to add the current module to the list for the activity dropdown menu.
873 if ($module->id == $this->page->cm->id) {
874 continue;
876 // Module name.
877 $modname = $module->get_formatted_name();
878 // Display the hidden text if necessary.
879 if (!$module->visible) {
880 $modname .= ' ' . get_string('hiddenwithbrackets');
882 // Module URL.
883 $linkurl = new moodle_url($module->url, array('forceview' => 1));
884 // Add module URL (as key) and name (as value) to the activity list array.
885 $activitylist[$linkurl->out(false)] = $modname;
888 $nummods = count($mods);
890 // If there is only one mod then do nothing.
891 if ($nummods == 1) {
892 return '';
895 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
896 $modids = array_keys($mods);
898 // Get the position in the array of the course module we are viewing.
899 $position = array_search($this->page->cm->id, $modids);
901 $prevmod = null;
902 $nextmod = null;
904 // Check if we have a previous mod to show.
905 if ($position > 0) {
906 $prevmod = $mods[$modids[$position - 1]];
909 // Check if we have a next mod to show.
910 if ($position < ($nummods - 1)) {
911 $nextmod = $mods[$modids[$position + 1]];
914 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
915 $renderer = $this->page->get_renderer('core', 'course');
916 return $renderer->render($activitynav);
920 * The standard tags (typically script tags that are not needed earlier) that
921 * should be output after everything else. Designed to be called in theme layout.php files.
923 * @return string HTML fragment.
925 public function standard_end_of_body_html() {
926 global $CFG;
928 // This function is normally called from a layout.php file in {@link core_renderer::header()}
929 // but some of the content won't be known until later, so we return a placeholder
930 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
931 $output = '';
932 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
933 $output .= "\n".$CFG->additionalhtmlfooter;
935 $output .= $this->unique_end_html_token;
936 return $output;
940 * Return the standard string that says whether you are logged in (and switched
941 * roles/logged in as another user).
942 * @param bool $withlinks if false, then don't include any links in the HTML produced.
943 * If not set, the default is the nologinlinks option from the theme config.php file,
944 * and if that is not set, then links are included.
945 * @return string HTML fragment.
947 public function login_info($withlinks = null) {
948 global $USER, $CFG, $DB, $SESSION;
950 if (during_initial_install()) {
951 return '';
954 if (is_null($withlinks)) {
955 $withlinks = empty($this->page->layout_options['nologinlinks']);
958 $course = $this->page->course;
959 if (\core\session\manager::is_loggedinas()) {
960 $realuser = \core\session\manager::get_realuser();
961 $fullname = fullname($realuser, true);
962 if ($withlinks) {
963 $loginastitle = get_string('loginas');
964 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
965 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
966 } else {
967 $realuserinfo = " [$fullname] ";
969 } else {
970 $realuserinfo = '';
973 $loginpage = $this->is_login_page();
974 $loginurl = get_login_url();
976 if (empty($course->id)) {
977 // $course->id is not defined during installation
978 return '';
979 } else if (isloggedin()) {
980 $context = context_course::instance($course->id);
982 $fullname = fullname($USER, true);
983 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
984 if ($withlinks) {
985 $linktitle = get_string('viewprofile');
986 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
987 } else {
988 $username = $fullname;
990 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
991 if ($withlinks) {
992 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
993 } else {
994 $username .= " from {$idprovider->name}";
997 if (isguestuser()) {
998 $loggedinas = $realuserinfo.get_string('loggedinasguest');
999 if (!$loginpage && $withlinks) {
1000 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1002 } else if (is_role_switched($course->id)) { // Has switched roles
1003 $rolename = '';
1004 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1005 $rolename = ': '.role_get_name($role, $context);
1007 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1008 if ($withlinks) {
1009 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1010 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1012 } else {
1013 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1014 if ($withlinks) {
1015 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1018 } else {
1019 $loggedinas = get_string('loggedinnot', 'moodle');
1020 if (!$loginpage && $withlinks) {
1021 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1025 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1027 if (isset($SESSION->justloggedin)) {
1028 unset($SESSION->justloggedin);
1029 if (!empty($CFG->displayloginfailures)) {
1030 if (!isguestuser()) {
1031 // Include this file only when required.
1032 require_once($CFG->dirroot . '/user/lib.php');
1033 if ($count = user_count_login_failures($USER)) {
1034 $loggedinas .= '<div class="loginfailures">';
1035 $a = new stdClass();
1036 $a->attempts = $count;
1037 $loggedinas .= get_string('failedloginattempts', '', $a);
1038 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1039 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1040 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1042 $loggedinas .= '</div>';
1048 return $loggedinas;
1052 * Check whether the current page is a login page.
1054 * @since Moodle 2.9
1055 * @return bool
1057 protected function is_login_page() {
1058 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1059 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1060 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1061 return in_array(
1062 $this->page->url->out_as_local_url(false, array()),
1063 array(
1064 '/login/index.php',
1065 '/login/forgot_password.php',
1071 * Return the 'back' link that normally appears in the footer.
1073 * @return string HTML fragment.
1075 public function home_link() {
1076 global $CFG, $SITE;
1078 if ($this->page->pagetype == 'site-index') {
1079 // Special case for site home page - please do not remove
1080 return '<div class="sitelink">' .
1081 '<a title="Moodle" href="http://moodle.org/">' .
1082 '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1084 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1085 // Special case for during install/upgrade.
1086 return '<div class="sitelink">'.
1087 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1088 '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1090 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1091 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1092 get_string('home') . '</a></div>';
1094 } else {
1095 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1096 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1101 * Redirects the user by any means possible given the current state
1103 * This function should not be called directly, it should always be called using
1104 * the redirect function in lib/weblib.php
1106 * The redirect function should really only be called before page output has started
1107 * however it will allow itself to be called during the state STATE_IN_BODY
1109 * @param string $encodedurl The URL to send to encoded if required
1110 * @param string $message The message to display to the user if any
1111 * @param int $delay The delay before redirecting a user, if $message has been
1112 * set this is a requirement and defaults to 3, set to 0 no delay
1113 * @param boolean $debugdisableredirect this redirect has been disabled for
1114 * debugging purposes. Display a message that explains, and don't
1115 * trigger the redirect.
1116 * @param string $messagetype The type of notification to show the message in.
1117 * See constants on \core\output\notification.
1118 * @return string The HTML to display to the user before dying, may contain
1119 * meta refresh, javascript refresh, and may have set header redirects
1121 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1122 $messagetype = \core\output\notification::NOTIFY_INFO) {
1123 global $CFG;
1124 $url = str_replace('&amp;', '&', $encodedurl);
1126 switch ($this->page->state) {
1127 case moodle_page::STATE_BEFORE_HEADER :
1128 // No output yet it is safe to delivery the full arsenal of redirect methods
1129 if (!$debugdisableredirect) {
1130 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1131 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1132 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1134 $output = $this->header();
1135 break;
1136 case moodle_page::STATE_PRINTING_HEADER :
1137 // We should hopefully never get here
1138 throw new coding_exception('You cannot redirect while printing the page header');
1139 break;
1140 case moodle_page::STATE_IN_BODY :
1141 // We really shouldn't be here but we can deal with this
1142 debugging("You should really redirect before you start page output");
1143 if (!$debugdisableredirect) {
1144 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1146 $output = $this->opencontainers->pop_all_but_last();
1147 break;
1148 case moodle_page::STATE_DONE :
1149 // Too late to be calling redirect now
1150 throw new coding_exception('You cannot redirect after the entire page has been generated');
1151 break;
1153 $output .= $this->notification($message, $messagetype);
1154 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1155 if ($debugdisableredirect) {
1156 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1158 $output .= $this->footer();
1159 return $output;
1163 * Start output by sending the HTTP headers, and printing the HTML <head>
1164 * and the start of the <body>.
1166 * To control what is printed, you should set properties on $PAGE. If you
1167 * are familiar with the old {@link print_header()} function from Moodle 1.9
1168 * you will find that there are properties on $PAGE that correspond to most
1169 * of the old parameters to could be passed to print_header.
1171 * Not that, in due course, the remaining $navigation, $menu parameters here
1172 * will be replaced by more properties of $PAGE, but that is still to do.
1174 * @return string HTML that you must output this, preferably immediately.
1176 public function header() {
1177 global $USER, $CFG, $SESSION;
1179 // Give plugins an opportunity touch things before the http headers are sent
1180 // such as adding additional headers. The return value is ignored.
1181 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1182 foreach ($pluginswithfunction as $plugins) {
1183 foreach ($plugins as $function) {
1184 $function();
1188 if (\core\session\manager::is_loggedinas()) {
1189 $this->page->add_body_class('userloggedinas');
1192 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1193 require_once($CFG->dirroot . '/user/lib.php');
1194 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1195 if ($count = user_count_login_failures($USER, false)) {
1196 $this->page->add_body_class('loginfailures');
1200 // If the user is logged in, and we're not in initial install,
1201 // check to see if the user is role-switched and add the appropriate
1202 // CSS class to the body element.
1203 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1204 $this->page->add_body_class('userswitchedrole');
1207 // Give themes a chance to init/alter the page object.
1208 $this->page->theme->init_page($this->page);
1210 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1212 // Find the appropriate page layout file, based on $this->page->pagelayout.
1213 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1214 // Render the layout using the layout file.
1215 $rendered = $this->render_page_layout($layoutfile);
1217 // Slice the rendered output into header and footer.
1218 $cutpos = strpos($rendered, $this->unique_main_content_token);
1219 if ($cutpos === false) {
1220 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1221 $token = self::MAIN_CONTENT_TOKEN;
1222 } else {
1223 $token = $this->unique_main_content_token;
1226 if ($cutpos === false) {
1227 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.');
1229 $header = substr($rendered, 0, $cutpos);
1230 $footer = substr($rendered, $cutpos + strlen($token));
1232 if (empty($this->contenttype)) {
1233 debugging('The page layout file did not call $OUTPUT->doctype()');
1234 $header = $this->doctype() . $header;
1237 // If this theme version is below 2.4 release and this is a course view page
1238 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1239 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1240 // check if course content header/footer have not been output during render of theme layout
1241 $coursecontentheader = $this->course_content_header(true);
1242 $coursecontentfooter = $this->course_content_footer(true);
1243 if (!empty($coursecontentheader)) {
1244 // display debug message and add header and footer right above and below main content
1245 // Please note that course header and footer (to be displayed above and below the whole page)
1246 // are not displayed in this case at all.
1247 // Besides the content header and footer are not displayed on any other course page
1248 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);
1249 $header .= $coursecontentheader;
1250 $footer = $coursecontentfooter. $footer;
1254 send_headers($this->contenttype, $this->page->cacheable);
1256 $this->opencontainers->push('header/footer', $footer);
1257 $this->page->set_state(moodle_page::STATE_IN_BODY);
1259 return $header . $this->skip_link_target('maincontent');
1263 * Renders and outputs the page layout file.
1265 * This is done by preparing the normal globals available to a script, and
1266 * then including the layout file provided by the current theme for the
1267 * requested layout.
1269 * @param string $layoutfile The name of the layout file
1270 * @return string HTML code
1272 protected function render_page_layout($layoutfile) {
1273 global $CFG, $SITE, $USER;
1274 // The next lines are a bit tricky. The point is, here we are in a method
1275 // of a renderer class, and this object may, or may not, be the same as
1276 // the global $OUTPUT object. When rendering the page layout file, we want to use
1277 // this object. However, people writing Moodle code expect the current
1278 // renderer to be called $OUTPUT, not $this, so define a variable called
1279 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1280 $OUTPUT = $this;
1281 $PAGE = $this->page;
1282 $COURSE = $this->page->course;
1284 ob_start();
1285 include($layoutfile);
1286 $rendered = ob_get_contents();
1287 ob_end_clean();
1288 return $rendered;
1292 * Outputs the page's footer
1294 * @return string HTML fragment
1296 public function footer() {
1297 global $CFG, $DB, $PAGE;
1299 // Give plugins an opportunity to touch the page before JS is finalized.
1300 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1301 foreach ($pluginswithfunction as $plugins) {
1302 foreach ($plugins as $function) {
1303 $function();
1307 $output = $this->container_end_all(true);
1309 $footer = $this->opencontainers->pop('header/footer');
1311 if (debugging() and $DB and $DB->is_transaction_started()) {
1312 // TODO: MDL-20625 print warning - transaction will be rolled back
1315 // Provide some performance info if required
1316 $performanceinfo = '';
1317 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1318 $perf = get_performance_info();
1319 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1320 $performanceinfo = $perf['html'];
1324 // We always want performance data when running a performance test, even if the user is redirected to another page.
1325 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1326 $footer = $this->unique_performance_info_token . $footer;
1328 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1330 // Only show notifications when we have a $PAGE context id.
1331 if (!empty($PAGE->context->id)) {
1332 $this->page->requires->js_call_amd('core/notification', 'init', array(
1333 $PAGE->context->id,
1334 \core\notification::fetch_as_array($this)
1337 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1339 $this->page->set_state(moodle_page::STATE_DONE);
1341 return $output . $footer;
1345 * Close all but the last open container. This is useful in places like error
1346 * handling, where you want to close all the open containers (apart from <body>)
1347 * before outputting the error message.
1349 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1350 * developer debug warning if it isn't.
1351 * @return string the HTML required to close any open containers inside <body>.
1353 public function container_end_all($shouldbenone = false) {
1354 return $this->opencontainers->pop_all_but_last($shouldbenone);
1358 * Returns course-specific information to be output immediately above content on any course page
1359 * (for the current course)
1361 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1362 * @return string
1364 public function course_content_header($onlyifnotcalledbefore = false) {
1365 global $CFG;
1366 static $functioncalled = false;
1367 if ($functioncalled && $onlyifnotcalledbefore) {
1368 // we have already output the content header
1369 return '';
1372 // Output any session notification.
1373 $notifications = \core\notification::fetch();
1375 $bodynotifications = '';
1376 foreach ($notifications as $notification) {
1377 $bodynotifications .= $this->render_from_template(
1378 $notification->get_template_name(),
1379 $notification->export_for_template($this)
1383 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1385 if ($this->page->course->id == SITEID) {
1386 // return immediately and do not include /course/lib.php if not necessary
1387 return $output;
1390 require_once($CFG->dirroot.'/course/lib.php');
1391 $functioncalled = true;
1392 $courseformat = course_get_format($this->page->course);
1393 if (($obj = $courseformat->course_content_header()) !== null) {
1394 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1396 return $output;
1400 * Returns course-specific information to be output immediately below content on any course page
1401 * (for the current course)
1403 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1404 * @return string
1406 public function course_content_footer($onlyifnotcalledbefore = false) {
1407 global $CFG;
1408 if ($this->page->course->id == SITEID) {
1409 // return immediately and do not include /course/lib.php if not necessary
1410 return '';
1412 static $functioncalled = false;
1413 if ($functioncalled && $onlyifnotcalledbefore) {
1414 // we have already output the content footer
1415 return '';
1417 $functioncalled = true;
1418 require_once($CFG->dirroot.'/course/lib.php');
1419 $courseformat = course_get_format($this->page->course);
1420 if (($obj = $courseformat->course_content_footer()) !== null) {
1421 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1423 return '';
1427 * Returns course-specific information to be output on any course page in the header area
1428 * (for the current course)
1430 * @return string
1432 public function course_header() {
1433 global $CFG;
1434 if ($this->page->course->id == SITEID) {
1435 // return immediately and do not include /course/lib.php if not necessary
1436 return '';
1438 require_once($CFG->dirroot.'/course/lib.php');
1439 $courseformat = course_get_format($this->page->course);
1440 if (($obj = $courseformat->course_header()) !== null) {
1441 return $courseformat->get_renderer($this->page)->render($obj);
1443 return '';
1447 * Returns course-specific information to be output on any course page in the footer area
1448 * (for the current course)
1450 * @return string
1452 public function course_footer() {
1453 global $CFG;
1454 if ($this->page->course->id == SITEID) {
1455 // return immediately and do not include /course/lib.php if not necessary
1456 return '';
1458 require_once($CFG->dirroot.'/course/lib.php');
1459 $courseformat = course_get_format($this->page->course);
1460 if (($obj = $courseformat->course_footer()) !== null) {
1461 return $courseformat->get_renderer($this->page)->render($obj);
1463 return '';
1467 * Returns lang menu or '', this method also checks forcing of languages in courses.
1469 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1471 * @return string The lang menu HTML or empty string
1473 public function lang_menu() {
1474 global $CFG;
1476 if (empty($CFG->langmenu)) {
1477 return '';
1480 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1481 // do not show lang menu if language forced
1482 return '';
1485 $currlang = current_language();
1486 $langs = get_string_manager()->get_list_of_translations();
1488 if (count($langs) < 2) {
1489 return '';
1492 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1493 $s->label = get_accesshide(get_string('language'));
1494 $s->class = 'langmenu';
1495 return $this->render($s);
1499 * Output the row of editing icons for a block, as defined by the controls array.
1501 * @param array $controls an array like {@link block_contents::$controls}.
1502 * @param string $blockid The ID given to the block.
1503 * @return string HTML fragment.
1505 public function block_controls($actions, $blockid = null) {
1506 global $CFG;
1507 if (empty($actions)) {
1508 return '';
1510 $menu = new action_menu($actions);
1511 if ($blockid !== null) {
1512 $menu->set_owner_selector('#'.$blockid);
1514 $menu->set_constraint('.block-region');
1515 $menu->attributes['class'] .= ' block-control-actions commands';
1516 return $this->render($menu);
1520 * Renders an action menu component.
1522 * ARIA references:
1523 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1524 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1526 * @param action_menu $menu
1527 * @return string HTML
1529 public function render_action_menu(action_menu $menu) {
1530 $context = $menu->export_for_template($this);
1531 return $this->render_from_template('core/action_menu', $context);
1535 * Renders an action_menu_link item.
1537 * @param action_menu_link $action
1538 * @return string HTML fragment
1540 protected function render_action_menu_link(action_menu_link $action) {
1541 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1545 * Renders a primary action_menu_filler item.
1547 * @param action_menu_link_filler $action
1548 * @return string HTML fragment
1550 protected function render_action_menu_filler(action_menu_filler $action) {
1551 return html_writer::span('&nbsp;', 'filler');
1555 * Renders a primary action_menu_link item.
1557 * @param action_menu_link_primary $action
1558 * @return string HTML fragment
1560 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1561 return $this->render_action_menu_link($action);
1565 * Renders a secondary action_menu_link item.
1567 * @param action_menu_link_secondary $action
1568 * @return string HTML fragment
1570 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1571 return $this->render_action_menu_link($action);
1575 * Prints a nice side block with an optional header.
1577 * The content is described
1578 * by a {@link core_renderer::block_contents} object.
1580 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1581 * <div class="header"></div>
1582 * <div class="content">
1583 * ...CONTENT...
1584 * <div class="footer">
1585 * </div>
1586 * </div>
1587 * <div class="annotation">
1588 * </div>
1589 * </div>
1591 * @param block_contents $bc HTML for the content
1592 * @param string $region the region the block is appearing in.
1593 * @return string the HTML to be output.
1595 public function block(block_contents $bc, $region) {
1596 $bc = clone($bc); // Avoid messing up the object passed in.
1597 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1598 $bc->collapsible = block_contents::NOT_HIDEABLE;
1600 if (!empty($bc->blockinstanceid)) {
1601 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1603 $skiptitle = strip_tags($bc->title);
1604 if ($bc->blockinstanceid && !empty($skiptitle)) {
1605 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1606 } else if (!empty($bc->arialabel)) {
1607 $bc->attributes['aria-label'] = $bc->arialabel;
1609 if ($bc->dockable) {
1610 $bc->attributes['data-dockable'] = 1;
1612 if ($bc->collapsible == block_contents::HIDDEN) {
1613 $bc->add_class('hidden');
1615 if (!empty($bc->controls)) {
1616 $bc->add_class('block_with_controls');
1620 if (empty($skiptitle)) {
1621 $output = '';
1622 $skipdest = '';
1623 } else {
1624 $output = html_writer::link('#sb-'.$bc->skipid, get_string('skipa', 'access', $skiptitle),
1625 array('class' => 'skip skip-block', 'id' => 'fsb-' . $bc->skipid));
1626 $skipdest = html_writer::span('', 'skip-block-to',
1627 array('id' => 'sb-' . $bc->skipid));
1630 $output .= html_writer::start_tag('div', $bc->attributes);
1632 $output .= $this->block_header($bc);
1633 $output .= $this->block_content($bc);
1635 $output .= html_writer::end_tag('div');
1637 $output .= $this->block_annotation($bc);
1639 $output .= $skipdest;
1641 $this->init_block_hider_js($bc);
1642 return $output;
1646 * Produces a header for a block
1648 * @param block_contents $bc
1649 * @return string
1651 protected function block_header(block_contents $bc) {
1653 $title = '';
1654 if ($bc->title) {
1655 $attributes = array();
1656 if ($bc->blockinstanceid) {
1657 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1659 $title = html_writer::tag('h2', $bc->title, $attributes);
1662 $blockid = null;
1663 if (isset($bc->attributes['id'])) {
1664 $blockid = $bc->attributes['id'];
1666 $controlshtml = $this->block_controls($bc->controls, $blockid);
1668 $output = '';
1669 if ($title || $controlshtml) {
1670 $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'));
1672 return $output;
1676 * Produces the content area for a block
1678 * @param block_contents $bc
1679 * @return string
1681 protected function block_content(block_contents $bc) {
1682 $output = html_writer::start_tag('div', array('class' => 'content'));
1683 if (!$bc->title && !$this->block_controls($bc->controls)) {
1684 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1686 $output .= $bc->content;
1687 $output .= $this->block_footer($bc);
1688 $output .= html_writer::end_tag('div');
1690 return $output;
1694 * Produces the footer for a block
1696 * @param block_contents $bc
1697 * @return string
1699 protected function block_footer(block_contents $bc) {
1700 $output = '';
1701 if ($bc->footer) {
1702 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1704 return $output;
1708 * Produces the annotation for a block
1710 * @param block_contents $bc
1711 * @return string
1713 protected function block_annotation(block_contents $bc) {
1714 $output = '';
1715 if ($bc->annotation) {
1716 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1718 return $output;
1722 * Calls the JS require function to hide a block.
1724 * @param block_contents $bc A block_contents object
1726 protected function init_block_hider_js(block_contents $bc) {
1727 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1728 $config = new stdClass;
1729 $config->id = $bc->attributes['id'];
1730 $config->title = strip_tags($bc->title);
1731 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1732 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1733 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1735 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1736 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1741 * Render the contents of a block_list.
1743 * @param array $icons the icon for each item.
1744 * @param array $items the content of each item.
1745 * @return string HTML
1747 public function list_block_contents($icons, $items) {
1748 $row = 0;
1749 $lis = array();
1750 foreach ($items as $key => $string) {
1751 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1752 if (!empty($icons[$key])) { //test if the content has an assigned icon
1753 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1755 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1756 $item .= html_writer::end_tag('li');
1757 $lis[] = $item;
1758 $row = 1 - $row; // Flip even/odd.
1760 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1764 * Output all the blocks in a particular region.
1766 * @param string $region the name of a region on this page.
1767 * @return string the HTML to be output.
1769 public function blocks_for_region($region) {
1770 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1771 $blocks = $this->page->blocks->get_blocks_for_region($region);
1772 $lastblock = null;
1773 $zones = array();
1774 foreach ($blocks as $block) {
1775 $zones[] = $block->title;
1777 $output = '';
1779 foreach ($blockcontents as $bc) {
1780 if ($bc instanceof block_contents) {
1781 $output .= $this->block($bc, $region);
1782 $lastblock = $bc->title;
1783 } else if ($bc instanceof block_move_target) {
1784 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1785 } else {
1786 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1789 return $output;
1793 * Output a place where the block that is currently being moved can be dropped.
1795 * @param block_move_target $target with the necessary details.
1796 * @param array $zones array of areas where the block can be moved to
1797 * @param string $previous the block located before the area currently being rendered.
1798 * @param string $region the name of the region
1799 * @return string the HTML to be output.
1801 public function block_move_target($target, $zones, $previous, $region) {
1802 if ($previous == null) {
1803 if (empty($zones)) {
1804 // There are no zones, probably because there are no blocks.
1805 $regions = $this->page->theme->get_all_block_regions();
1806 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1807 } else {
1808 $position = get_string('moveblockbefore', 'block', $zones[0]);
1810 } else {
1811 $position = get_string('moveblockafter', 'block', $previous);
1813 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1817 * Renders a special html link with attached action
1819 * Theme developers: DO NOT OVERRIDE! Please override function
1820 * {@link core_renderer::render_action_link()} instead.
1822 * @param string|moodle_url $url
1823 * @param string $text HTML fragment
1824 * @param component_action $action
1825 * @param array $attributes associative array of html link attributes + disabled
1826 * @param pix_icon optional pix icon to render with the link
1827 * @return string HTML fragment
1829 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1830 if (!($url instanceof moodle_url)) {
1831 $url = new moodle_url($url);
1833 $link = new action_link($url, $text, $action, $attributes, $icon);
1835 return $this->render($link);
1839 * Renders an action_link object.
1841 * The provided link is renderer and the HTML returned. At the same time the
1842 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1844 * @param action_link $link
1845 * @return string HTML fragment
1847 protected function render_action_link(action_link $link) {
1848 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1852 * Renders an action_icon.
1854 * This function uses the {@link core_renderer::action_link()} method for the
1855 * most part. What it does different is prepare the icon as HTML and use it
1856 * as the link text.
1858 * Theme developers: If you want to change how action links and/or icons are rendered,
1859 * consider overriding function {@link core_renderer::render_action_link()} and
1860 * {@link core_renderer::render_pix_icon()}.
1862 * @param string|moodle_url $url A string URL or moodel_url
1863 * @param pix_icon $pixicon
1864 * @param component_action $action
1865 * @param array $attributes associative array of html link attributes + disabled
1866 * @param bool $linktext show title next to image in link
1867 * @return string HTML fragment
1869 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1870 if (!($url instanceof moodle_url)) {
1871 $url = new moodle_url($url);
1873 $attributes = (array)$attributes;
1875 if (empty($attributes['class'])) {
1876 // let ppl override the class via $options
1877 $attributes['class'] = 'action-icon';
1880 $icon = $this->render($pixicon);
1882 if ($linktext) {
1883 $text = $pixicon->attributes['alt'];
1884 } else {
1885 $text = '';
1888 return $this->action_link($url, $text.$icon, $action, $attributes);
1892 * Print a message along with button choices for Continue/Cancel
1894 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1896 * @param string $message The question to ask the user
1897 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1898 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1899 * @return string HTML fragment
1901 public function confirm($message, $continue, $cancel) {
1902 if ($continue instanceof single_button) {
1903 // ok
1904 $continue->primary = true;
1905 } else if (is_string($continue)) {
1906 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1907 } else if ($continue instanceof moodle_url) {
1908 $continue = new single_button($continue, get_string('continue'), 'post', true);
1909 } else {
1910 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1913 if ($cancel instanceof single_button) {
1914 // ok
1915 } else if (is_string($cancel)) {
1916 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1917 } else if ($cancel instanceof moodle_url) {
1918 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1919 } else {
1920 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1923 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice');
1924 $output .= $this->box_start('modal-content', 'modal-content');
1925 $output .= $this->box_start('modal-header p-x-1', 'modal-header');
1926 $output .= html_writer::tag('h4', get_string('confirm'));
1927 $output .= $this->box_end();
1928 $output .= $this->box_start('modal-body', 'modal-body');
1929 $output .= html_writer::tag('p', $message);
1930 $output .= $this->box_end();
1931 $output .= $this->box_start('modal-footer', 'modal-footer');
1932 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1933 $output .= $this->box_end();
1934 $output .= $this->box_end();
1935 $output .= $this->box_end();
1936 return $output;
1940 * Returns a form with a single button.
1942 * Theme developers: DO NOT OVERRIDE! Please override function
1943 * {@link core_renderer::render_single_button()} instead.
1945 * @param string|moodle_url $url
1946 * @param string $label button text
1947 * @param string $method get or post submit method
1948 * @param array $options associative array {disabled, title, etc.}
1949 * @return string HTML fragment
1951 public function single_button($url, $label, $method='post', array $options=null) {
1952 if (!($url instanceof moodle_url)) {
1953 $url = new moodle_url($url);
1955 $button = new single_button($url, $label, $method);
1957 foreach ((array)$options as $key=>$value) {
1958 if (array_key_exists($key, $button)) {
1959 $button->$key = $value;
1963 return $this->render($button);
1967 * Renders a single button widget.
1969 * This will return HTML to display a form containing a single button.
1971 * @param single_button $button
1972 * @return string HTML fragment
1974 protected function render_single_button(single_button $button) {
1975 $attributes = array('type' => 'submit',
1976 'value' => $button->label,
1977 'disabled' => $button->disabled ? 'disabled' : null,
1978 'title' => $button->tooltip);
1980 if ($button->actions) {
1981 $id = html_writer::random_id('single_button');
1982 $attributes['id'] = $id;
1983 foreach ($button->actions as $action) {
1984 $this->add_action_handler($action, $id);
1988 // first the input element
1989 $output = html_writer::empty_tag('input', $attributes);
1991 // then hidden fields
1992 $params = $button->url->params();
1993 if ($button->method === 'post') {
1994 $params['sesskey'] = sesskey();
1996 foreach ($params as $var => $val) {
1997 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
2000 // then div wrapper for xhtml strictness
2001 $output = html_writer::tag('div', $output);
2003 // now the form itself around it
2004 if ($button->method === 'get') {
2005 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
2006 } else {
2007 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
2009 if ($url === '') {
2010 $url = '#'; // there has to be always some action
2012 $attributes = array('method' => $button->method,
2013 'action' => $url,
2014 'id' => $button->formid);
2015 $output = html_writer::tag('form', $output, $attributes);
2017 // and finally one more wrapper with class
2018 return html_writer::tag('div', $output, array('class' => $button->class));
2022 * Returns a form with a single select widget.
2024 * Theme developers: DO NOT OVERRIDE! Please override function
2025 * {@link core_renderer::render_single_select()} instead.
2027 * @param moodle_url $url form action target, includes hidden fields
2028 * @param string $name name of selection field - the changing parameter in url
2029 * @param array $options list of options
2030 * @param string $selected selected element
2031 * @param array $nothing
2032 * @param string $formid
2033 * @param array $attributes other attributes for the single select
2034 * @return string HTML fragment
2036 public function single_select($url, $name, array $options, $selected = '',
2037 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2038 if (!($url instanceof moodle_url)) {
2039 $url = new moodle_url($url);
2041 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2043 if (array_key_exists('label', $attributes)) {
2044 $select->set_label($attributes['label']);
2045 unset($attributes['label']);
2047 $select->attributes = $attributes;
2049 return $this->render($select);
2053 * Returns a dataformat selection and download form
2055 * @param string $label A text label
2056 * @param moodle_url|string $base The download page url
2057 * @param string $name The query param which will hold the type of the download
2058 * @param array $params Extra params sent to the download page
2059 * @return string HTML fragment
2061 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2063 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2064 $options = array();
2065 foreach ($formats as $format) {
2066 if ($format->is_enabled()) {
2067 $options[] = array(
2068 'value' => $format->name,
2069 'label' => get_string('dataformat', $format->component),
2073 $hiddenparams = array();
2074 foreach ($params as $key => $value) {
2075 $hiddenparams[] = array(
2076 'name' => $key,
2077 'value' => $value,
2080 $data = array(
2081 'label' => $label,
2082 'base' => $base,
2083 'name' => $name,
2084 'params' => $hiddenparams,
2085 'options' => $options,
2086 'sesskey' => sesskey(),
2087 'submit' => get_string('download'),
2090 return $this->render_from_template('core/dataformat_selector', $data);
2095 * Internal implementation of single_select rendering
2097 * @param single_select $select
2098 * @return string HTML fragment
2100 protected function render_single_select(single_select $select) {
2101 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2105 * Returns a form with a url select widget.
2107 * Theme developers: DO NOT OVERRIDE! Please override function
2108 * {@link core_renderer::render_url_select()} instead.
2110 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2111 * @param string $selected selected element
2112 * @param array $nothing
2113 * @param string $formid
2114 * @return string HTML fragment
2116 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2117 $select = new url_select($urls, $selected, $nothing, $formid);
2118 return $this->render($select);
2122 * Internal implementation of url_select rendering
2124 * @param url_select $select
2125 * @return string HTML fragment
2127 protected function render_url_select(url_select $select) {
2128 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2132 * Returns a string containing a link to the user documentation.
2133 * Also contains an icon by default. Shown to teachers and admin only.
2135 * @param string $path The page link after doc root and language, no leading slash.
2136 * @param string $text The text to be displayed for the link
2137 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2138 * @return string
2140 public function doc_link($path, $text = '', $forcepopup = false) {
2141 global $CFG;
2143 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2145 $url = new moodle_url(get_docs_url($path));
2147 $attributes = array('href'=>$url);
2148 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2149 $attributes['class'] = 'helplinkpopup';
2152 return html_writer::tag('a', $icon.$text, $attributes);
2156 * Return HTML for an image_icon.
2158 * Theme developers: DO NOT OVERRIDE! Please override function
2159 * {@link core_renderer::render_image_icon()} instead.
2161 * @param string $pix short pix name
2162 * @param string $alt mandatory alt attribute
2163 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2164 * @param array $attributes htm lattributes
2165 * @return string HTML fragment
2167 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2168 $icon = new image_icon($pix, $alt, $component, $attributes);
2169 return $this->render($icon);
2173 * Renders a pix_icon widget and returns the HTML to display it.
2175 * @param image_icon $icon
2176 * @return string HTML fragment
2178 protected function render_image_icon(image_icon $icon) {
2179 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2180 return $system->render_pix_icon($this, $icon);
2184 * Return HTML for a pix_icon.
2186 * Theme developers: DO NOT OVERRIDE! Please override function
2187 * {@link core_renderer::render_pix_icon()} instead.
2189 * @param string $pix short pix name
2190 * @param string $alt mandatory alt attribute
2191 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2192 * @param array $attributes htm lattributes
2193 * @return string HTML fragment
2195 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2196 $icon = new pix_icon($pix, $alt, $component, $attributes);
2197 return $this->render($icon);
2201 * Renders a pix_icon widget and returns the HTML to display it.
2203 * @param pix_icon $icon
2204 * @return string HTML fragment
2206 protected function render_pix_icon(pix_icon $icon) {
2207 $system = \core\output\icon_system::instance();
2208 return $system->render_pix_icon($this, $icon);
2212 * Return HTML to display an emoticon icon.
2214 * @param pix_emoticon $emoticon
2215 * @return string HTML fragment
2217 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2218 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2219 return $system->render_pix_icon($this, $emoticon);
2223 * Produces the html that represents this rating in the UI
2225 * @param rating $rating the page object on which this rating will appear
2226 * @return string
2228 function render_rating(rating $rating) {
2229 global $CFG, $USER;
2231 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2232 return null;//ratings are turned off
2235 $ratingmanager = new rating_manager();
2236 // Initialise the JavaScript so ratings can be done by AJAX.
2237 $ratingmanager->initialise_rating_javascript($this->page);
2239 $strrate = get_string("rate", "rating");
2240 $ratinghtml = ''; //the string we'll return
2242 // permissions check - can they view the aggregate?
2243 if ($rating->user_can_view_aggregate()) {
2245 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2246 $aggregatestr = $rating->get_aggregate_string();
2248 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2249 if ($rating->count > 0) {
2250 $countstr = "({$rating->count})";
2251 } else {
2252 $countstr = '-';
2254 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2256 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2257 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2259 $nonpopuplink = $rating->get_view_ratings_url();
2260 $popuplink = $rating->get_view_ratings_url(true);
2262 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2263 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2264 } else {
2265 $ratinghtml .= $aggregatehtml;
2269 $formstart = null;
2270 // if the item doesn't belong to the current user, the user has permission to rate
2271 // and we're within the assessable period
2272 if ($rating->user_can_rate()) {
2274 $rateurl = $rating->get_rate_url();
2275 $inputs = $rateurl->params();
2277 //start the rating form
2278 $formattrs = array(
2279 'id' => "postrating{$rating->itemid}",
2280 'class' => 'postratingform',
2281 'method' => 'post',
2282 'action' => $rateurl->out_omit_querystring()
2284 $formstart = html_writer::start_tag('form', $formattrs);
2285 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2287 // add the hidden inputs
2288 foreach ($inputs as $name => $value) {
2289 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2290 $formstart .= html_writer::empty_tag('input', $attributes);
2293 if (empty($ratinghtml)) {
2294 $ratinghtml .= $strrate.': ';
2296 $ratinghtml = $formstart.$ratinghtml;
2298 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2299 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2300 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2301 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2303 //output submit button
2304 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2306 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2307 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2309 if (!$rating->settings->scale->isnumeric) {
2310 // If a global scale, try to find current course ID from the context
2311 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2312 $courseid = $coursecontext->instanceid;
2313 } else {
2314 $courseid = $rating->settings->scale->courseid;
2316 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2318 $ratinghtml .= html_writer::end_tag('span');
2319 $ratinghtml .= html_writer::end_tag('div');
2320 $ratinghtml .= html_writer::end_tag('form');
2323 return $ratinghtml;
2327 * Centered heading with attached help button (same title text)
2328 * and optional icon attached.
2330 * @param string $text A heading text
2331 * @param string $helpidentifier The keyword that defines a help page
2332 * @param string $component component name
2333 * @param string|moodle_url $icon
2334 * @param string $iconalt icon alt text
2335 * @param int $level The level of importance of the heading. Defaulting to 2
2336 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2337 * @return string HTML fragment
2339 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2340 $image = '';
2341 if ($icon) {
2342 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2345 $help = '';
2346 if ($helpidentifier) {
2347 $help = $this->help_icon($helpidentifier, $component);
2350 return $this->heading($image.$text.$help, $level, $classnames);
2354 * Returns HTML to display a help icon.
2356 * @deprecated since Moodle 2.0
2358 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2359 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2363 * Returns HTML to display a help icon.
2365 * Theme developers: DO NOT OVERRIDE! Please override function
2366 * {@link core_renderer::render_help_icon()} instead.
2368 * @param string $identifier The keyword that defines a help page
2369 * @param string $component component name
2370 * @param string|bool $linktext true means use $title as link text, string means link text value
2371 * @return string HTML fragment
2373 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2374 $icon = new help_icon($identifier, $component);
2375 $icon->diag_strings();
2376 if ($linktext === true) {
2377 $icon->linktext = get_string($icon->identifier, $icon->component);
2378 } else if (!empty($linktext)) {
2379 $icon->linktext = $linktext;
2381 return $this->render($icon);
2385 * Implementation of user image rendering.
2387 * @param help_icon $helpicon A help icon instance
2388 * @return string HTML fragment
2390 protected function render_help_icon(help_icon $helpicon) {
2391 return $this->render_from_template('core/help_icon', $helpicon->export_for_template($this));
2395 * Returns HTML to display a scale help icon.
2397 * @param int $courseid
2398 * @param stdClass $scale instance
2399 * @return string HTML fragment
2401 public function help_icon_scale($courseid, stdClass $scale) {
2402 global $CFG;
2404 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2406 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2408 $scaleid = abs($scale->id);
2410 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2411 $action = new popup_action('click', $link, 'ratingscale');
2413 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2417 * Creates and returns a spacer image with optional line break.
2419 * @param array $attributes Any HTML attributes to add to the spaced.
2420 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2421 * laxy do it with CSS which is a much better solution.
2422 * @return string HTML fragment
2424 public function spacer(array $attributes = null, $br = false) {
2425 $attributes = (array)$attributes;
2426 if (empty($attributes['width'])) {
2427 $attributes['width'] = 1;
2429 if (empty($attributes['height'])) {
2430 $attributes['height'] = 1;
2432 $attributes['class'] = 'spacer';
2434 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2436 if (!empty($br)) {
2437 $output .= '<br />';
2440 return $output;
2444 * Returns HTML to display the specified user's avatar.
2446 * User avatar may be obtained in two ways:
2447 * <pre>
2448 * // Option 1: (shortcut for simple cases, preferred way)
2449 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2450 * $OUTPUT->user_picture($user, array('popup'=>true));
2452 * // Option 2:
2453 * $userpic = new user_picture($user);
2454 * // Set properties of $userpic
2455 * $userpic->popup = true;
2456 * $OUTPUT->render($userpic);
2457 * </pre>
2459 * Theme developers: DO NOT OVERRIDE! Please override function
2460 * {@link core_renderer::render_user_picture()} instead.
2462 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2463 * If any of these are missing, the database is queried. Avoid this
2464 * if at all possible, particularly for reports. It is very bad for performance.
2465 * @param array $options associative array with user picture options, used only if not a user_picture object,
2466 * options are:
2467 * - courseid=$this->page->course->id (course id of user profile in link)
2468 * - size=35 (size of image)
2469 * - link=true (make image clickable - the link leads to user profile)
2470 * - popup=false (open in popup)
2471 * - alttext=true (add image alt attribute)
2472 * - class = image class attribute (default 'userpicture')
2473 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2474 * - includefullname=false (whether to include the user's full name together with the user picture)
2475 * @return string HTML fragment
2477 public function user_picture(stdClass $user, array $options = null) {
2478 $userpicture = new user_picture($user);
2479 foreach ((array)$options as $key=>$value) {
2480 if (array_key_exists($key, $userpicture)) {
2481 $userpicture->$key = $value;
2484 return $this->render($userpicture);
2488 * Internal implementation of user image rendering.
2490 * @param user_picture $userpicture
2491 * @return string
2493 protected function render_user_picture(user_picture $userpicture) {
2494 global $CFG, $DB;
2496 $user = $userpicture->user;
2498 if ($userpicture->alttext) {
2499 if (!empty($user->imagealt)) {
2500 $alt = $user->imagealt;
2501 } else {
2502 $alt = get_string('pictureof', '', fullname($user));
2504 } else {
2505 $alt = '';
2508 if (empty($userpicture->size)) {
2509 $size = 35;
2510 } else if ($userpicture->size === true or $userpicture->size == 1) {
2511 $size = 100;
2512 } else {
2513 $size = $userpicture->size;
2516 $class = $userpicture->class;
2518 if ($user->picture == 0) {
2519 $class .= ' defaultuserpic';
2522 $src = $userpicture->get_url($this->page, $this);
2524 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2525 if (!$userpicture->visibletoscreenreaders) {
2526 $attributes['role'] = 'presentation';
2529 // get the image html output fisrt
2530 $output = html_writer::empty_tag('img', $attributes);
2532 // Show fullname together with the picture when desired.
2533 if ($userpicture->includefullname) {
2534 $output .= fullname($userpicture->user);
2537 // then wrap it in link if needed
2538 if (!$userpicture->link) {
2539 return $output;
2542 if (empty($userpicture->courseid)) {
2543 $courseid = $this->page->course->id;
2544 } else {
2545 $courseid = $userpicture->courseid;
2548 if ($courseid == SITEID) {
2549 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2550 } else {
2551 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2554 $attributes = array('href'=>$url);
2555 if (!$userpicture->visibletoscreenreaders) {
2556 $attributes['tabindex'] = '-1';
2557 $attributes['aria-hidden'] = 'true';
2560 if ($userpicture->popup) {
2561 $id = html_writer::random_id('userpicture');
2562 $attributes['id'] = $id;
2563 $this->add_action_handler(new popup_action('click', $url), $id);
2566 return html_writer::tag('a', $output, $attributes);
2570 * Internal implementation of file tree viewer items rendering.
2572 * @param array $dir
2573 * @return string
2575 public function htmllize_file_tree($dir) {
2576 if (empty($dir['subdirs']) and empty($dir['files'])) {
2577 return '';
2579 $result = '<ul>';
2580 foreach ($dir['subdirs'] as $subdir) {
2581 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2583 foreach ($dir['files'] as $file) {
2584 $filename = $file->get_filename();
2585 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2587 $result .= '</ul>';
2589 return $result;
2593 * Returns HTML to display the file picker
2595 * <pre>
2596 * $OUTPUT->file_picker($options);
2597 * </pre>
2599 * Theme developers: DO NOT OVERRIDE! Please override function
2600 * {@link core_renderer::render_file_picker()} instead.
2602 * @param array $options associative array with file manager options
2603 * options are:
2604 * maxbytes=>-1,
2605 * itemid=>0,
2606 * client_id=>uniqid(),
2607 * acepted_types=>'*',
2608 * return_types=>FILE_INTERNAL,
2609 * context=>$PAGE->context
2610 * @return string HTML fragment
2612 public function file_picker($options) {
2613 $fp = new file_picker($options);
2614 return $this->render($fp);
2618 * Internal implementation of file picker rendering.
2620 * @param file_picker $fp
2621 * @return string
2623 public function render_file_picker(file_picker $fp) {
2624 global $CFG, $OUTPUT, $USER;
2625 $options = $fp->options;
2626 $client_id = $options->client_id;
2627 $strsaved = get_string('filesaved', 'repository');
2628 $straddfile = get_string('openpicker', 'repository');
2629 $strloading = get_string('loading', 'repository');
2630 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2631 $strdroptoupload = get_string('droptoupload', 'moodle');
2632 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2634 $currentfile = $options->currentfile;
2635 if (empty($currentfile)) {
2636 $currentfile = '';
2637 } else {
2638 $currentfile .= ' - ';
2640 if ($options->maxbytes) {
2641 $size = $options->maxbytes;
2642 } else {
2643 $size = get_max_upload_file_size();
2645 if ($size == -1) {
2646 $maxsize = '';
2647 } else {
2648 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2650 if ($options->buttonname) {
2651 $buttonname = ' name="' . $options->buttonname . '"';
2652 } else {
2653 $buttonname = '';
2655 $html = <<<EOD
2656 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2657 $icon_progress
2658 </div>
2659 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2660 <div>
2661 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2662 <span> $maxsize </span>
2663 </div>
2664 EOD;
2665 if ($options->env != 'url') {
2666 $html .= <<<EOD
2667 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2668 <div class="filepicker-filename">
2669 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2670 <div class="dndupload-progressbars"></div>
2671 </div>
2672 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2673 </div>
2674 EOD;
2676 $html .= '</div>';
2677 return $html;
2681 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2683 * @deprecated since Moodle 3.2
2685 * @param string $cmid the course_module id.
2686 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2687 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2689 public function update_module_button($cmid, $modulename) {
2690 global $CFG;
2692 debugging('core_renderer::update_module_button() has been deprecated and should not be used anymore. Activity modules ' .
2693 'should not add the edit module button, the link is already available in the Administration block. Themes can choose ' .
2694 'to display the link in the buttons row consistently for all module types.', DEBUG_DEVELOPER);
2696 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2697 $modulename = get_string('modulename', $modulename);
2698 $string = get_string('updatethis', '', $modulename);
2699 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2700 return $this->single_button($url, $string);
2701 } else {
2702 return '';
2707 * Returns HTML to display a "Turn editing on/off" button in a form.
2709 * @param moodle_url $url The URL + params to send through when clicking the button
2710 * @return string HTML the button
2712 public function edit_button(moodle_url $url) {
2714 $url->param('sesskey', sesskey());
2715 if ($this->page->user_is_editing()) {
2716 $url->param('edit', 'off');
2717 $editstring = get_string('turneditingoff');
2718 } else {
2719 $url->param('edit', 'on');
2720 $editstring = get_string('turneditingon');
2723 return $this->single_button($url, $editstring);
2727 * Returns HTML to display a simple button to close a window
2729 * @param string $text The lang string for the button's label (already output from get_string())
2730 * @return string html fragment
2732 public function close_window_button($text='') {
2733 if (empty($text)) {
2734 $text = get_string('closewindow');
2736 $button = new single_button(new moodle_url('#'), $text, 'get');
2737 $button->add_action(new component_action('click', 'close_window'));
2739 return $this->container($this->render($button), 'closewindow');
2743 * Output an error message. By default wraps the error message in <span class="error">.
2744 * If the error message is blank, nothing is output.
2746 * @param string $message the error message.
2747 * @return string the HTML to output.
2749 public function error_text($message) {
2750 if (empty($message)) {
2751 return '';
2753 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2754 return html_writer::tag('span', $message, array('class' => 'error'));
2758 * Do not call this function directly.
2760 * To terminate the current script with a fatal error, call the {@link print_error}
2761 * function, or throw an exception. Doing either of those things will then call this
2762 * function to display the error, before terminating the execution.
2764 * @param string $message The message to output
2765 * @param string $moreinfourl URL where more info can be found about the error
2766 * @param string $link Link for the Continue button
2767 * @param array $backtrace The execution backtrace
2768 * @param string $debuginfo Debugging information
2769 * @return string the HTML to output.
2771 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2772 global $CFG;
2774 $output = '';
2775 $obbuffer = '';
2777 if ($this->has_started()) {
2778 // we can not always recover properly here, we have problems with output buffering,
2779 // html tables, etc.
2780 $output .= $this->opencontainers->pop_all_but_last();
2782 } else {
2783 // It is really bad if library code throws exception when output buffering is on,
2784 // because the buffered text would be printed before our start of page.
2785 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2786 error_reporting(0); // disable notices from gzip compression, etc.
2787 while (ob_get_level() > 0) {
2788 $buff = ob_get_clean();
2789 if ($buff === false) {
2790 break;
2792 $obbuffer .= $buff;
2794 error_reporting($CFG->debug);
2796 // Output not yet started.
2797 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2798 if (empty($_SERVER['HTTP_RANGE'])) {
2799 @header($protocol . ' 404 Not Found');
2800 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2801 // Coax iOS 10 into sending the session cookie.
2802 @header($protocol . ' 403 Forbidden');
2803 } else {
2804 // Must stop byteserving attempts somehow,
2805 // this is weird but Chrome PDF viewer can be stopped only with 407!
2806 @header($protocol . ' 407 Proxy Authentication Required');
2809 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2810 $this->page->set_url('/'); // no url
2811 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2812 $this->page->set_title(get_string('error'));
2813 $this->page->set_heading($this->page->course->fullname);
2814 $output .= $this->header();
2817 $message = '<p class="errormessage">' . $message . '</p>'.
2818 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2819 get_string('moreinformation') . '</a></p>';
2820 if (empty($CFG->rolesactive)) {
2821 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2822 //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.
2824 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2826 if ($CFG->debugdeveloper) {
2827 if (!empty($debuginfo)) {
2828 $debuginfo = s($debuginfo); // removes all nasty JS
2829 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2830 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2832 if (!empty($backtrace)) {
2833 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2835 if ($obbuffer !== '' ) {
2836 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2840 if (empty($CFG->rolesactive)) {
2841 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2842 } else if (!empty($link)) {
2843 $output .= $this->continue_button($link);
2846 $output .= $this->footer();
2848 // Padding to encourage IE to display our error page, rather than its own.
2849 $output .= str_repeat(' ', 512);
2851 return $output;
2855 * Output a notification (that is, a status message about something that has just happened).
2857 * Note: \core\notification::add() may be more suitable for your usage.
2859 * @param string $message The message to print out.
2860 * @param string $type The type of notification. See constants on \core\output\notification.
2861 * @return string the HTML to output.
2863 public function notification($message, $type = null) {
2864 $typemappings = [
2865 // Valid types.
2866 'success' => \core\output\notification::NOTIFY_SUCCESS,
2867 'info' => \core\output\notification::NOTIFY_INFO,
2868 'warning' => \core\output\notification::NOTIFY_WARNING,
2869 'error' => \core\output\notification::NOTIFY_ERROR,
2871 // Legacy types mapped to current types.
2872 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2873 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2874 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2875 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2876 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2877 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2878 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2881 $extraclasses = [];
2883 if ($type) {
2884 if (strpos($type, ' ') === false) {
2885 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2886 if (isset($typemappings[$type])) {
2887 $type = $typemappings[$type];
2888 } else {
2889 // The value provided did not match a known type. It must be an extra class.
2890 $extraclasses = [$type];
2892 } else {
2893 // Identify what type of notification this is.
2894 $classarray = explode(' ', self::prepare_classes($type));
2896 // Separate out the type of notification from the extra classes.
2897 foreach ($classarray as $class) {
2898 if (isset($typemappings[$class])) {
2899 $type = $typemappings[$class];
2900 } else {
2901 $extraclasses[] = $class;
2907 $notification = new \core\output\notification($message, $type);
2908 if (count($extraclasses)) {
2909 $notification->set_extra_classes($extraclasses);
2912 // Return the rendered template.
2913 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2917 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2919 public function notify_problem() {
2920 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
2921 'please use \core\notification::add(), or \core\output\notification as required.');
2925 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2927 public function notify_success() {
2928 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
2929 'please use \core\notification::add(), or \core\output\notification as required.');
2933 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2935 public function notify_message() {
2936 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
2937 'please use \core\notification::add(), or \core\output\notification as required.');
2941 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2943 public function notify_redirect() {
2944 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
2945 'please use \core\notification::add(), or \core\output\notification as required.');
2949 * Render a notification (that is, a status message about something that has
2950 * just happened).
2952 * @param \core\output\notification $notification the notification to print out
2953 * @return string the HTML to output.
2955 protected function render_notification(\core\output\notification $notification) {
2956 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2960 * Returns HTML to display a continue button that goes to a particular URL.
2962 * @param string|moodle_url $url The url the button goes to.
2963 * @return string the HTML to output.
2965 public function continue_button($url) {
2966 if (!($url instanceof moodle_url)) {
2967 $url = new moodle_url($url);
2969 $button = new single_button($url, get_string('continue'), 'get', true);
2970 $button->class = 'continuebutton';
2972 return $this->render($button);
2976 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2978 * Theme developers: DO NOT OVERRIDE! Please override function
2979 * {@link core_renderer::render_paging_bar()} instead.
2981 * @param int $totalcount The total number of entries available to be paged through
2982 * @param int $page The page you are currently viewing
2983 * @param int $perpage The number of entries that should be shown per page
2984 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2985 * @param string $pagevar name of page parameter that holds the page number
2986 * @return string the HTML to output.
2988 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2989 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2990 return $this->render($pb);
2994 * Internal implementation of paging bar rendering.
2996 * @param paging_bar $pagingbar
2997 * @return string
2999 protected function render_paging_bar(paging_bar $pagingbar) {
3000 $output = '';
3001 $pagingbar = clone($pagingbar);
3002 $pagingbar->prepare($this, $this->page, $this->target);
3004 if ($pagingbar->totalcount > $pagingbar->perpage) {
3005 $output .= get_string('page') . ':';
3007 if (!empty($pagingbar->previouslink)) {
3008 $output .= ' (' . $pagingbar->previouslink . ') ';
3011 if (!empty($pagingbar->firstlink)) {
3012 $output .= ' ' . $pagingbar->firstlink . ' ...';
3015 foreach ($pagingbar->pagelinks as $link) {
3016 $output .= " $link";
3019 if (!empty($pagingbar->lastlink)) {
3020 $output .= ' ... ' . $pagingbar->lastlink . ' ';
3023 if (!empty($pagingbar->nextlink)) {
3024 $output .= ' (' . $pagingbar->nextlink . ')';
3028 return html_writer::tag('div', $output, array('class' => 'paging'));
3032 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3034 * @param string $current the currently selected letter.
3035 * @param string $class class name to add to this initial bar.
3036 * @param string $title the name to put in front of this initial bar.
3037 * @param string $urlvar URL parameter name for this initial.
3038 * @param string $url URL object.
3039 * @param array $alpha of letters in the alphabet.
3040 * @return string the HTML to output.
3042 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3043 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3044 return $this->render($ib);
3048 * Internal implementation of initials bar rendering.
3050 * @param initials_bar $initialsbar
3051 * @return string
3053 protected function render_initials_bar(initials_bar $initialsbar) {
3054 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3058 * Output the place a skip link goes to.
3060 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3061 * @return string the HTML to output.
3063 public function skip_link_target($id = null) {
3064 return html_writer::span('', '', array('id' => $id));
3068 * Outputs a heading
3070 * @param string $text The text of the heading
3071 * @param int $level The level of importance of the heading. Defaulting to 2
3072 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3073 * @param string $id An optional ID
3074 * @return string the HTML to output.
3076 public function heading($text, $level = 2, $classes = null, $id = null) {
3077 $level = (integer) $level;
3078 if ($level < 1 or $level > 6) {
3079 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3081 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3085 * Outputs a box.
3087 * @param string $contents The contents of the box
3088 * @param string $classes A space-separated list of CSS classes
3089 * @param string $id An optional ID
3090 * @param array $attributes An array of other attributes to give the box.
3091 * @return string the HTML to output.
3093 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3094 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3098 * Outputs the opening section of a box.
3100 * @param string $classes A space-separated list of CSS classes
3101 * @param string $id An optional ID
3102 * @param array $attributes An array of other attributes to give the box.
3103 * @return string the HTML to output.
3105 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3106 $this->opencontainers->push('box', html_writer::end_tag('div'));
3107 $attributes['id'] = $id;
3108 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
3109 return html_writer::start_tag('div', $attributes);
3113 * Outputs the closing section of a box.
3115 * @return string the HTML to output.
3117 public function box_end() {
3118 return $this->opencontainers->pop('box');
3122 * Outputs a container.
3124 * @param string $contents The contents of the box
3125 * @param string $classes A space-separated list of CSS classes
3126 * @param string $id An optional ID
3127 * @return string the HTML to output.
3129 public function container($contents, $classes = null, $id = null) {
3130 return $this->container_start($classes, $id) . $contents . $this->container_end();
3134 * Outputs the opening section of a container.
3136 * @param string $classes A space-separated list of CSS classes
3137 * @param string $id An optional ID
3138 * @return string the HTML to output.
3140 public function container_start($classes = null, $id = null) {
3141 $this->opencontainers->push('container', html_writer::end_tag('div'));
3142 return html_writer::start_tag('div', array('id' => $id,
3143 'class' => renderer_base::prepare_classes($classes)));
3147 * Outputs the closing section of a container.
3149 * @return string the HTML to output.
3151 public function container_end() {
3152 return $this->opencontainers->pop('container');
3156 * Make nested HTML lists out of the items
3158 * The resulting list will look something like this:
3160 * <pre>
3161 * <<ul>>
3162 * <<li>><div class='tree_item parent'>(item contents)</div>
3163 * <<ul>
3164 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3165 * <</ul>>
3166 * <</li>>
3167 * <</ul>>
3168 * </pre>
3170 * @param array $items
3171 * @param array $attrs html attributes passed to the top ofs the list
3172 * @return string HTML
3174 public function tree_block_contents($items, $attrs = array()) {
3175 // exit if empty, we don't want an empty ul element
3176 if (empty($items)) {
3177 return '';
3179 // array of nested li elements
3180 $lis = array();
3181 foreach ($items as $item) {
3182 // this applies to the li item which contains all child lists too
3183 $content = $item->content($this);
3184 $liclasses = array($item->get_css_type());
3185 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3186 $liclasses[] = 'collapsed';
3188 if ($item->isactive === true) {
3189 $liclasses[] = 'current_branch';
3191 $liattr = array('class'=>join(' ',$liclasses));
3192 // class attribute on the div item which only contains the item content
3193 $divclasses = array('tree_item');
3194 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3195 $divclasses[] = 'branch';
3196 } else {
3197 $divclasses[] = 'leaf';
3199 if (!empty($item->classes) && count($item->classes)>0) {
3200 $divclasses[] = join(' ', $item->classes);
3202 $divattr = array('class'=>join(' ', $divclasses));
3203 if (!empty($item->id)) {
3204 $divattr['id'] = $item->id;
3206 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3207 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3208 $content = html_writer::empty_tag('hr') . $content;
3210 $content = html_writer::tag('li', $content, $liattr);
3211 $lis[] = $content;
3213 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3217 * Returns a search box.
3219 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3220 * @return string HTML with the search form hidden by default.
3222 public function search_box($id = false) {
3223 global $CFG;
3225 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3226 // result in an extra included file for each site, even the ones where global search
3227 // is disabled.
3228 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3229 return '';
3232 if ($id == false) {
3233 $id = uniqid();
3234 } else {
3235 // Needs to be cleaned, we use it for the input id.
3236 $id = clean_param($id, PARAM_ALPHANUMEXT);
3239 // JS to animate the form.
3240 $this->page->requires->js_call_amd('core/search-input', 'init', array($id));
3242 $searchicon = html_writer::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
3243 array('role' => 'button', 'tabindex' => 0));
3244 $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot . '/search/index.php');
3245 $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
3246 'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id, 'class' => 'form-control');
3248 $contents = html_writer::tag('label', get_string('enteryoursearchquery', 'search'),
3249 array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer::tag('input', '', $inputattrs);
3250 if ($this->page->context && $this->page->context->contextlevel !== CONTEXT_SYSTEM) {
3251 $contents .= html_writer::empty_tag('input', ['type' => 'hidden',
3252 'name' => 'context', 'value' => $this->page->context->id]);
3254 $searchinput = html_writer::tag('form', $contents, $formattrs);
3256 return html_writer::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper nav-link', 'id' => $id));
3260 * Allow plugins to provide some content to be rendered in the navbar.
3261 * The plugin must define a PLUGIN_render_navbar_output function that returns
3262 * the HTML they wish to add to the navbar.
3264 * @return string HTML for the navbar
3266 public function navbar_plugin_output() {
3267 $output = '';
3269 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3270 foreach ($pluginsfunction as $plugintype => $plugins) {
3271 foreach ($plugins as $pluginfunction) {
3272 $output .= $pluginfunction($this);
3277 return $output;
3281 * Construct a user menu, returning HTML that can be echoed out by a
3282 * layout file.
3284 * @param stdClass $user A user object, usually $USER.
3285 * @param bool $withlinks true if a dropdown should be built.
3286 * @return string HTML fragment.
3288 public function user_menu($user = null, $withlinks = null) {
3289 global $USER, $CFG;
3290 require_once($CFG->dirroot . '/user/lib.php');
3292 if (is_null($user)) {
3293 $user = $USER;
3296 // Note: this behaviour is intended to match that of core_renderer::login_info,
3297 // but should not be considered to be good practice; layout options are
3298 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3299 if (is_null($withlinks)) {
3300 $withlinks = empty($this->page->layout_options['nologinlinks']);
3303 // Add a class for when $withlinks is false.
3304 $usermenuclasses = 'usermenu';
3305 if (!$withlinks) {
3306 $usermenuclasses .= ' withoutlinks';
3309 $returnstr = "";
3311 // If during initial install, return the empty return string.
3312 if (during_initial_install()) {
3313 return $returnstr;
3316 $loginpage = $this->is_login_page();
3317 $loginurl = get_login_url();
3318 // If not logged in, show the typical not-logged-in string.
3319 if (!isloggedin()) {
3320 $returnstr = get_string('loggedinnot', 'moodle');
3321 if (!$loginpage) {
3322 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3324 return html_writer::div(
3325 html_writer::span(
3326 $returnstr,
3327 'login'
3329 $usermenuclasses
3334 // If logged in as a guest user, show a string to that effect.
3335 if (isguestuser()) {
3336 $returnstr = get_string('loggedinasguest');
3337 if (!$loginpage && $withlinks) {
3338 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3341 return html_writer::div(
3342 html_writer::span(
3343 $returnstr,
3344 'login'
3346 $usermenuclasses
3350 // Get some navigation opts.
3351 $opts = user_get_user_navigation_info($user, $this->page);
3353 $avatarclasses = "avatars";
3354 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3355 $usertextcontents = $opts->metadata['userfullname'];
3357 // Other user.
3358 if (!empty($opts->metadata['asotheruser'])) {
3359 $avatarcontents .= html_writer::span(
3360 $opts->metadata['realuseravatar'],
3361 'avatar realuser'
3363 $usertextcontents = $opts->metadata['realuserfullname'];
3364 $usertextcontents .= html_writer::tag(
3365 'span',
3366 get_string(
3367 'loggedinas',
3368 'moodle',
3369 html_writer::span(
3370 $opts->metadata['userfullname'],
3371 'value'
3374 array('class' => 'meta viewingas')
3378 // Role.
3379 if (!empty($opts->metadata['asotherrole'])) {
3380 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3381 $usertextcontents .= html_writer::span(
3382 $opts->metadata['rolename'],
3383 'meta role role-' . $role
3387 // User login failures.
3388 if (!empty($opts->metadata['userloginfail'])) {
3389 $usertextcontents .= html_writer::span(
3390 $opts->metadata['userloginfail'],
3391 'meta loginfailures'
3395 // MNet.
3396 if (!empty($opts->metadata['asmnetuser'])) {
3397 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3398 $usertextcontents .= html_writer::span(
3399 $opts->metadata['mnetidprovidername'],
3400 'meta mnet mnet-' . $mnet
3404 $returnstr .= html_writer::span(
3405 html_writer::span($usertextcontents, 'usertext mr-1') .
3406 html_writer::span($avatarcontents, $avatarclasses),
3407 'userbutton'
3410 // Create a divider (well, a filler).
3411 $divider = new action_menu_filler();
3412 $divider->primary = false;
3414 $am = new action_menu();
3415 $am->set_menu_trigger(
3416 $returnstr
3418 $am->set_alignment(action_menu::TR, action_menu::BR);
3419 $am->set_nowrap_on_items();
3420 if ($withlinks) {
3421 $navitemcount = count($opts->navitems);
3422 $idx = 0;
3423 foreach ($opts->navitems as $key => $value) {
3425 switch ($value->itemtype) {
3426 case 'divider':
3427 // If the nav item is a divider, add one and skip link processing.
3428 $am->add($divider);
3429 break;
3431 case 'invalid':
3432 // Silently skip invalid entries (should we post a notification?).
3433 break;
3435 case 'link':
3436 // Process this as a link item.
3437 $pix = null;
3438 if (isset($value->pix) && !empty($value->pix)) {
3439 $pix = new pix_icon($value->pix, $value->title, null, array('class' => 'iconsmall'));
3440 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3441 $value->title = html_writer::img(
3442 $value->imgsrc,
3443 $value->title,
3444 array('class' => 'iconsmall')
3445 ) . $value->title;
3448 $al = new action_menu_link_secondary(
3449 $value->url,
3450 $pix,
3451 $value->title,
3452 array('class' => 'icon')
3454 if (!empty($value->titleidentifier)) {
3455 $al->attributes['data-title'] = $value->titleidentifier;
3457 $am->add($al);
3458 break;
3461 $idx++;
3463 // Add dividers after the first item and before the last item.
3464 if ($idx == 1 || $idx == $navitemcount - 1) {
3465 $am->add($divider);
3470 return html_writer::div(
3471 $this->render($am),
3472 $usermenuclasses
3477 * Return the navbar content so that it can be echoed out by the layout
3479 * @return string XHTML navbar
3481 public function navbar() {
3482 $items = $this->page->navbar->get_items();
3483 $itemcount = count($items);
3484 if ($itemcount === 0) {
3485 return '';
3488 $htmlblocks = array();
3489 // Iterate the navarray and display each node
3490 $separator = get_separator();
3491 for ($i=0;$i < $itemcount;$i++) {
3492 $item = $items[$i];
3493 $item->hideicon = true;
3494 if ($i===0) {
3495 $content = html_writer::tag('li', $this->render($item));
3496 } else {
3497 $content = html_writer::tag('li', $separator.$this->render($item));
3499 $htmlblocks[] = $content;
3502 //accessibility: heading for navbar list (MDL-20446)
3503 $navbarcontent = html_writer::tag('span', get_string('pagepath'),
3504 array('class' => 'accesshide', 'id' => 'navbar-label'));
3505 $navbarcontent .= html_writer::tag('nav',
3506 html_writer::tag('ul', join('', $htmlblocks)),
3507 array('aria-labelledby' => 'navbar-label'));
3508 // XHTML
3509 return $navbarcontent;
3513 * Renders a breadcrumb navigation node object.
3515 * @param breadcrumb_navigation_node $item The navigation node to render.
3516 * @return string HTML fragment
3518 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3520 if ($item->action instanceof moodle_url) {
3521 $content = $item->get_content();
3522 $title = $item->get_title();
3523 $attributes = array();
3524 $attributes['itemprop'] = 'url';
3525 if ($title !== '') {
3526 $attributes['title'] = $title;
3528 if ($item->hidden) {
3529 $attributes['class'] = 'dimmed_text';
3531 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3532 $content = html_writer::link($item->action, $content, $attributes);
3534 $attributes = array();
3535 $attributes['itemscope'] = '';
3536 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3537 $content = html_writer::tag('span', $content, $attributes);
3539 } else {
3540 $content = $this->render_navigation_node($item);
3542 return $content;
3546 * Renders a navigation node object.
3548 * @param navigation_node $item The navigation node to render.
3549 * @return string HTML fragment
3551 protected function render_navigation_node(navigation_node $item) {
3552 $content = $item->get_content();
3553 $title = $item->get_title();
3554 if ($item->icon instanceof renderable && !$item->hideicon) {
3555 $icon = $this->render($item->icon);
3556 $content = $icon.$content; // use CSS for spacing of icons
3558 if ($item->helpbutton !== null) {
3559 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3561 if ($content === '') {
3562 return '';
3564 if ($item->action instanceof action_link) {
3565 $link = $item->action;
3566 if ($item->hidden) {
3567 $link->add_class('dimmed');
3569 if (!empty($content)) {
3570 // Providing there is content we will use that for the link content.
3571 $link->text = $content;
3573 $content = $this->render($link);
3574 } else if ($item->action instanceof moodle_url) {
3575 $attributes = array();
3576 if ($title !== '') {
3577 $attributes['title'] = $title;
3579 if ($item->hidden) {
3580 $attributes['class'] = 'dimmed_text';
3582 $content = html_writer::link($item->action, $content, $attributes);
3584 } else if (is_string($item->action) || empty($item->action)) {
3585 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3586 if ($title !== '') {
3587 $attributes['title'] = $title;
3589 if ($item->hidden) {
3590 $attributes['class'] = 'dimmed_text';
3592 $content = html_writer::tag('span', $content, $attributes);
3594 return $content;
3598 * Accessibility: Right arrow-like character is
3599 * used in the breadcrumb trail, course navigation menu
3600 * (previous/next activity), calendar, and search forum block.
3601 * If the theme does not set characters, appropriate defaults
3602 * are set automatically. Please DO NOT
3603 * use &lt; &gt; &raquo; - these are confusing for blind users.
3605 * @return string
3607 public function rarrow() {
3608 return $this->page->theme->rarrow;
3612 * Accessibility: Left arrow-like character is
3613 * used in the breadcrumb trail, course navigation menu
3614 * (previous/next activity), calendar, and search forum block.
3615 * If the theme does not set characters, appropriate defaults
3616 * are set automatically. Please DO NOT
3617 * use &lt; &gt; &raquo; - these are confusing for blind users.
3619 * @return string
3621 public function larrow() {
3622 return $this->page->theme->larrow;
3626 * Accessibility: Up arrow-like character is used in
3627 * the book heirarchical navigation.
3628 * If the theme does not set characters, appropriate defaults
3629 * are set automatically. Please DO NOT
3630 * use ^ - this is confusing for blind users.
3632 * @return string
3634 public function uarrow() {
3635 return $this->page->theme->uarrow;
3639 * Accessibility: Down arrow-like character.
3640 * If the theme does not set characters, appropriate defaults
3641 * are set automatically.
3643 * @return string
3645 public function darrow() {
3646 return $this->page->theme->darrow;
3650 * Returns the custom menu if one has been set
3652 * A custom menu can be configured by browsing to
3653 * Settings: Administration > Appearance > Themes > Theme settings
3654 * and then configuring the custommenu config setting as described.
3656 * Theme developers: DO NOT OVERRIDE! Please override function
3657 * {@link core_renderer::render_custom_menu()} instead.
3659 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3660 * @return string
3662 public function custom_menu($custommenuitems = '') {
3663 global $CFG;
3664 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3665 $custommenuitems = $CFG->custommenuitems;
3667 if (empty($custommenuitems)) {
3668 return '';
3670 $custommenu = new custom_menu($custommenuitems, current_language());
3671 return $this->render($custommenu);
3675 * Renders a custom menu object (located in outputcomponents.php)
3677 * The custom menu this method produces makes use of the YUI3 menunav widget
3678 * and requires very specific html elements and classes.
3680 * @staticvar int $menucount
3681 * @param custom_menu $menu
3682 * @return string
3684 protected function render_custom_menu(custom_menu $menu) {
3685 static $menucount = 0;
3686 // If the menu has no children return an empty string
3687 if (!$menu->has_children()) {
3688 return '';
3690 // Increment the menu count. This is used for ID's that get worked with
3691 // in JavaScript as is essential
3692 $menucount++;
3693 // Initialise this custom menu (the custom menu object is contained in javascript-static
3694 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
3695 $jscode = "(function(){{$jscode}})";
3696 $this->page->requires->yui_module('node-menunav', $jscode);
3697 // Build the root nodes as required by YUI
3698 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
3699 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3700 $content .= html_writer::start_tag('ul');
3701 // Render each child
3702 foreach ($menu->get_children() as $item) {
3703 $content .= $this->render_custom_menu_item($item);
3705 // Close the open tags
3706 $content .= html_writer::end_tag('ul');
3707 $content .= html_writer::end_tag('div');
3708 $content .= html_writer::end_tag('div');
3709 // Return the custom menu
3710 return $content;
3714 * Renders a custom menu node as part of a submenu
3716 * The custom menu this method produces makes use of the YUI3 menunav widget
3717 * and requires very specific html elements and classes.
3719 * @see core:renderer::render_custom_menu()
3721 * @staticvar int $submenucount
3722 * @param custom_menu_item $menunode
3723 * @return string
3725 protected function render_custom_menu_item(custom_menu_item $menunode) {
3726 // Required to ensure we get unique trackable id's
3727 static $submenucount = 0;
3728 if ($menunode->has_children()) {
3729 // If the child has menus render it as a sub menu
3730 $submenucount++;
3731 $content = html_writer::start_tag('li');
3732 if ($menunode->get_url() !== null) {
3733 $url = $menunode->get_url();
3734 } else {
3735 $url = '#cm_submenu_'.$submenucount;
3737 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3738 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3739 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3740 $content .= html_writer::start_tag('ul');
3741 foreach ($menunode->get_children() as $menunode) {
3742 $content .= $this->render_custom_menu_item($menunode);
3744 $content .= html_writer::end_tag('ul');
3745 $content .= html_writer::end_tag('div');
3746 $content .= html_writer::end_tag('div');
3747 $content .= html_writer::end_tag('li');
3748 } else {
3749 // The node doesn't have children so produce a final menuitem.
3750 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3751 $content = '';
3752 if (preg_match("/^#+$/", $menunode->get_text())) {
3754 // This is a divider.
3755 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3756 } else {
3757 $content = html_writer::start_tag(
3758 'li',
3759 array(
3760 'class' => 'yui3-menuitem'
3763 if ($menunode->get_url() !== null) {
3764 $url = $menunode->get_url();
3765 } else {
3766 $url = '#';
3768 $content .= html_writer::link(
3769 $url,
3770 $menunode->get_text(),
3771 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3774 $content .= html_writer::end_tag('li');
3776 // Return the sub menu
3777 return $content;
3781 * Renders theme links for switching between default and other themes.
3783 * @return string
3785 protected function theme_switch_links() {
3787 $actualdevice = core_useragent::get_device_type();
3788 $currentdevice = $this->page->devicetypeinuse;
3789 $switched = ($actualdevice != $currentdevice);
3791 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3792 // The user is using the a default device and hasn't switched so don't shown the switch
3793 // device links.
3794 return '';
3797 if ($switched) {
3798 $linktext = get_string('switchdevicerecommended');
3799 $devicetype = $actualdevice;
3800 } else {
3801 $linktext = get_string('switchdevicedefault');
3802 $devicetype = 'default';
3804 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3806 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3807 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3808 $content .= html_writer::end_tag('div');
3810 return $content;
3814 * Renders tabs
3816 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3818 * Theme developers: In order to change how tabs are displayed please override functions
3819 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3821 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3822 * @param string|null $selected which tab to mark as selected, all parent tabs will
3823 * automatically be marked as activated
3824 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3825 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3826 * @return string
3828 public final function tabtree($tabs, $selected = null, $inactive = null) {
3829 return $this->render(new tabtree($tabs, $selected, $inactive));
3833 * Renders tabtree
3835 * @param tabtree $tabtree
3836 * @return string
3838 protected function render_tabtree(tabtree $tabtree) {
3839 if (empty($tabtree->subtree)) {
3840 return '';
3842 $str = '';
3843 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
3844 $str .= $this->render_tabobject($tabtree);
3845 $str .= html_writer::end_tag('div').
3846 html_writer::tag('div', ' ', array('class' => 'clearer'));
3847 return $str;
3851 * Renders tabobject (part of tabtree)
3853 * This function is called from {@link core_renderer::render_tabtree()}
3854 * and also it calls itself when printing the $tabobject subtree recursively.
3856 * Property $tabobject->level indicates the number of row of tabs.
3858 * @param tabobject $tabobject
3859 * @return string HTML fragment
3861 protected function render_tabobject(tabobject $tabobject) {
3862 $str = '';
3864 // Print name of the current tab.
3865 if ($tabobject instanceof tabtree) {
3866 // No name for tabtree root.
3867 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3868 // Tab name without a link. The <a> tag is used for styling.
3869 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3870 } else {
3871 // Tab name with a link.
3872 if (!($tabobject->link instanceof moodle_url)) {
3873 // backward compartibility when link was passed as quoted string
3874 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3875 } else {
3876 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3880 if (empty($tabobject->subtree)) {
3881 if ($tabobject->selected) {
3882 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3884 return $str;
3887 // Print subtree.
3888 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
3889 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3890 $cnt = 0;
3891 foreach ($tabobject->subtree as $tab) {
3892 $liclass = '';
3893 if (!$cnt) {
3894 $liclass .= ' first';
3896 if ($cnt == count($tabobject->subtree) - 1) {
3897 $liclass .= ' last';
3899 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3900 $liclass .= ' onerow';
3903 if ($tab->selected) {
3904 $liclass .= ' here selected';
3905 } else if ($tab->activated) {
3906 $liclass .= ' here active';
3909 // This will recursively call function render_tabobject() for each item in subtree.
3910 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3911 $cnt++;
3913 $str .= html_writer::end_tag('ul');
3916 return $str;
3920 * Get the HTML for blocks in the given region.
3922 * @since Moodle 2.5.1 2.6
3923 * @param string $region The region to get HTML for.
3924 * @return string HTML.
3926 public function blocks($region, $classes = array(), $tag = 'aside') {
3927 $displayregion = $this->page->apply_theme_region_manipulations($region);
3928 $classes = (array)$classes;
3929 $classes[] = 'block-region';
3930 $attributes = array(
3931 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3932 'class' => join(' ', $classes),
3933 'data-blockregion' => $displayregion,
3934 'data-droptarget' => '1'
3936 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3937 $content = $this->blocks_for_region($displayregion);
3938 } else {
3939 $content = '';
3941 return html_writer::tag($tag, $content, $attributes);
3945 * Renders a custom block region.
3947 * Use this method if you want to add an additional block region to the content of the page.
3948 * Please note this should only be used in special situations.
3949 * We want to leave the theme is control where ever possible!
3951 * This method must use the same method that the theme uses within its layout file.
3952 * As such it asks the theme what method it is using.
3953 * It can be one of two values, blocks or blocks_for_region (deprecated).
3955 * @param string $regionname The name of the custom region to add.
3956 * @return string HTML for the block region.
3958 public function custom_block_region($regionname) {
3959 if ($this->page->theme->get_block_render_method() === 'blocks') {
3960 return $this->blocks($regionname);
3961 } else {
3962 return $this->blocks_for_region($regionname);
3967 * Returns the CSS classes to apply to the body tag.
3969 * @since Moodle 2.5.1 2.6
3970 * @param array $additionalclasses Any additional classes to apply.
3971 * @return string
3973 public function body_css_classes(array $additionalclasses = array()) {
3974 // Add a class for each block region on the page.
3975 // We use the block manager here because the theme object makes get_string calls.
3976 $usedregions = array();
3977 foreach ($this->page->blocks->get_regions() as $region) {
3978 $additionalclasses[] = 'has-region-'.$region;
3979 if ($this->page->blocks->region_has_content($region, $this)) {
3980 $additionalclasses[] = 'used-region-'.$region;
3981 $usedregions[] = $region;
3982 } else {
3983 $additionalclasses[] = 'empty-region-'.$region;
3985 if ($this->page->blocks->region_completely_docked($region, $this)) {
3986 $additionalclasses[] = 'docked-region-'.$region;
3989 if (!$usedregions) {
3990 // No regions means there is only content, add 'content-only' class.
3991 $additionalclasses[] = 'content-only';
3992 } else if (count($usedregions) === 1) {
3993 // Add the -only class for the only used region.
3994 $region = array_shift($usedregions);
3995 $additionalclasses[] = $region . '-only';
3997 foreach ($this->page->layout_options as $option => $value) {
3998 if ($value) {
3999 $additionalclasses[] = 'layout-option-'.$option;
4002 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
4003 return $css;
4007 * The ID attribute to apply to the body tag.
4009 * @since Moodle 2.5.1 2.6
4010 * @return string
4012 public function body_id() {
4013 return $this->page->bodyid;
4017 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4019 * @since Moodle 2.5.1 2.6
4020 * @param string|array $additionalclasses Any additional classes to give the body tag,
4021 * @return string
4023 public function body_attributes($additionalclasses = array()) {
4024 if (!is_array($additionalclasses)) {
4025 $additionalclasses = explode(' ', $additionalclasses);
4027 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4031 * Gets HTML for the page heading.
4033 * @since Moodle 2.5.1 2.6
4034 * @param string $tag The tag to encase the heading in. h1 by default.
4035 * @return string HTML.
4037 public function page_heading($tag = 'h1') {
4038 return html_writer::tag($tag, $this->page->heading);
4042 * Gets the HTML for the page heading button.
4044 * @since Moodle 2.5.1 2.6
4045 * @return string HTML.
4047 public function page_heading_button() {
4048 return $this->page->button;
4052 * Returns the Moodle docs link to use for this page.
4054 * @since Moodle 2.5.1 2.6
4055 * @param string $text
4056 * @return string
4058 public function page_doc_link($text = null) {
4059 if ($text === null) {
4060 $text = get_string('moodledocslink');
4062 $path = page_get_doc_link_path($this->page);
4063 if (!$path) {
4064 return '';
4066 return $this->doc_link($path, $text);
4070 * Returns the page heading menu.
4072 * @since Moodle 2.5.1 2.6
4073 * @return string HTML.
4075 public function page_heading_menu() {
4076 return $this->page->headingmenu;
4080 * Returns the title to use on the page.
4082 * @since Moodle 2.5.1 2.6
4083 * @return string
4085 public function page_title() {
4086 return $this->page->title;
4090 * Returns the URL for the favicon.
4092 * @since Moodle 2.5.1 2.6
4093 * @return string The favicon URL
4095 public function favicon() {
4096 return $this->image_url('favicon', 'theme');
4100 * Renders preferences groups.
4102 * @param preferences_groups $renderable The renderable
4103 * @return string The output.
4105 public function render_preferences_groups(preferences_groups $renderable) {
4106 $html = '';
4107 $html .= html_writer::start_div('row-fluid');
4108 $html .= html_writer::start_tag('div', array('class' => 'span12 preferences-groups'));
4109 $i = 0;
4110 $open = false;
4111 foreach ($renderable->groups as $group) {
4112 if ($i == 0 || $i % 3 == 0) {
4113 if ($open) {
4114 $html .= html_writer::end_tag('div');
4116 $html .= html_writer::start_tag('div', array('class' => 'row-fluid'));
4117 $open = true;
4119 $html .= $this->render($group);
4120 $i++;
4123 $html .= html_writer::end_tag('div');
4125 $html .= html_writer::end_tag('ul');
4126 $html .= html_writer::end_tag('div');
4127 $html .= html_writer::end_div();
4128 return $html;
4132 * Renders preferences group.
4134 * @param preferences_group $renderable The renderable
4135 * @return string The output.
4137 public function render_preferences_group(preferences_group $renderable) {
4138 $html = '';
4139 $html .= html_writer::start_tag('div', array('class' => 'span4 preferences-group'));
4140 $html .= $this->heading($renderable->title, 3);
4141 $html .= html_writer::start_tag('ul');
4142 foreach ($renderable->nodes as $node) {
4143 if ($node->has_children()) {
4144 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4146 $html .= html_writer::tag('li', $this->render($node));
4148 $html .= html_writer::end_tag('ul');
4149 $html .= html_writer::end_tag('div');
4150 return $html;
4153 public function context_header($headerinfo = null, $headinglevel = 1) {
4154 global $DB, $USER, $CFG;
4155 require_once($CFG->dirroot . '/user/lib.php');
4156 $context = $this->page->context;
4157 $heading = null;
4158 $imagedata = null;
4159 $subheader = null;
4160 $userbuttons = null;
4161 // Make sure to use the heading if it has been set.
4162 if (isset($headerinfo['heading'])) {
4163 $heading = $headerinfo['heading'];
4165 // The user context currently has images and buttons. Other contexts may follow.
4166 if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
4167 if (isset($headerinfo['user'])) {
4168 $user = $headerinfo['user'];
4169 } else {
4170 // Look up the user information if it is not supplied.
4171 $user = $DB->get_record('user', array('id' => $context->instanceid));
4174 // If the user context is set, then use that for capability checks.
4175 if (isset($headerinfo['usercontext'])) {
4176 $context = $headerinfo['usercontext'];
4179 // Only provide user information if the user is the current user, or a user which the current user can view.
4180 // When checking user_can_view_profile(), either:
4181 // If the page context is course, check the course context (from the page object) or;
4182 // If page context is NOT course, then check across all courses.
4183 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4185 if (user_can_view_profile($user, $course)) {
4186 // Use the user's full name if the heading isn't set.
4187 if (!isset($heading)) {
4188 $heading = fullname($user);
4191 $imagedata = $this->user_picture($user, array('size' => 100));
4193 // Check to see if we should be displaying a message button.
4194 if (!empty($CFG->messaging) && $USER->id != $user->id && has_capability('moodle/site:sendmessage', $context)) {
4195 $iscontact = !empty(message_get_contact($user->id));
4196 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4197 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4198 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4199 $userbuttons = array(
4200 'messages' => array(
4201 'buttontype' => 'message',
4202 'title' => get_string('message', 'message'),
4203 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4204 'image' => 'message',
4205 'linkattributes' => array('role' => 'button'),
4206 'page' => $this->page
4208 'togglecontact' => array(
4209 'buttontype' => 'togglecontact',
4210 'title' => get_string($contacttitle, 'message'),
4211 'url' => new moodle_url('/message/index.php', array(
4212 'user1' => $USER->id,
4213 'user2' => $user->id,
4214 $contacturlaction => $user->id,
4215 'sesskey' => sesskey())
4217 'image' => $contactimage,
4218 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4219 'page' => $this->page
4223 $this->page->requires->string_for_js('changesmadereallygoaway', 'moodle');
4225 } else {
4226 $heading = null;
4230 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4231 return $this->render_context_header($contextheader);
4235 * Renders the skip links for the page.
4237 * @param array $links List of skip links.
4238 * @return string HTML for the skip links.
4240 public function render_skip_links($links) {
4241 $context = [ 'links' => []];
4243 foreach ($links as $url => $text) {
4244 $context['links'][] = [ 'url' => $url, 'text' => $text];
4247 return $this->render_from_template('core/skip_links', $context);
4251 * Renders the header bar.
4253 * @param context_header $contextheader Header bar object.
4254 * @return string HTML for the header bar.
4256 protected function render_context_header(context_header $contextheader) {
4258 // All the html stuff goes here.
4259 $html = html_writer::start_div('page-context-header');
4261 // Image data.
4262 if (isset($contextheader->imagedata)) {
4263 // Header specific image.
4264 $html .= html_writer::div($contextheader->imagedata, 'page-header-image');
4267 // Headings.
4268 if (!isset($contextheader->heading)) {
4269 $headings = $this->heading($this->page->heading, $contextheader->headinglevel);
4270 } else {
4271 $headings = $this->heading($contextheader->heading, $contextheader->headinglevel);
4274 $html .= html_writer::tag('div', $headings, array('class' => 'page-header-headings'));
4276 // Buttons.
4277 if (isset($contextheader->additionalbuttons)) {
4278 $html .= html_writer::start_div('btn-group header-button-group');
4279 foreach ($contextheader->additionalbuttons as $button) {
4280 if (!isset($button->page)) {
4281 // Include js for messaging.
4282 if ($button['buttontype'] === 'togglecontact') {
4283 \core_message\helper::togglecontact_requirejs();
4285 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4286 'class' => 'iconsmall',
4287 'role' => 'presentation'
4289 $image .= html_writer::span($button['title'], 'header-button-title');
4290 } else {
4291 $image = html_writer::empty_tag('img', array(
4292 'src' => $button['formattedimage'],
4293 'role' => 'presentation'
4296 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4298 $html .= html_writer::end_div();
4300 $html .= html_writer::end_div();
4302 return $html;
4306 * Wrapper for header elements.
4308 * @return string HTML to display the main header.
4310 public function full_header() {
4311 $html = html_writer::start_tag('header', array('id' => 'page-header', 'class' => 'clearfix'));
4312 $html .= $this->context_header();
4313 $html .= html_writer::start_div('clearfix', array('id' => 'page-navbar'));
4314 $html .= html_writer::tag('div', $this->navbar(), array('class' => 'breadcrumb-nav'));
4315 $html .= html_writer::div($this->page_heading_button(), 'breadcrumb-button');
4316 $html .= html_writer::end_div();
4317 $html .= html_writer::tag('div', $this->course_header(), array('id' => 'course-header'));
4318 $html .= html_writer::end_tag('header');
4319 return $html;
4323 * Displays the list of tags associated with an entry
4325 * @param array $tags list of instances of core_tag or stdClass
4326 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4327 * to use default, set to '' (empty string) to omit the label completely
4328 * @param string $classes additional classes for the enclosing div element
4329 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4330 * will be appended to the end, JS will toggle the rest of the tags
4331 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4332 * @return string
4334 public function tag_list($tags, $label = null, $classes = '', $limit = 10, $pagecontext = null) {
4335 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext);
4336 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4340 * Renders element for inline editing of any value
4342 * @param \core\output\inplace_editable $element
4343 * @return string
4345 public function render_inplace_editable(\core\output\inplace_editable $element) {
4346 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4350 * Renders a bar chart.
4352 * @param \core\chart_bar $chart The chart.
4353 * @return string.
4355 public function render_chart_bar(\core\chart_bar $chart) {
4356 return $this->render_chart($chart);
4360 * Renders a line chart.
4362 * @param \core\chart_line $chart The chart.
4363 * @return string.
4365 public function render_chart_line(\core\chart_line $chart) {
4366 return $this->render_chart($chart);
4370 * Renders a pie chart.
4372 * @param \core\chart_pie $chart The chart.
4373 * @return string.
4375 public function render_chart_pie(\core\chart_pie $chart) {
4376 return $this->render_chart($chart);
4380 * Renders a chart.
4382 * @param \core\chart_base $chart The chart.
4383 * @param bool $withtable Whether to include a data table with the chart.
4384 * @return string.
4386 public function render_chart(\core\chart_base $chart, $withtable = true) {
4387 $chartdata = json_encode($chart);
4388 return $this->render_from_template('core/chart', (object) [
4389 'chartdata' => $chartdata,
4390 'withtable' => $withtable
4395 * Renders the login form.
4397 * @param \core_auth\output\login $form The renderable.
4398 * @return string
4400 public function render_login(\core_auth\output\login $form) {
4401 $context = $form->export_for_template($this);
4403 // Override because rendering is not supported in template yet.
4404 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
4405 $context->errorformatted = $this->error_text($context->error);
4407 return $this->render_from_template('core/loginform', $context);
4411 * Renders an mform element from a template.
4413 * @param HTML_QuickForm_element $element element
4414 * @param bool $required if input is required field
4415 * @param bool $advanced if input is an advanced field
4416 * @param string $error error message to display
4417 * @param bool $ingroup True if this element is rendered as part of a group
4418 * @return mixed string|bool
4420 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4421 $templatename = 'core_form/element-' . $element->getType();
4422 if ($ingroup) {
4423 $templatename .= "-inline";
4425 try {
4426 // We call this to generate a file not found exception if there is no template.
4427 // We don't want to call export_for_template if there is no template.
4428 core\output\mustache_template_finder::get_template_filepath($templatename);
4430 if ($element instanceof templatable) {
4431 $elementcontext = $element->export_for_template($this);
4433 $helpbutton = '';
4434 if (method_exists($element, 'getHelpButton')) {
4435 $helpbutton = $element->getHelpButton();
4437 $label = $element->getLabel();
4438 $text = '';
4439 if (method_exists($element, 'getText')) {
4440 // There currently exists code that adds a form element with an empty label.
4441 // If this is the case then set the label to the description.
4442 if (empty($label)) {
4443 $label = $element->getText();
4444 } else {
4445 $text = $element->getText();
4449 $context = array(
4450 'element' => $elementcontext,
4451 'label' => $label,
4452 'text' => $text,
4453 'required' => $required,
4454 'advanced' => $advanced,
4455 'helpbutton' => $helpbutton,
4456 'error' => $error
4458 return $this->render_from_template($templatename, $context);
4460 } catch (Exception $e) {
4461 // No template for this element.
4462 return false;
4467 * Render the login signup form into a nice template for the theme.
4469 * @param mform $form
4470 * @return string
4472 public function render_login_signup_form($form) {
4473 $context = $form->export_for_template($this);
4475 return $this->render_from_template('core/signup_form_layout', $context);
4479 * Render the verify age and location page into a nice template for the theme.
4481 * @param \core_auth\output\verify_age_location_page $page The renderable
4482 * @return string
4484 protected function render_verify_age_location_page($page) {
4485 $context = $page->export_for_template($this);
4487 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4491 * Render the digital minor contact information page into a nice template for the theme.
4493 * @param \core_auth\output\digital_minor_page $page The renderable
4494 * @return string
4496 protected function render_digital_minor_page($page) {
4497 $context = $page->export_for_template($this);
4499 return $this->render_from_template('core/auth_digital_minor_page', $context);
4503 * Renders a progress bar.
4505 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4507 * @param progress_bar $bar The bar.
4508 * @return string HTML fragment
4510 public function render_progress_bar(progress_bar $bar) {
4511 global $PAGE;
4512 $data = $bar->export_for_template($this);
4513 return $this->render_from_template('core/progress_bar', $data);
4518 * A renderer that generates output for command-line scripts.
4520 * The implementation of this renderer is probably incomplete.
4522 * @copyright 2009 Tim Hunt
4523 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4524 * @since Moodle 2.0
4525 * @package core
4526 * @category output
4528 class core_renderer_cli extends core_renderer {
4531 * Returns the page header.
4533 * @return string HTML fragment
4535 public function header() {
4536 return $this->page->heading . "\n";
4540 * Returns a template fragment representing a Heading.
4542 * @param string $text The text of the heading
4543 * @param int $level The level of importance of the heading
4544 * @param string $classes A space-separated list of CSS classes
4545 * @param string $id An optional ID
4546 * @return string A template fragment for a heading
4548 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4549 $text .= "\n";
4550 switch ($level) {
4551 case 1:
4552 return '=>' . $text;
4553 case 2:
4554 return '-->' . $text;
4555 default:
4556 return $text;
4561 * Returns a template fragment representing a fatal error.
4563 * @param string $message The message to output
4564 * @param string $moreinfourl URL where more info can be found about the error
4565 * @param string $link Link for the Continue button
4566 * @param array $backtrace The execution backtrace
4567 * @param string $debuginfo Debugging information
4568 * @return string A template fragment for a fatal error
4570 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4571 global $CFG;
4573 $output = "!!! $message !!!\n";
4575 if ($CFG->debugdeveloper) {
4576 if (!empty($debuginfo)) {
4577 $output .= $this->notification($debuginfo, 'notifytiny');
4579 if (!empty($backtrace)) {
4580 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
4584 return $output;
4588 * Returns a template fragment representing a notification.
4590 * @param string $message The message to print out.
4591 * @param string $type The type of notification. See constants on \core\output\notification.
4592 * @return string A template fragment for a notification
4594 public function notification($message, $type = null) {
4595 $message = clean_text($message);
4596 if ($type === 'notifysuccess' || $type === 'success') {
4597 return "++ $message ++\n";
4599 return "!! $message !!\n";
4603 * There is no footer for a cli request, however we must override the
4604 * footer method to prevent the default footer.
4606 public function footer() {}
4609 * Render a notification (that is, a status message about something that has
4610 * just happened).
4612 * @param \core\output\notification $notification the notification to print out
4613 * @return string plain text output
4615 public function render_notification(\core\output\notification $notification) {
4616 return $this->notification($notification->get_message(), $notification->get_message_type());
4622 * A renderer that generates output for ajax scripts.
4624 * This renderer prevents accidental sends back only json
4625 * encoded error messages, all other output is ignored.
4627 * @copyright 2010 Petr Skoda
4628 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4629 * @since Moodle 2.0
4630 * @package core
4631 * @category output
4633 class core_renderer_ajax extends core_renderer {
4636 * Returns a template fragment representing a fatal error.
4638 * @param string $message The message to output
4639 * @param string $moreinfourl URL where more info can be found about the error
4640 * @param string $link Link for the Continue button
4641 * @param array $backtrace The execution backtrace
4642 * @param string $debuginfo Debugging information
4643 * @return string A template fragment for a fatal error
4645 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4646 global $CFG;
4648 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
4650 $e = new stdClass();
4651 $e->error = $message;
4652 $e->errorcode = $errorcode;
4653 $e->stacktrace = NULL;
4654 $e->debuginfo = NULL;
4655 $e->reproductionlink = NULL;
4656 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
4657 $link = (string) $link;
4658 if ($link) {
4659 $e->reproductionlink = $link;
4661 if (!empty($debuginfo)) {
4662 $e->debuginfo = $debuginfo;
4664 if (!empty($backtrace)) {
4665 $e->stacktrace = format_backtrace($backtrace, true);
4668 $this->header();
4669 return json_encode($e);
4673 * Used to display a notification.
4674 * For the AJAX notifications are discarded.
4676 * @param string $message The message to print out.
4677 * @param string $type The type of notification. See constants on \core\output\notification.
4679 public function notification($message, $type = null) {}
4682 * Used to display a redirection message.
4683 * AJAX redirections should not occur and as such redirection messages
4684 * are discarded.
4686 * @param moodle_url|string $encodedurl
4687 * @param string $message
4688 * @param int $delay
4689 * @param bool $debugdisableredirect
4690 * @param string $messagetype The type of notification to show the message in.
4691 * See constants on \core\output\notification.
4693 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
4694 $messagetype = \core\output\notification::NOTIFY_INFO) {}
4697 * Prepares the start of an AJAX output.
4699 public function header() {
4700 // unfortunately YUI iframe upload does not support application/json
4701 if (!empty($_FILES)) {
4702 @header('Content-type: text/plain; charset=utf-8');
4703 if (!core_useragent::supports_json_contenttype()) {
4704 @header('X-Content-Type-Options: nosniff');
4706 } else if (!core_useragent::supports_json_contenttype()) {
4707 @header('Content-type: text/plain; charset=utf-8');
4708 @header('X-Content-Type-Options: nosniff');
4709 } else {
4710 @header('Content-type: application/json; charset=utf-8');
4713 // Headers to make it not cacheable and json
4714 @header('Cache-Control: no-store, no-cache, must-revalidate');
4715 @header('Cache-Control: post-check=0, pre-check=0', false);
4716 @header('Pragma: no-cache');
4717 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
4718 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
4719 @header('Accept-Ranges: none');
4723 * There is no footer for an AJAX request, however we must override the
4724 * footer method to prevent the default footer.
4726 public function footer() {}
4729 * No need for headers in an AJAX request... this should never happen.
4730 * @param string $text
4731 * @param int $level
4732 * @param string $classes
4733 * @param string $id
4735 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
4740 * Renderer for media files.
4742 * Used in file resources, media filter, and any other places that need to
4743 * output embedded media.
4745 * @deprecated since Moodle 3.2
4746 * @copyright 2011 The Open University
4747 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4749 class core_media_renderer extends plugin_renderer_base {
4750 /** @var array Array of available 'player' objects */
4751 private $players;
4752 /** @var string Regex pattern for links which may contain embeddable content */
4753 private $embeddablemarkers;
4756 * Constructor
4758 * This is needed in the constructor (not later) so that you can use the
4759 * constants and static functions that are defined in core_media class
4760 * before you call renderer functions.
4762 public function __construct() {
4763 debugging('Class core_media_renderer is deprecated, please use core_media_manager::instance()', DEBUG_DEVELOPER);
4767 * Renders a media file (audio or video) using suitable embedded player.
4769 * See embed_alternatives function for full description of parameters.
4770 * This function calls through to that one.
4772 * When using this function you can also specify width and height in the
4773 * URL by including ?d=100x100 at the end. If specified in the URL, this
4774 * will override the $width and $height parameters.
4776 * @param moodle_url $url Full URL of media file
4777 * @param string $name Optional user-readable name to display in download link
4778 * @param int $width Width in pixels (optional)
4779 * @param int $height Height in pixels (optional)
4780 * @param array $options Array of key/value pairs
4781 * @return string HTML content of embed
4783 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
4784 $options = array()) {
4785 return core_media_manager::instance()->embed_url($url, $name, $width, $height, $options);
4789 * Renders media files (audio or video) using suitable embedded player.
4790 * The list of URLs should be alternative versions of the same content in
4791 * multiple formats. If there is only one format it should have a single
4792 * entry.
4794 * If the media files are not in a supported format, this will give students
4795 * a download link to each format. The download link uses the filename
4796 * unless you supply the optional name parameter.
4798 * Width and height are optional. If specified, these are suggested sizes
4799 * and should be the exact values supplied by the user, if they come from
4800 * user input. These will be treated as relating to the size of the video
4801 * content, not including any player control bar.
4803 * For audio files, height will be ignored. For video files, a few formats
4804 * work if you specify only width, but in general if you specify width
4805 * you must specify height as well.
4807 * The $options array is passed through to the core_media_player classes
4808 * that render the object tag. The keys can contain values from
4809 * core_media::OPTION_xx.
4811 * @param array $alternatives Array of moodle_url to media files
4812 * @param string $name Optional user-readable name to display in download link
4813 * @param int $width Width in pixels (optional)
4814 * @param int $height Height in pixels (optional)
4815 * @param array $options Array of key/value pairs
4816 * @return string HTML content of embed
4818 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
4819 $options = array()) {
4820 return core_media_manager::instance()->embed_alternatives($alternatives, $name, $width, $height, $options);
4824 * Checks whether a file can be embedded. If this returns true you will get
4825 * an embedded player; if this returns false, you will just get a download
4826 * link.
4828 * This is a wrapper for can_embed_urls.
4830 * @param moodle_url $url URL of media file
4831 * @param array $options Options (same as when embedding)
4832 * @return bool True if file can be embedded
4834 public function can_embed_url(moodle_url $url, $options = array()) {
4835 return core_media_manager::instance()->can_embed_url($url, $options);
4839 * Checks whether a file can be embedded. If this returns true you will get
4840 * an embedded player; if this returns false, you will just get a download
4841 * link.
4843 * @param array $urls URL of media file and any alternatives (moodle_url)
4844 * @param array $options Options (same as when embedding)
4845 * @return bool True if file can be embedded
4847 public function can_embed_urls(array $urls, $options = array()) {
4848 return core_media_manager::instance()->can_embed_urls($urls, $options);
4852 * Obtains a list of markers that can be used in a regular expression when
4853 * searching for URLs that can be embedded by any player type.
4855 * This string is used to improve peformance of regex matching by ensuring
4856 * that the (presumably C) regex code can do a quick keyword check on the
4857 * URL part of a link to see if it matches one of these, rather than having
4858 * to go into PHP code for every single link to see if it can be embedded.
4860 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
4862 public function get_embeddable_markers() {
4863 return core_media_manager::instance()->get_embeddable_markers();
4868 * The maintenance renderer.
4870 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
4871 * is running a maintenance related task.
4872 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
4874 * @since Moodle 2.6
4875 * @package core
4876 * @category output
4877 * @copyright 2013 Sam Hemelryk
4878 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4880 class core_renderer_maintenance extends core_renderer {
4883 * Initialises the renderer instance.
4884 * @param moodle_page $page
4885 * @param string $target
4886 * @throws coding_exception
4888 public function __construct(moodle_page $page, $target) {
4889 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
4890 throw new coding_exception('Invalid request for the maintenance renderer.');
4892 parent::__construct($page, $target);
4896 * Does nothing. The maintenance renderer cannot produce blocks.
4898 * @param block_contents $bc
4899 * @param string $region
4900 * @return string
4902 public function block(block_contents $bc, $region) {
4903 // Computer says no blocks.
4904 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4905 return '';
4909 * Does nothing. The maintenance renderer cannot produce blocks.
4911 * @param string $region
4912 * @param array $classes
4913 * @param string $tag
4914 * @return string
4916 public function blocks($region, $classes = array(), $tag = 'aside') {
4917 // Computer says no blocks.
4918 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4919 return '';
4923 * Does nothing. The maintenance renderer cannot produce blocks.
4925 * @param string $region
4926 * @return string
4928 public function blocks_for_region($region) {
4929 // Computer says no blocks for region.
4930 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4931 return '';
4935 * Does nothing. The maintenance renderer cannot produce a course content header.
4937 * @param bool $onlyifnotcalledbefore
4938 * @return string
4940 public function course_content_header($onlyifnotcalledbefore = false) {
4941 // Computer says no course content header.
4942 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4943 return '';
4947 * Does nothing. The maintenance renderer cannot produce a course content footer.
4949 * @param bool $onlyifnotcalledbefore
4950 * @return string
4952 public function course_content_footer($onlyifnotcalledbefore = false) {
4953 // Computer says no course content footer.
4954 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4955 return '';
4959 * Does nothing. The maintenance renderer cannot produce a course header.
4961 * @return string
4963 public function course_header() {
4964 // Computer says no course header.
4965 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4966 return '';
4970 * Does nothing. The maintenance renderer cannot produce a course footer.
4972 * @return string
4974 public function course_footer() {
4975 // Computer says no course footer.
4976 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4977 return '';
4981 * Does nothing. The maintenance renderer cannot produce a custom menu.
4983 * @param string $custommenuitems
4984 * @return string
4986 public function custom_menu($custommenuitems = '') {
4987 // Computer says no custom menu.
4988 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4989 return '';
4993 * Does nothing. The maintenance renderer cannot produce a file picker.
4995 * @param array $options
4996 * @return string
4998 public function file_picker($options) {
4999 // Computer says no file picker.
5000 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5001 return '';
5005 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
5007 * @param array $dir
5008 * @return string
5010 public function htmllize_file_tree($dir) {
5011 // Hell no we don't want no htmllized file tree.
5012 // Also why on earth is this function on the core renderer???
5013 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5014 return '';
5019 * Overridden confirm message for upgrades.
5021 * @param string $message The question to ask the user
5022 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5023 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5024 * @return string HTML fragment
5026 public function confirm($message, $continue, $cancel) {
5027 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5028 // from any previous version of Moodle).
5029 if ($continue instanceof single_button) {
5030 $continue->primary = true;
5031 } else if (is_string($continue)) {
5032 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
5033 } else if ($continue instanceof moodle_url) {
5034 $continue = new single_button($continue, get_string('continue'), 'post', true);
5035 } else {
5036 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5037 ' (string/moodle_url) or a single_button instance.');
5040 if ($cancel instanceof single_button) {
5041 $output = '';
5042 } else if (is_string($cancel)) {
5043 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5044 } else if ($cancel instanceof moodle_url) {
5045 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5046 } else {
5047 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5048 ' (string/moodle_url) or a single_button instance.');
5051 $output = $this->box_start('generalbox', 'notice');
5052 $output .= html_writer::tag('h4', get_string('confirm'));
5053 $output .= html_writer::tag('p', $message);
5054 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
5055 $output .= $this->box_end();
5056 return $output;
5060 * Does nothing. The maintenance renderer does not support JS.
5062 * @param block_contents $bc
5064 public function init_block_hider_js(block_contents $bc) {
5065 // Computer says no JavaScript.
5066 // Do nothing, ridiculous method.
5070 * Does nothing. The maintenance renderer cannot produce language menus.
5072 * @return string
5074 public function lang_menu() {
5075 // Computer says no lang menu.
5076 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5077 return '';
5081 * Does nothing. The maintenance renderer has no need for login information.
5083 * @param null $withlinks
5084 * @return string
5086 public function login_info($withlinks = null) {
5087 // Computer says no login info.
5088 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5089 return '';
5093 * Does nothing. The maintenance renderer cannot produce user pictures.
5095 * @param stdClass $user
5096 * @param array $options
5097 * @return string
5099 public function user_picture(stdClass $user, array $options = null) {
5100 // Computer says no user pictures.
5101 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5102 return '';