2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
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
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') ||
die();
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
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
65 * @var string The requested rendering target.
70 * @var Mustache_Engine $mustache The mustache template compiler
75 * Return an instance of the mustache class.
78 * @return Mustache_Engine
80 protected function get_mustache() {
83 if ($this->mustache
=== null) {
84 require_once("{$CFG->libdir}/filelib.php");
86 $themename = $this->page
->theme
->name
;
87 $themerev = theme_get_revision();
89 // Create new localcache directory.
90 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
92 // Remove old localcache directories.
93 $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR
);
94 foreach ($mustachecachedirs as $localcachedir) {
96 preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
97 $cachedrev = isset($cachedrev[1]) ?
intval($cachedrev[1]) : 0;
98 if ($cachedrev > 0 && $cachedrev < $themerev) {
99 fulldelete($localcachedir);
103 $loader = new \core\output\
mustache_filesystem_loader();
104 $stringhelper = new \core\output\
mustache_string_helper();
105 $quotehelper = new \core\output\
mustache_quote_helper();
106 $jshelper = new \core\output\
mustache_javascript_helper($this->page
);
107 $pixhelper = new \core\output\
mustache_pix_helper($this);
108 $shortentexthelper = new \core\output\
mustache_shorten_text_helper();
109 $userdatehelper = new \core\output\
mustache_user_date_helper();
111 // We only expose the variables that are exposed to JS templates.
112 $safeconfig = $this->page
->requires
->get_config_for_javascript($this->page
, $this);
114 $helpers = array('config' => $safeconfig,
115 'str' => array($stringhelper, 'str'),
116 'quote' => array($quotehelper, 'quote'),
117 'js' => array($jshelper, 'help'),
118 'pix' => array($pixhelper, 'pix'),
119 'shortentext' => array($shortentexthelper, 'shorten'),
120 'userdate' => array($userdatehelper, 'transform'),
123 $this->mustache
= new \core\output\
mustache_engine(array(
124 'cache' => $cachedir,
127 'helpers' => $helpers,
128 'pragmas' => [Mustache_Engine
::PRAGMA_BLOCKS
],
129 // Don't allow the JavaScript helper to be executed from within another
130 // helper. If it's allowed it can be used by users to inject malicious
132 'blacklistednestedhelpers' => ['js']));
136 return $this->mustache
;
143 * The constructor takes two arguments. The first is the page that the renderer
144 * has been created to assist with, and the second is the target.
145 * The target is an additional identifier that can be used to load different
146 * renderers for different options.
148 * @param moodle_page $page the page we are doing output for.
149 * @param string $target one of rendering target constants
151 public function __construct(moodle_page
$page, $target) {
152 $this->opencontainers
= $page->opencontainers
;
154 $this->target
= $target;
158 * Renders a template by name with the given context.
160 * The provided data needs to be array/stdClass made up of only simple types.
161 * Simple types are array,stdClass,bool,int,float,string
164 * @param array|stdClass $context Context containing data for the template.
165 * @return string|boolean
167 public function render_from_template($templatename, $context) {
168 static $templatecache = array();
169 $mustache = $this->get_mustache();
172 // Grab a copy of the existing helper to be restored later.
173 $uniqidhelper = $mustache->getHelper('uniqid');
174 } catch (Mustache_Exception_UnknownHelperException
$e) {
175 // Helper doesn't exist.
176 $uniqidhelper = null;
179 // Provide 1 random value that will not change within a template
180 // but will be different from template to template. This is useful for
181 // e.g. aria attributes that only work with id attributes and must be
183 $mustache->addHelper('uniqid', new \core\output\
mustache_uniqid_helper());
184 if (isset($templatecache[$templatename])) {
185 $template = $templatecache[$templatename];
188 $template = $mustache->loadTemplate($templatename);
189 $templatecache[$templatename] = $template;
190 } catch (Mustache_Exception_UnknownTemplateException
$e) {
191 throw new moodle_exception('Unknown template: ' . $templatename);
195 $renderedtemplate = trim($template->render($context));
197 // If we had an existing uniqid helper then we need to restore it to allow
198 // handle nested calls of render_from_template.
200 $mustache->addHelper('uniqid', $uniqidhelper);
203 return $renderedtemplate;
208 * Returns rendered widget.
210 * The provided widget needs to be an object that extends the renderable
212 * If will then be rendered by a method based upon the classname for the widget.
213 * For instance a widget of class `crazywidget` will be rendered by a protected
214 * render_crazywidget method of this renderer.
215 * If no render_crazywidget method exists and crazywidget implements templatable,
216 * look for the 'crazywidget' template in the same component and render that.
218 * @param renderable $widget instance with renderable interface
221 public function render(renderable
$widget) {
222 $classparts = explode('\\', get_class($widget));
224 $classname = array_pop($classparts);
225 // Remove _renderable suffixes
226 $classname = preg_replace('/_renderable$/', '', $classname);
228 $rendermethod = 'render_'.$classname;
229 if (method_exists($this, $rendermethod)) {
230 return $this->$rendermethod($widget);
232 if ($widget instanceof templatable
) {
233 $component = array_shift($classparts);
237 $template = $component . '/' . $classname;
238 $context = $widget->export_for_template($this);
239 return $this->render_from_template($template, $context);
241 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
245 * Adds a JS action for the element with the provided id.
247 * This method adds a JS event for the provided component action to the page
248 * and then returns the id that the event has been attached to.
249 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
251 * @param component_action $action
253 * @return string id of element, either original submitted or random new if not supplied
255 public function add_action_handler(component_action
$action, $id = null) {
257 $id = html_writer
::random_id($action->event
);
259 $this->page
->requires
->event_handler("#$id", $action->event
, $action->jsfunction
, $action->jsfunctionargs
);
264 * Returns true is output has already started, and false if not.
266 * @return boolean true if the header has been printed.
268 public function has_started() {
269 return $this->page
->state
>= moodle_page
::STATE_IN_BODY
;
273 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
275 * @param mixed $classes Space-separated string or array of classes
276 * @return string HTML class attribute value
278 public static function prepare_classes($classes) {
279 if (is_array($classes)) {
280 return implode(' ', array_unique($classes));
286 * Return the direct URL for an image from the pix folder.
288 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
290 * @deprecated since Moodle 3.3
291 * @param string $imagename the name of the icon.
292 * @param string $component specification of one plugin like in get_string()
295 public function pix_url($imagename, $component = 'moodle') {
296 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER
);
297 return $this->page
->theme
->image_url($imagename, $component);
301 * Return the moodle_url for an image.
303 * The exact image location and extension is determined
304 * automatically by searching for gif|png|jpg|jpeg, please
305 * note there can not be diferent images with the different
306 * extension. The imagename is for historical reasons
307 * a relative path name, it may be changed later for core
308 * images. It is recommended to not use subdirectories
309 * in plugin and theme pix directories.
311 * There are three types of images:
312 * 1/ theme images - stored in theme/mytheme/pix/,
313 * use component 'theme'
314 * 2/ core images - stored in /pix/,
315 * overridden via theme/mytheme/pix_core/
316 * 3/ plugin images - stored in mod/mymodule/pix,
317 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
318 * example: image_url('comment', 'mod_glossary')
320 * @param string $imagename the pathname of the image
321 * @param string $component full plugin name (aka component) or 'theme'
324 public function image_url($imagename, $component = 'moodle') {
325 return $this->page
->theme
->image_url($imagename, $component);
329 * Return the site's logo URL, if any.
331 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
332 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
333 * @return moodle_url|false
335 public function get_logo_url($maxwidth = null, $maxheight = 200) {
337 $logo = get_config('core_admin', 'logo');
342 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
343 // It's not worth the overhead of detecting and serving 2 different images based on the device.
345 // Hide the requested size in the file path.
346 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
348 // Use $CFG->themerev to prevent browser caching when the file changes.
349 return moodle_url
::make_pluginfile_url(context_system
::instance()->id
, 'core_admin', 'logo', $filepath,
350 theme_get_revision(), $logo);
354 * Return the site's compact logo URL, if any.
356 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
357 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
358 * @return moodle_url|false
360 public function get_compact_logo_url($maxwidth = 100, $maxheight = 100) {
362 $logo = get_config('core_admin', 'logocompact');
367 // Hide the requested size in the file path.
368 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
370 // Use $CFG->themerev to prevent browser caching when the file changes.
371 return moodle_url
::make_pluginfile_url(context_system
::instance()->id
, 'core_admin', 'logocompact', $filepath,
372 theme_get_revision(), $logo);
376 * Whether we should display the logo in the navbar.
378 * We will when there are no main logos, and we have compact logo.
382 public function should_display_navbar_logo() {
383 $logo = $this->get_compact_logo_url();
384 return !empty($logo) && !$this->should_display_main_logo();
388 * Whether we should display the main logo.
390 * @param int $headinglevel The heading level we want to check against.
393 public function should_display_main_logo($headinglevel = 1) {
396 // Only render the logo if we're on the front page or login page and the we have a logo.
397 $logo = $this->get_logo_url();
398 if ($headinglevel == 1 && !empty($logo)) {
399 if ($PAGE->pagelayout
== 'frontpage' ||
$PAGE->pagelayout
== 'login') {
411 * Basis for all plugin renderers.
413 * @copyright Petr Skoda (skodak)
414 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
419 class plugin_renderer_base
extends renderer_base
{
422 * @var renderer_base|core_renderer A reference to the current renderer.
423 * The renderer provided here will be determined by the page but will in 90%
424 * of cases by the {@link core_renderer}
429 * Constructor method, calls the parent constructor
431 * @param moodle_page $page
432 * @param string $target one of rendering target constants
434 public function __construct(moodle_page
$page, $target) {
435 if (empty($target) && $page->pagelayout
=== 'maintenance') {
436 // If the page is using the maintenance layout then we're going to force the target to maintenance.
437 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
438 // unavailable for this page layout.
439 $target = RENDERER_TARGET_MAINTENANCE
;
441 $this->output
= $page->get_renderer('core', null, $target);
442 parent
::__construct($page, $target);
446 * Renders the provided widget and returns the HTML to display it.
448 * @param renderable $widget instance with renderable interface
451 public function render(renderable
$widget) {
452 $classname = get_class($widget);
454 $classname = preg_replace('/^.*\\\/', '', $classname);
455 // Keep a copy at this point, we may need to look for a deprecated method.
456 $deprecatedmethod = 'render_'.$classname;
457 // Remove _renderable suffixes
458 $classname = preg_replace('/_renderable$/', '', $classname);
460 $rendermethod = 'render_'.$classname;
461 if (method_exists($this, $rendermethod)) {
462 return $this->$rendermethod($widget);
464 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
465 // This is exactly where we don't want to be.
466 // If you have arrived here you have a renderable component within your plugin that has the name
467 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
468 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
469 // and the _renderable suffix now gets removed when looking for a render method.
470 // You need to change your renderers render_blah_renderable to render_blah.
471 // Until you do this it will not be possible for a theme to override the renderer to override your method.
472 // Please do it ASAP.
473 static $debugged = array();
474 if (!isset($debugged[$deprecatedmethod])) {
475 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
476 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER
);
477 $debugged[$deprecatedmethod] = true;
479 return $this->$deprecatedmethod($widget);
481 // pass to core renderer if method not found here
482 return $this->output
->render($widget);
486 * Magic method used to pass calls otherwise meant for the standard renderer
487 * to it to ensure we don't go causing unnecessary grief.
489 * @param string $method
490 * @param array $arguments
493 public function __call($method, $arguments) {
494 if (method_exists('renderer_base', $method)) {
495 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
497 if (method_exists($this->output
, $method)) {
498 return call_user_func_array(array($this->output
, $method), $arguments);
500 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
507 * The standard implementation of the core_renderer interface.
509 * @copyright 2009 Tim Hunt
510 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
515 class core_renderer
extends renderer_base
{
517 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
518 * in layout files instead.
520 * @var string used in {@link core_renderer::header()}.
522 const MAIN_CONTENT_TOKEN
= '[MAIN CONTENT GOES HERE]';
525 * @var string Used to pass information from {@link core_renderer::doctype()} to
526 * {@link core_renderer::standard_head_html()}.
528 protected $contenttype;
531 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
532 * with {@link core_renderer::header()}.
534 protected $metarefreshtag = '';
537 * @var string Unique token for the closing HTML
539 protected $unique_end_html_token;
542 * @var string Unique token for performance information
544 protected $unique_performance_info_token;
547 * @var string Unique token for the main content.
549 protected $unique_main_content_token;
551 /** @var custom_menu_item language The language menu if created */
552 protected $language = null;
557 * @param moodle_page $page the page we are doing output for.
558 * @param string $target one of rendering target constants
560 public function __construct(moodle_page
$page, $target) {
561 $this->opencontainers
= $page->opencontainers
;
563 $this->target
= $target;
565 $this->unique_end_html_token
= '%%ENDHTML-'.sesskey().'%%';
566 $this->unique_performance_info_token
= '%%PERFORMANCEINFO-'.sesskey().'%%';
567 $this->unique_main_content_token
= '[MAIN CONTENT GOES HERE - '.sesskey().']';
571 * Get the DOCTYPE declaration that should be used with this page. Designed to
572 * be called in theme layout.php files.
574 * @return string the DOCTYPE declaration that should be used.
576 public function doctype() {
577 if ($this->page
->theme
->doctype
=== 'html5') {
578 $this->contenttype
= 'text/html; charset=utf-8';
579 return "<!DOCTYPE html>\n";
581 } else if ($this->page
->theme
->doctype
=== 'xhtml5') {
582 $this->contenttype
= 'application/xhtml+xml; charset=utf-8';
583 return "<!DOCTYPE html>\n";
587 $this->contenttype
= 'text/html; charset=utf-8';
588 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
593 * The attributes that should be added to the <html> tag. Designed to
594 * be called in theme layout.php files.
596 * @return string HTML fragment.
598 public function htmlattributes() {
599 $return = get_html_lang(true);
600 $attributes = array();
601 if ($this->page
->theme
->doctype
!== 'html5') {
602 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
605 // Give plugins an opportunity to add things like xml namespaces to the html element.
606 // This function should return an array of html attribute names => values.
607 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
608 foreach ($pluginswithfunction as $plugins) {
609 foreach ($plugins as $function) {
610 $newattrs = $function();
611 unset($newattrs['dir']);
612 unset($newattrs['lang']);
613 unset($newattrs['xmlns']);
614 unset($newattrs['xml:lang']);
615 $attributes +
= $newattrs;
619 foreach ($attributes as $key => $val) {
621 $return .= " $key=\"$val\"";
628 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
629 * that should be included in the <head> tag. Designed to be called in theme
632 * @return string HTML fragment.
634 public function standard_head_html() {
635 global $CFG, $SESSION, $SITE, $PAGE;
637 // Before we output any content, we need to ensure that certain
638 // page components are set up.
640 // Blocks must be set up early as they may require javascript which
641 // has to be included in the page header before output is created.
642 foreach ($this->page
->blocks
->get_regions() as $region) {
643 $this->page
->blocks
->ensure_content_created($region, $this);
648 // Give plugins an opportunity to add any head elements. The callback
649 // must always return a string containing valid html head content.
650 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
651 foreach ($pluginswithfunction as $plugins) {
652 foreach ($plugins as $function) {
653 $output .= $function();
657 // Allow a url_rewrite plugin to setup any dynamic head content.
658 if (isset($CFG->urlrewriteclass
) && !isset($CFG->upgraderunning
)) {
659 $class = $CFG->urlrewriteclass
;
660 $output .= $class::html_head_setup();
663 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
664 $output .= '<meta name="keywords" content="moodle, ' . $this->page
->title
. '" />' . "\n";
665 // This is only set by the {@link redirect()} method
666 $output .= $this->metarefreshtag
;
668 // Check if a periodic refresh delay has been set and make sure we arn't
669 // already meta refreshing
670 if ($this->metarefreshtag
=='' && $this->page
->periodicrefreshdelay
!==null) {
671 $output .= '<meta http-equiv="refresh" content="'.$this->page
->periodicrefreshdelay
.';url='.$this->page
->url
->out().'" />';
674 // Set up help link popups for all links with the helptooltip class
675 $this->page
->requires
->js_init_call('M.util.help_popups.setup');
677 $focus = $this->page
->focuscontrol
;
678 if (!empty($focus)) {
679 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
680 // This is a horrifically bad way to handle focus but it is passed in
681 // through messy formslib::moodleform
682 $this->page
->requires
->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
683 } else if (strpos($focus, '.')!==false) {
684 // Old style of focus, bad way to do it
685 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
);
686 $this->page
->requires
->js_function_call('old_onload_focus', explode('.', $focus, 2));
688 // Focus element with given id
689 $this->page
->requires
->js_function_call('focuscontrol', array($focus));
693 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
694 // any other custom CSS can not be overridden via themes and is highly discouraged
695 $urls = $this->page
->theme
->css_urls($this->page
);
696 foreach ($urls as $url) {
697 $this->page
->requires
->css_theme($url);
700 // Get the theme javascript head and footer
701 if ($jsurl = $this->page
->theme
->javascript_url(true)) {
702 $this->page
->requires
->js($jsurl, true);
704 if ($jsurl = $this->page
->theme
->javascript_url(false)) {
705 $this->page
->requires
->js($jsurl);
708 // Get any HTML from the page_requirements_manager.
709 $output .= $this->page
->requires
->get_head_code($this->page
, $this);
711 // List alternate versions.
712 foreach ($this->page
->alternateversions
as $type => $alt) {
713 $output .= html_writer
::empty_tag('link', array('rel' => 'alternate',
714 'type' => $type, 'title' => $alt->title
, 'href' => $alt->url
));
717 // Add noindex tag if relevant page and setting applied.
718 $allowindexing = isset($CFG->allowindexing
) ?
$CFG->allowindexing
: 0;
719 $loginpages = array('login-index', 'login-signup');
720 if ($allowindexing == 2 ||
($allowindexing == 0 && in_array($this->page
->pagetype
, $loginpages))) {
721 if (!isset($CFG->additionalhtmlhead
)) {
722 $CFG->additionalhtmlhead
= '';
724 $CFG->additionalhtmlhead
.= '<meta name="robots" content="noindex" />';
727 if (!empty($CFG->additionalhtmlhead
)) {
728 $output .= "\n".$CFG->additionalhtmlhead
;
731 if ($PAGE->pagelayout
== 'frontpage') {
732 $summary = s(strip_tags(format_text($SITE->summary
, FORMAT_HTML
)));
733 if (!empty($summary)) {
734 $output .= "<meta name=\"description\" content=\"$summary\" />\n";
742 * The standard tags (typically skip links) that should be output just inside
743 * the start of the <body> tag. Designed to be called in theme layout.php files.
745 * @return string HTML fragment.
747 public function standard_top_of_body_html() {
749 $output = $this->page
->requires
->get_top_of_body_code($this);
750 if ($this->page
->pagelayout
!== 'embedded' && !empty($CFG->additionalhtmltopofbody
)) {
751 $output .= "\n".$CFG->additionalhtmltopofbody
;
754 // Give subsystems an opportunity to inject extra html content. The callback
755 // must always return a string containing valid html.
756 foreach (\core_component
::get_core_subsystems() as $name => $path) {
758 $output .= component_callback($name, 'before_standard_top_of_body_html', [], '');
762 // Give plugins an opportunity to inject extra html content. The callback
763 // must always return a string containing valid html.
764 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
765 foreach ($pluginswithfunction as $plugins) {
766 foreach ($plugins as $function) {
767 $output .= $function();
771 $output .= $this->maintenance_warning();
777 * Scheduled maintenance warning message.
779 * Note: This is a nasty hack to display maintenance notice, this should be moved
780 * to some general notification area once we have it.
784 public function maintenance_warning() {
788 if (isset($CFG->maintenance_later
) and $CFG->maintenance_later
> time()) {
789 $timeleft = $CFG->maintenance_later
- time();
790 // If timeleft less than 30 sec, set the class on block to error to highlight.
791 $errorclass = ($timeleft < 30) ?
'alert-error alert-danger' : 'alert-warning';
792 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-a-1 alert');
794 $a->hour
= (int)($timeleft / 3600);
795 $a->min
= (int)(($timeleft / 60) %
60);
796 $a->sec
= (int)($timeleft %
60);
798 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
800 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
803 $output .= $this->box_end();
804 $this->page
->requires
->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
805 array(array('timeleftinsec' => $timeleft)));
806 $this->page
->requires
->strings_for_js(
807 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
814 * The standard tags (typically performance information and validation links,
815 * if we are in developer debug mode) that should be output in the footer area
816 * of the page. Designed to be called in theme layout.php files.
818 * @return string HTML fragment.
820 public function standard_footer_html() {
821 global $CFG, $SCRIPT;
824 if (during_initial_install()) {
825 // Debugging info can not work before install is finished,
826 // in any case we do not want any links during installation!
830 // Give plugins an opportunity to add any footer elements.
831 // The callback must always return a string containing valid html footer content.
832 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
833 foreach ($pluginswithfunction as $plugins) {
834 foreach ($plugins as $function) {
835 $output .= $function();
839 // This function is normally called from a layout.php file in {@link core_renderer::header()}
840 // but some of the content won't be known until later, so we return a placeholder
841 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
842 $output .= $this->unique_performance_info_token
;
843 if ($this->page
->devicetypeinuse
== 'legacy') {
844 // The legacy theme is in use print the notification
845 $output .= html_writer
::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
848 // Get links to switch device types (only shown for users not on a default device)
849 $output .= $this->theme_switch_links();
851 if (!empty($CFG->debugpageinfo
)) {
852 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
853 $this->page
->debug_summary()) . '</div>';
855 if (debugging(null, DEBUG_DEVELOPER
) and has_capability('moodle/site:config', context_system
::instance())) { // Only in developer mode
856 // Add link to profiling report if necessary
857 if (function_exists('profiling_is_running') && profiling_is_running()) {
858 $txt = get_string('profiledscript', 'admin');
859 $title = get_string('profiledscriptview', 'admin');
860 $url = $CFG->wwwroot
. '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
861 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
862 $output .= '<div class="profilingfooter">' . $link . '</div>';
864 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
865 'sesskey' => sesskey(), 'returnurl' => $this->page
->url
->out_as_local_url(false)));
866 $output .= '<div class="purgecaches">' .
867 html_writer
::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
869 if (!empty($CFG->debugvalidators
)) {
870 // 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
871 $output .= '<div class="validators"><ul class="list-unstyled ml-1">
872 <li><a href="http://validator.w3.org/check?verbose=1&ss=1&uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
873 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
874 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&warnp2n3e=1&url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
881 * Returns standard main content placeholder.
882 * Designed to be called in theme layout.php files.
884 * @return string HTML fragment.
886 public function main_content() {
887 // This is here because it is the only place we can inject the "main" role over the entire main content area
888 // without requiring all theme's to manually do it, and without creating yet another thing people need to
889 // remember in the theme.
890 // This is an unfortunate hack. DO NO EVER add anything more here.
891 // DO NOT add classes.
893 return '<div role="main">'.$this->unique_main_content_token
.'</div>';
897 * Returns standard navigation between activities in a course.
899 * @return string the navigation HTML.
901 public function activity_navigation() {
902 // First we should check if we want to add navigation.
903 $context = $this->page
->context
;
904 if (($this->page
->pagelayout
!== 'incourse' && $this->page
->pagelayout
!== 'frametop')
905 ||
$context->contextlevel
!= CONTEXT_MODULE
) {
909 // If the activity is in stealth mode, show no links.
910 if ($this->page
->cm
->is_stealth()) {
914 // Get a list of all the activities in the course.
915 $course = $this->page
->cm
->get_course();
916 $modules = get_fast_modinfo($course->id
)->get_cms();
918 // Put the modules into an array in order by the position they are shown in the course.
921 foreach ($modules as $module) {
922 // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
923 if (!$module->uservisible ||
$module->is_stealth() ||
empty($module->url
)) {
926 $mods[$module->id
] = $module;
928 // No need to add the current module to the list for the activity dropdown menu.
929 if ($module->id
== $this->page
->cm
->id
) {
933 $modname = $module->get_formatted_name();
934 // Display the hidden text if necessary.
935 if (!$module->visible
) {
936 $modname .= ' ' . get_string('hiddenwithbrackets');
939 $linkurl = new moodle_url($module->url
, array('forceview' => 1));
940 // Add module URL (as key) and name (as value) to the activity list array.
941 $activitylist[$linkurl->out(false)] = $modname;
944 $nummods = count($mods);
946 // If there is only one mod then do nothing.
951 // Get an array of just the course module ids used to get the cmid value based on their position in the course.
952 $modids = array_keys($mods);
954 // Get the position in the array of the course module we are viewing.
955 $position = array_search($this->page
->cm
->id
, $modids);
960 // Check if we have a previous mod to show.
962 $prevmod = $mods[$modids[$position - 1]];
965 // Check if we have a next mod to show.
966 if ($position < ($nummods - 1)) {
967 $nextmod = $mods[$modids[$position +
1]];
970 $activitynav = new \core_course\output\activity_navigation
($prevmod, $nextmod, $activitylist);
971 $renderer = $this->page
->get_renderer('core', 'course');
972 return $renderer->render($activitynav);
976 * The standard tags (typically script tags that are not needed earlier) that
977 * should be output after everything else. Designed to be called in theme layout.php files.
979 * @return string HTML fragment.
981 public function standard_end_of_body_html() {
984 // This function is normally called from a layout.php file in {@link core_renderer::header()}
985 // but some of the content won't be known until later, so we return a placeholder
986 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
988 if ($this->page
->pagelayout
!== 'embedded' && !empty($CFG->additionalhtmlfooter
)) {
989 $output .= "\n".$CFG->additionalhtmlfooter
;
991 $output .= $this->unique_end_html_token
;
996 * The standard HTML that should be output just before the <footer> tag.
997 * Designed to be called in theme layout.php files.
999 * @return string HTML fragment.
1001 public function standard_after_main_region_html() {
1004 if ($this->page
->pagelayout
!== 'embedded' && !empty($CFG->additionalhtmlbottomofbody
)) {
1005 $output .= "\n".$CFG->additionalhtmlbottomofbody
;
1008 // Give subsystems an opportunity to inject extra html content. The callback
1009 // must always return a string containing valid html.
1010 foreach (\core_component
::get_core_subsystems() as $name => $path) {
1012 $output .= component_callback($name, 'standard_after_main_region_html', [], '');
1016 // Give plugins an opportunity to inject extra html content. The callback
1017 // must always return a string containing valid html.
1018 $pluginswithfunction = get_plugins_with_function('standard_after_main_region_html', 'lib.php');
1019 foreach ($pluginswithfunction as $plugins) {
1020 foreach ($plugins as $function) {
1021 $output .= $function();
1029 * Return the standard string that says whether you are logged in (and switched
1030 * roles/logged in as another user).
1031 * @param bool $withlinks if false, then don't include any links in the HTML produced.
1032 * If not set, the default is the nologinlinks option from the theme config.php file,
1033 * and if that is not set, then links are included.
1034 * @return string HTML fragment.
1036 public function login_info($withlinks = null) {
1037 global $USER, $CFG, $DB, $SESSION;
1039 if (during_initial_install()) {
1043 if (is_null($withlinks)) {
1044 $withlinks = empty($this->page
->layout_options
['nologinlinks']);
1047 $course = $this->page
->course
;
1048 if (\core\session\manager
::is_loggedinas()) {
1049 $realuser = \core\session\manager
::get_realuser();
1050 $fullname = fullname($realuser, true);
1052 $loginastitle = get_string('loginas');
1053 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&sesskey=".sesskey()."\"";
1054 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
1056 $realuserinfo = " [$fullname] ";
1062 $loginpage = $this->is_login_page();
1063 $loginurl = get_login_url();
1065 if (empty($course->id
)) {
1066 // $course->id is not defined during installation
1068 } else if (isloggedin()) {
1069 $context = context_course
::instance($course->id
);
1071 $fullname = fullname($USER, true);
1072 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
1074 $linktitle = get_string('viewprofile');
1075 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
1077 $username = $fullname;
1079 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid
))) {
1081 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1083 $username .= " from {$idprovider->name}";
1086 if (isguestuser()) {
1087 $loggedinas = $realuserinfo.get_string('loggedinasguest');
1088 if (!$loginpage && $withlinks) {
1089 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1091 } else if (is_role_switched($course->id
)) { // Has switched roles
1093 if ($role = $DB->get_record('role', array('id'=>$USER->access
['rsw'][$context->path
]))) {
1094 $rolename = ': '.role_get_name($role, $context);
1096 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1098 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id
,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page
->url
->out_as_local_url(false)));
1099 $loggedinas .= ' ('.html_writer
::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1102 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1104 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1108 $loggedinas = get_string('loggedinnot', 'moodle');
1109 if (!$loginpage && $withlinks) {
1110 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1114 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1116 if (isset($SESSION->justloggedin
)) {
1117 unset($SESSION->justloggedin
);
1118 if (!empty($CFG->displayloginfailures
)) {
1119 if (!isguestuser()) {
1120 // Include this file only when required.
1121 require_once($CFG->dirroot
. '/user/lib.php');
1122 if ($count = user_count_login_failures($USER)) {
1123 $loggedinas .= '<div class="loginfailures">';
1124 $a = new stdClass();
1125 $a->attempts
= $count;
1126 $loggedinas .= get_string('failedloginattempts', '', $a);
1127 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system
::instance())) {
1128 $loggedinas .= ' ('.html_writer
::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1129 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1131 $loggedinas .= '</div>';
1141 * Check whether the current page is a login page.
1146 protected function is_login_page() {
1147 // This is a real bit of a hack, but its a rarety that we need to do something like this.
1148 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1149 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1151 $this->page
->url
->out_as_local_url(false, array()),
1154 '/login/forgot_password.php',
1160 * Return the 'back' link that normally appears in the footer.
1162 * @return string HTML fragment.
1164 public function home_link() {
1167 if ($this->page
->pagetype
== 'site-index') {
1168 // Special case for site home page - please do not remove
1169 return '<div class="sitelink">' .
1170 '<a title="Moodle" href="http://moodle.org/">' .
1171 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1173 } else if (!empty($CFG->target_release
) && $CFG->target_release
!= $CFG->release
) {
1174 // Special case for during install/upgrade.
1175 return '<div class="sitelink">'.
1176 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1177 '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1179 } else if ($this->page
->course
->id
== $SITE->id ||
strpos($this->page
->pagetype
, 'course-view') === 0) {
1180 return '<div class="homelink"><a href="' . $CFG->wwwroot
. '/">' .
1181 get_string('home') . '</a></div>';
1184 return '<div class="homelink"><a href="' . $CFG->wwwroot
. '/course/view.php?id=' . $this->page
->course
->id
. '">' .
1185 format_string($this->page
->course
->shortname
, true, array('context' => $this->page
->context
)) . '</a></div>';
1190 * Redirects the user by any means possible given the current state
1192 * This function should not be called directly, it should always be called using
1193 * the redirect function in lib/weblib.php
1195 * The redirect function should really only be called before page output has started
1196 * however it will allow itself to be called during the state STATE_IN_BODY
1198 * @param string $encodedurl The URL to send to encoded if required
1199 * @param string $message The message to display to the user if any
1200 * @param int $delay The delay before redirecting a user, if $message has been
1201 * set this is a requirement and defaults to 3, set to 0 no delay
1202 * @param boolean $debugdisableredirect this redirect has been disabled for
1203 * debugging purposes. Display a message that explains, and don't
1204 * trigger the redirect.
1205 * @param string $messagetype The type of notification to show the message in.
1206 * See constants on \core\output\notification.
1207 * @return string The HTML to display to the user before dying, may contain
1208 * meta refresh, javascript refresh, and may have set header redirects
1210 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1211 $messagetype = \core\output\notification
::NOTIFY_INFO
) {
1213 $url = str_replace('&', '&', $encodedurl);
1215 switch ($this->page
->state
) {
1216 case moodle_page
::STATE_BEFORE_HEADER
:
1217 // No output yet it is safe to delivery the full arsenal of redirect methods
1218 if (!$debugdisableredirect) {
1219 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1220 $this->metarefreshtag
= '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1221 $this->page
->requires
->js_function_call('document.location.replace', array($url), false, ($delay +
3));
1223 $output = $this->header();
1225 case moodle_page
::STATE_PRINTING_HEADER
:
1226 // We should hopefully never get here
1227 throw new coding_exception('You cannot redirect while printing the page header');
1229 case moodle_page
::STATE_IN_BODY
:
1230 // We really shouldn't be here but we can deal with this
1231 debugging("You should really redirect before you start page output");
1232 if (!$debugdisableredirect) {
1233 $this->page
->requires
->js_function_call('document.location.replace', array($url), false, $delay);
1235 $output = $this->opencontainers
->pop_all_but_last();
1237 case moodle_page
::STATE_DONE
:
1238 // Too late to be calling redirect now
1239 throw new coding_exception('You cannot redirect after the entire page has been generated');
1242 $output .= $this->notification($message, $messagetype);
1243 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1244 if ($debugdisableredirect) {
1245 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1247 $output .= $this->footer();
1252 * Start output by sending the HTTP headers, and printing the HTML <head>
1253 * and the start of the <body>.
1255 * To control what is printed, you should set properties on $PAGE. If you
1256 * are familiar with the old {@link print_header()} function from Moodle 1.9
1257 * you will find that there are properties on $PAGE that correspond to most
1258 * of the old parameters to could be passed to print_header.
1260 * Not that, in due course, the remaining $navigation, $menu parameters here
1261 * will be replaced by more properties of $PAGE, but that is still to do.
1263 * @return string HTML that you must output this, preferably immediately.
1265 public function header() {
1266 global $USER, $CFG, $SESSION;
1268 // Give plugins an opportunity touch things before the http headers are sent
1269 // such as adding additional headers. The return value is ignored.
1270 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1271 foreach ($pluginswithfunction as $plugins) {
1272 foreach ($plugins as $function) {
1277 if (\core\session\manager
::is_loggedinas()) {
1278 $this->page
->add_body_class('userloggedinas');
1281 if (isset($SESSION->justloggedin
) && !empty($CFG->displayloginfailures
)) {
1282 require_once($CFG->dirroot
. '/user/lib.php');
1283 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1284 if ($count = user_count_login_failures($USER, false)) {
1285 $this->page
->add_body_class('loginfailures');
1289 // If the user is logged in, and we're not in initial install,
1290 // check to see if the user is role-switched and add the appropriate
1291 // CSS class to the body element.
1292 if (!during_initial_install() && isloggedin() && is_role_switched($this->page
->course
->id
)) {
1293 $this->page
->add_body_class('userswitchedrole');
1296 // Give themes a chance to init/alter the page object.
1297 $this->page
->theme
->init_page($this->page
);
1299 $this->page
->set_state(moodle_page
::STATE_PRINTING_HEADER
);
1301 // Find the appropriate page layout file, based on $this->page->pagelayout.
1302 $layoutfile = $this->page
->theme
->layout_file($this->page
->pagelayout
);
1303 // Render the layout using the layout file.
1304 $rendered = $this->render_page_layout($layoutfile);
1306 // Slice the rendered output into header and footer.
1307 $cutpos = strpos($rendered, $this->unique_main_content_token
);
1308 if ($cutpos === false) {
1309 $cutpos = strpos($rendered, self
::MAIN_CONTENT_TOKEN
);
1310 $token = self
::MAIN_CONTENT_TOKEN
;
1312 $token = $this->unique_main_content_token
;
1315 if ($cutpos === false) {
1316 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.');
1318 $header = substr($rendered, 0, $cutpos);
1319 $footer = substr($rendered, $cutpos +
strlen($token));
1321 if (empty($this->contenttype
)) {
1322 debugging('The page layout file did not call $OUTPUT->doctype()');
1323 $header = $this->doctype() . $header;
1326 // If this theme version is below 2.4 release and this is a course view page
1327 if ((!isset($this->page
->theme
->settings
->version
) ||
$this->page
->theme
->settings
->version
< 2012101500) &&
1328 $this->page
->pagelayout
=== 'course' && $this->page
->url
->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE
)) {
1329 // check if course content header/footer have not been output during render of theme layout
1330 $coursecontentheader = $this->course_content_header(true);
1331 $coursecontentfooter = $this->course_content_footer(true);
1332 if (!empty($coursecontentheader)) {
1333 // display debug message and add header and footer right above and below main content
1334 // Please note that course header and footer (to be displayed above and below the whole page)
1335 // are not displayed in this case at all.
1336 // Besides the content header and footer are not displayed on any other course page
1337 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
);
1338 $header .= $coursecontentheader;
1339 $footer = $coursecontentfooter. $footer;
1343 send_headers($this->contenttype
, $this->page
->cacheable
);
1345 $this->opencontainers
->push('header/footer', $footer);
1346 $this->page
->set_state(moodle_page
::STATE_IN_BODY
);
1348 return $header . $this->skip_link_target('maincontent');
1352 * Renders and outputs the page layout file.
1354 * This is done by preparing the normal globals available to a script, and
1355 * then including the layout file provided by the current theme for the
1358 * @param string $layoutfile The name of the layout file
1359 * @return string HTML code
1361 protected function render_page_layout($layoutfile) {
1362 global $CFG, $SITE, $USER;
1363 // The next lines are a bit tricky. The point is, here we are in a method
1364 // of a renderer class, and this object may, or may not, be the same as
1365 // the global $OUTPUT object. When rendering the page layout file, we want to use
1366 // this object. However, people writing Moodle code expect the current
1367 // renderer to be called $OUTPUT, not $this, so define a variable called
1368 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1370 $PAGE = $this->page
;
1371 $COURSE = $this->page
->course
;
1374 include($layoutfile);
1375 $rendered = ob_get_contents();
1381 * Outputs the page's footer
1383 * @return string HTML fragment
1385 public function footer() {
1386 global $CFG, $DB, $PAGE;
1388 // Give plugins an opportunity to touch the page before JS is finalized.
1389 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1390 foreach ($pluginswithfunction as $plugins) {
1391 foreach ($plugins as $function) {
1396 $output = $this->container_end_all(true);
1398 $footer = $this->opencontainers
->pop('header/footer');
1400 if (debugging() and $DB and $DB->is_transaction_started()) {
1401 // TODO: MDL-20625 print warning - transaction will be rolled back
1404 // Provide some performance info if required
1405 $performanceinfo = '';
1406 if (defined('MDL_PERF') ||
(!empty($CFG->perfdebug
) and $CFG->perfdebug
> 7)) {
1407 $perf = get_performance_info();
1408 if (defined('MDL_PERFTOFOOT') ||
debugging() ||
$CFG->perfdebug
> 7) {
1409 $performanceinfo = $perf['html'];
1413 // We always want performance data when running a performance test, even if the user is redirected to another page.
1414 if (MDL_PERF_TEST
&& strpos($footer, $this->unique_performance_info_token
) === false) {
1415 $footer = $this->unique_performance_info_token
. $footer;
1417 $footer = str_replace($this->unique_performance_info_token
, $performanceinfo, $footer);
1419 // Only show notifications when we have a $PAGE context id.
1420 if (!empty($PAGE->context
->id
)) {
1421 $this->page
->requires
->js_call_amd('core/notification', 'init', array(
1423 \core\notification
::fetch_as_array($this)
1426 $footer = str_replace($this->unique_end_html_token
, $this->page
->requires
->get_end_code(), $footer);
1428 $this->page
->set_state(moodle_page
::STATE_DONE
);
1430 return $output . $footer;
1434 * Close all but the last open container. This is useful in places like error
1435 * handling, where you want to close all the open containers (apart from <body>)
1436 * before outputting the error message.
1438 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1439 * developer debug warning if it isn't.
1440 * @return string the HTML required to close any open containers inside <body>.
1442 public function container_end_all($shouldbenone = false) {
1443 return $this->opencontainers
->pop_all_but_last($shouldbenone);
1447 * Returns course-specific information to be output immediately above content on any course page
1448 * (for the current course)
1450 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1453 public function course_content_header($onlyifnotcalledbefore = false) {
1455 static $functioncalled = false;
1456 if ($functioncalled && $onlyifnotcalledbefore) {
1457 // we have already output the content header
1461 // Output any session notification.
1462 $notifications = \core\notification
::fetch();
1464 $bodynotifications = '';
1465 foreach ($notifications as $notification) {
1466 $bodynotifications .= $this->render_from_template(
1467 $notification->get_template_name(),
1468 $notification->export_for_template($this)
1472 $output = html_writer
::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1474 if ($this->page
->course
->id
== SITEID
) {
1475 // return immediately and do not include /course/lib.php if not necessary
1479 require_once($CFG->dirroot
.'/course/lib.php');
1480 $functioncalled = true;
1481 $courseformat = course_get_format($this->page
->course
);
1482 if (($obj = $courseformat->course_content_header()) !== null) {
1483 $output .= html_writer
::div($courseformat->get_renderer($this->page
)->render($obj), 'course-content-header');
1489 * Returns course-specific information to be output immediately below content on any course page
1490 * (for the current course)
1492 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1495 public function course_content_footer($onlyifnotcalledbefore = false) {
1497 if ($this->page
->course
->id
== SITEID
) {
1498 // return immediately and do not include /course/lib.php if not necessary
1501 static $functioncalled = false;
1502 if ($functioncalled && $onlyifnotcalledbefore) {
1503 // we have already output the content footer
1506 $functioncalled = true;
1507 require_once($CFG->dirroot
.'/course/lib.php');
1508 $courseformat = course_get_format($this->page
->course
);
1509 if (($obj = $courseformat->course_content_footer()) !== null) {
1510 return html_writer
::div($courseformat->get_renderer($this->page
)->render($obj), 'course-content-footer');
1516 * Returns course-specific information to be output on any course page in the header area
1517 * (for the current course)
1521 public function course_header() {
1523 if ($this->page
->course
->id
== SITEID
) {
1524 // return immediately and do not include /course/lib.php if not necessary
1527 require_once($CFG->dirroot
.'/course/lib.php');
1528 $courseformat = course_get_format($this->page
->course
);
1529 if (($obj = $courseformat->course_header()) !== null) {
1530 return $courseformat->get_renderer($this->page
)->render($obj);
1536 * Returns course-specific information to be output on any course page in the footer area
1537 * (for the current course)
1541 public function course_footer() {
1543 if ($this->page
->course
->id
== SITEID
) {
1544 // return immediately and do not include /course/lib.php if not necessary
1547 require_once($CFG->dirroot
.'/course/lib.php');
1548 $courseformat = course_get_format($this->page
->course
);
1549 if (($obj = $courseformat->course_footer()) !== null) {
1550 return $courseformat->get_renderer($this->page
)->render($obj);
1556 * Get the course pattern datauri to show on a course card.
1558 * The datauri is an encoded svg that can be passed as a url.
1559 * @param int $id Id to use when generating the pattern
1560 * @return string datauri
1562 public function get_generated_image_for_id($id) {
1563 $color = $this->get_generated_color_for_id($id);
1564 $pattern = new \
core_geopattern();
1565 $pattern->setColor($color);
1566 $pattern->patternbyid($id);
1567 return $pattern->datauri();
1571 * Get the course color to show on a course card.
1573 * @param int $id Id to use when generating the color.
1574 * @return string hex color code.
1576 public function get_generated_color_for_id($id) {
1577 $colornumbers = range(1, 10);
1579 foreach ($colornumbers as $number) {
1580 $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1583 $color = $basecolors[$id %
10];
1588 * Returns lang menu or '', this method also checks forcing of languages in courses.
1590 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1592 * @return string The lang menu HTML or empty string
1594 public function lang_menu() {
1597 if (empty($CFG->langmenu
)) {
1601 if ($this->page
->course
!= SITEID
and !empty($this->page
->course
->lang
)) {
1602 // do not show lang menu if language forced
1606 $currlang = current_language();
1607 $langs = get_string_manager()->get_list_of_translations();
1609 if (count($langs) < 2) {
1613 $s = new single_select($this->page
->url
, 'lang', $langs, $currlang, null);
1614 $s->label
= get_accesshide(get_string('language'));
1615 $s->class = 'langmenu';
1616 return $this->render($s);
1620 * Output the row of editing icons for a block, as defined by the controls array.
1622 * @param array $controls an array like {@link block_contents::$controls}.
1623 * @param string $blockid The ID given to the block.
1624 * @return string HTML fragment.
1626 public function block_controls($actions, $blockid = null) {
1628 if (empty($actions)) {
1631 $menu = new action_menu($actions);
1632 if ($blockid !== null) {
1633 $menu->set_owner_selector('#'.$blockid);
1635 $menu->set_constraint('.block-region');
1636 $menu->attributes
['class'] .= ' block-control-actions commands';
1637 return $this->render($menu);
1641 * Returns the HTML for a basic textarea field.
1643 * @param string $name Name to use for the textarea element
1644 * @param string $id The id to use fort he textarea element
1645 * @param string $value Initial content to display in the textarea
1646 * @param int $rows Number of rows to display
1647 * @param int $cols Number of columns to display
1648 * @return string the HTML to display
1650 public function print_textarea($name, $id, $value, $rows, $cols) {
1653 editors_head_setup();
1654 $editor = editors_get_preferred_editor(FORMAT_HTML
);
1655 $editor->set_text($value);
1656 $editor->use_editor($id, []);
1666 return $OUTPUT->render_from_template('core_form/editor_textarea', $context);
1670 * Renders an action menu component.
1672 * @param action_menu $menu
1673 * @return string HTML
1675 public function render_action_menu(action_menu
$menu) {
1677 // We don't want the class icon there!
1678 foreach ($menu->get_secondary_actions() as $action) {
1679 if ($action instanceof \action_menu_link
&& $action->has_class('icon')) {
1680 $action->attributes
['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes
['class']);
1684 if ($menu->is_empty()) {
1687 $context = $menu->export_for_template($this);
1689 return $this->render_from_template('core/action_menu', $context);
1693 * Renders an action_menu_link item.
1695 * @param action_menu_link $action
1696 * @return string HTML fragment
1698 protected function render_action_menu_link(action_menu_link
$action) {
1699 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1703 * Renders a primary action_menu_filler item.
1705 * @param action_menu_link_filler $action
1706 * @return string HTML fragment
1708 protected function render_action_menu_filler(action_menu_filler
$action) {
1709 return html_writer
::span(' ', 'filler');
1713 * Renders a primary action_menu_link item.
1715 * @param action_menu_link_primary $action
1716 * @return string HTML fragment
1718 protected function render_action_menu_link_primary(action_menu_link_primary
$action) {
1719 return $this->render_action_menu_link($action);
1723 * Renders a secondary action_menu_link item.
1725 * @param action_menu_link_secondary $action
1726 * @return string HTML fragment
1728 protected function render_action_menu_link_secondary(action_menu_link_secondary
$action) {
1729 return $this->render_action_menu_link($action);
1733 * Prints a nice side block with an optional header.
1735 * @param block_contents $bc HTML for the content
1736 * @param string $region the region the block is appearing in.
1737 * @return string the HTML to be output.
1739 public function block(block_contents
$bc, $region) {
1740 $bc = clone($bc); // Avoid messing up the object passed in.
1741 if (empty($bc->blockinstanceid
) ||
!strip_tags($bc->title
)) {
1742 $bc->collapsible
= block_contents
::NOT_HIDEABLE
;
1745 $id = !empty($bc->attributes
['id']) ?
$bc->attributes
['id'] : uniqid('block-');
1746 $context = new stdClass();
1747 $context->skipid
= $bc->skipid
;
1748 $context->blockinstanceid
= $bc->blockinstanceid
;
1749 $context->dockable
= $bc->dockable
;
1751 $context->hidden
= $bc->collapsible
== block_contents
::HIDDEN
;
1752 $context->skiptitle
= strip_tags($bc->title
);
1753 $context->showskiplink
= !empty($context->skiptitle
);
1754 $context->arialabel
= $bc->arialabel
;
1755 $context->ariarole
= !empty($bc->attributes
['role']) ?
$bc->attributes
['role'] : 'complementary';
1756 $context->class = $bc->attributes
['class'];
1757 $context->type
= $bc->attributes
['data-block'];
1758 $context->title
= $bc->title
;
1759 $context->content
= $bc->content
;
1760 $context->annotation
= $bc->annotation
;
1761 $context->footer
= $bc->footer
;
1762 $context->hascontrols
= !empty($bc->controls
);
1763 if ($context->hascontrols
) {
1764 $context->controls
= $this->block_controls($bc->controls
, $id);
1767 return $this->render_from_template('core/block', $context);
1771 * Render the contents of a block_list.
1773 * @param array $icons the icon for each item.
1774 * @param array $items the content of each item.
1775 * @return string HTML
1777 public function list_block_contents($icons, $items) {
1780 foreach ($items as $key => $string) {
1781 $item = html_writer
::start_tag('li', array('class' => 'r' . $row));
1782 if (!empty($icons[$key])) { //test if the content has an assigned icon
1783 $item .= html_writer
::tag('div', $icons[$key], array('class' => 'icon column c0'));
1785 $item .= html_writer
::tag('div', $string, array('class' => 'column c1'));
1786 $item .= html_writer
::end_tag('li');
1788 $row = 1 - $row; // Flip even/odd.
1790 return html_writer
::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1794 * Output all the blocks in a particular region.
1796 * @param string $region the name of a region on this page.
1797 * @return string the HTML to be output.
1799 public function blocks_for_region($region) {
1800 $blockcontents = $this->page
->blocks
->get_content_for_region($region, $this);
1801 $blocks = $this->page
->blocks
->get_blocks_for_region($region);
1804 foreach ($blocks as $block) {
1805 $zones[] = $block->title
;
1809 foreach ($blockcontents as $bc) {
1810 if ($bc instanceof block_contents
) {
1811 $output .= $this->block($bc, $region);
1812 $lastblock = $bc->title
;
1813 } else if ($bc instanceof block_move_target
) {
1814 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1816 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1823 * Output a place where the block that is currently being moved can be dropped.
1825 * @param block_move_target $target with the necessary details.
1826 * @param array $zones array of areas where the block can be moved to
1827 * @param string $previous the block located before the area currently being rendered.
1828 * @param string $region the name of the region
1829 * @return string the HTML to be output.
1831 public function block_move_target($target, $zones, $previous, $region) {
1832 if ($previous == null) {
1833 if (empty($zones)) {
1834 // There are no zones, probably because there are no blocks.
1835 $regions = $this->page
->theme
->get_all_block_regions();
1836 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1838 $position = get_string('moveblockbefore', 'block', $zones[0]);
1841 $position = get_string('moveblockafter', 'block', $previous);
1843 return html_writer
::tag('a', html_writer
::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url
, 'class' => 'blockmovetarget'));
1847 * Renders a special html link with attached action
1849 * Theme developers: DO NOT OVERRIDE! Please override function
1850 * {@link core_renderer::render_action_link()} instead.
1852 * @param string|moodle_url $url
1853 * @param string $text HTML fragment
1854 * @param component_action $action
1855 * @param array $attributes associative array of html link attributes + disabled
1856 * @param pix_icon optional pix icon to render with the link
1857 * @return string HTML fragment
1859 public function action_link($url, $text, component_action
$action = null, array $attributes = null, $icon = null) {
1860 if (!($url instanceof moodle_url
)) {
1861 $url = new moodle_url($url);
1863 $link = new action_link($url, $text, $action, $attributes, $icon);
1865 return $this->render($link);
1869 * Renders an action_link object.
1871 * The provided link is renderer and the HTML returned. At the same time the
1872 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1874 * @param action_link $link
1875 * @return string HTML fragment
1877 protected function render_action_link(action_link
$link) {
1878 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1882 * Renders an action_icon.
1884 * This function uses the {@link core_renderer::action_link()} method for the
1885 * most part. What it does different is prepare the icon as HTML and use it
1888 * Theme developers: If you want to change how action links and/or icons are rendered,
1889 * consider overriding function {@link core_renderer::render_action_link()} and
1890 * {@link core_renderer::render_pix_icon()}.
1892 * @param string|moodle_url $url A string URL or moodel_url
1893 * @param pix_icon $pixicon
1894 * @param component_action $action
1895 * @param array $attributes associative array of html link attributes + disabled
1896 * @param bool $linktext show title next to image in link
1897 * @return string HTML fragment
1899 public function action_icon($url, pix_icon
$pixicon, component_action
$action = null, array $attributes = null, $linktext=false) {
1900 if (!($url instanceof moodle_url
)) {
1901 $url = new moodle_url($url);
1903 $attributes = (array)$attributes;
1905 if (empty($attributes['class'])) {
1906 // let ppl override the class via $options
1907 $attributes['class'] = 'action-icon';
1910 $icon = $this->render($pixicon);
1913 $text = $pixicon->attributes
['alt'];
1918 return $this->action_link($url, $text.$icon, $action, $attributes);
1922 * Print a message along with button choices for Continue/Cancel
1924 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1926 * @param string $message The question to ask the user
1927 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1928 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1929 * @return string HTML fragment
1931 public function confirm($message, $continue, $cancel) {
1932 if ($continue instanceof single_button
) {
1934 $continue->primary
= true;
1935 } else if (is_string($continue)) {
1936 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1937 } else if ($continue instanceof moodle_url
) {
1938 $continue = new single_button($continue, get_string('continue'), 'post', true);
1940 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1943 if ($cancel instanceof single_button
) {
1945 } else if (is_string($cancel)) {
1946 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1947 } else if ($cancel instanceof moodle_url
) {
1948 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1950 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1954 'role'=>'alertdialog',
1955 'aria-labelledby'=>'modal-header',
1956 'aria-describedby'=>'modal-body',
1957 'aria-modal'=>'true'
1960 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
1961 $output .= $this->box_start('modal-content', 'modal-content');
1962 $output .= $this->box_start('modal-header p-x-1', 'modal-header');
1963 $output .= html_writer
::tag('h4', get_string('confirm'));
1964 $output .= $this->box_end();
1967 'data-aria-autofocus'=>'true'
1969 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
1970 $output .= html_writer
::tag('p', $message);
1971 $output .= $this->box_end();
1972 $output .= $this->box_start('modal-footer', 'modal-footer');
1973 $output .= html_writer
::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1974 $output .= $this->box_end();
1975 $output .= $this->box_end();
1976 $output .= $this->box_end();
1981 * Returns a form with a single button.
1983 * Theme developers: DO NOT OVERRIDE! Please override function
1984 * {@link core_renderer::render_single_button()} instead.
1986 * @param string|moodle_url $url
1987 * @param string $label button text
1988 * @param string $method get or post submit method
1989 * @param array $options associative array {disabled, title, etc.}
1990 * @return string HTML fragment
1992 public function single_button($url, $label, $method='post', array $options=null) {
1993 if (!($url instanceof moodle_url
)) {
1994 $url = new moodle_url($url);
1996 $button = new single_button($url, $label, $method);
1998 foreach ((array)$options as $key=>$value) {
1999 if (array_key_exists($key, $button)) {
2000 $button->$key = $value;
2002 $button->set_attribute($key, $value);
2006 return $this->render($button);
2010 * Renders a single button widget.
2012 * This will return HTML to display a form containing a single button.
2014 * @param single_button $button
2015 * @return string HTML fragment
2017 protected function render_single_button(single_button
$button) {
2018 return $this->render_from_template('core/single_button', $button->export_for_template($this));
2022 * Returns a form with a single select widget.
2024 * Theme developers: DO NOT OVERRIDE! Please override function
2025 * {@link core_renderer::render_single_select()} instead.
2027 * @param moodle_url $url form action target, includes hidden fields
2028 * @param string $name name of selection field - the changing parameter in url
2029 * @param array $options list of options
2030 * @param string $selected selected element
2031 * @param array $nothing
2032 * @param string $formid
2033 * @param array $attributes other attributes for the single select
2034 * @return string HTML fragment
2036 public function single_select($url, $name, array $options, $selected = '',
2037 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2038 if (!($url instanceof moodle_url
)) {
2039 $url = new moodle_url($url);
2041 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2043 if (array_key_exists('label', $attributes)) {
2044 $select->set_label($attributes['label']);
2045 unset($attributes['label']);
2047 $select->attributes
= $attributes;
2049 return $this->render($select);
2053 * Returns a dataformat selection and download form
2055 * @param string $label A text label
2056 * @param moodle_url|string $base The download page url
2057 * @param string $name The query param which will hold the type of the download
2058 * @param array $params Extra params sent to the download page
2059 * @return string HTML fragment
2061 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2063 $formats = core_plugin_manager
::instance()->get_plugins_of_type('dataformat');
2065 foreach ($formats as $format) {
2066 if ($format->is_enabled()) {
2068 'value' => $format->name
,
2069 'label' => get_string('dataformat', $format->component
),
2073 $hiddenparams = array();
2074 foreach ($params as $key => $value) {
2075 $hiddenparams[] = array(
2084 'params' => $hiddenparams,
2085 'options' => $options,
2086 'sesskey' => sesskey(),
2087 'submit' => get_string('download'),
2090 return $this->render_from_template('core/dataformat_selector', $data);
2095 * Internal implementation of single_select rendering
2097 * @param single_select $select
2098 * @return string HTML fragment
2100 protected function render_single_select(single_select
$select) {
2101 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2105 * Returns a form with a url select widget.
2107 * Theme developers: DO NOT OVERRIDE! Please override function
2108 * {@link core_renderer::render_url_select()} instead.
2110 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2111 * @param string $selected selected element
2112 * @param array $nothing
2113 * @param string $formid
2114 * @return string HTML fragment
2116 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2117 $select = new url_select($urls, $selected, $nothing, $formid);
2118 return $this->render($select);
2122 * Internal implementation of url_select rendering
2124 * @param url_select $select
2125 * @return string HTML fragment
2127 protected function render_url_select(url_select
$select) {
2128 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2132 * Returns a string containing a link to the user documentation.
2133 * Also contains an icon by default. Shown to teachers and admin only.
2135 * @param string $path The page link after doc root and language, no leading slash.
2136 * @param string $text The text to be displayed for the link
2137 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2140 public function doc_link($path, $text = '', $forcepopup = false) {
2143 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2145 $url = new moodle_url(get_docs_url($path));
2147 $attributes = array('href'=>$url);
2148 if (!empty($CFG->doctonewwindow
) ||
$forcepopup) {
2149 $attributes['class'] = 'helplinkpopup';
2152 return html_writer
::tag('a', $icon.$text, $attributes);
2156 * Return HTML for an image_icon.
2158 * Theme developers: DO NOT OVERRIDE! Please override function
2159 * {@link core_renderer::render_image_icon()} instead.
2161 * @param string $pix short pix name
2162 * @param string $alt mandatory alt attribute
2163 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2164 * @param array $attributes htm lattributes
2165 * @return string HTML fragment
2167 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2168 $icon = new image_icon($pix, $alt, $component, $attributes);
2169 return $this->render($icon);
2173 * Renders a pix_icon widget and returns the HTML to display it.
2175 * @param image_icon $icon
2176 * @return string HTML fragment
2178 protected function render_image_icon(image_icon
$icon) {
2179 $system = \core\output\icon_system
::instance(\core\output\icon_system
::STANDARD
);
2180 return $system->render_pix_icon($this, $icon);
2184 * Return HTML for a pix_icon.
2186 * Theme developers: DO NOT OVERRIDE! Please override function
2187 * {@link core_renderer::render_pix_icon()} instead.
2189 * @param string $pix short pix name
2190 * @param string $alt mandatory alt attribute
2191 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2192 * @param array $attributes htm lattributes
2193 * @return string HTML fragment
2195 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2196 $icon = new pix_icon($pix, $alt, $component, $attributes);
2197 return $this->render($icon);
2201 * Renders a pix_icon widget and returns the HTML to display it.
2203 * @param pix_icon $icon
2204 * @return string HTML fragment
2206 protected function render_pix_icon(pix_icon
$icon) {
2207 $system = \core\output\icon_system
::instance();
2208 return $system->render_pix_icon($this, $icon);
2212 * Return HTML to display an emoticon icon.
2214 * @param pix_emoticon $emoticon
2215 * @return string HTML fragment
2217 protected function render_pix_emoticon(pix_emoticon
$emoticon) {
2218 $system = \core\output\icon_system
::instance(\core\output\icon_system
::STANDARD
);
2219 return $system->render_pix_icon($this, $emoticon);
2223 * Produces the html that represents this rating in the UI
2225 * @param rating $rating the page object on which this rating will appear
2228 function render_rating(rating
$rating) {
2231 if ($rating->settings
->aggregationmethod
== RATING_AGGREGATE_NONE
) {
2232 return null;//ratings are turned off
2235 $ratingmanager = new rating_manager();
2236 // Initialise the JavaScript so ratings can be done by AJAX.
2237 $ratingmanager->initialise_rating_javascript($this->page
);
2239 $strrate = get_string("rate", "rating");
2240 $ratinghtml = ''; //the string we'll return
2242 // permissions check - can they view the aggregate?
2243 if ($rating->user_can_view_aggregate()) {
2245 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings
->aggregationmethod
);
2246 $aggregatelabel = html_writer
::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2247 $aggregatestr = $rating->get_aggregate_string();
2249 $aggregatehtml = html_writer
::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid
, 'class' => 'ratingaggregate')).' ';
2250 if ($rating->count
> 0) {
2251 $countstr = "({$rating->count})";
2255 $aggregatehtml .= html_writer
::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2257 if ($rating->settings
->permissions
->viewall
&& $rating->settings
->pluginpermissions
->viewall
) {
2259 $nonpopuplink = $rating->get_view_ratings_url();
2260 $popuplink = $rating->get_view_ratings_url(true);
2262 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2263 $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
2266 $ratinghtml .= html_writer
::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
2270 // if the item doesn't belong to the current user, the user has permission to rate
2271 // and we're within the assessable period
2272 if ($rating->user_can_rate()) {
2274 $rateurl = $rating->get_rate_url();
2275 $inputs = $rateurl->params();
2277 //start the rating form
2279 'id' => "postrating{$rating->itemid}",
2280 'class' => 'postratingform',
2282 'action' => $rateurl->out_omit_querystring()
2284 $formstart = html_writer
::start_tag('form', $formattrs);
2285 $formstart .= html_writer
::start_tag('div', array('class' => 'ratingform'));
2287 // add the hidden inputs
2288 foreach ($inputs as $name => $value) {
2289 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2290 $formstart .= html_writer
::empty_tag('input', $attributes);
2293 if (empty($ratinghtml)) {
2294 $ratinghtml .= $strrate.': ';
2296 $ratinghtml = $formstart.$ratinghtml;
2298 $scalearray = array(RATING_UNSET_RATING
=> $strrate.'...') +
$rating->settings
->scale
->scaleitems
;
2299 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid
);
2300 $ratinghtml .= html_writer
::label($rating->rating
, 'menurating'.$rating->itemid
, false, array('class' => 'accesshide'));
2301 $ratinghtml .= html_writer
::select($scalearray, 'rating', $rating->rating
, false, $scaleattrs);
2303 //output submit button
2304 $ratinghtml .= html_writer
::start_tag('span', array('class'=>"ratingsubmit"));
2306 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid
, 'value' => s(get_string('rate', 'rating')));
2307 $ratinghtml .= html_writer
::empty_tag('input', $attributes);
2309 if (!$rating->settings
->scale
->isnumeric
) {
2310 // If a global scale, try to find current course ID from the context
2311 if (empty($rating->settings
->scale
->courseid
) and $coursecontext = $rating->context
->get_course_context(false)) {
2312 $courseid = $coursecontext->instanceid
;
2314 $courseid = $rating->settings
->scale
->courseid
;
2316 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings
->scale
);
2318 $ratinghtml .= html_writer
::end_tag('span');
2319 $ratinghtml .= html_writer
::end_tag('div');
2320 $ratinghtml .= html_writer
::end_tag('form');
2327 * Centered heading with attached help button (same title text)
2328 * and optional icon attached.
2330 * @param string $text A heading text
2331 * @param string $helpidentifier The keyword that defines a help page
2332 * @param string $component component name
2333 * @param string|moodle_url $icon
2334 * @param string $iconalt icon alt text
2335 * @param int $level The level of importance of the heading. Defaulting to 2
2336 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2337 * @return string HTML fragment
2339 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2342 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2346 if ($helpidentifier) {
2347 $help = $this->help_icon($helpidentifier, $component);
2350 return $this->heading($image.$text.$help, $level, $classnames);
2354 * Returns HTML to display a help icon.
2356 * @deprecated since Moodle 2.0
2358 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2359 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2363 * Returns HTML to display a help icon.
2365 * Theme developers: DO NOT OVERRIDE! Please override function
2366 * {@link core_renderer::render_help_icon()} instead.
2368 * @param string $identifier The keyword that defines a help page
2369 * @param string $component component name
2370 * @param string|bool $linktext true means use $title as link text, string means link text value
2371 * @return string HTML fragment
2373 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2374 $icon = new help_icon($identifier, $component);
2375 $icon->diag_strings();
2376 if ($linktext === true) {
2377 $icon->linktext
= get_string($icon->identifier
, $icon->component
);
2378 } else if (!empty($linktext)) {
2379 $icon->linktext
= $linktext;
2381 return $this->render($icon);
2385 * Implementation of user image rendering.
2387 * @param help_icon $helpicon A help icon instance
2388 * @return string HTML fragment
2390 protected function render_help_icon(help_icon
$helpicon) {
2391 $context = $helpicon->export_for_template($this);
2392 return $this->render_from_template('core/help_icon', $context);
2396 * Returns HTML to display a scale help icon.
2398 * @param int $courseid
2399 * @param stdClass $scale instance
2400 * @return string HTML fragment
2402 public function help_icon_scale($courseid, stdClass
$scale) {
2405 $title = get_string('helpprefix2', '', $scale->name
) .' ('.get_string('newwindow').')';
2407 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2409 $scaleid = abs($scale->id
);
2411 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2412 $action = new popup_action('click', $link, 'ratingscale');
2414 return html_writer
::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2418 * Creates and returns a spacer image with optional line break.
2420 * @param array $attributes Any HTML attributes to add to the spaced.
2421 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2422 * laxy do it with CSS which is a much better solution.
2423 * @return string HTML fragment
2425 public function spacer(array $attributes = null, $br = false) {
2426 $attributes = (array)$attributes;
2427 if (empty($attributes['width'])) {
2428 $attributes['width'] = 1;
2430 if (empty($attributes['height'])) {
2431 $attributes['height'] = 1;
2433 $attributes['class'] = 'spacer';
2435 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2438 $output .= '<br />';
2445 * Returns HTML to display the specified user's avatar.
2447 * User avatar may be obtained in two ways:
2449 * // Option 1: (shortcut for simple cases, preferred way)
2450 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2451 * $OUTPUT->user_picture($user, array('popup'=>true));
2454 * $userpic = new user_picture($user);
2455 * // Set properties of $userpic
2456 * $userpic->popup = true;
2457 * $OUTPUT->render($userpic);
2460 * Theme developers: DO NOT OVERRIDE! Please override function
2461 * {@link core_renderer::render_user_picture()} instead.
2463 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2464 * If any of these are missing, the database is queried. Avoid this
2465 * if at all possible, particularly for reports. It is very bad for performance.
2466 * @param array $options associative array with user picture options, used only if not a user_picture object,
2468 * - courseid=$this->page->course->id (course id of user profile in link)
2469 * - size=35 (size of image)
2470 * - link=true (make image clickable - the link leads to user profile)
2471 * - popup=false (open in popup)
2472 * - alttext=true (add image alt attribute)
2473 * - class = image class attribute (default 'userpicture')
2474 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2475 * - includefullname=false (whether to include the user's full name together with the user picture)
2476 * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2477 * @return string HTML fragment
2479 public function user_picture(stdClass
$user, array $options = null) {
2480 $userpicture = new user_picture($user);
2481 foreach ((array)$options as $key=>$value) {
2482 if (array_key_exists($key, $userpicture)) {
2483 $userpicture->$key = $value;
2486 return $this->render($userpicture);
2490 * Internal implementation of user image rendering.
2492 * @param user_picture $userpicture
2495 protected function render_user_picture(user_picture
$userpicture) {
2498 $user = $userpicture->user
;
2499 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page
->context
);
2501 if ($userpicture->alttext
) {
2502 if (!empty($user->imagealt
)) {
2503 $alt = $user->imagealt
;
2505 $alt = get_string('pictureof', '', fullname($user, $canviewfullnames));
2511 if (empty($userpicture->size
)) {
2513 } else if ($userpicture->size
=== true or $userpicture->size
== 1) {
2516 $size = $userpicture->size
;
2519 $class = $userpicture->class;
2521 if ($user->picture
== 0) {
2522 $class .= ' defaultuserpic';
2525 $src = $userpicture->get_url($this->page
, $this);
2527 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2528 if (!$userpicture->visibletoscreenreaders
) {
2529 $attributes['role'] = 'presentation';
2531 $attributes['aria-hidden'] = 'true';
2535 $attributes['alt'] = $alt;
2536 $attributes['title'] = $alt;
2539 // get the image html output fisrt
2540 $output = html_writer
::empty_tag('img', $attributes);
2542 // Show fullname together with the picture when desired.
2543 if ($userpicture->includefullname
) {
2544 $output .= fullname($userpicture->user
, $canviewfullnames);
2547 // then wrap it in link if needed
2548 if (!$userpicture->link
) {
2552 if (empty($userpicture->courseid
)) {
2553 $courseid = $this->page
->course
->id
;
2555 $courseid = $userpicture->courseid
;
2558 if ($courseid == SITEID
) {
2559 $url = new moodle_url('/user/profile.php', array('id' => $user->id
));
2561 $url = new moodle_url('/user/view.php', array('id' => $user->id
, 'course' => $courseid));
2564 $attributes = array('href'=>$url);
2565 if (!$userpicture->visibletoscreenreaders
) {
2566 $attributes['tabindex'] = '-1';
2567 $attributes['aria-hidden'] = 'true';
2570 if ($userpicture->popup
) {
2571 $id = html_writer
::random_id('userpicture');
2572 $attributes['id'] = $id;
2573 $this->add_action_handler(new popup_action('click', $url), $id);
2576 return html_writer
::tag('a', $output, $attributes);
2580 * Internal implementation of file tree viewer items rendering.
2585 public function htmllize_file_tree($dir) {
2586 if (empty($dir['subdirs']) and empty($dir['files'])) {
2590 foreach ($dir['subdirs'] as $subdir) {
2591 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2593 foreach ($dir['files'] as $file) {
2594 $filename = $file->get_filename();
2595 $result .= '<li><span>'.html_writer
::link($file->fileurl
, $filename).'</span></li>';
2603 * Returns HTML to display the file picker
2606 * $OUTPUT->file_picker($options);
2609 * Theme developers: DO NOT OVERRIDE! Please override function
2610 * {@link core_renderer::render_file_picker()} instead.
2612 * @param array $options associative array with file manager options
2616 * client_id=>uniqid(),
2617 * acepted_types=>'*',
2618 * return_types=>FILE_INTERNAL,
2619 * context=>$PAGE->context
2620 * @return string HTML fragment
2622 public function file_picker($options) {
2623 $fp = new file_picker($options);
2624 return $this->render($fp);
2628 * Internal implementation of file picker rendering.
2630 * @param file_picker $fp
2633 public function render_file_picker(file_picker
$fp) {
2634 global $CFG, $OUTPUT, $USER;
2635 $options = $fp->options
;
2636 $client_id = $options->client_id
;
2637 $strsaved = get_string('filesaved', 'repository');
2638 $straddfile = get_string('openpicker', 'repository');
2639 $strloading = get_string('loading', 'repository');
2640 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2641 $strdroptoupload = get_string('droptoupload', 'moodle');
2642 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2644 $currentfile = $options->currentfile
;
2645 if (empty($currentfile)) {
2648 $currentfile .= ' - ';
2650 if ($options->maxbytes
) {
2651 $size = $options->maxbytes
;
2653 $size = get_max_upload_file_size();
2658 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2660 if ($options->buttonname
) {
2661 $buttonname = ' name="' . $options->buttonname
. '"';
2666 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2669 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2671 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2672 <span> $maxsize </span>
2675 if ($options->env
!= 'url') {
2677 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2678 <div class="filepicker-filename">
2679 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2680 <div class="dndupload-progressbars"></div>
2682 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2691 * @deprecated since Moodle 3.2
2693 public function update_module_button() {
2694 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2695 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2696 'Themes can choose to display the link in the buttons row consistently for all module types.');
2700 * Returns HTML to display a "Turn editing on/off" button in a form.
2702 * @param moodle_url $url The URL + params to send through when clicking the button
2703 * @return string HTML the button
2705 public function edit_button(moodle_url
$url) {
2707 $url->param('sesskey', sesskey());
2708 if ($this->page
->user_is_editing()) {
2709 $url->param('edit', 'off');
2710 $editstring = get_string('turneditingoff');
2712 $url->param('edit', 'on');
2713 $editstring = get_string('turneditingon');
2716 return $this->single_button($url, $editstring);
2720 * Returns HTML to display a simple button to close a window
2722 * @param string $text The lang string for the button's label (already output from get_string())
2723 * @return string html fragment
2725 public function close_window_button($text='') {
2727 $text = get_string('closewindow');
2729 $button = new single_button(new moodle_url('#'), $text, 'get');
2730 $button->add_action(new component_action('click', 'close_window'));
2732 return $this->container($this->render($button), 'closewindow');
2736 * Output an error message. By default wraps the error message in <span class="error">.
2737 * If the error message is blank, nothing is output.
2739 * @param string $message the error message.
2740 * @return string the HTML to output.
2742 public function error_text($message) {
2743 if (empty($message)) {
2746 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2747 return html_writer
::tag('span', $message, array('class' => 'error'));
2751 * Do not call this function directly.
2753 * To terminate the current script with a fatal error, call the {@link print_error}
2754 * function, or throw an exception. Doing either of those things will then call this
2755 * function to display the error, before terminating the execution.
2757 * @param string $message The message to output
2758 * @param string $moreinfourl URL where more info can be found about the error
2759 * @param string $link Link for the Continue button
2760 * @param array $backtrace The execution backtrace
2761 * @param string $debuginfo Debugging information
2762 * @return string the HTML to output.
2764 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2770 if ($this->has_started()) {
2771 // we can not always recover properly here, we have problems with output buffering,
2772 // html tables, etc.
2773 $output .= $this->opencontainers
->pop_all_but_last();
2776 // It is really bad if library code throws exception when output buffering is on,
2777 // because the buffered text would be printed before our start of page.
2778 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2779 error_reporting(0); // disable notices from gzip compression, etc.
2780 while (ob_get_level() > 0) {
2781 $buff = ob_get_clean();
2782 if ($buff === false) {
2787 error_reporting($CFG->debug
);
2789 // Output not yet started.
2790 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ?
$_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2791 if (empty($_SERVER['HTTP_RANGE'])) {
2792 @header
($protocol . ' 404 Not Found');
2793 } else if (core_useragent
::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2794 // Coax iOS 10 into sending the session cookie.
2795 @header
($protocol . ' 403 Forbidden');
2797 // Must stop byteserving attempts somehow,
2798 // this is weird but Chrome PDF viewer can be stopped only with 407!
2799 @header
($protocol . ' 407 Proxy Authentication Required');
2802 $this->page
->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2803 $this->page
->set_url('/'); // no url
2804 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2805 $this->page
->set_title(get_string('error'));
2806 $this->page
->set_heading($this->page
->course
->fullname
);
2807 $output .= $this->header();
2810 $message = '<p class="errormessage">' . $message . '</p>'.
2811 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2812 get_string('moreinformation') . '</a></p>';
2813 if (empty($CFG->rolesactive
)) {
2814 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2815 //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.
2817 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2819 if ($CFG->debugdeveloper
) {
2820 $labelsep = get_string('labelsep', 'langconfig');
2821 if (!empty($debuginfo)) {
2822 $debuginfo = s($debuginfo); // removes all nasty JS
2823 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2824 $label = get_string('debuginfo', 'debug') . $labelsep;
2825 $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
2827 if (!empty($backtrace)) {
2828 $label = get_string('stacktrace', 'debug') . $labelsep;
2829 $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
2831 if ($obbuffer !== '' ) {
2832 $label = get_string('outputbuffer', 'debug') . $labelsep;
2833 $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
2837 if (empty($CFG->rolesactive
)) {
2838 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2839 } else if (!empty($link)) {
2840 $output .= $this->continue_button($link);
2843 $output .= $this->footer();
2845 // Padding to encourage IE to display our error page, rather than its own.
2846 $output .= str_repeat(' ', 512);
2852 * Output a notification (that is, a status message about something that has just happened).
2854 * Note: \core\notification::add() may be more suitable for your usage.
2856 * @param string $message The message to print out.
2857 * @param string $type The type of notification. See constants on \core\output\notification.
2858 * @return string the HTML to output.
2860 public function notification($message, $type = null) {
2863 'success' => \core\output\notification
::NOTIFY_SUCCESS
,
2864 'info' => \core\output\notification
::NOTIFY_INFO
,
2865 'warning' => \core\output\notification
::NOTIFY_WARNING
,
2866 'error' => \core\output\notification
::NOTIFY_ERROR
,
2868 // Legacy types mapped to current types.
2869 'notifyproblem' => \core\output\notification
::NOTIFY_ERROR
,
2870 'notifytiny' => \core\output\notification
::NOTIFY_ERROR
,
2871 'notifyerror' => \core\output\notification
::NOTIFY_ERROR
,
2872 'notifysuccess' => \core\output\notification
::NOTIFY_SUCCESS
,
2873 'notifymessage' => \core\output\notification
::NOTIFY_INFO
,
2874 'notifyredirect' => \core\output\notification
::NOTIFY_INFO
,
2875 'redirectmessage' => \core\output\notification
::NOTIFY_INFO
,
2881 if (strpos($type, ' ') === false) {
2882 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2883 if (isset($typemappings[$type])) {
2884 $type = $typemappings[$type];
2886 // The value provided did not match a known type. It must be an extra class.
2887 $extraclasses = [$type];
2890 // Identify what type of notification this is.
2891 $classarray = explode(' ', self
::prepare_classes($type));
2893 // Separate out the type of notification from the extra classes.
2894 foreach ($classarray as $class) {
2895 if (isset($typemappings[$class])) {
2896 $type = $typemappings[$class];
2898 $extraclasses[] = $class;
2904 $notification = new \core\output\notification
($message, $type);
2905 if (count($extraclasses)) {
2906 $notification->set_extra_classes($extraclasses);
2909 // Return the rendered template.
2910 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2914 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2916 public function notify_problem() {
2917 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
2918 'please use \core\notification::add(), or \core\output\notification as required.');
2922 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2924 public function notify_success() {
2925 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
2926 'please use \core\notification::add(), or \core\output\notification as required.');
2930 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2932 public function notify_message() {
2933 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
2934 'please use \core\notification::add(), or \core\output\notification as required.');
2938 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2940 public function notify_redirect() {
2941 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
2942 'please use \core\notification::add(), or \core\output\notification as required.');
2946 * Render a notification (that is, a status message about something that has
2949 * @param \core\output\notification $notification the notification to print out
2950 * @return string the HTML to output.
2952 protected function render_notification(\core\output\notification
$notification) {
2953 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2957 * Returns HTML to display a continue button that goes to a particular URL.
2959 * @param string|moodle_url $url The url the button goes to.
2960 * @return string the HTML to output.
2962 public function continue_button($url) {
2963 if (!($url instanceof moodle_url
)) {
2964 $url = new moodle_url($url);
2966 $button = new single_button($url, get_string('continue'), 'get', true);
2967 $button->class = 'continuebutton';
2969 return $this->render($button);
2973 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2975 * Theme developers: DO NOT OVERRIDE! Please override function
2976 * {@link core_renderer::render_paging_bar()} instead.
2978 * @param int $totalcount The total number of entries available to be paged through
2979 * @param int $page The page you are currently viewing
2980 * @param int $perpage The number of entries that should be shown per page
2981 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2982 * @param string $pagevar name of page parameter that holds the page number
2983 * @return string the HTML to output.
2985 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2986 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2987 return $this->render($pb);
2991 * Returns HTML to display the paging bar.
2993 * @param paging_bar $pagingbar
2994 * @return string the HTML to output.
2996 protected function render_paging_bar(paging_bar
$pagingbar) {
2997 // Any more than 10 is not usable and causes weird wrapping of the pagination.
2998 $pagingbar->maxdisplay
= 10;
2999 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3003 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3005 * @param string $current the currently selected letter.
3006 * @param string $class class name to add to this initial bar.
3007 * @param string $title the name to put in front of this initial bar.
3008 * @param string $urlvar URL parameter name for this initial.
3009 * @param string $url URL object.
3010 * @param array $alpha of letters in the alphabet.
3011 * @return string the HTML to output.
3013 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3014 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3015 return $this->render($ib);
3019 * Internal implementation of initials bar rendering.
3021 * @param initials_bar $initialsbar
3024 protected function render_initials_bar(initials_bar
$initialsbar) {
3025 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3029 * Output the place a skip link goes to.
3031 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3032 * @return string the HTML to output.
3034 public function skip_link_target($id = null) {
3035 return html_writer
::span('', '', array('id' => $id));
3041 * @param string $text The text of the heading
3042 * @param int $level The level of importance of the heading. Defaulting to 2
3043 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3044 * @param string $id An optional ID
3045 * @return string the HTML to output.
3047 public function heading($text, $level = 2, $classes = null, $id = null) {
3048 $level = (integer) $level;
3049 if ($level < 1 or $level > 6) {
3050 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3052 return html_writer
::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base
::prepare_classes($classes)));
3058 * @param string $contents The contents of the box
3059 * @param string $classes A space-separated list of CSS classes
3060 * @param string $id An optional ID
3061 * @param array $attributes An array of other attributes to give the box.
3062 * @return string the HTML to output.
3064 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3065 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3069 * Outputs the opening section of a box.
3071 * @param string $classes A space-separated list of CSS classes
3072 * @param string $id An optional ID
3073 * @param array $attributes An array of other attributes to give the box.
3074 * @return string the HTML to output.
3076 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3077 $this->opencontainers
->push('box', html_writer
::end_tag('div'));
3078 $attributes['id'] = $id;
3079 $attributes['class'] = 'box py-3 ' . renderer_base
::prepare_classes($classes);
3080 return html_writer
::start_tag('div', $attributes);
3084 * Outputs the closing section of a box.
3086 * @return string the HTML to output.
3088 public function box_end() {
3089 return $this->opencontainers
->pop('box');
3093 * Outputs a container.
3095 * @param string $contents The contents of the box
3096 * @param string $classes A space-separated list of CSS classes
3097 * @param string $id An optional ID
3098 * @return string the HTML to output.
3100 public function container($contents, $classes = null, $id = null) {
3101 return $this->container_start($classes, $id) . $contents . $this->container_end();
3105 * Outputs the opening section of a container.
3107 * @param string $classes A space-separated list of CSS classes
3108 * @param string $id An optional ID
3109 * @return string the HTML to output.
3111 public function container_start($classes = null, $id = null) {
3112 $this->opencontainers
->push('container', html_writer
::end_tag('div'));
3113 return html_writer
::start_tag('div', array('id' => $id,
3114 'class' => renderer_base
::prepare_classes($classes)));
3118 * Outputs the closing section of a container.
3120 * @return string the HTML to output.
3122 public function container_end() {
3123 return $this->opencontainers
->pop('container');
3127 * Make nested HTML lists out of the items
3129 * The resulting list will look something like this:
3133 * <<li>><div class='tree_item parent'>(item contents)</div>
3135 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3141 * @param array $items
3142 * @param array $attrs html attributes passed to the top ofs the list
3143 * @return string HTML
3145 public function tree_block_contents($items, $attrs = array()) {
3146 // exit if empty, we don't want an empty ul element
3147 if (empty($items)) {
3150 // array of nested li elements
3152 foreach ($items as $item) {
3153 // this applies to the li item which contains all child lists too
3154 $content = $item->content($this);
3155 $liclasses = array($item->get_css_type());
3156 if (!$item->forceopen ||
(!$item->forceopen
&& $item->collapse
) ||
($item->children
->count()==0 && $item->nodetype
==navigation_node
::NODETYPE_BRANCH
)) {
3157 $liclasses[] = 'collapsed';
3159 if ($item->isactive
=== true) {
3160 $liclasses[] = 'current_branch';
3162 $liattr = array('class'=>join(' ',$liclasses));
3163 // class attribute on the div item which only contains the item content
3164 $divclasses = array('tree_item');
3165 if ($item->children
->count()>0 ||
$item->nodetype
==navigation_node
::NODETYPE_BRANCH
) {
3166 $divclasses[] = 'branch';
3168 $divclasses[] = 'leaf';
3170 if (!empty($item->classes
) && count($item->classes
)>0) {
3171 $divclasses[] = join(' ', $item->classes
);
3173 $divattr = array('class'=>join(' ', $divclasses));
3174 if (!empty($item->id
)) {
3175 $divattr['id'] = $item->id
;
3177 $content = html_writer
::tag('p', $content, $divattr) . $this->tree_block_contents($item->children
);
3178 if (!empty($item->preceedwithhr
) && $item->preceedwithhr
===true) {
3179 $content = html_writer
::empty_tag('hr') . $content;
3181 $content = html_writer
::tag('li', $content, $liattr);
3184 return html_writer
::tag('ul', implode("\n", $lis), $attrs);
3188 * Returns a search box.
3190 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3191 * @return string HTML with the search form hidden by default.
3193 public function search_box($id = false) {
3196 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3197 // result in an extra included file for each site, even the ones where global search
3199 if (empty($CFG->enableglobalsearch
) ||
!has_capability('moodle/search:query', context_system
::instance())) {
3206 // Needs to be cleaned, we use it for the input id.
3207 $id = clean_param($id, PARAM_ALPHANUMEXT
);
3210 // JS to animate the form.
3211 $this->page
->requires
->js_call_amd('core/search-input', 'init', array($id));
3213 $searchicon = html_writer
::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
3214 array('role' => 'button', 'tabindex' => 0));
3215 $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot
. '/search/index.php');
3216 $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
3217 'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id, 'class' => 'form-control');
3219 $contents = html_writer
::tag('label', get_string('enteryoursearchquery', 'search'),
3220 array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer
::tag('input', '', $inputattrs);
3221 if ($this->page
->context
&& $this->page
->context
->contextlevel
!== CONTEXT_SYSTEM
) {
3222 $contents .= html_writer
::empty_tag('input', ['type' => 'hidden',
3223 'name' => 'context', 'value' => $this->page
->context
->id
]);
3225 $searchinput = html_writer
::tag('form', $contents, $formattrs);
3227 return html_writer
::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper nav-link', 'id' => $id));
3231 * Allow plugins to provide some content to be rendered in the navbar.
3232 * The plugin must define a PLUGIN_render_navbar_output function that returns
3233 * the HTML they wish to add to the navbar.
3235 * @return string HTML for the navbar
3237 public function navbar_plugin_output() {
3240 // Give subsystems an opportunity to inject extra html content. The callback
3241 // must always return a string containing valid html.
3242 foreach (\core_component
::get_core_subsystems() as $name => $path) {
3244 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3248 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3249 foreach ($pluginsfunction as $plugintype => $plugins) {
3250 foreach ($plugins as $pluginfunction) {
3251 $output .= $pluginfunction($this);
3260 * Construct a user menu, returning HTML that can be echoed out by a
3263 * @param stdClass $user A user object, usually $USER.
3264 * @param bool $withlinks true if a dropdown should be built.
3265 * @return string HTML fragment.
3267 public function user_menu($user = null, $withlinks = null) {
3269 require_once($CFG->dirroot
. '/user/lib.php');
3271 if (is_null($user)) {
3275 // Note: this behaviour is intended to match that of core_renderer::login_info,
3276 // but should not be considered to be good practice; layout options are
3277 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3278 if (is_null($withlinks)) {
3279 $withlinks = empty($this->page
->layout_options
['nologinlinks']);
3282 // Add a class for when $withlinks is false.
3283 $usermenuclasses = 'usermenu';
3285 $usermenuclasses .= ' withoutlinks';
3290 // If during initial install, return the empty return string.
3291 if (during_initial_install()) {
3295 $loginpage = $this->is_login_page();
3296 $loginurl = get_login_url();
3297 // If not logged in, show the typical not-logged-in string.
3298 if (!isloggedin()) {
3299 $returnstr = get_string('loggedinnot', 'moodle');
3301 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3303 return html_writer
::div(
3313 // If logged in as a guest user, show a string to that effect.
3314 if (isguestuser()) {
3315 $returnstr = get_string('loggedinasguest');
3316 if (!$loginpage && $withlinks) {
3317 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3320 return html_writer
::div(
3329 // Get some navigation opts.
3330 $opts = user_get_user_navigation_info($user, $this->page
);
3332 $avatarclasses = "avatars";
3333 $avatarcontents = html_writer
::span($opts->metadata
['useravatar'], 'avatar current');
3334 $usertextcontents = $opts->metadata
['userfullname'];
3337 if (!empty($opts->metadata
['asotheruser'])) {
3338 $avatarcontents .= html_writer
::span(
3339 $opts->metadata
['realuseravatar'],
3342 $usertextcontents = $opts->metadata
['realuserfullname'];
3343 $usertextcontents .= html_writer
::tag(
3349 $opts->metadata
['userfullname'],
3353 array('class' => 'meta viewingas')
3358 if (!empty($opts->metadata
['asotherrole'])) {
3359 $role = core_text
::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata
['rolename'])));
3360 $usertextcontents .= html_writer
::span(
3361 $opts->metadata
['rolename'],
3362 'meta role role-' . $role
3366 // User login failures.
3367 if (!empty($opts->metadata
['userloginfail'])) {
3368 $usertextcontents .= html_writer
::span(
3369 $opts->metadata
['userloginfail'],
3370 'meta loginfailures'
3375 if (!empty($opts->metadata
['asmnetuser'])) {
3376 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata
['mnetidprovidername'])));
3377 $usertextcontents .= html_writer
::span(
3378 $opts->metadata
['mnetidprovidername'],
3379 'meta mnet mnet-' . $mnet
3383 $returnstr .= html_writer
::span(
3384 html_writer
::span($usertextcontents, 'usertext mr-1') .
3385 html_writer
::span($avatarcontents, $avatarclasses),
3389 // Create a divider (well, a filler).
3390 $divider = new action_menu_filler();
3391 $divider->primary
= false;
3393 $am = new action_menu();
3394 $am->set_menu_trigger(
3397 $am->set_action_label(get_string('usermenu'));
3398 $am->set_alignment(action_menu
::TR
, action_menu
::BR
);
3399 $am->set_nowrap_on_items();
3401 $navitemcount = count($opts->navitems
);
3403 foreach ($opts->navitems
as $key => $value) {
3405 switch ($value->itemtype
) {
3407 // If the nav item is a divider, add one and skip link processing.
3412 // Silently skip invalid entries (should we post a notification?).
3416 // Process this as a link item.
3418 if (isset($value->pix
) && !empty($value->pix
)) {
3419 $pix = new pix_icon($value->pix
, '', null, array('class' => 'iconsmall'));
3420 } else if (isset($value->imgsrc
) && !empty($value->imgsrc
)) {
3421 $value->title
= html_writer
::img(
3424 array('class' => 'iconsmall')
3428 $al = new action_menu_link_secondary(
3432 array('class' => 'icon')
3434 if (!empty($value->titleidentifier
)) {
3435 $al->attributes
['data-title'] = $value->titleidentifier
;
3443 // Add dividers after the first item and before the last item.
3444 if ($idx == 1 ||
$idx == $navitemcount - 1) {
3450 return html_writer
::div(
3457 * This renders the navbar.
3458 * Uses bootstrap compatible html.
3460 public function navbar() {
3461 return $this->render_from_template('core/navbar', $this->page
->navbar
);
3465 * Renders a breadcrumb navigation node object.
3467 * @param breadcrumb_navigation_node $item The navigation node to render.
3468 * @return string HTML fragment
3470 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node
$item) {
3472 if ($item->action
instanceof moodle_url
) {
3473 $content = $item->get_content();
3474 $title = $item->get_title();
3475 $attributes = array();
3476 $attributes['itemprop'] = 'url';
3477 if ($title !== '') {
3478 $attributes['title'] = $title;
3480 if ($item->hidden
) {
3481 $attributes['class'] = 'dimmed_text';
3483 if ($item->is_last()) {
3484 $attributes['aria-current'] = 'page';
3486 $content = html_writer
::tag('span', $content, array('itemprop' => 'title'));
3487 $content = html_writer
::link($item->action
, $content, $attributes);
3489 $attributes = array();
3490 $attributes['itemscope'] = '';
3491 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3492 $content = html_writer
::tag('span', $content, $attributes);
3495 $content = $this->render_navigation_node($item);
3501 * Renders a navigation node object.
3503 * @param navigation_node $item The navigation node to render.
3504 * @return string HTML fragment
3506 protected function render_navigation_node(navigation_node
$item) {
3507 $content = $item->get_content();
3508 $title = $item->get_title();
3509 if ($item->icon
instanceof renderable
&& !$item->hideicon
) {
3510 $icon = $this->render($item->icon
);
3511 $content = $icon.$content; // use CSS for spacing of icons
3513 if ($item->helpbutton
!== null) {
3514 $content = trim($item->helpbutton
).html_writer
::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3516 if ($content === '') {
3519 if ($item->action
instanceof action_link
) {
3520 $link = $item->action
;
3521 if ($item->hidden
) {
3522 $link->add_class('dimmed');
3524 if (!empty($content)) {
3525 // Providing there is content we will use that for the link content.
3526 $link->text
= $content;
3528 $content = $this->render($link);
3529 } else if ($item->action
instanceof moodle_url
) {
3530 $attributes = array();
3531 if ($title !== '') {
3532 $attributes['title'] = $title;
3534 if ($item->hidden
) {
3535 $attributes['class'] = 'dimmed_text';
3537 $content = html_writer
::link($item->action
, $content, $attributes);
3539 } else if (is_string($item->action
) ||
empty($item->action
)) {
3540 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3541 if ($title !== '') {
3542 $attributes['title'] = $title;
3544 if ($item->hidden
) {
3545 $attributes['class'] = 'dimmed_text';
3547 $content = html_writer
::tag('span', $content, $attributes);
3553 * Accessibility: Right arrow-like character is
3554 * used in the breadcrumb trail, course navigation menu
3555 * (previous/next activity), calendar, and search forum block.
3556 * If the theme does not set characters, appropriate defaults
3557 * are set automatically. Please DO NOT
3558 * use < > » - these are confusing for blind users.
3562 public function rarrow() {
3563 return $this->page
->theme
->rarrow
;
3567 * Accessibility: Left arrow-like character is
3568 * used in the breadcrumb trail, course navigation menu
3569 * (previous/next activity), calendar, and search forum block.
3570 * If the theme does not set characters, appropriate defaults
3571 * are set automatically. Please DO NOT
3572 * use < > » - these are confusing for blind users.
3576 public function larrow() {
3577 return $this->page
->theme
->larrow
;
3581 * Accessibility: Up arrow-like character is used in
3582 * the book heirarchical navigation.
3583 * If the theme does not set characters, appropriate defaults
3584 * are set automatically. Please DO NOT
3585 * use ^ - this is confusing for blind users.
3589 public function uarrow() {
3590 return $this->page
->theme
->uarrow
;
3594 * Accessibility: Down arrow-like character.
3595 * If the theme does not set characters, appropriate defaults
3596 * are set automatically.
3600 public function darrow() {
3601 return $this->page
->theme
->darrow
;
3605 * Returns the custom menu if one has been set
3607 * A custom menu can be configured by browsing to
3608 * Settings: Administration > Appearance > Themes > Theme settings
3609 * and then configuring the custommenu config setting as described.
3611 * Theme developers: DO NOT OVERRIDE! Please override function
3612 * {@link core_renderer::render_custom_menu()} instead.
3614 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3617 public function custom_menu($custommenuitems = '') {
3620 if (empty($custommenuitems) && !empty($CFG->custommenuitems
)) {
3621 $custommenuitems = $CFG->custommenuitems
;
3623 $custommenu = new custom_menu($custommenuitems, current_language());
3624 return $this->render_custom_menu($custommenu);
3628 * We want to show the custom menus as a list of links in the footer on small screens.
3629 * Just return the menu object exported so we can render it differently.
3631 public function custom_menu_flat() {
3633 $custommenuitems = '';
3635 if (empty($custommenuitems) && !empty($CFG->custommenuitems
)) {
3636 $custommenuitems = $CFG->custommenuitems
;
3638 $custommenu = new custom_menu($custommenuitems, current_language());
3639 $langs = get_string_manager()->get_list_of_translations();
3640 $haslangmenu = $this->lang_menu() != '';
3643 $strlang = get_string('language');
3644 $currentlang = current_language();
3645 if (isset($langs[$currentlang])) {
3646 $currentlang = $langs[$currentlang];
3648 $currentlang = $strlang;
3650 $this->language
= $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3651 foreach ($langs as $langtype => $langname) {
3652 $this->language
->add($langname, new moodle_url($this->page
->url
, array('lang' => $langtype)), $langname);
3656 return $custommenu->export_for_template($this);
3660 * Renders a custom menu object (located in outputcomponents.php)
3662 * The custom menu this method produces makes use of the YUI3 menunav widget
3663 * and requires very specific html elements and classes.
3665 * @staticvar int $menucount
3666 * @param custom_menu $menu
3669 protected function render_custom_menu(custom_menu
$menu) {
3672 $langs = get_string_manager()->get_list_of_translations();
3673 $haslangmenu = $this->lang_menu() != '';
3675 if (!$menu->has_children() && !$haslangmenu) {
3680 $strlang = get_string('language');
3681 $currentlang = current_language();
3682 if (isset($langs[$currentlang])) {
3683 $currentlang = $langs[$currentlang];
3685 $currentlang = $strlang;
3687 $this->language
= $menu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3688 foreach ($langs as $langtype => $langname) {
3689 $this->language
->add($langname, new moodle_url($this->page
->url
, array('lang' => $langtype)), $langname);
3694 foreach ($menu->get_children() as $item) {
3695 $context = $item->export_for_template($this);
3696 $content .= $this->render_from_template('core/custom_menu_item', $context);
3703 * Renders a custom menu node as part of a submenu
3705 * The custom menu this method produces makes use of the YUI3 menunav widget
3706 * and requires very specific html elements and classes.
3708 * @see core:renderer::render_custom_menu()
3710 * @staticvar int $submenucount
3711 * @param custom_menu_item $menunode
3714 protected function render_custom_menu_item(custom_menu_item
$menunode) {
3715 // Required to ensure we get unique trackable id's
3716 static $submenucount = 0;
3717 if ($menunode->has_children()) {
3718 // If the child has menus render it as a sub menu
3720 $content = html_writer
::start_tag('li');
3721 if ($menunode->get_url() !== null) {
3722 $url = $menunode->get_url();
3724 $url = '#cm_submenu_'.$submenucount;
3726 $content .= html_writer
::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3727 $content .= html_writer
::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3728 $content .= html_writer
::start_tag('div', array('class'=>'yui3-menu-content'));
3729 $content .= html_writer
::start_tag('ul');
3730 foreach ($menunode->get_children() as $menunode) {
3731 $content .= $this->render_custom_menu_item($menunode);
3733 $content .= html_writer
::end_tag('ul');
3734 $content .= html_writer
::end_tag('div');
3735 $content .= html_writer
::end_tag('div');
3736 $content .= html_writer
::end_tag('li');
3738 // The node doesn't have children so produce a final menuitem.
3739 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3741 if (preg_match("/^#+$/", $menunode->get_text())) {
3743 // This is a divider.
3744 $content = html_writer
::start_tag('li', array('class' => 'yui3-menuitem divider'));
3746 $content = html_writer
::start_tag(
3749 'class' => 'yui3-menuitem'
3752 if ($menunode->get_url() !== null) {
3753 $url = $menunode->get_url();
3757 $content .= html_writer
::link(
3759 $menunode->get_text(),
3760 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3763 $content .= html_writer
::end_tag('li');
3765 // Return the sub menu
3770 * Renders theme links for switching between default and other themes.
3774 protected function theme_switch_links() {
3776 $actualdevice = core_useragent
::get_device_type();
3777 $currentdevice = $this->page
->devicetypeinuse
;
3778 $switched = ($actualdevice != $currentdevice);
3780 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3781 // The user is using the a default device and hasn't switched so don't shown the switch
3787 $linktext = get_string('switchdevicerecommended');
3788 $devicetype = $actualdevice;
3790 $linktext = get_string('switchdevicedefault');
3791 $devicetype = 'default';
3793 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page
->url
, 'device' => $devicetype, 'sesskey' => sesskey()));
3795 $content = html_writer
::start_tag('div', array('id' => 'theme_switch_link'));
3796 $content .= html_writer
::link($linkurl, $linktext, array('rel' => 'nofollow'));
3797 $content .= html_writer
::end_tag('div');
3805 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3807 * Theme developers: In order to change how tabs are displayed please override functions
3808 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3810 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3811 * @param string|null $selected which tab to mark as selected, all parent tabs will
3812 * automatically be marked as activated
3813 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3814 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3817 public final function tabtree($tabs, $selected = null, $inactive = null) {
3818 return $this->render(new tabtree($tabs, $selected, $inactive));
3824 * @param tabtree $tabtree
3827 protected function render_tabtree(tabtree
$tabtree) {
3828 if (empty($tabtree->subtree
)) {
3831 $data = $tabtree->export_for_template($this);
3832 return $this->render_from_template('core/tabtree', $data);
3836 * Renders tabobject (part of tabtree)
3838 * This function is called from {@link core_renderer::render_tabtree()}
3839 * and also it calls itself when printing the $tabobject subtree recursively.
3841 * Property $tabobject->level indicates the number of row of tabs.
3843 * @param tabobject $tabobject
3844 * @return string HTML fragment
3846 protected function render_tabobject(tabobject
$tabobject) {
3849 // Print name of the current tab.
3850 if ($tabobject instanceof tabtree
) {
3851 // No name for tabtree root.
3852 } else if ($tabobject->inactive ||
$tabobject->activated ||
($tabobject->selected
&& !$tabobject->linkedwhenselected
)) {
3853 // Tab name without a link. The <a> tag is used for styling.
3854 $str .= html_writer
::tag('a', html_writer
::span($tabobject->text
), array('class' => 'nolink moodle-has-zindex'));
3856 // Tab name with a link.
3857 if (!($tabobject->link
instanceof moodle_url
)) {
3858 // backward compartibility when link was passed as quoted string
3859 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3861 $str .= html_writer
::link($tabobject->link
, html_writer
::span($tabobject->text
), array('title' => $tabobject->title
));
3865 if (empty($tabobject->subtree
)) {
3866 if ($tabobject->selected
) {
3867 $str .= html_writer
::tag('div', ' ', array('class' => 'tabrow'. ($tabobject->level +
1). ' empty'));
3873 if ($tabobject->level
== 0 ||
$tabobject->selected ||
$tabobject->activated
) {
3874 $str .= html_writer
::start_tag('ul', array('class' => 'tabrow'. $tabobject->level
));
3876 foreach ($tabobject->subtree
as $tab) {
3879 $liclass .= ' first';
3881 if ($cnt == count($tabobject->subtree
) - 1) {
3882 $liclass .= ' last';
3884 if ((empty($tab->subtree
)) && (!empty($tab->selected
))) {
3885 $liclass .= ' onerow';
3888 if ($tab->selected
) {
3889 $liclass .= ' here selected';
3890 } else if ($tab->activated
) {
3891 $liclass .= ' here active';
3894 // This will recursively call function render_tabobject() for each item in subtree.
3895 $str .= html_writer
::tag('li', $this->render($tab), array('class' => trim($liclass)));
3898 $str .= html_writer
::end_tag('ul');
3905 * Get the HTML for blocks in the given region.
3907 * @since Moodle 2.5.1 2.6
3908 * @param string $region The region to get HTML for.
3909 * @return string HTML.
3911 public function blocks($region, $classes = array(), $tag = 'aside') {
3912 $displayregion = $this->page
->apply_theme_region_manipulations($region);
3913 $classes = (array)$classes;
3914 $classes[] = 'block-region';
3915 $attributes = array(
3916 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3917 'class' => join(' ', $classes),
3918 'data-blockregion' => $displayregion,
3919 'data-droptarget' => '1'
3921 if ($this->page
->blocks
->region_has_content($displayregion, $this)) {
3922 $content = $this->blocks_for_region($displayregion);
3926 return html_writer
::tag($tag, $content, $attributes);
3930 * Renders a custom block region.
3932 * Use this method if you want to add an additional block region to the content of the page.
3933 * Please note this should only be used in special situations.
3934 * We want to leave the theme is control where ever possible!
3936 * This method must use the same method that the theme uses within its layout file.
3937 * As such it asks the theme what method it is using.
3938 * It can be one of two values, blocks or blocks_for_region (deprecated).
3940 * @param string $regionname The name of the custom region to add.
3941 * @return string HTML for the block region.
3943 public function custom_block_region($regionname) {
3944 if ($this->page
->theme
->get_block_render_method() === 'blocks') {
3945 return $this->blocks($regionname);
3947 return $this->blocks_for_region($regionname);
3952 * Returns the CSS classes to apply to the body tag.
3954 * @since Moodle 2.5.1 2.6
3955 * @param array $additionalclasses Any additional classes to apply.
3958 public function body_css_classes(array $additionalclasses = array()) {
3959 return $this->page
->bodyclasses
. ' ' . implode(' ', $additionalclasses);
3963 * The ID attribute to apply to the body tag.
3965 * @since Moodle 2.5.1 2.6
3968 public function body_id() {
3969 return $this->page
->bodyid
;
3973 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
3975 * @since Moodle 2.5.1 2.6
3976 * @param string|array $additionalclasses Any additional classes to give the body tag,
3979 public function body_attributes($additionalclasses = array()) {
3980 if (!is_array($additionalclasses)) {
3981 $additionalclasses = explode(' ', $additionalclasses);
3983 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
3987 * Gets HTML for the page heading.
3989 * @since Moodle 2.5.1 2.6
3990 * @param string $tag The tag to encase the heading in. h1 by default.
3991 * @return string HTML.
3993 public function page_heading($tag = 'h1') {
3994 return html_writer
::tag($tag, $this->page
->heading
);
3998 * Gets the HTML for the page heading button.
4000 * @since Moodle 2.5.1 2.6
4001 * @return string HTML.
4003 public function page_heading_button() {
4004 return $this->page
->button
;
4008 * Returns the Moodle docs link to use for this page.
4010 * @since Moodle 2.5.1 2.6
4011 * @param string $text
4014 public function page_doc_link($text = null) {
4015 if ($text === null) {
4016 $text = get_string('moodledocslink');
4018 $path = page_get_doc_link_path($this->page
);
4022 return $this->doc_link($path, $text);
4026 * Returns the page heading menu.
4028 * @since Moodle 2.5.1 2.6
4029 * @return string HTML.
4031 public function page_heading_menu() {
4032 return $this->page
->headingmenu
;
4036 * Returns the title to use on the page.
4038 * @since Moodle 2.5.1 2.6
4041 public function page_title() {
4042 return $this->page
->title
;
4046 * Returns the moodle_url for the favicon.
4048 * @since Moodle 2.5.1 2.6
4049 * @return moodle_url The moodle_url for the favicon
4051 public function favicon() {
4052 return $this->image_url('favicon', 'theme');
4056 * Renders preferences groups.
4058 * @param preferences_groups $renderable The renderable
4059 * @return string The output.
4061 public function render_preferences_groups(preferences_groups
$renderable) {
4062 return $this->render_from_template('core/preferences_groups', $renderable);
4066 * Renders preferences group.
4068 * @param preferences_group $renderable The renderable
4069 * @return string The output.
4071 public function render_preferences_group(preferences_group
$renderable) {
4073 $html .= html_writer
::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4074 $html .= $this->heading($renderable->title
, 3);
4075 $html .= html_writer
::start_tag('ul');
4076 foreach ($renderable->nodes
as $node) {
4077 if ($node->has_children()) {
4078 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER
);
4080 $html .= html_writer
::tag('li', $this->render($node));
4082 $html .= html_writer
::end_tag('ul');
4083 $html .= html_writer
::end_tag('div');
4087 public function context_header($headerinfo = null, $headinglevel = 1) {
4088 global $DB, $USER, $CFG, $SITE;
4089 require_once($CFG->dirroot
. '/user/lib.php');
4090 $context = $this->page
->context
;
4094 $userbuttons = null;
4096 if ($this->should_display_main_logo($headinglevel)) {
4097 $sitename = format_string($SITE->fullname
, true, array('context' => context_course
::instance(SITEID
)));
4098 return html_writer
::div(html_writer
::empty_tag('img', [
4099 'src' => $this->get_logo_url(null, 150), 'alt' => $sitename, 'class' => 'img-fluid']), 'logo');
4102 // Make sure to use the heading if it has been set.
4103 if (isset($headerinfo['heading'])) {
4104 $heading = $headerinfo['heading'];
4107 // The user context currently has images and buttons. Other contexts may follow.
4108 if (isset($headerinfo['user']) ||
$context->contextlevel
== CONTEXT_USER
) {
4109 if (isset($headerinfo['user'])) {
4110 $user = $headerinfo['user'];
4112 // Look up the user information if it is not supplied.
4113 $user = $DB->get_record('user', array('id' => $context->instanceid
));
4116 // If the user context is set, then use that for capability checks.
4117 if (isset($headerinfo['usercontext'])) {
4118 $context = $headerinfo['usercontext'];
4121 // Only provide user information if the user is the current user, or a user which the current user can view.
4122 // When checking user_can_view_profile(), either:
4123 // If the page context is course, check the course context (from the page object) or;
4124 // If page context is NOT course, then check across all courses.
4125 $course = ($this->page
->context
->contextlevel
== CONTEXT_COURSE
) ?
$this->page
->course
: null;
4127 if (user_can_view_profile($user, $course)) {
4128 // Use the user's full name if the heading isn't set.
4129 if (!isset($heading)) {
4130 $heading = fullname($user);
4133 $imagedata = $this->user_picture($user, array('size' => 100));
4135 // Check to see if we should be displaying a message button.
4136 if (!empty($CFG->messaging
) && has_capability('moodle/site:sendmessage', $context)) {
4137 $userbuttons = array(
4138 'messages' => array(
4139 'buttontype' => 'message',
4140 'title' => get_string('message', 'message'),
4141 'url' => new moodle_url('/message/index.php', array('id' => $user->id
)),
4142 'image' => 'message',
4143 'linkattributes' => \core_message\helper
::messageuser_link_params($user->id
),
4144 'page' => $this->page
4148 if ($USER->id
!= $user->id
) {
4149 $iscontact = \core_message\api
::is_contact($USER->id
, $user->id
);
4150 $contacttitle = $iscontact ?
'removefromyourcontacts' : 'addtoyourcontacts';
4151 $contacturlaction = $iscontact ?
'removecontact' : 'addcontact';
4152 $contactimage = $iscontact ?
'removecontact' : 'addcontact';
4153 $userbuttons['togglecontact'] = array(
4154 'buttontype' => 'togglecontact',
4155 'title' => get_string($contacttitle, 'message'),
4156 'url' => new moodle_url('/message/index.php', array(
4157 'user1' => $USER->id
,
4158 'user2' => $user->id
,
4159 $contacturlaction => $user->id
,
4160 'sesskey' => sesskey())
4162 'image' => $contactimage,
4163 'linkattributes' => \core_message\helper
::togglecontact_link_params($user, $iscontact),
4164 'page' => $this->page
4168 $this->page
->requires
->string_for_js('changesmadereallygoaway', 'moodle');
4175 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4176 return $this->render_context_header($contextheader);
4180 * Renders the skip links for the page.
4182 * @param array $links List of skip links.
4183 * @return string HTML for the skip links.
4185 public function render_skip_links($links) {
4186 $context = [ 'links' => []];
4188 foreach ($links as $url => $text) {
4189 $context['links'][] = [ 'url' => $url, 'text' => $text];
4192 return $this->render_from_template('core/skip_links', $context);
4196 * Renders the header bar.
4198 * @param context_header $contextheader Header bar object.
4199 * @return string HTML for the header bar.
4201 protected function render_context_header(context_header
$contextheader) {
4203 $showheader = empty($this->page
->layout_options
['nocontextheader']);
4208 // All the html stuff goes here.
4209 $html = html_writer
::start_div('page-context-header');
4212 if (isset($contextheader->imagedata
)) {
4213 // Header specific image.
4214 $html .= html_writer
::div($contextheader->imagedata
, 'page-header-image');
4218 if (!isset($contextheader->heading
)) {
4219 $headings = $this->heading($this->page
->heading
, $contextheader->headinglevel
);
4221 $headings = $this->heading($contextheader->heading
, $contextheader->headinglevel
);
4224 $html .= html_writer
::tag('div', $headings, array('class' => 'page-header-headings'));
4227 if (isset($contextheader->additionalbuttons
)) {
4228 $html .= html_writer
::start_div('btn-group header-button-group');
4229 foreach ($contextheader->additionalbuttons
as $button) {
4230 if (!isset($button->page
)) {
4231 // Include js for messaging.
4232 if ($button['buttontype'] === 'togglecontact') {
4233 \core_message\helper
::togglecontact_requirejs();
4235 if ($button['buttontype'] === 'message') {
4236 \core_message\helper
::messageuser_requirejs();
4238 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4239 'class' => 'iconsmall',
4240 'role' => 'presentation'
4242 $image .= html_writer
::span($button['title'], 'header-button-title');
4244 $image = html_writer
::empty_tag('img', array(
4245 'src' => $button['formattedimage'],
4246 'role' => 'presentation'
4249 $html .= html_writer
::link($button['url'], html_writer
::tag('span', $image), $button['linkattributes']);
4251 $html .= html_writer
::end_div();
4253 $html .= html_writer
::end_div();
4259 * Wrapper for header elements.
4261 * @return string HTML to display the main header.
4263 public function full_header() {
4266 if ($PAGE->include_region_main_settings_in_header_actions() && !$PAGE->blocks
->is_block_present('settings')) {
4267 // Only include the region main settings if the page has requested it and it doesn't already have
4268 // the settings block on it. The region main settings are included in the settings block and
4269 // duplicating the content causes behat failures.
4270 $PAGE->add_header_action(html_writer
::div(
4271 $this->region_main_settings_menu(),
4273 ['id' => 'region-main-settings-menu']
4277 $header = new stdClass();
4278 $header->settingsmenu
= $this->context_header_settings_menu();
4279 $header->contextheader
= $this->context_header();
4280 $header->hasnavbar
= empty($PAGE->layout_options
['nonavbar']);
4281 $header->navbar
= $this->navbar();
4282 $header->pageheadingbutton
= $this->page_heading_button();
4283 $header->courseheader
= $this->course_header();
4284 $header->headeractions
= $PAGE->get_header_actions();
4285 return $this->render_from_template('core/full_header', $header);
4289 * This is an optional menu that can be added to a layout by a theme. It contains the
4290 * menu for the course administration, only on the course main page.
4294 public function context_header_settings_menu() {
4295 $context = $this->page
->context
;
4296 $menu = new action_menu();
4298 $items = $this->page
->navbar
->get_items();
4299 $currentnode = end($items);
4301 $showcoursemenu = false;
4302 $showfrontpagemenu = false;
4303 $showusermenu = false;
4305 // We are on the course home page.
4306 if (($context->contextlevel
== CONTEXT_COURSE
) &&
4307 !empty($currentnode) &&
4308 ($currentnode->type
== navigation_node
::TYPE_COURSE ||
$currentnode->type
== navigation_node
::TYPE_SECTION
)) {
4309 $showcoursemenu = true;
4312 $courseformat = course_get_format($this->page
->course
);
4313 // This is a single activity course format, always show the course menu on the activity main page.
4314 if ($context->contextlevel
== CONTEXT_MODULE
&&
4315 !$courseformat->has_view_page()) {
4317 $this->page
->navigation
->initialise();
4318 $activenode = $this->page
->navigation
->find_active_node();
4319 // If the settings menu has been forced then show the menu.
4320 if ($this->page
->is_settings_menu_forced()) {
4321 $showcoursemenu = true;
4322 } else if (!empty($activenode) && ($activenode->type
== navigation_node
::TYPE_ACTIVITY ||
4323 $activenode->type
== navigation_node
::TYPE_RESOURCE
)) {
4325 // We only want to show the menu on the first page of the activity. This means
4326 // the breadcrumb has no additional nodes.
4327 if ($currentnode && ($currentnode->key
== $activenode->key
&& $currentnode->type
== $activenode->type
)) {
4328 $showcoursemenu = true;
4333 // This is the site front page.
4334 if ($context->contextlevel
== CONTEXT_COURSE
&&
4335 !empty($currentnode) &&
4336 $currentnode->key
=== 'home') {
4337 $showfrontpagemenu = true;
4340 // This is the user profile page.
4341 if ($context->contextlevel
== CONTEXT_USER
&&
4342 !empty($currentnode) &&
4343 ($currentnode->key
=== 'myprofile')) {
4344 $showusermenu = true;
4347 if ($showfrontpagemenu) {
4348 $settingsnode = $this->page
->settingsnav
->find('frontpage', navigation_node
::TYPE_SETTING
);
4349 if ($settingsnode) {
4350 // Build an action menu based on the visible nodes from this navigation tree.
4351 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4353 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4355 $text = get_string('morenavigationlinks');
4356 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page
->course
->id
));
4357 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4358 $menu->add_secondary_action($link);
4361 } else if ($showcoursemenu) {
4362 $settingsnode = $this->page
->settingsnav
->find('courseadmin', navigation_node
::TYPE_COURSE
);
4363 if ($settingsnode) {
4364 // Build an action menu based on the visible nodes from this navigation tree.
4365 $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4367 // We only add a list to the full settings menu if we didn't include every node in the short menu.
4369 $text = get_string('morenavigationlinks');
4370 $url = new moodle_url('/course/admin.php', array('courseid' => $this->page
->course
->id
));
4371 $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4372 $menu->add_secondary_action($link);
4375 } else if ($showusermenu) {
4376 // Get the course admin node from the settings navigation.
4377 $settingsnode = $this->page
->settingsnav
->find('useraccount', navigation_node
::TYPE_CONTAINER
);
4378 if ($settingsnode) {
4379 // Build an action menu based on the visible nodes from this navigation tree.
4380 $this->build_action_menu_from_navigation($menu, $settingsnode);
4384 return $this->render($menu);
4388 * Take a node in the nav tree and make an action menu out of it.
4389 * The links are injected in the action menu.
4391 * @param action_menu $menu
4392 * @param navigation_node $node
4393 * @param boolean $indent
4394 * @param boolean $onlytopleafnodes
4395 * @return boolean nodesskipped - True if nodes were skipped in building the menu
4397 protected function build_action_menu_from_navigation(action_menu
$menu,
4398 navigation_node
$node,
4400 $onlytopleafnodes = false) {
4402 // Build an action menu based on the visible nodes from this navigation tree.
4403 foreach ($node->children
as $menuitem) {
4404 if ($menuitem->display
) {
4405 if ($onlytopleafnodes && $menuitem->children
->count()) {
4409 if ($menuitem->action
) {
4410 if ($menuitem->action
instanceof action_link
) {
4411 $link = $menuitem->action
;
4412 // Give preference to setting icon over action icon.
4413 if (!empty($menuitem->icon
)) {
4414 $link->icon
= $menuitem->icon
;
4417 $link = new action_link($menuitem->action
, $menuitem->text
, null, null, $menuitem->icon
);
4420 if ($onlytopleafnodes) {
4424 $link = new action_link(new moodle_url('#'), $menuitem->text
, null, ['disabled' => true], $menuitem->icon
);
4427 $link->add_class('ml-4');
4429 if (!empty($menuitem->classes
)) {
4430 $link->add_class(implode(" ", $menuitem->classes
));
4433 $menu->add_secondary_action($link);
4434 $skipped = $skipped ||
$this->build_action_menu_from_navigation($menu, $menuitem, true);
4441 * This is an optional menu that can be added to a layout by a theme. It contains the
4442 * menu for the most specific thing from the settings block. E.g. Module administration.
4446 public function region_main_settings_menu() {
4447 $context = $this->page
->context
;
4448 $menu = new action_menu();
4450 if ($context->contextlevel
== CONTEXT_MODULE
) {
4452 $this->page
->navigation
->initialise();
4453 $node = $this->page
->navigation
->find_active_node();
4455 // If the settings menu has been forced then show the menu.
4456 if ($this->page
->is_settings_menu_forced()) {
4458 } else if (!empty($node) && ($node->type
== navigation_node
::TYPE_ACTIVITY ||
4459 $node->type
== navigation_node
::TYPE_RESOURCE
)) {
4461 $items = $this->page
->navbar
->get_items();
4462 $navbarnode = end($items);
4463 // We only want to show the menu on the first page of the activity. This means
4464 // the breadcrumb has no additional nodes.
4465 if ($navbarnode && ($navbarnode->key
=== $node->key
&& $navbarnode->type
== $node->type
)) {
4470 // Get the course admin node from the settings navigation.
4471 $node = $this->page
->settingsnav
->find('modulesettings', navigation_node
::TYPE_SETTING
);
4473 // Build an action menu based on the visible nodes from this navigation tree.
4474 $this->build_action_menu_from_navigation($menu, $node);
4478 } else if ($context->contextlevel
== CONTEXT_COURSECAT
) {
4479 // For course category context, show category settings menu, if we're on the course category page.
4480 if ($this->page
->pagetype
=== 'course-index-category') {
4481 $node = $this->page
->settingsnav
->find('categorysettings', navigation_node
::TYPE_CONTAINER
);
4483 // Build an action menu based on the visible nodes from this navigation tree.
4484 $this->build_action_menu_from_navigation($menu, $node);
4489 $items = $this->page
->navbar
->get_items();
4490 $navbarnode = end($items);
4492 if ($navbarnode && ($navbarnode->key
=== 'participants')) {
4493 $node = $this->page
->settingsnav
->find('users', navigation_node
::TYPE_CONTAINER
);
4495 // Build an action menu based on the visible nodes from this navigation tree.
4496 $this->build_action_menu_from_navigation($menu, $node);
4501 return $this->render($menu);
4505 * Displays the list of tags associated with an entry
4507 * @param array $tags list of instances of core_tag or stdClass
4508 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4509 * to use default, set to '' (empty string) to omit the label completely
4510 * @param string $classes additional classes for the enclosing div element
4511 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4512 * will be appended to the end, JS will toggle the rest of the tags
4513 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4516 public function tag_list($tags, $label = null, $classes = '', $limit = 10, $pagecontext = null) {
4517 $list = new \core_tag\output\taglist
($tags, $label, $classes, $limit, $pagecontext);
4518 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4522 * Renders element for inline editing of any value
4524 * @param \core\output\inplace_editable $element
4527 public function render_inplace_editable(\core\output\inplace_editable
$element) {
4528 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4532 * Renders a bar chart.
4534 * @param \core\chart_bar $chart The chart.
4537 public function render_chart_bar(\core\chart_bar
$chart) {
4538 return $this->render_chart($chart);
4542 * Renders a line chart.
4544 * @param \core\chart_line $chart The chart.
4547 public function render_chart_line(\core\chart_line
$chart) {
4548 return $this->render_chart($chart);
4552 * Renders a pie chart.
4554 * @param \core\chart_pie $chart The chart.
4557 public function render_chart_pie(\core\chart_pie
$chart) {
4558 return $this->render_chart($chart);
4564 * @param \core\chart_base $chart The chart.
4565 * @param bool $withtable Whether to include a data table with the chart.
4568 public function render_chart(\core\chart_base
$chart, $withtable = true) {
4569 $chartdata = json_encode($chart);
4570 return $this->render_from_template('core/chart', (object) [
4571 'chartdata' => $chartdata,
4572 'withtable' => $withtable
4577 * Renders the login form.
4579 * @param \core_auth\output\login $form The renderable.
4582 public function render_login(\core_auth\output\login
$form) {
4585 $context = $form->export_for_template($this);
4587 // Override because rendering is not supported in template yet.
4588 if ($CFG->rememberusername
== 0) {
4589 $context->cookieshelpiconformatted
= $this->help_icon('cookiesenabledonlysession');
4591 $context->cookieshelpiconformatted
= $this->help_icon('cookiesenabled');
4593 $context->errorformatted
= $this->error_text($context->error
);
4594 $url = $this->get_logo_url();
4596 $url = $url->out(false);
4598 $context->logourl
= $url;
4599 $context->sitename
= format_string($SITE->fullname
, true,
4600 ['context' => context_course
::instance(SITEID
), "escape" => false]);
4602 return $this->render_from_template('core/loginform', $context);
4606 * Renders an mform element from a template.
4608 * @param HTML_QuickForm_element $element element
4609 * @param bool $required if input is required field
4610 * @param bool $advanced if input is an advanced field
4611 * @param string $error error message to display
4612 * @param bool $ingroup True if this element is rendered as part of a group
4613 * @return mixed string|bool
4615 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4616 $templatename = 'core_form/element-' . $element->getType();
4618 $templatename .= "-inline";
4621 // We call this to generate a file not found exception if there is no template.
4622 // We don't want to call export_for_template if there is no template.
4623 core\output\mustache_template_finder
::get_template_filepath($templatename);
4625 if ($element instanceof templatable
) {
4626 $elementcontext = $element->export_for_template($this);
4629 if (method_exists($element, 'getHelpButton')) {
4630 $helpbutton = $element->getHelpButton();
4632 $label = $element->getLabel();
4634 if (method_exists($element, 'getText')) {
4635 // There currently exists code that adds a form element with an empty label.
4636 // If this is the case then set the label to the description.
4637 if (empty($label)) {
4638 $label = $element->getText();
4640 $text = $element->getText();
4644 // Generate the form element wrapper ids and names to pass to the template.
4645 // This differs between group and non-group elements.
4646 if ($element->getType() === 'group') {
4648 // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
4649 $elementcontext['wrapperid'] = $elementcontext['id'];
4651 // Ensure group elements pass through the group name as the element name.
4652 $elementcontext['name'] = $elementcontext['groupname'];
4654 // Non grouped element.
4655 // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
4656 $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
4660 'element' => $elementcontext,
4663 'required' => $required,
4664 'advanced' => $advanced,
4665 'helpbutton' => $helpbutton,
4668 return $this->render_from_template($templatename, $context);
4670 } catch (Exception
$e) {
4671 // No template for this element.
4677 * Render the login signup form into a nice template for the theme.
4679 * @param mform $form
4682 public function render_login_signup_form($form) {
4685 $context = $form->export_for_template($this);
4686 $url = $this->get_logo_url();
4688 $url = $url->out(false);
4690 $context['logourl'] = $url;
4691 $context['sitename'] = format_string($SITE->fullname
, true,
4692 ['context' => context_course
::instance(SITEID
), "escape" => false]);
4694 return $this->render_from_template('core/signup_form_layout', $context);
4698 * Render the verify age and location page into a nice template for the theme.
4700 * @param \core_auth\output\verify_age_location_page $page The renderable
4703 protected function render_verify_age_location_page($page) {
4704 $context = $page->export_for_template($this);
4706 return $this->render_from_template('core/auth_verify_age_location_page', $context);
4710 * Render the digital minor contact information page into a nice template for the theme.
4712 * @param \core_auth\output\digital_minor_page $page The renderable
4715 protected function render_digital_minor_page($page) {
4716 $context = $page->export_for_template($this);
4718 return $this->render_from_template('core/auth_digital_minor_page', $context);
4722 * Renders a progress bar.
4724 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4726 * @param progress_bar $bar The bar.
4727 * @return string HTML fragment
4729 public function render_progress_bar(progress_bar
$bar) {
4731 $data = $bar->export_for_template($this);
4732 return $this->render_from_template('core/progress_bar', $data);
4736 * Renders element for a toggle-all checkbox.
4738 * @param \core\output\checkbox_toggleall $element
4741 public function render_checkbox_toggleall(\core\output\checkbox_toggleall
$element) {
4742 return $this->render_from_template($element->get_template(), $element->export_for_template($this));
4747 * A renderer that generates output for command-line scripts.
4749 * The implementation of this renderer is probably incomplete.
4751 * @copyright 2009 Tim Hunt
4752 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4757 class core_renderer_cli
extends core_renderer
{
4760 * Returns the page header.
4762 * @return string HTML fragment
4764 public function header() {
4765 return $this->page
->heading
. "\n";
4769 * Returns a template fragment representing a Heading.
4771 * @param string $text The text of the heading
4772 * @param int $level The level of importance of the heading
4773 * @param string $classes A space-separated list of CSS classes
4774 * @param string $id An optional ID
4775 * @return string A template fragment for a heading
4777 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4781 return '=>' . $text;
4783 return '-->' . $text;
4790 * Returns a template fragment representing a fatal error.
4792 * @param string $message The message to output
4793 * @param string $moreinfourl URL where more info can be found about the error
4794 * @param string $link Link for the Continue button
4795 * @param array $backtrace The execution backtrace
4796 * @param string $debuginfo Debugging information
4797 * @return string A template fragment for a fatal error
4799 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4802 $output = "!!! $message !!!\n";
4804 if ($CFG->debugdeveloper
) {
4805 if (!empty($debuginfo)) {
4806 $output .= $this->notification($debuginfo, 'notifytiny');
4808 if (!empty($backtrace)) {
4809 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
4817 * Returns a template fragment representing a notification.
4819 * @param string $message The message to print out.
4820 * @param string $type The type of notification. See constants on \core\output\notification.
4821 * @return string A template fragment for a notification
4823 public function notification($message, $type = null) {
4824 $message = clean_text($message);
4825 if ($type === 'notifysuccess' ||
$type === 'success') {
4826 return "++ $message ++\n";
4828 return "!! $message !!\n";
4832 * There is no footer for a cli request, however we must override the
4833 * footer method to prevent the default footer.
4835 public function footer() {}
4838 * Render a notification (that is, a status message about something that has
4841 * @param \core\output\notification $notification the notification to print out
4842 * @return string plain text output
4844 public function render_notification(\core\output\notification
$notification) {
4845 return $this->notification($notification->get_message(), $notification->get_message_type());
4851 * A renderer that generates output for ajax scripts.
4853 * This renderer prevents accidental sends back only json
4854 * encoded error messages, all other output is ignored.
4856 * @copyright 2010 Petr Skoda
4857 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4862 class core_renderer_ajax
extends core_renderer
{
4865 * Returns a template fragment representing a fatal error.
4867 * @param string $message The message to output
4868 * @param string $moreinfourl URL where more info can be found about the error
4869 * @param string $link Link for the Continue button
4870 * @param array $backtrace The execution backtrace
4871 * @param string $debuginfo Debugging information
4872 * @return string A template fragment for a fatal error
4874 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4877 $this->page
->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
4879 $e = new stdClass();
4880 $e->error
= $message;
4881 $e->errorcode
= $errorcode;
4882 $e->stacktrace
= NULL;
4883 $e->debuginfo
= NULL;
4884 $e->reproductionlink
= NULL;
4885 if (!empty($CFG->debug
) and $CFG->debug
>= DEBUG_DEVELOPER
) {
4886 $link = (string) $link;
4888 $e->reproductionlink
= $link;
4890 if (!empty($debuginfo)) {
4891 $e->debuginfo
= $debuginfo;
4893 if (!empty($backtrace)) {
4894 $e->stacktrace
= format_backtrace($backtrace, true);
4898 return json_encode($e);
4902 * Used to display a notification.
4903 * For the AJAX notifications are discarded.
4905 * @param string $message The message to print out.
4906 * @param string $type The type of notification. See constants on \core\output\notification.
4908 public function notification($message, $type = null) {}
4911 * Used to display a redirection message.
4912 * AJAX redirections should not occur and as such redirection messages
4915 * @param moodle_url|string $encodedurl
4916 * @param string $message
4918 * @param bool $debugdisableredirect
4919 * @param string $messagetype The type of notification to show the message in.
4920 * See constants on \core\output\notification.
4922 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
4923 $messagetype = \core\output\notification
::NOTIFY_INFO
) {}
4926 * Prepares the start of an AJAX output.
4928 public function header() {
4929 // unfortunately YUI iframe upload does not support application/json
4930 if (!empty($_FILES)) {
4931 @header
('Content-type: text/plain; charset=utf-8');
4932 if (!core_useragent
::supports_json_contenttype()) {
4933 @header
('X-Content-Type-Options: nosniff');
4935 } else if (!core_useragent
::supports_json_contenttype()) {
4936 @header
('Content-type: text/plain; charset=utf-8');
4937 @header
('X-Content-Type-Options: nosniff');
4939 @header
('Content-type: application/json; charset=utf-8');
4942 // Headers to make it not cacheable and json
4943 @header
('Cache-Control: no-store, no-cache, must-revalidate');
4944 @header
('Cache-Control: post-check=0, pre-check=0', false);
4945 @header
('Pragma: no-cache');
4946 @header
('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
4947 @header
('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
4948 @header
('Accept-Ranges: none');
4952 * There is no footer for an AJAX request, however we must override the
4953 * footer method to prevent the default footer.
4955 public function footer() {}
4958 * No need for headers in an AJAX request... this should never happen.
4959 * @param string $text
4961 * @param string $classes
4964 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
4970 * The maintenance renderer.
4972 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
4973 * is running a maintenance related task.
4974 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
4979 * @copyright 2013 Sam Hemelryk
4980 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4982 class core_renderer_maintenance
extends core_renderer
{
4985 * Initialises the renderer instance.
4987 * @param moodle_page $page
4988 * @param string $target
4989 * @throws coding_exception
4991 public function __construct(moodle_page
$page, $target) {
4992 if ($target !== RENDERER_TARGET_MAINTENANCE ||
$page->pagelayout
!== 'maintenance') {
4993 throw new coding_exception('Invalid request for the maintenance renderer.');
4995 parent
::__construct($page, $target);
4999 * Does nothing. The maintenance renderer cannot produce blocks.
5001 * @param block_contents $bc
5002 * @param string $region
5005 public function block(block_contents
$bc, $region) {
5010 * Does nothing. The maintenance renderer cannot produce blocks.
5012 * @param string $region
5013 * @param array $classes
5014 * @param string $tag
5017 public function blocks($region, $classes = array(), $tag = 'aside') {
5022 * Does nothing. The maintenance renderer cannot produce blocks.
5024 * @param string $region
5027 public function blocks_for_region($region) {
5032 * Does nothing. The maintenance renderer cannot produce a course content header.
5034 * @param bool $onlyifnotcalledbefore
5037 public function course_content_header($onlyifnotcalledbefore = false) {
5042 * Does nothing. The maintenance renderer cannot produce a course content footer.
5044 * @param bool $onlyifnotcalledbefore
5047 public function course_content_footer($onlyifnotcalledbefore = false) {
5052 * Does nothing. The maintenance renderer cannot produce a course header.
5056 public function course_header() {
5061 * Does nothing. The maintenance renderer cannot produce a course footer.
5065 public function course_footer() {
5070 * Does nothing. The maintenance renderer cannot produce a custom menu.
5072 * @param string $custommenuitems
5075 public function custom_menu($custommenuitems = '') {
5080 * Does nothing. The maintenance renderer cannot produce a file picker.
5082 * @param array $options
5085 public function file_picker($options) {
5090 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
5095 public function htmllize_file_tree($dir) {
5101 * Overridden confirm message for upgrades.
5103 * @param string $message The question to ask the user
5104 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5105 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5106 * @return string HTML fragment
5108 public function confirm($message, $continue, $cancel) {
5109 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5110 // from any previous version of Moodle).
5111 if ($continue instanceof single_button
) {
5112 $continue->primary
= true;
5113 } else if (is_string($continue)) {
5114 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
5115 } else if ($continue instanceof moodle_url
) {
5116 $continue = new single_button($continue, get_string('continue'), 'post', true);
5118 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5119 ' (string/moodle_url) or a single_button instance.');
5122 if ($cancel instanceof single_button
) {
5124 } else if (is_string($cancel)) {
5125 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5126 } else if ($cancel instanceof moodle_url
) {
5127 $cancel = new single_button($cancel, get_string('cancel'), 'get');
5129 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5130 ' (string/moodle_url) or a single_button instance.');
5133 $output = $this->box_start('generalbox', 'notice');
5134 $output .= html_writer
::tag('h4', get_string('confirm'));
5135 $output .= html_writer
::tag('p', $message);
5136 $output .= html_writer
::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
5137 $output .= $this->box_end();
5142 * Does nothing. The maintenance renderer does not support JS.
5144 * @param block_contents $bc
5146 public function init_block_hider_js(block_contents
$bc) {
5151 * Does nothing. The maintenance renderer cannot produce language menus.
5155 public function lang_menu() {
5160 * Does nothing. The maintenance renderer has no need for login information.
5162 * @param null $withlinks
5165 public function login_info($withlinks = null) {
5170 * Secure login info.
5174 public function secure_login_info() {
5175 return $this->login_info(false);
5179 * Does nothing. The maintenance renderer cannot produce user pictures.
5181 * @param stdClass $user
5182 * @param array $options
5185 public function user_picture(stdClass
$user, array $options = null) {