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) {
395 // Only render the logo if we're on the front page or login page and the we have a logo.
396 $logo = $this->get_logo_url();
397 if ($headinglevel == 1 && !empty($logo)) {
398 if ($this->page->pagelayout == 'frontpage' || $this->page->pagelayout == 'login') {
410 * Basis for all plugin renderers.
412 * @copyright Petr Skoda (skodak)
413 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
418 class plugin_renderer_base extends renderer_base {
421 * @var renderer_base|core_renderer A reference to the current renderer.
422 * The renderer provided here will be determined by the page but will in 90%
423 * of cases by the {@link core_renderer}
428 * Constructor method, calls the parent constructor
430 * @param moodle_page $page
431 * @param string $target one of rendering target constants
433 public function __construct(moodle_page $page, $target) {
434 if (empty($target) && $page->pagelayout === 'maintenance') {
435 // If the page is using the maintenance layout then we're going to force the target to maintenance.
436 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
437 // unavailable for this page layout.
438 $target = RENDERER_TARGET_MAINTENANCE;
440 $this->output = $page->get_renderer('core', null, $target);
441 parent::__construct($page, $target);
445 * Renders the provided widget and returns the HTML to display it.
447 * @param renderable $widget instance with renderable interface
450 public function render(renderable $widget) {
451 $classname = get_class($widget);
453 $classname = preg_replace('/^.*\\\/', '', $classname);
454 // Keep a copy at this point, we may need to look for a deprecated method.
455 $deprecatedmethod = 'render_'.$classname;
456 // Remove _renderable suffixes
457 $classname = preg_replace('/_renderable$/', '', $classname);
459 $rendermethod = 'render_'.$classname;
460 if (method_exists($this, $rendermethod)) {
461 return $this->$rendermethod($widget);
463 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
464 // This is exactly where we don't want to be.
465 // If you have arrived here you have a renderable component within your plugin that has the name
466 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
467 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
468 // and the _renderable suffix now gets removed when looking for a render method.
469 // You need to change your renderers render_blah_renderable to render_blah.
470 // Until you do this it will not be possible for a theme to override the renderer to override your method.
471 // Please do it ASAP.
472 static $debugged = array();
473 if (!isset($debugged[$deprecatedmethod])) {
474 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
475 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
476 $debugged[$deprecatedmethod] = true;
478 return $this->$deprecatedmethod($widget);
480 // pass to core renderer if method not found here
481 return $this->output->render($widget);
485 * Magic method used to pass calls otherwise meant for the standard renderer
486 * to it to ensure we don't go causing unnecessary grief.
488 * @param string $method
489 * @param array $arguments
492 public function __call($method, $arguments) {
493 if (method_exists('renderer_base', $method)) {
494 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
496 if (method_exists($this->output, $method)) {
497 return call_user_func_array(array($this->output, $method), $arguments);
499 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
506 * The standard implementation of the core_renderer interface.
508 * @copyright 2009 Tim Hunt
509 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
514 class core_renderer extends renderer_base {
516 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
517 * in layout files instead.
519 * @var string used in {@link core_renderer::header()}.
521 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
524 * @var string Used to pass information from {@link core_renderer::doctype()} to
525 * {@link core_renderer::standard_head_html()}.
527 protected $contenttype;
530 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
531 * with {@link core_renderer::header()}.
533 protected $metarefreshtag = '';
536 * @var string Unique token for the closing HTML
538 protected $unique_end_html_token;
541 * @var string Unique token for performance information
543 protected $unique_performance_info_token;
546 * @var string Unique token for the main content.
548 protected $unique_main_content_token;
550 /** @var custom_menu_item language The language menu if created */
551 protected $language = null;
556 * @param moodle_page $page the page we are doing output for.
557 * @param string $target one of rendering target constants
559 public function __construct(moodle_page $page, $target) {
560 $this->opencontainers = $page->opencontainers;
562 $this->target = $target;
564 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
565 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
566 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
570 * Get the DOCTYPE declaration that should be used with this page. Designed to
571 * be called in theme layout.php files.
573 * @return string the DOCTYPE declaration that should be used.
575 public function doctype() {
576 if ($this->page->theme->doctype === 'html5') {
577 $this->contenttype = 'text/html; charset=utf-8';
578 return "<!DOCTYPE html>\n";
580 } else if ($this->page->theme->doctype === 'xhtml5') {
581 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
582 return "<!DOCTYPE html>\n";
586 $this->contenttype = 'text/html; charset=utf-8';
587 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
592 * The attributes that should be added to the <html> tag. Designed to
593 * be called in theme layout.php files.
595 * @return string HTML fragment.
597 public function htmlattributes() {
598 $return = get_html_lang(true);
599 $attributes = array();
600 if ($this->page->theme->doctype !== 'html5') {
601 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
604 // Give plugins an opportunity to add things like xml namespaces to the html element.
605 // This function should return an array of html attribute names => values.
606 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
607 foreach ($pluginswithfunction as $plugins) {
608 foreach ($plugins as $function) {
609 $newattrs = $function();
610 unset($newattrs['dir']);
611 unset($newattrs['lang']);
612 unset($newattrs['xmlns']);
613 unset($newattrs['xml:lang']);
614 $attributes += $newattrs;
618 foreach ($attributes as $key => $val) {
620 $return .= " $key=\"$val\"";
627 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
628 * that should be included in the <head> tag. Designed to be called in theme
631 * @return string HTML fragment.
633 public function standard_head_html() {
634 global $CFG, $SESSION, $SITE;
636 // Before we output any content, we need to ensure that certain
637 // page components are set up.
639 // Blocks must be set up early as they may require javascript which
640 // has to be included in the page header before output is created.
641 foreach ($this->page->blocks->get_regions() as $region) {
642 $this->page->blocks->ensure_content_created($region, $this);
647 // Give plugins an opportunity to add any head elements. The callback
648 // must always return a string containing valid html head content.
649 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
650 foreach ($pluginswithfunction as $plugins) {
651 foreach ($plugins as $function) {
652 $output .= $function();
656 // Allow a url_rewrite plugin to setup any dynamic head content.
657 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
658 $class = $CFG->urlrewriteclass;
659 $output .= $class::html_head_setup();
662 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
663 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
664 // This is only set by the {@link redirect()} method
665 $output .= $this->metarefreshtag;
667 // Check if a periodic refresh delay has been set and make sure we arn't
668 // already meta refreshing
669 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
670 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
673 // Set up help link popups for all links with the helptooltip class
674 $this->page->requires->js_init_call('M.util.help_popups.setup');
676 $focus = $this->page->focuscontrol;
677 if (!empty($focus)) {
678 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
679 // This is a horrifically bad way to handle focus but it is passed in
680 // through messy formslib::moodleform
681 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
682 } else if (strpos($focus, '.')!==false) {
683 // Old style of focus, bad way to do it
684 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);
685 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
687 // Focus element with given id
688 $this->page->requires->js_function_call('focuscontrol', array($focus));
692 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
693 // any other custom CSS can not be overridden via themes and is highly discouraged
694 $urls = $this->page->theme->css_urls($this->page);
695 foreach ($urls as $url) {
696 $this->page->requires->css_theme($url);
699 // Get the theme javascript head and footer
700 if ($jsurl = $this->page->theme->javascript_url(true)) {
701 $this->page->requires->js($jsurl, true);
703 if ($jsurl = $this->page->theme->javascript_url(false)) {
704 $this->page->requires->js($jsurl);
707 // Get any HTML from the page_requirements_manager.
708 $output .= $this->page->requires->get_head_code($this->page, $this);
710 // List alternate versions.
711 foreach ($this->page->alternateversions as $type => $alt) {
712 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
713 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
716 // Add noindex tag if relevant page and setting applied.
717 $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
718 $loginpages = array('login-index', 'login-signup');
719 if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
720 if (!isset($CFG->additionalhtmlhead)) {
721 $CFG->additionalhtmlhead = '';
723 $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
726 if (!empty($CFG->additionalhtmlhead)) {
727 $output .= "\n".$CFG->additionalhtmlhead;
730 if ($this->page->pagelayout == 'frontpage') {
731 $summary = s(strip_tags(format_text($SITE->summary, FORMAT_HTML)));
732 if (!empty($summary)) {
733 $output .= "<meta name=\"description\" content=\"$summary\" />\n";
741 * The standard tags (typically skip links) that should be output just inside
742 * the start of the <body> tag. Designed to be called in theme layout.php files.
744 * @return string HTML fragment.
746 public function standard_top_of_body_html() {
748 $output = $this->page->requires->get_top_of_body_code($this);
749 if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
750 $output .= "\n".$CFG->additionalhtmltopofbody;
753 // Give subsystems an opportunity to inject extra html content. The callback
754 // must always return a string containing valid html.
755 foreach (\core_component::get_core_subsystems() as $name => $path) {
757 $output .= component_callback($name, 'before_standard_top_of_body_html', [], '');
761 // Give plugins an opportunity to inject extra html content. The callback
762 // must always return a string containing valid html.
763 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
764 foreach ($pluginswithfunction as $plugins) {
765 foreach ($plugins as $function) {
766 $output .= $function();
770 $output .= $this->maintenance_warning();
776 * Scheduled maintenance warning message.
778 * Note: This is a nasty hack to display maintenance notice, this should be moved
779 * to some general notification area once we have it.
783 public function maintenance_warning() {
787 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
788 $timeleft = $CFG->maintenance_later - time();
789 // If timeleft less than 30 sec, set the class on block to error to highlight.
790 $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
791 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-a-1 alert');
793 $a->hour = (int)($timeleft / 3600);
794 $a->min = (int)(($timeleft / 60) % 60);
795 $a->sec = (int)($timeleft % 60);
797 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
799 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
802 $output .= $this->box_end();
803 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
804 array(array('timeleftinsec' => $timeleft)));
805 $this->page->requires->strings_for_js(
806 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
813 * The standard tags (typically performance information and validation links,
814 * if we are in developer debug mode) that should be output in the footer area
815 * of the page. Designed to be called in theme layout.php files.
817 * @return string HTML fragment.
819 public function standard_footer_html() {
820 global $CFG, $SCRIPT;
823 if (during_initial_install()) {
824 // Debugging info can not work before install is finished,
825 // in any case we do not want any links during installation!
829 // Give plugins an opportunity to add any footer elements.
830 // The callback must always return a string containing valid html footer content.
831 $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
832 foreach ($pluginswithfunction as $plugins) {
833 foreach ($plugins as $function) {
834 $output .= $function();
838 // This function is normally called from a layout.php file in {@link core_renderer::header()}
839 // but some of the content won't be known until later, so we return a placeholder
840 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
841 $output .= $this->unique_performance_info_token;
842 if ($this->page->devicetypeinuse == 'legacy') {
843 // The legacy theme is in use print the notification
844 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
847 // Get links to switch device types (only shown for users not on a default device)
848 $output .= $this->theme_switch_links();
850 if (!empty($CFG->debugpageinfo)) {
851 $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
852 $this->page->debug_summary()) . '</div>';
854 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
855 // Add link to profiling report if necessary
856 if (function_exists('profiling_is_running') && profiling_is_running()) {
857 $txt = get_string('profiledscript', 'admin');
858 $title = get_string('profiledscriptview', 'admin');
859 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
860 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
861 $output .= '<div class="profilingfooter">' . $link . '</div>';
863 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
864 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
865 $output .= '<div class="purgecaches">' .
866 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
868 if (!empty($CFG->debugvalidators)) {
869 // NOTE: this is not a nice hack, $this->page->url is not always accurate and
870 // $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.
1257 * @return string HTML that you must output this, preferably immediately.
1259 public function header() {
1260 global $USER, $CFG, $SESSION;
1262 // Give plugins an opportunity touch things before the http headers are sent
1263 // such as adding additional headers. The return value is ignored.
1264 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1265 foreach ($pluginswithfunction as $plugins) {
1266 foreach ($plugins as $function) {
1271 if (\core\session\manager::is_loggedinas()) {
1272 $this->page->add_body_class('userloggedinas');
1275 if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1276 require_once($CFG->dirroot . '/user/lib.php');
1277 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1278 if ($count = user_count_login_failures($USER, false)) {
1279 $this->page->add_body_class('loginfailures');
1283 // If the user is logged in, and we're not in initial install,
1284 // check to see if the user is role-switched and add the appropriate
1285 // CSS class to the body element.
1286 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1287 $this->page->add_body_class('userswitchedrole');
1290 // Give themes a chance to init/alter the page object.
1291 $this->page->theme->init_page($this->page);
1293 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1295 // Find the appropriate page layout file, based on $this->page->pagelayout.
1296 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1297 // Render the layout using the layout file.
1298 $rendered = $this->render_page_layout($layoutfile);
1300 // Slice the rendered output into header and footer.
1301 $cutpos = strpos($rendered, $this->unique_main_content_token);
1302 if ($cutpos === false) {
1303 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1304 $token = self::MAIN_CONTENT_TOKEN;
1306 $token = $this->unique_main_content_token;
1309 if ($cutpos === false) {
1310 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.');
1312 $header = substr($rendered, 0, $cutpos);
1313 $footer = substr($rendered, $cutpos + strlen($token));
1315 if (empty($this->contenttype)) {
1316 debugging('The page layout file did not call $OUTPUT->doctype()');
1317 $header = $this->doctype() . $header;
1320 // If this theme version is below 2.4 release and this is a course view page
1321 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1322 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1323 // check if course content header/footer have not been output during render of theme layout
1324 $coursecontentheader = $this->course_content_header(true);
1325 $coursecontentfooter = $this->course_content_footer(true);
1326 if (!empty($coursecontentheader)) {
1327 // display debug message and add header and footer right above and below main content
1328 // Please note that course header and footer (to be displayed above and below the whole page)
1329 // are not displayed in this case at all.
1330 // Besides the content header and footer are not displayed on any other course page
1331 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);
1332 $header .= $coursecontentheader;
1333 $footer = $coursecontentfooter. $footer;
1337 send_headers($this->contenttype, $this->page->cacheable);
1339 $this->opencontainers->push('header/footer', $footer);
1340 $this->page->set_state(moodle_page::STATE_IN_BODY);
1342 return $header . $this->skip_link_target('maincontent');
1346 * Renders and outputs the page layout file.
1348 * This is done by preparing the normal globals available to a script, and
1349 * then including the layout file provided by the current theme for the
1352 * @param string $layoutfile The name of the layout file
1353 * @return string HTML code
1355 protected function render_page_layout($layoutfile) {
1356 global $CFG, $SITE, $USER;
1357 // The next lines are a bit tricky. The point is, here we are in a method
1358 // of a renderer class, and this object may, or may not, be the same as
1359 // the global $OUTPUT object. When rendering the page layout file, we want to use
1360 // this object. However, people writing Moodle code expect the current
1361 // renderer to be called $OUTPUT, not $this, so define a variable called
1362 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1364 $PAGE = $this->page;
1365 $COURSE = $this->page->course;
1368 include($layoutfile);
1369 $rendered = ob_get_contents();
1375 * Outputs the page's footer
1377 * @return string HTML fragment
1379 public function footer() {
1382 // Give plugins an opportunity to touch the page before JS is finalized.
1383 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1384 foreach ($pluginswithfunction as $plugins) {
1385 foreach ($plugins as $function) {
1390 $output = $this->container_end_all(true);
1392 $footer = $this->opencontainers->pop('header/footer');
1394 if (debugging() and $DB and $DB->is_transaction_started()) {
1395 // TODO: MDL-20625 print warning - transaction will be rolled back
1398 // Provide some performance info if required
1399 $performanceinfo = '';
1400 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1401 $perf = get_performance_info();
1402 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1403 $performanceinfo = $perf['html'];
1407 // We always want performance data when running a performance test, even if the user is redirected to another page.
1408 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1409 $footer = $this->unique_performance_info_token . $footer;
1411 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1413 // Only show notifications when the current page has a context id.
1414 if (!empty($this->page->context->id)) {
1415 $this->page->requires->js_call_amd('core/notification', 'init', array(
1416 $this->page->context->id,
1417 \core\notification::fetch_as_array($this),
1421 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1423 $this->page->set_state(moodle_page::STATE_DONE);
1425 return $output . $footer;
1429 * Close all but the last open container. This is useful in places like error
1430 * handling, where you want to close all the open containers (apart from <body>)
1431 * before outputting the error message.
1433 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1434 * developer debug warning if it isn't.
1435 * @return string the HTML required to close any open containers inside <body>.
1437 public function container_end_all($shouldbenone = false) {
1438 return $this->opencontainers->pop_all_but_last($shouldbenone);
1442 * Returns course-specific information to be output immediately above content on any course page
1443 * (for the current course)
1445 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1448 public function course_content_header($onlyifnotcalledbefore = false) {
1450 static $functioncalled = false;
1451 if ($functioncalled && $onlyifnotcalledbefore) {
1452 // we have already output the content header
1456 // Output any session notification.
1457 $notifications = \core\notification::fetch();
1459 $bodynotifications = '';
1460 foreach ($notifications as $notification) {
1461 $bodynotifications .= $this->render_from_template(
1462 $notification->get_template_name(),
1463 $notification->export_for_template($this)
1467 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1469 if ($this->page->course->id == SITEID) {
1470 // return immediately and do not include /course/lib.php if not necessary
1474 require_once($CFG->dirroot.'/course/lib.php');
1475 $functioncalled = true;
1476 $courseformat = course_get_format($this->page->course);
1477 if (($obj = $courseformat->course_content_header()) !== null) {
1478 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1484 * Returns course-specific information to be output immediately below content on any course page
1485 * (for the current course)
1487 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1490 public function course_content_footer($onlyifnotcalledbefore = false) {
1492 if ($this->page->course->id == SITEID) {
1493 // return immediately and do not include /course/lib.php if not necessary
1496 static $functioncalled = false;
1497 if ($functioncalled && $onlyifnotcalledbefore) {
1498 // we have already output the content footer
1501 $functioncalled = true;
1502 require_once($CFG->dirroot.'/course/lib.php');
1503 $courseformat = course_get_format($this->page->course);
1504 if (($obj = $courseformat->course_content_footer()) !== null) {
1505 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1511 * Returns course-specific information to be output on any course page in the header area
1512 * (for the current course)
1516 public function course_header() {
1518 if ($this->page->course->id == SITEID) {
1519 // return immediately and do not include /course/lib.php if not necessary
1522 require_once($CFG->dirroot.'/course/lib.php');
1523 $courseformat = course_get_format($this->page->course);
1524 if (($obj = $courseformat->course_header()) !== null) {
1525 return $courseformat->get_renderer($this->page)->render($obj);
1531 * Returns course-specific information to be output on any course page in the footer area
1532 * (for the current course)
1536 public function course_footer() {
1538 if ($this->page->course->id == SITEID) {
1539 // return immediately and do not include /course/lib.php if not necessary
1542 require_once($CFG->dirroot.'/course/lib.php');
1543 $courseformat = course_get_format($this->page->course);
1544 if (($obj = $courseformat->course_footer()) !== null) {
1545 return $courseformat->get_renderer($this->page)->render($obj);
1551 * Get the course pattern datauri to show on a course card.
1553 * The datauri is an encoded svg that can be passed as a url.
1554 * @param int $id Id to use when generating the pattern
1555 * @return string datauri
1557 public function get_generated_image_for_id($id) {
1558 $color = $this->get_generated_color_for_id($id);
1559 $pattern = new \core_geopattern();
1560 $pattern->setColor($color);
1561 $pattern->patternbyid($id);
1562 return $pattern->datauri();
1566 * Get the course color to show on a course card.
1568 * @param int $id Id to use when generating the color.
1569 * @return string hex color code.
1571 public function get_generated_color_for_id($id) {
1572 $colornumbers = range(1, 10);
1574 foreach ($colornumbers as $number) {
1575 $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1578 $color = $basecolors[$id % 10];
1583 * Returns lang menu or '', this method also checks forcing of languages in courses.
1585 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1587 * @return string The lang menu HTML or empty string
1589 public function lang_menu() {
1592 if (empty($CFG->langmenu)) {
1596 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1597 // do not show lang menu if language forced
1601 $currlang = current_language();
1602 $langs = get_string_manager()->get_list_of_translations();
1604 if (count($langs) < 2) {
1608 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1609 $s->label = get_accesshide(get_string('language'));
1610 $s->class = 'langmenu';
1611 return $this->render($s);
1615 * Output the row of editing icons for a block, as defined by the controls array.
1617 * @param array $controls an array like {@link block_contents::$controls}.
1618 * @param string $blockid The ID given to the block.
1619 * @return string HTML fragment.
1621 public function block_controls($actions, $blockid = null) {
1623 if (empty($actions)) {
1626 $menu = new action_menu($actions);
1627 if ($blockid !== null) {
1628 $menu->set_owner_selector('#'.$blockid);
1630 $menu->set_constraint('.block-region');
1631 $menu->attributes['class'] .= ' block-control-actions commands';
1632 return $this->render($menu);
1636 * Returns the HTML for a basic textarea field.
1638 * @param string $name Name to use for the textarea element
1639 * @param string $id The id to use fort he textarea element
1640 * @param string $value Initial content to display in the textarea
1641 * @param int $rows Number of rows to display
1642 * @param int $cols Number of columns to display
1643 * @return string the HTML to display
1645 public function print_textarea($name, $id, $value, $rows, $cols) {
1646 editors_head_setup();
1647 $editor = editors_get_preferred_editor(FORMAT_HTML);
1648 $editor->set_text($value);
1649 $editor->use_editor($id, []);
1659 return $this->render_from_template('core_form/editor_textarea', $context);
1663 * Renders an action menu component.
1665 * @param action_menu $menu
1666 * @return string HTML
1668 public function render_action_menu(action_menu $menu) {
1670 // We don't want the class icon there!
1671 foreach ($menu->get_secondary_actions() as $action) {
1672 if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1673 $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1677 if ($menu->is_empty()) {
1680 $context = $menu->export_for_template($this);
1682 return $this->render_from_template('core/action_menu', $context);
1686 * Renders a Check API result
1688 * @param result $result
1689 * @return string HTML fragment
1691 protected function render_check_result(core\check\result $result) {
1692 return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1696 * Renders a Check API result
1698 * @param result $result
1699 * @return string HTML fragment
1701 public function check_result(core\check\result $result) {
1702 return $this->render_check_result($result);
1706 * Renders an action_menu_link item.
1708 * @param action_menu_link $action
1709 * @return string HTML fragment
1711 protected function render_action_menu_link(action_menu_link $action) {
1712 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1716 * Renders a primary action_menu_filler item.
1718 * @param action_menu_link_filler $action
1719 * @return string HTML fragment
1721 protected function render_action_menu_filler(action_menu_filler $action) {
1722 return html_writer::span(' ', 'filler');
1726 * Renders a primary action_menu_link item.
1728 * @param action_menu_link_primary $action
1729 * @return string HTML fragment
1731 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1732 return $this->render_action_menu_link($action);
1736 * Renders a secondary action_menu_link item.
1738 * @param action_menu_link_secondary $action
1739 * @return string HTML fragment
1741 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1742 return $this->render_action_menu_link($action);
1746 * Prints a nice side block with an optional header.
1748 * @param block_contents $bc HTML for the content
1749 * @param string $region the region the block is appearing in.
1750 * @return string the HTML to be output.
1752 public function block(block_contents $bc, $region) {
1753 $bc = clone($bc); // Avoid messing up the object passed in.
1754 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1755 $bc->collapsible = block_contents::NOT_HIDEABLE;
1758 $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1759 $context = new stdClass();
1760 $context->skipid = $bc->skipid;
1761 $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
1762 $context->dockable = $bc->dockable;
1764 $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1765 $context->skiptitle = strip_tags($bc->title);
1766 $context->showskiplink = !empty($context->skiptitle);
1767 $context->arialabel = $bc->arialabel;
1768 $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
1769 $context->class = $bc->attributes['class'];
1770 $context->type = $bc->attributes['data-block'];
1771 $context->title = $bc->title;
1772 $context->content = $bc->content;
1773 $context->annotation = $bc->annotation;
1774 $context->footer = $bc->footer;
1775 $context->hascontrols = !empty($bc->controls);
1776 if ($context->hascontrols) {
1777 $context->controls = $this->block_controls($bc->controls, $id);
1780 return $this->render_from_template('core/block', $context);
1784 * Render the contents of a block_list.
1786 * @param array $icons the icon for each item.
1787 * @param array $items the content of each item.
1788 * @return string HTML
1790 public function list_block_contents($icons, $items) {
1793 foreach ($items as $key => $string) {
1794 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1795 if (!empty($icons[$key])) { //test if the content has an assigned icon
1796 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1798 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1799 $item .= html_writer::end_tag('li');
1801 $row = 1 - $row; // Flip even/odd.
1803 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1807 * Output all the blocks in a particular region.
1809 * @param string $region the name of a region on this page.
1810 * @return string the HTML to be output.
1812 public function blocks_for_region($region) {
1813 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1814 $blocks = $this->page->blocks->get_blocks_for_region($region);
1817 foreach ($blocks as $block) {
1818 $zones[] = $block->title;
1822 foreach ($blockcontents as $bc) {
1823 if ($bc instanceof block_contents) {
1824 $output .= $this->block($bc, $region);
1825 $lastblock = $bc->title;
1826 } else if ($bc instanceof block_move_target) {
1827 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1829 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1836 * Output a place where the block that is currently being moved can be dropped.
1838 * @param block_move_target $target with the necessary details.
1839 * @param array $zones array of areas where the block can be moved to
1840 * @param string $previous the block located before the area currently being rendered.
1841 * @param string $region the name of the region
1842 * @return string the HTML to be output.
1844 public function block_move_target($target, $zones, $previous, $region) {
1845 if ($previous == null) {
1846 if (empty($zones)) {
1847 // There are no zones, probably because there are no blocks.
1848 $regions = $this->page->theme->get_all_block_regions();
1849 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1851 $position = get_string('moveblockbefore', 'block', $zones[0]);
1854 $position = get_string('moveblockafter', 'block', $previous);
1856 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1860 * Renders a special html link with attached action
1862 * Theme developers: DO NOT OVERRIDE! Please override function
1863 * {@link core_renderer::render_action_link()} instead.
1865 * @param string|moodle_url $url
1866 * @param string $text HTML fragment
1867 * @param component_action $action
1868 * @param array $attributes associative array of html link attributes + disabled
1869 * @param pix_icon optional pix icon to render with the link
1870 * @return string HTML fragment
1872 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1873 if (!($url instanceof moodle_url)) {
1874 $url = new moodle_url($url);
1876 $link = new action_link($url, $text, $action, $attributes, $icon);
1878 return $this->render($link);
1882 * Renders an action_link object.
1884 * The provided link is renderer and the HTML returned. At the same time the
1885 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1887 * @param action_link $link
1888 * @return string HTML fragment
1890 protected function render_action_link(action_link $link) {
1891 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1895 * Renders an action_icon.
1897 * This function uses the {@link core_renderer::action_link()} method for the
1898 * most part. What it does different is prepare the icon as HTML and use it
1901 * Theme developers: If you want to change how action links and/or icons are rendered,
1902 * consider overriding function {@link core_renderer::render_action_link()} and
1903 * {@link core_renderer::render_pix_icon()}.
1905 * @param string|moodle_url $url A string URL or moodel_url
1906 * @param pix_icon $pixicon
1907 * @param component_action $action
1908 * @param array $attributes associative array of html link attributes + disabled
1909 * @param bool $linktext show title next to image in link
1910 * @return string HTML fragment
1912 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1913 if (!($url instanceof moodle_url)) {
1914 $url = new moodle_url($url);
1916 $attributes = (array)$attributes;
1918 if (empty($attributes['class'])) {
1919 // let ppl override the class via $options
1920 $attributes['class'] = 'action-icon';
1923 $icon = $this->render($pixicon);
1926 $text = $pixicon->attributes['alt'];
1931 return $this->action_link($url, $text.$icon, $action, $attributes);
1935 * Print a message along with button choices for Continue/Cancel
1937 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1939 * @param string $message The question to ask the user
1940 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1941 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1942 * @return string HTML fragment
1944 public function confirm($message, $continue, $cancel) {
1945 if ($continue instanceof single_button) {
1947 $continue->primary = true;
1948 } else if (is_string($continue)) {
1949 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1950 } else if ($continue instanceof moodle_url) {
1951 $continue = new single_button($continue, get_string('continue'), 'post', true);
1953 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1956 if ($cancel instanceof single_button) {
1958 } else if (is_string($cancel)) {
1959 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1960 } else if ($cancel instanceof moodle_url) {
1961 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1963 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1967 'role'=>'alertdialog',
1968 'aria-labelledby'=>'modal-header',
1969 'aria-describedby'=>'modal-body',
1970 'aria-modal'=>'true'
1973 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
1974 $output .= $this->box_start('modal-content', 'modal-content');
1975 $output .= $this->box_start('modal-header p-x-1', 'modal-header');
1976 $output .= html_writer::tag('h4', get_string('confirm'));
1977 $output .= $this->box_end();
1980 'data-aria-autofocus'=>'true'
1982 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
1983 $output .= html_writer::tag('p', $message);
1984 $output .= $this->box_end();
1985 $output .= $this->box_start('modal-footer', 'modal-footer');
1986 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1987 $output .= $this->box_end();
1988 $output .= $this->box_end();
1989 $output .= $this->box_end();
1994 * Returns a form with a single button.
1996 * Theme developers: DO NOT OVERRIDE! Please override function
1997 * {@link core_renderer::render_single_button()} instead.
1999 * @param string|moodle_url $url
2000 * @param string $label button text
2001 * @param string $method get or post submit method
2002 * @param array $options associative array {disabled, title, etc.}
2003 * @return string HTML fragment
2005 public function single_button($url, $label, $method='post', array $options=null) {
2006 if (!($url instanceof moodle_url)) {
2007 $url = new moodle_url($url);
2009 $button = new single_button($url, $label, $method);
2011 foreach ((array)$options as $key=>$value) {
2012 if (property_exists($button, $key)) {
2013 $button->$key = $value;
2015 $button->set_attribute($key, $value);
2019 return $this->render($button);
2023 * Renders a single button widget.
2025 * This will return HTML to display a form containing a single button.
2027 * @param single_button $button
2028 * @return string HTML fragment
2030 protected function render_single_button(single_button $button) {
2031 return $this->render_from_template('core/single_button', $button->export_for_template($this));
2035 * Returns a form with a single select widget.
2037 * Theme developers: DO NOT OVERRIDE! Please override function
2038 * {@link core_renderer::render_single_select()} instead.
2040 * @param moodle_url $url form action target, includes hidden fields
2041 * @param string $name name of selection field - the changing parameter in url
2042 * @param array $options list of options
2043 * @param string $selected selected element
2044 * @param array $nothing
2045 * @param string $formid
2046 * @param array $attributes other attributes for the single select
2047 * @return string HTML fragment
2049 public function single_select($url, $name, array $options, $selected = '',
2050 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2051 if (!($url instanceof moodle_url)) {
2052 $url = new moodle_url($url);
2054 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2056 if (array_key_exists('label', $attributes)) {
2057 $select->set_label($attributes['label']);
2058 unset($attributes['label']);
2060 $select->attributes = $attributes;
2062 return $this->render($select);
2066 * Returns a dataformat selection and download form
2068 * @param string $label A text label
2069 * @param moodle_url|string $base The download page url
2070 * @param string $name The query param which will hold the type of the download
2071 * @param array $params Extra params sent to the download page
2072 * @return string HTML fragment
2074 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2076 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2078 foreach ($formats as $format) {
2079 if ($format->is_enabled()) {
2081 'value' => $format->name,
2082 'label' => get_string('dataformat', $format->component),
2086 $hiddenparams = array();
2087 foreach ($params as $key => $value) {
2088 $hiddenparams[] = array(
2097 'params' => $hiddenparams,
2098 'options' => $options,
2099 'sesskey' => sesskey(),
2100 'submit' => get_string('download'),
2103 return $this->render_from_template('core/dataformat_selector', $data);
2108 * Internal implementation of single_select rendering
2110 * @param single_select $select
2111 * @return string HTML fragment
2113 protected function render_single_select(single_select $select) {
2114 return $this->render_from_template('core/single_select', $select->export_for_template($this));
2118 * Returns a form with a url select widget.
2120 * Theme developers: DO NOT OVERRIDE! Please override function
2121 * {@link core_renderer::render_url_select()} instead.
2123 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2124 * @param string $selected selected element
2125 * @param array $nothing
2126 * @param string $formid
2127 * @return string HTML fragment
2129 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2130 $select = new url_select($urls, $selected, $nothing, $formid);
2131 return $this->render($select);
2135 * Internal implementation of url_select rendering
2137 * @param url_select $select
2138 * @return string HTML fragment
2140 protected function render_url_select(url_select $select) {
2141 return $this->render_from_template('core/url_select', $select->export_for_template($this));
2145 * Returns a string containing a link to the user documentation.
2146 * Also contains an icon by default. Shown to teachers and admin only.
2148 * @param string $path The page link after doc root and language, no leading slash.
2149 * @param string $text The text to be displayed for the link
2150 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2151 * @param array $attributes htm attributes
2154 public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
2157 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2159 $attributes['href'] = new moodle_url(get_docs_url($path));
2160 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2161 $attributes['class'] = 'helplinkpopup';
2164 return html_writer::tag('a', $icon.$text, $attributes);
2168 * Return HTML for an image_icon.
2170 * Theme developers: DO NOT OVERRIDE! Please override function
2171 * {@link core_renderer::render_image_icon()} instead.
2173 * @param string $pix short pix name
2174 * @param string $alt mandatory alt attribute
2175 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2176 * @param array $attributes htm attributes
2177 * @return string HTML fragment
2179 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2180 $icon = new image_icon($pix, $alt, $component, $attributes);
2181 return $this->render($icon);
2185 * Renders a pix_icon widget and returns the HTML to display it.
2187 * @param image_icon $icon
2188 * @return string HTML fragment
2190 protected function render_image_icon(image_icon $icon) {
2191 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2192 return $system->render_pix_icon($this, $icon);
2196 * Return HTML for a pix_icon.
2198 * Theme developers: DO NOT OVERRIDE! Please override function
2199 * {@link core_renderer::render_pix_icon()} instead.
2201 * @param string $pix short pix name
2202 * @param string $alt mandatory alt attribute
2203 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2204 * @param array $attributes htm lattributes
2205 * @return string HTML fragment
2207 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2208 $icon = new pix_icon($pix, $alt, $component, $attributes);
2209 return $this->render($icon);
2213 * Renders a pix_icon widget and returns the HTML to display it.
2215 * @param pix_icon $icon
2216 * @return string HTML fragment
2218 protected function render_pix_icon(pix_icon $icon) {
2219 $system = \core\output\icon_system::instance();
2220 return $system->render_pix_icon($this, $icon);
2224 * Return HTML to display an emoticon icon.
2226 * @param pix_emoticon $emoticon
2227 * @return string HTML fragment
2229 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2230 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2231 return $system->render_pix_icon($this, $emoticon);
2235 * Produces the html that represents this rating in the UI
2237 * @param rating $rating the page object on which this rating will appear
2240 function render_rating(rating $rating) {
2243 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2244 return null;//ratings are turned off
2247 $ratingmanager = new rating_manager();
2248 // Initialise the JavaScript so ratings can be done by AJAX.
2249 $ratingmanager->initialise_rating_javascript($this->page);
2251 $strrate = get_string("rate", "rating");
2252 $ratinghtml = ''; //the string we'll return
2254 // permissions check - can they view the aggregate?
2255 if ($rating->user_can_view_aggregate()) {
2257 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2258 $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2259 $aggregatestr = $rating->get_aggregate_string();
2261 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2262 if ($rating->count > 0) {
2263 $countstr = "({$rating->count})";
2267 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2269 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2271 $nonpopuplink = $rating->get_view_ratings_url();
2272 $popuplink = $rating->get_view_ratings_url(true);
2274 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2275 $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
2278 $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
2282 // if the item doesn't belong to the current user, the user has permission to rate
2283 // and we're within the assessable period
2284 if ($rating->user_can_rate()) {
2286 $rateurl = $rating->get_rate_url();
2287 $inputs = $rateurl->params();
2289 //start the rating form
2291 'id' => "postrating{$rating->itemid}",
2292 'class' => 'postratingform',
2294 'action' => $rateurl->out_omit_querystring()
2296 $formstart = html_writer::start_tag('form', $formattrs);
2297 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2299 // add the hidden inputs
2300 foreach ($inputs as $name => $value) {
2301 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2302 $formstart .= html_writer::empty_tag('input', $attributes);
2305 if (empty($ratinghtml)) {
2306 $ratinghtml .= $strrate.': ';
2308 $ratinghtml = $formstart.$ratinghtml;
2310 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2311 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2312 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2313 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2315 //output submit button
2316 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2318 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2319 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2321 if (!$rating->settings->scale->isnumeric) {
2322 // If a global scale, try to find current course ID from the context
2323 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2324 $courseid = $coursecontext->instanceid;
2326 $courseid = $rating->settings->scale->courseid;
2328 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2330 $ratinghtml .= html_writer::end_tag('span');
2331 $ratinghtml .= html_writer::end_tag('div');
2332 $ratinghtml .= html_writer::end_tag('form');
2339 * Centered heading with attached help button (same title text)
2340 * and optional icon attached.
2342 * @param string $text A heading text
2343 * @param string $helpidentifier The keyword that defines a help page
2344 * @param string $component component name
2345 * @param string|moodle_url $icon
2346 * @param string $iconalt icon alt text
2347 * @param int $level The level of importance of the heading. Defaulting to 2
2348 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2349 * @return string HTML fragment
2351 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2354 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2358 if ($helpidentifier) {
2359 $help = $this->help_icon($helpidentifier, $component);
2362 return $this->heading($image.$text.$help, $level, $classnames);
2366 * Returns HTML to display a help icon.
2368 * @deprecated since Moodle 2.0
2370 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2371 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2375 * Returns HTML to display a help icon.
2377 * Theme developers: DO NOT OVERRIDE! Please override function
2378 * {@link core_renderer::render_help_icon()} instead.
2380 * @param string $identifier The keyword that defines a help page
2381 * @param string $component component name
2382 * @param string|bool $linktext true means use $title as link text, string means link text value
2383 * @return string HTML fragment
2385 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2386 $icon = new help_icon($identifier, $component);
2387 $icon->diag_strings();
2388 if ($linktext === true) {
2389 $icon->linktext = get_string($icon->identifier, $icon->component);
2390 } else if (!empty($linktext)) {
2391 $icon->linktext = $linktext;
2393 return $this->render($icon);
2397 * Implementation of user image rendering.
2399 * @param help_icon $helpicon A help icon instance
2400 * @return string HTML fragment
2402 protected function render_help_icon(help_icon $helpicon) {
2403 $context = $helpicon->export_for_template($this);
2404 return $this->render_from_template('core/help_icon', $context);
2408 * Returns HTML to display a scale help icon.
2410 * @param int $courseid
2411 * @param stdClass $scale instance
2412 * @return string HTML fragment
2414 public function help_icon_scale($courseid, stdClass $scale) {
2417 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2419 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2421 $scaleid = abs($scale->id);
2423 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2424 $action = new popup_action('click', $link, 'ratingscale');
2426 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2430 * Creates and returns a spacer image with optional line break.
2432 * @param array $attributes Any HTML attributes to add to the spaced.
2433 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2434 * laxy do it with CSS which is a much better solution.
2435 * @return string HTML fragment
2437 public function spacer(array $attributes = null, $br = false) {
2438 $attributes = (array)$attributes;
2439 if (empty($attributes['width'])) {
2440 $attributes['width'] = 1;
2442 if (empty($attributes['height'])) {
2443 $attributes['height'] = 1;
2445 $attributes['class'] = 'spacer';
2447 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2450 $output .= '<br />';
2457 * Returns HTML to display the specified user's avatar.
2459 * User avatar may be obtained in two ways:
2461 * // Option 1: (shortcut for simple cases, preferred way)
2462 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2463 * $OUTPUT->user_picture($user, array('popup'=>true));
2466 * $userpic = new user_picture($user);
2467 * // Set properties of $userpic
2468 * $userpic->popup = true;
2469 * $OUTPUT->render($userpic);
2472 * Theme developers: DO NOT OVERRIDE! Please override function
2473 * {@link core_renderer::render_user_picture()} instead.
2475 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2476 * If any of these are missing, the database is queried. Avoid this
2477 * if at all possible, particularly for reports. It is very bad for performance.
2478 * @param array $options associative array with user picture options, used only if not a user_picture object,
2480 * - courseid=$this->page->course->id (course id of user profile in link)
2481 * - size=35 (size of image)
2482 * - link=true (make image clickable - the link leads to user profile)
2483 * - popup=false (open in popup)
2484 * - alttext=true (add image alt attribute)
2485 * - class = image class attribute (default 'userpicture')
2486 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2487 * - includefullname=false (whether to include the user's full name together with the user picture)
2488 * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2489 * @return string HTML fragment
2491 public function user_picture(stdClass $user, array $options = null) {
2492 $userpicture = new user_picture($user);
2493 foreach ((array)$options as $key=>$value) {
2494 if (property_exists($userpicture, $key)) {
2495 $userpicture->$key = $value;
2498 return $this->render($userpicture);
2502 * Internal implementation of user image rendering.
2504 * @param user_picture $userpicture
2507 protected function render_user_picture(user_picture $userpicture) {
2510 $user = $userpicture->user;
2511 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
2513 if ($userpicture->alttext) {
2514 if (!empty($user->imagealt)) {
2515 $alt = $user->imagealt;
2517 $alt = get_string('pictureof', '', fullname($user, $canviewfullnames));
2523 if (empty($userpicture->size)) {
2525 } else if ($userpicture->size === true or $userpicture->size == 1) {
2528 $size = $userpicture->size;
2531 $class = $userpicture->class;
2533 if ($user->picture == 0) {
2534 $class .= ' defaultuserpic';
2537 $src = $userpicture->get_url($this->page, $this);
2539 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2540 if (!$userpicture->visibletoscreenreaders) {
2542 $attributes['aria-hidden'] = 'true';
2546 $attributes['alt'] = $alt;
2547 $attributes['title'] = $alt;
2550 // get the image html output fisrt
2551 $output = html_writer::empty_tag('img', $attributes);
2553 // Show fullname together with the picture when desired.
2554 if ($userpicture->includefullname) {
2555 $output .= fullname($userpicture->user, $canviewfullnames);
2558 // then wrap it in link if needed
2559 if (!$userpicture->link) {
2563 if (empty($userpicture->courseid)) {
2564 $courseid = $this->page->course->id;
2566 $courseid = $userpicture->courseid;
2569 if ($courseid == SITEID) {
2570 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2572 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2575 $attributes = array('href'=>$url);
2576 if (!$userpicture->visibletoscreenreaders) {
2577 $attributes['tabindex'] = '-1';
2578 $attributes['aria-hidden'] = 'true';
2581 if ($userpicture->popup) {
2582 $id = html_writer::random_id('userpicture');
2583 $attributes['id'] = $id;
2584 $this->add_action_handler(new popup_action('click', $url), $id);
2587 return html_writer::tag('a', $output, $attributes);
2591 * Internal implementation of file tree viewer items rendering.
2596 public function htmllize_file_tree($dir) {
2597 if (empty($dir['subdirs']) and empty($dir['files'])) {
2601 foreach ($dir['subdirs'] as $subdir) {
2602 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2604 foreach ($dir['files'] as $file) {
2605 $filename = $file->get_filename();
2606 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2614 * Returns HTML to display the file picker
2617 * $OUTPUT->file_picker($options);
2620 * Theme developers: DO NOT OVERRIDE! Please override function
2621 * {@link core_renderer::render_file_picker()} instead.
2623 * @param array $options associative array with file manager options
2627 * client_id=>uniqid(),
2628 * acepted_types=>'*',
2629 * return_types=>FILE_INTERNAL,
2630 * context=>current page context
2631 * @return string HTML fragment
2633 public function file_picker($options) {
2634 $fp = new file_picker($options);
2635 return $this->render($fp);
2639 * Internal implementation of file picker rendering.
2641 * @param file_picker $fp
2644 public function render_file_picker(file_picker $fp) {
2645 $options = $fp->options;
2646 $client_id = $options->client_id;
2647 $strsaved = get_string('filesaved', 'repository');
2648 $straddfile = get_string('openpicker', 'repository');
2649 $strloading = get_string('loading', 'repository');
2650 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2651 $strdroptoupload = get_string('droptoupload', 'moodle');
2652 $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
2654 $currentfile = $options->currentfile;
2655 if (empty($currentfile)) {
2658 $currentfile .= ' - ';
2660 if ($options->maxbytes) {
2661 $size = $options->maxbytes;
2663 $size = get_max_upload_file_size();
2668 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2670 if ($options->buttonname) {
2671 $buttonname = ' name="' . $options->buttonname . '"';
2676 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2679 <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2681 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2682 <span> $maxsize </span>
2685 if ($options->env != 'url') {
2687 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist border" style="position: relative">
2688 <div class="filepicker-filename">
2689 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2690 <div class="dndupload-progressbars"></div>
2692 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2701 * @deprecated since Moodle 3.2
2703 public function update_module_button() {
2704 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2705 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2706 'Themes can choose to display the link in the buttons row consistently for all module types.');
2710 * Returns HTML to display a "Turn editing on/off" button in a form.
2712 * @param moodle_url $url The URL + params to send through when clicking the button
2713 * @return string HTML the button
2715 public function edit_button(moodle_url $url) {
2717 $url->param('sesskey', sesskey());
2718 if ($this->page->user_is_editing()) {
2719 $url->param('edit', 'off');
2720 $editstring = get_string('turneditingoff');
2722 $url->param('edit', 'on');
2723 $editstring = get_string('turneditingon');
2726 return $this->single_button($url, $editstring);
2730 * Returns HTML to display a simple button to close a window
2732 * @param string $text The lang string for the button's label (already output from get_string())
2733 * @return string html fragment
2735 public function close_window_button($text='') {
2737 $text = get_string('closewindow');
2739 $button = new single_button(new moodle_url('#'), $text, 'get');
2740 $button->add_action(new component_action('click', 'close_window'));
2742 return $this->container($this->render($button), 'closewindow');
2746 * Output an error message. By default wraps the error message in <span class="error">.
2747 * If the error message is blank, nothing is output.
2749 * @param string $message the error message.
2750 * @return string the HTML to output.
2752 public function error_text($message) {
2753 if (empty($message)) {
2756 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2757 return html_writer::tag('span', $message, array('class' => 'error'));
2761 * Do not call this function directly.
2763 * To terminate the current script with a fatal error, call the {@link print_error}
2764 * function, or throw an exception. Doing either of those things will then call this
2765 * function to display the error, before terminating the execution.
2767 * @param string $message The message to output
2768 * @param string $moreinfourl URL where more info can be found about the error
2769 * @param string $link Link for the Continue button
2770 * @param array $backtrace The execution backtrace
2771 * @param string $debuginfo Debugging information
2772 * @return string the HTML to output.
2774 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2780 if ($this->has_started()) {
2781 // we can not always recover properly here, we have problems with output buffering,
2782 // html tables, etc.
2783 $output .= $this->opencontainers->pop_all_but_last();
2786 // It is really bad if library code throws exception when output buffering is on,
2787 // because the buffered text would be printed before our start of page.
2788 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2789 error_reporting(0); // disable notices from gzip compression, etc.
2790 while (ob_get_level() > 0) {
2791 $buff = ob_get_clean();
2792 if ($buff === false) {
2797 error_reporting($CFG->debug);
2799 // Output not yet started.
2800 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2801 if (empty($_SERVER['HTTP_RANGE'])) {
2802 @header($protocol . ' 404 Not Found');
2803 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2804 // Coax iOS 10 into sending the session cookie.
2805 @header($protocol . ' 403 Forbidden');
2807 // Must stop byteserving attempts somehow,
2808 // this is weird but Chrome PDF viewer can be stopped only with 407!
2809 @header($protocol . ' 407 Proxy Authentication Required');
2812 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2813 $this->page->set_url('/'); // no url
2814 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2815 $this->page->set_title(get_string('error'));
2816 $this->page->set_heading($this->page->course->fullname);
2817 $output .= $this->header();
2820 $message = '<p class="errormessage">' . s($message) . '</p>'.
2821 '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
2822 get_string('moreinformation') . '</a></p>';
2823 if (empty($CFG->rolesactive)) {
2824 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2825 //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.
2827 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2829 if ($CFG->debugdeveloper) {
2830 $labelsep = get_string('labelsep', 'langconfig');
2831 if (!empty($debuginfo)) {
2832 $debuginfo = s($debuginfo); // removes all nasty JS
2833 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2834 $label = get_string('debuginfo', 'debug') . $labelsep;
2835 $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
2837 if (!empty($backtrace)) {
2838 $label = get_string('stacktrace', 'debug') . $labelsep;
2839 $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
2841 if ($obbuffer !== '' ) {
2842 $label = get_string('outputbuffer', 'debug') . $labelsep;
2843 $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
2847 if (empty($CFG->rolesactive)) {
2848 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2849 } else if (!empty($link)) {
2850 $output .= $this->continue_button($link);
2853 $output .= $this->footer();
2855 // Padding to encourage IE to display our error page, rather than its own.
2856 $output .= str_repeat(' ', 512);
2862 * Output a notification (that is, a status message about something that has just happened).
2864 * Note: \core\notification::add() may be more suitable for your usage.
2866 * @param string $message The message to print out.
2867 * @param string $type The type of notification. See constants on \core\output\notification.
2868 * @return string the HTML to output.
2870 public function notification($message, $type = null) {
2873 'success' => \core\output\notification::NOTIFY_SUCCESS,
2874 'info' => \core\output\notification::NOTIFY_INFO,
2875 'warning' => \core\output\notification::NOTIFY_WARNING,
2876 'error' => \core\output\notification::NOTIFY_ERROR,
2878 // Legacy types mapped to current types.
2879 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2880 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2881 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2882 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2883 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2884 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2885 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2891 if (strpos($type, ' ') === false) {
2892 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2893 if (isset($typemappings[$type])) {
2894 $type = $typemappings[$type];
2896 // The value provided did not match a known type. It must be an extra class.
2897 $extraclasses = [$type];
2900 // Identify what type of notification this is.
2901 $classarray = explode(' ', self::prepare_classes($type));
2903 // Separate out the type of notification from the extra classes.
2904 foreach ($classarray as $class) {
2905 if (isset($typemappings[$class])) {
2906 $type = $typemappings[$class];
2908 $extraclasses[] = $class;
2914 $notification = new \core\output\notification($message, $type);
2915 if (count($extraclasses)) {
2916 $notification->set_extra_classes($extraclasses);
2919 // Return the rendered template.
2920 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2924 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2926 public function notify_problem() {
2927 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
2928 'please use \core\notification::add(), or \core\output\notification as required.');
2932 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2934 public function notify_success() {
2935 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
2936 'please use \core\notification::add(), or \core\output\notification as required.');
2940 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2942 public function notify_message() {
2943 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
2944 'please use \core\notification::add(), or \core\output\notification as required.');
2948 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2950 public function notify_redirect() {
2951 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
2952 'please use \core\notification::add(), or \core\output\notification as required.');
2956 * Render a notification (that is, a status message about something that has
2959 * @param \core\output\notification $notification the notification to print out
2960 * @return string the HTML to output.
2962 protected function render_notification(\core\output\notification $notification) {
2963 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2967 * Returns HTML to display a continue button that goes to a particular URL.
2969 * @param string|moodle_url $url The url the button goes to.
2970 * @return string the HTML to output.
2972 public function continue_button($url) {
2973 if (!($url instanceof moodle_url)) {
2974 $url = new moodle_url($url);
2976 $button = new single_button($url, get_string('continue'), 'get', true);
2977 $button->class = 'continuebutton';
2979 return $this->render($button);
2983 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2985 * Theme developers: DO NOT OVERRIDE! Please override function
2986 * {@link core_renderer::render_paging_bar()} instead.
2988 * @param int $totalcount The total number of entries available to be paged through
2989 * @param int $page The page you are currently viewing
2990 * @param int $perpage The number of entries that should be shown per page
2991 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2992 * @param string $pagevar name of page parameter that holds the page number
2993 * @return string the HTML to output.
2995 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2996 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2997 return $this->render($pb);
3001 * Returns HTML to display the paging bar.
3003 * @param paging_bar $pagingbar
3004 * @return string the HTML to output.
3006 protected function render_paging_bar(paging_bar $pagingbar) {
3007 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3008 $pagingbar->maxdisplay = 10;
3009 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3013 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3015 * @param string $current the currently selected letter.
3016 * @param string $class class name to add to this initial bar.
3017 * @param string $title the name to put in front of this initial bar.
3018 * @param string $urlvar URL parameter name for this initial.
3019 * @param string $url URL object.
3020 * @param array $alpha of letters in the alphabet.
3021 * @return string the HTML to output.
3023 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3024 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3025 return $this->render($ib);
3029 * Internal implementation of initials bar rendering.
3031 * @param initials_bar $initialsbar
3034 protected function render_initials_bar(initials_bar $initialsbar) {
3035 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3039 * Output the place a skip link goes to.
3041 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3042 * @return string the HTML to output.
3044 public function skip_link_target($id = null) {
3045 return html_writer::span('', '', array('id' => $id));
3051 * @param string $text The text of the heading
3052 * @param int $level The level of importance of the heading. Defaulting to 2
3053 * @param string $classes A space-separated list of CSS classes. Defaulting to null
3054 * @param string $id An optional ID
3055 * @return string the HTML to output.
3057 public function heading($text, $level = 2, $classes = null, $id = null) {
3058 $level = (integer) $level;
3059 if ($level < 1 or $level > 6) {
3060 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3062 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3068 * @param string $contents The contents of the box
3069 * @param string $classes A space-separated list of CSS classes
3070 * @param string $id An optional ID
3071 * @param array $attributes An array of other attributes to give the box.
3072 * @return string the HTML to output.
3074 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3075 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3079 * Outputs the opening section of a box.
3081 * @param string $classes A space-separated list of CSS classes
3082 * @param string $id An optional ID
3083 * @param array $attributes An array of other attributes to give the box.
3084 * @return string the HTML to output.
3086 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3087 $this->opencontainers->push('box', html_writer::end_tag('div'));
3088 $attributes['id'] = $id;
3089 $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes);
3090 return html_writer::start_tag('div', $attributes);
3094 * Outputs the closing section of a box.
3096 * @return string the HTML to output.
3098 public function box_end() {
3099 return $this->opencontainers->pop('box');
3103 * Outputs a container.
3105 * @param string $contents The contents of the box
3106 * @param string $classes A space-separated list of CSS classes
3107 * @param string $id An optional ID
3108 * @return string the HTML to output.
3110 public function container($contents, $classes = null, $id = null) {
3111 return $this->container_start($classes, $id) . $contents . $this->container_end();
3115 * Outputs the opening section of a container.
3117 * @param string $classes A space-separated list of CSS classes
3118 * @param string $id An optional ID
3119 * @return string the HTML to output.
3121 public function container_start($classes = null, $id = null) {
3122 $this->opencontainers->push('container', html_writer::end_tag('div'));
3123 return html_writer::start_tag('div', array('id' => $id,
3124 'class' => renderer_base::prepare_classes($classes)));
3128 * Outputs the closing section of a container.
3130 * @return string the HTML to output.
3132 public function container_end() {
3133 return $this->opencontainers->pop('container');
3137 * Make nested HTML lists out of the items
3139 * The resulting list will look something like this:
3143 * <<li>><div class='tree_item parent'>(item contents)</div>
3145 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3151 * @param array $items
3152 * @param array $attrs html attributes passed to the top ofs the list
3153 * @return string HTML
3155 public function tree_block_contents($items, $attrs = array()) {
3156 // exit if empty, we don't want an empty ul element
3157 if (empty($items)) {
3160 // array of nested li elements
3162 foreach ($items as $item) {
3163 // this applies to the li item which contains all child lists too
3164 $content = $item->content($this);
3165 $liclasses = array($item->get_css_type());
3166 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3167 $liclasses[] = 'collapsed';
3169 if ($item->isactive === true) {
3170 $liclasses[] = 'current_branch';
3172 $liattr = array('class'=>join(' ',$liclasses));
3173 // class attribute on the div item which only contains the item content
3174 $divclasses = array('tree_item');
3175 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3176 $divclasses[] = 'branch';
3178 $divclasses[] = 'leaf';
3180 if (!empty($item->classes) && count($item->classes)>0) {
3181 $divclasses[] = join(' ', $item->classes);
3183 $divattr = array('class'=>join(' ', $divclasses));
3184 if (!empty($item->id)) {
3185 $divattr['id'] = $item->id;
3187 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3188 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3189 $content = html_writer::empty_tag('hr') . $content;
3191 $content = html_writer::tag('li', $content, $liattr);
3194 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3198 * Returns a search box.
3200 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3201 * @return string HTML with the search form hidden by default.
3203 public function search_box($id = false) {
3206 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3207 // result in an extra included file for each site, even the ones where global search
3209 if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3216 // Needs to be cleaned, we use it for the input id.
3217 $id = clean_param($id, PARAM_ALPHANUMEXT);
3220 // JS to animate the form.
3221 $this->page->requires->js_call_amd('core/search-input', 'init', array($id));
3223 $searchicon = html_writer::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
3224 array('role' => 'button', 'tabindex' => 0));
3225 $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot . '/search/index.php');
3226 $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
3227 'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id, 'class' => 'form-control');
3229 $contents = html_writer::tag('label', get_string('enteryoursearchquery', 'search'),
3230 array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer::empty_tag('input', $inputattrs);
3231 if ($this->page->context && $this->page->context->contextlevel !== CONTEXT_SYSTEM) {
3232 $contents .= html_writer::empty_tag('input', ['type' => 'hidden',
3233 'name' => 'context', 'value' => $this->page->context->id]);
3235 $searchinput = html_writer::tag('form', $contents, $formattrs);
3237 return html_writer::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper nav-link', 'id' => $id));
3241 * Allow plugins to provide some content to be rendered in the navbar.
3242 * The plugin must define a PLUGIN_render_navbar_output function that returns
3243 * the HTML they wish to add to the navbar.
3245 * @return string HTML for the navbar
3247 public function navbar_plugin_output() {
3250 // Give subsystems an opportunity to inject extra html content. The callback
3251 // must always return a string containing valid html.
3252 foreach (\core_component::get_core_subsystems() as $name => $path) {
3254 $output .= component_callback($name, 'render_navbar_output', [$this], '');
3258 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3259 foreach ($pluginsfunction as $plugintype => $plugins) {
3260 foreach ($plugins as $pluginfunction) {
3261 $output .= $pluginfunction($this);
3270 * Construct a user menu, returning HTML that can be echoed out by a
3273 * @param stdClass $user A user object, usually $USER.
3274 * @param bool $withlinks true if a dropdown should be built.
3275 * @return string HTML fragment.
3277 public function user_menu($user = null, $withlinks = null) {
3279 require_once($CFG->dirroot . '/user/lib.php');
3281 if (is_null($user)) {
3285 // Note: this behaviour is intended to match that of core_renderer::login_info,
3286 // but should not be considered to be good practice; layout options are
3287 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3288 if (is_null($withlinks)) {
3289 $withlinks = empty($this->page->layout_options['nologinlinks']);
3292 // Add a class for when $withlinks is false.
3293 $usermenuclasses = 'usermenu';
3295 $usermenuclasses .= ' withoutlinks';
3300 // If during initial install, return the empty return string.
3301 if (during_initial_install()) {
3305 $loginpage = $this->is_login_page();
3306 $loginurl = get_login_url();
3307 // If not logged in, show the typical not-logged-in string.
3308 if (!isloggedin()) {
3309 $returnstr = get_string('loggedinnot', 'moodle');
3311 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3313 return html_writer::div(
3323 // If logged in as a guest user, show a string to that effect.
3324 if (isguestuser()) {
3325 $returnstr = get_string('loggedinasguest');
3326 if (!$loginpage && $withlinks) {
3327 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3330 return html_writer::div(
3339 // Get some navigation opts.
3340 $opts = user_get_user_navigation_info($user, $this->page);
3342 $avatarclasses = "avatars";
3343 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3344 $usertextcontents = $opts->metadata['userfullname'];
3347 if (!empty($opts->metadata['asotheruser'])) {
3348 $avatarcontents .= html_writer::span(
3349 $opts->metadata['realuseravatar'],
3352 $usertextcontents = $opts->metadata['realuserfullname'];
3353 $usertextcontents .= html_writer::tag(
3359 $opts->metadata['userfullname'],
3363 array('class' => 'meta viewingas')
3368 if (!empty($opts->metadata['asotherrole'])) {
3369 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3370 $usertextcontents .= html_writer::span(
3371 $opts->metadata['rolename'],
3372 'meta role role-' . $role
3376 // User login failures.
3377 if (!empty($opts->metadata['userloginfail'])) {
3378 $usertextcontents .= html_writer::span(
3379 $opts->metadata['userloginfail'],
3380 'meta loginfailures'