Merge branch 'MDL-61058-33' of git://github.com/junpataleta/moodle into MOODLE_33_STABLE
[moodle.git] / lib / outputrenderers.php
blob8a6d3cfc81cbcb2d4d61a3c4a01e616439c5b313
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 if (!empty($CFG->additionalhtmlhead)) {
654 $output .= "\n".$CFG->additionalhtmlhead;
657 return $output;
661 * The standard tags (typically skip links) that should be output just inside
662 * the start of the <body> tag. Designed to be called in theme layout.php files.
664 * @return string HTML fragment.
666 public function standard_top_of_body_html() {
667 global $CFG;
668 $output = $this->page->requires->get_top_of_body_code($this);
669 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
670 $output .= "\n".$CFG->additionalhtmltopofbody;
673 // Give plugins an opportunity to inject extra html content. The callback
674 // must always return a string containing valid html.
675 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
676 foreach ($pluginswithfunction as $plugins) {
677 foreach ($plugins as $function) {
678 $output .= $function();
682 $output .= $this->maintenance_warning();
684 return $output;
688 * Scheduled maintenance warning message.
690 * Note: This is a nasty hack to display maintenance notice, this should be moved
691 * to some general notification area once we have it.
693 * @return string
695 public function maintenance_warning() {
696 global $CFG;
698 $output = '';
699 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
700 $timeleft = $CFG->maintenance_later - time();
701 // If timeleft less than 30 sec, set the class on block to error to highlight.
702 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
703 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-a-1 alert');
704 $a = new stdClass();
705 $a->hour = (int)($timeleft / 3600);
706 $a->min = (int)(($timeleft / 60) % 60);
707 $a->sec = (int)($timeleft % 60);
708 if ($a->hour > 0) {
709 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
710 } else {
711 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
714 $output .= $this->box_end();
715 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
716 array(array('timeleftinsec' => $timeleft)));
717 $this->page->requires->strings_for_js(
718 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
719 'admin');
721 return $output;
725 * The standard tags (typically performance information and validation links,
726 * if we are in developer debug mode) that should be output in the footer area
727 * of the page. Designed to be called in theme layout.php files.
729 * @return string HTML fragment.
731 public function standard_footer_html() {
732 global $CFG, $SCRIPT;
734 if (during_initial_install()) {
735 // Debugging info can not work before install is finished,
736 // in any case we do not want any links during installation!
737 return '';
740 // This function is normally called from a layout.php file in {@link core_renderer::header()}
741 // but some of the content won't be known until later, so we return a placeholder
742 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
743 $output = $this->unique_performance_info_token;
744 if ($this->page->devicetypeinuse == 'legacy') {
745 // The legacy theme is in use print the notification
746 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
749 // Get links to switch device types (only shown for users not on a default device)
750 $output .= $this->theme_switch_links();
752 if (!empty($CFG->debugpageinfo)) {
753 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
755 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
756 // Add link to profiling report if necessary
757 if (function_exists('profiling_is_running') && profiling_is_running()) {
758 $txt = get_string('profiledscript', 'admin');
759 $title = get_string('profiledscriptview', 'admin');
760 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
761 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
762 $output .= '<div class="profilingfooter">' . $link . '</div>';
764 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
765 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
766 $output .= '<div class="purgecaches">' .
767 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
769 if (!empty($CFG->debugvalidators)) {
770 // 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
771 $output .= '<div class="validators"><ul class="list-unstyled m-l-1">
772 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
773 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
774 <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>
775 </ul></div>';
777 return $output;
781 * Returns standard main content placeholder.
782 * Designed to be called in theme layout.php files.
784 * @return string HTML fragment.
786 public function main_content() {
787 // This is here because it is the only place we can inject the "main" role over the entire main content area
788 // without requiring all theme's to manually do it, and without creating yet another thing people need to
789 // remember in the theme.
790 // This is an unfortunate hack. DO NO EVER add anything more here.
791 // DO NOT add classes.
792 // DO NOT add an id.
793 return '<div role="main">'.$this->unique_main_content_token.'</div>';
797 * The standard tags (typically script tags that are not needed earlier) that
798 * should be output after everything else. Designed to be called in theme layout.php files.
800 * @return string HTML fragment.
802 public function standard_end_of_body_html() {
803 global $CFG;
805 // This function is normally called from a layout.php file in {@link core_renderer::header()}
806 // but some of the content won't be known until later, so we return a placeholder
807 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
808 $output = '';
809 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
810 $output .= "\n".$CFG->additionalhtmlfooter;
812 $output .= $this->unique_end_html_token;
813 return $output;
817 * Return the standard string that says whether you are logged in (and switched
818 * roles/logged in as another user).
819 * @param bool $withlinks if false, then don't include any links in the HTML produced.
820 * If not set, the default is the nologinlinks option from the theme config.php file,
821 * and if that is not set, then links are included.
822 * @return string HTML fragment.
824 public function login_info($withlinks = null) {
825 global $USER, $CFG, $DB, $SESSION;
827 if (during_initial_install()) {
828 return '';
831 if (is_null($withlinks)) {
832 $withlinks = empty($this->page->layout_options['nologinlinks']);
835 $course = $this->page->course;
836 if (\core\session\manager::is_loggedinas()) {
837 $realuser = \core\session\manager::get_realuser();
838 $fullname = fullname($realuser, true);
839 if ($withlinks) {
840 $loginastitle = get_string('loginas');
841 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
842 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
843 } else {
844 $realuserinfo = " [$fullname] ";
846 } else {
847 $realuserinfo = '';
850 $loginpage = $this->is_login_page();
851 $loginurl = get_login_url();
853 if (empty($course->id)) {
854 // $course->id is not defined during installation
855 return '';
856 } else if (isloggedin()) {
857 $context = context_course::instance($course->id);
859 $fullname = fullname($USER, true);
860 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
861 if ($withlinks) {
862 $linktitle = get_string('viewprofile');
863 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
864 } else {
865 $username = $fullname;
867 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
868 if ($withlinks) {
869 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
870 } else {
871 $username .= " from {$idprovider->name}";
874 if (isguestuser()) {
875 $loggedinas = $realuserinfo.get_string('loggedinasguest');
876 if (!$loginpage && $withlinks) {
877 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
879 } else if (is_role_switched($course->id)) { // Has switched roles
880 $rolename = '';
881 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
882 $rolename = ': '.role_get_name($role, $context);
884 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
885 if ($withlinks) {
886 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
887 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
889 } else {
890 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
891 if ($withlinks) {
892 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
895 } else {
896 $loggedinas = get_string('loggedinnot', 'moodle');
897 if (!$loginpage && $withlinks) {
898 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
902 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
904 if (isset($SESSION->justloggedin)) {
905 unset($SESSION->justloggedin);
906 if (!empty($CFG->displayloginfailures)) {
907 if (!isguestuser()) {
908 // Include this file only when required.
909 require_once($CFG->dirroot . '/user/lib.php');
910 if ($count = user_count_login_failures($USER)) {
911 $loggedinas .= '<div class="loginfailures">';
912 $a = new stdClass();
913 $a->attempts = $count;
914 $loggedinas .= get_string('failedloginattempts', '', $a);
915 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
916 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
917 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
919 $loggedinas .= '</div>';
925 return $loggedinas;
929 * Check whether the current page is a login page.
931 * @since Moodle 2.9
932 * @return bool
934 protected function is_login_page() {
935 // This is a real bit of a hack, but its a rarety that we need to do something like this.
936 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
937 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
938 return in_array(
939 $this->page->url->out_as_local_url(false, array()),
940 array(
941 '/login/index.php',
942 '/login/forgot_password.php',
948 * Return the 'back' link that normally appears in the footer.
950 * @return string HTML fragment.
952 public function home_link() {
953 global $CFG, $SITE;
955 if ($this->page->pagetype == 'site-index') {
956 // Special case for site home page - please do not remove
957 return '<div class="sitelink">' .
958 '<a title="Moodle" href="http://moodle.org/">' .
959 '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
961 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
962 // Special case for during install/upgrade.
963 return '<div class="sitelink">'.
964 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
965 '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
967 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
968 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
969 get_string('home') . '</a></div>';
971 } else {
972 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
973 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
978 * Redirects the user by any means possible given the current state
980 * This function should not be called directly, it should always be called using
981 * the redirect function in lib/weblib.php
983 * The redirect function should really only be called before page output has started
984 * however it will allow itself to be called during the state STATE_IN_BODY
986 * @param string $encodedurl The URL to send to encoded if required
987 * @param string $message The message to display to the user if any
988 * @param int $delay The delay before redirecting a user, if $message has been
989 * set this is a requirement and defaults to 3, set to 0 no delay
990 * @param boolean $debugdisableredirect this redirect has been disabled for
991 * debugging purposes. Display a message that explains, and don't
992 * trigger the redirect.
993 * @param string $messagetype The type of notification to show the message in.
994 * See constants on \core\output\notification.
995 * @return string The HTML to display to the user before dying, may contain
996 * meta refresh, javascript refresh, and may have set header redirects
998 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
999 $messagetype = \core\output\notification::NOTIFY_INFO) {
1000 global $CFG;
1001 $url = str_replace('&amp;', '&', $encodedurl);
1003 switch ($this->page->state) {
1004 case moodle_page::STATE_BEFORE_HEADER :
1005 // No output yet it is safe to delivery the full arsenal of redirect methods
1006 if (!$debugdisableredirect) {
1007 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1008 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1009 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1011 $output = $this->header();
1012 break;
1013 case moodle_page::STATE_PRINTING_HEADER :
1014 // We should hopefully never get here
1015 throw new coding_exception('You cannot redirect while printing the page header');
1016 break;
1017 case moodle_page::STATE_IN_BODY :
1018 // We really shouldn't be here but we can deal with this
1019 debugging("You should really redirect before you start page output");
1020 if (!$debugdisableredirect) {
1021 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1023 $output = $this->opencontainers->pop_all_but_last();
1024 break;
1025 case moodle_page::STATE_DONE :
1026 // Too late to be calling redirect now
1027 throw new coding_exception('You cannot redirect after the entire page has been generated');
1028 break;
1030 $output .= $this->notification($message, $messagetype);
1031 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1032 if ($debugdisableredirect) {
1033 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1035 $output .= $this->footer();
1036 return $output;
1040 * Start output by sending the HTTP headers, and printing the HTML <head>
1041 * and the start of the <body>.
1043 * To control what is printed, you should set properties on $PAGE. If you
1044 * are familiar with the old {@link print_header()} function from Moodle 1.9
1045 * you will find that there are properties on $PAGE that correspond to most
1046 * of the old parameters to could be passed to print_header.
1048 * Not that, in due course, the remaining $navigation, $menu parameters here
1049 * will be replaced by more properties of $PAGE, but that is still to do.
1051 * @return string HTML that you must output this, preferably immediately.
1053 public function header() {
1054 global $USER, $CFG, $SESSION;
1056 // Give plugins an opportunity touch things before the http headers are sent
1057 // such as adding additional headers. The return value is ignored.
1058 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1059 foreach ($pluginswithfunction as $plugins) {
1060 foreach ($plugins as $function) {
1061 $function();
1065 if (\core\session\manager::is_loggedinas()) {
1066 $this->page->add_body_class('userloggedinas');
1069 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1070 require_once($CFG->dirroot . '/user/lib.php');
1071 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1072 if ($count = user_count_login_failures($USER, false)) {
1073 $this->page->add_body_class('loginfailures');
1077 // If the user is logged in, and we're not in initial install,
1078 // check to see if the user is role-switched and add the appropriate
1079 // CSS class to the body element.
1080 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1081 $this->page->add_body_class('userswitchedrole');
1084 // Give themes a chance to init/alter the page object.
1085 $this->page->theme->init_page($this->page);
1087 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1089 // Find the appropriate page layout file, based on $this->page->pagelayout.
1090 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1091 // Render the layout using the layout file.
1092 $rendered = $this->render_page_layout($layoutfile);
1094 // Slice the rendered output into header and footer.
1095 $cutpos = strpos($rendered, $this->unique_main_content_token);
1096 if ($cutpos === false) {
1097 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1098 $token = self::MAIN_CONTENT_TOKEN;
1099 } else {
1100 $token = $this->unique_main_content_token;
1103 if ($cutpos === false) {
1104 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.');
1106 $header = substr($rendered, 0, $cutpos);
1107 $footer = substr($rendered, $cutpos + strlen($token));
1109 if (empty($this->contenttype)) {
1110 debugging('The page layout file did not call $OUTPUT->doctype()');
1111 $header = $this->doctype() . $header;
1114 // If this theme version is below 2.4 release and this is a course view page
1115 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1116 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1117 // check if course content header/footer have not been output during render of theme layout
1118 $coursecontentheader = $this->course_content_header(true);
1119 $coursecontentfooter = $this->course_content_footer(true);
1120 if (!empty($coursecontentheader)) {
1121 // display debug message and add header and footer right above and below main content
1122 // Please note that course header and footer (to be displayed above and below the whole page)
1123 // are not displayed in this case at all.
1124 // Besides the content header and footer are not displayed on any other course page
1125 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);
1126 $header .= $coursecontentheader;
1127 $footer = $coursecontentfooter. $footer;
1131 send_headers($this->contenttype, $this->page->cacheable);
1133 $this->opencontainers->push('header/footer', $footer);
1134 $this->page->set_state(moodle_page::STATE_IN_BODY);
1136 return $header . $this->skip_link_target('maincontent');
1140 * Renders and outputs the page layout file.
1142 * This is done by preparing the normal globals available to a script, and
1143 * then including the layout file provided by the current theme for the
1144 * requested layout.
1146 * @param string $layoutfile The name of the layout file
1147 * @return string HTML code
1149 protected function render_page_layout($layoutfile) {
1150 global $CFG, $SITE, $USER;
1151 // The next lines are a bit tricky. The point is, here we are in a method
1152 // of a renderer class, and this object may, or may not, be the same as
1153 // the global $OUTPUT object. When rendering the page layout file, we want to use
1154 // this object. However, people writing Moodle code expect the current
1155 // renderer to be called $OUTPUT, not $this, so define a variable called
1156 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1157 $OUTPUT = $this;
1158 $PAGE = $this->page;
1159 $COURSE = $this->page->course;
1161 ob_start();
1162 include($layoutfile);
1163 $rendered = ob_get_contents();
1164 ob_end_clean();
1165 return $rendered;
1169 * Outputs the page's footer
1171 * @return string HTML fragment
1173 public function footer() {
1174 global $CFG, $DB, $PAGE;
1176 // Give plugins an opportunity to touch the page before JS is finalized.
1177 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1178 foreach ($pluginswithfunction as $plugins) {
1179 foreach ($plugins as $function) {
1180 $function();
1184 $output = $this->container_end_all(true);
1186 $footer = $this->opencontainers->pop('header/footer');
1188 if (debugging() and $DB and $DB->is_transaction_started()) {
1189 // TODO: MDL-20625 print warning - transaction will be rolled back
1192 // Provide some performance info if required
1193 $performanceinfo = '';
1194 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1195 $perf = get_performance_info();
1196 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1197 $performanceinfo = $perf['html'];
1201 // We always want performance data when running a performance test, even if the user is redirected to another page.
1202 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1203 $footer = $this->unique_performance_info_token . $footer;
1205 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1207 // Only show notifications when we have a $PAGE context id.
1208 if (!empty($PAGE->context->id)) {
1209 $this->page->requires->js_call_amd('core/notification', 'init', array(
1210 $PAGE->context->id,
1211 \core\notification::fetch_as_array($this)
1214 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1216 $this->page->set_state(moodle_page::STATE_DONE);
1218 return $output . $footer;
1222 * Close all but the last open container. This is useful in places like error
1223 * handling, where you want to close all the open containers (apart from <body>)
1224 * before outputting the error message.
1226 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1227 * developer debug warning if it isn't.
1228 * @return string the HTML required to close any open containers inside <body>.
1230 public function container_end_all($shouldbenone = false) {
1231 return $this->opencontainers->pop_all_but_last($shouldbenone);
1235 * Returns course-specific information to be output immediately above content on any course page
1236 * (for the current course)
1238 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1239 * @return string
1241 public function course_content_header($onlyifnotcalledbefore = false) {
1242 global $CFG;
1243 static $functioncalled = false;
1244 if ($functioncalled && $onlyifnotcalledbefore) {
1245 // we have already output the content header
1246 return '';
1249 // Output any session notification.
1250 $notifications = \core\notification::fetch();
1252 $bodynotifications = '';
1253 foreach ($notifications as $notification) {
1254 $bodynotifications .= $this->render_from_template(
1255 $notification->get_template_name(),
1256 $notification->export_for_template($this)
1260 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1262 if ($this->page->course->id == SITEID) {
1263 // return immediately and do not include /course/lib.php if not necessary
1264 return $output;
1267 require_once($CFG->dirroot.'/course/lib.php');
1268 $functioncalled = true;
1269 $courseformat = course_get_format($this->page->course);
1270 if (($obj = $courseformat->course_content_header()) !== null) {
1271 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1273 return $output;
1277 * Returns course-specific information to be output immediately below content on any course page
1278 * (for the current course)
1280 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1281 * @return string
1283 public function course_content_footer($onlyifnotcalledbefore = false) {
1284 global $CFG;
1285 if ($this->page->course->id == SITEID) {
1286 // return immediately and do not include /course/lib.php if not necessary
1287 return '';
1289 static $functioncalled = false;
1290 if ($functioncalled && $onlyifnotcalledbefore) {
1291 // we have already output the content footer
1292 return '';
1294 $functioncalled = true;
1295 require_once($CFG->dirroot.'/course/lib.php');
1296 $courseformat = course_get_format($this->page->course);
1297 if (($obj = $courseformat->course_content_footer()) !== null) {
1298 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1300 return '';
1304 * Returns course-specific information to be output on any course page in the header area
1305 * (for the current course)
1307 * @return string
1309 public function course_header() {
1310 global $CFG;
1311 if ($this->page->course->id == SITEID) {
1312 // return immediately and do not include /course/lib.php if not necessary
1313 return '';
1315 require_once($CFG->dirroot.'/course/lib.php');
1316 $courseformat = course_get_format($this->page->course);
1317 if (($obj = $courseformat->course_header()) !== null) {
1318 return $courseformat->get_renderer($this->page)->render($obj);
1320 return '';
1324 * Returns course-specific information to be output on any course page in the footer area
1325 * (for the current course)
1327 * @return string
1329 public function course_footer() {
1330 global $CFG;
1331 if ($this->page->course->id == SITEID) {
1332 // return immediately and do not include /course/lib.php if not necessary
1333 return '';
1335 require_once($CFG->dirroot.'/course/lib.php');
1336 $courseformat = course_get_format($this->page->course);
1337 if (($obj = $courseformat->course_footer()) !== null) {
1338 return $courseformat->get_renderer($this->page)->render($obj);
1340 return '';
1344 * Returns lang menu or '', this method also checks forcing of languages in courses.
1346 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1348 * @return string The lang menu HTML or empty string
1350 public function lang_menu() {
1351 global $CFG;
1353 if (empty($CFG->langmenu)) {
1354 return '';
1357 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1358 // do not show lang menu if language forced
1359 return '';
1362 $currlang = current_language();
1363 $langs = get_string_manager()->get_list_of_translations();
1365 if (count($langs) < 2) {
1366 return '';
1369 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1370 $s->label = get_accesshide(get_string('language'));
1371 $s->class = 'langmenu';
1372 return $this->render($s);
1376 * Output the row of editing icons for a block, as defined by the controls array.
1378 * @param array $controls an array like {@link block_contents::$controls}.
1379 * @param string $blockid The ID given to the block.
1380 * @return string HTML fragment.
1382 public function block_controls($actions, $blockid = null) {
1383 global $CFG;
1384 if (empty($actions)) {
1385 return '';
1387 $menu = new action_menu($actions);
1388 if ($blockid !== null) {
1389 $menu->set_owner_selector('#'.$blockid);
1391 $menu->set_constraint('.block-region');
1392 $menu->attributes['class'] .= ' block-control-actions commands';
1393 return $this->render($menu);
1397 * Renders an action menu component.
1399 * ARIA references:
1400 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1401 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1403 * @param action_menu $menu
1404 * @return string HTML
1406 public function render_action_menu(action_menu $menu) {
1407 $context = $menu->export_for_template($this);
1408 return $this->render_from_template('core/action_menu', $context);
1412 * Renders an action_menu_link item.
1414 * @param action_menu_link $action
1415 * @return string HTML fragment
1417 protected function render_action_menu_link(action_menu_link $action) {
1418 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1422 * Renders a primary action_menu_filler item.
1424 * @param action_menu_link_filler $action
1425 * @return string HTML fragment
1427 protected function render_action_menu_filler(action_menu_filler $action) {
1428 return html_writer::span('&nbsp;', 'filler');
1432 * Renders a primary action_menu_link item.
1434 * @param action_menu_link_primary $action
1435 * @return string HTML fragment
1437 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1438 return $this->render_action_menu_link($action);
1442 * Renders a secondary action_menu_link item.
1444 * @param action_menu_link_secondary $action
1445 * @return string HTML fragment
1447 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1448 return $this->render_action_menu_link($action);
1452 * Prints a nice side block with an optional header.
1454 * The content is described
1455 * by a {@link core_renderer::block_contents} object.
1457 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1458 * <div class="header"></div>
1459 * <div class="content">
1460 * ...CONTENT...
1461 * <div class="footer">
1462 * </div>
1463 * </div>
1464 * <div class="annotation">
1465 * </div>
1466 * </div>
1468 * @param block_contents $bc HTML for the content
1469 * @param string $region the region the block is appearing in.
1470 * @return string the HTML to be output.
1472 public function block(block_contents $bc, $region) {
1473 $bc = clone($bc); // Avoid messing up the object passed in.
1474 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1475 $bc->collapsible = block_contents::NOT_HIDEABLE;
1477 if (!empty($bc->blockinstanceid)) {
1478 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1480 $skiptitle = strip_tags($bc->title);
1481 if ($bc->blockinstanceid && !empty($skiptitle)) {
1482 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1483 } else if (!empty($bc->arialabel)) {
1484 $bc->attributes['aria-label'] = $bc->arialabel;
1486 if ($bc->dockable) {
1487 $bc->attributes['data-dockable'] = 1;
1489 if ($bc->collapsible == block_contents::HIDDEN) {
1490 $bc->add_class('hidden');
1492 if (!empty($bc->controls)) {
1493 $bc->add_class('block_with_controls');
1497 if (empty($skiptitle)) {
1498 $output = '';
1499 $skipdest = '';
1500 } else {
1501 $output = html_writer::link('#sb-'.$bc->skipid, get_string('skipa', 'access', $skiptitle),
1502 array('class' => 'skip skip-block', 'id' => 'fsb-' . $bc->skipid));
1503 $skipdest = html_writer::span('', 'skip-block-to',
1504 array('id' => 'sb-' . $bc->skipid));
1507 $output .= html_writer::start_tag('div', $bc->attributes);
1509 $output .= $this->block_header($bc);
1510 $output .= $this->block_content($bc);
1512 $output .= html_writer::end_tag('div');
1514 $output .= $this->block_annotation($bc);
1516 $output .= $skipdest;
1518 $this->init_block_hider_js($bc);
1519 return $output;
1523 * Produces a header for a block
1525 * @param block_contents $bc
1526 * @return string
1528 protected function block_header(block_contents $bc) {
1530 $title = '';
1531 if ($bc->title) {
1532 $attributes = array();
1533 if ($bc->blockinstanceid) {
1534 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1536 $title = html_writer::tag('h2', $bc->title, $attributes);
1539 $blockid = null;
1540 if (isset($bc->attributes['id'])) {
1541 $blockid = $bc->attributes['id'];
1543 $controlshtml = $this->block_controls($bc->controls, $blockid);
1545 $output = '';
1546 if ($title || $controlshtml) {
1547 $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'));
1549 return $output;
1553 * Produces the content area for a block
1555 * @param block_contents $bc
1556 * @return string
1558 protected function block_content(block_contents $bc) {
1559 $output = html_writer::start_tag('div', array('class' => 'content'));
1560 if (!$bc->title && !$this->block_controls($bc->controls)) {
1561 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1563 $output .= $bc->content;
1564 $output .= $this->block_footer($bc);
1565 $output .= html_writer::end_tag('div');
1567 return $output;
1571 * Produces the footer for a block
1573 * @param block_contents $bc
1574 * @return string
1576 protected function block_footer(block_contents $bc) {
1577 $output = '';
1578 if ($bc->footer) {
1579 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1581 return $output;
1585 * Produces the annotation for a block
1587 * @param block_contents $bc
1588 * @return string
1590 protected function block_annotation(block_contents $bc) {
1591 $output = '';
1592 if ($bc->annotation) {
1593 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1595 return $output;
1599 * Calls the JS require function to hide a block.
1601 * @param block_contents $bc A block_contents object
1603 protected function init_block_hider_js(block_contents $bc) {
1604 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1605 $config = new stdClass;
1606 $config->id = $bc->attributes['id'];
1607 $config->title = strip_tags($bc->title);
1608 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1609 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1610 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1612 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1613 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1618 * Render the contents of a block_list.
1620 * @param array $icons the icon for each item.
1621 * @param array $items the content of each item.
1622 * @return string HTML
1624 public function list_block_contents($icons, $items) {
1625 $row = 0;
1626 $lis = array();
1627 foreach ($items as $key => $string) {
1628 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1629 if (!empty($icons[$key])) { //test if the content has an assigned icon
1630 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1632 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1633 $item .= html_writer::end_tag('li');
1634 $lis[] = $item;
1635 $row = 1 - $row; // Flip even/odd.
1637 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1641 * Output all the blocks in a particular region.
1643 * @param string $region the name of a region on this page.
1644 * @return string the HTML to be output.
1646 public function blocks_for_region($region) {
1647 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1648 $blocks = $this->page->blocks->get_blocks_for_region($region);
1649 $lastblock = null;
1650 $zones = array();
1651 foreach ($blocks as $block) {
1652 $zones[] = $block->title;
1654 $output = '';
1656 foreach ($blockcontents as $bc) {
1657 if ($bc instanceof block_contents) {
1658 $output .= $this->block($bc, $region);
1659 $lastblock = $bc->title;
1660 } else if ($bc instanceof block_move_target) {
1661 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1662 } else {
1663 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1666 return $output;
1670 * Output a place where the block that is currently being moved can be dropped.
1672 * @param block_move_target $target with the necessary details.
1673 * @param array $zones array of areas where the block can be moved to
1674 * @param string $previous the block located before the area currently being rendered.
1675 * @param string $region the name of the region
1676 * @return string the HTML to be output.
1678 public function block_move_target($target, $zones, $previous, $region) {
1679 if ($previous == null) {
1680 if (empty($zones)) {
1681 // There are no zones, probably because there are no blocks.
1682 $regions = $this->page->theme->get_all_block_regions();
1683 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1684 } else {
1685 $position = get_string('moveblockbefore', 'block', $zones[0]);
1687 } else {
1688 $position = get_string('moveblockafter', 'block', $previous);
1690 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1694 * Renders a special html link with attached action
1696 * Theme developers: DO NOT OVERRIDE! Please override function
1697 * {@link core_renderer::render_action_link()} instead.
1699 * @param string|moodle_url $url
1700 * @param string $text HTML fragment
1701 * @param component_action $action
1702 * @param array $attributes associative array of html link attributes + disabled
1703 * @param pix_icon optional pix icon to render with the link
1704 * @return string HTML fragment
1706 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1707 if (!($url instanceof moodle_url)) {
1708 $url = new moodle_url($url);
1710 $link = new action_link($url, $text, $action, $attributes, $icon);
1712 return $this->render($link);
1716 * Renders an action_link object.
1718 * The provided link is renderer and the HTML returned. At the same time the
1719 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1721 * @param action_link $link
1722 * @return string HTML fragment
1724 protected function render_action_link(action_link $link) {
1725 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1729 * Renders an action_icon.
1731 * This function uses the {@link core_renderer::action_link()} method for the
1732 * most part. What it does different is prepare the icon as HTML and use it
1733 * as the link text.
1735 * Theme developers: If you want to change how action links and/or icons are rendered,
1736 * consider overriding function {@link core_renderer::render_action_link()} and
1737 * {@link core_renderer::render_pix_icon()}.
1739 * @param string|moodle_url $url A string URL or moodel_url
1740 * @param pix_icon $pixicon
1741 * @param component_action $action
1742 * @param array $attributes associative array of html link attributes + disabled
1743 * @param bool $linktext show title next to image in link
1744 * @return string HTML fragment
1746 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1747 if (!($url instanceof moodle_url)) {
1748 $url = new moodle_url($url);
1750 $attributes = (array)$attributes;
1752 if (empty($attributes['class'])) {
1753 // let ppl override the class via $options
1754 $attributes['class'] = 'action-icon';
1757 $icon = $this->render($pixicon);
1759 if ($linktext) {
1760 $text = $pixicon->attributes['alt'];
1761 } else {
1762 $text = '';
1765 return $this->action_link($url, $text.$icon, $action, $attributes);
1769 * Print a message along with button choices for Continue/Cancel
1771 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1773 * @param string $message The question to ask the user
1774 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1775 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1776 * @return string HTML fragment
1778 public function confirm($message, $continue, $cancel) {
1779 if ($continue instanceof single_button) {
1780 // ok
1781 $continue->primary = true;
1782 } else if (is_string($continue)) {
1783 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1784 } else if ($continue instanceof moodle_url) {
1785 $continue = new single_button($continue, get_string('continue'), 'post', true);
1786 } else {
1787 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1790 if ($cancel instanceof single_button) {
1791 // ok
1792 } else if (is_string($cancel)) {
1793 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1794 } else if ($cancel instanceof moodle_url) {
1795 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1796 } else {
1797 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1800 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice');
1801 $output .= $this->box_start('modal-content', 'modal-content');
1802 $output .= $this->box_start('modal-header', 'modal-header');
1803 $output .= html_writer::tag('h4', get_string('confirm'));
1804 $output .= $this->box_end();
1805 $output .= $this->box_start('modal-body', 'modal-body');
1806 $output .= html_writer::tag('p', $message);
1807 $output .= $this->box_end();
1808 $output .= $this->box_start('modal-footer', 'modal-footer');
1809 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1810 $output .= $this->box_end();
1811 $output .= $this->box_end();
1812 $output .= $this->box_end();
1813 return $output;
1817 * Returns a form with a single button.
1819 * Theme developers: DO NOT OVERRIDE! Please override function
1820 * {@link core_renderer::render_single_button()} instead.
1822 * @param string|moodle_url $url
1823 * @param string $label button text
1824 * @param string $method get or post submit method
1825 * @param array $options associative array {disabled, title, etc.}
1826 * @return string HTML fragment
1828 public function single_button($url, $label, $method='post', array $options=null) {
1829 if (!($url instanceof moodle_url)) {
1830 $url = new moodle_url($url);
1832 $button = new single_button($url, $label, $method);
1834 foreach ((array)$options as $key=>$value) {
1835 if (array_key_exists($key, $button)) {
1836 $button->$key = $value;
1840 return $this->render($button);
1844 * Renders a single button widget.
1846 * This will return HTML to display a form containing a single button.
1848 * @param single_button $button
1849 * @return string HTML fragment
1851 protected function render_single_button(single_button $button) {
1852 $attributes = array('type' => 'submit',
1853 'value' => $button->label,
1854 'disabled' => $button->disabled ? 'disabled' : null,
1855 'title' => $button->tooltip);
1857 if ($button->actions) {
1858 $id = html_writer::random_id('single_button');
1859 $attributes['id'] = $id;
1860 foreach ($button->actions as $action) {
1861 $this->add_action_handler($action, $id);
1865 // first the input element
1866 $output = html_writer::empty_tag('input', $attributes);
1868 // then hidden fields
1869 $params = $button->url->params();
1870 if ($button->method === 'post') {
1871 $params['sesskey'] = sesskey();
1873 foreach ($params as $var => $val) {
1874 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1877 // then div wrapper for xhtml strictness
1878 $output = html_writer::tag('div', $output);
1880 // now the form itself around it
1881 if ($button->method === 'get') {
1882 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1883 } else {
1884 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1886 if ($url === '') {
1887 $url = '#'; // there has to be always some action
1889 $attributes = array('method' => $button->method,
1890 'action' => $url,
1891 'id' => $button->formid);
1892 $output = html_writer::tag('form', $output, $attributes);
1894 // and finally one more wrapper with class
1895 return html_writer::tag('div', $output, array('class' => $button->class));
1899 * Returns a form with a single select widget.
1901 * Theme developers: DO NOT OVERRIDE! Please override function
1902 * {@link core_renderer::render_single_select()} instead.
1904 * @param moodle_url $url form action target, includes hidden fields
1905 * @param string $name name of selection field - the changing parameter in url
1906 * @param array $options list of options
1907 * @param string $selected selected element
1908 * @param array $nothing
1909 * @param string $formid
1910 * @param array $attributes other attributes for the single select
1911 * @return string HTML fragment
1913 public function single_select($url, $name, array $options, $selected = '',
1914 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
1915 if (!($url instanceof moodle_url)) {
1916 $url = new moodle_url($url);
1918 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1920 if (array_key_exists('label', $attributes)) {
1921 $select->set_label($attributes['label']);
1922 unset($attributes['label']);
1924 $select->attributes = $attributes;
1926 return $this->render($select);
1930 * Returns a dataformat selection and download form
1932 * @param string $label A text label
1933 * @param moodle_url|string $base The download page url
1934 * @param string $name The query param which will hold the type of the download
1935 * @param array $params Extra params sent to the download page
1936 * @return string HTML fragment
1938 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
1940 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
1941 $options = array();
1942 foreach ($formats as $format) {
1943 if ($format->is_enabled()) {
1944 $options[] = array(
1945 'value' => $format->name,
1946 'label' => get_string('dataformat', $format->component),
1950 $hiddenparams = array();
1951 foreach ($params as $key => $value) {
1952 $hiddenparams[] = array(
1953 'name' => $key,
1954 'value' => $value,
1957 $data = array(
1958 'label' => $label,
1959 'base' => $base,
1960 'name' => $name,
1961 'params' => $hiddenparams,
1962 'options' => $options,
1963 'sesskey' => sesskey(),
1964 'submit' => get_string('download'),
1967 return $this->render_from_template('core/dataformat_selector', $data);
1972 * Internal implementation of single_select rendering
1974 * @param single_select $select
1975 * @return string HTML fragment
1977 protected function render_single_select(single_select $select) {
1978 return $this->render_from_template('core/single_select', $select->export_for_template($this));
1982 * Returns a form with a url select widget.
1984 * Theme developers: DO NOT OVERRIDE! Please override function
1985 * {@link core_renderer::render_url_select()} instead.
1987 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1988 * @param string $selected selected element
1989 * @param array $nothing
1990 * @param string $formid
1991 * @return string HTML fragment
1993 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1994 $select = new url_select($urls, $selected, $nothing, $formid);
1995 return $this->render($select);
1999 * Internal implementation of url_select rendering
2001 * @param url_select $select
2002 * @return string HTML fragment
2004 protected function render_url_select(url_select $select) {
2005 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2009 * Returns a string containing a link to the user documentation.
2010 * Also contains an icon by default. Shown to teachers and admin only.
2012 * @param string $path The page link after doc root and language, no leading slash.
2013 * @param string $text The text to be displayed for the link
2014 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2015 * @return string
2017 public function doc_link($path, $text = '', $forcepopup = false) {
2018 global $CFG;
2020 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2022 $url = new moodle_url(get_docs_url($path));
2024 $attributes = array('href'=>$url);
2025 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2026 $attributes['class'] = 'helplinkpopup';
2029 return html_writer::tag('a', $icon.$text, $attributes);
2033 * Return HTML for an image_icon.
2035 * Theme developers: DO NOT OVERRIDE! Please override function
2036 * {@link core_renderer::render_image_icon()} instead.
2038 * @param string $pix short pix name
2039 * @param string $alt mandatory alt attribute
2040 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2041 * @param array $attributes htm lattributes
2042 * @return string HTML fragment
2044 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2045 $icon = new image_icon($pix, $alt, $component, $attributes);
2046 return $this->render($icon);
2050 * Renders a pix_icon widget and returns the HTML to display it.
2052 * @param image_icon $icon
2053 * @return string HTML fragment
2055 protected function render_image_icon(image_icon $icon) {
2056 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2057 return $system->render_pix_icon($this, $icon);
2061 * Return HTML for a pix_icon.
2063 * Theme developers: DO NOT OVERRIDE! Please override function
2064 * {@link core_renderer::render_pix_icon()} instead.
2066 * @param string $pix short pix name
2067 * @param string $alt mandatory alt attribute
2068 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2069 * @param array $attributes htm lattributes
2070 * @return string HTML fragment
2072 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2073 $icon = new pix_icon($pix, $alt, $component, $attributes);
2074 return $this->render($icon);
2078 * Renders a pix_icon widget and returns the HTML to display it.
2080 * @param pix_icon $icon
2081 * @return string HTML fragment
2083 protected function render_pix_icon(pix_icon $icon) {
2084 $system = \core\output\icon_system::instance();
2085 return $system->render_pix_icon($this, $icon);
2089 * Return HTML to display an emoticon icon.
2091 * @param pix_emoticon $emoticon
2092 * @return string HTML fragment
2094 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2095 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2096 return $system->render_pix_icon($this, $emoticon);
2100 * Produces the html that represents this rating in the UI
2102 * @param rating $rating the page object on which this rating will appear
2103 * @return string
2105 function render_rating(rating $rating) {
2106 global $CFG, $USER;
2108 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2109 return null;//ratings are turned off
2112 $ratingmanager = new rating_manager();
2113 // Initialise the JavaScript so ratings can be done by AJAX.
2114 $ratingmanager->initialise_rating_javascript($this->page);
2116 $strrate = get_string("rate", "rating");
2117 $ratinghtml = ''; //the string we'll return
2119 // permissions check - can they view the aggregate?
2120 if ($rating->user_can_view_aggregate()) {
2122 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2123 $aggregatestr = $rating->get_aggregate_string();
2125 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2126 if ($rating->count > 0) {
2127 $countstr = "({$rating->count})";
2128 } else {
2129 $countstr = '-';
2131 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2133 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2134 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2136 $nonpopuplink = $rating->get_view_ratings_url();
2137 $popuplink = $rating->get_view_ratings_url(true);
2139 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2140 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2141 } else {
2142 $ratinghtml .= $aggregatehtml;
2146 $formstart = null;
2147 // if the item doesn't belong to the current user, the user has permission to rate
2148 // and we're within the assessable period
2149 if ($rating->user_can_rate()) {
2151 $rateurl = $rating->get_rate_url();
2152 $inputs = $rateurl->params();
2154 //start the rating form
2155 $formattrs = array(
2156 'id' => "postrating{$rating->itemid}",
2157 'class' => 'postratingform',
2158 'method' => 'post',
2159 'action' => $rateurl->out_omit_querystring()
2161 $formstart = html_writer::start_tag('form', $formattrs);
2162 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2164 // add the hidden inputs
2165 foreach ($inputs as $name => $value) {
2166 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2167 $formstart .= html_writer::empty_tag('input', $attributes);
2170 if (empty($ratinghtml)) {
2171 $ratinghtml .= $strrate.': ';
2173 $ratinghtml = $formstart.$ratinghtml;
2175 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2176 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2177 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2178 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2180 //output submit button
2181 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2183 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2184 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2186 if (!$rating->settings->scale->isnumeric) {
2187 // If a global scale, try to find current course ID from the context
2188 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2189 $courseid = $coursecontext->instanceid;
2190 } else {
2191 $courseid = $rating->settings->scale->courseid;
2193 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2195 $ratinghtml .= html_writer::end_tag('span');
2196 $ratinghtml .= html_writer::end_tag('div');
2197 $ratinghtml .= html_writer::end_tag('form');
2200 return $ratinghtml;
2204 * Centered heading with attached help button (same title text)
2205 * and optional icon attached.
2207 * @param string $text A heading text
2208 * @param string $helpidentifier The keyword that defines a help page
2209 * @param string $component component name
2210 * @param string|moodle_url $icon
2211 * @param string $iconalt icon alt text
2212 * @param int $level The level of importance of the heading. Defaulting to 2
2213 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2214 * @return string HTML fragment
2216 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2217 $image = '';
2218 if ($icon) {
2219 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2222 $help = '';
2223 if ($helpidentifier) {
2224 $help = $this->help_icon($helpidentifier, $component);
2227 return $this->heading($image.$text.$help, $level, $classnames);
2231 * Returns HTML to display a help icon.
2233 * @deprecated since Moodle 2.0
2235 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2236 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2240 * Returns HTML to display a help icon.
2242 * Theme developers: DO NOT OVERRIDE! Please override function
2243 * {@link core_renderer::render_help_icon()} instead.
2245 * @param string $identifier The keyword that defines a help page
2246 * @param string $component component name
2247 * @param string|bool $linktext true means use $title as link text, string means link text value
2248 * @return string HTML fragment
2250 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2251 $icon = new help_icon($identifier, $component);
2252 $icon->diag_strings();
2253 if ($linktext === true) {
2254 $icon->linktext = get_string($icon->identifier, $icon->component);
2255 } else if (!empty($linktext)) {
2256 $icon->linktext = $linktext;
2258 return $this->render($icon);
2262 * Implementation of user image rendering.
2264 * @param help_icon $helpicon A help icon instance
2265 * @return string HTML fragment
2267 protected function render_help_icon(help_icon $helpicon) {
2268 return $this->render_from_template('core/help_icon', $helpicon->export_for_template($this));
2272 * Returns HTML to display a scale help icon.
2274 * @param int $courseid
2275 * @param stdClass $scale instance
2276 * @return string HTML fragment
2278 public function help_icon_scale($courseid, stdClass $scale) {
2279 global $CFG;
2281 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2283 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2285 $scaleid = abs($scale->id);
2287 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2288 $action = new popup_action('click', $link, 'ratingscale');
2290 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2294 * Creates and returns a spacer image with optional line break.
2296 * @param array $attributes Any HTML attributes to add to the spaced.
2297 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2298 * laxy do it with CSS which is a much better solution.
2299 * @return string HTML fragment
2301 public function spacer(array $attributes = null, $br = false) {
2302 $attributes = (array)$attributes;
2303 if (empty($attributes['width'])) {
2304 $attributes['width'] = 1;
2306 if (empty($attributes['height'])) {
2307 $attributes['height'] = 1;
2309 $attributes['class'] = 'spacer';
2311 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2313 if (!empty($br)) {
2314 $output .= '<br />';
2317 return $output;
2321 * Returns HTML to display the specified user's avatar.
2323 * User avatar may be obtained in two ways:
2324 * <pre>
2325 * // Option 1: (shortcut for simple cases, preferred way)
2326 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2327 * $OUTPUT->user_picture($user, array('popup'=>true));
2329 * // Option 2:
2330 * $userpic = new user_picture($user);
2331 * // Set properties of $userpic
2332 * $userpic->popup = true;
2333 * $OUTPUT->render($userpic);
2334 * </pre>
2336 * Theme developers: DO NOT OVERRIDE! Please override function
2337 * {@link core_renderer::render_user_picture()} instead.
2339 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2340 * If any of these are missing, the database is queried. Avoid this
2341 * if at all possible, particularly for reports. It is very bad for performance.
2342 * @param array $options associative array with user picture options, used only if not a user_picture object,
2343 * options are:
2344 * - courseid=$this->page->course->id (course id of user profile in link)
2345 * - size=35 (size of image)
2346 * - link=true (make image clickable - the link leads to user profile)
2347 * - popup=false (open in popup)
2348 * - alttext=true (add image alt attribute)
2349 * - class = image class attribute (default 'userpicture')
2350 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2351 * @return string HTML fragment
2353 public function user_picture(stdClass $user, array $options = null) {
2354 $userpicture = new user_picture($user);
2355 foreach ((array)$options as $key=>$value) {
2356 if (array_key_exists($key, $userpicture)) {
2357 $userpicture->$key = $value;
2360 return $this->render($userpicture);
2364 * Internal implementation of user image rendering.
2366 * @param user_picture $userpicture
2367 * @return string
2369 protected function render_user_picture(user_picture $userpicture) {
2370 global $CFG, $DB;
2372 $user = $userpicture->user;
2374 if ($userpicture->alttext) {
2375 if (!empty($user->imagealt)) {
2376 $alt = $user->imagealt;
2377 } else {
2378 $alt = get_string('pictureof', '', fullname($user));
2380 } else {
2381 $alt = '';
2384 if (empty($userpicture->size)) {
2385 $size = 35;
2386 } else if ($userpicture->size === true or $userpicture->size == 1) {
2387 $size = 100;
2388 } else {
2389 $size = $userpicture->size;
2392 $class = $userpicture->class;
2394 if ($user->picture == 0) {
2395 $class .= ' defaultuserpic';
2398 $src = $userpicture->get_url($this->page, $this);
2400 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2401 if (!$userpicture->visibletoscreenreaders) {
2402 $attributes['role'] = 'presentation';
2405 // get the image html output fisrt
2406 $output = html_writer::empty_tag('img', $attributes);
2408 // then wrap it in link if needed
2409 if (!$userpicture->link) {
2410 return $output;
2413 if (empty($userpicture->courseid)) {
2414 $courseid = $this->page->course->id;
2415 } else {
2416 $courseid = $userpicture->courseid;
2419 if ($courseid == SITEID) {
2420 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2421 } else {
2422 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2425 $attributes = array('href'=>$url);
2426 if (!$userpicture->visibletoscreenreaders) {
2427 $attributes['tabindex'] = '-1';
2428 $attributes['aria-hidden'] = 'true';
2431 if ($userpicture->popup) {
2432 $id = html_writer::random_id('userpicture');
2433 $attributes['id'] = $id;
2434 $this->add_action_handler(new popup_action('click', $url), $id);
2437 return html_writer::tag('a', $output, $attributes);
2441 * Internal implementation of file tree viewer items rendering.
2443 * @param array $dir
2444 * @return string
2446 public function htmllize_file_tree($dir) {
2447 if (empty($dir['subdirs']) and empty($dir['files'])) {
2448 return '';
2450 $result = '<ul>';
2451 foreach ($dir['subdirs'] as $subdir) {
2452 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2454 foreach ($dir['files'] as $file) {
2455 $filename = $file->get_filename();
2456 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2458 $result .= '</ul>';
2460 return $result;
2464 * Returns HTML to display the file picker
2466 * <pre>
2467 * $OUTPUT->file_picker($options);
2468 * </pre>
2470 * Theme developers: DO NOT OVERRIDE! Please override function
2471 * {@link core_renderer::render_file_picker()} instead.
2473 * @param array $options associative array with file manager options
2474 * options are:
2475 * maxbytes=>-1,
2476 * itemid=>0,
2477 * client_id=>uniqid(),
2478 * acepted_types=>'*',
2479 * return_types=>FILE_INTERNAL,
2480 * context=>$PAGE->context
2481 * @return string HTML fragment
2483 public function file_picker($options) {
2484 $fp = new file_picker($options);
2485 return $this->render($fp);
2489 * Internal implementation of file picker rendering.
2491 * @param file_picker $fp
2492 * @return string
2494 public function render_file_picker(file_picker $fp) {
2495 global $CFG, $OUTPUT, $USER;
2496 $options = $fp->options;
2497 $client_id = $options->client_id;
2498 $strsaved = get_string('filesaved', 'repository');
2499 $straddfile = get_string('openpicker', 'repository');
2500 $strloading = get_string('loading', 'repository');
2501 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2502 $strdroptoupload = get_string('droptoupload', 'moodle');
2503 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2505 $currentfile = $options->currentfile;
2506 if (empty($currentfile)) {
2507 $currentfile = '';
2508 } else {
2509 $currentfile .= ' - ';
2511 if ($options->maxbytes) {
2512 $size = $options->maxbytes;
2513 } else {
2514 $size = get_max_upload_file_size();
2516 if ($size == -1) {
2517 $maxsize = '';
2518 } else {
2519 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2521 if ($options->buttonname) {
2522 $buttonname = ' name="' . $options->buttonname . '"';
2523 } else {
2524 $buttonname = '';
2526 $html = <<<EOD
2527 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2528 $icon_progress
2529 </div>
2530 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2531 <div>
2532 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2533 <span> $maxsize </span>
2534 </div>
2535 EOD;
2536 if ($options->env != 'url') {
2537 $html .= <<<EOD
2538 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2539 <div class="filepicker-filename">
2540 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2541 <div class="dndupload-progressbars"></div>
2542 </div>
2543 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2544 </div>
2545 EOD;
2547 $html .= '</div>';
2548 return $html;
2552 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2554 * @deprecated since Moodle 3.2
2556 * @param string $cmid the course_module id.
2557 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2558 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2560 public function update_module_button($cmid, $modulename) {
2561 global $CFG;
2563 debugging('core_renderer::update_module_button() has been deprecated and should not be used anymore. Activity modules ' .
2564 'should not add the edit module button, the link is already available in the Administration block. Themes can choose ' .
2565 'to display the link in the buttons row consistently for all module types.', DEBUG_DEVELOPER);
2567 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2568 $modulename = get_string('modulename', $modulename);
2569 $string = get_string('updatethis', '', $modulename);
2570 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2571 return $this->single_button($url, $string);
2572 } else {
2573 return '';
2578 * Returns HTML to display a "Turn editing on/off" button in a form.
2580 * @param moodle_url $url The URL + params to send through when clicking the button
2581 * @return string HTML the button
2583 public function edit_button(moodle_url $url) {
2585 $url->param('sesskey', sesskey());
2586 if ($this->page->user_is_editing()) {
2587 $url->param('edit', 'off');
2588 $editstring = get_string('turneditingoff');
2589 } else {
2590 $url->param('edit', 'on');
2591 $editstring = get_string('turneditingon');
2594 return $this->single_button($url, $editstring);
2598 * Returns HTML to display a simple button to close a window
2600 * @param string $text The lang string for the button's label (already output from get_string())
2601 * @return string html fragment
2603 public function close_window_button($text='') {
2604 if (empty($text)) {
2605 $text = get_string('closewindow');
2607 $button = new single_button(new moodle_url('#'), $text, 'get');
2608 $button->add_action(new component_action('click', 'close_window'));
2610 return $this->container($this->render($button), 'closewindow');
2614 * Output an error message. By default wraps the error message in <span class="error">.
2615 * If the error message is blank, nothing is output.
2617 * @param string $message the error message.
2618 * @return string the HTML to output.
2620 public function error_text($message) {
2621 if (empty($message)) {
2622 return '';
2624 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2625 return html_writer::tag('span', $message, array('class' => 'error'));
2629 * Do not call this function directly.
2631 * To terminate the current script with a fatal error, call the {@link print_error}
2632 * function, or throw an exception. Doing either of those things will then call this
2633 * function to display the error, before terminating the execution.
2635 * @param string $message The message to output
2636 * @param string $moreinfourl URL where more info can be found about the error
2637 * @param string $link Link for the Continue button
2638 * @param array $backtrace The execution backtrace
2639 * @param string $debuginfo Debugging information
2640 * @return string the HTML to output.
2642 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2643 global $CFG;
2645 $output = '';
2646 $obbuffer = '';
2648 if ($this->has_started()) {
2649 // we can not always recover properly here, we have problems with output buffering,
2650 // html tables, etc.
2651 $output .= $this->opencontainers->pop_all_but_last();
2653 } else {
2654 // It is really bad if library code throws exception when output buffering is on,
2655 // because the buffered text would be printed before our start of page.
2656 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2657 error_reporting(0); // disable notices from gzip compression, etc.
2658 while (ob_get_level() > 0) {
2659 $buff = ob_get_clean();
2660 if ($buff === false) {
2661 break;
2663 $obbuffer .= $buff;
2665 error_reporting($CFG->debug);
2667 // Output not yet started.
2668 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2669 if (empty($_SERVER['HTTP_RANGE'])) {
2670 @header($protocol . ' 404 Not Found');
2671 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2672 // Coax iOS 10 into sending the session cookie.
2673 @header($protocol . ' 403 Forbidden');
2674 } else {
2675 // Must stop byteserving attempts somehow,
2676 // this is weird but Chrome PDF viewer can be stopped only with 407!
2677 @header($protocol . ' 407 Proxy Authentication Required');
2680 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2681 $this->page->set_url('/'); // no url
2682 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2683 $this->page->set_title(get_string('error'));
2684 $this->page->set_heading($this->page->course->fullname);
2685 $output .= $this->header();
2688 $message = '<p class="errormessage">' . $message . '</p>'.
2689 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2690 get_string('moreinformation') . '</a></p>';
2691 if (empty($CFG->rolesactive)) {
2692 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2693 //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.
2695 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
2697 if ($CFG->debugdeveloper) {
2698 if (!empty($debuginfo)) {
2699 $debuginfo = s($debuginfo); // removes all nasty JS
2700 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2701 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2703 if (!empty($backtrace)) {
2704 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2706 if ($obbuffer !== '' ) {
2707 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2711 if (empty($CFG->rolesactive)) {
2712 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2713 } else if (!empty($link)) {
2714 $output .= $this->continue_button($link);
2717 $output .= $this->footer();
2719 // Padding to encourage IE to display our error page, rather than its own.
2720 $output .= str_repeat(' ', 512);
2722 return $output;
2726 * Output a notification (that is, a status message about something that has just happened).
2728 * Note: \core\notification::add() may be more suitable for your usage.
2730 * @param string $message The message to print out.
2731 * @param string $type The type of notification. See constants on \core\output\notification.
2732 * @return string the HTML to output.
2734 public function notification($message, $type = null) {
2735 $typemappings = [
2736 // Valid types.
2737 'success' => \core\output\notification::NOTIFY_SUCCESS,
2738 'info' => \core\output\notification::NOTIFY_INFO,
2739 'warning' => \core\output\notification::NOTIFY_WARNING,
2740 'error' => \core\output\notification::NOTIFY_ERROR,
2742 // Legacy types mapped to current types.
2743 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2744 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2745 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2746 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2747 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2748 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2749 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2752 $extraclasses = [];
2754 if ($type) {
2755 if (strpos($type, ' ') === false) {
2756 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2757 if (isset($typemappings[$type])) {
2758 $type = $typemappings[$type];
2759 } else {
2760 // The value provided did not match a known type. It must be an extra class.
2761 $extraclasses = [$type];
2763 } else {
2764 // Identify what type of notification this is.
2765 $classarray = explode(' ', self::prepare_classes($type));
2767 // Separate out the type of notification from the extra classes.
2768 foreach ($classarray as $class) {
2769 if (isset($typemappings[$class])) {
2770 $type = $typemappings[$class];
2771 } else {
2772 $extraclasses[] = $class;
2778 $notification = new \core\output\notification($message, $type);
2779 if (count($extraclasses)) {
2780 $notification->set_extra_classes($extraclasses);
2783 // Return the rendered template.
2784 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2788 * Output a notification at a particular level - in this case, NOTIFY_PROBLEM.
2790 * @param string $message the message to print out
2791 * @return string HTML fragment.
2792 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2793 * @todo MDL-53113 This will be removed in Moodle 3.5.
2794 * @see \core\output\notification
2796 public function notify_problem($message) {
2797 debugging(__FUNCTION__ . ' is deprecated.' .
2798 'Please use \core\notification::add, or \core\output\notification as required',
2799 DEBUG_DEVELOPER);
2800 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_ERROR);
2801 return $this->render($n);
2805 * Output a notification at a particular level - in this case, NOTIFY_SUCCESS.
2807 * @param string $message the message to print out
2808 * @return string HTML fragment.
2809 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2810 * @todo MDL-53113 This will be removed in Moodle 3.5.
2811 * @see \core\output\notification
2813 public function notify_success($message) {
2814 debugging(__FUNCTION__ . ' is deprecated.' .
2815 'Please use \core\notification::add, or \core\output\notification as required',
2816 DEBUG_DEVELOPER);
2817 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_SUCCESS);
2818 return $this->render($n);
2822 * Output a notification at a particular level - in this case, NOTIFY_MESSAGE.
2824 * @param string $message the message to print out
2825 * @return string HTML fragment.
2826 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2827 * @todo MDL-53113 This will be removed in Moodle 3.5.
2828 * @see \core\output\notification
2830 public function notify_message($message) {
2831 debugging(__FUNCTION__ . ' is deprecated.' .
2832 'Please use \core\notification::add, or \core\output\notification as required',
2833 DEBUG_DEVELOPER);
2834 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_INFO);
2835 return $this->render($n);
2839 * Output a notification at a particular level - in this case, NOTIFY_REDIRECT.
2841 * @param string $message the message to print out
2842 * @return string HTML fragment.
2843 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2844 * @todo MDL-53113 This will be removed in Moodle 3.5.
2845 * @see \core\output\notification
2847 public function notify_redirect($message) {
2848 debugging(__FUNCTION__ . ' is deprecated.' .
2849 'Please use \core\notification::add, or \core\output\notification as required',
2850 DEBUG_DEVELOPER);
2851 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_INFO);
2852 return $this->render($n);
2856 * Render a notification (that is, a status message about something that has
2857 * just happened).
2859 * @param \core\output\notification $notification the notification to print out
2860 * @return string the HTML to output.
2862 protected function render_notification(\core\output\notification $notification) {
2863 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2867 * Returns HTML to display a continue button that goes to a particular URL.
2869 * @param string|moodle_url $url The url the button goes to.
2870 * @return string the HTML to output.
2872 public function continue_button($url) {
2873 if (!($url instanceof moodle_url)) {
2874 $url = new moodle_url($url);
2876 $button = new single_button($url, get_string('continue'), 'get', true);
2877 $button->class = 'continuebutton';
2879 return $this->render($button);
2883 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2885 * Theme developers: DO NOT OVERRIDE! Please override function
2886 * {@link core_renderer::render_paging_bar()} instead.
2888 * @param int $totalcount The total number of entries available to be paged through
2889 * @param int $page The page you are currently viewing
2890 * @param int $perpage The number of entries that should be shown per page
2891 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2892 * @param string $pagevar name of page parameter that holds the page number
2893 * @return string the HTML to output.
2895 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2896 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2897 return $this->render($pb);
2901 * Internal implementation of paging bar rendering.
2903 * @param paging_bar $pagingbar
2904 * @return string
2906 protected function render_paging_bar(paging_bar $pagingbar) {
2907 $output = '';
2908 $pagingbar = clone($pagingbar);
2909 $pagingbar->prepare($this, $this->page, $this->target);
2911 if ($pagingbar->totalcount > $pagingbar->perpage) {
2912 $output .= get_string('page') . ':';
2914 if (!empty($pagingbar->previouslink)) {
2915 $output .= ' (' . $pagingbar->previouslink . ') ';
2918 if (!empty($pagingbar->firstlink)) {
2919 $output .= ' ' . $pagingbar->firstlink . ' ...';
2922 foreach ($pagingbar->pagelinks as $link) {
2923 $output .= " $link";
2926 if (!empty($pagingbar->lastlink)) {
2927 $output .= ' ... ' . $pagingbar->lastlink . ' ';
2930 if (!empty($pagingbar->nextlink)) {
2931 $output .= ' (' . $pagingbar->nextlink . ')';
2935 return html_writer::tag('div', $output, array('class' => 'paging'));
2939 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
2941 * @param string $current the currently selected letter.
2942 * @param string $class class name to add to this initial bar.
2943 * @param string $title the name to put in front of this initial bar.
2944 * @param string $urlvar URL parameter name for this initial.
2945 * @param string $url URL object.
2946 * @param array $alpha of letters in the alphabet.
2947 * @return string the HTML to output.
2949 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
2950 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
2951 return $this->render($ib);
2955 * Internal implementation of initials bar rendering.
2957 * @param initials_bar $initialsbar
2958 * @return string
2960 protected function render_initials_bar(initials_bar $initialsbar) {
2961 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
2965 * Output the place a skip link goes to.
2967 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2968 * @return string the HTML to output.
2970 public function skip_link_target($id = null) {
2971 return html_writer::span('', '', array('id' => $id));
2975 * Outputs a heading
2977 * @param string $text The text of the heading
2978 * @param int $level The level of importance of the heading. Defaulting to 2
2979 * @param string $classes A space-separated list of CSS classes. Defaulting to null
2980 * @param string $id An optional ID
2981 * @return string the HTML to output.
2983 public function heading($text, $level = 2, $classes = null, $id = null) {
2984 $level = (integer) $level;
2985 if ($level < 1 or $level > 6) {
2986 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2988 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2992 * Outputs a box.
2994 * @param string $contents The contents of the box
2995 * @param string $classes A space-separated list of CSS classes
2996 * @param string $id An optional ID
2997 * @param array $attributes An array of other attributes to give the box.
2998 * @return string the HTML to output.
3000 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3001 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3005 * Outputs the opening section of a box.
3007 * @param string $classes A space-separated list of CSS classes
3008 * @param string $id An optional ID
3009 * @param array $attributes An array of other attributes to give the box.
3010 * @return string the HTML to output.
3012 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3013 $this->opencontainers->push('box', html_writer::end_tag('div'));
3014 $attributes['id'] = $id;
3015 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
3016 return html_writer::start_tag('div', $attributes);
3020 * Outputs the closing section of a box.
3022 * @return string the HTML to output.
3024 public function box_end() {
3025 return $this->opencontainers->pop('box');
3029 * Outputs a container.
3031 * @param string $contents The contents of the box
3032 * @param string $classes A space-separated list of CSS classes
3033 * @param string $id An optional ID
3034 * @return string the HTML to output.
3036 public function container($contents, $classes = null, $id = null) {
3037 return $this->container_start($classes, $id) . $contents . $this->container_end();
3041 * Outputs the opening section of a container.
3043 * @param string $classes A space-separated list of CSS classes
3044 * @param string $id An optional ID
3045 * @return string the HTML to output.
3047 public function container_start($classes = null, $id = null) {
3048 $this->opencontainers->push('container', html_writer::end_tag('div'));
3049 return html_writer::start_tag('div', array('id' => $id,
3050 'class' => renderer_base::prepare_classes($classes)));
3054 * Outputs the closing section of a container.
3056 * @return string the HTML to output.
3058 public function container_end() {
3059 return $this->opencontainers->pop('container');
3063 * Make nested HTML lists out of the items
3065 * The resulting list will look something like this:
3067 * <pre>
3068 * <<ul>>
3069 * <<li>><div class='tree_item parent'>(item contents)</div>
3070 * <<ul>
3071 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3072 * <</ul>>
3073 * <</li>>
3074 * <</ul>>
3075 * </pre>
3077 * @param array $items
3078 * @param array $attrs html attributes passed to the top ofs the list
3079 * @return string HTML
3081 public function tree_block_contents($items, $attrs = array()) {
3082 // exit if empty, we don't want an empty ul element
3083 if (empty($items)) {
3084 return '';
3086 // array of nested li elements
3087 $lis = array();
3088 foreach ($items as $item) {
3089 // this applies to the li item which contains all child lists too
3090 $content = $item->content($this);
3091 $liclasses = array($item->get_css_type());
3092 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3093 $liclasses[] = 'collapsed';
3095 if ($item->isactive === true) {
3096 $liclasses[] = 'current_branch';
3098 $liattr = array('class'=>join(' ',$liclasses));
3099 // class attribute on the div item which only contains the item content
3100 $divclasses = array('tree_item');
3101 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3102 $divclasses[] = 'branch';
3103 } else {
3104 $divclasses[] = 'leaf';
3106 if (!empty($item->classes) && count($item->classes)>0) {
3107 $divclasses[] = join(' ', $item->classes);
3109 $divattr = array('class'=>join(' ', $divclasses));
3110 if (!empty($item->id)) {
3111 $divattr['id'] = $item->id;
3113 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3114 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3115 $content = html_writer::empty_tag('hr') . $content;
3117 $content = html_writer::tag('li', $content, $liattr);
3118 $lis[] = $content;
3120 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3124 * Returns a search box.
3126 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3127 * @return string HTML with the search form hidden by default.
3129 public function search_box($id = false) {
3130 global $CFG;
3132 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3133 // result in an extra included file for each site, even the ones where global search
3134 // is disabled.
3135 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3136 return '';
3139 if ($id == false) {
3140 $id = uniqid();
3141 } else {
3142 // Needs to be cleaned, we use it for the input id.
3143 $id = clean_param($id, PARAM_ALPHANUMEXT);
3146 // JS to animate the form.
3147 $this->page->requires->js_call_amd('core/search-input', 'init', array($id));
3149 $searchicon = html_writer::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
3150 array('role' => 'button', 'tabindex' => 0));
3151 $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot . '/search/index.php');
3152 $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
3153 'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id, 'class' => 'form-control');
3155 $contents = html_writer::tag('label', get_string('enteryoursearchquery', 'search'),
3156 array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer::tag('input', '', $inputattrs);
3157 $searchinput = html_writer::tag('form', $contents, $formattrs);
3159 return html_writer::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper nav-link', 'id' => $id));
3163 * Allow plugins to provide some content to be rendered in the navbar.
3164 * The plugin must define a PLUGIN_render_navbar_output function that returns
3165 * the HTML they wish to add to the navbar.
3167 * @return string HTML for the navbar
3169 public function navbar_plugin_output() {
3170 $output = '';
3172 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3173 foreach ($pluginsfunction as $plugintype => $plugins) {
3174 foreach ($plugins as $pluginfunction) {
3175 $output .= $pluginfunction($this);
3180 return $output;
3184 * Construct a user menu, returning HTML that can be echoed out by a
3185 * layout file.
3187 * @param stdClass $user A user object, usually $USER.
3188 * @param bool $withlinks true if a dropdown should be built.
3189 * @return string HTML fragment.
3191 public function user_menu($user = null, $withlinks = null) {
3192 global $USER, $CFG;
3193 require_once($CFG->dirroot . '/user/lib.php');
3195 if (is_null($user)) {
3196 $user = $USER;
3199 // Note: this behaviour is intended to match that of core_renderer::login_info,
3200 // but should not be considered to be good practice; layout options are
3201 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3202 if (is_null($withlinks)) {
3203 $withlinks = empty($this->page->layout_options['nologinlinks']);
3206 // Add a class for when $withlinks is false.
3207 $usermenuclasses = 'usermenu';
3208 if (!$withlinks) {
3209 $usermenuclasses .= ' withoutlinks';
3212 $returnstr = "";
3214 // If during initial install, return the empty return string.
3215 if (during_initial_install()) {
3216 return $returnstr;
3219 $loginpage = $this->is_login_page();
3220 $loginurl = get_login_url();
3221 // If not logged in, show the typical not-logged-in string.
3222 if (!isloggedin()) {
3223 $returnstr = get_string('loggedinnot', 'moodle');
3224 if (!$loginpage) {
3225 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3227 return html_writer::div(
3228 html_writer::span(
3229 $returnstr,
3230 'login'
3232 $usermenuclasses
3237 // If logged in as a guest user, show a string to that effect.
3238 if (isguestuser()) {
3239 $returnstr = get_string('loggedinasguest');
3240 if (!$loginpage && $withlinks) {
3241 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3244 return html_writer::div(
3245 html_writer::span(
3246 $returnstr,
3247 'login'
3249 $usermenuclasses
3253 // Get some navigation opts.
3254 $opts = user_get_user_navigation_info($user, $this->page);
3256 $avatarclasses = "avatars";
3257 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3258 $usertextcontents = $opts->metadata['userfullname'];
3260 // Other user.
3261 if (!empty($opts->metadata['asotheruser'])) {
3262 $avatarcontents .= html_writer::span(
3263 $opts->metadata['realuseravatar'],
3264 'avatar realuser'
3266 $usertextcontents = $opts->metadata['realuserfullname'];
3267 $usertextcontents .= html_writer::tag(
3268 'span',
3269 get_string(
3270 'loggedinas',
3271 'moodle',
3272 html_writer::span(
3273 $opts->metadata['userfullname'],
3274 'value'
3277 array('class' => 'meta viewingas')
3281 // Role.
3282 if (!empty($opts->metadata['asotherrole'])) {
3283 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3284 $usertextcontents .= html_writer::span(
3285 $opts->metadata['rolename'],
3286 'meta role role-' . $role
3290 // User login failures.
3291 if (!empty($opts->metadata['userloginfail'])) {
3292 $usertextcontents .= html_writer::span(
3293 $opts->metadata['userloginfail'],
3294 'meta loginfailures'
3298 // MNet.
3299 if (!empty($opts->metadata['asmnetuser'])) {
3300 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3301 $usertextcontents .= html_writer::span(
3302 $opts->metadata['mnetidprovidername'],
3303 'meta mnet mnet-' . $mnet
3307 $returnstr .= html_writer::span(
3308 html_writer::span($usertextcontents, 'usertext') .
3309 html_writer::span($avatarcontents, $avatarclasses),
3310 'userbutton'
3313 // Create a divider (well, a filler).
3314 $divider = new action_menu_filler();
3315 $divider->primary = false;
3317 $am = new action_menu();
3318 $am->set_menu_trigger(
3319 $returnstr
3321 $am->set_alignment(action_menu::TR, action_menu::BR);
3322 $am->set_nowrap_on_items();
3323 if ($withlinks) {
3324 $navitemcount = count($opts->navitems);
3325 $idx = 0;
3326 foreach ($opts->navitems as $key => $value) {
3328 switch ($value->itemtype) {
3329 case 'divider':
3330 // If the nav item is a divider, add one and skip link processing.
3331 $am->add($divider);
3332 break;
3334 case 'invalid':
3335 // Silently skip invalid entries (should we post a notification?).
3336 break;
3338 case 'link':
3339 // Process this as a link item.
3340 $pix = null;
3341 if (isset($value->pix) && !empty($value->pix)) {
3342 $pix = new pix_icon($value->pix, $value->title, null, array('class' => 'iconsmall'));
3343 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3344 $value->title = html_writer::img(
3345 $value->imgsrc,
3346 $value->title,
3347 array('class' => 'iconsmall')
3348 ) . $value->title;
3351 $al = new action_menu_link_secondary(
3352 $value->url,
3353 $pix,
3354 $value->title,
3355 array('class' => 'icon')
3357 if (!empty($value->titleidentifier)) {
3358 $al->attributes['data-title'] = $value->titleidentifier;
3360 $am->add($al);
3361 break;
3364 $idx++;
3366 // Add dividers after the first item and before the last item.
3367 if ($idx == 1 || $idx == $navitemcount - 1) {
3368 $am->add($divider);
3373 return html_writer::div(
3374 $this->render($am),
3375 $usermenuclasses
3380 * Return the navbar content so that it can be echoed out by the layout
3382 * @return string XHTML navbar
3384 public function navbar() {
3385 $items = $this->page->navbar->get_items();
3386 $itemcount = count($items);
3387 if ($itemcount === 0) {
3388 return '';
3391 $htmlblocks = array();
3392 // Iterate the navarray and display each node
3393 $separator = get_separator();
3394 for ($i=0;$i < $itemcount;$i++) {
3395 $item = $items[$i];
3396 $item->hideicon = true;
3397 if ($i===0) {
3398 $content = html_writer::tag('li', $this->render($item));
3399 } else {
3400 $content = html_writer::tag('li', $separator.$this->render($item));
3402 $htmlblocks[] = $content;
3405 //accessibility: heading for navbar list (MDL-20446)
3406 $navbarcontent = html_writer::tag('span', get_string('pagepath'),
3407 array('class' => 'accesshide', 'id' => 'navbar-label'));
3408 $navbarcontent .= html_writer::tag('nav',
3409 html_writer::tag('ul', join('', $htmlblocks)),
3410 array('aria-labelledby' => 'navbar-label'));
3411 // XHTML
3412 return $navbarcontent;
3416 * Renders a breadcrumb navigation node object.
3418 * @param breadcrumb_navigation_node $item The navigation node to render.
3419 * @return string HTML fragment
3421 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3423 if ($item->action instanceof moodle_url) {
3424 $content = $item->get_content();
3425 $title = $item->get_title();
3426 $attributes = array();
3427 $attributes['itemprop'] = 'url';
3428 if ($title !== '') {
3429 $attributes['title'] = $title;
3431 if ($item->hidden) {
3432 $attributes['class'] = 'dimmed_text';
3434 $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3435 $content = html_writer::link($item->action, $content, $attributes);
3437 $attributes = array();
3438 $attributes['itemscope'] = '';
3439 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3440 $content = html_writer::tag('span', $content, $attributes);
3442 } else {
3443 $content = $this->render_navigation_node($item);
3445 return $content;
3449 * Renders a navigation node object.
3451 * @param navigation_node $item The navigation node to render.
3452 * @return string HTML fragment
3454 protected function render_navigation_node(navigation_node $item) {
3455 $content = $item->get_content();
3456 $title = $item->get_title();
3457 if ($item->icon instanceof renderable && !$item->hideicon) {
3458 $icon = $this->render($item->icon);
3459 $content = $icon.$content; // use CSS for spacing of icons
3461 if ($item->helpbutton !== null) {
3462 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3464 if ($content === '') {
3465 return '';
3467 if ($item->action instanceof action_link) {
3468 $link = $item->action;
3469 if ($item->hidden) {
3470 $link->add_class('dimmed');
3472 if (!empty($content)) {
3473 // Providing there is content we will use that for the link content.
3474 $link->text = $content;
3476 $content = $this->render($link);
3477 } else if ($item->action instanceof moodle_url) {
3478 $attributes = array();
3479 if ($title !== '') {
3480 $attributes['title'] = $title;
3482 if ($item->hidden) {
3483 $attributes['class'] = 'dimmed_text';
3485 $content = html_writer::link($item->action, $content, $attributes);
3487 } else if (is_string($item->action) || empty($item->action)) {
3488 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3489 if ($title !== '') {
3490 $attributes['title'] = $title;
3492 if ($item->hidden) {
3493 $attributes['class'] = 'dimmed_text';
3495 $content = html_writer::tag('span', $content, $attributes);
3497 return $content;
3501 * Accessibility: Right arrow-like character is
3502 * used in the breadcrumb trail, course navigation menu
3503 * (previous/next activity), calendar, and search forum block.
3504 * If the theme does not set characters, appropriate defaults
3505 * are set automatically. Please DO NOT
3506 * use &lt; &gt; &raquo; - these are confusing for blind users.
3508 * @return string
3510 public function rarrow() {
3511 return $this->page->theme->rarrow;
3515 * Accessibility: Left arrow-like character is
3516 * used in the breadcrumb trail, course navigation menu
3517 * (previous/next activity), calendar, and search forum block.
3518 * If the theme does not set characters, appropriate defaults
3519 * are set automatically. Please DO NOT
3520 * use &lt; &gt; &raquo; - these are confusing for blind users.
3522 * @return string
3524 public function larrow() {
3525 return $this->page->theme->larrow;
3529 * Accessibility: Up arrow-like character is used in
3530 * the book heirarchical navigation.
3531 * If the theme does not set characters, appropriate defaults
3532 * are set automatically. Please DO NOT
3533 * use ^ - this is confusing for blind users.
3535 * @return string
3537 public function uarrow() {
3538 return $this->page->theme->uarrow;
3542 * Accessibility: Down arrow-like character.
3543 * If the theme does not set characters, appropriate defaults
3544 * are set automatically.
3546 * @return string
3548 public function darrow() {
3549 return $this->page->theme->darrow;
3553 * Returns the custom menu if one has been set
3555 * A custom menu can be configured by browsing to
3556 * Settings: Administration > Appearance > Themes > Theme settings
3557 * and then configuring the custommenu config setting as described.
3559 * Theme developers: DO NOT OVERRIDE! Please override function
3560 * {@link core_renderer::render_custom_menu()} instead.
3562 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3563 * @return string
3565 public function custom_menu($custommenuitems = '') {
3566 global $CFG;
3567 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3568 $custommenuitems = $CFG->custommenuitems;
3570 if (empty($custommenuitems)) {
3571 return '';
3573 $custommenu = new custom_menu($custommenuitems, current_language());
3574 return $this->render($custommenu);
3578 * Renders a custom menu object (located in outputcomponents.php)
3580 * The custom menu this method produces makes use of the YUI3 menunav widget
3581 * and requires very specific html elements and classes.
3583 * @staticvar int $menucount
3584 * @param custom_menu $menu
3585 * @return string
3587 protected function render_custom_menu(custom_menu $menu) {
3588 static $menucount = 0;
3589 // If the menu has no children return an empty string
3590 if (!$menu->has_children()) {
3591 return '';
3593 // Increment the menu count. This is used for ID's that get worked with
3594 // in JavaScript as is essential
3595 $menucount++;
3596 // Initialise this custom menu (the custom menu object is contained in javascript-static
3597 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
3598 $jscode = "(function(){{$jscode}})";
3599 $this->page->requires->yui_module('node-menunav', $jscode);
3600 // Build the root nodes as required by YUI
3601 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
3602 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3603 $content .= html_writer::start_tag('ul');
3604 // Render each child
3605 foreach ($menu->get_children() as $item) {
3606 $content .= $this->render_custom_menu_item($item);
3608 // Close the open tags
3609 $content .= html_writer::end_tag('ul');
3610 $content .= html_writer::end_tag('div');
3611 $content .= html_writer::end_tag('div');
3612 // Return the custom menu
3613 return $content;
3617 * Renders a custom menu node as part of a submenu
3619 * The custom menu this method produces makes use of the YUI3 menunav widget
3620 * and requires very specific html elements and classes.
3622 * @see core:renderer::render_custom_menu()
3624 * @staticvar int $submenucount
3625 * @param custom_menu_item $menunode
3626 * @return string
3628 protected function render_custom_menu_item(custom_menu_item $menunode) {
3629 // Required to ensure we get unique trackable id's
3630 static $submenucount = 0;
3631 if ($menunode->has_children()) {
3632 // If the child has menus render it as a sub menu
3633 $submenucount++;
3634 $content = html_writer::start_tag('li');
3635 if ($menunode->get_url() !== null) {
3636 $url = $menunode->get_url();
3637 } else {
3638 $url = '#cm_submenu_'.$submenucount;
3640 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3641 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3642 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3643 $content .= html_writer::start_tag('ul');
3644 foreach ($menunode->get_children() as $menunode) {
3645 $content .= $this->render_custom_menu_item($menunode);
3647 $content .= html_writer::end_tag('ul');
3648 $content .= html_writer::end_tag('div');
3649 $content .= html_writer::end_tag('div');
3650 $content .= html_writer::end_tag('li');
3651 } else {
3652 // The node doesn't have children so produce a final menuitem.
3653 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3654 $content = '';
3655 if (preg_match("/^#+$/", $menunode->get_text())) {
3657 // This is a divider.
3658 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3659 } else {
3660 $content = html_writer::start_tag(
3661 'li',
3662 array(
3663 'class' => 'yui3-menuitem'
3666 if ($menunode->get_url() !== null) {
3667 $url = $menunode->get_url();
3668 } else {
3669 $url = '#';
3671 $content .= html_writer::link(
3672 $url,
3673 $menunode->get_text(),
3674 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3677 $content .= html_writer::end_tag('li');
3679 // Return the sub menu
3680 return $content;
3684 * Renders theme links for switching between default and other themes.
3686 * @return string
3688 protected function theme_switch_links() {
3690 $actualdevice = core_useragent::get_device_type();
3691 $currentdevice = $this->page->devicetypeinuse;
3692 $switched = ($actualdevice != $currentdevice);
3694 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3695 // The user is using the a default device and hasn't switched so don't shown the switch
3696 // device links.
3697 return '';
3700 if ($switched) {
3701 $linktext = get_string('switchdevicerecommended');
3702 $devicetype = $actualdevice;
3703 } else {
3704 $linktext = get_string('switchdevicedefault');
3705 $devicetype = 'default';
3707 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3709 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3710 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3711 $content .= html_writer::end_tag('div');
3713 return $content;
3717 * Renders tabs
3719 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3721 * Theme developers: In order to change how tabs are displayed please override functions
3722 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3724 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3725 * @param string|null $selected which tab to mark as selected, all parent tabs will
3726 * automatically be marked as activated
3727 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3728 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3729 * @return string
3731 public final function tabtree($tabs, $selected = null, $inactive = null) {
3732 return $this->render(new tabtree($tabs, $selected, $inactive));
3736 * Renders tabtree
3738 * @param tabtree $tabtree
3739 * @return string
3741 protected function render_tabtree(tabtree $tabtree) {
3742 if (empty($tabtree->subtree)) {
3743 return '';
3745 $str = '';
3746 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
3747 $str .= $this->render_tabobject($tabtree);
3748 $str .= html_writer::end_tag('div').
3749 html_writer::tag('div', ' ', array('class' => 'clearer'));
3750 return $str;
3754 * Renders tabobject (part of tabtree)
3756 * This function is called from {@link core_renderer::render_tabtree()}
3757 * and also it calls itself when printing the $tabobject subtree recursively.
3759 * Property $tabobject->level indicates the number of row of tabs.
3761 * @param tabobject $tabobject
3762 * @return string HTML fragment
3764 protected function render_tabobject(tabobject $tabobject) {
3765 $str = '';
3767 // Print name of the current tab.
3768 if ($tabobject instanceof tabtree) {
3769 // No name for tabtree root.
3770 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3771 // Tab name without a link. The <a> tag is used for styling.
3772 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3773 } else {
3774 // Tab name with a link.
3775 if (!($tabobject->link instanceof moodle_url)) {
3776 // backward compartibility when link was passed as quoted string
3777 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3778 } else {
3779 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3783 if (empty($tabobject->subtree)) {
3784 if ($tabobject->selected) {
3785 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3787 return $str;
3790 // Print subtree.
3791 if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
3792 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3793 $cnt = 0;
3794 foreach ($tabobject->subtree as $tab) {
3795 $liclass = '';
3796 if (!$cnt) {
3797 $liclass .= ' first';
3799 if ($cnt == count($tabobject->subtree) - 1) {
3800 $liclass .= ' last';
3802 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3803 $liclass .= ' onerow';
3806 if ($tab->selected) {
3807 $liclass .= ' here selected';
3808 } else if ($tab->activated) {
3809 $liclass .= ' here active';
3812 // This will recursively call function render_tabobject() for each item in subtree.
3813 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3814 $cnt++;
3816 $str .= html_writer::end_tag('ul');
3819 return $str;
3823 * Get the HTML for blocks in the given region.
3825 * @since Moodle 2.5.1 2.6
3826 * @param string $region The region to get HTML for.
3827 * @return string HTML.
3829 public function blocks($region, $classes = array(), $tag = 'aside') {
3830 $displayregion = $this->page->apply_theme_region_manipulations($region);
3831 $classes = (array)$classes;
3832 $classes[] = 'block-region';
3833 $attributes = array(
3834 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3835 'class' => join(' ', $classes),
3836 'data-blockregion' => $displayregion,
3837 'data-droptarget' => '1'
3839 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3840 $content = $this->blocks_for_region($displayregion);
3841 } else {
3842 $content = '';
3844 return html_writer::tag($tag, $content, $attributes);
3848 * Renders a custom block region.
3850 * Use this method if you want to add an additional block region to the content of the page.
3851 * Please note this should only be used in special situations.
3852 * We want to leave the theme is control where ever possible!
3854 * This method must use the same method that the theme uses within its layout file.
3855 * As such it asks the theme what method it is using.
3856 * It can be one of two values, blocks or blocks_for_region (deprecated).
3858 * @param string $regionname The name of the custom region to add.
3859 * @return string HTML for the block region.
3861 public function custom_block_region($regionname) {
3862 if ($this->page->theme->get_block_render_method() === 'blocks') {
3863 return $this->blocks($regionname);
3864 } else {
3865 return $this->blocks_for_region($regionname);
3870 * Returns the CSS classes to apply to the body tag.
3872 * @since Moodle 2.5.1 2.6
3873 * @param array $additionalclasses Any additional classes to apply.
3874 * @return string
3876 public function body_css_classes(array $additionalclasses = array()) {
3877 // Add a class for each block region on the page.
3878 // We use the block manager here because the theme object makes get_string calls.
3879 $usedregions = array();
3880 foreach ($this->page->blocks->get_regions() as $region) {
3881 $additionalclasses[] = 'has-region-'.$region;
3882 if ($this->page->blocks->region_has_content($region, $this)) {
3883 $additionalclasses[] = 'used-region-'.$region;
3884 $usedregions[] = $region;
3885 } else {
3886 $additionalclasses[] = 'empty-region-'.$region;
3888 if ($this->page->blocks->region_completely_docked($region, $this)) {
3889 $additionalclasses[] = 'docked-region-'.$region;
3892 if (!$usedregions) {
3893 // No regions means there is only content, add 'content-only' class.
3894 $additionalclasses[] = 'content-only';
3895 } else if (count($usedregions) === 1) {
3896 // Add the -only class for the only used region.
3897 $region = array_shift($usedregions);
3898 $additionalclasses[] = $region . '-only';
3900 foreach ($this->page->layout_options as $option => $value) {
3901 if ($value) {
3902 $additionalclasses[] = 'layout-option-'.$option;
3905 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
3906 return $css;
3910 * The ID attribute to apply to the body tag.
3912 * @since Moodle 2.5.1 2.6
3913 * @return string
3915 public function body_id() {
3916 return $this->page->bodyid;
3920 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
3922 * @since Moodle 2.5.1 2.6
3923 * @param string|array $additionalclasses Any additional classes to give the body tag,
3924 * @return string
3926 public function body_attributes($additionalclasses = array()) {
3927 if (!is_array($additionalclasses)) {
3928 $additionalclasses = explode(' ', $additionalclasses);
3930 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
3934 * Gets HTML for the page heading.
3936 * @since Moodle 2.5.1 2.6
3937 * @param string $tag The tag to encase the heading in. h1 by default.
3938 * @return string HTML.
3940 public function page_heading($tag = 'h1') {
3941 return html_writer::tag($tag, $this->page->heading);
3945 * Gets the HTML for the page heading button.
3947 * @since Moodle 2.5.1 2.6
3948 * @return string HTML.
3950 public function page_heading_button() {
3951 return $this->page->button;
3955 * Returns the Moodle docs link to use for this page.
3957 * @since Moodle 2.5.1 2.6
3958 * @param string $text
3959 * @return string
3961 public function page_doc_link($text = null) {
3962 if ($text === null) {
3963 $text = get_string('moodledocslink');
3965 $path = page_get_doc_link_path($this->page);
3966 if (!$path) {
3967 return '';
3969 return $this->doc_link($path, $text);
3973 * Returns the page heading menu.
3975 * @since Moodle 2.5.1 2.6
3976 * @return string HTML.
3978 public function page_heading_menu() {
3979 return $this->page->headingmenu;
3983 * Returns the title to use on the page.
3985 * @since Moodle 2.5.1 2.6
3986 * @return string
3988 public function page_title() {
3989 return $this->page->title;
3993 * Returns the URL for the favicon.
3995 * @since Moodle 2.5.1 2.6
3996 * @return string The favicon URL
3998 public function favicon() {
3999 return $this->image_url('favicon', 'theme');
4003 * Renders preferences groups.
4005 * @param preferences_groups $renderable The renderable
4006 * @return string The output.
4008 public function render_preferences_groups(preferences_groups $renderable) {
4009 $html = '';
4010 $html .= html_writer::start_div('row-fluid');
4011 $html .= html_writer::start_tag('div', array('class' => 'span12 preferences-groups'));
4012 $i = 0;
4013 $open = false;
4014 foreach ($renderable->groups as $group) {
4015 if ($i == 0 || $i % 3 == 0) {
4016 if ($open) {
4017 $html .= html_writer::end_tag('div');
4019 $html .= html_writer::start_tag('div', array('class' => 'row-fluid'));
4020 $open = true;
4022 $html .= $this->render($group);
4023 $i++;
4026 $html .= html_writer::end_tag('div');
4028 $html .= html_writer::end_tag('ul');
4029 $html .= html_writer::end_tag('div');
4030 $html .= html_writer::end_div();
4031 return $html;
4035 * Renders preferences group.
4037 * @param preferences_group $renderable The renderable
4038 * @return string The output.
4040 public function render_preferences_group(preferences_group $renderable) {
4041 $html = '';
4042 $html .= html_writer::start_tag('div', array('class' => 'span4 preferences-group'));
4043 $html .= $this->heading($renderable->title, 3);
4044 $html .= html_writer::start_tag('ul');
4045 foreach ($renderable->nodes as $node) {
4046 if ($node->has_children()) {
4047 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4049 $html .= html_writer::tag('li', $this->render($node));
4051 $html .= html_writer::end_tag('ul');
4052 $html .= html_writer::end_tag('div');
4053 return $html;
4056 public function context_header($headerinfo = null, $headinglevel = 1) {
4057 global $DB, $USER, $CFG;
4058 require_once($CFG->dirroot . '/user/lib.php');
4059 $context = $this->page->context;
4060 $heading = null;
4061 $imagedata = null;
4062 $subheader = null;
4063 $userbuttons = null;
4064 // Make sure to use the heading if it has been set.
4065 if (isset($headerinfo['heading'])) {
4066 $heading = $headerinfo['heading'];
4068 // The user context currently has images and buttons. Other contexts may follow.
4069 if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
4070 if (isset($headerinfo['user'])) {
4071 $user = $headerinfo['user'];
4072 } else {
4073 // Look up the user information if it is not supplied.
4074 $user = $DB->get_record('user', array('id' => $context->instanceid));
4077 // If the user context is set, then use that for capability checks.
4078 if (isset($headerinfo['usercontext'])) {
4079 $context = $headerinfo['usercontext'];
4082 // Only provide user information if the user is the current user, or a user which the current user can view.
4083 // When checking user_can_view_profile(), either:
4084 // If the page context is course, check the course context (from the page object) or;
4085 // If page context is NOT course, then check across all courses.
4086 $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4088 if (user_can_view_profile($user, $course)) {
4089 // Use the user's full name if the heading isn't set.
4090 if (!isset($heading)) {
4091 $heading = fullname($user);
4094 $imagedata = $this->user_picture($user, array('size' => 100));
4096 // Check to see if we should be displaying a message button.
4097 if (!empty($CFG->messaging) && $USER->id != $user->id && has_capability('moodle/site:sendmessage', $context)) {
4098 $iscontact = !empty(message_get_contact($user->id));
4099 $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4100 $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4101 $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4102 $userbuttons = array(
4103 'messages' => array(
4104 'buttontype' => 'message',
4105 'title' => get_string('message', 'message'),
4106 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4107 'image' => 'message',
4108 'linkattributes' => array('role' => 'button'),
4109 'page' => $this->page
4111 'togglecontact' => array(
4112 'buttontype' => 'togglecontact',
4113 'title' => get_string($contacttitle, 'message'),
4114 'url' => new moodle_url('/message/index.php', array(
4115 'user1' => $USER->id,
4116 'user2' => $user->id,
4117 $contacturlaction => $user->id,
4118 'sesskey' => sesskey())
4120 'image' => $contactimage,
4121 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4122 'page' => $this->page
4126 $this->page->requires->string_for_js('changesmadereallygoaway', 'moodle');
4128 } else {
4129 $heading = null;
4133 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4134 return $this->render_context_header($contextheader);
4138 * Renders the skip links for the page.
4140 * @param array $links List of skip links.
4141 * @return string HTML for the skip links.
4143 public function render_skip_links($links) {
4144 $context = [ 'links' => []];
4146 foreach ($links as $url => $text) {
4147 $context['links'][] = [ 'url' => $url, 'text' => $text];
4150 return $this->render_from_template('core/skip_links', $context);
4154 * Renders the header bar.
4156 * @param context_header $contextheader Header bar object.
4157 * @return string HTML for the header bar.
4159 protected function render_context_header(context_header $contextheader) {
4161 // All the html stuff goes here.
4162 $html = html_writer::start_div('page-context-header');
4164 // Image data.
4165 if (isset($contextheader->imagedata)) {
4166 // Header specific image.
4167 $html .= html_writer::div($contextheader->imagedata, 'page-header-image');
4170 // Headings.
4171 if (!isset($contextheader->heading)) {
4172 $headings = $this->heading($this->page->heading, $contextheader->headinglevel);
4173 } else {
4174 $headings = $this->heading($contextheader->heading, $contextheader->headinglevel);
4177 $html .= html_writer::tag('div', $headings, array('class' => 'page-header-headings'));
4179 // Buttons.
4180 if (isset($contextheader->additionalbuttons)) {
4181 $html .= html_writer::start_div('btn-group header-button-group');
4182 foreach ($contextheader->additionalbuttons as $button) {
4183 if (!isset($button->page)) {
4184 // Include js for messaging.
4185 if ($button['buttontype'] === 'togglecontact') {
4186 \core_message\helper::togglecontact_requirejs();
4188 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4189 'class' => 'iconsmall',
4190 'role' => 'presentation'
4192 $image .= html_writer::span($button['title'], 'header-button-title');
4193 } else {
4194 $image = html_writer::empty_tag('img', array(
4195 'src' => $button['formattedimage'],
4196 'role' => 'presentation'
4199 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4201 $html .= html_writer::end_div();
4203 $html .= html_writer::end_div();
4205 return $html;
4209 * Wrapper for header elements.
4211 * @return string HTML to display the main header.
4213 public function full_header() {
4214 $html = html_writer::start_tag('header', array('id' => 'page-header', 'class' => 'clearfix'));
4215 $html .= $this->context_header();
4216 $html .= html_writer::start_div('clearfix', array('id' => 'page-navbar'));
4217 $html .= html_writer::tag('div', $this->navbar(), array('class' => 'breadcrumb-nav'));
4218 $html .= html_writer::div($this->page_heading_button(), 'breadcrumb-button');
4219 $html .= html_writer::end_div();
4220 $html .= html_writer::tag('div', $this->course_header(), array('id' => 'course-header'));
4221 $html .= html_writer::end_tag('header');
4222 return $html;
4226 * Displays the list of tags associated with an entry
4228 * @param array $tags list of instances of core_tag or stdClass
4229 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4230 * to use default, set to '' (empty string) to omit the label completely
4231 * @param string $classes additional classes for the enclosing div element
4232 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4233 * will be appended to the end, JS will toggle the rest of the tags
4234 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4235 * @return string
4237 public function tag_list($tags, $label = null, $classes = '', $limit = 10, $pagecontext = null) {
4238 $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext);
4239 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4243 * Renders element for inline editing of any value
4245 * @param \core\output\inplace_editable $element
4246 * @return string
4248 public function render_inplace_editable(\core\output\inplace_editable $element) {
4249 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4253 * Renders a bar chart.
4255 * @param \core\chart_bar $chart The chart.
4256 * @return string.
4258 public function render_chart_bar(\core\chart_bar $chart) {
4259 return $this->render_chart($chart);
4263 * Renders a line chart.
4265 * @param \core\chart_line $chart The chart.
4266 * @return string.
4268 public function render_chart_line(\core\chart_line $chart) {
4269 return $this->render_chart($chart);
4273 * Renders a pie chart.
4275 * @param \core\chart_pie $chart The chart.
4276 * @return string.
4278 public function render_chart_pie(\core\chart_pie $chart) {
4279 return $this->render_chart($chart);
4283 * Renders a chart.
4285 * @param \core\chart_base $chart The chart.
4286 * @param bool $withtable Whether to include a data table with the chart.
4287 * @return string.
4289 public function render_chart(\core\chart_base $chart, $withtable = true) {
4290 $chartdata = json_encode($chart);
4291 return $this->render_from_template('core/chart', (object) [
4292 'chartdata' => $chartdata,
4293 'withtable' => $withtable
4298 * Renders the login form.
4300 * @param \core_auth\output\login $form The renderable.
4301 * @return string
4303 public function render_login(\core_auth\output\login $form) {
4304 $context = $form->export_for_template($this);
4306 // Override because rendering is not supported in template yet.
4307 $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
4308 $context->errorformatted = $this->error_text($context->error);
4310 return $this->render_from_template('core/login', $context);
4314 * Renders an mform element from a template.
4316 * @param HTML_QuickForm_element $element element
4317 * @param bool $required if input is required field
4318 * @param bool $advanced if input is an advanced field
4319 * @param string $error error message to display
4320 * @param bool $ingroup True if this element is rendered as part of a group
4321 * @return mixed string|bool
4323 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4324 $templatename = 'core_form/element-' . $element->getType();
4325 if ($ingroup) {
4326 $templatename .= "-inline";
4328 try {
4329 // We call this to generate a file not found exception if there is no template.
4330 // We don't want to call export_for_template if there is no template.
4331 core\output\mustache_template_finder::get_template_filepath($templatename);
4333 if ($element instanceof templatable) {
4334 $elementcontext = $element->export_for_template($this);
4336 $helpbutton = '';
4337 if (method_exists($element, 'getHelpButton')) {
4338 $helpbutton = $element->getHelpButton();
4340 $label = $element->getLabel();
4341 $text = '';
4342 if (method_exists($element, 'getText')) {
4343 // There currently exists code that adds a form element with an empty label.
4344 // If this is the case then set the label to the description.
4345 if (empty($label)) {
4346 $label = $element->getText();
4347 } else {
4348 $text = $element->getText();
4352 $context = array(
4353 'element' => $elementcontext,
4354 'label' => $label,
4355 'text' => $text,
4356 'required' => $required,
4357 'advanced' => $advanced,
4358 'helpbutton' => $helpbutton,
4359 'error' => $error
4361 return $this->render_from_template($templatename, $context);
4363 } catch (Exception $e) {
4364 // No template for this element.
4365 return false;
4370 * Render the login signup form into a nice template for the theme.
4372 * @param mform $form
4373 * @return string
4375 public function render_login_signup_form($form) {
4376 $context = $form->export_for_template($this);
4378 return $this->render_from_template('core/signup_form_layout', $context);
4382 * Renders a progress bar.
4384 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4386 * @param progress_bar $bar The bar.
4387 * @return string HTML fragment
4389 public function render_progress_bar(progress_bar $bar) {
4390 global $PAGE;
4391 $data = $bar->export_for_template($this);
4392 return $this->render_from_template('core/progress_bar', $data);
4397 * A renderer that generates output for command-line scripts.
4399 * The implementation of this renderer is probably incomplete.
4401 * @copyright 2009 Tim Hunt
4402 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4403 * @since Moodle 2.0
4404 * @package core
4405 * @category output
4407 class core_renderer_cli extends core_renderer {
4410 * Returns the page header.
4412 * @return string HTML fragment
4414 public function header() {
4415 return $this->page->heading . "\n";
4419 * Returns a template fragment representing a Heading.
4421 * @param string $text The text of the heading
4422 * @param int $level The level of importance of the heading
4423 * @param string $classes A space-separated list of CSS classes
4424 * @param string $id An optional ID
4425 * @return string A template fragment for a heading
4427 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4428 $text .= "\n";
4429 switch ($level) {
4430 case 1:
4431 return '=>' . $text;
4432 case 2:
4433 return '-->' . $text;
4434 default:
4435 return $text;
4440 * Returns a template fragment representing a fatal error.
4442 * @param string $message The message to output
4443 * @param string $moreinfourl URL where more info can be found about the error
4444 * @param string $link Link for the Continue button
4445 * @param array $backtrace The execution backtrace
4446 * @param string $debuginfo Debugging information
4447 * @return string A template fragment for a fatal error
4449 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4450 global $CFG;
4452 $output = "!!! $message !!!\n";
4454 if ($CFG->debugdeveloper) {
4455 if (!empty($debuginfo)) {
4456 $output .= $this->notification($debuginfo, 'notifytiny');
4458 if (!empty($backtrace)) {
4459 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
4463 return $output;
4467 * Returns a template fragment representing a notification.
4469 * @param string $message The message to print out.
4470 * @param string $type The type of notification. See constants on \core\output\notification.
4471 * @return string A template fragment for a notification
4473 public function notification($message, $type = null) {
4474 $message = clean_text($message);
4475 if ($type === 'notifysuccess' || $type === 'success') {
4476 return "++ $message ++\n";
4478 return "!! $message !!\n";
4482 * There is no footer for a cli request, however we must override the
4483 * footer method to prevent the default footer.
4485 public function footer() {}
4488 * Render a notification (that is, a status message about something that has
4489 * just happened).
4491 * @param \core\output\notification $notification the notification to print out
4492 * @return string plain text output
4494 public function render_notification(\core\output\notification $notification) {
4495 return $this->notification($notification->get_message(), $notification->get_message_type());
4501 * A renderer that generates output for ajax scripts.
4503 * This renderer prevents accidental sends back only json
4504 * encoded error messages, all other output is ignored.
4506 * @copyright 2010 Petr Skoda
4507 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4508 * @since Moodle 2.0
4509 * @package core
4510 * @category output
4512 class core_renderer_ajax extends core_renderer {
4515 * Returns a template fragment representing a fatal error.
4517 * @param string $message The message to output
4518 * @param string $moreinfourl URL where more info can be found about the error
4519 * @param string $link Link for the Continue button
4520 * @param array $backtrace The execution backtrace
4521 * @param string $debuginfo Debugging information
4522 * @return string A template fragment for a fatal error
4524 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4525 global $CFG;
4527 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
4529 $e = new stdClass();
4530 $e->error = $message;
4531 $e->errorcode = $errorcode;
4532 $e->stacktrace = NULL;
4533 $e->debuginfo = NULL;
4534 $e->reproductionlink = NULL;
4535 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
4536 $link = (string) $link;
4537 if ($link) {
4538 $e->reproductionlink = $link;
4540 if (!empty($debuginfo)) {
4541 $e->debuginfo = $debuginfo;
4543 if (!empty($backtrace)) {
4544 $e->stacktrace = format_backtrace($backtrace, true);
4547 $this->header();
4548 return json_encode($e);
4552 * Used to display a notification.
4553 * For the AJAX notifications are discarded.
4555 * @param string $message The message to print out.
4556 * @param string $type The type of notification. See constants on \core\output\notification.
4558 public function notification($message, $type = null) {}
4561 * Used to display a redirection message.
4562 * AJAX redirections should not occur and as such redirection messages
4563 * are discarded.
4565 * @param moodle_url|string $encodedurl
4566 * @param string $message
4567 * @param int $delay
4568 * @param bool $debugdisableredirect
4569 * @param string $messagetype The type of notification to show the message in.
4570 * See constants on \core\output\notification.
4572 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
4573 $messagetype = \core\output\notification::NOTIFY_INFO) {}
4576 * Prepares the start of an AJAX output.
4578 public function header() {
4579 // unfortunately YUI iframe upload does not support application/json
4580 if (!empty($_FILES)) {
4581 @header('Content-type: text/plain; charset=utf-8');
4582 if (!core_useragent::supports_json_contenttype()) {
4583 @header('X-Content-Type-Options: nosniff');
4585 } else if (!core_useragent::supports_json_contenttype()) {
4586 @header('Content-type: text/plain; charset=utf-8');
4587 @header('X-Content-Type-Options: nosniff');
4588 } else {
4589 @header('Content-type: application/json; charset=utf-8');
4592 // Headers to make it not cacheable and json
4593 @header('Cache-Control: no-store, no-cache, must-revalidate');
4594 @header('Cache-Control: post-check=0, pre-check=0', false);
4595 @header('Pragma: no-cache');
4596 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
4597 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
4598 @header('Accept-Ranges: none');
4602 * There is no footer for an AJAX request, however we must override the
4603 * footer method to prevent the default footer.
4605 public function footer() {}
4608 * No need for headers in an AJAX request... this should never happen.
4609 * @param string $text
4610 * @param int $level
4611 * @param string $classes
4612 * @param string $id
4614 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
4619 * Renderer for media files.
4621 * Used in file resources, media filter, and any other places that need to
4622 * output embedded media.
4624 * @deprecated since Moodle 3.2
4625 * @copyright 2011 The Open University
4626 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4628 class core_media_renderer extends plugin_renderer_base {
4629 /** @var array Array of available 'player' objects */
4630 private $players;
4631 /** @var string Regex pattern for links which may contain embeddable content */
4632 private $embeddablemarkers;
4635 * Constructor
4637 * This is needed in the constructor (not later) so that you can use the
4638 * constants and static functions that are defined in core_media class
4639 * before you call renderer functions.
4641 public function __construct() {
4642 debugging('Class core_media_renderer is deprecated, please use core_media_manager::instance()', DEBUG_DEVELOPER);
4646 * Renders a media file (audio or video) using suitable embedded player.
4648 * See embed_alternatives function for full description of parameters.
4649 * This function calls through to that one.
4651 * When using this function you can also specify width and height in the
4652 * URL by including ?d=100x100 at the end. If specified in the URL, this
4653 * will override the $width and $height parameters.
4655 * @param moodle_url $url Full URL of media file
4656 * @param string $name Optional user-readable name to display in download link
4657 * @param int $width Width in pixels (optional)
4658 * @param int $height Height in pixels (optional)
4659 * @param array $options Array of key/value pairs
4660 * @return string HTML content of embed
4662 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
4663 $options = array()) {
4664 return core_media_manager::instance()->embed_url($url, $name, $width, $height, $options);
4668 * Renders media files (audio or video) using suitable embedded player.
4669 * The list of URLs should be alternative versions of the same content in
4670 * multiple formats. If there is only one format it should have a single
4671 * entry.
4673 * If the media files are not in a supported format, this will give students
4674 * a download link to each format. The download link uses the filename
4675 * unless you supply the optional name parameter.
4677 * Width and height are optional. If specified, these are suggested sizes
4678 * and should be the exact values supplied by the user, if they come from
4679 * user input. These will be treated as relating to the size of the video
4680 * content, not including any player control bar.
4682 * For audio files, height will be ignored. For video files, a few formats
4683 * work if you specify only width, but in general if you specify width
4684 * you must specify height as well.
4686 * The $options array is passed through to the core_media_player classes
4687 * that render the object tag. The keys can contain values from
4688 * core_media::OPTION_xx.
4690 * @param array $alternatives Array of moodle_url to media files
4691 * @param string $name Optional user-readable name to display in download link
4692 * @param int $width Width in pixels (optional)
4693 * @param int $height Height in pixels (optional)
4694 * @param array $options Array of key/value pairs
4695 * @return string HTML content of embed
4697 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
4698 $options = array()) {
4699 return core_media_manager::instance()->embed_alternatives($alternatives, $name, $width, $height, $options);
4703 * Checks whether a file can be embedded. If this returns true you will get
4704 * an embedded player; if this returns false, you will just get a download
4705 * link.
4707 * This is a wrapper for can_embed_urls.
4709 * @param moodle_url $url URL of media file
4710 * @param array $options Options (same as when embedding)
4711 * @return bool True if file can be embedded
4713 public function can_embed_url(moodle_url $url, $options = array()) {
4714 return core_media_manager::instance()->can_embed_url($url, $options);
4718 * Checks whether a file can be embedded. If this returns true you will get
4719 * an embedded player; if this returns false, you will just get a download
4720 * link.
4722 * @param array $urls URL of media file and any alternatives (moodle_url)
4723 * @param array $options Options (same as when embedding)
4724 * @return bool True if file can be embedded
4726 public function can_embed_urls(array $urls, $options = array()) {
4727 return core_media_manager::instance()->can_embed_urls($urls, $options);
4731 * Obtains a list of markers that can be used in a regular expression when
4732 * searching for URLs that can be embedded by any player type.
4734 * This string is used to improve peformance of regex matching by ensuring
4735 * that the (presumably C) regex code can do a quick keyword check on the
4736 * URL part of a link to see if it matches one of these, rather than having
4737 * to go into PHP code for every single link to see if it can be embedded.
4739 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
4741 public function get_embeddable_markers() {
4742 return core_media_manager::instance()->get_embeddable_markers();
4747 * The maintenance renderer.
4749 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
4750 * is running a maintenance related task.
4751 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
4753 * @since Moodle 2.6
4754 * @package core
4755 * @category output
4756 * @copyright 2013 Sam Hemelryk
4757 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4759 class core_renderer_maintenance extends core_renderer {
4762 * Initialises the renderer instance.
4763 * @param moodle_page $page
4764 * @param string $target
4765 * @throws coding_exception
4767 public function __construct(moodle_page $page, $target) {
4768 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
4769 throw new coding_exception('Invalid request for the maintenance renderer.');
4771 parent::__construct($page, $target);
4775 * Does nothing. The maintenance renderer cannot produce blocks.
4777 * @param block_contents $bc
4778 * @param string $region
4779 * @return string
4781 public function block(block_contents $bc, $region) {
4782 // Computer says no blocks.
4783 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4784 return '';
4788 * Does nothing. The maintenance renderer cannot produce blocks.
4790 * @param string $region
4791 * @param array $classes
4792 * @param string $tag
4793 * @return string
4795 public function blocks($region, $classes = array(), $tag = 'aside') {
4796 // Computer says no blocks.
4797 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4798 return '';
4802 * Does nothing. The maintenance renderer cannot produce blocks.
4804 * @param string $region
4805 * @return string
4807 public function blocks_for_region($region) {
4808 // Computer says no blocks for region.
4809 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4810 return '';
4814 * Does nothing. The maintenance renderer cannot produce a course content header.
4816 * @param bool $onlyifnotcalledbefore
4817 * @return string
4819 public function course_content_header($onlyifnotcalledbefore = false) {
4820 // Computer says no course content header.
4821 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4822 return '';
4826 * Does nothing. The maintenance renderer cannot produce a course content footer.
4828 * @param bool $onlyifnotcalledbefore
4829 * @return string
4831 public function course_content_footer($onlyifnotcalledbefore = false) {
4832 // Computer says no course content footer.
4833 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4834 return '';
4838 * Does nothing. The maintenance renderer cannot produce a course header.
4840 * @return string
4842 public function course_header() {
4843 // Computer says no course header.
4844 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4845 return '';
4849 * Does nothing. The maintenance renderer cannot produce a course footer.
4851 * @return string
4853 public function course_footer() {
4854 // Computer says no course footer.
4855 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4856 return '';
4860 * Does nothing. The maintenance renderer cannot produce a custom menu.
4862 * @param string $custommenuitems
4863 * @return string
4865 public function custom_menu($custommenuitems = '') {
4866 // Computer says no custom menu.
4867 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4868 return '';
4872 * Does nothing. The maintenance renderer cannot produce a file picker.
4874 * @param array $options
4875 * @return string
4877 public function file_picker($options) {
4878 // Computer says no file picker.
4879 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4880 return '';
4884 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
4886 * @param array $dir
4887 * @return string
4889 public function htmllize_file_tree($dir) {
4890 // Hell no we don't want no htmllized file tree.
4891 // Also why on earth is this function on the core renderer???
4892 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4893 return '';
4898 * Overridden confirm message for upgrades.
4900 * @param string $message The question to ask the user
4901 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
4902 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
4903 * @return string HTML fragment
4905 public function confirm($message, $continue, $cancel) {
4906 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
4907 // from any previous version of Moodle).
4908 if ($continue instanceof single_button) {
4909 $continue->primary = true;
4910 } else if (is_string($continue)) {
4911 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
4912 } else if ($continue instanceof moodle_url) {
4913 $continue = new single_button($continue, get_string('continue'), 'post', true);
4914 } else {
4915 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
4916 ' (string/moodle_url) or a single_button instance.');
4919 if ($cancel instanceof single_button) {
4920 $output = '';
4921 } else if (is_string($cancel)) {
4922 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
4923 } else if ($cancel instanceof moodle_url) {
4924 $cancel = new single_button($cancel, get_string('cancel'), 'get');
4925 } else {
4926 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
4927 ' (string/moodle_url) or a single_button instance.');
4930 $output = $this->box_start('generalbox', 'notice');
4931 $output .= html_writer::tag('h4', get_string('confirm'));
4932 $output .= html_writer::tag('p', $message);
4933 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
4934 $output .= $this->box_end();
4935 return $output;
4939 * Does nothing. The maintenance renderer does not support JS.
4941 * @param block_contents $bc
4943 public function init_block_hider_js(block_contents $bc) {
4944 // Computer says no JavaScript.
4945 // Do nothing, ridiculous method.
4949 * Does nothing. The maintenance renderer cannot produce language menus.
4951 * @return string
4953 public function lang_menu() {
4954 // Computer says no lang menu.
4955 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4956 return '';
4960 * Does nothing. The maintenance renderer has no need for login information.
4962 * @param null $withlinks
4963 * @return string
4965 public function login_info($withlinks = null) {
4966 // Computer says no login info.
4967 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4968 return '';
4972 * Does nothing. The maintenance renderer cannot produce user pictures.
4974 * @param stdClass $user
4975 * @param array $options
4976 * @return string
4978 public function user_picture(stdClass $user, array $options = null) {
4979 // Computer says no user pictures.
4980 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4981 return '';