Merge branch 'MDL-61480-master' of git://github.com/andrewnicols/moodle
[moodle.git] / lib / outputrenderers.php
blobd4ad83dc010ecef3070e3d88c11ad0ceca77cef5
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.
198 * @param renderable $widget instance with renderable interface
199 * @return string
201 public function render(renderable $widget) {
202 $classname = get_class($widget);
203 // Strip namespaces.
204 $classname = preg_replace('/^.*\\\/', '', $classname);
205 // Remove _renderable suffixes
206 $classname = preg_replace('/_renderable$/', '', $classname);
208 $rendermethod = 'render_'.$classname;
209 if (method_exists($this, $rendermethod)) {
210 return $this->$rendermethod($widget);
212 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
216 * Adds a JS action for the element with the provided id.
218 * This method adds a JS event for the provided component action to the page
219 * and then returns the id that the event has been attached to.
220 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
222 * @param component_action $action
223 * @param string $id
224 * @return string id of element, either original submitted or random new if not supplied
226 public function add_action_handler(component_action $action, $id = null) {
227 if (!$id) {
228 $id = html_writer::random_id($action->event);
230 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
231 return $id;
235 * Returns true is output has already started, and false if not.
237 * @return boolean true if the header has been printed.
239 public function has_started() {
240 return $this->page->state >= moodle_page::STATE_IN_BODY;
244 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
246 * @param mixed $classes Space-separated string or array of classes
247 * @return string HTML class attribute value
249 public static function prepare_classes($classes) {
250 if (is_array($classes)) {
251 return implode(' ', array_unique($classes));
253 return $classes;
257 * Return the direct URL for an image from the pix folder.
259 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
261 * @deprecated since Moodle 3.3
262 * @param string $imagename the name of the icon.
263 * @param string $component specification of one plugin like in get_string()
264 * @return moodle_url
266 public function pix_url($imagename, $component = 'moodle') {
267 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
268 return $this->page->theme->image_url($imagename, $component);
272 * Return the moodle_url for an image.
274 * The exact image location and extension is determined
275 * automatically by searching for gif|png|jpg|jpeg, please
276 * note there can not be diferent images with the different
277 * extension. The imagename is for historical reasons
278 * a relative path name, it may be changed later for core
279 * images. It is recommended to not use subdirectories
280 * in plugin and theme pix directories.
282 * There are three types of images:
283 * 1/ theme images - stored in theme/mytheme/pix/,
284 * use component 'theme'
285 * 2/ core images - stored in /pix/,
286 * overridden via theme/mytheme/pix_core/
287 * 3/ plugin images - stored in mod/mymodule/pix,
288 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
289 * example: image_url('comment', 'mod_glossary')
291 * @param string $imagename the pathname of the image
292 * @param string $component full plugin name (aka component) or 'theme'
293 * @return moodle_url
295 public function image_url($imagename, $component = 'moodle') {
296 return $this->page->theme->image_url($imagename, $component);
300 * Return the site's logo URL, if any.
302 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
303 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
304 * @return moodle_url|false
306 public function get_logo_url($maxwidth = null, $maxheight = 200) {
307 global $CFG;
308 $logo = get_config('core_admin', 'logo');
309 if (empty($logo)) {
310 return false;
313 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
314 // It's not worth the overhead of detecting and serving 2 different images based on the device.
316 // Hide the requested size in the file path.
317 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
319 // Use $CFG->themerev to prevent browser caching when the file changes.
320 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
321 theme_get_revision(), $logo);
325 * Return the site's compact logo URL, if any.
327 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
328 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
329 * @return moodle_url|false
331 public function get_compact_logo_url($maxwidth = 100, $maxheight = 100) {
332 global $CFG;
333 $logo = get_config('core_admin', 'logocompact');
334 if (empty($logo)) {
335 return false;
338 // Hide the requested size in the file path.
339 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
341 // Use $CFG->themerev to prevent browser caching when the file changes.
342 return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
343 theme_get_revision(), $logo);
350 * Basis for all plugin renderers.
352 * @copyright Petr Skoda (skodak)
353 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
354 * @since Moodle 2.0
355 * @package core
356 * @category output
358 class plugin_renderer_base extends renderer_base {
361 * @var renderer_base|core_renderer A reference to the current renderer.
362 * The renderer provided here will be determined by the page but will in 90%
363 * of cases by the {@link core_renderer}
365 protected $output;
368 * Constructor method, calls the parent constructor
370 * @param moodle_page $page
371 * @param string $target one of rendering target constants
373 public function __construct(moodle_page $page, $target) {
374 if (empty($target) && $page->pagelayout === 'maintenance') {
375 // If the page is using the maintenance layout then we're going to force the target to maintenance.
376 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
377 // unavailable for this page layout.
378 $target = RENDERER_TARGET_MAINTENANCE;
380 $this->output = $page->get_renderer('core', null, $target);
381 parent::__construct($page, $target);
385 * Renders the provided widget and returns the HTML to display it.
387 * @param renderable $widget instance with renderable interface
388 * @return string
390 public function render(renderable $widget) {
391 $classname = get_class($widget);
392 // Strip namespaces.
393 $classname = preg_replace('/^.*\\\/', '', $classname);
394 // Keep a copy at this point, we may need to look for a deprecated method.
395 $deprecatedmethod = 'render_'.$classname;
396 // Remove _renderable suffixes
397 $classname = preg_replace('/_renderable$/', '', $classname);
399 $rendermethod = 'render_'.$classname;
400 if (method_exists($this, $rendermethod)) {
401 return $this->$rendermethod($widget);
403 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
404 // This is exactly where we don't want to be.
405 // If you have arrived here you have a renderable component within your plugin that has the name
406 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
407 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
408 // and the _renderable suffix now gets removed when looking for a render method.
409 // You need to change your renderers render_blah_renderable to render_blah.
410 // Until you do this it will not be possible for a theme to override the renderer to override your method.
411 // Please do it ASAP.
412 static $debugged = array();
413 if (!isset($debugged[$deprecatedmethod])) {
414 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
415 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
416 $debugged[$deprecatedmethod] = true;
418 return $this->$deprecatedmethod($widget);
420 // pass to core renderer if method not found here
421 return $this->output->render($widget);
425 * Magic method used to pass calls otherwise meant for the standard renderer
426 * to it to ensure we don't go causing unnecessary grief.
428 * @param string $method
429 * @param array $arguments
430 * @return mixed
432 public function __call($method, $arguments) {
433 if (method_exists('renderer_base', $method)) {
434 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
436 if (method_exists($this->output, $method)) {
437 return call_user_func_array(array($this->output, $method), $arguments);
438 } else {
439 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
446 * The standard implementation of the core_renderer interface.
448 * @copyright 2009 Tim Hunt
449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
450 * @since Moodle 2.0
451 * @package core
452 * @category output
454 class core_renderer extends renderer_base {
456 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
457 * in layout files instead.
458 * @deprecated
459 * @var string used in {@link core_renderer::header()}.
461 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
464 * @var string Used to pass information from {@link core_renderer::doctype()} to
465 * {@link core_renderer::standard_head_html()}.
467 protected $contenttype;
470 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
471 * with {@link core_renderer::header()}.
473 protected $metarefreshtag = '';
476 * @var string Unique token for the closing HTML
478 protected $unique_end_html_token;
481 * @var string Unique token for performance information
483 protected $unique_performance_info_token;
486 * @var string Unique token for the main content.
488 protected $unique_main_content_token;
491 * Constructor
493 * @param moodle_page $page the page we are doing output for.
494 * @param string $target one of rendering target constants
496 public function __construct(moodle_page $page, $target) {
497 $this->opencontainers = $page->opencontainers;
498 $this->page = $page;
499 $this->target = $target;
501 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
502 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
503 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
507 * Get the DOCTYPE declaration that should be used with this page. Designed to
508 * be called in theme layout.php files.
510 * @return string the DOCTYPE declaration that should be used.
512 public function doctype() {
513 if ($this->page->theme->doctype === 'html5') {
514 $this->contenttype = 'text/html; charset=utf-8';
515 return "<!DOCTYPE html>\n";
517 } else if ($this->page->theme->doctype === 'xhtml5') {
518 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
519 return "<!DOCTYPE html>\n";
521 } else {
522 // legacy xhtml 1.0
523 $this->contenttype = 'text/html; charset=utf-8';
524 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
529 * The attributes that should be added to the <html> tag. Designed to
530 * be called in theme layout.php files.
532 * @return string HTML fragment.
534 public function htmlattributes() {
535 $return = get_html_lang(true);
536 $attributes = array();
537 if ($this->page->theme->doctype !== 'html5') {
538 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
541 // Give plugins an opportunity to add things like xml namespaces to the html element.
542 // This function should return an array of html attribute names => values.
543 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
544 foreach ($pluginswithfunction as $plugins) {
545 foreach ($plugins as $function) {
546 $newattrs = $function();
547 unset($newattrs['dir']);
548 unset($newattrs['lang']);
549 unset($newattrs['xmlns']);
550 unset($newattrs['xml:lang']);
551 $attributes += $newattrs;
555 foreach ($attributes as $key => $val) {
556 $val = s($val);
557 $return .= " $key=\"$val\"";
560 return $return;
564 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
565 * that should be included in the <head> tag. Designed to be called in theme
566 * layout.php files.
568 * @return string HTML fragment.
570 public function standard_head_html() {
571 global $CFG, $SESSION;
573 // Before we output any content, we need to ensure that certain
574 // page components are set up.
576 // Blocks must be set up early as they may require javascript which
577 // has to be included in the page header before output is created.
578 foreach ($this->page->blocks->get_regions() as $region) {
579 $this->page->blocks->ensure_content_created($region, $this);
582 $output = '';
584 // Give plugins an opportunity to add any head elements. The callback
585 // must always return a string containing valid html head content.
586 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
587 foreach ($pluginswithfunction as $plugins) {
588 foreach ($plugins as $function) {
589 $output .= $function();
593 // Allow a url_rewrite plugin to setup any dynamic head content.
594 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
595 $class = $CFG->urlrewriteclass;
596 $output .= $class::html_head_setup();
599 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
600 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
601 // This is only set by the {@link redirect()} method
602 $output .= $this->metarefreshtag;
604 // Check if a periodic refresh delay has been set and make sure we arn't
605 // already meta refreshing
606 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
607 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
610 // Set up help link popups for all links with the helptooltip class
611 $this->page->requires->js_init_call('M.util.help_popups.setup');
613 $focus = $this->page->focuscontrol;
614 if (!empty($focus)) {
615 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
616 // This is a horrifically bad way to handle focus but it is passed in
617 // through messy formslib::moodleform
618 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
619 } else if (strpos($focus, '.')!==false) {
620 // Old style of focus, bad way to do it
621 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);
622 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
623 } else {
624 // Focus element with given id
625 $this->page->requires->js_function_call('focuscontrol', array($focus));
629 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
630 // any other custom CSS can not be overridden via themes and is highly discouraged
631 $urls = $this->page->theme->css_urls($this->page);
632 foreach ($urls as $url) {
633 $this->page->requires->css_theme($url);
636 // Get the theme javascript head and footer
637 if ($jsurl = $this->page->theme->javascript_url(true)) {
638 $this->page->requires->js($jsurl, true);
640 if ($jsurl = $this->page->theme->javascript_url(false)) {
641 $this->page->requires->js($jsurl);
644 // Get any HTML from the page_requirements_manager.
645 $output .= $this->page->requires->get_head_code($this->page, $this);
647 // List alternate versions.
648 foreach ($this->page->alternateversions as $type => $alt) {
649 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
650 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
653 // Add noindex tag if relevant page and setting applied.
654 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
655 $loginpages = array('login-index', 'login-signup');
656 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
657 if (!isset($CFG->additionalhtmlhead)) {
658 $CFG->additionalhtmlhead = '';
660 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
663 if (!empty($CFG->additionalhtmlhead)) {
664 $output .= "\n".$CFG->additionalhtmlhead;
667 return $output;
671 * The standard tags (typically skip links) that should be output just inside
672 * the start of the <body> tag. Designed to be called in theme layout.php files.
674 * @return string HTML fragment.
676 public function standard_top_of_body_html() {
677 global $CFG;
678 $output = $this->page->requires->get_top_of_body_code($this);
679 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
680 $output .= "\n".$CFG->additionalhtmltopofbody;
683 // Give plugins an opportunity to inject extra html content. The callback
684 // must always return a string containing valid html.
685 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
686 foreach ($pluginswithfunction as $plugins) {
687 foreach ($plugins as $function) {
688 $output .= $function();
692 $output .= $this->maintenance_warning();
694 return $output;
698 * Scheduled maintenance warning message.
700 * Note: This is a nasty hack to display maintenance notice, this should be moved
701 * to some general notification area once we have it.
703 * @return string
705 public function maintenance_warning() {
706 global $CFG;
708 $output = '';
709 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
710 $timeleft = $CFG->maintenance_later - time();
711 // If timeleft less than 30 sec, set the class on block to error to highlight.
712 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
713 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-a-1 alert');
714 $a = new stdClass();
715 $a->hour = (int)($timeleft / 3600);
716 $a->min = (int)(($timeleft / 60) % 60);
717 $a->sec = (int)($timeleft % 60);
718 if ($a->hour > 0) {
719 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
720 } else {
721 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
724 $output .= $this->box_end();
725 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
726 array(array('timeleftinsec' => $timeleft)));
727 $this->page->requires->strings_for_js(
728 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
729 'admin');
731 return $output;
735 * The standard tags (typically performance information and validation links,
736 * if we are in developer debug mode) that should be output in the footer area
737 * of the page. Designed to be called in theme layout.php files.
739 * @return string HTML fragment.
741 public function standard_footer_html() {
742 global $CFG, $SCRIPT;
744 $output = '';
745 if (during_initial_install()) {
746 // Debugging info can not work before install is finished,
747 // in any case we do not want any links during installation!
748 return $output;
751 // Give plugins an opportunity to add any footer elements.
752 // The callback must always return a string containing valid html footer content.
753 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
754 foreach ($pluginswithfunction as $plugins) {
755 foreach ($plugins as $function) {
756 $output .= $function();
760 // This function is normally called from a layout.php file in {@link core_renderer::header()}
761 // but some of the content won't be known until later, so we return a placeholder
762 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
763 $output .= $this->unique_performance_info_token;
764 if ($this->page->devicetypeinuse == 'legacy') {
765 // The legacy theme is in use print the notification
766 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
769 // Get links to switch device types (only shown for users not on a default device)
770 $output .= $this->theme_switch_links();
772 if (!empty($CFG->debugpageinfo)) {
773 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
775 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
776 // Add link to profiling report if necessary
777 if (function_exists('profiling_is_running') && profiling_is_running()) {
778 $txt = get_string('profiledscript', 'admin');
779 $title = get_string('profiledscriptview', 'admin');
780 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
781 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
782 $output .= '<div class="profilingfooter">' . $link . '</div>';
784 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
785 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
786 $output .= '<div class="purgecaches">' .
787 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
789 if (!empty($CFG->debugvalidators)) {
790 // 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
791 $output .= '<div class="validators"><ul class="list-unstyled m-l-1">
792 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
793 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
794 <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>
795 </ul></div>';
797 return $output;
801 * Returns standard main content placeholder.
802 * Designed to be called in theme layout.php files.
804 * @return string HTML fragment.
806 public function main_content() {
807 // This is here because it is the only place we can inject the "main" role over the entire main content area
808 // without requiring all theme's to manually do it, and without creating yet another thing people need to
809 // remember in the theme.
810 // This is an unfortunate hack. DO NO EVER add anything more here.
811 // DO NOT add classes.
812 // DO NOT add an id.
813 return '<div role="main">'.$this->unique_main_content_token.'</div>';
817 * Returns standard navigation between activities in a course.
819 * @return string the navigation HTML.
821 public function activity_navigation() {
822 // First we should check if we want to add navigation.
823 $context = $this->page->context;
824 if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
825 || $context->contextlevel != CONTEXT_MODULE) {
826 return '';
829 // If the activity is in stealth mode, show no links.
830 if ($this->page->cm->is_stealth()) {
831 return '';
834 // Get a list of all the activities in the course.
835 $course = $this->page->cm->get_course();
836 $modules = get_fast_modinfo($course->id)->get_cms();
838 // Put the modules into an array in order by the position they are shown in the course.
839 $mods = [];
840 $activitylist = [];
841 foreach ($modules as $module) {
842 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
843 if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
844 continue;
846 $mods[$module->id] = $module;
848 // No need to add the current module to the list for the activity dropdown menu.
849 if ($module->id == $this->page->cm->id) {
850 continue;
852 // Module name.
853 $modname = $module->get_formatted_name();
854 // Display the hidden text if necessary.
855 if (!$module->visible) {
856 $modname .= ' ' . get_string('hiddenwithbrackets');
858 // Module URL.
859 $linkurl = new moodle_url($module->url, array('forceview' => 1));
860 // Add module URL (as key) and name (as value) to the activity list array.
861 $activitylist[$linkurl->out(false)] = $modname;
864 $nummods = count($mods);
866 // If there is only one mod then do nothing.
867 if ($nummods == 1) {
868 return '';
871 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
872 $modids = array_keys($mods);
874 // Get the position in the array of the course module we are viewing.
875 $position = array_search($this->page->cm->id, $modids);
877 $prevmod = null;
878 $nextmod = null;
880 // Check if we have a previous mod to show.
881 if ($position > 0) {
882 $prevmod = $mods[$modids[$position - 1]];
885 // Check if we have a next mod to show.
886 if ($position < ($nummods - 1)) {
887 $nextmod = $mods[$modids[$position + 1]];
890 $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
891 $renderer = $this->page->get_renderer('core', 'course');
892 return $renderer->render($activitynav);
896 * The standard tags (typically script tags that are not needed earlier) that
897 * should be output after everything else. Designed to be called in theme layout.php files.
899 * @return string HTML fragment.
901 public function standard_end_of_body_html() {
902 global $CFG;
904 // This function is normally called from a layout.php file in {@link core_renderer::header()}
905 // but some of the content won't be known until later, so we return a placeholder
906 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
907 $output = '';
908 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
909 $output .= "\n".$CFG->additionalhtmlfooter;
911 $output .= $this->unique_end_html_token;
912 return $output;
916 * Return the standard string that says whether you are logged in (and switched
917 * roles/logged in as another user).
918 * @param bool $withlinks if false, then don't include any links in the HTML produced.
919 * If not set, the default is the nologinlinks option from the theme config.php file,
920 * and if that is not set, then links are included.
921 * @return string HTML fragment.
923 public function login_info($withlinks = null) {
924 global $USER, $CFG, $DB, $SESSION;
926 if (during_initial_install()) {
927 return '';
930 if (is_null($withlinks)) {
931 $withlinks = empty($this->page->layout_options['nologinlinks']);
934 $course = $this->page->course;
935 if (\core\session\manager::is_loggedinas()) {
936 $realuser = \core\session\manager::get_realuser();
937 $fullname = fullname($realuser, true);
938 if ($withlinks) {
939 $loginastitle = get_string('loginas');
940 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
941 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
942 } else {
943 $realuserinfo = " [$fullname] ";
945 } else {
946 $realuserinfo = '';
949 $loginpage = $this->is_login_page();
950 $loginurl = get_login_url();
952 if (empty($course->id)) {
953 // $course->id is not defined during installation
954 return '';
955 } else if (isloggedin()) {
956 $context = context_course::instance($course->id);
958 $fullname = fullname($USER, true);
959 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
960 if ($withlinks) {
961 $linktitle = get_string('viewprofile');
962 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
963 } else {
964 $username = $fullname;
966 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
967 if ($withlinks) {
968 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
969 } else {
970 $username .= " from {$idprovider->name}";
973 if (isguestuser()) {
974 $loggedinas = $realuserinfo.get_string('loggedinasguest');
975 if (!$loginpage && $withlinks) {
976 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
978 } else if (is_role_switched($course->id)) { // Has switched roles
979 $rolename = '';
980 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
981 $rolename = ': '.role_get_name($role, $context);
983 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
984 if ($withlinks) {
985 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
986 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
988 } else {
989 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
990 if ($withlinks) {
991 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
994 } else {
995 $loggedinas = get_string('loggedinnot', 'moodle');
996 if (!$loginpage && $withlinks) {
997 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1001 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1003 if (isset($SESSION->justloggedin)) {
1004 unset($SESSION->justloggedin);
1005 if (!empty($CFG->displayloginfailures)) {
1006 if (!isguestuser()) {
1007 // Include this file only when required.
1008 require_once($CFG->dirroot . '/user/lib.php');
1009 if ($count = user_count_login_failures($USER)) {
1010 $loggedinas .= '<div class="loginfailures">';
1011 $a = new stdClass();
1012 $a->attempts = $count;
1013 $loggedinas .= get_string('failedloginattempts', '', $a);
1014 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1015 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1016 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1018 $loggedinas .= '</div>';
1024 return $loggedinas;
1028 * Check whether the current page is a login page.
1030 * @since Moodle 2.9
1031 * @return bool
1033 protected function is_login_page() {
1034 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1035 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1036 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1037 return in_array(
1038 $this->page->url->out_as_local_url(false, array()),
1039 array(
1040 '/login/index.php',
1041 '/login/forgot_password.php',
1047 * Return the 'back' link that normally appears in the footer.
1049 * @return string HTML fragment.
1051 public function home_link() {
1052 global $CFG, $SITE;
1054 if ($this->page->pagetype == 'site-index') {
1055 // Special case for site home page - please do not remove
1056 return '<div class="sitelink">' .
1057 '<a title="Moodle" href="http://moodle.org/">' .
1058 '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1060 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1061 // Special case for during install/upgrade.
1062 return '<div class="sitelink">'.
1063 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1064 '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1066 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1067 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1068 get_string('home') . '</a></div>';
1070 } else {
1071 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1072 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1077 * Redirects the user by any means possible given the current state
1079 * This function should not be called directly, it should always be called using
1080 * the redirect function in lib/weblib.php
1082 * The redirect function should really only be called before page output has started
1083 * however it will allow itself to be called during the state STATE_IN_BODY
1085 * @param string $encodedurl The URL to send to encoded if required
1086 * @param string $message The message to display to the user if any
1087 * @param int $delay The delay before redirecting a user, if $message has been
1088 * set this is a requirement and defaults to 3, set to 0 no delay
1089 * @param boolean $debugdisableredirect this redirect has been disabled for
1090 * debugging purposes. Display a message that explains, and don't
1091 * trigger the redirect.
1092 * @param string $messagetype The type of notification to show the message in.
1093 * See constants on \core\output\notification.
1094 * @return string The HTML to display to the user before dying, may contain
1095 * meta refresh, javascript refresh, and may have set header redirects
1097 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1098 $messagetype = \core\output\notification::NOTIFY_INFO) {
1099 global $CFG;
1100 $url = str_replace('&amp;', '&', $encodedurl);
1102 switch ($this->page->state) {
1103 case moodle_page::STATE_BEFORE_HEADER :
1104 // No output yet it is safe to delivery the full arsenal of redirect methods
1105 if (!$debugdisableredirect) {
1106 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1107 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1108 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1110 $output = $this->header();
1111 break;
1112 case moodle_page::STATE_PRINTING_HEADER :
1113 // We should hopefully never get here
1114 throw new coding_exception('You cannot redirect while printing the page header');
1115 break;
1116 case moodle_page::STATE_IN_BODY :
1117 // We really shouldn't be here but we can deal with this
1118 debugging("You should really redirect before you start page output");
1119 if (!$debugdisableredirect) {
1120 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1122 $output = $this->opencontainers->pop_all_but_last();
1123 break;
1124 case moodle_page::STATE_DONE :
1125 // Too late to be calling redirect now
1126 throw new coding_exception('You cannot redirect after the entire page has been generated');
1127 break;
1129 $output .= $this->notification($message, $messagetype);
1130 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1131 if ($debugdisableredirect) {
1132 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1134 $output .= $this->footer();
1135 return $output;
1139 * Start output by sending the HTTP headers, and printing the HTML <head>
1140 * and the start of the <body>.
1142 * To control what is printed, you should set properties on $PAGE. If you
1143 * are familiar with the old {@link print_header()} function from Moodle 1.9
1144 * you will find that there are properties on $PAGE that correspond to most
1145 * of the old parameters to could be passed to print_header.
1147 * Not that, in due course, the remaining $navigation, $menu parameters here
1148 * will be replaced by more properties of $PAGE, but that is still to do.
1150 * @return string HTML that you must output this, preferably immediately.
1152 public function header() {
1153 global $USER, $CFG, $SESSION;
1155 // Give plugins an opportunity touch things before the http headers are sent
1156 // such as adding additional headers. The return value is ignored.
1157 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1158 foreach ($pluginswithfunction as $plugins) {
1159 foreach ($plugins as $function) {
1160 $function();
1164 if (\core\session\manager::is_loggedinas()) {
1165 $this->page->add_body_class('userloggedinas');
1168 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1169 require_once($CFG->dirroot . '/user/lib.php');
1170 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1171 if ($count = user_count_login_failures($USER, false)) {
1172 $this->page->add_body_class('loginfailures');
1176 // If the user is logged in, and we're not in initial install,
1177 // check to see if the user is role-switched and add the appropriate
1178 // CSS class to the body element.
1179 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1180 $this->page->add_body_class('userswitchedrole');
1183 // Give themes a chance to init/alter the page object.
1184 $this->page->theme->init_page($this->page);
1186 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1188 // Find the appropriate page layout file, based on $this->page->pagelayout.
1189 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1190 // Render the layout using the layout file.
1191 $rendered = $this->render_page_layout($layoutfile);
1193 // Slice the rendered output into header and footer.
1194 $cutpos = strpos($rendered, $this->unique_main_content_token);
1195 if ($cutpos === false) {
1196 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1197 $token = self::MAIN_CONTENT_TOKEN;
1198 } else {
1199 $token = $this->unique_main_content_token;
1202 if ($cutpos === false) {
1203 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.');
1205 $header = substr($rendered, 0, $cutpos);
1206 $footer = substr($rendered, $cutpos + strlen($token));
1208 if (empty($this->contenttype)) {
1209 debugging('The page layout file did not call $OUTPUT->doctype()');
1210 $header = $this->doctype() . $header;
1213 // If this theme version is below 2.4 release and this is a course view page
1214 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1215 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1216 // check if course content header/footer have not been output during render of theme layout
1217 $coursecontentheader = $this->course_content_header(true);
1218 $coursecontentfooter = $this->course_content_footer(true);
1219 if (!empty($coursecontentheader)) {
1220 // display debug message and add header and footer right above and below main content
1221 // Please note that course header and footer (to be displayed above and below the whole page)
1222 // are not displayed in this case at all.
1223 // Besides the content header and footer are not displayed on any other course page
1224 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);
1225 $header .= $coursecontentheader;
1226 $footer = $coursecontentfooter. $footer;
1230 send_headers($this->contenttype, $this->page->cacheable);
1232 $this->opencontainers->push('header/footer', $footer);
1233 $this->page->set_state(moodle_page::STATE_IN_BODY);
1235 return $header . $this->skip_link_target('maincontent');
1239 * Renders and outputs the page layout file.
1241 * This is done by preparing the normal globals available to a script, and
1242 * then including the layout file provided by the current theme for the
1243 * requested layout.
1245 * @param string $layoutfile The name of the layout file
1246 * @return string HTML code
1248 protected function render_page_layout($layoutfile) {
1249 global $CFG, $SITE, $USER;
1250 // The next lines are a bit tricky. The point is, here we are in a method
1251 // of a renderer class, and this object may, or may not, be the same as
1252 // the global $OUTPUT object. When rendering the page layout file, we want to use
1253 // this object. However, people writing Moodle code expect the current
1254 // renderer to be called $OUTPUT, not $this, so define a variable called
1255 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1256 $OUTPUT = $this;
1257 $PAGE = $this->page;
1258 $COURSE = $this->page->course;
1260 ob_start();
1261 include($layoutfile);
1262 $rendered = ob_get_contents();
1263 ob_end_clean();
1264 return $rendered;
1268 * Outputs the page's footer
1270 * @return string HTML fragment
1272 public function footer() {
1273 global $CFG, $DB, $PAGE;
1275 // Give plugins an opportunity to touch the page before JS is finalized.
1276 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1277 foreach ($pluginswithfunction as $plugins) {
1278 foreach ($plugins as $function) {
1279 $function();
1283 $output = $this->container_end_all(true);
1285 $footer = $this->opencontainers->pop('header/footer');
1287 if (debugging() and $DB and $DB->is_transaction_started()) {
1288 // TODO: MDL-20625 print warning - transaction will be rolled back
1291 // Provide some performance info if required
1292 $performanceinfo = '';
1293 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1294 $perf = get_performance_info();
1295 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1296 $performanceinfo = $perf['html'];
1300 // We always want performance data when running a performance test, even if the user is redirected to another page.
1301 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1302 $footer = $this->unique_performance_info_token . $footer;
1304 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1306 // Only show notifications when we have a $PAGE context id.
1307 if (!empty($PAGE->context->id)) {
1308 $this->page->requires->js_call_amd('core/notification', 'init', array(
1309 $PAGE->context->id,
1310 \core\notification::fetch_as_array($this)
1313 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1315 $this->page->set_state(moodle_page::STATE_DONE);
1317 return $output . $footer;
1321 * Close all but the last open container. This is useful in places like error
1322 * handling, where you want to close all the open containers (apart from <body>)
1323 * before outputting the error message.
1325 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1326 * developer debug warning if it isn't.
1327 * @return string the HTML required to close any open containers inside <body>.
1329 public function container_end_all($shouldbenone = false) {
1330 return $this->opencontainers->pop_all_but_last($shouldbenone);
1334 * Returns course-specific information to be output immediately above content on any course page
1335 * (for the current course)
1337 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1338 * @return string
1340 public function course_content_header($onlyifnotcalledbefore = false) {
1341 global $CFG;
1342 static $functioncalled = false;
1343 if ($functioncalled && $onlyifnotcalledbefore) {
1344 // we have already output the content header
1345 return '';
1348 // Output any session notification.
1349 $notifications = \core\notification::fetch();
1351 $bodynotifications = '';
1352 foreach ($notifications as $notification) {
1353 $bodynotifications .= $this->render_from_template(
1354 $notification->get_template_name(),
1355 $notification->export_for_template($this)
1359 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1361 if ($this->page->course->id == SITEID) {
1362 // return immediately and do not include /course/lib.php if not necessary
1363 return $output;
1366 require_once($CFG->dirroot.'/course/lib.php');
1367 $functioncalled = true;
1368 $courseformat = course_get_format($this->page->course);
1369 if (($obj = $courseformat->course_content_header()) !== null) {
1370 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1372 return $output;
1376 * Returns course-specific information to be output immediately below content on any course page
1377 * (for the current course)
1379 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1380 * @return string
1382 public function course_content_footer($onlyifnotcalledbefore = false) {
1383 global $CFG;
1384 if ($this->page->course->id == SITEID) {
1385 // return immediately and do not include /course/lib.php if not necessary
1386 return '';
1388 static $functioncalled = false;
1389 if ($functioncalled && $onlyifnotcalledbefore) {
1390 // we have already output the content footer
1391 return '';
1393 $functioncalled = true;
1394 require_once($CFG->dirroot.'/course/lib.php');
1395 $courseformat = course_get_format($this->page->course);
1396 if (($obj = $courseformat->course_content_footer()) !== null) {
1397 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1399 return '';
1403 * Returns course-specific information to be output on any course page in the header area
1404 * (for the current course)
1406 * @return string
1408 public function course_header() {
1409 global $CFG;
1410 if ($this->page->course->id == SITEID) {
1411 // return immediately and do not include /course/lib.php if not necessary
1412 return '';
1414 require_once($CFG->dirroot.'/course/lib.php');
1415 $courseformat = course_get_format($this->page->course);
1416 if (($obj = $courseformat->course_header()) !== null) {
1417 return $courseformat->get_renderer($this->page)->render($obj);
1419 return '';
1423 * Returns course-specific information to be output on any course page in the footer area
1424 * (for the current course)
1426 * @return string
1428 public function course_footer() {
1429 global $CFG;
1430 if ($this->page->course->id == SITEID) {
1431 // return immediately and do not include /course/lib.php if not necessary
1432 return '';
1434 require_once($CFG->dirroot.'/course/lib.php');
1435 $courseformat = course_get_format($this->page->course);
1436 if (($obj = $courseformat->course_footer()) !== null) {
1437 return $courseformat->get_renderer($this->page)->render($obj);
1439 return '';
1443 * Returns lang menu or '', this method also checks forcing of languages in courses.
1445 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1447 * @return string The lang menu HTML or empty string
1449 public function lang_menu() {
1450 global $CFG;
1452 if (empty($CFG->langmenu)) {
1453 return '';
1456 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1457 // do not show lang menu if language forced
1458 return '';
1461 $currlang = current_language();
1462 $langs = get_string_manager()->get_list_of_translations();
1464 if (count($langs) < 2) {
1465 return '';
1468 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1469 $s->label = get_accesshide(get_string('language'));
1470 $s->class = 'langmenu';
1471 return $this->render($s);
1475 * Output the row of editing icons for a block, as defined by the controls array.
1477 * @param array $controls an array like {@link block_contents::$controls}.
1478 * @param string $blockid The ID given to the block.
1479 * @return string HTML fragment.
1481 public function block_controls($actions, $blockid = null) {
1482 global $CFG;
1483 if (empty($actions)) {
1484 return '';
1486 $menu = new action_menu($actions);
1487 if ($blockid !== null) {
1488 $menu->set_owner_selector('#'.$blockid);
1490 $menu->set_constraint('.block-region');
1491 $menu->attributes['class'] .= ' block-control-actions commands';
1492 return $this->render($menu);
1496 * Renders an action menu component.
1498 * ARIA references:
1499 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1500 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1502 * @param action_menu $menu
1503 * @return string HTML
1505 public function render_action_menu(action_menu $menu) {
1506 $context = $menu->export_for_template($this);
1507 return $this->render_from_template('core/action_menu', $context);
1511 * Renders an action_menu_link item.
1513 * @param action_menu_link $action
1514 * @return string HTML fragment
1516 protected function render_action_menu_link(action_menu_link $action) {
1517 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1521 * Renders a primary action_menu_filler item.
1523 * @param action_menu_link_filler $action
1524 * @return string HTML fragment
1526 protected function render_action_menu_filler(action_menu_filler $action) {
1527 return html_writer::span('&nbsp;', 'filler');
1531 * Renders a primary action_menu_link item.
1533 * @param action_menu_link_primary $action
1534 * @return string HTML fragment
1536 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1537 return $this->render_action_menu_link($action);
1541 * Renders a secondary action_menu_link item.
1543 * @param action_menu_link_secondary $action
1544 * @return string HTML fragment
1546 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1547 return $this->render_action_menu_link($action);
1551 * Prints a nice side block with an optional header.
1553 * The content is described
1554 * by a {@link core_renderer::block_contents} object.
1556 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1557 * <div class="header"></div>
1558 * <div class="content">
1559 * ...CONTENT...
1560 * <div class="footer">
1561 * </div>
1562 * </div>
1563 * <div class="annotation">
1564 * </div>
1565 * </div>
1567 * @param block_contents $bc HTML for the content
1568 * @param string $region the region the block is appearing in.
1569 * @return string the HTML to be output.
1571 public function block(block_contents $bc, $region) {
1572 $bc = clone($bc); // Avoid messing up the object passed in.
1573 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1574 $bc->collapsible = block_contents::NOT_HIDEABLE;
1576 if (!empty($bc->blockinstanceid)) {
1577 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1579 $skiptitle = strip_tags($bc->title);
1580 if ($bc->blockinstanceid && !empty($skiptitle)) {
1581 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1582 } else if (!empty($bc->arialabel)) {
1583 $bc->attributes['aria-label'] = $bc->arialabel;
1585 if ($bc->dockable) {
1586 $bc->attributes['data-dockable'] = 1;
1588 if ($bc->collapsible == block_contents::HIDDEN) {
1589 $bc->add_class('hidden');
1591 if (!empty($bc->controls)) {
1592 $bc->add_class('block_with_controls');
1596 if (empty($skiptitle)) {
1597 $output = '';
1598 $skipdest = '';
1599 } else {
1600 $output = html_writer::link('#sb-'.$bc->skipid, get_string('skipa', 'access', $skiptitle),
1601 array('class' => 'skip skip-block', 'id' => 'fsb-' . $bc->skipid));
1602 $skipdest = html_writer::span('', 'skip-block-to',
1603 array('id' => 'sb-' . $bc->skipid));
1606 $output .= html_writer::start_tag('div', $bc->attributes);
1608 $output .= $this->block_header($bc);
1609 $output .= $this->block_content($bc);
1611 $output .= html_writer::end_tag('div');
1613 $output .= $this->block_annotation($bc);
1615 $output .= $skipdest;
1617 $this->init_block_hider_js($bc);
1618 return $output;
1622 * Produces a header for a block
1624 * @param block_contents $bc
1625 * @return string
1627 protected function block_header(block_contents $bc) {
1629 $title = '';
1630 if ($bc->title) {
1631 $attributes = array();
1632 if ($bc->blockinstanceid) {
1633 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1635 $title = html_writer::tag('h2', $bc->title, $attributes);
1638 $blockid = null;
1639 if (isset($bc->attributes['id'])) {
1640 $blockid = $bc->attributes['id'];
1642 $controlshtml = $this->block_controls($bc->controls, $blockid);
1644 $output = '';
1645 if ($title || $controlshtml) {
1646 $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'));
1648 return $output;
1652 * Produces the content area for a block
1654 * @param block_contents $bc
1655 * @return string
1657 protected function block_content(block_contents $bc) {
1658 $output = html_writer::start_tag('div', array('class' => 'content'));
1659 if (!$bc->title && !$this->block_controls($bc->controls)) {
1660 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1662 $output .= $bc->content;
1663 $output .= $this->block_footer($bc);
1664 $output .= html_writer::end_tag('div');
1666 return $output;
1670 * Produces the footer for a block
1672 * @param block_contents $bc
1673 * @return string
1675 protected function block_footer(block_contents $bc) {
1676 $output = '';
1677 if ($bc->footer) {
1678 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1680 return $output;
1684 * Produces the annotation for a block
1686 * @param block_contents $bc
1687 * @return string
1689 protected function block_annotation(block_contents $bc) {
1690 $output = '';
1691 if ($bc->annotation) {
1692 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1694 return $output;
1698 * Calls the JS require function to hide a block.
1700 * @param block_contents $bc A block_contents object
1702 protected function init_block_hider_js(block_contents $bc) {
1703 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1704 $config = new stdClass;
1705 $config->id = $bc->attributes['id'];
1706 $config->title = strip_tags($bc->title);
1707 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1708 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1709 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1711 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1712 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1717 * Render the contents of a block_list.
1719 * @param array $icons the icon for each item.
1720 * @param array $items the content of each item.
1721 * @return string HTML
1723 public function list_block_contents($icons, $items) {
1724 $row = 0;
1725 $lis = array();
1726 foreach ($items as $key => $string) {
1727 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1728 if (!empty($icons[$key])) { //test if the content has an assigned icon
1729 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1731 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1732 $item .= html_writer::end_tag('li');
1733 $lis[] = $item;
1734 $row = 1 - $row; // Flip even/odd.
1736 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1740 * Output all the blocks in a particular region.
1742 * @param string $region the name of a region on this page.
1743 * @return string the HTML to be output.
1745 public function blocks_for_region($region) {
1746 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1747 $blocks = $this->page->blocks->get_blocks_for_region($region);
1748 $lastblock = null;
1749 $zones = array();
1750 foreach ($blocks as $block) {
1751 $zones[] = $block->title;
1753 $output = '';
1755 foreach ($blockcontents as $bc) {
1756 if ($bc instanceof block_contents) {
1757 $output .= $this->block($bc, $region);
1758 $lastblock = $bc->title;
1759 } else if ($bc instanceof block_move_target) {
1760 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1761 } else {
1762 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1765 return $output;
1769 * Output a place where the block that is currently being moved can be dropped.
1771 * @param block_move_target $target with the necessary details.
1772 * @param array $zones array of areas where the block can be moved to
1773 * @param string $previous the block located before the area currently being rendered.
1774 * @param string $region the name of the region
1775 * @return string the HTML to be output.
1777 public function block_move_target($target, $zones, $previous, $region) {
1778 if ($previous == null) {
1779 if (empty($zones)) {
1780 // There are no zones, probably because there are no blocks.
1781 $regions = $this->page->theme->get_all_block_regions();
1782 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1783 } else {
1784 $position = get_string('moveblockbefore', 'block', $zones[0]);
1786 } else {
1787 $position = get_string('moveblockafter', 'block', $previous);
1789 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1793 * Renders a special html link with attached action
1795 * Theme developers: DO NOT OVERRIDE! Please override function
1796 * {@link core_renderer::render_action_link()} instead.
1798 * @param string|moodle_url $url
1799 * @param string $text HTML fragment
1800 * @param component_action $action
1801 * @param array $attributes associative array of html link attributes + disabled
1802 * @param pix_icon optional pix icon to render with the link
1803 * @return string HTML fragment
1805 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1806 if (!($url instanceof moodle_url)) {
1807 $url = new moodle_url($url);
1809 $link = new action_link($url, $text, $action, $attributes, $icon);
1811 return $this->render($link);
1815 * Renders an action_link object.
1817 * The provided link is renderer and the HTML returned. At the same time the
1818 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1820 * @param action_link $link
1821 * @return string HTML fragment
1823 protected function render_action_link(action_link $link) {
1824 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1828 * Renders an action_icon.
1830 * This function uses the {@link core_renderer::action_link()} method for the
1831 * most part. What it does different is prepare the icon as HTML and use it
1832 * as the link text.
1834 * Theme developers: If you want to change how action links and/or icons are rendered,
1835 * consider overriding function {@link core_renderer::render_action_link()} and
1836 * {@link core_renderer::render_pix_icon()}.
1838 * @param string|moodle_url $url A string URL or moodel_url
1839 * @param pix_icon $pixicon
1840 * @param component_action $action
1841 * @param array $attributes associative array of html link attributes + disabled
1842 * @param bool $linktext show title next to image in link
1843 * @return string HTML fragment
1845 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1846 if (!($url instanceof moodle_url)) {
1847 $url = new moodle_url($url);
1849 $attributes = (array)$attributes;
1851 if (empty($attributes['class'])) {
1852 // let ppl override the class via $options
1853 $attributes['class'] = 'action-icon';
1856 $icon = $this->render($pixicon);
1858 if ($linktext) {
1859 $text = $pixicon->attributes['alt'];
1860 } else {
1861 $text = '';
1864 return $this->action_link($url, $text.$icon, $action, $attributes);
1868 * Print a message along with button choices for Continue/Cancel
1870 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1872 * @param string $message The question to ask the user
1873 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1874 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1875 * @return string HTML fragment
1877 public function confirm($message, $continue, $cancel) {
1878 if ($continue instanceof single_button) {
1879 // ok
1880 $continue->primary = true;
1881 } else if (is_string($continue)) {
1882 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1883 } else if ($continue instanceof moodle_url) {
1884 $continue = new single_button($continue, get_string('continue'), 'post', true);
1885 } else {
1886 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1889 if ($cancel instanceof single_button) {
1890 // ok
1891 } else if (is_string($cancel)) {
1892 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1893 } else if ($cancel instanceof moodle_url) {
1894 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1895 } else {
1896 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1899 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice');
1900 $output .= $this->box_start('modal-content', 'modal-content');
1901 $output .= $this->box_start('modal-header p-x-1', 'modal-header');
1902 $output .= html_writer::tag('h4', get_string('confirm'));
1903 $output .= $this->box_end();
1904 $output .= $this->box_start('modal-body', 'modal-body');
1905 $output .= html_writer::tag('p', $message);
1906 $output .= $this->box_end();
1907 $output .= $this->box_start('modal-footer', 'modal-footer');
1908 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1909 $output .= $this->box_end();
1910 $output .= $this->box_end();
1911 $output .= $this->box_end();
1912 return $output;
1916 * Returns a form with a single button.
1918 * Theme developers: DO NOT OVERRIDE! Please override function
1919 * {@link core_renderer::render_single_button()} instead.
1921 * @param string|moodle_url $url
1922 * @param string $label button text
1923 * @param string $method get or post submit method
1924 * @param array $options associative array {disabled, title, etc.}
1925 * @return string HTML fragment
1927 public function single_button($url, $label, $method='post', array $options=null) {
1928 if (!($url instanceof moodle_url)) {
1929 $url = new moodle_url($url);
1931 $button = new single_button($url, $label, $method);
1933 foreach ((array)$options as $key=>$value) {
1934 if (array_key_exists($key, $button)) {
1935 $button->$key = $value;
1939 return $this->render($button);
1943 * Renders a single button widget.
1945 * This will return HTML to display a form containing a single button.
1947 * @param single_button $button
1948 * @return string HTML fragment
1950 protected function render_single_button(single_button $button) {
1951 $attributes = array('type' => 'submit',
1952 'value' => $button->label,
1953 'disabled' => $button->disabled ? 'disabled' : null,
1954 'title' => $button->tooltip);
1956 if ($button->actions) {
1957 $id = html_writer::random_id('single_button');
1958 $attributes['id'] = $id;
1959 foreach ($button->actions as $action) {
1960 $this->add_action_handler($action, $id);
1964 // first the input element
1965 $output = html_writer::empty_tag('input', $attributes);
1967 // then hidden fields
1968 $params = $button->url->params();
1969 if ($button->method === 'post') {
1970 $params['sesskey'] = sesskey();
1972 foreach ($params as $var => $val) {
1973 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1976 // then div wrapper for xhtml strictness
1977 $output = html_writer::tag('div', $output);
1979 // now the form itself around it
1980 if ($button->method === 'get') {
1981 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1982 } else {
1983 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1985 if ($url === '') {
1986 $url = '#'; // there has to be always some action
1988 $attributes = array('method' => $button->method,
1989 'action' => $url,
1990 'id' => $button->formid);
1991 $output = html_writer::tag('form', $output, $attributes);
1993 // and finally one more wrapper with class
1994 return html_writer::tag('div', $output, array('class' => $button->class));
1998 * Returns a form with a single select widget.
2000 * Theme developers: DO NOT OVERRIDE! Please override function
2001 * {@link core_renderer::render_single_select()} instead.
2003 * @param moodle_url $url form action target, includes hidden fields
2004 * @param string $name name of selection field - the changing parameter in url
2005 * @param array $options list of options
2006 * @param string $selected selected element
2007 * @param array $nothing
2008 * @param string $formid
2009 * @param array $attributes other attributes for the single select
2010 * @return string HTML fragment
2012 public function single_select($url, $name, array $options, $selected = '',
2013 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2014 if (!($url instanceof moodle_url)) {
2015 $url = new moodle_url($url);
2017 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2019 if (array_key_exists('label', $attributes)) {
2020 $select->set_label($attributes['label']);
2021 unset($attributes['label']);
2023 $select->attributes = $attributes;
2025 return $this->render($select);
2029 * Returns a dataformat selection and download form
2031 * @param string $label A text label
2032 * @param moodle_url|string $base The download page url
2033 * @param string $name The query param which will hold the type of the download
2034 * @param array $params Extra params sent to the download page
2035 * @return string HTML fragment
2037 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2039 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2040 $options = array();
2041 foreach ($formats as $format) {
2042 if ($format->is_enabled()) {
2043 $options[] = array(
2044 'value' => $format->name,
2045 'label' => get_string('dataformat', $format->component),
2049 $hiddenparams = array();
2050 foreach ($params as $key => $value) {
2051 $hiddenparams[] = array(
2052 'name' => $key,
2053 'value' => $value,
2056 $data = array(
2057 'label' => $label,
2058 'base' => $base,
2059 'name' => $name,
2060 'params' => $hiddenparams,
2061 'options' => $options,
2062 'sesskey' => sesskey(),
2063 'submit' => get_string('download'),
2066 return $this->render_from_template('core/dataformat_selector', $data);
2071 * Internal implementation of single_select rendering
2073 * @param single_select $select
2074 * @return string HTML fragment
2076 protected function render_single_select(single_select $select) {
2077 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2081 * Returns a form with a url select widget.
2083 * Theme developers: DO NOT OVERRIDE! Please override function
2084 * {@link core_renderer::render_url_select()} instead.
2086 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2087 * @param string $selected selected element
2088 * @param array $nothing
2089 * @param string $formid
2090 * @return string HTML fragment
2092 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2093 $select = new url_select($urls, $selected, $nothing, $formid);
2094 return $this->render($select);
2098 * Internal implementation of url_select rendering
2100 * @param url_select $select
2101 * @return string HTML fragment
2103 protected function render_url_select(url_select $select) {
2104 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2108 * Returns a string containing a link to the user documentation.
2109 * Also contains an icon by default. Shown to teachers and admin only.
2111 * @param string $path The page link after doc root and language, no leading slash.
2112 * @param string $text The text to be displayed for the link
2113 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2114 * @return string
2116 public function doc_link($path, $text = '', $forcepopup = false) {
2117 global $CFG;
2119 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2121 $url = new moodle_url(get_docs_url($path));
2123 $attributes = array('href'=>$url);
2124 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2125 $attributes['class'] = 'helplinkpopup';
2128 return html_writer::tag('a', $icon.$text, $attributes);
2132 * Return HTML for an image_icon.
2134 * Theme developers: DO NOT OVERRIDE! Please override function
2135 * {@link core_renderer::render_image_icon()} instead.
2137 * @param string $pix short pix name
2138 * @param string $alt mandatory alt attribute
2139 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2140 * @param array $attributes htm lattributes
2141 * @return string HTML fragment
2143 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2144 $icon = new image_icon($pix, $alt, $component, $attributes);
2145 return $this->render($icon);
2149 * Renders a pix_icon widget and returns the HTML to display it.
2151 * @param image_icon $icon
2152 * @return string HTML fragment
2154 protected function render_image_icon(image_icon $icon) {
2155 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2156 return $system->render_pix_icon($this, $icon);
2160 * Return HTML for a pix_icon.
2162 * Theme developers: DO NOT OVERRIDE! Please override function
2163 * {@link core_renderer::render_pix_icon()} instead.
2165 * @param string $pix short pix name
2166 * @param string $alt mandatory alt attribute
2167 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2168 * @param array $attributes htm lattributes
2169 * @return string HTML fragment
2171 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2172 $icon = new pix_icon($pix, $alt, $component, $attributes);
2173 return $this->render($icon);
2177 * Renders a pix_icon widget and returns the HTML to display it.
2179 * @param pix_icon $icon
2180 * @return string HTML fragment
2182 protected function render_pix_icon(pix_icon $icon) {
2183 $system = \core\output\icon_system::instance();
2184 return $system->render_pix_icon($this, $icon);
2188 * Return HTML to display an emoticon icon.
2190 * @param pix_emoticon $emoticon
2191 * @return string HTML fragment
2193 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2194 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2195 return $system->render_pix_icon($this, $emoticon);
2199 * Produces the html that represents this rating in the UI
2201 * @param rating $rating the page object on which this rating will appear
2202 * @return string
2204 function render_rating(rating $rating) {
2205 global $CFG, $USER;
2207 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2208 return null;//ratings are turned off
2211 $ratingmanager = new rating_manager();
2212 // Initialise the JavaScript so ratings can be done by AJAX.
2213 $ratingmanager->initialise_rating_javascript($this->page);
2215 $strrate = get_string("rate", "rating");
2216 $ratinghtml = ''; //the string we'll return
2218 // permissions check - can they view the aggregate?
2219 if ($rating->user_can_view_aggregate()) {
2221 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2222 $aggregatestr = $rating->get_aggregate_string();
2224 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2225 if ($rating->count > 0) {
2226 $countstr = "({$rating->count})";
2227 } else {
2228 $countstr = '-';
2230 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2232 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2233 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2235 $nonpopuplink = $rating->get_view_ratings_url();
2236 $popuplink = $rating->get_view_ratings_url(true);
2238 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2239 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2240 } else {
2241 $ratinghtml .= $aggregatehtml;
2245 $formstart = null;
2246 // if the item doesn't belong to the current user, the user has permission to rate
2247 // and we're within the assessable period
2248 if ($rating->user_can_rate()) {
2250 $rateurl = $rating->get_rate_url();
2251 $inputs = $rateurl->params();
2253 //start the rating form
2254 $formattrs = array(
2255 'id' => "postrating{$rating->itemid}",
2256 'class' => 'postratingform',
2257 'method' => 'post',
2258 'action' => $rateurl->out_omit_querystring()
2260 $formstart = html_writer::start_tag('form', $formattrs);
2261 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2263 // add the hidden inputs
2264 foreach ($inputs as $name => $value) {
2265 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2266 $formstart .= html_writer::empty_tag('input', $attributes);
2269 if (empty($ratinghtml)) {
2270 $ratinghtml .= $strrate.': ';
2272 $ratinghtml = $formstart.$ratinghtml;
2274 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2275 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2276 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2277 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2279 //output submit button
2280 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2282 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2283 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2285 if (!$rating->settings->scale->isnumeric) {
2286 // If a global scale, try to find current course ID from the context
2287 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2288 $courseid = $coursecontext->instanceid;
2289 } else {
2290 $courseid = $rating->settings->scale->courseid;
2292 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2294 $ratinghtml .= html_writer::end_tag('span');
2295 $ratinghtml .= html_writer::end_tag('div');
2296 $ratinghtml .= html_writer::end_tag('form');
2299 return $ratinghtml;
2303 * Centered heading with attached help button (same title text)
2304 * and optional icon attached.
2306 * @param string $text A heading text
2307 * @param string $helpidentifier The keyword that defines a help page
2308 * @param string $component component name
2309 * @param string|moodle_url $icon
2310 * @param string $iconalt icon alt text
2311 * @param int $level The level of importance of the heading. Defaulting to 2
2312 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2313 * @return string HTML fragment
2315 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2316 $image = '';
2317 if ($icon) {
2318 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2321 $help = '';
2322 if ($helpidentifier) {
2323 $help = $this->help_icon($helpidentifier, $component);
2326 return $this->heading($image.$text.$help, $level, $classnames);
2330 * Returns HTML to display a help icon.
2332 * @deprecated since Moodle 2.0
2334 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2335 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2339 * Returns HTML to display a help icon.
2341 * Theme developers: DO NOT OVERRIDE! Please override function
2342 * {@link core_renderer::render_help_icon()} instead.
2344 * @param string $identifier The keyword that defines a help page
2345 * @param string $component component name
2346 * @param string|bool $linktext true means use $title as link text, string means link text value
2347 * @return string HTML fragment
2349 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2350 $icon = new help_icon($identifier, $component);
2351 $icon->diag_strings();
2352 if ($linktext === true) {
2353 $icon->linktext = get_string($icon->identifier, $icon->component);
2354 } else if (!empty($linktext)) {
2355 $icon->linktext = $linktext;
2357 return $this->render($icon);
2361 * Implementation of user image rendering.
2363 * @param help_icon $helpicon A help icon instance
2364 * @return string HTML fragment
2366 protected function render_help_icon(help_icon $helpicon) {
2367 return $this->render_from_template('core/help_icon', $helpicon->export_for_template($this));
2371 * Returns HTML to display a scale help icon.
2373 * @param int $courseid
2374 * @param stdClass $scale instance
2375 * @return string HTML fragment
2377 public function help_icon_scale($courseid, stdClass $scale) {
2378 global $CFG;
2380 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2382 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2384 $scaleid = abs($scale->id);
2386 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2387 $action = new popup_action('click', $link, 'ratingscale');
2389 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2393 * Creates and returns a spacer image with optional line break.
2395 * @param array $attributes Any HTML attributes to add to the spaced.
2396 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2397 * laxy do it with CSS which is a much better solution.
2398 * @return string HTML fragment
2400 public function spacer(array $attributes = null, $br = false) {
2401 $attributes = (array)$attributes;
2402 if (empty($attributes['width'])) {
2403 $attributes['width'] = 1;
2405 if (empty($attributes['height'])) {
2406 $attributes['height'] = 1;
2408 $attributes['class'] = 'spacer';
2410 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2412 if (!empty($br)) {
2413 $output .= '<br />';
2416 return $output;
2420 * Returns HTML to display the specified user's avatar.
2422 * User avatar may be obtained in two ways:
2423 * <pre>
2424 * // Option 1: (shortcut for simple cases, preferred way)
2425 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2426 * $OUTPUT->user_picture($user, array('popup'=>true));
2428 * // Option 2:
2429 * $userpic = new user_picture($user);
2430 * // Set properties of $userpic
2431 * $userpic->popup = true;
2432 * $OUTPUT->render($userpic);
2433 * </pre>
2435 * Theme developers: DO NOT OVERRIDE! Please override function
2436 * {@link core_renderer::render_user_picture()} instead.
2438 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2439 * If any of these are missing, the database is queried. Avoid this
2440 * if at all possible, particularly for reports. It is very bad for performance.
2441 * @param array $options associative array with user picture options, used only if not a user_picture object,
2442 * options are:
2443 * - courseid=$this->page->course->id (course id of user profile in link)
2444 * - size=35 (size of image)
2445 * - link=true (make image clickable - the link leads to user profile)
2446 * - popup=false (open in popup)
2447 * - alttext=true (add image alt attribute)
2448 * - class = image class attribute (default 'userpicture')
2449 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2450 * - includefullname=false (whether to include the user's full name together with the user picture)
2451 * @return string HTML fragment
2453 public function user_picture(stdClass $user, array $options = null) {
2454 $userpicture = new user_picture($user);
2455 foreach ((array)$options as $key=>$value) {
2456 if (array_key_exists($key, $userpicture)) {
2457 $userpicture->$key = $value;
2460 return $this->render($userpicture);
2464 * Internal implementation of user image rendering.
2466 * @param user_picture $userpicture
2467 * @return string
2469 protected function render_user_picture(user_picture $userpicture) {
2470 global $CFG, $DB;
2472 $user = $userpicture->user;
2474 if ($userpicture->alttext) {
2475 if (!empty($user->imagealt)) {
2476 $alt = $user->imagealt;
2477 } else {
2478 $alt = get_string('pictureof', '', fullname($user));
2480 } else {
2481 $alt = '';
2484 if (empty($userpicture->size)) {
2485 $size = 35;
2486 } else if ($userpicture->size === true or $userpicture->size == 1) {
2487 $size = 100;
2488 } else {
2489 $size = $userpicture->size;
2492 $class = $userpicture->class;
2494 if ($user->picture == 0) {
2495 $class .= ' defaultuserpic';
2498 $src = $userpicture->get_url($this->page, $this);
2500 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2501 if (!$userpicture->visibletoscreenreaders) {
2502 $attributes['role'] = 'presentation';
2505 // get the image html output fisrt
2506 $output = html_writer::empty_tag('img', $attributes);
2508 // Show fullname together with the picture when desired.
2509 if ($userpicture->includefullname) {
2510 $output .= fullname($userpicture->user);
2513 // then wrap it in link if needed
2514 if (!$userpicture->link) {
2515 return $output;
2518 if (empty($userpicture->courseid)) {
2519 $courseid = $this->page->course->id;
2520 } else {
2521 $courseid = $userpicture->courseid;
2524 if ($courseid == SITEID) {
2525 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2526 } else {
2527 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2530 $attributes = array('href'=>$url);
2531 if (!$userpicture->visibletoscreenreaders) {
2532 $attributes['tabindex'] = '-1';
2533 $attributes['aria-hidden'] = 'true';
2536 if ($userpicture->popup) {
2537 $id = html_writer::random_id('userpicture');
2538 $attributes['id'] = $id;
2539 $this->add_action_handler(new popup_action('click', $url), $id);
2542 return html_writer::tag('a', $output, $attributes);
2546 * Internal implementation of file tree viewer items rendering.
2548 * @param array $dir
2549 * @return string
2551 public function htmllize_file_tree($dir) {
2552 if (empty($dir['subdirs']) and empty($dir['files'])) {
2553 return '';
2555 $result = '<ul>';
2556 foreach ($dir['subdirs'] as $subdir) {
2557 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2559 foreach ($dir['files'] as $file) {
2560 $filename = $file->get_filename();
2561 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2563 $result .= '</ul>';
2565 return $result;
2569 * Returns HTML to display the file picker
2571 * <pre>
2572 * $OUTPUT->file_picker($options);
2573 * </pre>
2575 * Theme developers: DO NOT OVERRIDE! Please override function
2576 * {@link core_renderer::render_file_picker()} instead.
2578 * @param array $options associative array with file manager options
2579 * options are:
2580 * maxbytes=>-1,
2581 * itemid=>0,
2582 * client_id=>uniqid(),
2583 * acepted_types=>'*',
2584 * return_types=>FILE_INTERNAL,
2585 * context=>$PAGE->context
2586 * @return string HTML fragment
2588 public function file_picker($options) {
2589 $fp = new file_picker($options);
2590 return $this->render($fp);
2594 * Internal implementation of file picker rendering.
2596 * @param file_picker $fp
2597 * @return string
2599 public function render_file_picker(file_picker $fp) {
2600 global $CFG, $OUTPUT, $USER;
2601 $options = $fp->options;
2602 $client_id = $options->client_id;
2603 $strsaved = get_string('filesaved', 'repository');
2604 $straddfile = get_string('openpicker', 'repository');
2605 $strloading = get_string('loading', 'repository');
2606 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2607 $strdroptoupload = get_string('droptoupload', 'moodle');
2608 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2610 $currentfile = $options->currentfile;
2611 if (empty($currentfile)) {
2612 $currentfile = '';
2613 } else {
2614 $currentfile .= ' - ';
2616 if ($options->maxbytes) {
2617 $size = $options->maxbytes;
2618 } else {
2619 $size = get_max_upload_file_size();
2621 if ($size == -1) {
2622 $maxsize = '';
2623 } else {
2624 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2626 if ($options->buttonname) {
2627 $buttonname = ' name="' . $options->buttonname . '"';
2628 } else {
2629 $buttonname = '';
2631 $html = <<<EOD
2632 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2633 $icon_progress
2634 </div>
2635 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2636 <div>
2637 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2638 <span> $maxsize </span>
2639 </div>
2640 EOD;
2641 if ($options->env != 'url') {
2642 $html .= <<<EOD
2643 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2644 <div class="filepicker-filename">
2645 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2646 <div class="dndupload-progressbars"></div>
2647 </div>
2648 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2649 </div>
2650 EOD;
2652 $html .= '</div>';
2653 return $html;
2657 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2659 * @deprecated since Moodle 3.2
2661 * @param string $cmid the course_module id.
2662 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2663 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2665 public function update_module_button($cmid, $modulename) {
2666 global $CFG;
2668 debugging('core_renderer::update_module_button() has been deprecated and should not be used anymore. Activity modules ' .
2669 'should not add the edit module button, the link is already available in the Administration block. Themes can choose ' .
2670 'to display the link in the buttons row consistently for all module types.', DEBUG_DEVELOPER);
2672 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2673 $modulename = get_string('modulename', $modulename);
2674 $string = get_string('updatethis', '', $modulename);
2675 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2676 return $this->single_button($url, $string);
2677 } else {
2678 return '';
2683 * Returns HTML to display a "Turn editing on/off" button in a form.
2685 * @param moodle_url $url The URL + params to send through when clicking the button
2686 * @return string HTML the button
2688 public function edit_button(moodle_url $url) {
2690 $url->param('sesskey', sesskey());
2691 if ($this->page->user_is_editing()) {
2692 $url->param('edit', 'off');
2693 $editstring = get_string('turneditingoff');
2694 } else {
2695 $url->param('edit', 'on');
2696 $editstring = get_string('turneditingon');
2699 return $this->single_button($url, $editstring);
2703 * Returns HTML to display a simple button to close a window
2705 * @param string $text The lang string for the button's label (already output from get_string())
2706 * @return string html fragment
2708 public function close_window_button($text='') {
2709 if (empty($text)) {
2710 $text = get_string('closewindow');
2712 $button = new single_button(new moodle_url('#'), $text, 'get');
2713 $button->add_action(new component_action('click', 'close_window'));
2715 return $this->container($this->render($button), 'closewindow');
2719 * Output an error message. By default wraps the error message in <span class="error">.
2720 * If the error message is blank, nothing is output.
2722 * @param string $message the error message.
2723 * @return string the HTML to output.
2725 public function error_text($message) {
2726 if (empty($message)) {
2727 return '';
2729 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2730 return html_writer::tag('span', $message, array('class' => 'error'));
2734 * Do not call this function directly.
2736 * To terminate the current script with a fatal error, call the {@link print_error}
2737 * function, or throw an exception. Doing either of those things will then call this
2738 * function to display the error, before terminating the execution.
2740 * @param string $message The message to output
2741 * @param string $moreinfourl URL where more info can be found about the error
2742 * @param string $link Link for the Continue button
2743 * @param array $backtrace The execution backtrace
2744 * @param string $debuginfo Debugging information
2745 * @return string the HTML to output.
2747 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2748 global $CFG;
2750 $output = '';
2751 $obbuffer = '';
2753 if ($this->has_started()) {
2754 // we can not always recover properly here, we have problems with output buffering,
2755 // html tables, etc.
2756 $output .= $this->opencontainers->pop_all_but_last();
2758 } else {
2759 // It is really bad if library code throws exception when output buffering is on,
2760 // because the buffered text would be printed before our start of page.
2761 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2762 error_reporting(0); // disable notices from gzip compression, etc.
2763 while (ob_get_level() > 0) {
2764 $buff = ob_get_clean();
2765 if ($buff === false) {
2766 break;
2768 $obbuffer .= $buff;
2770 error_reporting($CFG->debug);
2772 // Output not yet started.
2773 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2774 if (empty($_SERVER['HTTP_RANGE'])) {
2775 @header($protocol . ' 404 Not Found');
2776 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2777 // Coax iOS 10 into sending the session cookie.
2778 @header($protocol . ' 403 Forbidden');
2779 } else {
2780 // Must stop byteserving attempts somehow,
2781 // this is weird but Chrome PDF viewer can be stopped only with 407!
2782 @header($protocol . ' 407 Proxy Authentication Required');
2785 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2786 $this->page->set_url('/'); // no url
2787 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2788 $this->page->set_title(get_string('error'));
2789 $this->page->set_heading($this->page->course->fullname);
2790 $output .= $this->header();
2793 $message = '<p class="errormessage">' . $message . '</p>'.
2794 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2795 get_string('moreinformation') . '</a></p>';
2796 if (empty($CFG->rolesactive)) {
2797 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2798 //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.
2800 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
2802 if ($CFG->debugdeveloper) {
2803 if (!empty($debuginfo)) {
2804 $debuginfo = s($debuginfo); // removes all nasty JS
2805 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2806 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2808 if (!empty($backtrace)) {
2809 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2811 if ($obbuffer !== '' ) {
2812 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2816 if (empty($CFG->rolesactive)) {
2817 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2818 } else if (!empty($link)) {
2819 $output .= $this->continue_button($link);
2822 $output .= $this->footer();
2824 // Padding to encourage IE to display our error page, rather than its own.
2825 $output .= str_repeat(' ', 512);
2827 return $output;
2831 * Output a notification (that is, a status message about something that has just happened).
2833 * Note: \core\notification::add() may be more suitable for your usage.
2835 * @param string $message The message to print out.
2836 * @param string $type The type of notification. See constants on \core\output\notification.
2837 * @return string the HTML to output.
2839 public function notification($message, $type = null) {
2840 $typemappings = [
2841 // Valid types.
2842 'success' => \core\output\notification::NOTIFY_SUCCESS,
2843 'info' => \core\output\notification::NOTIFY_INFO,
2844 'warning' => \core\output\notification::NOTIFY_WARNING,
2845 'error' => \core\output\notification::NOTIFY_ERROR,
2847 // Legacy types mapped to current types.
2848 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2849 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2850 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2851 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2852 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2853 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2854 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2857 $extraclasses = [];
2859 if ($type) {
2860 if (strpos($type, ' ') === false) {
2861 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2862 if (isset($typemappings[$type])) {
2863 $type = $typemappings[$type];
2864 } else {
2865 // The value provided did not match a known type. It must be an extra class.
2866 $extraclasses = [$type];
2868 } else {
2869 // Identify what type of notification this is.
2870 $classarray = explode(' ', self::prepare_classes($type));
2872 // Separate out the type of notification from the extra classes.
2873 foreach ($classarray as $class) {
2874 if (isset($typemappings[$class])) {
2875 $type = $typemappings[$class];
2876 } else {
2877 $extraclasses[] = $class;
2883 $notification = new \core\output\notification($message, $type);
2884 if (count($extraclasses)) {
2885 $notification->set_extra_classes($extraclasses);
2888 // Return the rendered template.
2889 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2893 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2895 public function notify_problem() {
2896 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
2897 'please use \core\notification::add(), or \core\output\notification as required.');
2901 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2903 public function notify_success() {
2904 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
2905 'please use \core\notification::add(), or \core\output\notification as required.');
2909 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2911 public function notify_message() {
2912 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
2913 'please use \core\notification::add(), or \core\output\notification as required.');
2917 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2919 public function notify_redirect() {
2920 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
2921 'please use \core\notification::add(), or \core\output\notification as required.');
2925 * Render a notification (that is, a status message about something that has
2926 * just happened).
2928 * @param \core\output\notification $notification the notification to print out
2929 * @return string the HTML to output.
2931 protected function render_notification(\core\output\notification $notification) {
2932 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2936 * Returns HTML to display a continue button that goes to a particular URL.
2938 * @param string|moodle_url $url The url the button goes to.
2939 * @return string the HTML to output.
2941 public function continue_button($url) {
2942 if (!($url instanceof moodle_url)) {
2943 $url = new moodle_url($url);
2945 $button = new single_button($url, get_string('continue'), 'get', true);
2946 $button->class = 'continuebutton';
2948 return $this->render($button);
2952 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2954 * Theme developers: DO NOT OVERRIDE! Please override function
2955 * {@link core_renderer::render_paging_bar()} instead.
2957 * @param int $totalcount The total number of entries available to be paged through
2958 * @param int $page The page you are currently viewing
2959 * @param int $perpage The number of entries that should be shown per page
2960 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2961 * @param string $pagevar name of page parameter that holds the page number
2962 * @return string the HTML to output.
2964 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2965 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2966 return $this->render($pb);
2970 * Internal implementation of paging bar rendering.
2972 * @param paging_bar $pagingbar
2973 * @return string
2975 protected function render_paging_bar(paging_bar $pagingbar) {
2976 $output = '';
2977 $pagingbar = clone($pagingbar);
2978 $pagingbar->prepare($this, $this->page, $this->target);
2980 if ($pagingbar->totalcount > $pagingbar->perpage) {
2981 $output .= get_string('page') . ':';
2983 if (!empty($pagingbar->previouslink)) {
2984 $output .= ' (' . $pagingbar->previouslink . ') ';
2987 if (!empty($pagingbar->firstlink)) {
2988 $output .= ' ' . $pagingbar->firstlink . ' ...';
2991 foreach ($pagingbar->pagelinks as $link) {
2992 $output .= " $link";
2995 if (!empty($pagingbar->lastlink)) {
2996 $output .= ' ... ' . $pagingbar->lastlink . ' ';
2999 if (!empty($pagingbar->nextlink)) {
3000 $output .= ' (' . $pagingbar->nextlink . ')';
3004 return html_writer::tag('div', $output, array('class' => 'paging'));
3008 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3010 * @param string $current the currently selected letter.
3011 * @param string $class class name to add to this initial bar.
3012 * @param string $title the name to put in front of this initial bar.
3013 * @param string $urlvar URL parameter name for this initial.
3014 * @param string $url URL object.
3015 * @param array $alpha of letters in the alphabet.
3016 * @return string the HTML to output.
3018 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3019 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3020 return $this->render($ib);
3024 * Internal implementation of initials bar rendering.
3026 * @param initials_bar $initialsbar
3027 * @return string
3029 protected function render_initials_bar(initials_bar $initialsbar) {
3030 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3034 * Output the place a skip link goes to.
3036 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3037 * @return string the HTML to output.
3039 public function skip_link_target($id = null) {
3040 return html_writer::span('', '', array('id' => $id));
3044 * Outputs a heading
3046 * @param string $text The text of the heading
3047 * @param int $level The level of importance of the heading. Defaulting to 2
3048 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3049 * @param string $id An optional ID
3050 * @return string the HTML to output.
3052 public function heading($text, $level = 2, $classes = null, $id = null) {
3053 $level = (integer) $level;
3054 if ($level < 1 or $level > 6) {
3055 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3057 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3061 * Outputs a box.
3063 * @param string $contents The contents of the box
3064 * @param string $classes A space-separated list of CSS classes
3065 * @param string $id An optional ID
3066 * @param array $attributes An array of other attributes to give the box.
3067 * @return string the HTML to output.
3069 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3070 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3074 * Outputs the opening section of a box.
3076 * @param string $classes A space-separated list of CSS classes
3077 * @param string $id An optional ID
3078 * @param array $attributes An array of other attributes to give the box.
3079 * @return string the HTML to output.
3081 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3082 $this->opencontainers->push('box', html_writer::end_tag('div'));
3083 $attributes['id'] = $id;
3084 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
3085 return html_writer::start_tag('div', $attributes);
3089 * Outputs the closing section of a box.
3091 * @return string the HTML to output.
3093 public function box_end() {
3094 return $this->opencontainers->pop('box');
3098 * Outputs a container.
3100 * @param string $contents The contents of the box
3101 * @param string $classes A space-separated list of CSS classes
3102 * @param string $id An optional ID
3103 * @return string the HTML to output.
3105 public function container($contents, $classes = null, $id = null) {
3106 return $this->container_start($classes, $id) . $contents . $this->container_end();
3110 * Outputs the opening section of a container.
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_start($classes = null, $id = null) {
3117 $this->opencontainers->push('container', html_writer::end_tag('div'));
3118 return html_writer::start_tag('div', array('id' => $id,
3119 'class' => renderer_base::prepare_classes($classes)));
3123 * Outputs the closing section of a container.
3125 * @return string the HTML to output.
3127 public function container_end() {
3128 return $this->opencontainers->pop('container');
3132 * Make nested HTML lists out of the items
3134 * The resulting list will look something like this:
3136 * <pre>
3137 * <<ul>>
3138 * <<li>><div class='tree_item parent'>(item contents)</div>
3139 * <<ul>
3140 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3141 * <</ul>>
3142 * <</li>>
3143 * <</ul>>
3144 * </pre>
3146 * @param array $items
3147 * @param array $attrs html attributes passed to the top ofs the list
3148 * @return string HTML
3150 public function tree_block_contents($items, $attrs = array()) {
3151 // exit if empty, we don't want an empty ul element
3152 if (empty($items)) {
3153 return '';
3155 // array of nested li elements
3156 $lis = array();
3157 foreach ($items as $item) {
3158 // this applies to the li item which contains all child lists too
3159 $content = $item->content($this);
3160 $liclasses = array($item->get_css_type());
3161 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3162 $liclasses[] = 'collapsed';
3164 if ($item->isactive === true) {
3165 $liclasses[] = 'current_branch';
3167 $liattr = array('class'=>join(' ',$liclasses));
3168 // class attribute on the div item which only contains the item content
3169 $divclasses = array('tree_item');
3170 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3171 $divclasses[] = 'branch';
3172 } else {
3173 $divclasses[] = 'leaf';
3175 if (!empty($item->classes) && count($item->classes)>0) {
3176 $divclasses[] = join(' ', $item->classes);
3178 $divattr = array('class'=>join(' ', $divclasses));
3179 if (!empty($item->id)) {
3180 $divattr['id'] = $item->id;
3182 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3183 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3184 $content = html_writer::empty_tag('hr') . $content;
3186 $content = html_writer::tag('li', $content, $liattr);
3187 $lis[] = $content;
3189 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3193 * Returns a search box.
3195 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3196 * @return string HTML with the search form hidden by default.
3198 public function search_box($id = false) {
3199 global $CFG;
3201 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3202 // result in an extra included file for each site, even the ones where global search
3203 // is disabled.
3204 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3205 return '';
3208 if ($id == false) {
3209 $id = uniqid();
3210 } else {
3211 // Needs to be cleaned, we use it for the input id.
3212 $id = clean_param($id, PARAM_ALPHANUMEXT);
3215 // JS to animate the form.
3216 $this->page->requires->js_call_amd('core/search-input', 'init', array($id));
3218 $searchicon = html_writer::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
3219 array('role' => 'button', 'tabindex' => 0));
3220 $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot . '/search/index.php');
3221 $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
3222 'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id, 'class' => 'form-control');
3224 $contents = html_writer::tag('label', get_string('enteryoursearchquery', 'search'),
3225 array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer::tag('input', '', $inputattrs);
3226 if ($this->page->context && $this->page->context->contextlevel !== CONTEXT_SYSTEM) {
3227 $contents .= html_writer::empty_tag('input', ['type' => 'hidden',
3228 'name' => 'context', 'value' => $this->page->context->id]);
3230 $searchinput = html_writer::tag('form', $contents, $formattrs);
3232 return html_writer::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper nav-link', 'id' => $id));
3236 * Allow plugins to provide some content to be rendered in the navbar.
3237 * The plugin must define a PLUGIN_render_navbar_output function that returns
3238 * the HTML they wish to add to the navbar.
3240 * @return string HTML for the navbar
3242 public function navbar_plugin_output() {
3243 $output = '';
3245 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3246 foreach ($pluginsfunction as $plugintype => $plugins) {
3247 foreach ($plugins as $pluginfunction) {
3248 $output .= $pluginfunction($this);
3253 return $output;
3257 * Construct a user menu, returning HTML that can be echoed out by a
3258 * layout file.
3260 * @param stdClass $user A user object, usually $USER.
3261 * @param bool $withlinks true if a dropdown should be built.
3262 * @return string HTML fragment.
3264 public function user_menu($user = null, $withlinks = null) {
3265 global $USER, $CFG;
3266 require_once($CFG->dirroot . '/user/lib.php');
3268 if (is_null($user)) {
3269 $user = $USER;
3272 // Note: this behaviour is intended to match that of core_renderer::login_info,
3273 // but should not be considered to be good practice; layout options are
3274 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3275 if (is_null($withlinks)) {
3276 $withlinks = empty($this->page->layout_options['nologinlinks']);
3279 // Add a class for when $withlinks is false.
3280 $usermenuclasses = 'usermenu';
3281 if (!$withlinks) {
3282 $usermenuclasses .= ' withoutlinks';
3285 $returnstr = "";
3287 // If during initial install, return the empty return string.
3288 if (during_initial_install()) {
3289 return $returnstr;
3292 $loginpage = $this->is_login_page();
3293 $loginurl = get_login_url();
3294 // If not logged in, show the typical not-logged-in string.
3295 if (!isloggedin()) {
3296 $returnstr = get_string('loggedinnot', 'moodle');
3297 if (!$loginpage) {
3298 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3300 return html_writer::div(
3301 html_writer::span(
3302 $returnstr,
3303 'login'
3305 $usermenuclasses
3310 // If logged in as a guest user, show a string to that effect.
3311 if (isguestuser()) {
3312 $returnstr = get_string('loggedinasguest');
3313 if (!$loginpage && $withlinks) {
3314 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3317 return html_writer::div(
3318 html_writer::span(
3319 $returnstr,
3320 'login'
3322 $usermenuclasses
3326 // Get some navigation opts.
3327 $opts = user_get_user_navigation_info($user, $this->page);
3329 $avatarclasses = "avatars";
3330 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3331 $usertextcontents = $opts->metadata['userfullname'];
3333 // Other user.
3334 if (!empty($opts->metadata['asotheruser'])) {
3335 $avatarcontents .= html_writer::span(
3336 $opts->metadata['realuseravatar'],
3337 'avatar realuser'
3339 $usertextcontents = $opts->metadata['realuserfullname'];
3340 $usertextcontents .= html_writer::tag(
3341 'span',
3342 get_string(
3343 'loggedinas',
3344 'moodle',
3345 html_writer::span(
3346 $opts->metadata['userfullname'],
3347 'value'
3350 array('class' => 'meta viewingas')
3354 // Role.
3355 if (!empty($opts->metadata['asotherrole'])) {
3356 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3357 $usertextcontents .= html_writer::span(
3358 $opts->metadata['rolename'],
3359 'meta role role-' . $role
3363 // User login failures.
3364 if (!empty($opts->metadata['userloginfail'])) {
3365 $usertextcontents .= html_writer::span(
3366 $opts->metadata['userloginfail'],
3367 'meta loginfailures'
3371 // MNet.
3372 if (!empty($opts->metadata['asmnetuser'])) {
3373 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3374 $usertextcontents .= html_writer::span(
3375 $opts->metadata['mnetidprovidername'],
3376 'meta mnet mnet-' . $mnet
3380 $returnstr .= html_writer::span(
3381 html_writer::span($usertextcontents, 'usertext') .
3382 html_writer::span($avatarcontents, $avatarclasses),
3383 'userbutton'
3386 // Create a divider (well, a filler).
3387 $divider = new action_menu_filler();
3388 $divider->primary = false;
3390 $am = new action_menu();
3391 $am->set_menu_trigger(
3392 $returnstr
3394 $am->set_alignment(action_menu::TR, action_menu::BR);
3395 $am->set_nowrap_on_items();
3396 if ($withlinks) {
3397 $navitemcount = count($opts->navitems);
3398 $idx = 0;
3399 foreach ($opts->navitems as $key => $value) {
3401 switch ($value->itemtype) {
3402 case 'divider':
3403 // If the nav item is a divider, add one and skip link processing.
3404 $am->add($divider);
3405 break;
3407 case 'invalid':
3408 // Silently skip invalid entries (should we post a notification?).
3409 break;
3411 case 'link':
3412 // Process this as a link item.
3413 $pix = null;
3414 if (isset($value->pix) && !empty($value->pix)) {
3415 $pix = new pix_icon($value->pix, $value->title, null, array('class' => 'iconsmall'));
3416 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3417 $value->title = html_writer::img(
3418 $value->imgsrc,
3419 $value->title,
3420 array('class' => 'iconsmall')
3421 ) . $value->title;
3424 $al = new action_menu_link_secondary(
3425 $value->url,
3426 $pix,
3427 $value->title,
3428 array('class' => 'icon')
3430 if (!empty($value->titleidentifier)) {
3431 $al->attributes['data-title'] = $value->titleidentifier;
3433 $am->add($al);
3434 break;
3437 $idx++;
3439 // Add dividers after the first item and before the last item.
3440 if ($idx == 1 || $idx == $navitemcount - 1) {
3441 $am->add($divider);
3446 return html_writer::div(
3447 $this->render($am),
3448 $usermenuclasses
3453 * Return the navbar content so that it can be echoed out by the layout
3455 * @return string XHTML navbar
3457 public function navbar() {
3458 $items = $this->page->navbar->get_items();
3459 $itemcount = count($items);
3460 if ($itemcount === 0) {
3461 return '';
3464 $htmlblocks = array();
3465 // Iterate the navarray and display each node
3466 $separator = get_separator();
3467 for ($i=0;$i < $itemcount;$i++) {
3468 $item = $items[$i];
3469 $item->hideicon = true;
3470 if ($i===0) {
3471 $content = html_writer::tag('li', $this->render($item));
3472 } else {
3473 $content = html_writer::tag('li', $separator.$this->render($item));
3475 $htmlblocks[] = $content;
3478 //accessibility: heading for navbar list (MDL-20446)
3479 $navbarcontent = html_writer::tag('span', get_string('pagepath'),
3480 array('class' => 'accesshide', 'id' => 'navbar-label'));
3481 $navbarcontent .= html_writer::tag('nav',
3482 html_writer::tag('ul', join('', $htmlblocks)),
3483 array('aria-labelledby' => 'navbar-label'));
3484 // XHTML
3485 return $navbarcontent;
3489 * Renders a breadcrumb navigation node object.
3491 * @param breadcrumb_navigation_node $item The navigation node to render.
3492 * @return string HTML fragment
3494 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3496 if ($item->action instanceof moodle_url) {
3497 $content = $item->get_content();
3498 $title = $item->get_title();
3499 $attributes = array();
3500 $attributes['itemprop'] = 'url';
3501 if ($title !== '') {
3502 $attributes['title'] = $title;
3504 if ($item->hidden) {
3505 $attributes['class'] = 'dimmed_text';
3507 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3508 $content = html_writer::link($item->action, $content, $attributes);
3510 $attributes = array();
3511 $attributes['itemscope'] = '';
3512 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3513 $content = html_writer::tag('span', $content, $attributes);
3515 } else {
3516 $content = $this->render_navigation_node($item);
3518 return $content;
3522 * Renders a navigation node object.
3524 * @param navigation_node $item The navigation node to render.
3525 * @return string HTML fragment
3527 protected function render_navigation_node(navigation_node $item) {
3528 $content = $item->get_content();
3529 $title = $item->get_title();
3530 if ($item->icon instanceof renderable && !$item->hideicon) {
3531 $icon = $this->render($item->icon);
3532 $content = $icon.$content; // use CSS for spacing of icons
3534 if ($item->helpbutton !== null) {
3535 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3537 if ($content === '') {
3538 return '';
3540 if ($item->action instanceof action_link) {
3541 $link = $item->action;
3542 if ($item->hidden) {
3543 $link->add_class('dimmed');
3545 if (!empty($content)) {
3546 // Providing there is content we will use that for the link content.
3547 $link->text = $content;
3549 $content = $this->render($link);
3550 } else if ($item->action instanceof moodle_url) {
3551 $attributes = array();
3552 if ($title !== '') {
3553 $attributes['title'] = $title;
3555 if ($item->hidden) {
3556 $attributes['class'] = 'dimmed_text';
3558 $content = html_writer::link($item->action, $content, $attributes);
3560 } else if (is_string($item->action) || empty($item->action)) {
3561 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3562 if ($title !== '') {
3563 $attributes['title'] = $title;
3565 if ($item->hidden) {
3566 $attributes['class'] = 'dimmed_text';
3568 $content = html_writer::tag('span', $content, $attributes);
3570 return $content;
3574 * Accessibility: Right arrow-like character is
3575 * used in the breadcrumb trail, course navigation menu
3576 * (previous/next activity), calendar, and search forum block.
3577 * If the theme does not set characters, appropriate defaults
3578 * are set automatically. Please DO NOT
3579 * use &lt; &gt; &raquo; - these are confusing for blind users.
3581 * @return string
3583 public function rarrow() {
3584 return $this->page->theme->rarrow;
3588 * Accessibility: Left arrow-like character is
3589 * used in the breadcrumb trail, course navigation menu
3590 * (previous/next activity), calendar, and search forum block.
3591 * If the theme does not set characters, appropriate defaults
3592 * are set automatically. Please DO NOT
3593 * use &lt; &gt; &raquo; - these are confusing for blind users.
3595 * @return string
3597 public function larrow() {
3598 return $this->page->theme->larrow;
3602 * Accessibility: Up arrow-like character is used in
3603 * the book heirarchical navigation.
3604 * If the theme does not set characters, appropriate defaults
3605 * are set automatically. Please DO NOT
3606 * use ^ - this is confusing for blind users.
3608 * @return string
3610 public function uarrow() {
3611 return $this->page->theme->uarrow;
3615 * Accessibility: Down arrow-like character.
3616 * If the theme does not set characters, appropriate defaults
3617 * are set automatically.
3619 * @return string
3621 public function darrow() {
3622 return $this->page->theme->darrow;
3626 * Returns the custom menu if one has been set
3628 * A custom menu can be configured by browsing to
3629 * Settings: Administration > Appearance > Themes > Theme settings
3630 * and then configuring the custommenu config setting as described.
3632 * Theme developers: DO NOT OVERRIDE! Please override function
3633 * {@link core_renderer::render_custom_menu()} instead.
3635 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3636 * @return string
3638 public function custom_menu($custommenuitems = '') {
3639 global $CFG;
3640 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3641 $custommenuitems = $CFG->custommenuitems;
3643 if (empty($custommenuitems)) {
3644 return '';
3646 $custommenu = new custom_menu($custommenuitems, current_language());
3647 return $this->render($custommenu);
3651 * Renders a custom menu object (located in outputcomponents.php)
3653 * The custom menu this method produces makes use of the YUI3 menunav widget
3654 * and requires very specific html elements and classes.
3656 * @staticvar int $menucount
3657 * @param custom_menu $menu
3658 * @return string
3660 protected function render_custom_menu(custom_menu $menu) {
3661 static $menucount = 0;
3662 // If the menu has no children return an empty string
3663 if (!$menu->has_children()) {
3664 return '';
3666 // Increment the menu count. This is used for ID's that get worked with
3667 // in JavaScript as is essential
3668 $menucount++;
3669 // Initialise this custom menu (the custom menu object is contained in javascript-static
3670 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
3671 $jscode = "(function(){{$jscode}})";
3672 $this->page->requires->yui_module('node-menunav', $jscode);
3673 // Build the root nodes as required by YUI
3674 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
3675 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3676 $content .= html_writer::start_tag('ul');
3677 // Render each child
3678 foreach ($menu->get_children() as $item) {
3679 $content .= $this->render_custom_menu_item($item);
3681 // Close the open tags
3682 $content .= html_writer::end_tag('ul');
3683 $content .= html_writer::end_tag('div');
3684 $content .= html_writer::end_tag('div');
3685 // Return the custom menu
3686 return $content;
3690 * Renders a custom menu node as part of a submenu
3692 * The custom menu this method produces makes use of the YUI3 menunav widget
3693 * and requires very specific html elements and classes.
3695 * @see core:renderer::render_custom_menu()
3697 * @staticvar int $submenucount
3698 * @param custom_menu_item $menunode
3699 * @return string
3701 protected function render_custom_menu_item(custom_menu_item $menunode) {
3702 // Required to ensure we get unique trackable id's
3703 static $submenucount = 0;
3704 if ($menunode->has_children()) {
3705 // If the child has menus render it as a sub menu
3706 $submenucount++;
3707 $content = html_writer::start_tag('li');
3708 if ($menunode->get_url() !== null) {
3709 $url = $menunode->get_url();
3710 } else {
3711 $url = '#cm_submenu_'.$submenucount;
3713 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3714 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3715 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3716 $content .= html_writer::start_tag('ul');
3717 foreach ($menunode->get_children() as $menunode) {
3718 $content .= $this->render_custom_menu_item($menunode);
3720 $content .= html_writer::end_tag('ul');
3721 $content .= html_writer::end_tag('div');
3722 $content .= html_writer::end_tag('div');
3723 $content .= html_writer::end_tag('li');
3724 } else {
3725 // The node doesn't have children so produce a final menuitem.
3726 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3727 $content = '';
3728 if (preg_match("/^#+$/", $menunode->get_text())) {
3730 // This is a divider.
3731 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3732 } else {
3733 $content = html_writer::start_tag(
3734 'li',
3735 array(
3736 'class' => 'yui3-menuitem'
3739 if ($menunode->get_url() !== null) {
3740 $url = $menunode->get_url();
3741 } else {
3742 $url = '#';
3744 $content .= html_writer::link(
3745 $url,
3746 $menunode->get_text(),
3747 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3750 $content .= html_writer::end_tag('li');
3752 // Return the sub menu
3753 return $content;
3757 * Renders theme links for switching between default and other themes.
3759 * @return string
3761 protected function theme_switch_links() {
3763 $actualdevice = core_useragent::get_device_type();
3764 $currentdevice = $this->page->devicetypeinuse;
3765 $switched = ($actualdevice != $currentdevice);
3767 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3768 // The user is using the a default device and hasn't switched so don't shown the switch
3769 // device links.
3770 return '';
3773 if ($switched) {
3774 $linktext = get_string('switchdevicerecommended');
3775 $devicetype = $actualdevice;
3776 } else {
3777 $linktext = get_string('switchdevicedefault');
3778 $devicetype = 'default';
3780 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3782 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3783 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3784 $content .= html_writer::end_tag('div');
3786 return $content;
3790 * Renders tabs
3792 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3794 * Theme developers: In order to change how tabs are displayed please override functions
3795 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3797 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3798 * @param string|null $selected which tab to mark as selected, all parent tabs will
3799 * automatically be marked as activated
3800 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3801 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3802 * @return string
3804 public final function tabtree($tabs, $selected = null, $inactive = null) {
3805 return $this->render(new tabtree($tabs, $selected, $inactive));
3809 * Renders tabtree
3811 * @param tabtree $tabtree
3812 * @return string
3814 protected function render_tabtree(tabtree $tabtree) {
3815 if (empty($tabtree->subtree)) {
3816 return '';
3818 $str = '';
3819 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
3820 $str .= $this->render_tabobject($tabtree);
3821 $str .= html_writer::end_tag('div').
3822 html_writer::tag('div', ' ', array('class' => 'clearer'));
3823 return $str;
3827 * Renders tabobject (part of tabtree)
3829 * This function is called from {@link core_renderer::render_tabtree()}
3830 * and also it calls itself when printing the $tabobject subtree recursively.
3832 * Property $tabobject->level indicates the number of row of tabs.
3834 * @param tabobject $tabobject
3835 * @return string HTML fragment
3837 protected function render_tabobject(tabobject $tabobject) {
3838 $str = '';
3840 // Print name of the current tab.
3841 if ($tabobject instanceof tabtree) {
3842 // No name for tabtree root.
3843 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3844 // Tab name without a link. The <a> tag is used for styling.
3845 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3846 } else {
3847 // Tab name with a link.
3848 if (!($tabobject->link instanceof moodle_url)) {
3849 // backward compartibility when link was passed as quoted string
3850 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3851 } else {
3852 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3856 if (empty($tabobject->subtree)) {
3857 if ($tabobject->selected) {
3858 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3860 return $str;
3863 // Print subtree.
3864 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
3865 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3866 $cnt = 0;
3867 foreach ($tabobject->subtree as $tab) {
3868 $liclass = '';
3869 if (!$cnt) {
3870 $liclass .= ' first';
3872 if ($cnt == count($tabobject->subtree) - 1) {
3873 $liclass .= ' last';
3875 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3876 $liclass .= ' onerow';
3879 if ($tab->selected) {
3880 $liclass .= ' here selected';
3881 } else if ($tab->activated) {
3882 $liclass .= ' here active';
3885 // This will recursively call function render_tabobject() for each item in subtree.
3886 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3887 $cnt++;
3889 $str .= html_writer::end_tag('ul');
3892 return $str;
3896 * Get the HTML for blocks in the given region.
3898 * @since Moodle 2.5.1 2.6
3899 * @param string $region The region to get HTML for.
3900 * @return string HTML.
3902 public function blocks($region, $classes = array(), $tag = 'aside') {
3903 $displayregion = $this->page->apply_theme_region_manipulations($region);
3904 $classes = (array)$classes;
3905 $classes[] = 'block-region';
3906 $attributes = array(
3907 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3908 'class' => join(' ', $classes),
3909 'data-blockregion' => $displayregion,
3910 'data-droptarget' => '1'
3912 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3913 $content = $this->blocks_for_region($displayregion);
3914 } else {
3915 $content = '';
3917 return html_writer::tag($tag, $content, $attributes);
3921 * Renders a custom block region.
3923 * Use this method if you want to add an additional block region to the content of the page.
3924 * Please note this should only be used in special situations.
3925 * We want to leave the theme is control where ever possible!
3927 * This method must use the same method that the theme uses within its layout file.
3928 * As such it asks the theme what method it is using.
3929 * It can be one of two values, blocks or blocks_for_region (deprecated).
3931 * @param string $regionname The name of the custom region to add.
3932 * @return string HTML for the block region.
3934 public function custom_block_region($regionname) {
3935 if ($this->page->theme->get_block_render_method() === 'blocks') {
3936 return $this->blocks($regionname);
3937 } else {
3938 return $this->blocks_for_region($regionname);
3943 * Returns the CSS classes to apply to the body tag.
3945 * @since Moodle 2.5.1 2.6
3946 * @param array $additionalclasses Any additional classes to apply.
3947 * @return string
3949 public function body_css_classes(array $additionalclasses = array()) {
3950 // Add a class for each block region on the page.
3951 // We use the block manager here because the theme object makes get_string calls.
3952 $usedregions = array();
3953 foreach ($this->page->blocks->get_regions() as $region) {
3954 $additionalclasses[] = 'has-region-'.$region;
3955 if ($this->page->blocks->region_has_content($region, $this)) {
3956 $additionalclasses[] = 'used-region-'.$region;
3957 $usedregions[] = $region;
3958 } else {
3959 $additionalclasses[] = 'empty-region-'.$region;
3961 if ($this->page->blocks->region_completely_docked($region, $this)) {
3962 $additionalclasses[] = 'docked-region-'.$region;
3965 if (!$usedregions) {
3966 // No regions means there is only content, add 'content-only' class.
3967 $additionalclasses[] = 'content-only';
3968 } else if (count($usedregions) === 1) {
3969 // Add the -only class for the only used region.
3970 $region = array_shift($usedregions);
3971 $additionalclasses[] = $region . '-only';
3973 foreach ($this->page->layout_options as $option => $value) {
3974 if ($value) {
3975 $additionalclasses[] = 'layout-option-'.$option;
3978 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
3979 return $css;
3983 * The ID attribute to apply to the body tag.
3985 * @since Moodle 2.5.1 2.6
3986 * @return string
3988 public function body_id() {
3989 return $this->page->bodyid;
3993 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
3995 * @since Moodle 2.5.1 2.6
3996 * @param string|array $additionalclasses Any additional classes to give the body tag,
3997 * @return string
3999 public function body_attributes($additionalclasses = array()) {
4000 if (!is_array($additionalclasses)) {
4001 $additionalclasses = explode(' ', $additionalclasses);
4003 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4007 * Gets HTML for the page heading.
4009 * @since Moodle 2.5.1 2.6
4010 * @param string $tag The tag to encase the heading in. h1 by default.
4011 * @return string HTML.
4013 public function page_heading($tag = 'h1') {
4014 return html_writer::tag($tag, $this->page->heading);
4018 * Gets the HTML for the page heading button.
4020 * @since Moodle 2.5.1 2.6
4021 * @return string HTML.
4023 public function page_heading_button() {
4024 return $this->page->button;
4028 * Returns the Moodle docs link to use for this page.
4030 * @since Moodle 2.5.1 2.6
4031 * @param string $text
4032 * @return string
4034 public function page_doc_link($text = null) {
4035 if ($text === null) {
4036 $text = get_string('moodledocslink');
4038 $path = page_get_doc_link_path($this->page);
4039 if (!$path) {
4040 return '';
4042 return $this->doc_link($path, $text);
4046 * Returns the page heading menu.
4048 * @since Moodle 2.5.1 2.6
4049 * @return string HTML.
4051 public function page_heading_menu() {
4052 return $this->page->headingmenu;
4056 * Returns the title to use on the page.
4058 * @since Moodle 2.5.1 2.6
4059 * @return string
4061 public function page_title() {
4062 return $this->page->title;
4066 * Returns the URL for the favicon.
4068 * @since Moodle 2.5.1 2.6
4069 * @return string The favicon URL
4071 public function favicon() {
4072 return $this->image_url('favicon', 'theme');
4076 * Renders preferences groups.
4078 * @param preferences_groups $renderable The renderable
4079 * @return string The output.
4081 public function render_preferences_groups(preferences_groups $renderable) {
4082 $html = '';
4083 $html .= html_writer::start_div('row-fluid');
4084 $html .= html_writer::start_tag('div', array('class' => 'span12 preferences-groups'));
4085 $i = 0;
4086 $open = false;
4087 foreach ($renderable->groups as $group) {
4088 if ($i == 0 || $i % 3 == 0) {
4089 if ($open) {
4090 $html .= html_writer::end_tag('div');
4092 $html .= html_writer::start_tag('div', array('class' => 'row-fluid'));
4093 $open = true;
4095 $html .= $this->render($group);
4096 $i++;
4099 $html .= html_writer::end_tag('div');
4101 $html .= html_writer::end_tag('ul');
4102 $html .= html_writer::end_tag('div');
4103 $html .= html_writer::end_div();
4104 return $html;
4108 * Renders preferences group.
4110 * @param preferences_group $renderable The renderable
4111 * @return string The output.
4113 public function render_preferences_group(preferences_group $renderable) {
4114 $html = '';
4115 $html .= html_writer::start_tag('div', array('class' => 'span4 preferences-group'));
4116 $html .= $this->heading($renderable->title, 3);
4117 $html .= html_writer::start_tag('ul');
4118 foreach ($renderable->nodes as $node) {
4119 if ($node->has_children()) {
4120 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4122 $html .= html_writer::tag('li', $this->render($node));
4124 $html .= html_writer::end_tag('ul');
4125 $html .= html_writer::end_tag('div');
4126 return $html;
4129 public function context_header($headerinfo = null, $headinglevel = 1) {
4130 global $DB, $USER, $CFG;
4131 require_once($CFG->dirroot . '/user/lib.php');
4132 $context = $this->page->context;
4133 $heading = null;
4134 $imagedata = null;
4135 $subheader = null;
4136 $userbuttons = null;
4137 // Make sure to use the heading if it has been set.
4138 if (isset($headerinfo['heading'])) {
4139 $heading = $headerinfo['heading'];
4141 // The user context currently has images and buttons. Other contexts may follow.
4142 if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
4143 if (isset($headerinfo['user'])) {
4144 $user = $headerinfo['user'];
4145 } else {
4146 // Look up the user information if it is not supplied.
4147 $user = $DB->get_record('user', array('id' => $context->instanceid));
4150 // If the user context is set, then use that for capability checks.
4151 if (isset($headerinfo['usercontext'])) {
4152 $context = $headerinfo['usercontext'];
4155 // Only provide user information if the user is the current user, or a user which the current user can view.
4156 // When checking user_can_view_profile(), either:
4157 // If the page context is course, check the course context (from the page object) or;
4158 // If page context is NOT course, then check across all courses.
4159 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4161 if (user_can_view_profile($user, $course)) {
4162 // Use the user's full name if the heading isn't set.
4163 if (!isset($heading)) {
4164 $heading = fullname($user);
4167 $imagedata = $this->user_picture($user, array('size' => 100));
4169 // Check to see if we should be displaying a message button.
4170 if (!empty($CFG->messaging) && $USER->id != $user->id && has_capability('moodle/site:sendmessage', $context)) {
4171 $iscontact = !empty(message_get_contact($user->id));
4172 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4173 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4174 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4175 $userbuttons = array(
4176 'messages' => array(
4177 'buttontype' => 'message',
4178 'title' => get_string('message', 'message'),
4179 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4180 'image' => 'message',
4181 'linkattributes' => array('role' => 'button'),
4182 'page' => $this->page
4184 'togglecontact' => array(
4185 'buttontype' => 'togglecontact',
4186 'title' => get_string($contacttitle, 'message'),
4187 'url' => new moodle_url('/message/index.php', array(
4188 'user1' => $USER->id,
4189 'user2' => $user->id,
4190 $contacturlaction => $user->id,
4191 'sesskey' => sesskey())
4193 'image' => $contactimage,
4194 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4195 'page' => $this->page
4199 $this->page->requires->string_for_js('changesmadereallygoaway', 'moodle');
4201 } else {
4202 $heading = null;
4206 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4207 return $this->render_context_header($contextheader);
4211 * Renders the skip links for the page.
4213 * @param array $links List of skip links.
4214 * @return string HTML for the skip links.
4216 public function render_skip_links($links) {
4217 $context = [ 'links' => []];
4219 foreach ($links as $url => $text) {
4220 $context['links'][] = [ 'url' => $url, 'text' => $text];
4223 return $this->render_from_template('core/skip_links', $context);
4227 * Renders the header bar.
4229 * @param context_header $contextheader Header bar object.
4230 * @return string HTML for the header bar.
4232 protected function render_context_header(context_header $contextheader) {
4234 // All the html stuff goes here.
4235 $html = html_writer::start_div('page-context-header');
4237 // Image data.
4238 if (isset($contextheader->imagedata)) {
4239 // Header specific image.
4240 $html .= html_writer::div($contextheader->imagedata, 'page-header-image');
4243 // Headings.
4244 if (!isset($contextheader->heading)) {
4245 $headings = $this->heading($this->page->heading, $contextheader->headinglevel);
4246 } else {
4247 $headings = $this->heading($contextheader->heading, $contextheader->headinglevel);
4250 $html .= html_writer::tag('div', $headings, array('class' => 'page-header-headings'));
4252 // Buttons.
4253 if (isset($contextheader->additionalbuttons)) {
4254 $html .= html_writer::start_div('btn-group header-button-group');
4255 foreach ($contextheader->additionalbuttons as $button) {
4256 if (!isset($button->page)) {
4257 // Include js for messaging.
4258 if ($button['buttontype'] === 'togglecontact') {
4259 \core_message\helper::togglecontact_requirejs();
4261 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4262 'class' => 'iconsmall',
4263 'role' => 'presentation'
4265 $image .= html_writer::span($button['title'], 'header-button-title');
4266 } else {
4267 $image = html_writer::empty_tag('img', array(
4268 'src' => $button['formattedimage'],
4269 'role' => 'presentation'
4272 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4274 $html .= html_writer::end_div();
4276 $html .= html_writer::end_div();
4278 return $html;
4282 * Wrapper for header elements.
4284 * @return string HTML to display the main header.
4286 public function full_header() {
4287 $html = html_writer::start_tag('header', array('id' => 'page-header', 'class' => 'clearfix'));
4288 $html .= $this->context_header();
4289 $html .= html_writer::start_div('clearfix', array('id' => 'page-navbar'));
4290 $html .= html_writer::tag('div', $this->navbar(), array('class' => 'breadcrumb-nav'));
4291 $html .= html_writer::div($this->page_heading_button(), 'breadcrumb-button');
4292 $html .= html_writer::end_div();
4293 $html .= html_writer::tag('div', $this->course_header(), array('id' => 'course-header'));
4294 $html .= html_writer::end_tag('header');
4295 return $html;
4299 * Displays the list of tags associated with an entry
4301 * @param array $tags list of instances of core_tag or stdClass
4302 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4303 * to use default, set to '' (empty string) to omit the label completely
4304 * @param string $classes additional classes for the enclosing div element
4305 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4306 * will be appended to the end, JS will toggle the rest of the tags
4307 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4308 * @return string
4310 public function tag_list($tags, $label = null, $classes = '', $limit = 10, $pagecontext = null) {
4311 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext);
4312 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4316 * Renders element for inline editing of any value
4318 * @param \core\output\inplace_editable $element
4319 * @return string
4321 public function render_inplace_editable(\core\output\inplace_editable $element) {
4322 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4326 * Renders a bar chart.
4328 * @param \core\chart_bar $chart The chart.
4329 * @return string.
4331 public function render_chart_bar(\core\chart_bar $chart) {
4332 return $this->render_chart($chart);
4336 * Renders a line chart.
4338 * @param \core\chart_line $chart The chart.
4339 * @return string.
4341 public function render_chart_line(\core\chart_line $chart) {
4342 return $this->render_chart($chart);
4346 * Renders a pie chart.
4348 * @param \core\chart_pie $chart The chart.
4349 * @return string.
4351 public function render_chart_pie(\core\chart_pie $chart) {
4352 return $this->render_chart($chart);
4356 * Renders a chart.
4358 * @param \core\chart_base $chart The chart.
4359 * @param bool $withtable Whether to include a data table with the chart.
4360 * @return string.
4362 public function render_chart(\core\chart_base $chart, $withtable = true) {
4363 $chartdata = json_encode($chart);
4364 return $this->render_from_template('core/chart', (object) [
4365 'chartdata' => $chartdata,
4366 'withtable' => $withtable
4371 * Renders the login form.
4373 * @param \core_auth\output\login $form The renderable.
4374 * @return string
4376 public function render_login(\core_auth\output\login $form) {
4377 $context = $form->export_for_template($this);
4379 // Override because rendering is not supported in template yet.
4380 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
4381 $context->errorformatted = $this->error_text($context->error);
4383 return $this->render_from_template('core/loginform', $context);
4387 * Renders an mform element from a template.
4389 * @param HTML_QuickForm_element $element element
4390 * @param bool $required if input is required field
4391 * @param bool $advanced if input is an advanced field
4392 * @param string $error error message to display
4393 * @param bool $ingroup True if this element is rendered as part of a group
4394 * @return mixed string|bool
4396 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4397 $templatename = 'core_form/element-' . $element->getType();
4398 if ($ingroup) {
4399 $templatename .= "-inline";
4401 try {
4402 // We call this to generate a file not found exception if there is no template.
4403 // We don't want to call export_for_template if there is no template.
4404 core\output\mustache_template_finder::get_template_filepath($templatename);
4406 if ($element instanceof templatable) {
4407 $elementcontext = $element->export_for_template($this);
4409 $helpbutton = '';
4410 if (method_exists($element, 'getHelpButton')) {
4411 $helpbutton = $element->getHelpButton();
4413 $label = $element->getLabel();
4414 $text = '';
4415 if (method_exists($element, 'getText')) {
4416 // There currently exists code that adds a form element with an empty label.
4417 // If this is the case then set the label to the description.
4418 if (empty($label)) {
4419 $label = $element->getText();
4420 } else {
4421 $text = $element->getText();
4425 $context = array(
4426 'element' => $elementcontext,
4427 'label' => $label,
4428 'text' => $text,
4429 'required' => $required,
4430 'advanced' => $advanced,
4431 'helpbutton' => $helpbutton,
4432 'error' => $error
4434 return $this->render_from_template($templatename, $context);
4436 } catch (Exception $e) {
4437 // No template for this element.
4438 return false;
4443 * Render the login signup form into a nice template for the theme.
4445 * @param mform $form
4446 * @return string
4448 public function render_login_signup_form($form) {
4449 $context = $form->export_for_template($this);
4451 return $this->render_from_template('core/signup_form_layout', $context);
4455 * Renders a progress bar.
4457 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4459 * @param progress_bar $bar The bar.
4460 * @return string HTML fragment
4462 public function render_progress_bar(progress_bar $bar) {
4463 global $PAGE;
4464 $data = $bar->export_for_template($this);
4465 return $this->render_from_template('core/progress_bar', $data);
4470 * A renderer that generates output for command-line scripts.
4472 * The implementation of this renderer is probably incomplete.
4474 * @copyright 2009 Tim Hunt
4475 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4476 * @since Moodle 2.0
4477 * @package core
4478 * @category output
4480 class core_renderer_cli extends core_renderer {
4483 * Returns the page header.
4485 * @return string HTML fragment
4487 public function header() {
4488 return $this->page->heading . "\n";
4492 * Returns a template fragment representing a Heading.
4494 * @param string $text The text of the heading
4495 * @param int $level The level of importance of the heading
4496 * @param string $classes A space-separated list of CSS classes
4497 * @param string $id An optional ID
4498 * @return string A template fragment for a heading
4500 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4501 $text .= "\n";
4502 switch ($level) {
4503 case 1:
4504 return '=>' . $text;
4505 case 2:
4506 return '-->' . $text;
4507 default:
4508 return $text;
4513 * Returns a template fragment representing a fatal error.
4515 * @param string $message The message to output
4516 * @param string $moreinfourl URL where more info can be found about the error
4517 * @param string $link Link for the Continue button
4518 * @param array $backtrace The execution backtrace
4519 * @param string $debuginfo Debugging information
4520 * @return string A template fragment for a fatal error
4522 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4523 global $CFG;
4525 $output = "!!! $message !!!\n";
4527 if ($CFG->debugdeveloper) {
4528 if (!empty($debuginfo)) {
4529 $output .= $this->notification($debuginfo, 'notifytiny');
4531 if (!empty($backtrace)) {
4532 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
4536 return $output;
4540 * Returns a template fragment representing a notification.
4542 * @param string $message The message to print out.
4543 * @param string $type The type of notification. See constants on \core\output\notification.
4544 * @return string A template fragment for a notification
4546 public function notification($message, $type = null) {
4547 $message = clean_text($message);
4548 if ($type === 'notifysuccess' || $type === 'success') {
4549 return "++ $message ++\n";
4551 return "!! $message !!\n";
4555 * There is no footer for a cli request, however we must override the
4556 * footer method to prevent the default footer.
4558 public function footer() {}
4561 * Render a notification (that is, a status message about something that has
4562 * just happened).
4564 * @param \core\output\notification $notification the notification to print out
4565 * @return string plain text output
4567 public function render_notification(\core\output\notification $notification) {
4568 return $this->notification($notification->get_message(), $notification->get_message_type());
4574 * A renderer that generates output for ajax scripts.
4576 * This renderer prevents accidental sends back only json
4577 * encoded error messages, all other output is ignored.
4579 * @copyright 2010 Petr Skoda
4580 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4581 * @since Moodle 2.0
4582 * @package core
4583 * @category output
4585 class core_renderer_ajax extends core_renderer {
4588 * Returns a template fragment representing a fatal error.
4590 * @param string $message The message to output
4591 * @param string $moreinfourl URL where more info can be found about the error
4592 * @param string $link Link for the Continue button
4593 * @param array $backtrace The execution backtrace
4594 * @param string $debuginfo Debugging information
4595 * @return string A template fragment for a fatal error
4597 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4598 global $CFG;
4600 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
4602 $e = new stdClass();
4603 $e->error = $message;
4604 $e->errorcode = $errorcode;
4605 $e->stacktrace = NULL;
4606 $e->debuginfo = NULL;
4607 $e->reproductionlink = NULL;
4608 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
4609 $link = (string) $link;
4610 if ($link) {
4611 $e->reproductionlink = $link;
4613 if (!empty($debuginfo)) {
4614 $e->debuginfo = $debuginfo;
4616 if (!empty($backtrace)) {
4617 $e->stacktrace = format_backtrace($backtrace, true);
4620 $this->header();
4621 return json_encode($e);
4625 * Used to display a notification.
4626 * For the AJAX notifications are discarded.
4628 * @param string $message The message to print out.
4629 * @param string $type The type of notification. See constants on \core\output\notification.
4631 public function notification($message, $type = null) {}
4634 * Used to display a redirection message.
4635 * AJAX redirections should not occur and as such redirection messages
4636 * are discarded.
4638 * @param moodle_url|string $encodedurl
4639 * @param string $message
4640 * @param int $delay
4641 * @param bool $debugdisableredirect
4642 * @param string $messagetype The type of notification to show the message in.
4643 * See constants on \core\output\notification.
4645 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
4646 $messagetype = \core\output\notification::NOTIFY_INFO) {}
4649 * Prepares the start of an AJAX output.
4651 public function header() {
4652 // unfortunately YUI iframe upload does not support application/json
4653 if (!empty($_FILES)) {
4654 @header('Content-type: text/plain; charset=utf-8');
4655 if (!core_useragent::supports_json_contenttype()) {
4656 @header('X-Content-Type-Options: nosniff');
4658 } else if (!core_useragent::supports_json_contenttype()) {
4659 @header('Content-type: text/plain; charset=utf-8');
4660 @header('X-Content-Type-Options: nosniff');
4661 } else {
4662 @header('Content-type: application/json; charset=utf-8');
4665 // Headers to make it not cacheable and json
4666 @header('Cache-Control: no-store, no-cache, must-revalidate');
4667 @header('Cache-Control: post-check=0, pre-check=0', false);
4668 @header('Pragma: no-cache');
4669 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
4670 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
4671 @header('Accept-Ranges: none');
4675 * There is no footer for an AJAX request, however we must override the
4676 * footer method to prevent the default footer.
4678 public function footer() {}
4681 * No need for headers in an AJAX request... this should never happen.
4682 * @param string $text
4683 * @param int $level
4684 * @param string $classes
4685 * @param string $id
4687 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
4692 * Renderer for media files.
4694 * Used in file resources, media filter, and any other places that need to
4695 * output embedded media.
4697 * @deprecated since Moodle 3.2
4698 * @copyright 2011 The Open University
4699 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4701 class core_media_renderer extends plugin_renderer_base {
4702 /** @var array Array of available 'player' objects */
4703 private $players;
4704 /** @var string Regex pattern for links which may contain embeddable content */
4705 private $embeddablemarkers;
4708 * Constructor
4710 * This is needed in the constructor (not later) so that you can use the
4711 * constants and static functions that are defined in core_media class
4712 * before you call renderer functions.
4714 public function __construct() {
4715 debugging('Class core_media_renderer is deprecated, please use core_media_manager::instance()', DEBUG_DEVELOPER);
4719 * Renders a media file (audio or video) using suitable embedded player.
4721 * See embed_alternatives function for full description of parameters.
4722 * This function calls through to that one.
4724 * When using this function you can also specify width and height in the
4725 * URL by including ?d=100x100 at the end. If specified in the URL, this
4726 * will override the $width and $height parameters.
4728 * @param moodle_url $url Full URL of media file
4729 * @param string $name Optional user-readable name to display in download link
4730 * @param int $width Width in pixels (optional)
4731 * @param int $height Height in pixels (optional)
4732 * @param array $options Array of key/value pairs
4733 * @return string HTML content of embed
4735 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
4736 $options = array()) {
4737 return core_media_manager::instance()->embed_url($url, $name, $width, $height, $options);
4741 * Renders media files (audio or video) using suitable embedded player.
4742 * The list of URLs should be alternative versions of the same content in
4743 * multiple formats. If there is only one format it should have a single
4744 * entry.
4746 * If the media files are not in a supported format, this will give students
4747 * a download link to each format. The download link uses the filename
4748 * unless you supply the optional name parameter.
4750 * Width and height are optional. If specified, these are suggested sizes
4751 * and should be the exact values supplied by the user, if they come from
4752 * user input. These will be treated as relating to the size of the video
4753 * content, not including any player control bar.
4755 * For audio files, height will be ignored. For video files, a few formats
4756 * work if you specify only width, but in general if you specify width
4757 * you must specify height as well.
4759 * The $options array is passed through to the core_media_player classes
4760 * that render the object tag. The keys can contain values from
4761 * core_media::OPTION_xx.
4763 * @param array $alternatives Array of moodle_url to media files
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_alternatives($alternatives, $name = '', $width = 0, $height = 0,
4771 $options = array()) {
4772 return core_media_manager::instance()->embed_alternatives($alternatives, $name, $width, $height, $options);
4776 * Checks whether a file can be embedded. If this returns true you will get
4777 * an embedded player; if this returns false, you will just get a download
4778 * link.
4780 * This is a wrapper for can_embed_urls.
4782 * @param moodle_url $url URL of media file
4783 * @param array $options Options (same as when embedding)
4784 * @return bool True if file can be embedded
4786 public function can_embed_url(moodle_url $url, $options = array()) {
4787 return core_media_manager::instance()->can_embed_url($url, $options);
4791 * Checks whether a file can be embedded. If this returns true you will get
4792 * an embedded player; if this returns false, you will just get a download
4793 * link.
4795 * @param array $urls URL of media file and any alternatives (moodle_url)
4796 * @param array $options Options (same as when embedding)
4797 * @return bool True if file can be embedded
4799 public function can_embed_urls(array $urls, $options = array()) {
4800 return core_media_manager::instance()->can_embed_urls($urls, $options);
4804 * Obtains a list of markers that can be used in a regular expression when
4805 * searching for URLs that can be embedded by any player type.
4807 * This string is used to improve peformance of regex matching by ensuring
4808 * that the (presumably C) regex code can do a quick keyword check on the
4809 * URL part of a link to see if it matches one of these, rather than having
4810 * to go into PHP code for every single link to see if it can be embedded.
4812 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
4814 public function get_embeddable_markers() {
4815 return core_media_manager::instance()->get_embeddable_markers();
4820 * The maintenance renderer.
4822 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
4823 * is running a maintenance related task.
4824 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
4826 * @since Moodle 2.6
4827 * @package core
4828 * @category output
4829 * @copyright 2013 Sam Hemelryk
4830 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4832 class core_renderer_maintenance extends core_renderer {
4835 * Initialises the renderer instance.
4836 * @param moodle_page $page
4837 * @param string $target
4838 * @throws coding_exception
4840 public function __construct(moodle_page $page, $target) {
4841 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
4842 throw new coding_exception('Invalid request for the maintenance renderer.');
4844 parent::__construct($page, $target);
4848 * Does nothing. The maintenance renderer cannot produce blocks.
4850 * @param block_contents $bc
4851 * @param string $region
4852 * @return string
4854 public function block(block_contents $bc, $region) {
4855 // Computer says no blocks.
4856 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4857 return '';
4861 * Does nothing. The maintenance renderer cannot produce blocks.
4863 * @param string $region
4864 * @param array $classes
4865 * @param string $tag
4866 * @return string
4868 public function blocks($region, $classes = array(), $tag = 'aside') {
4869 // Computer says no blocks.
4870 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4871 return '';
4875 * Does nothing. The maintenance renderer cannot produce blocks.
4877 * @param string $region
4878 * @return string
4880 public function blocks_for_region($region) {
4881 // Computer says no blocks for region.
4882 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4883 return '';
4887 * Does nothing. The maintenance renderer cannot produce a course content header.
4889 * @param bool $onlyifnotcalledbefore
4890 * @return string
4892 public function course_content_header($onlyifnotcalledbefore = false) {
4893 // Computer says no course content header.
4894 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4895 return '';
4899 * Does nothing. The maintenance renderer cannot produce a course content footer.
4901 * @param bool $onlyifnotcalledbefore
4902 * @return string
4904 public function course_content_footer($onlyifnotcalledbefore = false) {
4905 // Computer says no course content footer.
4906 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4907 return '';
4911 * Does nothing. The maintenance renderer cannot produce a course header.
4913 * @return string
4915 public function course_header() {
4916 // Computer says no course header.
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 footer.
4924 * @return string
4926 public function course_footer() {
4927 // Computer says no course footer.
4928 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4929 return '';
4933 * Does nothing. The maintenance renderer cannot produce a custom menu.
4935 * @param string $custommenuitems
4936 * @return string
4938 public function custom_menu($custommenuitems = '') {
4939 // Computer says no custom menu.
4940 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4941 return '';
4945 * Does nothing. The maintenance renderer cannot produce a file picker.
4947 * @param array $options
4948 * @return string
4950 public function file_picker($options) {
4951 // Computer says no file picker.
4952 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4953 return '';
4957 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
4959 * @param array $dir
4960 * @return string
4962 public function htmllize_file_tree($dir) {
4963 // Hell no we don't want no htmllized file tree.
4964 // Also why on earth is this function on the core renderer???
4965 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4966 return '';
4971 * Overridden confirm message for upgrades.
4973 * @param string $message The question to ask the user
4974 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
4975 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
4976 * @return string HTML fragment
4978 public function confirm($message, $continue, $cancel) {
4979 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
4980 // from any previous version of Moodle).
4981 if ($continue instanceof single_button) {
4982 $continue->primary = true;
4983 } else if (is_string($continue)) {
4984 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
4985 } else if ($continue instanceof moodle_url) {
4986 $continue = new single_button($continue, get_string('continue'), 'post', true);
4987 } else {
4988 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
4989 ' (string/moodle_url) or a single_button instance.');
4992 if ($cancel instanceof single_button) {
4993 $output = '';
4994 } else if (is_string($cancel)) {
4995 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
4996 } else if ($cancel instanceof moodle_url) {
4997 $cancel = new single_button($cancel, get_string('cancel'), 'get');
4998 } else {
4999 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5000 ' (string/moodle_url) or a single_button instance.');
5003 $output = $this->box_start('generalbox', 'notice');
5004 $output .= html_writer::tag('h4', get_string('confirm'));
5005 $output .= html_writer::tag('p', $message);
5006 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
5007 $output .= $this->box_end();
5008 return $output;
5012 * Does nothing. The maintenance renderer does not support JS.
5014 * @param block_contents $bc
5016 public function init_block_hider_js(block_contents $bc) {
5017 // Computer says no JavaScript.
5018 // Do nothing, ridiculous method.
5022 * Does nothing. The maintenance renderer cannot produce language menus.
5024 * @return string
5026 public function lang_menu() {
5027 // Computer says no lang menu.
5028 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5029 return '';
5033 * Does nothing. The maintenance renderer has no need for login information.
5035 * @param null $withlinks
5036 * @return string
5038 public function login_info($withlinks = null) {
5039 // Computer says no login info.
5040 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5041 return '';
5045 * Does nothing. The maintenance renderer cannot produce user pictures.
5047 * @param stdClass $user
5048 * @param array $options
5049 * @return string
5051 public function user_picture(stdClass $user, array $options = null) {
5052 // Computer says no user pictures.
5053 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
5054 return '';