NOBUG: Fixed file access permissions
[moodle.git] / lib / outputrenderers.php
blob4be95a1c6030919860d2b1a9e1297195156b9544
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 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
89 $loader = new \core\output\mustache_filesystem_loader();
90 $stringhelper = new \core\output\mustache_string_helper();
91 $quotehelper = new \core\output\mustache_quote_helper();
92 $jshelper = new \core\output\mustache_javascript_helper($this->page);
93 $pixhelper = new \core\output\mustache_pix_helper($this);
94 $shortentexthelper = new \core\output\mustache_shorten_text_helper();
95 $userdatehelper = new \core\output\mustache_user_date_helper();
97 // We only expose the variables that are exposed to JS templates.
98 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
100 $helpers = array('config' => $safeconfig,
101 'str' => array($stringhelper, 'str'),
102 'quote' => array($quotehelper, 'quote'),
103 'js' => array($jshelper, 'help'),
104 'pix' => array($pixhelper, 'pix'),
105 'shortentext' => array($shortentexthelper, 'shorten'),
106 'userdate' => array($userdatehelper, 'transform'),
109 $this->mustache = new Mustache_Engine(array(
110 'cache' => $cachedir,
111 'escape' => 's',
112 'loader' => $loader,
113 'helpers' => $helpers,
114 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS]));
118 return $this->mustache;
123 * Constructor
125 * The constructor takes two arguments. The first is the page that the renderer
126 * has been created to assist with, and the second is the target.
127 * The target is an additional identifier that can be used to load different
128 * renderers for different options.
130 * @param moodle_page $page the page we are doing output for.
131 * @param string $target one of rendering target constants
133 public function __construct(moodle_page $page, $target) {
134 $this->opencontainers = $page->opencontainers;
135 $this->page = $page;
136 $this->target = $target;
140 * Renders a template by name with the given context.
142 * The provided data needs to be array/stdClass made up of only simple types.
143 * Simple types are array,stdClass,bool,int,float,string
145 * @since 2.9
146 * @param array|stdClass $context Context containing data for the template.
147 * @return string|boolean
149 public function render_from_template($templatename, $context) {
150 static $templatecache = array();
151 $mustache = $this->get_mustache();
153 try {
154 // Grab a copy of the existing helper to be restored later.
155 $uniqidhelper = $mustache->getHelper('uniqid');
156 } catch (Mustache_Exception_UnknownHelperException $e) {
157 // Helper doesn't exist.
158 $uniqidhelper = null;
161 // Provide 1 random value that will not change within a template
162 // but will be different from template to template. This is useful for
163 // e.g. aria attributes that only work with id attributes and must be
164 // unique in a page.
165 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
166 if (isset($templatecache[$templatename])) {
167 $template = $templatecache[$templatename];
168 } else {
169 try {
170 $template = $mustache->loadTemplate($templatename);
171 $templatecache[$templatename] = $template;
172 } catch (Mustache_Exception_UnknownTemplateException $e) {
173 throw new moodle_exception('Unknown template: ' . $templatename);
177 $renderedtemplate = trim($template->render($context));
179 // If we had an existing uniqid helper then we need to restore it to allow
180 // handle nested calls of render_from_template.
181 if ($uniqidhelper) {
182 $mustache->addHelper('uniqid', $uniqidhelper);
185 return $renderedtemplate;
190 * Returns rendered widget.
192 * The provided widget needs to be an object that extends the renderable
193 * interface.
194 * If will then be rendered by a method based upon the classname for the widget.
195 * For instance a widget of class `crazywidget` will be rendered by a protected
196 * render_crazywidget method of this renderer.
197 * If no render_crazywidget method exists and crazywidget implements templatable,
198 * look for the 'crazywidget' template in the same component and render that.
200 * @param renderable $widget instance with renderable interface
201 * @return string
203 public function render(renderable $widget) {
204 $classparts = explode('\\', get_class($widget));
205 // Strip namespaces.
206 $classname = array_pop($classparts);
207 // Remove _renderable suffixes
208 $classname = preg_replace('/_renderable$/', '', $classname);
210 $rendermethod = 'render_'.$classname;
211 if (method_exists($this, $rendermethod)) {
212 return $this->$rendermethod($widget);
214 if ($widget instanceof templatable) {
215 $component = array_shift($classparts);
216 if (!$component) {
217 $component = 'core';
219 $template = $component . '/' . $classname;
220 $context = $widget->export_for_template($this);
221 return $this->render_from_template($template, $context);
223 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
227 * Adds a JS action for the element with the provided id.
229 * This method adds a JS event for the provided component action to the page
230 * and then returns the id that the event has been attached to.
231 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
233 * @param component_action $action
234 * @param string $id
235 * @return string id of element, either original submitted or random new if not supplied
237 public function add_action_handler(component_action $action, $id = null) {
238 if (!$id) {
239 $id = html_writer::random_id($action->event);
241 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
242 return $id;
246 * Returns true is output has already started, and false if not.
248 * @return boolean true if the header has been printed.
250 public function has_started() {
251 return $this->page->state >= moodle_page::STATE_IN_BODY;
255 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
257 * @param mixed $classes Space-separated string or array of classes
258 * @return string HTML class attribute value
260 public static function prepare_classes($classes) {
261 if (is_array($classes)) {
262 return implode(' ', array_unique($classes));
264 return $classes;
268 * Return the direct URL for an image from the pix folder.
270 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
272 * @deprecated since Moodle 3.3
273 * @param string $imagename the name of the icon.
274 * @param string $component specification of one plugin like in get_string()
275 * @return moodle_url
277 public function pix_url($imagename, $component = 'moodle') {
278 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
279 return $this->page->theme->image_url($imagename, $component);
283 * Return the moodle_url for an image.
285 * The exact image location and extension is determined
286 * automatically by searching for gif|png|jpg|jpeg, please
287 * note there can not be diferent images with the different
288 * extension. The imagename is for historical reasons
289 * a relative path name, it may be changed later for core
290 * images. It is recommended to not use subdirectories
291 * in plugin and theme pix directories.
293 * There are three types of images:
294 * 1/ theme images - stored in theme/mytheme/pix/,
295 * use component 'theme'
296 * 2/ core images - stored in /pix/,
297 * overridden via theme/mytheme/pix_core/
298 * 3/ plugin images - stored in mod/mymodule/pix,
299 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
300 * example: image_url('comment', 'mod_glossary')
302 * @param string $imagename the pathname of the image
303 * @param string $component full plugin name (aka component) or 'theme'
304 * @return moodle_url
306 public function image_url($imagename, $component = 'moodle') {
307 return $this->page->theme->image_url($imagename, $component);
311 * Return the site's logo URL, if any.
313 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
314 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
315 * @return moodle_url|false
317 public function get_logo_url($maxwidth = null, $maxheight = 200) {
318 global $CFG;
319 $logo = get_config('core_admin', 'logo');
320 if (empty($logo)) {
321 return false;
324 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
325 // It's not worth the overhead of detecting and serving 2 different images based on the device.
327 // Hide the requested size in the file path.
328 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
330 // Use $CFG->themerev to prevent browser caching when the file changes.
331 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
332 theme_get_revision(), $logo);
336 * Return the site's compact logo URL, if any.
338 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
339 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
340 * @return moodle_url|false
342 public function get_compact_logo_url($maxwidth = 100, $maxheight = 100) {
343 global $CFG;
344 $logo = get_config('core_admin', 'logocompact');
345 if (empty($logo)) {
346 return false;
349 // Hide the requested size in the file path.
350 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
352 // Use $CFG->themerev to prevent browser caching when the file changes.
353 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
354 theme_get_revision(), $logo);
361 * Basis for all plugin renderers.
363 * @copyright Petr Skoda (skodak)
364 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
365 * @since Moodle 2.0
366 * @package core
367 * @category output
369 class plugin_renderer_base extends renderer_base {
372 * @var renderer_base|core_renderer A reference to the current renderer.
373 * The renderer provided here will be determined by the page but will in 90%
374 * of cases by the {@link core_renderer}
376 protected $output;
379 * Constructor method, calls the parent constructor
381 * @param moodle_page $page
382 * @param string $target one of rendering target constants
384 public function __construct(moodle_page $page, $target) {
385 if (empty($target) && $page->pagelayout === 'maintenance') {
386 // If the page is using the maintenance layout then we're going to force the target to maintenance.
387 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
388 // unavailable for this page layout.
389 $target = RENDERER_TARGET_MAINTENANCE;
391 $this->output = $page->get_renderer('core', null, $target);
392 parent::__construct($page, $target);
396 * Renders the provided widget and returns the HTML to display it.
398 * @param renderable $widget instance with renderable interface
399 * @return string
401 public function render(renderable $widget) {
402 $classname = get_class($widget);
403 // Strip namespaces.
404 $classname = preg_replace('/^.*\\\/', '', $classname);
405 // Keep a copy at this point, we may need to look for a deprecated method.
406 $deprecatedmethod = 'render_'.$classname;
407 // Remove _renderable suffixes
408 $classname = preg_replace('/_renderable$/', '', $classname);
410 $rendermethod = 'render_'.$classname;
411 if (method_exists($this, $rendermethod)) {
412 return $this->$rendermethod($widget);
414 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
415 // This is exactly where we don't want to be.
416 // If you have arrived here you have a renderable component within your plugin that has the name
417 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
418 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
419 // and the _renderable suffix now gets removed when looking for a render method.
420 // You need to change your renderers render_blah_renderable to render_blah.
421 // Until you do this it will not be possible for a theme to override the renderer to override your method.
422 // Please do it ASAP.
423 static $debugged = array();
424 if (!isset($debugged[$deprecatedmethod])) {
425 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
426 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
427 $debugged[$deprecatedmethod] = true;
429 return $this->$deprecatedmethod($widget);
431 // pass to core renderer if method not found here
432 return $this->output->render($widget);
436 * Magic method used to pass calls otherwise meant for the standard renderer
437 * to it to ensure we don't go causing unnecessary grief.
439 * @param string $method
440 * @param array $arguments
441 * @return mixed
443 public function __call($method, $arguments) {
444 if (method_exists('renderer_base', $method)) {
445 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
447 if (method_exists($this->output, $method)) {
448 return call_user_func_array(array($this->output, $method), $arguments);
449 } else {
450 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
457 * The standard implementation of the core_renderer interface.
459 * @copyright 2009 Tim Hunt
460 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
461 * @since Moodle 2.0
462 * @package core
463 * @category output
465 class core_renderer extends renderer_base {
467 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
468 * in layout files instead.
469 * @deprecated
470 * @var string used in {@link core_renderer::header()}.
472 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
475 * @var string Used to pass information from {@link core_renderer::doctype()} to
476 * {@link core_renderer::standard_head_html()}.
478 protected $contenttype;
481 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
482 * with {@link core_renderer::header()}.
484 protected $metarefreshtag = '';
487 * @var string Unique token for the closing HTML
489 protected $unique_end_html_token;
492 * @var string Unique token for performance information
494 protected $unique_performance_info_token;
497 * @var string Unique token for the main content.
499 protected $unique_main_content_token;
502 * Constructor
504 * @param moodle_page $page the page we are doing output for.
505 * @param string $target one of rendering target constants
507 public function __construct(moodle_page $page, $target) {
508 $this->opencontainers = $page->opencontainers;
509 $this->page = $page;
510 $this->target = $target;
512 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
513 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
514 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
518 * Get the DOCTYPE declaration that should be used with this page. Designed to
519 * be called in theme layout.php files.
521 * @return string the DOCTYPE declaration that should be used.
523 public function doctype() {
524 if ($this->page->theme->doctype === 'html5') {
525 $this->contenttype = 'text/html; charset=utf-8';
526 return "<!DOCTYPE html>\n";
528 } else if ($this->page->theme->doctype === 'xhtml5') {
529 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
530 return "<!DOCTYPE html>\n";
532 } else {
533 // legacy xhtml 1.0
534 $this->contenttype = 'text/html; charset=utf-8';
535 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
540 * The attributes that should be added to the <html> tag. Designed to
541 * be called in theme layout.php files.
543 * @return string HTML fragment.
545 public function htmlattributes() {
546 $return = get_html_lang(true);
547 $attributes = array();
548 if ($this->page->theme->doctype !== 'html5') {
549 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
552 // Give plugins an opportunity to add things like xml namespaces to the html element.
553 // This function should return an array of html attribute names => values.
554 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
555 foreach ($pluginswithfunction as $plugins) {
556 foreach ($plugins as $function) {
557 $newattrs = $function();
558 unset($newattrs['dir']);
559 unset($newattrs['lang']);
560 unset($newattrs['xmlns']);
561 unset($newattrs['xml:lang']);
562 $attributes += $newattrs;
566 foreach ($attributes as $key => $val) {
567 $val = s($val);
568 $return .= " $key=\"$val\"";
571 return $return;
575 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
576 * that should be included in the <head> tag. Designed to be called in theme
577 * layout.php files.
579 * @return string HTML fragment.
581 public function standard_head_html() {
582 global $CFG, $SESSION;
584 // Before we output any content, we need to ensure that certain
585 // page components are set up.
587 // Blocks must be set up early as they may require javascript which
588 // has to be included in the page header before output is created.
589 foreach ($this->page->blocks->get_regions() as $region) {
590 $this->page->blocks->ensure_content_created($region, $this);
593 $output = '';
595 // Give plugins an opportunity to add any head elements. The callback
596 // must always return a string containing valid html head content.
597 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
598 foreach ($pluginswithfunction as $plugins) {
599 foreach ($plugins as $function) {
600 $output .= $function();
604 // Allow a url_rewrite plugin to setup any dynamic head content.
605 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
606 $class = $CFG->urlrewriteclass;
607 $output .= $class::html_head_setup();
610 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
611 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
612 // This is only set by the {@link redirect()} method
613 $output .= $this->metarefreshtag;
615 // Check if a periodic refresh delay has been set and make sure we arn't
616 // already meta refreshing
617 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
618 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
621 // Set up help link popups for all links with the helptooltip class
622 $this->page->requires->js_init_call('M.util.help_popups.setup');
624 $focus = $this->page->focuscontrol;
625 if (!empty($focus)) {
626 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
627 // This is a horrifically bad way to handle focus but it is passed in
628 // through messy formslib::moodleform
629 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
630 } else if (strpos($focus, '.')!==false) {
631 // Old style of focus, bad way to do it
632 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);
633 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
634 } else {
635 // Focus element with given id
636 $this->page->requires->js_function_call('focuscontrol', array($focus));
640 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
641 // any other custom CSS can not be overridden via themes and is highly discouraged
642 $urls = $this->page->theme->css_urls($this->page);
643 foreach ($urls as $url) {
644 $this->page->requires->css_theme($url);
647 // Get the theme javascript head and footer
648 if ($jsurl = $this->page->theme->javascript_url(true)) {
649 $this->page->requires->js($jsurl, true);
651 if ($jsurl = $this->page->theme->javascript_url(false)) {
652 $this->page->requires->js($jsurl);
655 // Get any HTML from the page_requirements_manager.
656 $output .= $this->page->requires->get_head_code($this->page, $this);
658 // List alternate versions.
659 foreach ($this->page->alternateversions as $type => $alt) {
660 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
661 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
664 // Add noindex tag if relevant page and setting applied.
665 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
666 $loginpages = array('login-index', 'login-signup');
667 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
668 if (!isset($CFG->additionalhtmlhead)) {
669 $CFG->additionalhtmlhead = '';
671 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
674 if (!empty($CFG->additionalhtmlhead)) {
675 $output .= "\n".$CFG->additionalhtmlhead;
678 return $output;
682 * The standard tags (typically skip links) that should be output just inside
683 * the start of the <body> tag. Designed to be called in theme layout.php files.
685 * @return string HTML fragment.
687 public function standard_top_of_body_html() {
688 global $CFG;
689 $output = $this->page->requires->get_top_of_body_code($this);
690 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
691 $output .= "\n".$CFG->additionalhtmltopofbody;
694 // Give plugins an opportunity to inject extra html content. The callback
695 // must always return a string containing valid html.
696 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
697 foreach ($pluginswithfunction as $plugins) {
698 foreach ($plugins as $function) {
699 $output .= $function();
703 $output .= $this->maintenance_warning();
705 return $output;
709 * Scheduled maintenance warning message.
711 * Note: This is a nasty hack to display maintenance notice, this should be moved
712 * to some general notification area once we have it.
714 * @return string
716 public function maintenance_warning() {
717 global $CFG;
719 $output = '';
720 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
721 $timeleft = $CFG->maintenance_later - time();
722 // If timeleft less than 30 sec, set the class on block to error to highlight.
723 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
724 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-a-1 alert');
725 $a = new stdClass();
726 $a->hour = (int)($timeleft / 3600);
727 $a->min = (int)(($timeleft / 60) % 60);
728 $a->sec = (int)($timeleft % 60);
729 if ($a->hour > 0) {
730 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
731 } else {
732 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
735 $output .= $this->box_end();
736 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
737 array(array('timeleftinsec' => $timeleft)));
738 $this->page->requires->strings_for_js(
739 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
740 'admin');
742 return $output;
746 * The standard tags (typically performance information and validation links,
747 * if we are in developer debug mode) that should be output in the footer area
748 * of the page. Designed to be called in theme layout.php files.
750 * @return string HTML fragment.
752 public function standard_footer_html() {
753 global $CFG, $SCRIPT;
755 $output = '';
756 if (during_initial_install()) {
757 // Debugging info can not work before install is finished,
758 // in any case we do not want any links during installation!
759 return $output;
762 // Give plugins an opportunity to add any footer elements.
763 // The callback must always return a string containing valid html footer content.
764 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
765 foreach ($pluginswithfunction as $plugins) {
766 foreach ($plugins as $function) {
767 $output .= $function();
771 // This function is normally called from a layout.php file in {@link core_renderer::header()}
772 // but some of the content won't be known until later, so we return a placeholder
773 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
774 $output .= $this->unique_performance_info_token;
775 if ($this->page->devicetypeinuse == 'legacy') {
776 // The legacy theme is in use print the notification
777 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
780 // Get links to switch device types (only shown for users not on a default device)
781 $output .= $this->theme_switch_links();
783 if (!empty($CFG->debugpageinfo)) {
784 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
786 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
787 // Add link to profiling report if necessary
788 if (function_exists('profiling_is_running') && profiling_is_running()) {
789 $txt = get_string('profiledscript', 'admin');
790 $title = get_string('profiledscriptview', 'admin');
791 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
792 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
793 $output .= '<div class="profilingfooter">' . $link . '</div>';
795 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
796 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
797 $output .= '<div class="purgecaches">' .
798 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
800 if (!empty($CFG->debugvalidators)) {
801 // 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
802 $output .= '<div class="validators"><ul class="list-unstyled m-l-1">
803 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
804 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
805 <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>
806 </ul></div>';
808 return $output;
812 * Returns standard main content placeholder.
813 * Designed to be called in theme layout.php files.
815 * @return string HTML fragment.
817 public function main_content() {
818 // This is here because it is the only place we can inject the "main" role over the entire main content area
819 // without requiring all theme's to manually do it, and without creating yet another thing people need to
820 // remember in the theme.
821 // This is an unfortunate hack. DO NO EVER add anything more here.
822 // DO NOT add classes.
823 // DO NOT add an id.
824 return '<div role="main">'.$this->unique_main_content_token.'</div>';
828 * Returns standard navigation between activities in a course.
830 * @return string the navigation HTML.
832 public function activity_navigation() {
833 // First we should check if we want to add navigation.
834 $context = $this->page->context;
835 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
836 || $context->contextlevel != CONTEXT_MODULE) {
837 return '';
840 // If the activity is in stealth mode, show no links.
841 if ($this->page->cm->is_stealth()) {
842 return '';
845 // Get a list of all the activities in the course.
846 $course = $this->page->cm->get_course();
847 $modules = get_fast_modinfo($course->id)->get_cms();
849 // Put the modules into an array in order by the position they are shown in the course.
850 $mods = [];
851 $activitylist = [];
852 foreach ($modules as $module) {
853 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
854 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
855 continue;
857 $mods[$module->id] = $module;
859 // No need to add the current module to the list for the activity dropdown menu.
860 if ($module->id == $this->page->cm->id) {
861 continue;
863 // Module name.
864 $modname = $module->get_formatted_name();
865 // Display the hidden text if necessary.
866 if (!$module->visible) {
867 $modname .= ' ' . get_string('hiddenwithbrackets');
869 // Module URL.
870 $linkurl = new moodle_url($module->url, array('forceview' => 1));
871 // Add module URL (as key) and name (as value) to the activity list array.
872 $activitylist[$linkurl->out(false)] = $modname;
875 $nummods = count($mods);
877 // If there is only one mod then do nothing.
878 if ($nummods == 1) {
879 return '';
882 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
883 $modids = array_keys($mods);
885 // Get the position in the array of the course module we are viewing.
886 $position = array_search($this->page->cm->id, $modids);
888 $prevmod = null;
889 $nextmod = null;
891 // Check if we have a previous mod to show.
892 if ($position > 0) {
893 $prevmod = $mods[$modids[$position - 1]];
896 // Check if we have a next mod to show.
897 if ($position < ($nummods - 1)) {
898 $nextmod = $mods[$modids[$position + 1]];
901 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
902 $renderer = $this->page->get_renderer('core', 'course');
903 return $renderer->render($activitynav);
907 * The standard tags (typically script tags that are not needed earlier) that
908 * should be output after everything else. Designed to be called in theme layout.php files.
910 * @return string HTML fragment.
912 public function standard_end_of_body_html() {
913 global $CFG;
915 // This function is normally called from a layout.php file in {@link core_renderer::header()}
916 // but some of the content won't be known until later, so we return a placeholder
917 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
918 $output = '';
919 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
920 $output .= "\n".$CFG->additionalhtmlfooter;
922 $output .= $this->unique_end_html_token;
923 return $output;
927 * Return the standard string that says whether you are logged in (and switched
928 * roles/logged in as another user).
929 * @param bool $withlinks if false, then don't include any links in the HTML produced.
930 * If not set, the default is the nologinlinks option from the theme config.php file,
931 * and if that is not set, then links are included.
932 * @return string HTML fragment.
934 public function login_info($withlinks = null) {
935 global $USER, $CFG, $DB, $SESSION;
937 if (during_initial_install()) {
938 return '';
941 if (is_null($withlinks)) {
942 $withlinks = empty($this->page->layout_options['nologinlinks']);
945 $course = $this->page->course;
946 if (\core\session\manager::is_loggedinas()) {
947 $realuser = \core\session\manager::get_realuser();
948 $fullname = fullname($realuser, true);
949 if ($withlinks) {
950 $loginastitle = get_string('loginas');
951 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
952 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
953 } else {
954 $realuserinfo = " [$fullname] ";
956 } else {
957 $realuserinfo = '';
960 $loginpage = $this->is_login_page();
961 $loginurl = get_login_url();
963 if (empty($course->id)) {
964 // $course->id is not defined during installation
965 return '';
966 } else if (isloggedin()) {
967 $context = context_course::instance($course->id);
969 $fullname = fullname($USER, true);
970 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
971 if ($withlinks) {
972 $linktitle = get_string('viewprofile');
973 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
974 } else {
975 $username = $fullname;
977 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
978 if ($withlinks) {
979 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
980 } else {
981 $username .= " from {$idprovider->name}";
984 if (isguestuser()) {
985 $loggedinas = $realuserinfo.get_string('loggedinasguest');
986 if (!$loginpage && $withlinks) {
987 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
989 } else if (is_role_switched($course->id)) { // Has switched roles
990 $rolename = '';
991 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
992 $rolename = ': '.role_get_name($role, $context);
994 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
995 if ($withlinks) {
996 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
997 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
999 } else {
1000 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1001 if ($withlinks) {
1002 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1005 } else {
1006 $loggedinas = get_string('loggedinnot', 'moodle');
1007 if (!$loginpage && $withlinks) {
1008 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1012 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1014 if (isset($SESSION->justloggedin)) {
1015 unset($SESSION->justloggedin);
1016 if (!empty($CFG->displayloginfailures)) {
1017 if (!isguestuser()) {
1018 // Include this file only when required.
1019 require_once($CFG->dirroot . '/user/lib.php');
1020 if ($count = user_count_login_failures($USER)) {
1021 $loggedinas .= '<div class="loginfailures">';
1022 $a = new stdClass();
1023 $a->attempts = $count;
1024 $loggedinas .= get_string('failedloginattempts', '', $a);
1025 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1026 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1027 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1029 $loggedinas .= '</div>';
1035 return $loggedinas;
1039 * Check whether the current page is a login page.
1041 * @since Moodle 2.9
1042 * @return bool
1044 protected function is_login_page() {
1045 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1046 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1047 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1048 return in_array(
1049 $this->page->url->out_as_local_url(false, array()),
1050 array(
1051 '/login/index.php',
1052 '/login/forgot_password.php',
1058 * Return the 'back' link that normally appears in the footer.
1060 * @return string HTML fragment.
1062 public function home_link() {
1063 global $CFG, $SITE;
1065 if ($this->page->pagetype == 'site-index') {
1066 // Special case for site home page - please do not remove
1067 return '<div class="sitelink">' .
1068 '<a title="Moodle" href="http://moodle.org/">' .
1069 '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1071 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1072 // Special case for during install/upgrade.
1073 return '<div class="sitelink">'.
1074 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1075 '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1077 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1078 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1079 get_string('home') . '</a></div>';
1081 } else {
1082 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1083 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1088 * Redirects the user by any means possible given the current state
1090 * This function should not be called directly, it should always be called using
1091 * the redirect function in lib/weblib.php
1093 * The redirect function should really only be called before page output has started
1094 * however it will allow itself to be called during the state STATE_IN_BODY
1096 * @param string $encodedurl The URL to send to encoded if required
1097 * @param string $message The message to display to the user if any
1098 * @param int $delay The delay before redirecting a user, if $message has been
1099 * set this is a requirement and defaults to 3, set to 0 no delay
1100 * @param boolean $debugdisableredirect this redirect has been disabled for
1101 * debugging purposes. Display a message that explains, and don't
1102 * trigger the redirect.
1103 * @param string $messagetype The type of notification to show the message in.
1104 * See constants on \core\output\notification.
1105 * @return string The HTML to display to the user before dying, may contain
1106 * meta refresh, javascript refresh, and may have set header redirects
1108 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1109 $messagetype = \core\output\notification::NOTIFY_INFO) {
1110 global $CFG;
1111 $url = str_replace('&amp;', '&', $encodedurl);
1113 switch ($this->page->state) {
1114 case moodle_page::STATE_BEFORE_HEADER :
1115 // No output yet it is safe to delivery the full arsenal of redirect methods
1116 if (!$debugdisableredirect) {
1117 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1118 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1119 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1121 $output = $this->header();
1122 break;
1123 case moodle_page::STATE_PRINTING_HEADER :
1124 // We should hopefully never get here
1125 throw new coding_exception('You cannot redirect while printing the page header');
1126 break;
1127 case moodle_page::STATE_IN_BODY :
1128 // We really shouldn't be here but we can deal with this
1129 debugging("You should really redirect before you start page output");
1130 if (!$debugdisableredirect) {
1131 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1133 $output = $this->opencontainers->pop_all_but_last();
1134 break;
1135 case moodle_page::STATE_DONE :
1136 // Too late to be calling redirect now
1137 throw new coding_exception('You cannot redirect after the entire page has been generated');
1138 break;
1140 $output .= $this->notification($message, $messagetype);
1141 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1142 if ($debugdisableredirect) {
1143 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1145 $output .= $this->footer();
1146 return $output;
1150 * Start output by sending the HTTP headers, and printing the HTML <head>
1151 * and the start of the <body>.
1153 * To control what is printed, you should set properties on $PAGE. If you
1154 * are familiar with the old {@link print_header()} function from Moodle 1.9
1155 * you will find that there are properties on $PAGE that correspond to most
1156 * of the old parameters to could be passed to print_header.
1158 * Not that, in due course, the remaining $navigation, $menu parameters here
1159 * will be replaced by more properties of $PAGE, but that is still to do.
1161 * @return string HTML that you must output this, preferably immediately.
1163 public function header() {
1164 global $USER, $CFG, $SESSION;
1166 // Give plugins an opportunity touch things before the http headers are sent
1167 // such as adding additional headers. The return value is ignored.
1168 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1169 foreach ($pluginswithfunction as $plugins) {
1170 foreach ($plugins as $function) {
1171 $function();
1175 if (\core\session\manager::is_loggedinas()) {
1176 $this->page->add_body_class('userloggedinas');
1179 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1180 require_once($CFG->dirroot . '/user/lib.php');
1181 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1182 if ($count = user_count_login_failures($USER, false)) {
1183 $this->page->add_body_class('loginfailures');
1187 // If the user is logged in, and we're not in initial install,
1188 // check to see if the user is role-switched and add the appropriate
1189 // CSS class to the body element.
1190 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1191 $this->page->add_body_class('userswitchedrole');
1194 // Give themes a chance to init/alter the page object.
1195 $this->page->theme->init_page($this->page);
1197 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1199 // Find the appropriate page layout file, based on $this->page->pagelayout.
1200 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1201 // Render the layout using the layout file.
1202 $rendered = $this->render_page_layout($layoutfile);
1204 // Slice the rendered output into header and footer.
1205 $cutpos = strpos($rendered, $this->unique_main_content_token);
1206 if ($cutpos === false) {
1207 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1208 $token = self::MAIN_CONTENT_TOKEN;
1209 } else {
1210 $token = $this->unique_main_content_token;
1213 if ($cutpos === false) {
1214 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.');
1216 $header = substr($rendered, 0, $cutpos);
1217 $footer = substr($rendered, $cutpos + strlen($token));
1219 if (empty($this->contenttype)) {
1220 debugging('The page layout file did not call $OUTPUT->doctype()');
1221 $header = $this->doctype() . $header;
1224 // If this theme version is below 2.4 release and this is a course view page
1225 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1226 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1227 // check if course content header/footer have not been output during render of theme layout
1228 $coursecontentheader = $this->course_content_header(true);
1229 $coursecontentfooter = $this->course_content_footer(true);
1230 if (!empty($coursecontentheader)) {
1231 // display debug message and add header and footer right above and below main content
1232 // Please note that course header and footer (to be displayed above and below the whole page)
1233 // are not displayed in this case at all.
1234 // Besides the content header and footer are not displayed on any other course page
1235 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);
1236 $header .= $coursecontentheader;
1237 $footer = $coursecontentfooter. $footer;
1241 send_headers($this->contenttype, $this->page->cacheable);
1243 $this->opencontainers->push('header/footer', $footer);
1244 $this->page->set_state(moodle_page::STATE_IN_BODY);
1246 return $header . $this->skip_link_target('maincontent');
1250 * Renders and outputs the page layout file.
1252 * This is done by preparing the normal globals available to a script, and
1253 * then including the layout file provided by the current theme for the
1254 * requested layout.
1256 * @param string $layoutfile The name of the layout file
1257 * @return string HTML code
1259 protected function render_page_layout($layoutfile) {
1260 global $CFG, $SITE, $USER;
1261 // The next lines are a bit tricky. The point is, here we are in a method
1262 // of a renderer class, and this object may, or may not, be the same as
1263 // the global $OUTPUT object. When rendering the page layout file, we want to use
1264 // this object. However, people writing Moodle code expect the current
1265 // renderer to be called $OUTPUT, not $this, so define a variable called
1266 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1267 $OUTPUT = $this;
1268 $PAGE = $this->page;
1269 $COURSE = $this->page->course;
1271 ob_start();
1272 include($layoutfile);
1273 $rendered = ob_get_contents();
1274 ob_end_clean();
1275 return $rendered;
1279 * Outputs the page's footer
1281 * @return string HTML fragment
1283 public function footer() {
1284 global $CFG, $DB, $PAGE;
1286 // Give plugins an opportunity to touch the page before JS is finalized.
1287 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1288 foreach ($pluginswithfunction as $plugins) {
1289 foreach ($plugins as $function) {
1290 $function();
1294 $output = $this->container_end_all(true);
1296 $footer = $this->opencontainers->pop('header/footer');
1298 if (debugging() and $DB and $DB->is_transaction_started()) {
1299 // TODO: MDL-20625 print warning - transaction will be rolled back
1302 // Provide some performance info if required
1303 $performanceinfo = '';
1304 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1305 $perf = get_performance_info();
1306 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1307 $performanceinfo = $perf['html'];
1311 // We always want performance data when running a performance test, even if the user is redirected to another page.
1312 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1313 $footer = $this->unique_performance_info_token . $footer;
1315 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1317 // Only show notifications when we have a $PAGE context id.
1318 if (!empty($PAGE->context->id)) {
1319 $this->page->requires->js_call_amd('core/notification', 'init', array(
1320 $PAGE->context->id,
1321 \core\notification::fetch_as_array($this)
1324 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1326 $this->page->set_state(moodle_page::STATE_DONE);
1328 return $output . $footer;
1332 * Close all but the last open container. This is useful in places like error
1333 * handling, where you want to close all the open containers (apart from <body>)
1334 * before outputting the error message.
1336 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1337 * developer debug warning if it isn't.
1338 * @return string the HTML required to close any open containers inside <body>.
1340 public function container_end_all($shouldbenone = false) {
1341 return $this->opencontainers->pop_all_but_last($shouldbenone);
1345 * Returns course-specific information to be output immediately above content on any course page
1346 * (for the current course)
1348 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1349 * @return string
1351 public function course_content_header($onlyifnotcalledbefore = false) {
1352 global $CFG;
1353 static $functioncalled = false;
1354 if ($functioncalled && $onlyifnotcalledbefore) {
1355 // we have already output the content header
1356 return '';
1359 // Output any session notification.
1360 $notifications = \core\notification::fetch();
1362 $bodynotifications = '';
1363 foreach ($notifications as $notification) {
1364 $bodynotifications .= $this->render_from_template(
1365 $notification->get_template_name(),
1366 $notification->export_for_template($this)
1370 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1372 if ($this->page->course->id == SITEID) {
1373 // return immediately and do not include /course/lib.php if not necessary
1374 return $output;
1377 require_once($CFG->dirroot.'/course/lib.php');
1378 $functioncalled = true;
1379 $courseformat = course_get_format($this->page->course);
1380 if (($obj = $courseformat->course_content_header()) !== null) {
1381 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1383 return $output;
1387 * Returns course-specific information to be output immediately below content on any course page
1388 * (for the current course)
1390 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1391 * @return string
1393 public function course_content_footer($onlyifnotcalledbefore = false) {
1394 global $CFG;
1395 if ($this->page->course->id == SITEID) {
1396 // return immediately and do not include /course/lib.php if not necessary
1397 return '';
1399 static $functioncalled = false;
1400 if ($functioncalled && $onlyifnotcalledbefore) {
1401 // we have already output the content footer
1402 return '';
1404 $functioncalled = true;
1405 require_once($CFG->dirroot.'/course/lib.php');
1406 $courseformat = course_get_format($this->page->course);
1407 if (($obj = $courseformat->course_content_footer()) !== null) {
1408 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1410 return '';
1414 * Returns course-specific information to be output on any course page in the header area
1415 * (for the current course)
1417 * @return string
1419 public function course_header() {
1420 global $CFG;
1421 if ($this->page->course->id == SITEID) {
1422 // return immediately and do not include /course/lib.php if not necessary
1423 return '';
1425 require_once($CFG->dirroot.'/course/lib.php');
1426 $courseformat = course_get_format($this->page->course);
1427 if (($obj = $courseformat->course_header()) !== null) {
1428 return $courseformat->get_renderer($this->page)->render($obj);
1430 return '';
1434 * Returns course-specific information to be output on any course page in the footer area
1435 * (for the current course)
1437 * @return string
1439 public function course_footer() {
1440 global $CFG;
1441 if ($this->page->course->id == SITEID) {
1442 // return immediately and do not include /course/lib.php if not necessary
1443 return '';
1445 require_once($CFG->dirroot.'/course/lib.php');
1446 $courseformat = course_get_format($this->page->course);
1447 if (($obj = $courseformat->course_footer()) !== null) {
1448 return $courseformat->get_renderer($this->page)->render($obj);
1450 return '';
1454 * Returns lang menu or '', this method also checks forcing of languages in courses.
1456 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1458 * @return string The lang menu HTML or empty string
1460 public function lang_menu() {
1461 global $CFG;
1463 if (empty($CFG->langmenu)) {
1464 return '';
1467 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1468 // do not show lang menu if language forced
1469 return '';
1472 $currlang = current_language();
1473 $langs = get_string_manager()->get_list_of_translations();
1475 if (count($langs) < 2) {
1476 return '';
1479 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1480 $s->label = get_accesshide(get_string('language'));
1481 $s->class = 'langmenu';
1482 return $this->render($s);
1486 * Output the row of editing icons for a block, as defined by the controls array.
1488 * @param array $controls an array like {@link block_contents::$controls}.
1489 * @param string $blockid The ID given to the block.
1490 * @return string HTML fragment.
1492 public function block_controls($actions, $blockid = null) {
1493 global $CFG;
1494 if (empty($actions)) {
1495 return '';
1497 $menu = new action_menu($actions);
1498 if ($blockid !== null) {
1499 $menu->set_owner_selector('#'.$blockid);
1501 $menu->set_constraint('.block-region');
1502 $menu->attributes['class'] .= ' block-control-actions commands';
1503 return $this->render($menu);
1507 * Renders an action menu component.
1509 * ARIA references:
1510 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1511 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1513 * @param action_menu $menu
1514 * @return string HTML
1516 public function render_action_menu(action_menu $menu) {
1517 $context = $menu->export_for_template($this);
1518 return $this->render_from_template('core/action_menu', $context);
1522 * Renders an action_menu_link item.
1524 * @param action_menu_link $action
1525 * @return string HTML fragment
1527 protected function render_action_menu_link(action_menu_link $action) {
1528 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1532 * Renders a primary action_menu_filler item.
1534 * @param action_menu_link_filler $action
1535 * @return string HTML fragment
1537 protected function render_action_menu_filler(action_menu_filler $action) {
1538 return html_writer::span('&nbsp;', 'filler');
1542 * Renders a primary action_menu_link item.
1544 * @param action_menu_link_primary $action
1545 * @return string HTML fragment
1547 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1548 return $this->render_action_menu_link($action);
1552 * Renders a secondary action_menu_link item.
1554 * @param action_menu_link_secondary $action
1555 * @return string HTML fragment
1557 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1558 return $this->render_action_menu_link($action);
1562 * Prints a nice side block with an optional header.
1564 * The content is described
1565 * by a {@link core_renderer::block_contents} object.
1567 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1568 * <div class="header"></div>
1569 * <div class="content">
1570 * ...CONTENT...
1571 * <div class="footer">
1572 * </div>
1573 * </div>
1574 * <div class="annotation">
1575 * </div>
1576 * </div>
1578 * @param block_contents $bc HTML for the content
1579 * @param string $region the region the block is appearing in.
1580 * @return string the HTML to be output.
1582 public function block(block_contents $bc, $region) {
1583 $bc = clone($bc); // Avoid messing up the object passed in.
1584 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1585 $bc->collapsible = block_contents::NOT_HIDEABLE;
1587 if (!empty($bc->blockinstanceid)) {
1588 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1590 $skiptitle = strip_tags($bc->title);
1591 if ($bc->blockinstanceid && !empty($skiptitle)) {
1592 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1593 } else if (!empty($bc->arialabel)) {
1594 $bc->attributes['aria-label'] = $bc->arialabel;
1596 if ($bc->dockable) {
1597 $bc->attributes['data-dockable'] = 1;
1599 if ($bc->collapsible == block_contents::HIDDEN) {
1600 $bc->add_class('hidden');
1602 if (!empty($bc->controls)) {
1603 $bc->add_class('block_with_controls');
1607 if (empty($skiptitle)) {
1608 $output = '';
1609 $skipdest = '';
1610 } else {
1611 $output = html_writer::link('#sb-'.$bc->skipid, get_string('skipa', 'access', $skiptitle),
1612 array('class' => 'skip skip-block', 'id' => 'fsb-' . $bc->skipid));
1613 $skipdest = html_writer::span('', 'skip-block-to',
1614 array('id' => 'sb-' . $bc->skipid));
1617 $output .= html_writer::start_tag('div', $bc->attributes);
1619 $output .= $this->block_header($bc);
1620 $output .= $this->block_content($bc);
1622 $output .= html_writer::end_tag('div');
1624 $output .= $this->block_annotation($bc);
1626 $output .= $skipdest;
1628 $this->init_block_hider_js($bc);
1629 return $output;
1633 * Produces a header for a block
1635 * @param block_contents $bc
1636 * @return string
1638 protected function block_header(block_contents $bc) {
1640 $title = '';
1641 if ($bc->title) {
1642 $attributes = array();
1643 if ($bc->blockinstanceid) {
1644 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1646 $title = html_writer::tag('h2', $bc->title, $attributes);
1649 $blockid = null;
1650 if (isset($bc->attributes['id'])) {
1651 $blockid = $bc->attributes['id'];
1653 $controlshtml = $this->block_controls($bc->controls, $blockid);
1655 $output = '';
1656 if ($title || $controlshtml) {
1657 $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'));
1659 return $output;
1663 * Produces the content area for a block
1665 * @param block_contents $bc
1666 * @return string
1668 protected function block_content(block_contents $bc) {
1669 $output = html_writer::start_tag('div', array('class' => 'content'));
1670 if (!$bc->title && !$this->block_controls($bc->controls)) {
1671 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1673 $output .= $bc->content;
1674 $output .= $this->block_footer($bc);
1675 $output .= html_writer::end_tag('div');
1677 return $output;
1681 * Produces the footer for a block
1683 * @param block_contents $bc
1684 * @return string
1686 protected function block_footer(block_contents $bc) {
1687 $output = '';
1688 if ($bc->footer) {
1689 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1691 return $output;
1695 * Produces the annotation for a block
1697 * @param block_contents $bc
1698 * @return string
1700 protected function block_annotation(block_contents $bc) {
1701 $output = '';
1702 if ($bc->annotation) {
1703 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1705 return $output;
1709 * Calls the JS require function to hide a block.
1711 * @param block_contents $bc A block_contents object
1713 protected function init_block_hider_js(block_contents $bc) {
1714 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1715 $config = new stdClass;
1716 $config->id = $bc->attributes['id'];
1717 $config->title = strip_tags($bc->title);
1718 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1719 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1720 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1722 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1723 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1728 * Render the contents of a block_list.
1730 * @param array $icons the icon for each item.
1731 * @param array $items the content of each item.
1732 * @return string HTML
1734 public function list_block_contents($icons, $items) {
1735 $row = 0;
1736 $lis = array();
1737 foreach ($items as $key => $string) {
1738 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1739 if (!empty($icons[$key])) { //test if the content has an assigned icon
1740 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1742 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1743 $item .= html_writer::end_tag('li');
1744 $lis[] = $item;
1745 $row = 1 - $row; // Flip even/odd.
1747 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1751 * Output all the blocks in a particular region.
1753 * @param string $region the name of a region on this page.
1754 * @return string the HTML to be output.
1756 public function blocks_for_region($region) {
1757 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1758 $blocks = $this->page->blocks->get_blocks_for_region($region);
1759 $lastblock = null;
1760 $zones = array();
1761 foreach ($blocks as $block) {
1762 $zones[] = $block->title;
1764 $output = '';
1766 foreach ($blockcontents as $bc) {
1767 if ($bc instanceof block_contents) {
1768 $output .= $this->block($bc, $region);
1769 $lastblock = $bc->title;
1770 } else if ($bc instanceof block_move_target) {
1771 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1772 } else {
1773 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1776 return $output;
1780 * Output a place where the block that is currently being moved can be dropped.
1782 * @param block_move_target $target with the necessary details.
1783 * @param array $zones array of areas where the block can be moved to
1784 * @param string $previous the block located before the area currently being rendered.
1785 * @param string $region the name of the region
1786 * @return string the HTML to be output.
1788 public function block_move_target($target, $zones, $previous, $region) {
1789 if ($previous == null) {
1790 if (empty($zones)) {
1791 // There are no zones, probably because there are no blocks.
1792 $regions = $this->page->theme->get_all_block_regions();
1793 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1794 } else {
1795 $position = get_string('moveblockbefore', 'block', $zones[0]);
1797 } else {
1798 $position = get_string('moveblockafter', 'block', $previous);
1800 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1804 * Renders a special html link with attached action
1806 * Theme developers: DO NOT OVERRIDE! Please override function
1807 * {@link core_renderer::render_action_link()} instead.
1809 * @param string|moodle_url $url
1810 * @param string $text HTML fragment
1811 * @param component_action $action
1812 * @param array $attributes associative array of html link attributes + disabled
1813 * @param pix_icon optional pix icon to render with the link
1814 * @return string HTML fragment
1816 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1817 if (!($url instanceof moodle_url)) {
1818 $url = new moodle_url($url);
1820 $link = new action_link($url, $text, $action, $attributes, $icon);
1822 return $this->render($link);
1826 * Renders an action_link object.
1828 * The provided link is renderer and the HTML returned. At the same time the
1829 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1831 * @param action_link $link
1832 * @return string HTML fragment
1834 protected function render_action_link(action_link $link) {
1835 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1839 * Renders an action_icon.
1841 * This function uses the {@link core_renderer::action_link()} method for the
1842 * most part. What it does different is prepare the icon as HTML and use it
1843 * as the link text.
1845 * Theme developers: If you want to change how action links and/or icons are rendered,
1846 * consider overriding function {@link core_renderer::render_action_link()} and
1847 * {@link core_renderer::render_pix_icon()}.
1849 * @param string|moodle_url $url A string URL or moodel_url
1850 * @param pix_icon $pixicon
1851 * @param component_action $action
1852 * @param array $attributes associative array of html link attributes + disabled
1853 * @param bool $linktext show title next to image in link
1854 * @return string HTML fragment
1856 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1857 if (!($url instanceof moodle_url)) {
1858 $url = new moodle_url($url);
1860 $attributes = (array)$attributes;
1862 if (empty($attributes['class'])) {
1863 // let ppl override the class via $options
1864 $attributes['class'] = 'action-icon';
1867 $icon = $this->render($pixicon);
1869 if ($linktext) {
1870 $text = $pixicon->attributes['alt'];
1871 } else {
1872 $text = '';
1875 return $this->action_link($url, $text.$icon, $action, $attributes);
1879 * Print a message along with button choices for Continue/Cancel
1881 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1883 * @param string $message The question to ask the user
1884 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1885 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1886 * @return string HTML fragment
1888 public function confirm($message, $continue, $cancel) {
1889 if ($continue instanceof single_button) {
1890 // ok
1891 $continue->primary = true;
1892 } else if (is_string($continue)) {
1893 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1894 } else if ($continue instanceof moodle_url) {
1895 $continue = new single_button($continue, get_string('continue'), 'post', true);
1896 } else {
1897 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1900 if ($cancel instanceof single_button) {
1901 // ok
1902 } else if (is_string($cancel)) {
1903 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1904 } else if ($cancel instanceof moodle_url) {
1905 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1906 } else {
1907 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1910 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice');
1911 $output .= $this->box_start('modal-content', 'modal-content');
1912 $output .= $this->box_start('modal-header p-x-1', 'modal-header');
1913 $output .= html_writer::tag('h4', get_string('confirm'));
1914 $output .= $this->box_end();
1915 $output .= $this->box_start('modal-body', 'modal-body');
1916 $output .= html_writer::tag('p', $message);
1917 $output .= $this->box_end();
1918 $output .= $this->box_start('modal-footer', 'modal-footer');
1919 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1920 $output .= $this->box_end();
1921 $output .= $this->box_end();
1922 $output .= $this->box_end();
1923 return $output;
1927 * Returns a form with a single button.
1929 * Theme developers: DO NOT OVERRIDE! Please override function
1930 * {@link core_renderer::render_single_button()} instead.
1932 * @param string|moodle_url $url
1933 * @param string $label button text
1934 * @param string $method get or post submit method
1935 * @param array $options associative array {disabled, title, etc.}
1936 * @return string HTML fragment
1938 public function single_button($url, $label, $method='post', array $options=null) {
1939 if (!($url instanceof moodle_url)) {
1940 $url = new moodle_url($url);
1942 $button = new single_button($url, $label, $method);
1944 foreach ((array)$options as $key=>$value) {
1945 if (array_key_exists($key, $button)) {
1946 $button->$key = $value;
1950 return $this->render($button);
1954 * Renders a single button widget.
1956 * This will return HTML to display a form containing a single button.
1958 * @param single_button $button
1959 * @return string HTML fragment
1961 protected function render_single_button(single_button $button) {
1962 $attributes = array('type' => 'submit',
1963 'value' => $button->label,
1964 'disabled' => $button->disabled ? 'disabled' : null,
1965 'title' => $button->tooltip);
1967 if ($button->actions) {
1968 $id = html_writer::random_id('single_button');
1969 $attributes['id'] = $id;
1970 foreach ($button->actions as $action) {
1971 $this->add_action_handler($action, $id);
1975 // first the input element
1976 $output = html_writer::empty_tag('input', $attributes);
1978 // then hidden fields
1979 $params = $button->url->params();
1980 if ($button->method === 'post') {
1981 $params['sesskey'] = sesskey();
1983 foreach ($params as $var => $val) {
1984 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1987 // then div wrapper for xhtml strictness
1988 $output = html_writer::tag('div', $output);
1990 // now the form itself around it
1991 if ($button->method === 'get') {
1992 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1993 } else {
1994 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1996 if ($url === '') {
1997 $url = '#'; // there has to be always some action
1999 $attributes = array('method' => $button->method,
2000 'action' => $url,
2001 'id' => $button->formid);
2002 $output = html_writer::tag('form', $output, $attributes);
2004 // and finally one more wrapper with class
2005 return html_writer::tag('div', $output, array('class' => $button->class));
2009 * Returns a form with a single select widget.
2011 * Theme developers: DO NOT OVERRIDE! Please override function
2012 * {@link core_renderer::render_single_select()} instead.
2014 * @param moodle_url $url form action target, includes hidden fields
2015 * @param string $name name of selection field - the changing parameter in url
2016 * @param array $options list of options
2017 * @param string $selected selected element
2018 * @param array $nothing
2019 * @param string $formid
2020 * @param array $attributes other attributes for the single select
2021 * @return string HTML fragment
2023 public function single_select($url, $name, array $options, $selected = '',
2024 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2025 if (!($url instanceof moodle_url)) {
2026 $url = new moodle_url($url);
2028 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2030 if (array_key_exists('label', $attributes)) {
2031 $select->set_label($attributes['label']);
2032 unset($attributes['label']);
2034 $select->attributes = $attributes;
2036 return $this->render($select);
2040 * Returns a dataformat selection and download form
2042 * @param string $label A text label
2043 * @param moodle_url|string $base The download page url
2044 * @param string $name The query param which will hold the type of the download
2045 * @param array $params Extra params sent to the download page
2046 * @return string HTML fragment
2048 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2050 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2051 $options = array();
2052 foreach ($formats as $format) {
2053 if ($format->is_enabled()) {
2054 $options[] = array(
2055 'value' => $format->name,
2056 'label' => get_string('dataformat', $format->component),
2060 $hiddenparams = array();
2061 foreach ($params as $key => $value) {
2062 $hiddenparams[] = array(
2063 'name' => $key,
2064 'value' => $value,
2067 $data = array(
2068 'label' => $label,
2069 'base' => $base,
2070 'name' => $name,
2071 'params' => $hiddenparams,
2072 'options' => $options,
2073 'sesskey' => sesskey(),
2074 'submit' => get_string('download'),
2077 return $this->render_from_template('core/dataformat_selector', $data);
2082 * Internal implementation of single_select rendering
2084 * @param single_select $select
2085 * @return string HTML fragment
2087 protected function render_single_select(single_select $select) {
2088 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2092 * Returns a form with a url select widget.
2094 * Theme developers: DO NOT OVERRIDE! Please override function
2095 * {@link core_renderer::render_url_select()} instead.
2097 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2098 * @param string $selected selected element
2099 * @param array $nothing
2100 * @param string $formid
2101 * @return string HTML fragment
2103 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2104 $select = new url_select($urls, $selected, $nothing, $formid);
2105 return $this->render($select);
2109 * Internal implementation of url_select rendering
2111 * @param url_select $select
2112 * @return string HTML fragment
2114 protected function render_url_select(url_select $select) {
2115 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2119 * Returns a string containing a link to the user documentation.
2120 * Also contains an icon by default. Shown to teachers and admin only.
2122 * @param string $path The page link after doc root and language, no leading slash.
2123 * @param string $text The text to be displayed for the link
2124 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2125 * @return string
2127 public function doc_link($path, $text = '', $forcepopup = false) {
2128 global $CFG;
2130 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2132 $url = new moodle_url(get_docs_url($path));
2134 $attributes = array('href'=>$url);
2135 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2136 $attributes['class'] = 'helplinkpopup';
2139 return html_writer::tag('a', $icon.$text, $attributes);
2143 * Return HTML for an image_icon.
2145 * Theme developers: DO NOT OVERRIDE! Please override function
2146 * {@link core_renderer::render_image_icon()} instead.
2148 * @param string $pix short pix name
2149 * @param string $alt mandatory alt attribute
2150 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2151 * @param array $attributes htm lattributes
2152 * @return string HTML fragment
2154 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2155 $icon = new image_icon($pix, $alt, $component, $attributes);
2156 return $this->render($icon);
2160 * Renders a pix_icon widget and returns the HTML to display it.
2162 * @param image_icon $icon
2163 * @return string HTML fragment
2165 protected function render_image_icon(image_icon $icon) {
2166 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2167 return $system->render_pix_icon($this, $icon);
2171 * Return HTML for a pix_icon.
2173 * Theme developers: DO NOT OVERRIDE! Please override function
2174 * {@link core_renderer::render_pix_icon()} instead.
2176 * @param string $pix short pix name
2177 * @param string $alt mandatory alt attribute
2178 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2179 * @param array $attributes htm lattributes
2180 * @return string HTML fragment
2182 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2183 $icon = new pix_icon($pix, $alt, $component, $attributes);
2184 return $this->render($icon);
2188 * Renders a pix_icon widget and returns the HTML to display it.
2190 * @param pix_icon $icon
2191 * @return string HTML fragment
2193 protected function render_pix_icon(pix_icon $icon) {
2194 $system = \core\output\icon_system::instance();
2195 return $system->render_pix_icon($this, $icon);
2199 * Return HTML to display an emoticon icon.
2201 * @param pix_emoticon $emoticon
2202 * @return string HTML fragment
2204 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2205 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2206 return $system->render_pix_icon($this, $emoticon);
2210 * Produces the html that represents this rating in the UI
2212 * @param rating $rating the page object on which this rating will appear
2213 * @return string
2215 function render_rating(rating $rating) {
2216 global $CFG, $USER;
2218 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2219 return null;//ratings are turned off
2222 $ratingmanager = new rating_manager();
2223 // Initialise the JavaScript so ratings can be done by AJAX.
2224 $ratingmanager->initialise_rating_javascript($this->page);
2226 $strrate = get_string("rate", "rating");
2227 $ratinghtml = ''; //the string we'll return
2229 // permissions check - can they view the aggregate?
2230 if ($rating->user_can_view_aggregate()) {
2232 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2233 $aggregatestr = $rating->get_aggregate_string();
2235 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2236 if ($rating->count > 0) {
2237 $countstr = "({$rating->count})";
2238 } else {
2239 $countstr = '-';
2241 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2243 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2244 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2246 $nonpopuplink = $rating->get_view_ratings_url();
2247 $popuplink = $rating->get_view_ratings_url(true);
2249 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2250 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2251 } else {
2252 $ratinghtml .= $aggregatehtml;
2256 $formstart = null;
2257 // if the item doesn't belong to the current user, the user has permission to rate
2258 // and we're within the assessable period
2259 if ($rating->user_can_rate()) {
2261 $rateurl = $rating->get_rate_url();
2262 $inputs = $rateurl->params();
2264 //start the rating form
2265 $formattrs = array(
2266 'id' => "postrating{$rating->itemid}",
2267 'class' => 'postratingform',
2268 'method' => 'post',
2269 'action' => $rateurl->out_omit_querystring()
2271 $formstart = html_writer::start_tag('form', $formattrs);
2272 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2274 // add the hidden inputs
2275 foreach ($inputs as $name => $value) {
2276 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2277 $formstart .= html_writer::empty_tag('input', $attributes);
2280 if (empty($ratinghtml)) {
2281 $ratinghtml .= $strrate.': ';
2283 $ratinghtml = $formstart.$ratinghtml;
2285 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2286 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2287 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2288 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2290 //output submit button
2291 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2293 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2294 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2296 if (!$rating->settings->scale->isnumeric) {
2297 // If a global scale, try to find current course ID from the context
2298 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2299 $courseid = $coursecontext->instanceid;
2300 } else {
2301 $courseid = $rating->settings->scale->courseid;
2303 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2305 $ratinghtml .= html_writer::end_tag('span');
2306 $ratinghtml .= html_writer::end_tag('div');
2307 $ratinghtml .= html_writer::end_tag('form');
2310 return $ratinghtml;
2314 * Centered heading with attached help button (same title text)
2315 * and optional icon attached.
2317 * @param string $text A heading text
2318 * @param string $helpidentifier The keyword that defines a help page
2319 * @param string $component component name
2320 * @param string|moodle_url $icon
2321 * @param string $iconalt icon alt text
2322 * @param int $level The level of importance of the heading. Defaulting to 2
2323 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2324 * @return string HTML fragment
2326 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2327 $image = '';
2328 if ($icon) {
2329 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2332 $help = '';
2333 if ($helpidentifier) {
2334 $help = $this->help_icon($helpidentifier, $component);
2337 return $this->heading($image.$text.$help, $level, $classnames);
2341 * Returns HTML to display a help icon.
2343 * @deprecated since Moodle 2.0
2345 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2346 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2350 * Returns HTML to display a help icon.
2352 * Theme developers: DO NOT OVERRIDE! Please override function
2353 * {@link core_renderer::render_help_icon()} instead.
2355 * @param string $identifier The keyword that defines a help page
2356 * @param string $component component name
2357 * @param string|bool $linktext true means use $title as link text, string means link text value
2358 * @return string HTML fragment
2360 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2361 $icon = new help_icon($identifier, $component);
2362 $icon->diag_strings();
2363 if ($linktext === true) {
2364 $icon->linktext = get_string($icon->identifier, $icon->component);
2365 } else if (!empty($linktext)) {
2366 $icon->linktext = $linktext;
2368 return $this->render($icon);
2372 * Implementation of user image rendering.
2374 * @param help_icon $helpicon A help icon instance
2375 * @return string HTML fragment
2377 protected function render_help_icon(help_icon $helpicon) {
2378 return $this->render_from_template('core/help_icon', $helpicon->export_for_template($this));
2382 * Returns HTML to display a scale help icon.
2384 * @param int $courseid
2385 * @param stdClass $scale instance
2386 * @return string HTML fragment
2388 public function help_icon_scale($courseid, stdClass $scale) {
2389 global $CFG;
2391 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2393 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2395 $scaleid = abs($scale->id);
2397 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2398 $action = new popup_action('click', $link, 'ratingscale');
2400 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2404 * Creates and returns a spacer image with optional line break.
2406 * @param array $attributes Any HTML attributes to add to the spaced.
2407 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2408 * laxy do it with CSS which is a much better solution.
2409 * @return string HTML fragment
2411 public function spacer(array $attributes = null, $br = false) {
2412 $attributes = (array)$attributes;
2413 if (empty($attributes['width'])) {
2414 $attributes['width'] = 1;
2416 if (empty($attributes['height'])) {
2417 $attributes['height'] = 1;
2419 $attributes['class'] = 'spacer';
2421 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2423 if (!empty($br)) {
2424 $output .= '<br />';
2427 return $output;
2431 * Returns HTML to display the specified user's avatar.
2433 * User avatar may be obtained in two ways:
2434 * <pre>
2435 * // Option 1: (shortcut for simple cases, preferred way)
2436 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2437 * $OUTPUT->user_picture($user, array('popup'=>true));
2439 * // Option 2:
2440 * $userpic = new user_picture($user);
2441 * // Set properties of $userpic
2442 * $userpic->popup = true;
2443 * $OUTPUT->render($userpic);
2444 * </pre>
2446 * Theme developers: DO NOT OVERRIDE! Please override function
2447 * {@link core_renderer::render_user_picture()} instead.
2449 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2450 * If any of these are missing, the database is queried. Avoid this
2451 * if at all possible, particularly for reports. It is very bad for performance.
2452 * @param array $options associative array with user picture options, used only if not a user_picture object,
2453 * options are:
2454 * - courseid=$this->page->course->id (course id of user profile in link)
2455 * - size=35 (size of image)
2456 * - link=true (make image clickable - the link leads to user profile)
2457 * - popup=false (open in popup)
2458 * - alttext=true (add image alt attribute)
2459 * - class = image class attribute (default 'userpicture')
2460 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2461 * - includefullname=false (whether to include the user's full name together with the user picture)
2462 * @return string HTML fragment
2464 public function user_picture(stdClass $user, array $options = null) {
2465 $userpicture = new user_picture($user);
2466 foreach ((array)$options as $key=>$value) {
2467 if (array_key_exists($key, $userpicture)) {
2468 $userpicture->$key = $value;
2471 return $this->render($userpicture);
2475 * Internal implementation of user image rendering.
2477 * @param user_picture $userpicture
2478 * @return string
2480 protected function render_user_picture(user_picture $userpicture) {
2481 global $CFG, $DB;
2483 $user = $userpicture->user;
2485 if ($userpicture->alttext) {
2486 if (!empty($user->imagealt)) {
2487 $alt = $user->imagealt;
2488 } else {
2489 $alt = get_string('pictureof', '', fullname($user));
2491 } else {
2492 $alt = '';
2495 if (empty($userpicture->size)) {
2496 $size = 35;
2497 } else if ($userpicture->size === true or $userpicture->size == 1) {
2498 $size = 100;
2499 } else {
2500 $size = $userpicture->size;
2503 $class = $userpicture->class;
2505 if ($user->picture == 0) {
2506 $class .= ' defaultuserpic';
2509 $src = $userpicture->get_url($this->page, $this);
2511 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2512 if (!$userpicture->visibletoscreenreaders) {
2513 $attributes['role'] = 'presentation';
2516 // get the image html output fisrt
2517 $output = html_writer::empty_tag('img', $attributes);
2519 // Show fullname together with the picture when desired.
2520 if ($userpicture->includefullname) {
2521 $output .= fullname($userpicture->user);
2524 // then wrap it in link if needed
2525 if (!$userpicture->link) {
2526 return $output;
2529 if (empty($userpicture->courseid)) {
2530 $courseid = $this->page->course->id;
2531 } else {
2532 $courseid = $userpicture->courseid;
2535 if ($courseid == SITEID) {
2536 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2537 } else {
2538 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2541 $attributes = array('href'=>$url);
2542 if (!$userpicture->visibletoscreenreaders) {
2543 $attributes['tabindex'] = '-1';
2544 $attributes['aria-hidden'] = 'true';
2547 if ($userpicture->popup) {
2548 $id = html_writer::random_id('userpicture');
2549 $attributes['id'] = $id;
2550 $this->add_action_handler(new popup_action('click', $url), $id);
2553 return html_writer::tag('a', $output, $attributes);
2557 * Internal implementation of file tree viewer items rendering.
2559 * @param array $dir
2560 * @return string
2562 public function htmllize_file_tree($dir) {
2563 if (empty($dir['subdirs']) and empty($dir['files'])) {
2564 return '';
2566 $result = '<ul>';
2567 foreach ($dir['subdirs'] as $subdir) {
2568 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2570 foreach ($dir['files'] as $file) {
2571 $filename = $file->get_filename();
2572 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2574 $result .= '</ul>';
2576 return $result;
2580 * Returns HTML to display the file picker
2582 * <pre>
2583 * $OUTPUT->file_picker($options);
2584 * </pre>
2586 * Theme developers: DO NOT OVERRIDE! Please override function
2587 * {@link core_renderer::render_file_picker()} instead.
2589 * @param array $options associative array with file manager options
2590 * options are:
2591 * maxbytes=>-1,
2592 * itemid=>0,
2593 * client_id=>uniqid(),
2594 * acepted_types=>'*',
2595 * return_types=>FILE_INTERNAL,
2596 * context=>$PAGE->context
2597 * @return string HTML fragment
2599 public function file_picker($options) {
2600 $fp = new file_picker($options);
2601 return $this->render($fp);
2605 * Internal implementation of file picker rendering.
2607 * @param file_picker $fp
2608 * @return string
2610 public function render_file_picker(file_picker $fp) {
2611 global $CFG, $OUTPUT, $USER;
2612 $options = $fp->options;
2613 $client_id = $options->client_id;
2614 $strsaved = get_string('filesaved', 'repository');
2615 $straddfile = get_string('openpicker', 'repository');
2616 $strloading = get_string('loading', 'repository');
2617 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2618 $strdroptoupload = get_string('droptoupload', 'moodle');
2619 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2621 $currentfile = $options->currentfile;
2622 if (empty($currentfile)) {
2623 $currentfile = '';
2624 } else {
2625 $currentfile .= ' - ';
2627 if ($options->maxbytes) {
2628 $size = $options->maxbytes;
2629 } else {
2630 $size = get_max_upload_file_size();
2632 if ($size == -1) {
2633 $maxsize = '';
2634 } else {
2635 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2637 if ($options->buttonname) {
2638 $buttonname = ' name="' . $options->buttonname . '"';
2639 } else {
2640 $buttonname = '';
2642 $html = <<<EOD
2643 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2644 $icon_progress
2645 </div>
2646 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2647 <div>
2648 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2649 <span> $maxsize </span>
2650 </div>
2651 EOD;
2652 if ($options->env != 'url') {
2653 $html .= <<<EOD
2654 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2655 <div class="filepicker-filename">
2656 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2657 <div class="dndupload-progressbars"></div>
2658 </div>
2659 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2660 </div>
2661 EOD;
2663 $html .= '</div>';
2664 return $html;
2668 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2670 * @deprecated since Moodle 3.2
2672 * @param string $cmid the course_module id.
2673 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2674 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2676 public function update_module_button($cmid, $modulename) {
2677 global $CFG;
2679 debugging('core_renderer::update_module_button() has been deprecated and should not be used anymore. Activity modules ' .
2680 'should not add the edit module button, the link is already available in the Administration block. Themes can choose ' .
2681 'to display the link in the buttons row consistently for all module types.', DEBUG_DEVELOPER);
2683 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2684 $modulename = get_string('modulename', $modulename);
2685 $string = get_string('updatethis', '', $modulename);
2686 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2687 return $this->single_button($url, $string);
2688 } else {
2689 return '';
2694 * Returns HTML to display a "Turn editing on/off" button in a form.
2696 * @param moodle_url $url The URL + params to send through when clicking the button
2697 * @return string HTML the button
2699 public function edit_button(moodle_url $url) {
2701 $url->param('sesskey', sesskey());
2702 if ($this->page->user_is_editing()) {
2703 $url->param('edit', 'off');
2704 $editstring = get_string('turneditingoff');
2705 } else {
2706 $url->param('edit', 'on');
2707 $editstring = get_string('turneditingon');
2710 return $this->single_button($url, $editstring);
2714 * Returns HTML to display a simple button to close a window
2716 * @param string $text The lang string for the button's label (already output from get_string())
2717 * @return string html fragment
2719 public function close_window_button($text='') {
2720 if (empty($text)) {
2721 $text = get_string('closewindow');
2723 $button = new single_button(new moodle_url('#'), $text, 'get');
2724 $button->add_action(new component_action('click', 'close_window'));
2726 return $this->container($this->render($button), 'closewindow');
2730 * Output an error message. By default wraps the error message in <span class="error">.
2731 * If the error message is blank, nothing is output.
2733 * @param string $message the error message.
2734 * @return string the HTML to output.
2736 public function error_text($message) {
2737 if (empty($message)) {
2738 return '';
2740 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2741 return html_writer::tag('span', $message, array('class' => 'error'));
2745 * Do not call this function directly.
2747 * To terminate the current script with a fatal error, call the {@link print_error}
2748 * function, or throw an exception. Doing either of those things will then call this
2749 * function to display the error, before terminating the execution.
2751 * @param string $message The message to output
2752 * @param string $moreinfourl URL where more info can be found about the error
2753 * @param string $link Link for the Continue button
2754 * @param array $backtrace The execution backtrace
2755 * @param string $debuginfo Debugging information
2756 * @return string the HTML to output.
2758 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2759 global $CFG;
2761 $output = '';
2762 $obbuffer = '';
2764 if ($this->has_started()) {
2765 // we can not always recover properly here, we have problems with output buffering,
2766 // html tables, etc.
2767 $output .= $this->opencontainers->pop_all_but_last();
2769 } else {
2770 // It is really bad if library code throws exception when output buffering is on,
2771 // because the buffered text would be printed before our start of page.
2772 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2773 error_reporting(0); // disable notices from gzip compression, etc.
2774 while (ob_get_level() > 0) {
2775 $buff = ob_get_clean();
2776 if ($buff === false) {
2777 break;
2779 $obbuffer .= $buff;
2781 error_reporting($CFG->debug);
2783 // Output not yet started.
2784 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2785 if (empty($_SERVER['HTTP_RANGE'])) {
2786 @header($protocol . ' 404 Not Found');
2787 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2788 // Coax iOS 10 into sending the session cookie.
2789 @header($protocol . ' 403 Forbidden');
2790 } else {
2791 // Must stop byteserving attempts somehow,
2792 // this is weird but Chrome PDF viewer can be stopped only with 407!
2793 @header($protocol . ' 407 Proxy Authentication Required');
2796 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2797 $this->page->set_url('/'); // no url
2798 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2799 $this->page->set_title(get_string('error'));
2800 $this->page->set_heading($this->page->course->fullname);
2801 $output .= $this->header();
2804 $message = '<p class="errormessage">' . $message . '</p>'.
2805 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2806 get_string('moreinformation') . '</a></p>';
2807 if (empty($CFG->rolesactive)) {
2808 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2809 //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.
2811 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2813 if ($CFG->debugdeveloper) {
2814 if (!empty($debuginfo)) {
2815 $debuginfo = s($debuginfo); // removes all nasty JS
2816 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2817 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2819 if (!empty($backtrace)) {
2820 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2822 if ($obbuffer !== '' ) {
2823 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2827 if (empty($CFG->rolesactive)) {
2828 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2829 } else if (!empty($link)) {
2830 $output .= $this->continue_button($link);
2833 $output .= $this->footer();
2835 // Padding to encourage IE to display our error page, rather than its own.
2836 $output .= str_repeat(' ', 512);
2838 return $output;
2842 * Output a notification (that is, a status message about something that has just happened).
2844 * Note: \core\notification::add() may be more suitable for your usage.
2846 * @param string $message The message to print out.
2847 * @param string $type The type of notification. See constants on \core\output\notification.
2848 * @return string the HTML to output.
2850 public function notification($message, $type = null) {
2851 $typemappings = [
2852 // Valid types.
2853 'success' => \core\output\notification::NOTIFY_SUCCESS,
2854 'info' => \core\output\notification::NOTIFY_INFO,
2855 'warning' => \core\output\notification::NOTIFY_WARNING,
2856 'error' => \core\output\notification::NOTIFY_ERROR,
2858 // Legacy types mapped to current types.
2859 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2860 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2861 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2862 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2863 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2864 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2865 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2868 $extraclasses = [];
2870 if ($type) {
2871 if (strpos($type, ' ') === false) {
2872 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2873 if (isset($typemappings[$type])) {
2874 $type = $typemappings[$type];
2875 } else {
2876 // The value provided did not match a known type. It must be an extra class.
2877 $extraclasses = [$type];
2879 } else {
2880 // Identify what type of notification this is.
2881 $classarray = explode(' ', self::prepare_classes($type));
2883 // Separate out the type of notification from the extra classes.
2884 foreach ($classarray as $class) {
2885 if (isset($typemappings[$class])) {
2886 $type = $typemappings[$class];
2887 } else {
2888 $extraclasses[] = $class;
2894 $notification = new \core\output\notification($message, $type);
2895 if (count($extraclasses)) {
2896 $notification->set_extra_classes($extraclasses);
2899 // Return the rendered template.
2900 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2904 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2906 public function notify_problem() {
2907 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
2908 'please use \core\notification::add(), or \core\output\notification as required.');
2912 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2914 public function notify_success() {
2915 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
2916 'please use \core\notification::add(), or \core\output\notification as required.');
2920 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2922 public function notify_message() {
2923 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
2924 'please use \core\notification::add(), or \core\output\notification as required.');
2928 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2930 public function notify_redirect() {
2931 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
2932 'please use \core\notification::add(), or \core\output\notification as required.');
2936 * Render a notification (that is, a status message about something that has
2937 * just happened).
2939 * @param \core\output\notification $notification the notification to print out
2940 * @return string the HTML to output.
2942 protected function render_notification(\core\output\notification $notification) {
2943 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2947 * Returns HTML to display a continue button that goes to a particular URL.
2949 * @param string|moodle_url $url The url the button goes to.
2950 * @return string the HTML to output.
2952 public function continue_button($url) {
2953 if (!($url instanceof moodle_url)) {
2954 $url = new moodle_url($url);
2956 $button = new single_button($url, get_string('continue'), 'get', true);
2957 $button->class = 'continuebutton';
2959 return $this->render($button);
2963 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2965 * Theme developers: DO NOT OVERRIDE! Please override function
2966 * {@link core_renderer::render_paging_bar()} instead.
2968 * @param int $totalcount The total number of entries available to be paged through
2969 * @param int $page The page you are currently viewing
2970 * @param int $perpage The number of entries that should be shown per page
2971 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2972 * @param string $pagevar name of page parameter that holds the page number
2973 * @return string the HTML to output.
2975 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2976 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2977 return $this->render($pb);
2981 * Internal implementation of paging bar rendering.
2983 * @param paging_bar $pagingbar
2984 * @return string
2986 protected function render_paging_bar(paging_bar $pagingbar) {
2987 $output = '';
2988 $pagingbar = clone($pagingbar);
2989 $pagingbar->prepare($this, $this->page, $this->target);
2991 if ($pagingbar->totalcount > $pagingbar->perpage) {
2992 $output .= get_string('page') . ':';
2994 if (!empty($pagingbar->previouslink)) {
2995 $output .= ' (' . $pagingbar->previouslink . ') ';
2998 if (!empty($pagingbar->firstlink)) {
2999 $output .= ' ' . $pagingbar->firstlink . ' ...';
3002 foreach ($pagingbar->pagelinks as $link) {
3003 $output .= " $link";
3006 if (!empty($pagingbar->lastlink)) {
3007 $output .= ' ... ' . $pagingbar->lastlink . ' ';
3010 if (!empty($pagingbar->nextlink)) {
3011 $output .= ' (' . $pagingbar->nextlink . ')';
3015 return html_writer::tag('div', $output, array('class' => 'paging'));
3019 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3021 * @param string $current the currently selected letter.
3022 * @param string $class class name to add to this initial bar.
3023 * @param string $title the name to put in front of this initial bar.
3024 * @param string $urlvar URL parameter name for this initial.
3025 * @param string $url URL object.
3026 * @param array $alpha of letters in the alphabet.
3027 * @return string the HTML to output.
3029 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3030 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3031 return $this->render($ib);
3035 * Internal implementation of initials bar rendering.
3037 * @param initials_bar $initialsbar
3038 * @return string
3040 protected function render_initials_bar(initials_bar $initialsbar) {
3041 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3045 * Output the place a skip link goes to.
3047 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3048 * @return string the HTML to output.
3050 public function skip_link_target($id = null) {
3051 return html_writer::span('', '', array('id' => $id));
3055 * Outputs a heading
3057 * @param string $text The text of the heading
3058 * @param int $level The level of importance of the heading. Defaulting to 2
3059 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3060 * @param string $id An optional ID
3061 * @return string the HTML to output.
3063 public function heading($text, $level = 2, $classes = null, $id = null) {
3064 $level = (integer) $level;
3065 if ($level < 1 or $level > 6) {
3066 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3068 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3072 * Outputs a box.
3074 * @param string $contents The contents of the box
3075 * @param string $classes A space-separated list of CSS classes
3076 * @param string $id An optional ID
3077 * @param array $attributes An array of other attributes to give the box.
3078 * @return string the HTML to output.
3080 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3081 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3085 * Outputs the opening section of a box.
3087 * @param string $classes A space-separated list of CSS classes
3088 * @param string $id An optional ID
3089 * @param array $attributes An array of other attributes to give the box.
3090 * @return string the HTML to output.
3092 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3093 $this->opencontainers->push('box', html_writer::end_tag('div'));
3094 $attributes['id'] = $id;
3095 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
3096 return html_writer::start_tag('div', $attributes);
3100 * Outputs the closing section of a box.
3102 * @return string the HTML to output.
3104 public function box_end() {
3105 return $this->opencontainers->pop('box');
3109 * Outputs a container.
3111 * @param string $contents The contents of the box
3112 * @param string $classes A space-separated list of CSS classes
3113 * @param string $id An optional ID
3114 * @return string the HTML to output.
3116 public function container($contents, $classes = null, $id = null) {
3117 return $this->container_start($classes, $id) . $contents . $this->container_end();
3121 * Outputs the opening section of a container.
3123 * @param string $classes A space-separated list of CSS classes
3124 * @param string $id An optional ID
3125 * @return string the HTML to output.
3127 public function container_start($classes = null, $id = null) {
3128 $this->opencontainers->push('container', html_writer::end_tag('div'));
3129 return html_writer::start_tag('div', array('id' => $id,
3130 'class' => renderer_base::prepare_classes($classes)));
3134 * Outputs the closing section of a container.
3136 * @return string the HTML to output.
3138 public function container_end() {
3139 return $this->opencontainers->pop('container');
3143 * Make nested HTML lists out of the items
3145 * The resulting list will look something like this:
3147 * <pre>
3148 * <<ul>>
3149 * <<li>><div class='tree_item parent'>(item contents)</div>
3150 * <<ul>
3151 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3152 * <</ul>>
3153 * <</li>>
3154 * <</ul>>
3155 * </pre>
3157 * @param array $items
3158 * @param array $attrs html attributes passed to the top ofs the list
3159 * @return string HTML
3161 public function tree_block_contents($items, $attrs = array()) {
3162 // exit if empty, we don't want an empty ul element
3163 if (empty($items)) {
3164 return '';
3166 // array of nested li elements
3167 $lis = array();
3168 foreach ($items as $item) {
3169 // this applies to the li item which contains all child lists too
3170 $content = $item->content($this);
3171 $liclasses = array($item->get_css_type());
3172 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3173 $liclasses[] = 'collapsed';
3175 if ($item->isactive === true) {
3176 $liclasses[] = 'current_branch';
3178 $liattr = array('class'=>join(' ',$liclasses));
3179 // class attribute on the div item which only contains the item content
3180 $divclasses = array('tree_item');
3181 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3182 $divclasses[] = 'branch';
3183 } else {
3184 $divclasses[] = 'leaf';
3186 if (!empty($item->classes) && count($item->classes)>0) {
3187 $divclasses[] = join(' ', $item->classes);
3189 $divattr = array('class'=>join(' ', $divclasses));
3190 if (!empty($item->id)) {
3191 $divattr['id'] = $item->id;
3193 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3194 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3195 $content = html_writer::empty_tag('hr') . $content;
3197 $content = html_writer::tag('li', $content, $liattr);
3198 $lis[] = $content;
3200 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3204 * Returns a search box.
3206 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3207 * @return string HTML with the search form hidden by default.
3209 public function search_box($id = false) {
3210 global $CFG;
3212 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3213 // result in an extra included file for each site, even the ones where global search
3214 // is disabled.
3215 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3216 return '';
3219 if ($id == false) {
3220 $id = uniqid();
3221 } else {
3222 // Needs to be cleaned, we use it for the input id.
3223 $id = clean_param($id, PARAM_ALPHANUMEXT);
3226 // JS to animate the form.
3227 $this->page->requires->js_call_amd('core/search-input', 'init', array($id));
3229 $searchicon = html_writer::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
3230 array('role' => 'button', 'tabindex' => 0));
3231 $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot . '/search/index.php');
3232 $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
3233 'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id, 'class' => 'form-control');
3235 $contents = html_writer::tag('label', get_string('enteryoursearchquery', 'search'),
3236 array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer::tag('input', '', $inputattrs);
3237 if ($this->page->context && $this->page->context->contextlevel !== CONTEXT_SYSTEM) {
3238 $contents .= html_writer::empty_tag('input', ['type' => 'hidden',
3239 'name' => 'context', 'value' => $this->page->context->id]);
3241 $searchinput = html_writer::tag('form', $contents, $formattrs);
3243 return html_writer::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper nav-link', 'id' => $id));
3247 * Allow plugins to provide some content to be rendered in the navbar.
3248 * The plugin must define a PLUGIN_render_navbar_output function that returns
3249 * the HTML they wish to add to the navbar.
3251 * @return string HTML for the navbar
3253 public function navbar_plugin_output() {
3254 $output = '';
3256 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3257 foreach ($pluginsfunction as $plugintype => $plugins) {
3258 foreach ($plugins as $pluginfunction) {
3259 $output .= $pluginfunction($this);
3264 return $output;
3268 * Construct a user menu, returning HTML that can be echoed out by a
3269 * layout file.
3271 * @param stdClass $user A user object, usually $USER.
3272 * @param bool $withlinks true if a dropdown should be built.
3273 * @return string HTML fragment.
3275 public function user_menu($user = null, $withlinks = null) {
3276 global $USER, $CFG;
3277 require_once($CFG->dirroot . '/user/lib.php');
3279 if (is_null($user)) {
3280 $user = $USER;
3283 // Note: this behaviour is intended to match that of core_renderer::login_info,
3284 // but should not be considered to be good practice; layout options are
3285 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3286 if (is_null($withlinks)) {
3287 $withlinks = empty($this->page->layout_options['nologinlinks']);
3290 // Add a class for when $withlinks is false.
3291 $usermenuclasses = 'usermenu';
3292 if (!$withlinks) {
3293 $usermenuclasses .= ' withoutlinks';
3296 $returnstr = "";
3298 // If during initial install, return the empty return string.
3299 if (during_initial_install()) {
3300 return $returnstr;
3303 $loginpage = $this->is_login_page();
3304 $loginurl = get_login_url();
3305 // If not logged in, show the typical not-logged-in string.
3306 if (!isloggedin()) {
3307 $returnstr = get_string('loggedinnot', 'moodle');
3308 if (!$loginpage) {
3309 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3311 return html_writer::div(
3312 html_writer::span(
3313 $returnstr,
3314 'login'
3316 $usermenuclasses
3321 // If logged in as a guest user, show a string to that effect.
3322 if (isguestuser()) {
3323 $returnstr = get_string('loggedinasguest');
3324 if (!$loginpage && $withlinks) {
3325 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3328 return html_writer::div(
3329 html_writer::span(
3330 $returnstr,
3331 'login'
3333 $usermenuclasses
3337 // Get some navigation opts.
3338 $opts = user_get_user_navigation_info($user, $this->page);
3340 $avatarclasses = "avatars";
3341 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3342 $usertextcontents = $opts->metadata['userfullname'];
3344 // Other user.
3345 if (!empty($opts->metadata['asotheruser'])) {
3346 $avatarcontents .= html_writer::span(
3347 $opts->metadata['realuseravatar'],
3348 'avatar realuser'
3350 $usertextcontents = $opts->metadata['realuserfullname'];
3351 $usertextcontents .= html_writer::tag(
3352 'span',
3353 get_string(
3354 'loggedinas',
3355 'moodle',
3356 html_writer::span(
3357 $opts->metadata['userfullname'],
3358 'value'
3361 array('class' => 'meta viewingas')
3365 // Role.
3366 if (!empty($opts->metadata['asotherrole'])) {
3367 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3368 $usertextcontents .= html_writer::span(
3369 $opts->metadata['rolename'],
3370 'meta role role-' . $role
3374 // User login failures.
3375 if (!empty($opts->metadata['userloginfail'])) {
3376 $usertextcontents .= html_writer::span(
3377 $opts->metadata['userloginfail'],
3378 'meta loginfailures'
3382 // MNet.
3383 if (!empty($opts->metadata['asmnetuser'])) {
3384 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3385 $usertextcontents .= html_writer::span(
3386 $opts->metadata['mnetidprovidername'],
3387 'meta mnet mnet-' . $mnet
3391 $returnstr .= html_writer::span(
3392 html_writer::span($usertextcontents, 'usertext mr-1') .
3393 html_writer::span($avatarcontents, $avatarclasses),
3394 'userbutton'
3397 // Create a divider (well, a filler).
3398 $divider = new action_menu_filler();
3399 $divider->primary = false;
3401 $am = new action_menu();
3402 $am->set_menu_trigger(
3403 $returnstr
3405 $am->set_alignment(action_menu::TR, action_menu::BR);
3406 $am->set_nowrap_on_items();
3407 if ($withlinks) {
3408 $navitemcount = count($opts->navitems);
3409 $idx = 0;
3410 foreach ($opts->navitems as $key => $value) {
3412 switch ($value->itemtype) {
3413 case 'divider':
3414 // If the nav item is a divider, add one and skip link processing.
3415 $am->add($divider);
3416 break;
3418 case 'invalid':
3419 // Silently skip invalid entries (should we post a notification?).
3420 break;
3422 case 'link':
3423 // Process this as a link item.
3424 $pix = null;
3425 if (isset($value->pix) && !empty($value->pix)) {
3426 $pix = new pix_icon($value->pix, $value->title, null, array('class' => 'iconsmall'));
3427 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3428 $value->title = html_writer::img(
3429 $value->imgsrc,
3430 $value->title,
3431 array('class' => 'iconsmall')
3432 ) . $value->title;
3435 $al = new action_menu_link_secondary(
3436 $value->url,
3437 $pix,
3438 $value->title,
3439 array('class' => 'icon')
3441 if (!empty($value->titleidentifier)) {
3442 $al->attributes['data-title'] = $value->titleidentifier;
3444 $am->add($al);
3445 break;
3448 $idx++;
3450 // Add dividers after the first item and before the last item.
3451 if ($idx == 1 || $idx == $navitemcount - 1) {
3452 $am->add($divider);
3457 return html_writer::div(
3458 $this->render($am),
3459 $usermenuclasses
3464 * Return the navbar content so that it can be echoed out by the layout
3466 * @return string XHTML navbar
3468 public function navbar() {
3469 $items = $this->page->navbar->get_items();
3470 $itemcount = count($items);
3471 if ($itemcount === 0) {
3472 return '';
3475 $htmlblocks = array();
3476 // Iterate the navarray and display each node
3477 $separator = get_separator();
3478 for ($i=0;$i < $itemcount;$i++) {
3479 $item = $items[$i];
3480 $item->hideicon = true;
3481 if ($i===0) {
3482 $content = html_writer::tag('li', $this->render($item));
3483 } else {
3484 $content = html_writer::tag('li', $separator.$this->render($item));
3486 $htmlblocks[] = $content;
3489 //accessibility: heading for navbar list (MDL-20446)
3490 $navbarcontent = html_writer::tag('span', get_string('pagepath'),
3491 array('class' => 'accesshide', 'id' => 'navbar-label'));
3492 $navbarcontent .= html_writer::tag('nav',
3493 html_writer::tag('ul', join('', $htmlblocks)),
3494 array('aria-labelledby' => 'navbar-label'));
3495 // XHTML
3496 return $navbarcontent;
3500 * Renders a breadcrumb navigation node object.
3502 * @param breadcrumb_navigation_node $item The navigation node to render.
3503 * @return string HTML fragment
3505 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3507 if ($item->action instanceof moodle_url) {
3508 $content = $item->get_content();
3509 $title = $item->get_title();
3510 $attributes = array();
3511 $attributes['itemprop'] = 'url';
3512 if ($title !== '') {
3513 $attributes['title'] = $title;
3515 if ($item->hidden) {
3516 $attributes['class'] = 'dimmed_text';
3518 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3519 $content = html_writer::link($item->action, $content, $attributes);
3521 $attributes = array();
3522 $attributes['itemscope'] = '';
3523 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3524 $content = html_writer::tag('span', $content, $attributes);
3526 } else {
3527 $content = $this->render_navigation_node($item);
3529 return $content;
3533 * Renders a navigation node object.
3535 * @param navigation_node $item The navigation node to render.
3536 * @return string HTML fragment
3538 protected function render_navigation_node(navigation_node $item) {
3539 $content = $item->get_content();
3540 $title = $item->get_title();
3541 if ($item->icon instanceof renderable && !$item->hideicon) {
3542 $icon = $this->render($item->icon);
3543 $content = $icon.$content; // use CSS for spacing of icons
3545 if ($item->helpbutton !== null) {
3546 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3548 if ($content === '') {
3549 return '';
3551 if ($item->action instanceof action_link) {
3552 $link = $item->action;
3553 if ($item->hidden) {
3554 $link->add_class('dimmed');
3556 if (!empty($content)) {
3557 // Providing there is content we will use that for the link content.
3558 $link->text = $content;
3560 $content = $this->render($link);
3561 } else if ($item->action instanceof moodle_url) {
3562 $attributes = array();
3563 if ($title !== '') {
3564 $attributes['title'] = $title;
3566 if ($item->hidden) {
3567 $attributes['class'] = 'dimmed_text';
3569 $content = html_writer::link($item->action, $content, $attributes);
3571 } else if (is_string($item->action) || empty($item->action)) {
3572 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3573 if ($title !== '') {
3574 $attributes['title'] = $title;
3576 if ($item->hidden) {
3577 $attributes['class'] = 'dimmed_text';
3579 $content = html_writer::tag('span', $content, $attributes);
3581 return $content;
3585 * Accessibility: Right arrow-like character is
3586 * used in the breadcrumb trail, course navigation menu
3587 * (previous/next activity), calendar, and search forum block.
3588 * If the theme does not set characters, appropriate defaults
3589 * are set automatically. Please DO NOT
3590 * use &lt; &gt; &raquo; - these are confusing for blind users.
3592 * @return string
3594 public function rarrow() {
3595 return $this->page->theme->rarrow;
3599 * Accessibility: Left arrow-like character is
3600 * used in the breadcrumb trail, course navigation menu
3601 * (previous/next activity), calendar, and search forum block.
3602 * If the theme does not set characters, appropriate defaults
3603 * are set automatically. Please DO NOT
3604 * use &lt; &gt; &raquo; - these are confusing for blind users.
3606 * @return string
3608 public function larrow() {
3609 return $this->page->theme->larrow;
3613 * Accessibility: Up arrow-like character is used in
3614 * the book heirarchical navigation.
3615 * If the theme does not set characters, appropriate defaults
3616 * are set automatically. Please DO NOT
3617 * use ^ - this is confusing for blind users.
3619 * @return string
3621 public function uarrow() {
3622 return $this->page->theme->uarrow;
3626 * Accessibility: Down arrow-like character.
3627 * If the theme does not set characters, appropriate defaults
3628 * are set automatically.
3630 * @return string
3632 public function darrow() {
3633 return $this->page->theme->darrow;
3637 * Returns the custom menu if one has been set
3639 * A custom menu can be configured by browsing to
3640 * Settings: Administration > Appearance > Themes > Theme settings
3641 * and then configuring the custommenu config setting as described.
3643 * Theme developers: DO NOT OVERRIDE! Please override function
3644 * {@link core_renderer::render_custom_menu()} instead.
3646 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3647 * @return string
3649 public function custom_menu($custommenuitems = '') {
3650 global $CFG;
3651 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3652 $custommenuitems = $CFG->custommenuitems;
3654 if (empty($custommenuitems)) {
3655 return '';
3657 $custommenu = new custom_menu($custommenuitems, current_language());
3658 return $this->render($custommenu);
3662 * Renders a custom menu object (located in outputcomponents.php)
3664 * The custom menu this method produces makes use of the YUI3 menunav widget
3665 * and requires very specific html elements and classes.
3667 * @staticvar int $menucount
3668 * @param custom_menu $menu
3669 * @return string
3671 protected function render_custom_menu(custom_menu $menu) {
3672 static $menucount = 0;
3673 // If the menu has no children return an empty string
3674 if (!$menu->has_children()) {
3675 return '';
3677 // Increment the menu count. This is used for ID's that get worked with
3678 // in JavaScript as is essential
3679 $menucount++;
3680 // Initialise this custom menu (the custom menu object is contained in javascript-static
3681 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
3682 $jscode = "(function(){{$jscode}})";
3683 $this->page->requires->yui_module('node-menunav', $jscode);
3684 // Build the root nodes as required by YUI
3685 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
3686 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3687 $content .= html_writer::start_tag('ul');
3688 // Render each child
3689 foreach ($menu->get_children() as $item) {
3690 $content .= $this->render_custom_menu_item($item);
3692 // Close the open tags
3693 $content .= html_writer::end_tag('ul');
3694 $content .= html_writer::end_tag('div');
3695 $content .= html_writer::end_tag('div');
3696 // Return the custom menu
3697 return $content;
3701 * Renders a custom menu node as part of a submenu
3703 * The custom menu this method produces makes use of the YUI3 menunav widget
3704 * and requires very specific html elements and classes.
3706 * @see core:renderer::render_custom_menu()
3708 * @staticvar int $submenucount
3709 * @param custom_menu_item $menunode
3710 * @return string
3712 protected function render_custom_menu_item(custom_menu_item $menunode) {
3713 // Required to ensure we get unique trackable id's
3714 static $submenucount = 0;
3715 if ($menunode->has_children()) {
3716 // If the child has menus render it as a sub menu
3717 $submenucount++;
3718 $content = html_writer::start_tag('li');
3719 if ($menunode->get_url() !== null) {
3720 $url = $menunode->get_url();
3721 } else {
3722 $url = '#cm_submenu_'.$submenucount;
3724 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3725 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3726 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3727 $content .= html_writer::start_tag('ul');
3728 foreach ($menunode->get_children() as $menunode) {
3729 $content .= $this->render_custom_menu_item($menunode);
3731 $content .= html_writer::end_tag('ul');
3732 $content .= html_writer::end_tag('div');
3733 $content .= html_writer::end_tag('div');
3734 $content .= html_writer::end_tag('li');
3735 } else {
3736 // The node doesn't have children so produce a final menuitem.
3737 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3738 $content = '';
3739 if (preg_match("/^#+$/", $menunode->get_text())) {
3741 // This is a divider.
3742 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3743 } else {
3744 $content = html_writer::start_tag(
3745 'li',
3746 array(
3747 'class' => 'yui3-menuitem'
3750 if ($menunode->get_url() !== null) {
3751 $url = $menunode->get_url();
3752 } else {
3753 $url = '#';
3755 $content .= html_writer::link(
3756 $url,
3757 $menunode->get_text(),
3758 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3761 $content .= html_writer::end_tag('li');
3763 // Return the sub menu
3764 return $content;
3768 * Renders theme links for switching between default and other themes.
3770 * @return string
3772 protected function theme_switch_links() {
3774 $actualdevice = core_useragent::get_device_type();
3775 $currentdevice = $this->page->devicetypeinuse;
3776 $switched = ($actualdevice != $currentdevice);
3778 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3779 // The user is using the a default device and hasn't switched so don't shown the switch
3780 // device links.
3781 return '';
3784 if ($switched) {
3785 $linktext = get_string('switchdevicerecommended');
3786 $devicetype = $actualdevice;
3787 } else {
3788 $linktext = get_string('switchdevicedefault');
3789 $devicetype = 'default';
3791 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3793 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3794 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3795 $content .= html_writer::end_tag('div');
3797 return $content;
3801 * Renders tabs
3803 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3805 * Theme developers: In order to change how tabs are displayed please override functions
3806 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3808 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3809 * @param string|null $selected which tab to mark as selected, all parent tabs will
3810 * automatically be marked as activated
3811 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3812 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3813 * @return string
3815 public final function tabtree($tabs, $selected = null, $inactive = null) {
3816 return $this->render(new tabtree($tabs, $selected, $inactive));
3820 * Renders tabtree
3822 * @param tabtree $tabtree
3823 * @return string
3825 protected function render_tabtree(tabtree $tabtree) {
3826 if (empty($tabtree->subtree)) {
3827 return '';
3829 $str = '';
3830 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
3831 $str .= $this->render_tabobject($tabtree);
3832 $str .= html_writer::end_tag('div').
3833 html_writer::tag('div', ' ', array('class' => 'clearer'));
3834 return $str;
3838 * Renders tabobject (part of tabtree)
3840 * This function is called from {@link core_renderer::render_tabtree()}
3841 * and also it calls itself when printing the $tabobject subtree recursively.
3843 * Property $tabobject->level indicates the number of row of tabs.
3845 * @param tabobject $tabobject
3846 * @return string HTML fragment
3848 protected function render_tabobject(tabobject $tabobject) {
3849 $str = '';
3851 // Print name of the current tab.
3852 if ($tabobject instanceof tabtree) {
3853 // No name for tabtree root.
3854 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3855 // Tab name without a link. The <a> tag is used for styling.
3856 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3857 } else {
3858 // Tab name with a link.
3859 if (!($tabobject->link instanceof moodle_url)) {
3860 // backward compartibility when link was passed as quoted string
3861 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3862 } else {
3863 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3867 if (empty($tabobject->subtree)) {
3868 if ($tabobject->selected) {
3869 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3871 return $str;
3874 // Print subtree.
3875 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
3876 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3877 $cnt = 0;
3878 foreach ($tabobject->subtree as $tab) {
3879 $liclass = '';
3880 if (!$cnt) {
3881 $liclass .= ' first';
3883 if ($cnt == count($tabobject->subtree) - 1) {
3884 $liclass .= ' last';
3886 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3887 $liclass .= ' onerow';
3890 if ($tab->selected) {
3891 $liclass .= ' here selected';
3892 } else if ($tab->activated) {
3893 $liclass .= ' here active';
3896 // This will recursively call function render_tabobject() for each item in subtree.
3897 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3898 $cnt++;
3900 $str .= html_writer::end_tag('ul');
3903 return $str;
3907 * Get the HTML for blocks in the given region.
3909 * @since Moodle 2.5.1 2.6
3910 * @param string $region The region to get HTML for.
3911 * @return string HTML.
3913 public function blocks($region, $classes = array(), $tag = 'aside') {
3914 $displayregion = $this->page->apply_theme_region_manipulations($region);
3915 $classes = (array)$classes;
3916 $classes[] = 'block-region';
3917 $attributes = array(
3918 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3919 'class' => join(' ', $classes),
3920 'data-blockregion' => $displayregion,
3921 'data-droptarget' => '1'
3923 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3924 $content = $this->blocks_for_region($displayregion);
3925 } else {
3926 $content = '';
3928 return html_writer::tag($tag, $content, $attributes);
3932 * Renders a custom block region.
3934 * Use this method if you want to add an additional block region to the content of the page.
3935 * Please note this should only be used in special situations.
3936 * We want to leave the theme is control where ever possible!
3938 * This method must use the same method that the theme uses within its layout file.
3939 * As such it asks the theme what method it is using.
3940 * It can be one of two values, blocks or blocks_for_region (deprecated).
3942 * @param string $regionname The name of the custom region to add.
3943 * @return string HTML for the block region.
3945 public function custom_block_region($regionname) {
3946 if ($this->page->theme->get_block_render_method() === 'blocks') {
3947 return $this->blocks($regionname);
3948 } else {
3949 return $this->blocks_for_region($regionname);
3954 * Returns the CSS classes to apply to the body tag.
3956 * @since Moodle 2.5.1 2.6
3957 * @param array $additionalclasses Any additional classes to apply.
3958 * @return string
3960 public function body_css_classes(array $additionalclasses = array()) {
3961 // Add a class for each block region on the page.
3962 // We use the block manager here because the theme object makes get_string calls.
3963 $usedregions = array();
3964 foreach ($this->page->blocks->get_regions() as $region) {
3965 $additionalclasses[] = 'has-region-'.$region;
3966 if ($this->page->blocks->region_has_content($region, $this)) {
3967 $additionalclasses[] = 'used-region-'.$region;
3968 $usedregions[] = $region;
3969 } else {
3970 $additionalclasses[] = 'empty-region-'.$region;
3972 if ($this->page->blocks->region_completely_docked($region, $this)) {
3973 $additionalclasses[] = 'docked-region-'.$region;
3976 if (!$usedregions) {
3977 // No regions means there is only content, add 'content-only' class.
3978 $additionalclasses[] = 'content-only';
3979 } else if (count($usedregions) === 1) {
3980 // Add the -only class for the only used region.
3981 $region = array_shift($usedregions);
3982 $additionalclasses[] = $region . '-only';
3984 foreach ($this->page->layout_options as $option => $value) {
3985 if ($value) {
3986 $additionalclasses[] = 'layout-option-'.$option;
3989 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
3990 return $css;
3994 * The ID attribute to apply to the body tag.
3996 * @since Moodle 2.5.1 2.6
3997 * @return string
3999 public function body_id() {
4000 return $this->page->bodyid;
4004 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4006 * @since Moodle 2.5.1 2.6
4007 * @param string|array $additionalclasses Any additional classes to give the body tag,
4008 * @return string
4010 public function body_attributes($additionalclasses = array()) {
4011 if (!is_array($additionalclasses)) {
4012 $additionalclasses = explode(' ', $additionalclasses);
4014 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4018 * Gets HTML for the page heading.
4020 * @since Moodle 2.5.1 2.6
4021 * @param string $tag The tag to encase the heading in. h1 by default.
4022 * @return string HTML.
4024 public function page_heading($tag = 'h1') {
4025 return html_writer::tag($tag, $this->page->heading);
4029 * Gets the HTML for the page heading button.
4031 * @since Moodle 2.5.1 2.6
4032 * @return string HTML.
4034 public function page_heading_button() {
4035 return $this->page->button;
4039 * Returns the Moodle docs link to use for this page.
4041 * @since Moodle 2.5.1 2.6
4042 * @param string $text
4043 * @return string
4045 public function page_doc_link($text = null) {
4046 if ($text === null) {
4047 $text = get_string('moodledocslink');
4049 $path = page_get_doc_link_path($this->page);
4050 if (!$path) {
4051 return '';
4053 return $this->doc_link($path, $text);
4057 * Returns the page heading menu.
4059 * @since Moodle 2.5.1 2.6
4060 * @return string HTML.
4062 public function page_heading_menu() {
4063 return $this->page->headingmenu;
4067 * Returns the title to use on the page.
4069 * @since Moodle 2.5.1 2.6
4070 * @return string
4072 public function page_title() {
4073 return $this->page->title;
4077 * Returns the URL for the favicon.
4079 * @since Moodle 2.5.1 2.6
4080 * @return string The favicon URL
4082 public function favicon() {
4083 return $this->image_url('favicon', 'theme');
4087 * Renders preferences groups.
4089 * @param preferences_groups $renderable The renderable
4090 * @return string The output.
4092 public function render_preferences_groups(preferences_groups $renderable) {
4093 $html = '';
4094 $html .= html_writer::start_div('row-fluid');
4095 $html .= html_writer::start_tag('div', array('class' => 'span12 preferences-groups'));
4096 $i = 0;
4097 $open = false;
4098 foreach ($renderable->groups as $group) {
4099 if ($i == 0 || $i % 3 == 0) {
4100 if ($open) {
4101 $html .= html_writer::end_tag('div');
4103 $html .= html_writer::start_tag('div', array('class' => 'row-fluid'));
4104 $open = true;
4106 $html .= $this->render($group);
4107 $i++;
4110 $html .= html_writer::end_tag('div');
4112 $html .= html_writer::end_tag('ul');
4113 $html .= html_writer::end_tag('div');
4114 $html .= html_writer::end_div();
4115 return $html;
4119 * Renders preferences group.
4121 * @param preferences_group $renderable The renderable
4122 * @return string The output.
4124 public function render_preferences_group(preferences_group $renderable) {
4125 $html = '';
4126 $html .= html_writer::start_tag('div', array('class' => 'span4 preferences-group'));
4127 $html .= $this->heading($renderable->title, 3);
4128 $html .= html_writer::start_tag('ul');
4129 foreach ($renderable->nodes as $node) {
4130 if ($node->has_children()) {
4131 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4133 $html .= html_writer::tag('li', $this->render($node));
4135 $html .= html_writer::end_tag('ul');
4136 $html .= html_writer::end_tag('div');
4137 return $html;
4140 public function context_header($headerinfo = null, $headinglevel = 1) {
4141 global $DB, $USER, $CFG;
4142 require_once($CFG->dirroot . '/user/lib.php');
4143 $context = $this->page->context;
4144 $heading = null;
4145 $imagedata = null;
4146 $subheader = null;
4147 $userbuttons = null;
4148 // Make sure to use the heading if it has been set.
4149 if (isset($headerinfo['heading'])) {
4150 $heading = $headerinfo['heading'];
4152 // The user context currently has images and buttons. Other contexts may follow.
4153 if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
4154 if (isset($headerinfo['user'])) {
4155 $user = $headerinfo['user'];
4156 } else {
4157 // Look up the user information if it is not supplied.
4158 $user = $DB->get_record('user', array('id' => $context->instanceid));
4161 // If the user context is set, then use that for capability checks.
4162 if (isset($headerinfo['usercontext'])) {
4163 $context = $headerinfo['usercontext'];
4166 // Only provide user information if the user is the current user, or a user which the current user can view.
4167 // When checking user_can_view_profile(), either:
4168 // If the page context is course, check the course context (from the page object) or;
4169 // If page context is NOT course, then check across all courses.
4170 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4172 if (user_can_view_profile($user, $course)) {
4173 // Use the user's full name if the heading isn't set.
4174 if (!isset($heading)) {
4175 $heading = fullname($user);
4178 $imagedata = $this->user_picture($user, array('size' => 100));
4180 // Check to see if we should be displaying a message button.
4181 if (!empty($CFG->messaging) && $USER->id != $user->id && has_capability('moodle/site:sendmessage', $context)) {
4182 $iscontact = !empty(message_get_contact($user->id));
4183 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4184 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4185 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4186 $userbuttons = array(
4187 'messages' => array(
4188 'buttontype' => 'message',
4189 'title' => get_string('message', 'message'),
4190 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4191 'image' => 'message',
4192 'linkattributes' => array('role' => 'button'),
4193 'page' => $this->page
4195 'togglecontact' => array(
4196 'buttontype' => 'togglecontact',
4197 'title' => get_string($contacttitle, 'message'),
4198 'url' => new moodle_url('/message/index.php', array(
4199 'user1' => $USER->id,
4200 'user2' => $user->id,
4201 $contacturlaction => $user->id,
4202 'sesskey' => sesskey())
4204 'image' => $contactimage,
4205 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4206 'page' => $this->page
4210 $this->page->requires->string_for_js('changesmadereallygoaway', 'moodle');
4212 } else {
4213 $heading = null;
4217 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4218 return $this->render_context_header($contextheader);
4222 * Renders the skip links for the page.
4224 * @param array $links List of skip links.
4225 * @return string HTML for the skip links.
4227 public function render_skip_links($links) {
4228 $context = [ 'links' => []];
4230 foreach ($links as $url => $text) {
4231 $context['links'][] = [ 'url' => $url, 'text' => $text];
4234 return $this->render_from_template('core/skip_links', $context);
4238 * Renders the header bar.
4240 * @param context_header $contextheader Header bar object.
4241 * @return string HTML for the header bar.
4243 protected function render_context_header(context_header $contextheader) {
4245 // All the html stuff goes here.
4246 $html = html_writer::start_div('page-context-header');
4248 // Image data.
4249 if (isset($contextheader->imagedata)) {
4250 // Header specific image.
4251 $html .= html_writer::div($contextheader->imagedata, 'page-header-image');
4254 // Headings.
4255 if (!isset($contextheader->heading)) {
4256 $headings = $this->heading($this->page->heading, $contextheader->headinglevel);
4257 } else {
4258 $headings = $this->heading($contextheader->heading, $contextheader->headinglevel);
4261 $html .= html_writer::tag('div', $headings, array('class' => 'page-header-headings'));
4263 // Buttons.
4264 if (isset($contextheader->additionalbuttons)) {
4265 $html .= html_writer::start_div('btn-group header-button-group');
4266 foreach ($contextheader->additionalbuttons as $button) {
4267 if (!isset($button->page)) {
4268 // Include js for messaging.
4269 if ($button['buttontype'] === 'togglecontact') {
4270 \core_message\helper::togglecontact_requirejs();
4272 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4273 'class' => 'iconsmall',
4274 'role' => 'presentation'
4276 $image .= html_writer::span($button['title'], 'header-button-title');
4277 } else {
4278 $image = html_writer::empty_tag('img', array(
4279 'src' => $button['formattedimage'],
4280 'role' => 'presentation'
4283 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4285 $html .= html_writer::end_div();
4287 $html .= html_writer::end_div();
4289 return $html;
4293 * Wrapper for header elements.
4295 * @return string HTML to display the main header.
4297 public function full_header() {
4298 $html = html_writer::start_tag('header', array('id' => 'page-header', 'class' => 'clearfix'));
4299 $html .= $this->context_header();
4300 $html .= html_writer::start_div('clearfix', array('id' => 'page-navbar'));
4301 $html .= html_writer::tag('div', $this->navbar(), array('class' => 'breadcrumb-nav'));
4302 $html .= html_writer::div($this->page_heading_button(), 'breadcrumb-button');
4303 $html .= html_writer::end_div();
4304 $html .= html_writer::tag('div', $this->course_header(), array('id' => 'course-header'));
4305 $html .= html_writer::end_tag('header');
4306 return $html;
4310 * Displays the list of tags associated with an entry
4312 * @param array $tags list of instances of core_tag or stdClass
4313 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4314 * to use default, set to '' (empty string) to omit the label completely
4315 * @param string $classes additional classes for the enclosing div element
4316 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4317 * will be appended to the end, JS will toggle the rest of the tags
4318 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4319 * @return string
4321 public function tag_list($tags, $label = null, $classes = '', $limit = 10, $pagecontext = null) {
4322 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext);
4323 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4327 * Renders element for inline editing of any value
4329 * @param \core\output\inplace_editable $element
4330 * @return string
4332 public function render_inplace_editable(\core\output\inplace_editable $element) {
4333 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4337 * Renders a bar chart.
4339 * @param \core\chart_bar $chart The chart.
4340 * @return string.
4342 public function render_chart_bar(\core\chart_bar $chart) {
4343 return $this->render_chart($chart);
4347 * Renders a line chart.
4349 * @param \core\chart_line $chart The chart.
4350 * @return string.
4352 public function render_chart_line(\core\chart_line $chart) {
4353 return $this->render_chart($chart);
4357 * Renders a pie chart.
4359 * @param \core\chart_pie $chart The chart.
4360 * @return string.
4362 public function render_chart_pie(\core\chart_pie $chart) {
4363 return $this->render_chart($chart);
4367 * Renders a chart.
4369 * @param \core\chart_base $chart The chart.
4370 * @param bool $withtable Whether to include a data table with the chart.
4371 * @return string.
4373 public function render_chart(\core\chart_base $chart, $withtable = true) {
4374 $chartdata = json_encode($chart);
4375 return $this->render_from_template('core/chart', (object) [
4376 'chartdata' => $chartdata,
4377 'withtable' => $withtable
4382 * Renders the login form.
4384 * @param \core_auth\output\login $form The renderable.
4385 * @return string
4387 public function render_login(\core_auth\output\login $form) {
4388 $context = $form->export_for_template($this);
4390 // Override because rendering is not supported in template yet.
4391 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
4392 $context->errorformatted = $this->error_text($context->error);
4394 return $this->render_from_template('core/loginform', $context);
4398 * Renders an mform element from a template.
4400 * @param HTML_QuickForm_element $element element
4401 * @param bool $required if input is required field
4402 * @param bool $advanced if input is an advanced field
4403 * @param string $error error message to display
4404 * @param bool $ingroup True if this element is rendered as part of a group
4405 * @return mixed string|bool
4407 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4408 $templatename = 'core_form/element-' . $element->getType();
4409 if ($ingroup) {
4410 $templatename .= "-inline";
4412 try {
4413 // We call this to generate a file not found exception if there is no template.
4414 // We don't want to call export_for_template if there is no template.
4415 core\output\mustache_template_finder::get_template_filepath($templatename);
4417 if ($element instanceof templatable) {
4418 $elementcontext = $element->export_for_template($this);
4420 $helpbutton = '';
4421 if (method_exists($element, 'getHelpButton')) {
4422 $helpbutton = $element->getHelpButton();
4424 $label = $element->getLabel();
4425 $text = '';
4426 if (method_exists($element, 'getText')) {
4427 // There currently exists code that adds a form element with an empty label.
4428 // If this is the case then set the label to the description.
4429 if (empty($label)) {
4430 $label = $element->getText();
4431 } else {
4432 $text = $element->getText();
4436 $context = array(
4437 'element' => $elementcontext,
4438 'label' => $label,
4439 'text' => $text,
4440 'required' => $required,
4441 'advanced' => $advanced,
4442 'helpbutton' => $helpbutton,
4443 'error' => $error
4445 return $this->render_from_template($templatename, $context);
4447 } catch (Exception $e) {
4448 // No template for this element.
4449 return false;
4454 * Render the login signup form into a nice template for the theme.
4456 * @param mform $form
4457 * @return string
4459 public function render_login_signup_form($form) {
4460 $context = $form->export_for_template($this);
4462 return $this->render_from_template('core/signup_form_layout', $context);
4466 * Render the verify age and location page into a nice template for the theme.
4468 * @param \core_auth\output\verify_age_location_page $page The renderable
4469 * @return string
4471 protected function render_verify_age_location_page($page) {
4472 $context = $page->export_for_template($this);
4474 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4478 * Render the digital minor contact information page into a nice template for the theme.
4480 * @param \core_auth\output\digital_minor_page $page The renderable
4481 * @return string
4483 protected function render_digital_minor_page($page) {
4484 $context = $page->export_for_template($this);
4486 return $this->render_from_template('core/auth_digital_minor_page', $context);
4490 * Renders a progress bar.
4492 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4494 * @param progress_bar $bar The bar.
4495 * @return string HTML fragment
4497 public function render_progress_bar(progress_bar $bar) {
4498 global $PAGE;
4499 $data = $bar->export_for_template($this);
4500 return $this->render_from_template('core/progress_bar', $data);
4505 * A renderer that generates output for command-line scripts.
4507 * The implementation of this renderer is probably incomplete.
4509 * @copyright 2009 Tim Hunt
4510 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4511 * @since Moodle 2.0
4512 * @package core
4513 * @category output
4515 class core_renderer_cli extends core_renderer {
4518 * Returns the page header.
4520 * @return string HTML fragment
4522 public function header() {
4523 return $this->page->heading . "\n";
4527 * Returns a template fragment representing a Heading.
4529 * @param string $text The text of the heading
4530 * @param int $level The level of importance of the heading
4531 * @param string $classes A space-separated list of CSS classes
4532 * @param string $id An optional ID
4533 * @return string A template fragment for a heading
4535 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4536 $text .= "\n";
4537 switch ($level) {
4538 case 1:
4539 return '=>' . $text;
4540 case 2:
4541 return '-->' . $text;
4542 default:
4543 return $text;
4548 * Returns a template fragment representing a fatal error.
4550 * @param string $message The message to output
4551 * @param string $moreinfourl URL where more info can be found about the error
4552 * @param string $link Link for the Continue button
4553 * @param array $backtrace The execution backtrace
4554 * @param string $debuginfo Debugging information
4555 * @return string A template fragment for a fatal error
4557 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4558 global $CFG;
4560 $output = "!!! $message !!!\n";
4562 if ($CFG->debugdeveloper) {
4563 if (!empty($debuginfo)) {
4564 $output .= $this->notification($debuginfo, 'notifytiny');
4566 if (!empty($backtrace)) {
4567 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
4571 return $output;
4575 * Returns a template fragment representing a notification.
4577 * @param string $message The message to print out.
4578 * @param string $type The type of notification. See constants on \core\output\notification.
4579 * @return string A template fragment for a notification
4581 public function notification($message, $type = null) {
4582 $message = clean_text($message);
4583 if ($type === 'notifysuccess' || $type === 'success') {
4584 return "++ $message ++\n";
4586 return "!! $message !!\n";
4590 * There is no footer for a cli request, however we must override the
4591 * footer method to prevent the default footer.
4593 public function footer() {}
4596 * Render a notification (that is, a status message about something that has
4597 * just happened).
4599 * @param \core\output\notification $notification the notification to print out
4600 * @return string plain text output
4602 public function render_notification(\core\output\notification $notification) {
4603 return $this->notification($notification->get_message(), $notification->get_message_type());
4609 * A renderer that generates output for ajax scripts.
4611 * This renderer prevents accidental sends back only json
4612 * encoded error messages, all other output is ignored.
4614 * @copyright 2010 Petr Skoda
4615 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4616 * @since Moodle 2.0
4617 * @package core
4618 * @category output
4620 class core_renderer_ajax extends core_renderer {
4623 * Returns a template fragment representing a fatal error.
4625 * @param string $message The message to output
4626 * @param string $moreinfourl URL where more info can be found about the error
4627 * @param string $link Link for the Continue button
4628 * @param array $backtrace The execution backtrace
4629 * @param string $debuginfo Debugging information
4630 * @return string A template fragment for a fatal error
4632 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4633 global $CFG;
4635 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
4637 $e = new stdClass();
4638 $e->error = $message;
4639 $e->errorcode = $errorcode;
4640 $e->stacktrace = NULL;
4641 $e->debuginfo = NULL;
4642 $e->reproductionlink = NULL;
4643 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
4644 $link = (string) $link;
4645 if ($link) {
4646 $e->reproductionlink = $link;
4648 if (!empty($debuginfo)) {
4649 $e->debuginfo = $debuginfo;
4651 if (!empty($backtrace)) {
4652 $e->stacktrace = format_backtrace($backtrace, true);
4655 $this->header();
4656 return json_encode($e);
4660 * Used to display a notification.
4661 * For the AJAX notifications are discarded.
4663 * @param string $message The message to print out.
4664 * @param string $type The type of notification. See constants on \core\output\notification.
4666 public function notification($message, $type = null) {}
4669 * Used to display a redirection message.
4670 * AJAX redirections should not occur and as such redirection messages
4671 * are discarded.
4673 * @param moodle_url|string $encodedurl
4674 * @param string $message
4675 * @param int $delay
4676 * @param bool $debugdisableredirect
4677 * @param string $messagetype The type of notification to show the message in.
4678 * See constants on \core\output\notification.
4680 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
4681 $messagetype = \core\output\notification::NOTIFY_INFO) {}
4684 * Prepares the start of an AJAX output.
4686 public function header() {
4687 // unfortunately YUI iframe upload does not support application/json
4688 if (!empty($_FILES)) {
4689 @header('Content-type: text/plain; charset=utf-8');
4690 if (!core_useragent::supports_json_contenttype()) {
4691 @header('X-Content-Type-Options: nosniff');
4693 } else if (!core_useragent::supports_json_contenttype()) {
4694 @header('Content-type: text/plain; charset=utf-8');
4695 @header('X-Content-Type-Options: nosniff');
4696 } else {
4697 @header('Content-type: application/json; charset=utf-8');
4700 // Headers to make it not cacheable and json
4701 @header('Cache-Control: no-store, no-cache, must-revalidate');
4702 @header('Cache-Control: post-check=0, pre-check=0', false);
4703 @header('Pragma: no-cache');
4704 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
4705 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
4706 @header('Accept-Ranges: none');
4710 * There is no footer for an AJAX request, however we must override the
4711 * footer method to prevent the default footer.
4713 public function footer() {}
4716 * No need for headers in an AJAX request... this should never happen.
4717 * @param string $text
4718 * @param int $level
4719 * @param string $classes
4720 * @param string $id
4722 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
4727 * Renderer for media files.
4729 * Used in file resources, media filter, and any other places that need to
4730 * output embedded media.
4732 * @deprecated since Moodle 3.2
4733 * @copyright 2011 The Open University
4734 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4736 class core_media_renderer extends plugin_renderer_base {
4737 /** @var array Array of available 'player' objects */
4738 private $players;
4739 /** @var string Regex pattern for links which may contain embeddable content */
4740 private $embeddablemarkers;
4743 * Constructor
4745 * This is needed in the constructor (not later) so that you can use the
4746 * constants and static functions that are defined in core_media class
4747 * before you call renderer functions.
4749 public function __construct() {
4750 debugging('Class core_media_renderer is deprecated, please use core_media_manager::instance()', DEBUG_DEVELOPER);
4754 * Renders a media file (audio or video) using suitable embedded player.
4756 * See embed_alternatives function for full description of parameters.
4757 * This function calls through to that one.
4759 * When using this function you can also specify width and height in the
4760 * URL by including ?d=100x100 at the end. If specified in the URL, this
4761 * will override the $width and $height parameters.
4763 * @param moodle_url $url Full URL of media file
4764 * @param string $name Optional user-readable name to display in download link
4765 * @param int $width Width in pixels (optional)
4766 * @param int $height Height in pixels (optional)
4767 * @param array $options Array of key/value pairs
4768 * @return string HTML content of embed
4770 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
4771 $options = array()) {
4772 return core_media_manager::instance()->embed_url($url, $name, $width, $height, $options);
4776 * Renders media files (audio or video) using suitable embedded player.
4777 * The list of URLs should be alternative versions of the same content in
4778 * multiple formats. If there is only one format it should have a single
4779 * entry.
4781 * If the media files are not in a supported format, this will give students
4782 * a download link to each format. The download link uses the filename
4783 * unless you supply the optional name parameter.
4785 * Width and height are optional. If specified, these are suggested sizes
4786 * and should be the exact values supplied by the user, if they come from
4787 * user input. These will be treated as relating to the size of the video
4788 * content, not including any player control bar.
4790 * For audio files, height will be ignored. For video files, a few formats
4791 * work if you specify only width, but in general if you specify width
4792 * you must specify height as well.
4794 * The $options array is passed through to the core_media_player classes
4795 * that render the object tag. The keys can contain values from
4796 * core_media::OPTION_xx.
4798 * @param array $alternatives Array of moodle_url to media files
4799 * @param string $name Optional user-readable name to display in download link
4800 * @param int $width Width in pixels (optional)
4801 * @param int $height Height in pixels (optional)
4802 * @param array $options Array of key/value pairs
4803 * @return string HTML content of embed
4805 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
4806 $options = array()) {
4807 return core_media_manager::instance()->embed_alternatives($alternatives, $name, $width, $height, $options);
4811 * Checks whether a file can be embedded. If this returns true you will get
4812 * an embedded player; if this returns false, you will just get a download
4813 * link.
4815 * This is a wrapper for can_embed_urls.
4817 * @param moodle_url $url URL of media file
4818 * @param array $options Options (same as when embedding)
4819 * @return bool True if file can be embedded
4821 public function can_embed_url(moodle_url $url, $options = array()) {
4822 return core_media_manager::instance()->can_embed_url($url, $options);
4826 * Checks whether a file can be embedded. If this returns true you will get
4827 * an embedded player; if this returns false, you will just get a download
4828 * link.
4830 * @param array $urls URL of media file and any alternatives (moodle_url)
4831 * @param array $options Options (same as when embedding)
4832 * @return bool True if file can be embedded
4834 public function can_embed_urls(array $urls, $options = array()) {
4835 return core_media_manager::instance()->can_embed_urls($urls, $options);
4839 * Obtains a list of markers that can be used in a regular expression when
4840 * searching for URLs that can be embedded by any player type.
4842 * This string is used to improve peformance of regex matching by ensuring
4843 * that the (presumably C) regex code can do a quick keyword check on the
4844 * URL part of a link to see if it matches one of these, rather than having
4845 * to go into PHP code for every single link to see if it can be embedded.
4847 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
4849 public function get_embeddable_markers() {
4850 return core_media_manager::instance()->get_embeddable_markers();
4855 * The maintenance renderer.
4857 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
4858 * is running a maintenance related task.
4859 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
4861 * @since Moodle 2.6
4862 * @package core
4863 * @category output
4864 * @copyright 2013 Sam Hemelryk
4865 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4867 class core_renderer_maintenance extends core_renderer {
4870 * Initialises the renderer instance.
4871 * @param moodle_page $page
4872 * @param string $target
4873 * @throws coding_exception
4875 public function __construct(moodle_page $page, $target) {
4876 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
4877 throw new coding_exception('Invalid request for the maintenance renderer.');
4879 parent::__construct($page, $target);
4883 * Does nothing. The maintenance renderer cannot produce blocks.
4885 * @param block_contents $bc
4886 * @param string $region
4887 * @return string
4889 public function block(block_contents $bc, $region) {
4890 // Computer says no blocks.
4891 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4892 return '';
4896 * Does nothing. The maintenance renderer cannot produce blocks.
4898 * @param string $region
4899 * @param array $classes
4900 * @param string $tag
4901 * @return string
4903 public function blocks($region, $classes = array(), $tag = 'aside') {
4904 // Computer says no blocks.
4905 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4906 return '';
4910 * Does nothing. The maintenance renderer cannot produce blocks.
4912 * @param string $region
4913 * @return string
4915 public function blocks_for_region($region) {
4916 // Computer says no blocks for region.
4917 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4918 return '';
4922 * Does nothing. The maintenance renderer cannot produce a course content header.
4924 * @param bool $onlyifnotcalledbefore
4925 * @return string
4927 public function course_content_header($onlyifnotcalledbefore = false) {
4928 // Computer says no course content header.
4929 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4930 return '';
4934 * Does nothing. The maintenance renderer cannot produce a course content footer.
4936 * @param bool $onlyifnotcalledbefore
4937 * @return string
4939 public function course_content_footer($onlyifnotcalledbefore = false) {
4940 // Computer says no course content footer.
4941 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4942 return '';
4946 * Does nothing. The maintenance renderer cannot produce a course header.
4948 * @return string
4950 public function course_header() {
4951 // Computer says no course header.
4952 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4953 return '';
4957 * Does nothing. The maintenance renderer cannot produce a course footer.
4959 * @return string
4961 public function course_footer() {
4962 // Computer says no course footer.
4963 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4964 return '';
4968 * Does nothing. The maintenance renderer cannot produce a custom menu.
4970 * @param string $custommenuitems
4971 * @return string
4973 public function custom_menu($custommenuitems = '') {
4974 // Computer says no custom menu.
4975 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4976 return '';
4980 * Does nothing. The maintenance renderer cannot produce a file picker.
4982 * @param array $options
4983 * @return string
4985 public function file_picker($options) {
4986 // Computer says no file picker.
4987 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4988 return '';
4992 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
4994 * @param array $dir
4995 * @return string
4997 public function htmllize_file_tree($dir) {
4998 // Hell no we don't want no htmllized file tree.
4999 // Also why on earth is this function on the core renderer???
5000 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5001 return '';
5006 * Overridden confirm message for upgrades.
5008 * @param string $message The question to ask the user
5009 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5010 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5011 * @return string HTML fragment
5013 public function confirm($message, $continue, $cancel) {
5014 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5015 // from any previous version of Moodle).
5016 if ($continue instanceof single_button) {
5017 $continue->primary = true;
5018 } else if (is_string($continue)) {
5019 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
5020 } else if ($continue instanceof moodle_url) {
5021 $continue = new single_button($continue, get_string('continue'), 'post', true);
5022 } else {
5023 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5024 ' (string/moodle_url) or a single_button instance.');
5027 if ($cancel instanceof single_button) {
5028 $output = '';
5029 } else if (is_string($cancel)) {
5030 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5031 } else if ($cancel instanceof moodle_url) {
5032 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5033 } else {
5034 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5035 ' (string/moodle_url) or a single_button instance.');
5038 $output = $this->box_start('generalbox', 'notice');
5039 $output .= html_writer::tag('h4', get_string('confirm'));
5040 $output .= html_writer::tag('p', $message);
5041 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
5042 $output .= $this->box_end();
5043 return $output;
5047 * Does nothing. The maintenance renderer does not support JS.
5049 * @param block_contents $bc
5051 public function init_block_hider_js(block_contents $bc) {
5052 // Computer says no JavaScript.
5053 // Do nothing, ridiculous method.
5057 * Does nothing. The maintenance renderer cannot produce language menus.
5059 * @return string
5061 public function lang_menu() {
5062 // Computer says no lang menu.
5063 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5064 return '';
5068 * Does nothing. The maintenance renderer has no need for login information.
5070 * @param null $withlinks
5071 * @return string
5073 public function login_info($withlinks = null) {
5074 // Computer says no login info.
5075 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5076 return '';
5080 * Does nothing. The maintenance renderer cannot produce user pictures.
5082 * @param stdClass $user
5083 * @param array $options
5084 * @return string
5086 public function user_picture(stdClass $user, array $options = null) {
5087 // Computer says no user pictures.
5088 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5089 return '';