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 $themename = $this->page
->theme
->name
;
85 $themerev = theme_get_revision();
87 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
89 $loader = new \core\output\
mustache_filesystem_loader();
90 $stringhelper = new \core\output\
mustache_string_helper();
91 $quotehelper = new \core\output\
mustache_quote_helper();
92 $jshelper = new \core\output\
mustache_javascript_helper($this->page
->requires
);
93 $pixhelper = new \core\output\
mustache_pix_helper($this);
94 $shortentexthelper = new \core\output\
mustache_shorten_text_helper();
95 $userdatehelper = new \core\output\
mustache_user_date_helper();
97 // We only expose the variables that are exposed to JS templates.
98 $safeconfig = $this->page
->requires
->get_config_for_javascript($this->page
, $this);
100 $helpers = array('config' => $safeconfig,
101 'str' => array($stringhelper, 'str'),
102 'quote' => array($quotehelper, 'quote'),
103 'js' => array($jshelper, 'help'),
104 'pix' => array($pixhelper, 'pix'),
105 'shortentext' => array($shortentexthelper, 'shorten'),
106 'userdate' => array($userdatehelper, 'transform'),
109 $this->mustache
= new Mustache_Engine(array(
110 'cache' => $cachedir,
113 'helpers' => $helpers,
114 'pragmas' => [Mustache_Engine
::PRAGMA_BLOCKS
]));
118 return $this->mustache
;
125 * The constructor takes two arguments. The first is the page that the renderer
126 * has been created to assist with, and the second is the target.
127 * The target is an additional identifier that can be used to load different
128 * renderers for different options.
130 * @param moodle_page $page the page we are doing output for.
131 * @param string $target one of rendering target constants
133 public function __construct(moodle_page
$page, $target) {
134 $this->opencontainers
= $page->opencontainers
;
136 $this->target
= $target;
140 * Renders a template by name with the given context.
142 * The provided data needs to be array/stdClass made up of only simple types.
143 * Simple types are array,stdClass,bool,int,float,string
146 * @param array|stdClass $context Context containing data for the template.
147 * @return string|boolean
149 public function render_from_template($templatename, $context) {
150 static $templatecache = array();
151 $mustache = $this->get_mustache();
154 // Grab a copy of the existing helper to be restored later.
155 $uniqidhelper = $mustache->getHelper('uniqid');
156 } catch (Mustache_Exception_UnknownHelperException
$e) {
157 // Helper doesn't exist.
158 $uniqidhelper = null;
161 // Provide 1 random value that will not change within a template
162 // but will be different from template to template. This is useful for
163 // e.g. aria attributes that only work with id attributes and must be
165 $mustache->addHelper('uniqid', new \core\output\
mustache_uniqid_helper());
166 if (isset($templatecache[$templatename])) {
167 $template = $templatecache[$templatename];
170 $template = $mustache->loadTemplate($templatename);
171 $templatecache[$templatename] = $template;
172 } catch (Mustache_Exception_UnknownTemplateException
$e) {
173 throw new moodle_exception('Unknown template: ' . $templatename);
177 $renderedtemplate = trim($template->render($context));
179 // If we had an existing uniqid helper then we need to restore it to allow
180 // handle nested calls of render_from_template.
182 $mustache->addHelper('uniqid', $uniqidhelper);
185 return $renderedtemplate;
190 * Returns rendered widget.
192 * The provided widget needs to be an object that extends the renderable
194 * If will then be rendered by a method based upon the classname for the widget.
195 * For instance a widget of class `crazywidget` will be rendered by a protected
196 * render_crazywidget method of this renderer.
198 * @param renderable $widget instance with renderable interface
201 public function render(renderable
$widget) {
202 $classname = get_class($widget);
204 $classname = preg_replace('/^.*\\\/', '', $classname);
205 // Remove _renderable suffixes
206 $classname = preg_replace('/_renderable$/', '', $classname);
208 $rendermethod = 'render_'.$classname;
209 if (method_exists($this, $rendermethod)) {
210 return $this->$rendermethod($widget);
212 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
216 * Adds a JS action for the element with the provided id.
218 * This method adds a JS event for the provided component action to the page
219 * and then returns the id that the event has been attached to.
220 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
222 * @param component_action $action
224 * @return string id of element, either original submitted or random new if not supplied
226 public function add_action_handler(component_action
$action, $id = null) {
228 $id = html_writer
::random_id($action->event
);
230 $this->page
->requires
->event_handler("#$id", $action->event
, $action->jsfunction
, $action->jsfunctionargs
);
235 * Returns true is output has already started, and false if not.
237 * @return boolean true if the header has been printed.
239 public function has_started() {
240 return $this->page
->state
>= moodle_page
::STATE_IN_BODY
;
244 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
246 * @param mixed $classes Space-separated string or array of classes
247 * @return string HTML class attribute value
249 public static function prepare_classes($classes) {
250 if (is_array($classes)) {
251 return implode(' ', array_unique($classes));
256 public function pix_url($imagename, $component = 'moodle') {
257 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.');
258 return $this->page
->theme
->image_url($imagename, $component);
262 * Return the moodle_url for an image.
264 * The exact image location and extension is determined
265 * automatically by searching for gif|png|jpg|jpeg, please
266 * note there can not be diferent images with the different
267 * extension. The imagename is for historical reasons
268 * a relative path name, it may be changed later for core
269 * images. It is recommended to not use subdirectories
270 * in plugin and theme pix directories.
272 * There are three types of images:
273 * 1/ theme images - stored in theme/mytheme/pix/,
274 * use component 'theme'
275 * 2/ core images - stored in /pix/,
276 * overridden via theme/mytheme/pix_core/
277 * 3/ plugin images - stored in mod/mymodule/pix,
278 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
279 * example: image_url('comment', 'mod_glossary')
281 * @param string $imagename the pathname of the image
282 * @param string $component full plugin name (aka component) or 'theme'
285 public function image_url($imagename, $component = 'moodle') {
286 return $this->page
->theme
->image_url($imagename, $component);
290 * Return the site's logo URL, if any.
292 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
293 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
294 * @return moodle_url|false
296 public function get_logo_url($maxwidth = null, $maxheight = 200) {
298 $logo = get_config('core_admin', 'logo');
303 // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
304 // It's not worth the overhead of detecting and serving 2 different images based on the device.
306 // Hide the requested size in the file path.
307 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
309 // Use $CFG->themerev to prevent browser caching when the file changes.
310 return moodle_url
::make_pluginfile_url(context_system
::instance()->id
, 'core_admin', 'logo', $filepath,
311 theme_get_revision(), $logo);
315 * Return the site's compact logo URL, if any.
317 * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
318 * @param int $maxheight The maximum height, or null when the maximum height does not matter.
319 * @return moodle_url|false
321 public function get_compact_logo_url($maxwidth = 100, $maxheight = 100) {
323 $logo = get_config('core_admin', 'logocompact');
328 // Hide the requested size in the file path.
329 $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
331 // Use $CFG->themerev to prevent browser caching when the file changes.
332 return moodle_url
::make_pluginfile_url(context_system
::instance()->id
, 'core_admin', 'logocompact', $filepath,
333 theme_get_revision(), $logo);
340 * Basis for all plugin renderers.
342 * @copyright Petr Skoda (skodak)
343 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
348 class plugin_renderer_base
extends renderer_base
{
351 * @var renderer_base|core_renderer A reference to the current renderer.
352 * The renderer provided here will be determined by the page but will in 90%
353 * of cases by the {@link core_renderer}
358 * Constructor method, calls the parent constructor
360 * @param moodle_page $page
361 * @param string $target one of rendering target constants
363 public function __construct(moodle_page
$page, $target) {
364 if (empty($target) && $page->pagelayout
=== 'maintenance') {
365 // If the page is using the maintenance layout then we're going to force the target to maintenance.
366 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
367 // unavailable for this page layout.
368 $target = RENDERER_TARGET_MAINTENANCE
;
370 $this->output
= $page->get_renderer('core', null, $target);
371 parent
::__construct($page, $target);
375 * Renders the provided widget and returns the HTML to display it.
377 * @param renderable $widget instance with renderable interface
380 public function render(renderable
$widget) {
381 $classname = get_class($widget);
383 $classname = preg_replace('/^.*\\\/', '', $classname);
384 // Keep a copy at this point, we may need to look for a deprecated method.
385 $deprecatedmethod = 'render_'.$classname;
386 // Remove _renderable suffixes
387 $classname = preg_replace('/_renderable$/', '', $classname);
389 $rendermethod = 'render_'.$classname;
390 if (method_exists($this, $rendermethod)) {
391 return $this->$rendermethod($widget);
393 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
394 // This is exactly where we don't want to be.
395 // If you have arrived here you have a renderable component within your plugin that has the name
396 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
397 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
398 // and the _renderable suffix now gets removed when looking for a render method.
399 // You need to change your renderers render_blah_renderable to render_blah.
400 // Until you do this it will not be possible for a theme to override the renderer to override your method.
401 // Please do it ASAP.
402 static $debugged = array();
403 if (!isset($debugged[$deprecatedmethod])) {
404 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
405 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER
);
406 $debugged[$deprecatedmethod] = true;
408 return $this->$deprecatedmethod($widget);
410 // pass to core renderer if method not found here
411 return $this->output
->render($widget);
415 * Magic method used to pass calls otherwise meant for the standard renderer
416 * to it to ensure we don't go causing unnecessary grief.
418 * @param string $method
419 * @param array $arguments
422 public function __call($method, $arguments) {
423 if (method_exists('renderer_base', $method)) {
424 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
426 if (method_exists($this->output
, $method)) {
427 return call_user_func_array(array($this->output
, $method), $arguments);
429 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
436 * The standard implementation of the core_renderer interface.
438 * @copyright 2009 Tim Hunt
439 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
444 class core_renderer
extends renderer_base
{
446 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
447 * in layout files instead.
449 * @var string used in {@link core_renderer::header()}.
451 const MAIN_CONTENT_TOKEN
= '[MAIN CONTENT GOES HERE]';
454 * @var string Used to pass information from {@link core_renderer::doctype()} to
455 * {@link core_renderer::standard_head_html()}.
457 protected $contenttype;
460 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
461 * with {@link core_renderer::header()}.
463 protected $metarefreshtag = '';
466 * @var string Unique token for the closing HTML
468 protected $unique_end_html_token;
471 * @var string Unique token for performance information
473 protected $unique_performance_info_token;
476 * @var string Unique token for the main content.
478 protected $unique_main_content_token;
483 * @param moodle_page $page the page we are doing output for.
484 * @param string $target one of rendering target constants
486 public function __construct(moodle_page
$page, $target) {
487 $this->opencontainers
= $page->opencontainers
;
489 $this->target
= $target;
491 $this->unique_end_html_token
= '%%ENDHTML-'.sesskey().'%%';
492 $this->unique_performance_info_token
= '%%PERFORMANCEINFO-'.sesskey().'%%';
493 $this->unique_main_content_token
= '[MAIN CONTENT GOES HERE - '.sesskey().']';
497 * Get the DOCTYPE declaration that should be used with this page. Designed to
498 * be called in theme layout.php files.
500 * @return string the DOCTYPE declaration that should be used.
502 public function doctype() {
503 if ($this->page
->theme
->doctype
=== 'html5') {
504 $this->contenttype
= 'text/html; charset=utf-8';
505 return "<!DOCTYPE html>\n";
507 } else if ($this->page
->theme
->doctype
=== 'xhtml5') {
508 $this->contenttype
= 'application/xhtml+xml; charset=utf-8';
509 return "<!DOCTYPE html>\n";
513 $this->contenttype
= 'text/html; charset=utf-8';
514 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
519 * The attributes that should be added to the <html> tag. Designed to
520 * be called in theme layout.php files.
522 * @return string HTML fragment.
524 public function htmlattributes() {
525 $return = get_html_lang(true);
526 $attributes = array();
527 if ($this->page
->theme
->doctype
!== 'html5') {
528 $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
531 // Give plugins an opportunity to add things like xml namespaces to the html element.
532 // This function should return an array of html attribute names => values.
533 $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
534 foreach ($pluginswithfunction as $plugins) {
535 foreach ($plugins as $function) {
536 $newattrs = $function();
537 unset($newattrs['dir']);
538 unset($newattrs['lang']);
539 unset($newattrs['xmlns']);
540 unset($newattrs['xml:lang']);
541 $attributes +
= $newattrs;
545 foreach ($attributes as $key => $val) {
547 $return .= " $key=\"$val\"";
554 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
555 * that should be included in the <head> tag. Designed to be called in theme
558 * @return string HTML fragment.
560 public function standard_head_html() {
561 global $CFG, $SESSION;
563 // Before we output any content, we need to ensure that certain
564 // page components are set up.
566 // Blocks must be set up early as they may require javascript which
567 // has to be included in the page header before output is created.
568 foreach ($this->page
->blocks
->get_regions() as $region) {
569 $this->page
->blocks
->ensure_content_created($region, $this);
574 // Give plugins an opportunity to add any head elements. The callback
575 // must always return a string containing valid html head content.
576 $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
577 foreach ($pluginswithfunction as $plugins) {
578 foreach ($plugins as $function) {
579 $output .= $function();
583 // Allow a url_rewrite plugin to setup any dynamic head content.
584 if (isset($CFG->urlrewriteclass
) && !isset($CFG->upgraderunning
)) {
585 $class = $CFG->urlrewriteclass
;
586 $output .= $class::html_head_setup();
589 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
590 $output .= '<meta name="keywords" content="moodle, ' . $this->page
->title
. '" />' . "\n";
591 // This is only set by the {@link redirect()} method
592 $output .= $this->metarefreshtag
;
594 // Check if a periodic refresh delay has been set and make sure we arn't
595 // already meta refreshing
596 if ($this->metarefreshtag
=='' && $this->page
->periodicrefreshdelay
!==null) {
597 $output .= '<meta http-equiv="refresh" content="'.$this->page
->periodicrefreshdelay
.';url='.$this->page
->url
->out().'" />';
600 // Set up help link popups for all links with the helptooltip class
601 $this->page
->requires
->js_init_call('M.util.help_popups.setup');
603 $focus = $this->page
->focuscontrol
;
604 if (!empty($focus)) {
605 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
606 // This is a horrifically bad way to handle focus but it is passed in
607 // through messy formslib::moodleform
608 $this->page
->requires
->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
609 } else if (strpos($focus, '.')!==false) {
610 // Old style of focus, bad way to do it
611 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
);
612 $this->page
->requires
->js_function_call('old_onload_focus', explode('.', $focus, 2));
614 // Focus element with given id
615 $this->page
->requires
->js_function_call('focuscontrol', array($focus));
619 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
620 // any other custom CSS can not be overridden via themes and is highly discouraged
621 $urls = $this->page
->theme
->css_urls($this->page
);
622 foreach ($urls as $url) {
623 $this->page
->requires
->css_theme($url);
626 // Get the theme javascript head and footer
627 if ($jsurl = $this->page
->theme
->javascript_url(true)) {
628 $this->page
->requires
->js($jsurl, true);
630 if ($jsurl = $this->page
->theme
->javascript_url(false)) {
631 $this->page
->requires
->js($jsurl);
634 // Get any HTML from the page_requirements_manager.
635 $output .= $this->page
->requires
->get_head_code($this->page
, $this);
637 // List alternate versions.
638 foreach ($this->page
->alternateversions
as $type => $alt) {
639 $output .= html_writer
::empty_tag('link', array('rel' => 'alternate',
640 'type' => $type, 'title' => $alt->title
, 'href' => $alt->url
));
643 if (!empty($CFG->additionalhtmlhead
)) {
644 $output .= "\n".$CFG->additionalhtmlhead
;
651 * The standard tags (typically skip links) that should be output just inside
652 * the start of the <body> tag. Designed to be called in theme layout.php files.
654 * @return string HTML fragment.
656 public function standard_top_of_body_html() {
658 $output = $this->page
->requires
->get_top_of_body_code($this);
659 if ($this->page
->pagelayout
!== 'embedded' && !empty($CFG->additionalhtmltopofbody
)) {
660 $output .= "\n".$CFG->additionalhtmltopofbody
;
663 // Give plugins an opportunity to inject extra html content. The callback
664 // must always return a string containing valid html.
665 $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
666 foreach ($pluginswithfunction as $plugins) {
667 foreach ($plugins as $function) {
668 $output .= $function();
672 $output .= $this->maintenance_warning();
678 * Scheduled maintenance warning message.
680 * Note: This is a nasty hack to display maintenance notice, this should be moved
681 * to some general notification area once we have it.
685 public function maintenance_warning() {
689 if (isset($CFG->maintenance_later
) and $CFG->maintenance_later
> time()) {
690 $timeleft = $CFG->maintenance_later
- time();
691 // If timeleft less than 30 sec, set the class on block to error to highlight.
692 $errorclass = ($timeleft < 30) ?
'alert-error alert-danger' : 'alert-warning';
693 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-a-1 alert');
695 $a->hour
= (int)($timeleft / 3600);
696 $a->min
= (int)(($timeleft / 60) %
60);
697 $a->sec
= (int)($timeleft %
60);
699 $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
701 $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
704 $output .= $this->box_end();
705 $this->page
->requires
->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
706 array(array('timeleftinsec' => $timeleft)));
707 $this->page
->requires
->strings_for_js(
708 array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
715 * The standard tags (typically performance information and validation links,
716 * if we are in developer debug mode) that should be output in the footer area
717 * of the page. Designed to be called in theme layout.php files.
719 * @return string HTML fragment.
721 public function standard_footer_html() {
722 global $CFG, $SCRIPT;
724 if (during_initial_install()) {
725 // Debugging info can not work before install is finished,
726 // in any case we do not want any links during installation!
730 // This function is normally called from a layout.php file in {@link core_renderer::header()}
731 // but some of the content won't be known until later, so we return a placeholder
732 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
733 $output = $this->unique_performance_info_token
;
734 if ($this->page
->devicetypeinuse
== 'legacy') {
735 // The legacy theme is in use print the notification
736 $output .= html_writer
::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
739 // Get links to switch device types (only shown for users not on a default device)
740 $output .= $this->theme_switch_links();
742 if (!empty($CFG->debugpageinfo
)) {
743 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page
->debug_summary() . '</div>';
745 if (debugging(null, DEBUG_DEVELOPER
) and has_capability('moodle/site:config', context_system
::instance())) { // Only in developer mode
746 // Add link to profiling report if necessary
747 if (function_exists('profiling_is_running') && profiling_is_running()) {
748 $txt = get_string('profiledscript', 'admin');
749 $title = get_string('profiledscriptview', 'admin');
750 $url = $CFG->wwwroot
. '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
751 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
752 $output .= '<div class="profilingfooter">' . $link . '</div>';
754 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
755 'sesskey' => sesskey(), 'returnurl' => $this->page
->url
->out_as_local_url(false)));
756 $output .= '<div class="purgecaches">' .
757 html_writer
::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
759 if (!empty($CFG->debugvalidators
)) {
760 // NOTE: this is not a nice hack, $PAGE->url is not always accurate and $FULLME neither, it is not a bug if it fails. --skodak
761 $output .= '<div class="validators"><ul class="list-unstyled m-l-1">
762 <li><a href="http://validator.w3.org/check?verbose=1&ss=1&uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
763 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
764 <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>
771 * Returns standard main content placeholder.
772 * Designed to be called in theme layout.php files.
774 * @return string HTML fragment.
776 public function main_content() {
777 // This is here because it is the only place we can inject the "main" role over the entire main content area
778 // without requiring all theme's to manually do it, and without creating yet another thing people need to
779 // remember in the theme.
780 // This is an unfortunate hack. DO NO EVER add anything more here.
781 // DO NOT add classes.
783 return '<div role="main">'.$this->unique_main_content_token
.'</div>';
787 * The standard tags (typically script tags that are not needed earlier) that
788 * should be output after everything else. Designed to be called in theme layout.php files.
790 * @return string HTML fragment.
792 public function standard_end_of_body_html() {
795 // This function is normally called from a layout.php file in {@link core_renderer::header()}
796 // but some of the content won't be known until later, so we return a placeholder
797 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
799 if ($this->page
->pagelayout
!== 'embedded' && !empty($CFG->additionalhtmlfooter
)) {
800 $output .= "\n".$CFG->additionalhtmlfooter
;
802 $output .= $this->unique_end_html_token
;
807 * Return the standard string that says whether you are logged in (and switched
808 * roles/logged in as another user).
809 * @param bool $withlinks if false, then don't include any links in the HTML produced.
810 * If not set, the default is the nologinlinks option from the theme config.php file,
811 * and if that is not set, then links are included.
812 * @return string HTML fragment.
814 public function login_info($withlinks = null) {
815 global $USER, $CFG, $DB, $SESSION;
817 if (during_initial_install()) {
821 if (is_null($withlinks)) {
822 $withlinks = empty($this->page
->layout_options
['nologinlinks']);
825 $course = $this->page
->course
;
826 if (\core\session\manager
::is_loggedinas()) {
827 $realuser = \core\session\manager
::get_realuser();
828 $fullname = fullname($realuser, true);
830 $loginastitle = get_string('loginas');
831 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&sesskey=".sesskey()."\"";
832 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
834 $realuserinfo = " [$fullname] ";
840 $loginpage = $this->is_login_page();
841 $loginurl = get_login_url();
843 if (empty($course->id
)) {
844 // $course->id is not defined during installation
846 } else if (isloggedin()) {
847 $context = context_course
::instance($course->id
);
849 $fullname = fullname($USER, true);
850 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
852 $linktitle = get_string('viewprofile');
853 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
855 $username = $fullname;
857 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid
))) {
859 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
861 $username .= " from {$idprovider->name}";
865 $loggedinas = $realuserinfo.get_string('loggedinasguest');
866 if (!$loginpage && $withlinks) {
867 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
869 } else if (is_role_switched($course->id
)) { // Has switched roles
871 if ($role = $DB->get_record('role', array('id'=>$USER->access
['rsw'][$context->path
]))) {
872 $rolename = ': '.role_get_name($role, $context);
874 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
876 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id
,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page
->url
->out_as_local_url(false)));
877 $loggedinas .= ' ('.html_writer
::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
880 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
882 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
886 $loggedinas = get_string('loggedinnot', 'moodle');
887 if (!$loginpage && $withlinks) {
888 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
892 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
894 if (isset($SESSION->justloggedin
)) {
895 unset($SESSION->justloggedin
);
896 if (!empty($CFG->displayloginfailures
)) {
897 if (!isguestuser()) {
898 // Include this file only when required.
899 require_once($CFG->dirroot
. '/user/lib.php');
900 if ($count = user_count_login_failures($USER)) {
901 $loggedinas .= '<div class="loginfailures">';
903 $a->attempts
= $count;
904 $loggedinas .= get_string('failedloginattempts', '', $a);
905 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system
::instance())) {
906 $loggedinas .= ' ('.html_writer
::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
907 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
909 $loggedinas .= '</div>';
919 * Check whether the current page is a login page.
924 protected function is_login_page() {
925 // This is a real bit of a hack, but its a rarety that we need to do something like this.
926 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
927 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
929 $this->page
->url
->out_as_local_url(false, array()),
932 '/login/forgot_password.php',
938 * Return the 'back' link that normally appears in the footer.
940 * @return string HTML fragment.
942 public function home_link() {
945 if ($this->page
->pagetype
== 'site-index') {
946 // Special case for site home page - please do not remove
947 return '<div class="sitelink">' .
948 '<a title="Moodle" href="http://moodle.org/">' .
949 '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
951 } else if (!empty($CFG->target_release
) && $CFG->target_release
!= $CFG->release
) {
952 // Special case for during install/upgrade.
953 return '<div class="sitelink">'.
954 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
955 '<img src="' . $this->image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
957 } else if ($this->page
->course
->id
== $SITE->id ||
strpos($this->page
->pagetype
, 'course-view') === 0) {
958 return '<div class="homelink"><a href="' . $CFG->wwwroot
. '/">' .
959 get_string('home') . '</a></div>';
962 return '<div class="homelink"><a href="' . $CFG->wwwroot
. '/course/view.php?id=' . $this->page
->course
->id
. '">' .
963 format_string($this->page
->course
->shortname
, true, array('context' => $this->page
->context
)) . '</a></div>';
968 * Redirects the user by any means possible given the current state
970 * This function should not be called directly, it should always be called using
971 * the redirect function in lib/weblib.php
973 * The redirect function should really only be called before page output has started
974 * however it will allow itself to be called during the state STATE_IN_BODY
976 * @param string $encodedurl The URL to send to encoded if required
977 * @param string $message The message to display to the user if any
978 * @param int $delay The delay before redirecting a user, if $message has been
979 * set this is a requirement and defaults to 3, set to 0 no delay
980 * @param boolean $debugdisableredirect this redirect has been disabled for
981 * debugging purposes. Display a message that explains, and don't
982 * trigger the redirect.
983 * @param string $messagetype The type of notification to show the message in.
984 * See constants on \core\output\notification.
985 * @return string The HTML to display to the user before dying, may contain
986 * meta refresh, javascript refresh, and may have set header redirects
988 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
989 $messagetype = \core\output\notification
::NOTIFY_INFO
) {
991 $url = str_replace('&', '&', $encodedurl);
993 switch ($this->page
->state
) {
994 case moodle_page
::STATE_BEFORE_HEADER
:
995 // No output yet it is safe to delivery the full arsenal of redirect methods
996 if (!$debugdisableredirect) {
997 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
998 $this->metarefreshtag
= '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
999 $this->page
->requires
->js_function_call('document.location.replace', array($url), false, ($delay +
3));
1001 $output = $this->header();
1003 case moodle_page
::STATE_PRINTING_HEADER
:
1004 // We should hopefully never get here
1005 throw new coding_exception('You cannot redirect while printing the page header');
1007 case moodle_page
::STATE_IN_BODY
:
1008 // We really shouldn't be here but we can deal with this
1009 debugging("You should really redirect before you start page output");
1010 if (!$debugdisableredirect) {
1011 $this->page
->requires
->js_function_call('document.location.replace', array($url), false, $delay);
1013 $output = $this->opencontainers
->pop_all_but_last();
1015 case moodle_page
::STATE_DONE
:
1016 // Too late to be calling redirect now
1017 throw new coding_exception('You cannot redirect after the entire page has been generated');
1020 $output .= $this->notification($message, $messagetype);
1021 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1022 if ($debugdisableredirect) {
1023 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1025 $output .= $this->footer();
1030 * Start output by sending the HTTP headers, and printing the HTML <head>
1031 * and the start of the <body>.
1033 * To control what is printed, you should set properties on $PAGE. If you
1034 * are familiar with the old {@link print_header()} function from Moodle 1.9
1035 * you will find that there are properties on $PAGE that correspond to most
1036 * of the old parameters to could be passed to print_header.
1038 * Not that, in due course, the remaining $navigation, $menu parameters here
1039 * will be replaced by more properties of $PAGE, but that is still to do.
1041 * @return string HTML that you must output this, preferably immediately.
1043 public function header() {
1044 global $USER, $CFG, $SESSION;
1046 // Give plugins an opportunity touch things before the http headers are sent
1047 // such as adding additional headers. The return value is ignored.
1048 $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1049 foreach ($pluginswithfunction as $plugins) {
1050 foreach ($plugins as $function) {
1055 if (\core\session\manager
::is_loggedinas()) {
1056 $this->page
->add_body_class('userloggedinas');
1059 if (isset($SESSION->justloggedin
) && !empty($CFG->displayloginfailures
)) {
1060 require_once($CFG->dirroot
. '/user/lib.php');
1061 // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1062 if ($count = user_count_login_failures($USER, false)) {
1063 $this->page
->add_body_class('loginfailures');
1067 // If the user is logged in, and we're not in initial install,
1068 // check to see if the user is role-switched and add the appropriate
1069 // CSS class to the body element.
1070 if (!during_initial_install() && isloggedin() && is_role_switched($this->page
->course
->id
)) {
1071 $this->page
->add_body_class('userswitchedrole');
1074 // Give themes a chance to init/alter the page object.
1075 $this->page
->theme
->init_page($this->page
);
1077 $this->page
->set_state(moodle_page
::STATE_PRINTING_HEADER
);
1079 // Find the appropriate page layout file, based on $this->page->pagelayout.
1080 $layoutfile = $this->page
->theme
->layout_file($this->page
->pagelayout
);
1081 // Render the layout using the layout file.
1082 $rendered = $this->render_page_layout($layoutfile);
1084 // Slice the rendered output into header and footer.
1085 $cutpos = strpos($rendered, $this->unique_main_content_token
);
1086 if ($cutpos === false) {
1087 $cutpos = strpos($rendered, self
::MAIN_CONTENT_TOKEN
);
1088 $token = self
::MAIN_CONTENT_TOKEN
;
1090 $token = $this->unique_main_content_token
;
1093 if ($cutpos === false) {
1094 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.');
1096 $header = substr($rendered, 0, $cutpos);
1097 $footer = substr($rendered, $cutpos +
strlen($token));
1099 if (empty($this->contenttype
)) {
1100 debugging('The page layout file did not call $OUTPUT->doctype()');
1101 $header = $this->doctype() . $header;
1104 // If this theme version is below 2.4 release and this is a course view page
1105 if ((!isset($this->page
->theme
->settings
->version
) ||
$this->page
->theme
->settings
->version
< 2012101500) &&
1106 $this->page
->pagelayout
=== 'course' && $this->page
->url
->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE
)) {
1107 // check if course content header/footer have not been output during render of theme layout
1108 $coursecontentheader = $this->course_content_header(true);
1109 $coursecontentfooter = $this->course_content_footer(true);
1110 if (!empty($coursecontentheader)) {
1111 // display debug message and add header and footer right above and below main content
1112 // Please note that course header and footer (to be displayed above and below the whole page)
1113 // are not displayed in this case at all.
1114 // Besides the content header and footer are not displayed on any other course page
1115 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
);
1116 $header .= $coursecontentheader;
1117 $footer = $coursecontentfooter. $footer;
1121 send_headers($this->contenttype
, $this->page
->cacheable
);
1123 $this->opencontainers
->push('header/footer', $footer);
1124 $this->page
->set_state(moodle_page
::STATE_IN_BODY
);
1126 return $header . $this->skip_link_target('maincontent');
1130 * Renders and outputs the page layout file.
1132 * This is done by preparing the normal globals available to a script, and
1133 * then including the layout file provided by the current theme for the
1136 * @param string $layoutfile The name of the layout file
1137 * @return string HTML code
1139 protected function render_page_layout($layoutfile) {
1140 global $CFG, $SITE, $USER;
1141 // The next lines are a bit tricky. The point is, here we are in a method
1142 // of a renderer class, and this object may, or may not, be the same as
1143 // the global $OUTPUT object. When rendering the page layout file, we want to use
1144 // this object. However, people writing Moodle code expect the current
1145 // renderer to be called $OUTPUT, not $this, so define a variable called
1146 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1148 $PAGE = $this->page
;
1149 $COURSE = $this->page
->course
;
1152 include($layoutfile);
1153 $rendered = ob_get_contents();
1159 * Outputs the page's footer
1161 * @return string HTML fragment
1163 public function footer() {
1164 global $CFG, $DB, $PAGE;
1166 // Give plugins an opportunity to touch the page before JS is finalized.
1167 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1168 foreach ($pluginswithfunction as $plugins) {
1169 foreach ($plugins as $function) {
1174 $output = $this->container_end_all(true);
1176 $footer = $this->opencontainers
->pop('header/footer');
1178 if (debugging() and $DB and $DB->is_transaction_started()) {
1179 // TODO: MDL-20625 print warning - transaction will be rolled back
1182 // Provide some performance info if required
1183 $performanceinfo = '';
1184 if (defined('MDL_PERF') ||
(!empty($CFG->perfdebug
) and $CFG->perfdebug
> 7)) {
1185 $perf = get_performance_info();
1186 if (defined('MDL_PERFTOFOOT') ||
debugging() ||
$CFG->perfdebug
> 7) {
1187 $performanceinfo = $perf['html'];
1191 // We always want performance data when running a performance test, even if the user is redirected to another page.
1192 if (MDL_PERF_TEST
&& strpos($footer, $this->unique_performance_info_token
) === false) {
1193 $footer = $this->unique_performance_info_token
. $footer;
1195 $footer = str_replace($this->unique_performance_info_token
, $performanceinfo, $footer);
1197 // Only show notifications when we have a $PAGE context id.
1198 if (!empty($PAGE->context
->id
)) {
1199 $this->page
->requires
->js_call_amd('core/notification', 'init', array(
1201 \core\notification
::fetch_as_array($this)
1204 $footer = str_replace($this->unique_end_html_token
, $this->page
->requires
->get_end_code(), $footer);
1206 $this->page
->set_state(moodle_page
::STATE_DONE
);
1208 return $output . $footer;
1212 * Close all but the last open container. This is useful in places like error
1213 * handling, where you want to close all the open containers (apart from <body>)
1214 * before outputting the error message.
1216 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1217 * developer debug warning if it isn't.
1218 * @return string the HTML required to close any open containers inside <body>.
1220 public function container_end_all($shouldbenone = false) {
1221 return $this->opencontainers
->pop_all_but_last($shouldbenone);
1225 * Returns course-specific information to be output immediately above content on any course page
1226 * (for the current course)
1228 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1231 public function course_content_header($onlyifnotcalledbefore = false) {
1233 static $functioncalled = false;
1234 if ($functioncalled && $onlyifnotcalledbefore) {
1235 // we have already output the content header
1239 // Output any session notification.
1240 $notifications = \core\notification
::fetch();
1242 $bodynotifications = '';
1243 foreach ($notifications as $notification) {
1244 $bodynotifications .= $this->render_from_template(
1245 $notification->get_template_name(),
1246 $notification->export_for_template($this)
1250 $output = html_writer
::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1252 if ($this->page
->course
->id
== SITEID
) {
1253 // return immediately and do not include /course/lib.php if not necessary
1257 require_once($CFG->dirroot
.'/course/lib.php');
1258 $functioncalled = true;
1259 $courseformat = course_get_format($this->page
->course
);
1260 if (($obj = $courseformat->course_content_header()) !== null) {
1261 $output .= html_writer
::div($courseformat->get_renderer($this->page
)->render($obj), 'course-content-header');
1267 * Returns course-specific information to be output immediately below content on any course page
1268 * (for the current course)
1270 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1273 public function course_content_footer($onlyifnotcalledbefore = false) {
1275 if ($this->page
->course
->id
== SITEID
) {
1276 // return immediately and do not include /course/lib.php if not necessary
1279 static $functioncalled = false;
1280 if ($functioncalled && $onlyifnotcalledbefore) {
1281 // we have already output the content footer
1284 $functioncalled = true;
1285 require_once($CFG->dirroot
.'/course/lib.php');
1286 $courseformat = course_get_format($this->page
->course
);
1287 if (($obj = $courseformat->course_content_footer()) !== null) {
1288 return html_writer
::div($courseformat->get_renderer($this->page
)->render($obj), 'course-content-footer');
1294 * Returns course-specific information to be output on any course page in the header area
1295 * (for the current course)
1299 public function course_header() {
1301 if ($this->page
->course
->id
== SITEID
) {
1302 // return immediately and do not include /course/lib.php if not necessary
1305 require_once($CFG->dirroot
.'/course/lib.php');
1306 $courseformat = course_get_format($this->page
->course
);
1307 if (($obj = $courseformat->course_header()) !== null) {
1308 return $courseformat->get_renderer($this->page
)->render($obj);
1314 * Returns course-specific information to be output on any course page in the footer area
1315 * (for the current course)
1319 public function course_footer() {
1321 if ($this->page
->course
->id
== SITEID
) {
1322 // return immediately and do not include /course/lib.php if not necessary
1325 require_once($CFG->dirroot
.'/course/lib.php');
1326 $courseformat = course_get_format($this->page
->course
);
1327 if (($obj = $courseformat->course_footer()) !== null) {
1328 return $courseformat->get_renderer($this->page
)->render($obj);
1334 * Returns lang menu or '', this method also checks forcing of languages in courses.
1336 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1338 * @return string The lang menu HTML or empty string
1340 public function lang_menu() {
1343 if (empty($CFG->langmenu
)) {
1347 if ($this->page
->course
!= SITEID
and !empty($this->page
->course
->lang
)) {
1348 // do not show lang menu if language forced
1352 $currlang = current_language();
1353 $langs = get_string_manager()->get_list_of_translations();
1355 if (count($langs) < 2) {
1359 $s = new single_select($this->page
->url
, 'lang', $langs, $currlang, null);
1360 $s->label
= get_accesshide(get_string('language'));
1361 $s->class = 'langmenu';
1362 return $this->render($s);
1366 * Output the row of editing icons for a block, as defined by the controls array.
1368 * @param array $controls an array like {@link block_contents::$controls}.
1369 * @param string $blockid The ID given to the block.
1370 * @return string HTML fragment.
1372 public function block_controls($actions, $blockid = null) {
1374 if (empty($actions)) {
1377 $menu = new action_menu($actions);
1378 if ($blockid !== null) {
1379 $menu->set_owner_selector('#'.$blockid);
1381 $menu->set_constraint('.block-region');
1382 $menu->attributes
['class'] .= ' block-control-actions commands';
1383 return $this->render($menu);
1387 * Renders an action menu component.
1390 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1391 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1393 * @param action_menu $menu
1394 * @return string HTML
1396 public function render_action_menu(action_menu
$menu) {
1397 $context = $menu->export_for_template($this);
1398 return $this->render_from_template('core/action_menu', $context);
1402 * Renders an action_menu_link item.
1404 * @param action_menu_link $action
1405 * @return string HTML fragment
1407 protected function render_action_menu_link(action_menu_link
$action) {
1408 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1412 * Renders a primary action_menu_filler item.
1414 * @param action_menu_link_filler $action
1415 * @return string HTML fragment
1417 protected function render_action_menu_filler(action_menu_filler
$action) {
1418 return html_writer
::span(' ', 'filler');
1422 * Renders a primary action_menu_link item.
1424 * @param action_menu_link_primary $action
1425 * @return string HTML fragment
1427 protected function render_action_menu_link_primary(action_menu_link_primary
$action) {
1428 return $this->render_action_menu_link($action);
1432 * Renders a secondary action_menu_link item.
1434 * @param action_menu_link_secondary $action
1435 * @return string HTML fragment
1437 protected function render_action_menu_link_secondary(action_menu_link_secondary
$action) {
1438 return $this->render_action_menu_link($action);
1442 * Prints a nice side block with an optional header.
1444 * The content is described
1445 * by a {@link core_renderer::block_contents} object.
1447 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1448 * <div class="header"></div>
1449 * <div class="content">
1451 * <div class="footer">
1454 * <div class="annotation">
1458 * @param block_contents $bc HTML for the content
1459 * @param string $region the region the block is appearing in.
1460 * @return string the HTML to be output.
1462 public function block(block_contents
$bc, $region) {
1463 $bc = clone($bc); // Avoid messing up the object passed in.
1464 if (empty($bc->blockinstanceid
) ||
!strip_tags($bc->title
)) {
1465 $bc->collapsible
= block_contents
::NOT_HIDEABLE
;
1467 if (!empty($bc->blockinstanceid
)) {
1468 $bc->attributes
['data-instanceid'] = $bc->blockinstanceid
;
1470 $skiptitle = strip_tags($bc->title
);
1471 if ($bc->blockinstanceid
&& !empty($skiptitle)) {
1472 $bc->attributes
['aria-labelledby'] = 'instance-'.$bc->blockinstanceid
.'-header';
1473 } else if (!empty($bc->arialabel
)) {
1474 $bc->attributes
['aria-label'] = $bc->arialabel
;
1476 if ($bc->dockable
) {
1477 $bc->attributes
['data-dockable'] = 1;
1479 if ($bc->collapsible
== block_contents
::HIDDEN
) {
1480 $bc->add_class('hidden');
1482 if (!empty($bc->controls
)) {
1483 $bc->add_class('block_with_controls');
1487 if (empty($skiptitle)) {
1491 $output = html_writer
::link('#sb-'.$bc->skipid
, get_string('skipa', 'access', $skiptitle),
1492 array('class' => 'skip skip-block', 'id' => 'fsb-' . $bc->skipid
));
1493 $skipdest = html_writer
::span('', 'skip-block-to',
1494 array('id' => 'sb-' . $bc->skipid
));
1497 $output .= html_writer
::start_tag('div', $bc->attributes
);
1499 $output .= $this->block_header($bc);
1500 $output .= $this->block_content($bc);
1502 $output .= html_writer
::end_tag('div');
1504 $output .= $this->block_annotation($bc);
1506 $output .= $skipdest;
1508 $this->init_block_hider_js($bc);
1513 * Produces a header for a block
1515 * @param block_contents $bc
1518 protected function block_header(block_contents
$bc) {
1522 $attributes = array();
1523 if ($bc->blockinstanceid
) {
1524 $attributes['id'] = 'instance-'.$bc->blockinstanceid
.'-header';
1526 $title = html_writer
::tag('h2', $bc->title
, $attributes);
1530 if (isset($bc->attributes
['id'])) {
1531 $blockid = $bc->attributes
['id'];
1533 $controlshtml = $this->block_controls($bc->controls
, $blockid);
1536 if ($title ||
$controlshtml) {
1537 $output .= html_writer
::tag('div', html_writer
::tag('div', html_writer
::tag('div', '', array('class'=>'block_action')). $title . $controlshtml, array('class' => 'title')), array('class' => 'header'));
1543 * Produces the content area for a block
1545 * @param block_contents $bc
1548 protected function block_content(block_contents
$bc) {
1549 $output = html_writer
::start_tag('div', array('class' => 'content'));
1550 if (!$bc->title
&& !$this->block_controls($bc->controls
)) {
1551 $output .= html_writer
::tag('div', '', array('class'=>'block_action notitle'));
1553 $output .= $bc->content
;
1554 $output .= $this->block_footer($bc);
1555 $output .= html_writer
::end_tag('div');
1561 * Produces the footer for a block
1563 * @param block_contents $bc
1566 protected function block_footer(block_contents
$bc) {
1569 $output .= html_writer
::tag('div', $bc->footer
, array('class' => 'footer'));
1575 * Produces the annotation for a block
1577 * @param block_contents $bc
1580 protected function block_annotation(block_contents
$bc) {
1582 if ($bc->annotation
) {
1583 $output .= html_writer
::tag('div', $bc->annotation
, array('class' => 'blockannotation'));
1589 * Calls the JS require function to hide a block.
1591 * @param block_contents $bc A block_contents object
1593 protected function init_block_hider_js(block_contents
$bc) {
1594 if (!empty($bc->attributes
['id']) and $bc->collapsible
!= block_contents
::NOT_HIDEABLE
) {
1595 $config = new stdClass
;
1596 $config->id
= $bc->attributes
['id'];
1597 $config->title
= strip_tags($bc->title
);
1598 $config->preference
= 'block' . $bc->blockinstanceid
. 'hidden';
1599 $config->tooltipVisible
= get_string('hideblocka', 'access', $config->title
);
1600 $config->tooltipHidden
= get_string('showblocka', 'access', $config->title
);
1602 $this->page
->requires
->js_init_call('M.util.init_block_hider', array($config));
1603 user_preference_allow_ajax_update($config->preference
, PARAM_BOOL
);
1608 * Render the contents of a block_list.
1610 * @param array $icons the icon for each item.
1611 * @param array $items the content of each item.
1612 * @return string HTML
1614 public function list_block_contents($icons, $items) {
1617 foreach ($items as $key => $string) {
1618 $item = html_writer
::start_tag('li', array('class' => 'r' . $row));
1619 if (!empty($icons[$key])) { //test if the content has an assigned icon
1620 $item .= html_writer
::tag('div', $icons[$key], array('class' => 'icon column c0'));
1622 $item .= html_writer
::tag('div', $string, array('class' => 'column c1'));
1623 $item .= html_writer
::end_tag('li');
1625 $row = 1 - $row; // Flip even/odd.
1627 return html_writer
::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1631 * Output all the blocks in a particular region.
1633 * @param string $region the name of a region on this page.
1634 * @return string the HTML to be output.
1636 public function blocks_for_region($region) {
1637 $blockcontents = $this->page
->blocks
->get_content_for_region($region, $this);
1638 $blocks = $this->page
->blocks
->get_blocks_for_region($region);
1641 foreach ($blocks as $block) {
1642 $zones[] = $block->title
;
1646 foreach ($blockcontents as $bc) {
1647 if ($bc instanceof block_contents
) {
1648 $output .= $this->block($bc, $region);
1649 $lastblock = $bc->title
;
1650 } else if ($bc instanceof block_move_target
) {
1651 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1653 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1660 * Output a place where the block that is currently being moved can be dropped.
1662 * @param block_move_target $target with the necessary details.
1663 * @param array $zones array of areas where the block can be moved to
1664 * @param string $previous the block located before the area currently being rendered.
1665 * @param string $region the name of the region
1666 * @return string the HTML to be output.
1668 public function block_move_target($target, $zones, $previous, $region) {
1669 if ($previous == null) {
1670 if (empty($zones)) {
1671 // There are no zones, probably because there are no blocks.
1672 $regions = $this->page
->theme
->get_all_block_regions();
1673 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1675 $position = get_string('moveblockbefore', 'block', $zones[0]);
1678 $position = get_string('moveblockafter', 'block', $previous);
1680 return html_writer
::tag('a', html_writer
::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url
, 'class' => 'blockmovetarget'));
1684 * Renders a special html link with attached action
1686 * Theme developers: DO NOT OVERRIDE! Please override function
1687 * {@link core_renderer::render_action_link()} instead.
1689 * @param string|moodle_url $url
1690 * @param string $text HTML fragment
1691 * @param component_action $action
1692 * @param array $attributes associative array of html link attributes + disabled
1693 * @param pix_icon optional pix icon to render with the link
1694 * @return string HTML fragment
1696 public function action_link($url, $text, component_action
$action = null, array $attributes = null, $icon = null) {
1697 if (!($url instanceof moodle_url
)) {
1698 $url = new moodle_url($url);
1700 $link = new action_link($url, $text, $action, $attributes, $icon);
1702 return $this->render($link);
1706 * Renders an action_link object.
1708 * The provided link is renderer and the HTML returned. At the same time the
1709 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1711 * @param action_link $link
1712 * @return string HTML fragment
1714 protected function render_action_link(action_link
$link) {
1715 return $this->render_from_template('core/action_link', $link->export_for_template($this));
1719 * Renders an action_icon.
1721 * This function uses the {@link core_renderer::action_link()} method for the
1722 * most part. What it does different is prepare the icon as HTML and use it
1725 * Theme developers: If you want to change how action links and/or icons are rendered,
1726 * consider overriding function {@link core_renderer::render_action_link()} and
1727 * {@link core_renderer::render_pix_icon()}.
1729 * @param string|moodle_url $url A string URL or moodel_url
1730 * @param pix_icon $pixicon
1731 * @param component_action $action
1732 * @param array $attributes associative array of html link attributes + disabled
1733 * @param bool $linktext show title next to image in link
1734 * @return string HTML fragment
1736 public function action_icon($url, pix_icon
$pixicon, component_action
$action = null, array $attributes = null, $linktext=false) {
1737 if (!($url instanceof moodle_url
)) {
1738 $url = new moodle_url($url);
1740 $attributes = (array)$attributes;
1742 if (empty($attributes['class'])) {
1743 // let ppl override the class via $options
1744 $attributes['class'] = 'action-icon';
1747 $icon = $this->render($pixicon);
1750 $text = $pixicon->attributes
['alt'];
1755 return $this->action_link($url, $text.$icon, $action, $attributes);
1759 * Print a message along with button choices for Continue/Cancel
1761 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1763 * @param string $message The question to ask the user
1764 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1765 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1766 * @return string HTML fragment
1768 public function confirm($message, $continue, $cancel) {
1769 if ($continue instanceof single_button
) {
1771 $continue->primary
= true;
1772 } else if (is_string($continue)) {
1773 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
1774 } else if ($continue instanceof moodle_url
) {
1775 $continue = new single_button($continue, get_string('continue'), 'post', true);
1777 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1780 if ($cancel instanceof single_button
) {
1782 } else if (is_string($cancel)) {
1783 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1784 } else if ($cancel instanceof moodle_url
) {
1785 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1787 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1790 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice');
1791 $output .= $this->box_start('modal-content', 'modal-content');
1792 $output .= $this->box_start('modal-header', 'modal-header');
1793 $output .= html_writer
::tag('h4', get_string('confirm'));
1794 $output .= $this->box_end();
1795 $output .= $this->box_start('modal-body', 'modal-body');
1796 $output .= html_writer
::tag('p', $message);
1797 $output .= $this->box_end();
1798 $output .= $this->box_start('modal-footer', 'modal-footer');
1799 $output .= html_writer
::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1800 $output .= $this->box_end();
1801 $output .= $this->box_end();
1802 $output .= $this->box_end();
1807 * Returns a form with a single button.
1809 * Theme developers: DO NOT OVERRIDE! Please override function
1810 * {@link core_renderer::render_single_button()} instead.
1812 * @param string|moodle_url $url
1813 * @param string $label button text
1814 * @param string $method get or post submit method
1815 * @param array $options associative array {disabled, title, etc.}
1816 * @return string HTML fragment
1818 public function single_button($url, $label, $method='post', array $options=null) {
1819 if (!($url instanceof moodle_url
)) {
1820 $url = new moodle_url($url);
1822 $button = new single_button($url, $label, $method);
1824 foreach ((array)$options as $key=>$value) {
1825 if (array_key_exists($key, $button)) {
1826 $button->$key = $value;
1830 return $this->render($button);
1834 * Renders a single button widget.
1836 * This will return HTML to display a form containing a single button.
1838 * @param single_button $button
1839 * @return string HTML fragment
1841 protected function render_single_button(single_button
$button) {
1842 $attributes = array('type' => 'submit',
1843 'value' => $button->label
,
1844 'disabled' => $button->disabled ?
'disabled' : null,
1845 'title' => $button->tooltip
);
1847 if ($button->actions
) {
1848 $id = html_writer
::random_id('single_button');
1849 $attributes['id'] = $id;
1850 foreach ($button->actions
as $action) {
1851 $this->add_action_handler($action, $id);
1855 // first the input element
1856 $output = html_writer
::empty_tag('input', $attributes);
1858 // then hidden fields
1859 $params = $button->url
->params();
1860 if ($button->method
=== 'post') {
1861 $params['sesskey'] = sesskey();
1863 foreach ($params as $var => $val) {
1864 $output .= html_writer
::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1867 // then div wrapper for xhtml strictness
1868 $output = html_writer
::tag('div', $output);
1870 // now the form itself around it
1871 if ($button->method
=== 'get') {
1872 $url = $button->url
->out_omit_querystring(true); // url without params, the anchor part allowed
1874 $url = $button->url
->out_omit_querystring(); // url without params, the anchor part not allowed
1877 $url = '#'; // there has to be always some action
1879 $attributes = array('method' => $button->method
,
1881 'id' => $button->formid
);
1882 $output = html_writer
::tag('form', $output, $attributes);
1884 // and finally one more wrapper with class
1885 return html_writer
::tag('div', $output, array('class' => $button->class));
1889 * Returns a form with a single select widget.
1891 * Theme developers: DO NOT OVERRIDE! Please override function
1892 * {@link core_renderer::render_single_select()} instead.
1894 * @param moodle_url $url form action target, includes hidden fields
1895 * @param string $name name of selection field - the changing parameter in url
1896 * @param array $options list of options
1897 * @param string $selected selected element
1898 * @param array $nothing
1899 * @param string $formid
1900 * @param array $attributes other attributes for the single select
1901 * @return string HTML fragment
1903 public function single_select($url, $name, array $options, $selected = '',
1904 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
1905 if (!($url instanceof moodle_url
)) {
1906 $url = new moodle_url($url);
1908 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1910 if (array_key_exists('label', $attributes)) {
1911 $select->set_label($attributes['label']);
1912 unset($attributes['label']);
1914 $select->attributes
= $attributes;
1916 return $this->render($select);
1920 * Returns a dataformat selection and download form
1922 * @param string $label A text label
1923 * @param moodle_url|string $base The download page url
1924 * @param string $name The query param which will hold the type of the download
1925 * @param array $params Extra params sent to the download page
1926 * @return string HTML fragment
1928 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
1930 $formats = core_plugin_manager
::instance()->get_plugins_of_type('dataformat');
1932 foreach ($formats as $format) {
1933 if ($format->is_enabled()) {
1935 'value' => $format->name
,
1936 'label' => get_string('dataformat', $format->component
),
1940 $hiddenparams = array();
1941 foreach ($params as $key => $value) {
1942 $hiddenparams[] = array(
1951 'params' => $hiddenparams,
1952 'options' => $options,
1953 'sesskey' => sesskey(),
1954 'submit' => get_string('download'),
1957 return $this->render_from_template('core/dataformat_selector', $data);
1962 * Internal implementation of single_select rendering
1964 * @param single_select $select
1965 * @return string HTML fragment
1967 protected function render_single_select(single_select
$select) {
1968 return $this->render_from_template('core/single_select', $select->export_for_template($this));
1972 * Returns a form with a url select widget.
1974 * Theme developers: DO NOT OVERRIDE! Please override function
1975 * {@link core_renderer::render_url_select()} instead.
1977 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1978 * @param string $selected selected element
1979 * @param array $nothing
1980 * @param string $formid
1981 * @return string HTML fragment
1983 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1984 $select = new url_select($urls, $selected, $nothing, $formid);
1985 return $this->render($select);
1989 * Internal implementation of url_select rendering
1991 * @param url_select $select
1992 * @return string HTML fragment
1994 protected function render_url_select(url_select
$select) {
1995 return $this->render_from_template('core/url_select', $select->export_for_template($this));
1999 * Returns a string containing a link to the user documentation.
2000 * Also contains an icon by default. Shown to teachers and admin only.
2002 * @param string $path The page link after doc root and language, no leading slash.
2003 * @param string $text The text to be displayed for the link
2004 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2007 public function doc_link($path, $text = '', $forcepopup = false) {
2010 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2012 $url = new moodle_url(get_docs_url($path));
2014 $attributes = array('href'=>$url);
2015 if (!empty($CFG->doctonewwindow
) ||
$forcepopup) {
2016 $attributes['class'] = 'helplinkpopup';
2019 return html_writer
::tag('a', $icon.$text, $attributes);
2023 * Return HTML for an image_icon.
2025 * Theme developers: DO NOT OVERRIDE! Please override function
2026 * {@link core_renderer::render_image_icon()} instead.
2028 * @param string $pix short pix name
2029 * @param string $alt mandatory alt attribute
2030 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2031 * @param array $attributes htm lattributes
2032 * @return string HTML fragment
2034 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2035 $icon = new image_icon($pix, $alt, $component, $attributes);
2036 return $this->render($icon);
2040 * Renders a pix_icon widget and returns the HTML to display it.
2042 * @param image_icon $icon
2043 * @return string HTML fragment
2045 protected function render_image_icon(image_icon
$icon) {
2046 $system = \core\output\icon_system
::instance(\core\output\icon_system
::STANDARD
);
2047 return $system->render_pix_icon($this, $icon);
2051 * Return HTML for a pix_icon.
2053 * Theme developers: DO NOT OVERRIDE! Please override function
2054 * {@link core_renderer::render_pix_icon()} instead.
2056 * @param string $pix short pix name
2057 * @param string $alt mandatory alt attribute
2058 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2059 * @param array $attributes htm lattributes
2060 * @return string HTML fragment
2062 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2063 $icon = new pix_icon($pix, $alt, $component, $attributes);
2064 return $this->render($icon);
2068 * Renders a pix_icon widget and returns the HTML to display it.
2070 * @param pix_icon $icon
2071 * @return string HTML fragment
2073 protected function render_pix_icon(pix_icon
$icon) {
2074 $system = \core\output\icon_system
::instance();
2075 return $system->render_pix_icon($this, $icon);
2079 * Return HTML to display an emoticon icon.
2081 * @param pix_emoticon $emoticon
2082 * @return string HTML fragment
2084 protected function render_pix_emoticon(pix_emoticon
$emoticon) {
2085 $system = \core\output\icon_system
::instance(\core\output\icon_system
::STANDARD
);
2086 return $system->render_pix_icon($this, $emoticon);
2090 * Produces the html that represents this rating in the UI
2092 * @param rating $rating the page object on which this rating will appear
2095 function render_rating(rating
$rating) {
2098 if ($rating->settings
->aggregationmethod
== RATING_AGGREGATE_NONE
) {
2099 return null;//ratings are turned off
2102 $ratingmanager = new rating_manager();
2103 // Initialise the JavaScript so ratings can be done by AJAX.
2104 $ratingmanager->initialise_rating_javascript($this->page
);
2106 $strrate = get_string("rate", "rating");
2107 $ratinghtml = ''; //the string we'll return
2109 // permissions check - can they view the aggregate?
2110 if ($rating->user_can_view_aggregate()) {
2112 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings
->aggregationmethod
);
2113 $aggregatestr = $rating->get_aggregate_string();
2115 $aggregatehtml = html_writer
::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid
, 'class' => 'ratingaggregate')).' ';
2116 if ($rating->count
> 0) {
2117 $countstr = "({$rating->count})";
2121 $aggregatehtml .= html_writer
::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2123 $ratinghtml .= html_writer
::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2124 if ($rating->settings
->permissions
->viewall
&& $rating->settings
->pluginpermissions
->viewall
) {
2126 $nonpopuplink = $rating->get_view_ratings_url();
2127 $popuplink = $rating->get_view_ratings_url(true);
2129 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2130 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2132 $ratinghtml .= $aggregatehtml;
2137 // if the item doesn't belong to the current user, the user has permission to rate
2138 // and we're within the assessable period
2139 if ($rating->user_can_rate()) {
2141 $rateurl = $rating->get_rate_url();
2142 $inputs = $rateurl->params();
2144 //start the rating form
2146 'id' => "postrating{$rating->itemid}",
2147 'class' => 'postratingform',
2149 'action' => $rateurl->out_omit_querystring()
2151 $formstart = html_writer
::start_tag('form', $formattrs);
2152 $formstart .= html_writer
::start_tag('div', array('class' => 'ratingform'));
2154 // add the hidden inputs
2155 foreach ($inputs as $name => $value) {
2156 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2157 $formstart .= html_writer
::empty_tag('input', $attributes);
2160 if (empty($ratinghtml)) {
2161 $ratinghtml .= $strrate.': ';
2163 $ratinghtml = $formstart.$ratinghtml;
2165 $scalearray = array(RATING_UNSET_RATING
=> $strrate.'...') +
$rating->settings
->scale
->scaleitems
;
2166 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid
);
2167 $ratinghtml .= html_writer
::label($rating->rating
, 'menurating'.$rating->itemid
, false, array('class' => 'accesshide'));
2168 $ratinghtml .= html_writer
::select($scalearray, 'rating', $rating->rating
, false, $scaleattrs);
2170 //output submit button
2171 $ratinghtml .= html_writer
::start_tag('span', array('class'=>"ratingsubmit"));
2173 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid
, 'value' => s(get_string('rate', 'rating')));
2174 $ratinghtml .= html_writer
::empty_tag('input', $attributes);
2176 if (!$rating->settings
->scale
->isnumeric
) {
2177 // If a global scale, try to find current course ID from the context
2178 if (empty($rating->settings
->scale
->courseid
) and $coursecontext = $rating->context
->get_course_context(false)) {
2179 $courseid = $coursecontext->instanceid
;
2181 $courseid = $rating->settings
->scale
->courseid
;
2183 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings
->scale
);
2185 $ratinghtml .= html_writer
::end_tag('span');
2186 $ratinghtml .= html_writer
::end_tag('div');
2187 $ratinghtml .= html_writer
::end_tag('form');
2194 * Centered heading with attached help button (same title text)
2195 * and optional icon attached.
2197 * @param string $text A heading text
2198 * @param string $helpidentifier The keyword that defines a help page
2199 * @param string $component component name
2200 * @param string|moodle_url $icon
2201 * @param string $iconalt icon alt text
2202 * @param int $level The level of importance of the heading. Defaulting to 2
2203 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2204 * @return string HTML fragment
2206 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2209 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2213 if ($helpidentifier) {
2214 $help = $this->help_icon($helpidentifier, $component);
2217 return $this->heading($image.$text.$help, $level, $classnames);
2221 * Returns HTML to display a help icon.
2223 * @deprecated since Moodle 2.0
2225 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2226 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2230 * Returns HTML to display a help icon.
2232 * Theme developers: DO NOT OVERRIDE! Please override function
2233 * {@link core_renderer::render_help_icon()} instead.
2235 * @param string $identifier The keyword that defines a help page
2236 * @param string $component component name
2237 * @param string|bool $linktext true means use $title as link text, string means link text value
2238 * @return string HTML fragment
2240 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2241 $icon = new help_icon($identifier, $component);
2242 $icon->diag_strings();
2243 if ($linktext === true) {
2244 $icon->linktext
= get_string($icon->identifier
, $icon->component
);
2245 } else if (!empty($linktext)) {
2246 $icon->linktext
= $linktext;
2248 return $this->render($icon);
2252 * Implementation of user image rendering.
2254 * @param help_icon $helpicon A help icon instance
2255 * @return string HTML fragment
2257 protected function render_help_icon(help_icon
$helpicon) {
2258 return $this->render_from_template('core/help_icon', $helpicon->export_for_template($this));
2262 * Returns HTML to display a scale help icon.
2264 * @param int $courseid
2265 * @param stdClass $scale instance
2266 * @return string HTML fragment
2268 public function help_icon_scale($courseid, stdClass
$scale) {
2271 $title = get_string('helpprefix2', '', $scale->name
) .' ('.get_string('newwindow').')';
2273 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2275 $scaleid = abs($scale->id
);
2277 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2278 $action = new popup_action('click', $link, 'ratingscale');
2280 return html_writer
::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2284 * Creates and returns a spacer image with optional line break.
2286 * @param array $attributes Any HTML attributes to add to the spaced.
2287 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2288 * laxy do it with CSS which is a much better solution.
2289 * @return string HTML fragment
2291 public function spacer(array $attributes = null, $br = false) {
2292 $attributes = (array)$attributes;
2293 if (empty($attributes['width'])) {
2294 $attributes['width'] = 1;
2296 if (empty($attributes['height'])) {
2297 $attributes['height'] = 1;
2299 $attributes['class'] = 'spacer';
2301 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2304 $output .= '<br />';
2311 * Returns HTML to display the specified user's avatar.
2313 * User avatar may be obtained in two ways:
2315 * // Option 1: (shortcut for simple cases, preferred way)
2316 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2317 * $OUTPUT->user_picture($user, array('popup'=>true));
2320 * $userpic = new user_picture($user);
2321 * // Set properties of $userpic
2322 * $userpic->popup = true;
2323 * $OUTPUT->render($userpic);
2326 * Theme developers: DO NOT OVERRIDE! Please override function
2327 * {@link core_renderer::render_user_picture()} instead.
2329 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2330 * If any of these are missing, the database is queried. Avoid this
2331 * if at all possible, particularly for reports. It is very bad for performance.
2332 * @param array $options associative array with user picture options, used only if not a user_picture object,
2334 * - courseid=$this->page->course->id (course id of user profile in link)
2335 * - size=35 (size of image)
2336 * - link=true (make image clickable - the link leads to user profile)
2337 * - popup=false (open in popup)
2338 * - alttext=true (add image alt attribute)
2339 * - class = image class attribute (default 'userpicture')
2340 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2341 * @return string HTML fragment
2343 public function user_picture(stdClass
$user, array $options = null) {
2344 $userpicture = new user_picture($user);
2345 foreach ((array)$options as $key=>$value) {
2346 if (array_key_exists($key, $userpicture)) {
2347 $userpicture->$key = $value;
2350 return $this->render($userpicture);
2354 * Internal implementation of user image rendering.
2356 * @param user_picture $userpicture
2359 protected function render_user_picture(user_picture
$userpicture) {
2362 $user = $userpicture->user
;
2364 if ($userpicture->alttext
) {
2365 if (!empty($user->imagealt
)) {
2366 $alt = $user->imagealt
;
2368 $alt = get_string('pictureof', '', fullname($user));
2374 if (empty($userpicture->size
)) {
2376 } else if ($userpicture->size
=== true or $userpicture->size
== 1) {
2379 $size = $userpicture->size
;
2382 $class = $userpicture->class;
2384 if ($user->picture
== 0) {
2385 $class .= ' defaultuserpic';
2388 $src = $userpicture->get_url($this->page
, $this);
2390 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2391 if (!$userpicture->visibletoscreenreaders
) {
2392 $attributes['role'] = 'presentation';
2395 // get the image html output fisrt
2396 $output = html_writer
::empty_tag('img', $attributes);
2398 // then wrap it in link if needed
2399 if (!$userpicture->link
) {
2403 if (empty($userpicture->courseid
)) {
2404 $courseid = $this->page
->course
->id
;
2406 $courseid = $userpicture->courseid
;
2409 if ($courseid == SITEID
) {
2410 $url = new moodle_url('/user/profile.php', array('id' => $user->id
));
2412 $url = new moodle_url('/user/view.php', array('id' => $user->id
, 'course' => $courseid));
2415 $attributes = array('href'=>$url);
2416 if (!$userpicture->visibletoscreenreaders
) {
2417 $attributes['tabindex'] = '-1';
2418 $attributes['aria-hidden'] = 'true';
2421 if ($userpicture->popup
) {
2422 $id = html_writer
::random_id('userpicture');
2423 $attributes['id'] = $id;
2424 $this->add_action_handler(new popup_action('click', $url), $id);
2427 return html_writer
::tag('a', $output, $attributes);
2431 * Internal implementation of file tree viewer items rendering.
2436 public function htmllize_file_tree($dir) {
2437 if (empty($dir['subdirs']) and empty($dir['files'])) {
2441 foreach ($dir['subdirs'] as $subdir) {
2442 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2444 foreach ($dir['files'] as $file) {
2445 $filename = $file->get_filename();
2446 $result .= '<li><span>'.html_writer
::link($file->fileurl
, $filename).'</span></li>';
2454 * Returns HTML to display the file picker
2457 * $OUTPUT->file_picker($options);
2460 * Theme developers: DO NOT OVERRIDE! Please override function
2461 * {@link core_renderer::render_file_picker()} instead.
2463 * @param array $options associative array with file manager options
2467 * client_id=>uniqid(),
2468 * acepted_types=>'*',
2469 * return_types=>FILE_INTERNAL,
2470 * context=>$PAGE->context
2471 * @return string HTML fragment
2473 public function file_picker($options) {
2474 $fp = new file_picker($options);
2475 return $this->render($fp);
2479 * Internal implementation of file picker rendering.
2481 * @param file_picker $fp
2484 public function render_file_picker(file_picker
$fp) {
2485 global $CFG, $OUTPUT, $USER;
2486 $options = $fp->options
;
2487 $client_id = $options->client_id
;
2488 $strsaved = get_string('filesaved', 'repository');
2489 $straddfile = get_string('openpicker', 'repository');
2490 $strloading = get_string('loading', 'repository');
2491 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2492 $strdroptoupload = get_string('droptoupload', 'moodle');
2493 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2495 $currentfile = $options->currentfile
;
2496 if (empty($currentfile)) {
2499 $currentfile .= ' - ';
2501 if ($options->maxbytes
) {
2502 $size = $options->maxbytes
;
2504 $size = get_max_upload_file_size();
2509 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2511 if ($options->buttonname
) {
2512 $buttonname = ' name="' . $options->buttonname
. '"';
2517 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2520 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2522 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2523 <span> $maxsize </span>
2526 if ($options->env
!= 'url') {
2528 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2529 <div class="filepicker-filename">
2530 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2531 <div class="dndupload-progressbars"></div>
2533 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2542 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2544 * @deprecated since Moodle 3.2
2546 * @param string $cmid the course_module id.
2547 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2548 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2550 public function update_module_button($cmid, $modulename) {
2553 debugging('core_renderer::update_module_button() has been deprecated and should not be used anymore. Activity modules ' .
2554 'should not add the edit module button, the link is already available in the Administration block. Themes can choose ' .
2555 'to display the link in the buttons row consistently for all module types.', DEBUG_DEVELOPER
);
2557 if (has_capability('moodle/course:manageactivities', context_module
::instance($cmid))) {
2558 $modulename = get_string('modulename', $modulename);
2559 $string = get_string('updatethis', '', $modulename);
2560 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2561 return $this->single_button($url, $string);
2568 * Returns HTML to display a "Turn editing on/off" button in a form.
2570 * @param moodle_url $url The URL + params to send through when clicking the button
2571 * @return string HTML the button
2573 public function edit_button(moodle_url
$url) {
2575 $url->param('sesskey', sesskey());
2576 if ($this->page
->user_is_editing()) {
2577 $url->param('edit', 'off');
2578 $editstring = get_string('turneditingoff');
2580 $url->param('edit', 'on');
2581 $editstring = get_string('turneditingon');
2584 return $this->single_button($url, $editstring);
2588 * Returns HTML to display a simple button to close a window
2590 * @param string $text The lang string for the button's label (already output from get_string())
2591 * @return string html fragment
2593 public function close_window_button($text='') {
2595 $text = get_string('closewindow');
2597 $button = new single_button(new moodle_url('#'), $text, 'get');
2598 $button->add_action(new component_action('click', 'close_window'));
2600 return $this->container($this->render($button), 'closewindow');
2604 * Output an error message. By default wraps the error message in <span class="error">.
2605 * If the error message is blank, nothing is output.
2607 * @param string $message the error message.
2608 * @return string the HTML to output.
2610 public function error_text($message) {
2611 if (empty($message)) {
2614 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2615 return html_writer
::tag('span', $message, array('class' => 'error'));
2619 * Do not call this function directly.
2621 * To terminate the current script with a fatal error, call the {@link print_error}
2622 * function, or throw an exception. Doing either of those things will then call this
2623 * function to display the error, before terminating the execution.
2625 * @param string $message The message to output
2626 * @param string $moreinfourl URL where more info can be found about the error
2627 * @param string $link Link for the Continue button
2628 * @param array $backtrace The execution backtrace
2629 * @param string $debuginfo Debugging information
2630 * @return string the HTML to output.
2632 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2638 if ($this->has_started()) {
2639 // we can not always recover properly here, we have problems with output buffering,
2640 // html tables, etc.
2641 $output .= $this->opencontainers
->pop_all_but_last();
2644 // It is really bad if library code throws exception when output buffering is on,
2645 // because the buffered text would be printed before our start of page.
2646 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2647 error_reporting(0); // disable notices from gzip compression, etc.
2648 while (ob_get_level() > 0) {
2649 $buff = ob_get_clean();
2650 if ($buff === false) {
2655 error_reporting($CFG->debug
);
2657 // Output not yet started.
2658 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ?
$_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2659 if (empty($_SERVER['HTTP_RANGE'])) {
2660 @header
($protocol . ' 404 Not Found');
2661 } else if (core_useragent
::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2662 // Coax iOS 10 into sending the session cookie.
2663 @header
($protocol . ' 403 Forbidden');
2665 // Must stop byteserving attempts somehow,
2666 // this is weird but Chrome PDF viewer can be stopped only with 407!
2667 @header
($protocol . ' 407 Proxy Authentication Required');
2670 $this->page
->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2671 $this->page
->set_url('/'); // no url
2672 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2673 $this->page
->set_title(get_string('error'));
2674 $this->page
->set_heading($this->page
->course
->fullname
);
2675 $output .= $this->header();
2678 $message = '<p class="errormessage">' . $message . '</p>'.
2679 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2680 get_string('moreinformation') . '</a></p>';
2681 if (empty($CFG->rolesactive
)) {
2682 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2683 //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.
2685 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
2687 if ($CFG->debugdeveloper
) {
2688 if (!empty($debuginfo)) {
2689 $debuginfo = s($debuginfo); // removes all nasty JS
2690 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2691 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2693 if (!empty($backtrace)) {
2694 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2696 if ($obbuffer !== '' ) {
2697 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2701 if (empty($CFG->rolesactive
)) {
2702 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2703 } else if (!empty($link)) {
2704 $output .= $this->continue_button($link);
2707 $output .= $this->footer();
2709 // Padding to encourage IE to display our error page, rather than its own.
2710 $output .= str_repeat(' ', 512);
2716 * Output a notification (that is, a status message about something that has just happened).
2718 * Note: \core\notification::add() may be more suitable for your usage.
2720 * @param string $message The message to print out.
2721 * @param string $type The type of notification. See constants on \core\output\notification.
2722 * @return string the HTML to output.
2724 public function notification($message, $type = null) {
2727 'success' => \core\output\notification
::NOTIFY_SUCCESS
,
2728 'info' => \core\output\notification
::NOTIFY_INFO
,
2729 'warning' => \core\output\notification
::NOTIFY_WARNING
,
2730 'error' => \core\output\notification
::NOTIFY_ERROR
,
2732 // Legacy types mapped to current types.
2733 'notifyproblem' => \core\output\notification
::NOTIFY_ERROR
,
2734 'notifytiny' => \core\output\notification
::NOTIFY_ERROR
,
2735 'notifyerror' => \core\output\notification
::NOTIFY_ERROR
,
2736 'notifysuccess' => \core\output\notification
::NOTIFY_SUCCESS
,
2737 'notifymessage' => \core\output\notification
::NOTIFY_INFO
,
2738 'notifyredirect' => \core\output\notification
::NOTIFY_INFO
,
2739 'redirectmessage' => \core\output\notification
::NOTIFY_INFO
,
2745 if (strpos($type, ' ') === false) {
2746 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2747 if (isset($typemappings[$type])) {
2748 $type = $typemappings[$type];
2750 // The value provided did not match a known type. It must be an extra class.
2751 $extraclasses = [$type];
2754 // Identify what type of notification this is.
2755 $classarray = explode(' ', self
::prepare_classes($type));
2757 // Separate out the type of notification from the extra classes.
2758 foreach ($classarray as $class) {
2759 if (isset($typemappings[$class])) {
2760 $type = $typemappings[$class];
2762 $extraclasses[] = $class;
2768 $notification = new \core\output\notification
($message, $type);
2769 if (count($extraclasses)) {
2770 $notification->set_extra_classes($extraclasses);
2773 // Return the rendered template.
2774 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2778 * Output a notification at a particular level - in this case, NOTIFY_PROBLEM.
2780 * @param string $message the message to print out
2781 * @return string HTML fragment.
2782 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2783 * @todo MDL-53113 This will be removed in Moodle 3.5.
2784 * @see \core\output\notification
2786 public function notify_problem($message) {
2787 debugging(__FUNCTION__
. ' is deprecated.' .
2788 'Please use \core\notification::add, or \core\output\notification as required',
2790 $n = new \core\output\notification
($message, \core\output\notification
::NOTIFY_ERROR
);
2791 return $this->render($n);
2795 * Output a notification at a particular level - in this case, NOTIFY_SUCCESS.
2797 * @param string $message the message to print out
2798 * @return string HTML fragment.
2799 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2800 * @todo MDL-53113 This will be removed in Moodle 3.5.
2801 * @see \core\output\notification
2803 public function notify_success($message) {
2804 debugging(__FUNCTION__
. ' is deprecated.' .
2805 'Please use \core\notification::add, or \core\output\notification as required',
2807 $n = new \core\output\notification
($message, \core\output\notification
::NOTIFY_SUCCESS
);
2808 return $this->render($n);
2812 * Output a notification at a particular level - in this case, NOTIFY_MESSAGE.
2814 * @param string $message the message to print out
2815 * @return string HTML fragment.
2816 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2817 * @todo MDL-53113 This will be removed in Moodle 3.5.
2818 * @see \core\output\notification
2820 public function notify_message($message) {
2821 debugging(__FUNCTION__
. ' is deprecated.' .
2822 'Please use \core\notification::add, or \core\output\notification as required',
2824 $n = new \core\output\notification
($message, \core\output\notification
::NOTIFY_INFO
);
2825 return $this->render($n);
2829 * Output a notification at a particular level - in this case, NOTIFY_REDIRECT.
2831 * @param string $message the message to print out
2832 * @return string HTML fragment.
2833 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2834 * @todo MDL-53113 This will be removed in Moodle 3.5.
2835 * @see \core\output\notification
2837 public function notify_redirect($message) {
2838 debugging(__FUNCTION__
. ' is deprecated.' .
2839 'Please use \core\notification::add, or \core\output\notification as required',
2841 $n = new \core\output\notification
($message, \core\output\notification
::NOTIFY_INFO
);
2842 return $this->render($n);
2846 * Render a notification (that is, a status message about something that has
2849 * @param \core\output\notification $notification the notification to print out
2850 * @return string the HTML to output.
2852 protected function render_notification(\core\output\notification
$notification) {
2853 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
2857 * Returns HTML to display a continue button that goes to a particular URL.
2859 * @param string|moodle_url $url The url the button goes to.
2860 * @return string the HTML to output.
2862 public function continue_button($url) {
2863 if (!($url instanceof moodle_url
)) {
2864 $url = new moodle_url($url);
2866 $button = new single_button($url, get_string('continue'), 'get', true);
2867 $button->class = 'continuebutton';
2869 return $this->render($button);
2873 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2875 * Theme developers: DO NOT OVERRIDE! Please override function
2876 * {@link core_renderer::render_paging_bar()} instead.
2878 * @param int $totalcount The total number of entries available to be paged through
2879 * @param int $page The page you are currently viewing
2880 * @param int $perpage The number of entries that should be shown per page
2881 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2882 * @param string $pagevar name of page parameter that holds the page number
2883 * @return string the HTML to output.
2885 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2886 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2887 return $this->render($pb);
2891 * Internal implementation of paging bar rendering.
2893 * @param paging_bar $pagingbar
2896 protected function render_paging_bar(paging_bar
$pagingbar) {
2898 $pagingbar = clone($pagingbar);
2899 $pagingbar->prepare($this, $this->page
, $this->target
);
2901 if ($pagingbar->totalcount
> $pagingbar->perpage
) {
2902 $output .= get_string('page') . ':';
2904 if (!empty($pagingbar->previouslink
)) {
2905 $output .= ' (' . $pagingbar->previouslink
. ') ';
2908 if (!empty($pagingbar->firstlink
)) {
2909 $output .= ' ' . $pagingbar->firstlink
. ' ...';
2912 foreach ($pagingbar->pagelinks
as $link) {
2913 $output .= " $link";
2916 if (!empty($pagingbar->lastlink
)) {
2917 $output .= ' ... ' . $pagingbar->lastlink
. ' ';
2920 if (!empty($pagingbar->nextlink
)) {
2921 $output .= ' (' . $pagingbar->nextlink
. ')';
2925 return html_writer
::tag('div', $output, array('class' => 'paging'));
2929 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
2931 * @param string $current the currently selected letter.
2932 * @param string $class class name to add to this initial bar.
2933 * @param string $title the name to put in front of this initial bar.
2934 * @param string $urlvar URL parameter name for this initial.
2935 * @param string $url URL object.
2936 * @param array $alpha of letters in the alphabet.
2937 * @return string the HTML to output.
2939 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
2940 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
2941 return $this->render($ib);
2945 * Internal implementation of initials bar rendering.
2947 * @param initials_bar $initialsbar
2950 protected function render_initials_bar(initials_bar
$initialsbar) {
2951 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
2955 * Output the place a skip link goes to.
2957 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2958 * @return string the HTML to output.
2960 public function skip_link_target($id = null) {
2961 return html_writer
::span('', '', array('id' => $id));
2967 * @param string $text The text of the heading
2968 * @param int $level The level of importance of the heading. Defaulting to 2
2969 * @param string $classes A space-separated list of CSS classes. Defaulting to null
2970 * @param string $id An optional ID
2971 * @return string the HTML to output.
2973 public function heading($text, $level = 2, $classes = null, $id = null) {
2974 $level = (integer) $level;
2975 if ($level < 1 or $level > 6) {
2976 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2978 return html_writer
::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base
::prepare_classes($classes)));
2984 * @param string $contents The contents of the box
2985 * @param string $classes A space-separated list of CSS classes
2986 * @param string $id An optional ID
2987 * @param array $attributes An array of other attributes to give the box.
2988 * @return string the HTML to output.
2990 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
2991 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
2995 * Outputs the opening section of a box.
2997 * @param string $classes A space-separated list of CSS classes
2998 * @param string $id An optional ID
2999 * @param array $attributes An array of other attributes to give the box.
3000 * @return string the HTML to output.
3002 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3003 $this->opencontainers
->push('box', html_writer
::end_tag('div'));
3004 $attributes['id'] = $id;
3005 $attributes['class'] = 'box ' . renderer_base
::prepare_classes($classes);
3006 return html_writer
::start_tag('div', $attributes);
3010 * Outputs the closing section of a box.
3012 * @return string the HTML to output.
3014 public function box_end() {
3015 return $this->opencontainers
->pop('box');
3019 * Outputs a container.
3021 * @param string $contents The contents of the box
3022 * @param string $classes A space-separated list of CSS classes
3023 * @param string $id An optional ID
3024 * @return string the HTML to output.
3026 public function container($contents, $classes = null, $id = null) {
3027 return $this->container_start($classes, $id) . $contents . $this->container_end();
3031 * Outputs the opening section of a container.
3033 * @param string $classes A space-separated list of CSS classes
3034 * @param string $id An optional ID
3035 * @return string the HTML to output.
3037 public function container_start($classes = null, $id = null) {
3038 $this->opencontainers
->push('container', html_writer
::end_tag('div'));
3039 return html_writer
::start_tag('div', array('id' => $id,
3040 'class' => renderer_base
::prepare_classes($classes)));
3044 * Outputs the closing section of a container.
3046 * @return string the HTML to output.
3048 public function container_end() {
3049 return $this->opencontainers
->pop('container');
3053 * Make nested HTML lists out of the items
3055 * The resulting list will look something like this:
3059 * <<li>><div class='tree_item parent'>(item contents)</div>
3061 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3067 * @param array $items
3068 * @param array $attrs html attributes passed to the top ofs the list
3069 * @return string HTML
3071 public function tree_block_contents($items, $attrs = array()) {
3072 // exit if empty, we don't want an empty ul element
3073 if (empty($items)) {
3076 // array of nested li elements
3078 foreach ($items as $item) {
3079 // this applies to the li item which contains all child lists too
3080 $content = $item->content($this);
3081 $liclasses = array($item->get_css_type());
3082 if (!$item->forceopen ||
(!$item->forceopen
&& $item->collapse
) ||
($item->children
->count()==0 && $item->nodetype
==navigation_node
::NODETYPE_BRANCH
)) {
3083 $liclasses[] = 'collapsed';
3085 if ($item->isactive
=== true) {
3086 $liclasses[] = 'current_branch';
3088 $liattr = array('class'=>join(' ',$liclasses));
3089 // class attribute on the div item which only contains the item content
3090 $divclasses = array('tree_item');
3091 if ($item->children
->count()>0 ||
$item->nodetype
==navigation_node
::NODETYPE_BRANCH
) {
3092 $divclasses[] = 'branch';
3094 $divclasses[] = 'leaf';
3096 if (!empty($item->classes
) && count($item->classes
)>0) {
3097 $divclasses[] = join(' ', $item->classes
);
3099 $divattr = array('class'=>join(' ', $divclasses));
3100 if (!empty($item->id
)) {
3101 $divattr['id'] = $item->id
;
3103 $content = html_writer
::tag('p', $content, $divattr) . $this->tree_block_contents($item->children
);
3104 if (!empty($item->preceedwithhr
) && $item->preceedwithhr
===true) {
3105 $content = html_writer
::empty_tag('hr') . $content;
3107 $content = html_writer
::tag('li', $content, $liattr);
3110 return html_writer
::tag('ul', implode("\n", $lis), $attrs);
3114 * Returns a search box.
3116 * @param string $id The search box wrapper div id, defaults to an autogenerated one.
3117 * @return string HTML with the search form hidden by default.
3119 public function search_box($id = false) {
3122 // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3123 // result in an extra included file for each site, even the ones where global search
3125 if (empty($CFG->enableglobalsearch
) ||
!has_capability('moodle/search:query', context_system
::instance())) {
3132 // Needs to be cleaned, we use it for the input id.
3133 $id = clean_param($id, PARAM_ALPHANUMEXT
);
3136 // JS to animate the form.
3137 $this->page
->requires
->js_call_amd('core/search-input', 'init', array($id));
3139 $searchicon = html_writer
::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
3140 array('role' => 'button', 'tabindex' => 0));
3141 $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot
. '/search/index.php');
3142 $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
3143 'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id);
3145 $contents = html_writer
::tag('label', get_string('enteryoursearchquery', 'search'),
3146 array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer
::tag('input', '', $inputattrs);
3147 $searchinput = html_writer
::tag('form', $contents, $formattrs);
3149 return html_writer
::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper nav-link', 'id' => $id));
3153 * Allow plugins to provide some content to be rendered in the navbar.
3154 * The plugin must define a PLUGIN_render_navbar_output function that returns
3155 * the HTML they wish to add to the navbar.
3157 * @return string HTML for the navbar
3159 public function navbar_plugin_output() {
3162 if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3163 foreach ($pluginsfunction as $plugintype => $plugins) {
3164 foreach ($plugins as $pluginfunction) {
3165 $output .= $pluginfunction($this);
3174 * Construct a user menu, returning HTML that can be echoed out by a
3177 * @param stdClass $user A user object, usually $USER.
3178 * @param bool $withlinks true if a dropdown should be built.
3179 * @return string HTML fragment.
3181 public function user_menu($user = null, $withlinks = null) {
3183 require_once($CFG->dirroot
. '/user/lib.php');
3185 if (is_null($user)) {
3189 // Note: this behaviour is intended to match that of core_renderer::login_info,
3190 // but should not be considered to be good practice; layout options are
3191 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3192 if (is_null($withlinks)) {
3193 $withlinks = empty($this->page
->layout_options
['nologinlinks']);
3196 // Add a class for when $withlinks is false.
3197 $usermenuclasses = 'usermenu';
3199 $usermenuclasses .= ' withoutlinks';
3204 // If during initial install, return the empty return string.
3205 if (during_initial_install()) {
3209 $loginpage = $this->is_login_page();
3210 $loginurl = get_login_url();
3211 // If not logged in, show the typical not-logged-in string.
3212 if (!isloggedin()) {
3213 $returnstr = get_string('loggedinnot', 'moodle');
3215 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3217 return html_writer
::div(
3227 // If logged in as a guest user, show a string to that effect.
3228 if (isguestuser()) {
3229 $returnstr = get_string('loggedinasguest');
3230 if (!$loginpage && $withlinks) {
3231 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3234 return html_writer
::div(
3243 // Get some navigation opts.
3244 $opts = user_get_user_navigation_info($user, $this->page
);
3246 $avatarclasses = "avatars";
3247 $avatarcontents = html_writer
::span($opts->metadata
['useravatar'], 'avatar current');
3248 $usertextcontents = $opts->metadata
['userfullname'];
3251 if (!empty($opts->metadata
['asotheruser'])) {
3252 $avatarcontents .= html_writer
::span(
3253 $opts->metadata
['realuseravatar'],
3256 $usertextcontents = $opts->metadata
['realuserfullname'];
3257 $usertextcontents .= html_writer
::tag(
3263 $opts->metadata
['userfullname'],
3267 array('class' => 'meta viewingas')
3272 if (!empty($opts->metadata
['asotherrole'])) {
3273 $role = core_text
::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata
['rolename'])));
3274 $usertextcontents .= html_writer
::span(
3275 $opts->metadata
['rolename'],
3276 'meta role role-' . $role
3280 // User login failures.
3281 if (!empty($opts->metadata
['userloginfail'])) {
3282 $usertextcontents .= html_writer
::span(
3283 $opts->metadata
['userloginfail'],
3284 'meta loginfailures'
3289 if (!empty($opts->metadata
['asmnetuser'])) {
3290 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata
['mnetidprovidername'])));
3291 $usertextcontents .= html_writer
::span(
3292 $opts->metadata
['mnetidprovidername'],
3293 'meta mnet mnet-' . $mnet
3297 $returnstr .= html_writer
::span(
3298 html_writer
::span($usertextcontents, 'usertext') .
3299 html_writer
::span($avatarcontents, $avatarclasses),
3303 // Create a divider (well, a filler).
3304 $divider = new action_menu_filler();
3305 $divider->primary
= false;
3307 $am = new action_menu();
3308 $am->set_menu_trigger(
3311 $am->set_alignment(action_menu
::TR
, action_menu
::BR
);
3312 $am->set_nowrap_on_items();
3314 $navitemcount = count($opts->navitems
);
3316 foreach ($opts->navitems
as $key => $value) {
3318 switch ($value->itemtype
) {
3320 // If the nav item is a divider, add one and skip link processing.
3325 // Silently skip invalid entries (should we post a notification?).
3329 // Process this as a link item.
3331 if (isset($value->pix
) && !empty($value->pix
)) {
3332 $pix = new pix_icon($value->pix
, $value->title
, null, array('class' => 'iconsmall'));
3333 } else if (isset($value->imgsrc
) && !empty($value->imgsrc
)) {
3334 $value->title
= html_writer
::img(
3337 array('class' => 'iconsmall')
3341 $al = new action_menu_link_secondary(
3345 array('class' => 'icon')
3347 if (!empty($value->titleidentifier
)) {
3348 $al->attributes
['data-title'] = $value->titleidentifier
;
3356 // Add dividers after the first item and before the last item.
3357 if ($idx == 1 ||
$idx == $navitemcount - 1) {
3363 return html_writer
::div(
3370 * Return the navbar content so that it can be echoed out by the layout
3372 * @return string XHTML navbar
3374 public function navbar() {
3375 $items = $this->page
->navbar
->get_items();
3376 $itemcount = count($items);
3377 if ($itemcount === 0) {
3381 $htmlblocks = array();
3382 // Iterate the navarray and display each node
3383 $separator = get_separator();
3384 for ($i=0;$i < $itemcount;$i++
) {
3386 $item->hideicon
= true;
3388 $content = html_writer
::tag('li', $this->render($item));
3390 $content = html_writer
::tag('li', $separator.$this->render($item));
3392 $htmlblocks[] = $content;
3395 //accessibility: heading for navbar list (MDL-20446)
3396 $navbarcontent = html_writer
::tag('span', get_string('pagepath'),
3397 array('class' => 'accesshide', 'id' => 'navbar-label'));
3398 $navbarcontent .= html_writer
::tag('nav',
3399 html_writer
::tag('ul', join('', $htmlblocks)),
3400 array('aria-labelledby' => 'navbar-label'));
3402 return $navbarcontent;
3406 * Renders a breadcrumb navigation node object.
3408 * @param breadcrumb_navigation_node $item The navigation node to render.
3409 * @return string HTML fragment
3411 protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node
$item) {
3413 if ($item->action
instanceof moodle_url
) {
3414 $content = $item->get_content();
3415 $title = $item->get_title();
3416 $attributes = array();
3417 $attributes['itemprop'] = 'url';
3418 if ($title !== '') {
3419 $attributes['title'] = $title;
3421 if ($item->hidden
) {
3422 $attributes['class'] = 'dimmed_text';
3424 $content = html_writer
::tag('span', $content, array('itemprop' => 'title'));
3425 $content = html_writer
::link($item->action
, $content, $attributes);
3427 $attributes = array();
3428 $attributes['itemscope'] = '';
3429 $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3430 $content = html_writer
::tag('span', $content, $attributes);
3433 $content = $this->render_navigation_node($item);
3439 * Renders a navigation node object.
3441 * @param navigation_node $item The navigation node to render.
3442 * @return string HTML fragment
3444 protected function render_navigation_node(navigation_node
$item) {
3445 $content = $item->get_content();
3446 $title = $item->get_title();
3447 if ($item->icon
instanceof renderable
&& !$item->hideicon
) {
3448 $icon = $this->render($item->icon
);
3449 $content = $icon.$content; // use CSS for spacing of icons
3451 if ($item->helpbutton
!== null) {
3452 $content = trim($item->helpbutton
).html_writer
::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3454 if ($content === '') {
3457 if ($item->action
instanceof action_link
) {
3458 $link = $item->action
;
3459 if ($item->hidden
) {
3460 $link->add_class('dimmed');
3462 if (!empty($content)) {
3463 // Providing there is content we will use that for the link content.
3464 $link->text
= $content;
3466 $content = $this->render($link);
3467 } else if ($item->action
instanceof moodle_url
) {
3468 $attributes = array();
3469 if ($title !== '') {
3470 $attributes['title'] = $title;
3472 if ($item->hidden
) {
3473 $attributes['class'] = 'dimmed_text';
3475 $content = html_writer
::link($item->action
, $content, $attributes);
3477 } else if (is_string($item->action
) ||
empty($item->action
)) {
3478 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3479 if ($title !== '') {
3480 $attributes['title'] = $title;
3482 if ($item->hidden
) {
3483 $attributes['class'] = 'dimmed_text';
3485 $content = html_writer
::tag('span', $content, $attributes);
3491 * Accessibility: Right arrow-like character is
3492 * used in the breadcrumb trail, course navigation menu
3493 * (previous/next activity), calendar, and search forum block.
3494 * If the theme does not set characters, appropriate defaults
3495 * are set automatically. Please DO NOT
3496 * use < > » - these are confusing for blind users.
3500 public function rarrow() {
3501 return $this->page
->theme
->rarrow
;
3505 * Accessibility: Left arrow-like character is
3506 * used in the breadcrumb trail, course navigation menu
3507 * (previous/next activity), calendar, and search forum block.
3508 * If the theme does not set characters, appropriate defaults
3509 * are set automatically. Please DO NOT
3510 * use < > » - these are confusing for blind users.
3514 public function larrow() {
3515 return $this->page
->theme
->larrow
;
3519 * Accessibility: Up arrow-like character is used in
3520 * the book heirarchical navigation.
3521 * If the theme does not set characters, appropriate defaults
3522 * are set automatically. Please DO NOT
3523 * use ^ - this is confusing for blind users.
3527 public function uarrow() {
3528 return $this->page
->theme
->uarrow
;
3532 * Accessibility: Down arrow-like character.
3533 * If the theme does not set characters, appropriate defaults
3534 * are set automatically.
3538 public function darrow() {
3539 return $this->page
->theme
->darrow
;
3543 * Returns the custom menu if one has been set
3545 * A custom menu can be configured by browsing to
3546 * Settings: Administration > Appearance > Themes > Theme settings
3547 * and then configuring the custommenu config setting as described.
3549 * Theme developers: DO NOT OVERRIDE! Please override function
3550 * {@link core_renderer::render_custom_menu()} instead.
3552 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3555 public function custom_menu($custommenuitems = '') {
3557 if (empty($custommenuitems) && !empty($CFG->custommenuitems
)) {
3558 $custommenuitems = $CFG->custommenuitems
;
3560 if (empty($custommenuitems)) {
3563 $custommenu = new custom_menu($custommenuitems, current_language());
3564 return $this->render($custommenu);
3568 * Renders a custom menu object (located in outputcomponents.php)
3570 * The custom menu this method produces makes use of the YUI3 menunav widget
3571 * and requires very specific html elements and classes.
3573 * @staticvar int $menucount
3574 * @param custom_menu $menu
3577 protected function render_custom_menu(custom_menu
$menu) {
3578 static $menucount = 0;
3579 // If the menu has no children return an empty string
3580 if (!$menu->has_children()) {
3583 // Increment the menu count. This is used for ID's that get worked with
3584 // in JavaScript as is essential
3586 // Initialise this custom menu (the custom menu object is contained in javascript-static
3587 $jscode = js_writer
::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
3588 $jscode = "(function(){{$jscode}})";
3589 $this->page
->requires
->yui_module('node-menunav', $jscode);
3590 // Build the root nodes as required by YUI
3591 $content = html_writer
::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
3592 $content .= html_writer
::start_tag('div', array('class'=>'yui3-menu-content'));
3593 $content .= html_writer
::start_tag('ul');
3594 // Render each child
3595 foreach ($menu->get_children() as $item) {
3596 $content .= $this->render_custom_menu_item($item);
3598 // Close the open tags
3599 $content .= html_writer
::end_tag('ul');
3600 $content .= html_writer
::end_tag('div');
3601 $content .= html_writer
::end_tag('div');
3602 // Return the custom menu
3607 * Renders a custom menu node as part of a submenu
3609 * The custom menu this method produces makes use of the YUI3 menunav widget
3610 * and requires very specific html elements and classes.
3612 * @see core:renderer::render_custom_menu()
3614 * @staticvar int $submenucount
3615 * @param custom_menu_item $menunode
3618 protected function render_custom_menu_item(custom_menu_item
$menunode) {
3619 // Required to ensure we get unique trackable id's
3620 static $submenucount = 0;
3621 if ($menunode->has_children()) {
3622 // If the child has menus render it as a sub menu
3624 $content = html_writer
::start_tag('li');
3625 if ($menunode->get_url() !== null) {
3626 $url = $menunode->get_url();
3628 $url = '#cm_submenu_'.$submenucount;
3630 $content .= html_writer
::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3631 $content .= html_writer
::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3632 $content .= html_writer
::start_tag('div', array('class'=>'yui3-menu-content'));
3633 $content .= html_writer
::start_tag('ul');
3634 foreach ($menunode->get_children() as $menunode) {
3635 $content .= $this->render_custom_menu_item($menunode);
3637 $content .= html_writer
::end_tag('ul');
3638 $content .= html_writer
::end_tag('div');
3639 $content .= html_writer
::end_tag('div');
3640 $content .= html_writer
::end_tag('li');
3642 // The node doesn't have children so produce a final menuitem.
3643 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3645 if (preg_match("/^#+$/", $menunode->get_text())) {
3647 // This is a divider.
3648 $content = html_writer
::start_tag('li', array('class' => 'yui3-menuitem divider'));
3650 $content = html_writer
::start_tag(
3653 'class' => 'yui3-menuitem'
3656 if ($menunode->get_url() !== null) {
3657 $url = $menunode->get_url();
3661 $content .= html_writer
::link(
3663 $menunode->get_text(),
3664 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3667 $content .= html_writer
::end_tag('li');
3669 // Return the sub menu
3674 * Renders theme links for switching between default and other themes.
3678 protected function theme_switch_links() {
3680 $actualdevice = core_useragent
::get_device_type();
3681 $currentdevice = $this->page
->devicetypeinuse
;
3682 $switched = ($actualdevice != $currentdevice);
3684 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3685 // The user is using the a default device and hasn't switched so don't shown the switch
3691 $linktext = get_string('switchdevicerecommended');
3692 $devicetype = $actualdevice;
3694 $linktext = get_string('switchdevicedefault');
3695 $devicetype = 'default';
3697 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page
->url
, 'device' => $devicetype, 'sesskey' => sesskey()));
3699 $content = html_writer
::start_tag('div', array('id' => 'theme_switch_link'));
3700 $content .= html_writer
::link($linkurl, $linktext, array('rel' => 'nofollow'));
3701 $content .= html_writer
::end_tag('div');
3709 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3711 * Theme developers: In order to change how tabs are displayed please override functions
3712 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3714 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3715 * @param string|null $selected which tab to mark as selected, all parent tabs will
3716 * automatically be marked as activated
3717 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3718 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3721 public final function tabtree($tabs, $selected = null, $inactive = null) {
3722 return $this->render(new tabtree($tabs, $selected, $inactive));
3728 * @param tabtree $tabtree
3731 protected function render_tabtree(tabtree
$tabtree) {
3732 if (empty($tabtree->subtree
)) {
3736 $str .= html_writer
::start_tag('div', array('class' => 'tabtree'));
3737 $str .= $this->render_tabobject($tabtree);
3738 $str .= html_writer
::end_tag('div').
3739 html_writer
::tag('div', ' ', array('class' => 'clearer'));
3744 * Renders tabobject (part of tabtree)
3746 * This function is called from {@link core_renderer::render_tabtree()}
3747 * and also it calls itself when printing the $tabobject subtree recursively.
3749 * Property $tabobject->level indicates the number of row of tabs.
3751 * @param tabobject $tabobject
3752 * @return string HTML fragment
3754 protected function render_tabobject(tabobject
$tabobject) {
3757 // Print name of the current tab.
3758 if ($tabobject instanceof tabtree
) {
3759 // No name for tabtree root.
3760 } else if ($tabobject->inactive ||
$tabobject->activated ||
($tabobject->selected
&& !$tabobject->linkedwhenselected
)) {
3761 // Tab name without a link. The <a> tag is used for styling.
3762 $str .= html_writer
::tag('a', html_writer
::span($tabobject->text
), array('class' => 'nolink moodle-has-zindex'));
3764 // Tab name with a link.
3765 if (!($tabobject->link
instanceof moodle_url
)) {
3766 // backward compartibility when link was passed as quoted string
3767 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3769 $str .= html_writer
::link($tabobject->link
, html_writer
::span($tabobject->text
), array('title' => $tabobject->title
));
3773 if (empty($tabobject->subtree
)) {
3774 if ($tabobject->selected
) {
3775 $str .= html_writer
::tag('div', ' ', array('class' => 'tabrow'. ($tabobject->level +
1). ' empty'));
3781 if ($tabobject->level
== 0 ||
$tabobject->selected ||
$tabobject->activated
) {
3782 $str .= html_writer
::start_tag('ul', array('class' => 'tabrow'. $tabobject->level
));
3784 foreach ($tabobject->subtree
as $tab) {
3787 $liclass .= ' first';
3789 if ($cnt == count($tabobject->subtree
) - 1) {
3790 $liclass .= ' last';
3792 if ((empty($tab->subtree
)) && (!empty($tab->selected
))) {
3793 $liclass .= ' onerow';
3796 if ($tab->selected
) {
3797 $liclass .= ' here selected';
3798 } else if ($tab->activated
) {
3799 $liclass .= ' here active';
3802 // This will recursively call function render_tabobject() for each item in subtree.
3803 $str .= html_writer
::tag('li', $this->render($tab), array('class' => trim($liclass)));
3806 $str .= html_writer
::end_tag('ul');
3813 * Get the HTML for blocks in the given region.
3815 * @since Moodle 2.5.1 2.6
3816 * @param string $region The region to get HTML for.
3817 * @return string HTML.
3819 public function blocks($region, $classes = array(), $tag = 'aside') {
3820 $displayregion = $this->page
->apply_theme_region_manipulations($region);
3821 $classes = (array)$classes;
3822 $classes[] = 'block-region';
3823 $attributes = array(
3824 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3825 'class' => join(' ', $classes),
3826 'data-blockregion' => $displayregion,
3827 'data-droptarget' => '1'
3829 if ($this->page
->blocks
->region_has_content($displayregion, $this)) {
3830 $content = $this->blocks_for_region($displayregion);
3834 return html_writer
::tag($tag, $content, $attributes);
3838 * Renders a custom block region.
3840 * Use this method if you want to add an additional block region to the content of the page.
3841 * Please note this should only be used in special situations.
3842 * We want to leave the theme is control where ever possible!
3844 * This method must use the same method that the theme uses within its layout file.
3845 * As such it asks the theme what method it is using.
3846 * It can be one of two values, blocks or blocks_for_region (deprecated).
3848 * @param string $regionname The name of the custom region to add.
3849 * @return string HTML for the block region.
3851 public function custom_block_region($regionname) {
3852 if ($this->page
->theme
->get_block_render_method() === 'blocks') {
3853 return $this->blocks($regionname);
3855 return $this->blocks_for_region($regionname);
3860 * Returns the CSS classes to apply to the body tag.
3862 * @since Moodle 2.5.1 2.6
3863 * @param array $additionalclasses Any additional classes to apply.
3866 public function body_css_classes(array $additionalclasses = array()) {
3867 // Add a class for each block region on the page.
3868 // We use the block manager here because the theme object makes get_string calls.
3869 $usedregions = array();
3870 foreach ($this->page
->blocks
->get_regions() as $region) {
3871 $additionalclasses[] = 'has-region-'.$region;
3872 if ($this->page
->blocks
->region_has_content($region, $this)) {
3873 $additionalclasses[] = 'used-region-'.$region;
3874 $usedregions[] = $region;
3876 $additionalclasses[] = 'empty-region-'.$region;
3878 if ($this->page
->blocks
->region_completely_docked($region, $this)) {
3879 $additionalclasses[] = 'docked-region-'.$region;
3882 if (!$usedregions) {
3883 // No regions means there is only content, add 'content-only' class.
3884 $additionalclasses[] = 'content-only';
3885 } else if (count($usedregions) === 1) {
3886 // Add the -only class for the only used region.
3887 $region = array_shift($usedregions);
3888 $additionalclasses[] = $region . '-only';
3890 foreach ($this->page
->layout_options
as $option => $value) {
3892 $additionalclasses[] = 'layout-option-'.$option;
3895 $css = $this->page
->bodyclasses
.' '. join(' ', $additionalclasses);
3900 * The ID attribute to apply to the body tag.
3902 * @since Moodle 2.5.1 2.6
3905 public function body_id() {
3906 return $this->page
->bodyid
;
3910 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
3912 * @since Moodle 2.5.1 2.6
3913 * @param string|array $additionalclasses Any additional classes to give the body tag,
3916 public function body_attributes($additionalclasses = array()) {
3917 if (!is_array($additionalclasses)) {
3918 $additionalclasses = explode(' ', $additionalclasses);
3920 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
3924 * Gets HTML for the page heading.
3926 * @since Moodle 2.5.1 2.6
3927 * @param string $tag The tag to encase the heading in. h1 by default.
3928 * @return string HTML.
3930 public function page_heading($tag = 'h1') {
3931 return html_writer
::tag($tag, $this->page
->heading
);
3935 * Gets the HTML for the page heading button.
3937 * @since Moodle 2.5.1 2.6
3938 * @return string HTML.
3940 public function page_heading_button() {
3941 return $this->page
->button
;
3945 * Returns the Moodle docs link to use for this page.
3947 * @since Moodle 2.5.1 2.6
3948 * @param string $text
3951 public function page_doc_link($text = null) {
3952 if ($text === null) {
3953 $text = get_string('moodledocslink');
3955 $path = page_get_doc_link_path($this->page
);
3959 return $this->doc_link($path, $text);
3963 * Returns the page heading menu.
3965 * @since Moodle 2.5.1 2.6
3966 * @return string HTML.
3968 public function page_heading_menu() {
3969 return $this->page
->headingmenu
;
3973 * Returns the title to use on the page.
3975 * @since Moodle 2.5.1 2.6
3978 public function page_title() {
3979 return $this->page
->title
;
3983 * Returns the URL for the favicon.
3985 * @since Moodle 2.5.1 2.6
3986 * @return string The favicon URL
3988 public function favicon() {
3989 return $this->image_url('favicon', 'theme');
3993 * Renders preferences groups.
3995 * @param preferences_groups $renderable The renderable
3996 * @return string The output.
3998 public function render_preferences_groups(preferences_groups
$renderable) {
4000 $html .= html_writer
::start_div('row-fluid');
4001 $html .= html_writer
::start_tag('div', array('class' => 'span12 preferences-groups'));
4004 foreach ($renderable->groups
as $group) {
4005 if ($i == 0 ||
$i %
3 == 0) {
4007 $html .= html_writer
::end_tag('div');
4009 $html .= html_writer
::start_tag('div', array('class' => 'row-fluid'));
4012 $html .= $this->render($group);
4016 $html .= html_writer
::end_tag('div');
4018 $html .= html_writer
::end_tag('ul');
4019 $html .= html_writer
::end_tag('div');
4020 $html .= html_writer
::end_div();
4025 * Renders preferences group.
4027 * @param preferences_group $renderable The renderable
4028 * @return string The output.
4030 public function render_preferences_group(preferences_group
$renderable) {
4032 $html .= html_writer
::start_tag('div', array('class' => 'span4 preferences-group'));
4033 $html .= $this->heading($renderable->title
, 3);
4034 $html .= html_writer
::start_tag('ul');
4035 foreach ($renderable->nodes
as $node) {
4036 if ($node->has_children()) {
4037 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER
);
4039 $html .= html_writer
::tag('li', $this->render($node));
4041 $html .= html_writer
::end_tag('ul');
4042 $html .= html_writer
::end_tag('div');
4046 public function context_header($headerinfo = null, $headinglevel = 1) {
4047 global $DB, $USER, $CFG;
4048 $context = $this->page
->context
;
4049 // Make sure to use the heading if it has been set.
4050 if (isset($headerinfo['heading'])) {
4051 $heading = $headerinfo['heading'];
4057 $userbuttons = null;
4058 // The user context currently has images and buttons. Other contexts may follow.
4059 if (isset($headerinfo['user']) ||
$context->contextlevel
== CONTEXT_USER
) {
4060 if (isset($headerinfo['user'])) {
4061 $user = $headerinfo['user'];
4063 // Look up the user information if it is not supplied.
4064 $user = $DB->get_record('user', array('id' => $context->instanceid
));
4066 // If the user context is set, then use that for capability checks.
4067 if (isset($headerinfo['usercontext'])) {
4068 $context = $headerinfo['usercontext'];
4070 // Use the user's full name if the heading isn't set.
4071 if (!isset($heading)) {
4072 $heading = fullname($user);
4075 $imagedata = $this->user_picture($user, array('size' => 100));
4076 // Check to see if we should be displaying a message button.
4077 if (!empty($CFG->messaging
) && $USER->id
!= $user->id
&& has_capability('moodle/site:sendmessage', $context)) {
4078 $iscontact = !empty(message_get_contact($user->id
));
4079 $contacttitle = $iscontact ?
'removefromyourcontacts' : 'addtoyourcontacts';
4080 $contacturlaction = $iscontact ?
'removecontact' : 'addcontact';
4081 $contactimage = $iscontact ?
'removecontact' : 'addcontact';
4082 $userbuttons = array(
4083 'messages' => array(
4084 'buttontype' => 'message',
4085 'title' => get_string('message', 'message'),
4086 'url' => new moodle_url('/message/index.php', array('id' => $user->id
)),
4087 'image' => 'message',
4088 'linkattributes' => array('role' => 'button'),
4089 'page' => $this->page
4091 'togglecontact' => array(
4092 'buttontype' => 'togglecontact',
4093 'title' => get_string($contacttitle, 'message'),
4094 'url' => new moodle_url('/message/index.php', array(
4095 'user1' => $USER->id
,
4096 'user2' => $user->id
,
4097 $contacturlaction => $user->id
,
4098 'sesskey' => sesskey())
4100 'image' => $contactimage,
4101 'linkattributes' => \core_message\helper
::togglecontact_link_params($user, $iscontact),
4102 'page' => $this->page
4106 $this->page
->requires
->string_for_js('changesmadereallygoaway', 'moodle');
4110 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4111 return $this->render_context_header($contextheader);
4115 * Renders the skip links for the page.
4117 * @param array $links List of skip links.
4118 * @return string HTML for the skip links.
4120 public function render_skip_links($links) {
4121 $context = [ 'links' => []];
4123 foreach ($links as $url => $text) {
4124 $context['links'][] = [ 'url' => $url, 'text' => $text];
4127 return $this->render_from_template('core/skip_links', $context);
4131 * Renders the header bar.
4133 * @param context_header $contextheader Header bar object.
4134 * @return string HTML for the header bar.
4136 protected function render_context_header(context_header
$contextheader) {
4138 // All the html stuff goes here.
4139 $html = html_writer
::start_div('page-context-header');
4142 if (isset($contextheader->imagedata
)) {
4143 // Header specific image.
4144 $html .= html_writer
::div($contextheader->imagedata
, 'page-header-image');
4148 if (!isset($contextheader->heading
)) {
4149 $headings = $this->heading($this->page
->heading
, $contextheader->headinglevel
);
4151 $headings = $this->heading($contextheader->heading
, $contextheader->headinglevel
);
4154 $html .= html_writer
::tag('div', $headings, array('class' => 'page-header-headings'));
4157 if (isset($contextheader->additionalbuttons
)) {
4158 $html .= html_writer
::start_div('btn-group header-button-group');
4159 foreach ($contextheader->additionalbuttons
as $button) {
4160 if (!isset($button->page
)) {
4161 // Include js for messaging.
4162 if ($button['buttontype'] === 'togglecontact') {
4163 \core_message\helper
::togglecontact_requirejs();
4165 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4166 'class' => 'iconsmall',
4167 'role' => 'presentation'
4169 $image .= html_writer
::span($button['title'], 'header-button-title');
4171 $image = html_writer
::empty_tag('img', array(
4172 'src' => $button['formattedimage'],
4173 'role' => 'presentation'
4176 $html .= html_writer
::link($button['url'], html_writer
::tag('span', $image), $button['linkattributes']);
4178 $html .= html_writer
::end_div();
4180 $html .= html_writer
::end_div();
4186 * Wrapper for header elements.
4188 * @return string HTML to display the main header.
4190 public function full_header() {
4191 $html = html_writer
::start_tag('header', array('id' => 'page-header', 'class' => 'clearfix'));
4192 $html .= $this->context_header();
4193 $html .= html_writer
::start_div('clearfix', array('id' => 'page-navbar'));
4194 $html .= html_writer
::tag('div', $this->navbar(), array('class' => 'breadcrumb-nav'));
4195 $html .= html_writer
::div($this->page_heading_button(), 'breadcrumb-button');
4196 $html .= html_writer
::end_div();
4197 $html .= html_writer
::tag('div', $this->course_header(), array('id' => 'course-header'));
4198 $html .= html_writer
::end_tag('header');
4203 * Displays the list of tags associated with an entry
4205 * @param array $tags list of instances of core_tag or stdClass
4206 * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4207 * to use default, set to '' (empty string) to omit the label completely
4208 * @param string $classes additional classes for the enclosing div element
4209 * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4210 * will be appended to the end, JS will toggle the rest of the tags
4211 * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4214 public function tag_list($tags, $label = null, $classes = '', $limit = 10, $pagecontext = null) {
4215 $list = new \core_tag\output\taglist
($tags, $label, $classes, $limit, $pagecontext);
4216 return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4220 * Renders element for inline editing of any value
4222 * @param \core\output\inplace_editable $element
4225 public function render_inplace_editable(\core\output\inplace_editable
$element) {
4226 return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4230 * Renders a bar chart.
4232 * @param \core\chart_bar $chart The chart.
4235 public function render_chart_bar(\core\chart_bar
$chart) {
4236 return $this->render_chart($chart);
4240 * Renders a line chart.
4242 * @param \core\chart_line $chart The chart.
4245 public function render_chart_line(\core\chart_line
$chart) {
4246 return $this->render_chart($chart);
4250 * Renders a pie chart.
4252 * @param \core\chart_pie $chart The chart.
4255 public function render_chart_pie(\core\chart_pie
$chart) {
4256 return $this->render_chart($chart);
4262 * @param \core\chart_base $chart The chart.
4263 * @param bool $withtable Whether to include a data table with the chart.
4266 public function render_chart(\core\chart_base
$chart, $withtable = true) {
4267 $chartdata = json_encode($chart);
4268 return $this->render_from_template('core/chart', (object) [
4269 'chartdata' => $chartdata,
4270 'withtable' => $withtable
4275 * Renders the login form.
4277 * @param \core_auth\output\login $form The renderable.
4280 public function render_login(\core_auth\output\login
$form) {
4281 $context = $form->export_for_template($this);
4283 // Override because rendering is not supported in template yet.
4284 $context->cookieshelpiconformatted
= $this->help_icon('cookiesenabled');
4285 $context->errorformatted
= $this->error_text($context->error
);
4287 return $this->render_from_template('core/login', $context);
4291 * Renders an mform element from a template.
4293 * @param HTML_QuickForm_element $element element
4294 * @param bool $required if input is required field
4295 * @param bool $advanced if input is an advanced field
4296 * @param string $error error message to display
4297 * @param bool $ingroup True if this element is rendered as part of a group
4298 * @return mixed string|bool
4300 public function mform_element($element, $required, $advanced, $error, $ingroup) {
4301 $templatename = 'core_form/element-' . $element->getType();
4303 $templatename .= "-inline";
4306 // We call this to generate a file not found exception if there is no template.
4307 // We don't want to call export_for_template if there is no template.
4308 core\output\mustache_template_finder
::get_template_filepath($templatename);
4310 if ($element instanceof templatable
) {
4311 $elementcontext = $element->export_for_template($this);
4314 if (method_exists($element, 'getHelpButton')) {
4315 $helpbutton = $element->getHelpButton();
4317 $label = $element->getLabel();
4319 if (method_exists($element, 'getText')) {
4320 // There currently exists code that adds a form element with an empty label.
4321 // If this is the case then set the label to the description.
4322 if (empty($label)) {
4323 $label = $element->getText();
4325 $text = $element->getText();
4330 'element' => $elementcontext,
4333 'required' => $required,
4334 'advanced' => $advanced,
4335 'helpbutton' => $helpbutton,
4338 return $this->render_from_template($templatename, $context);
4340 } catch (Exception
$e) {
4341 // No template for this element.
4347 * Render the login signup form into a nice template for the theme.
4349 * @param mform $form
4352 public function render_login_signup_form($form) {
4353 $context = $form->export_for_template($this);
4355 return $this->render_from_template('core/signup_form_layout', $context);
4359 * Renders a progress bar.
4361 * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4363 * @param progress_bar $bar The bar.
4364 * @return string HTML fragment
4366 public function render_progress_bar(progress_bar
$bar) {
4368 $data = $bar->export_for_template($this);
4369 return $this->render_from_template('core/progress_bar', $data);
4374 * A renderer that generates output for command-line scripts.
4376 * The implementation of this renderer is probably incomplete.
4378 * @copyright 2009 Tim Hunt
4379 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4384 class core_renderer_cli
extends core_renderer
{
4387 * Returns the page header.
4389 * @return string HTML fragment
4391 public function header() {
4392 return $this->page
->heading
. "\n";
4396 * Returns a template fragment representing a Heading.
4398 * @param string $text The text of the heading
4399 * @param int $level The level of importance of the heading
4400 * @param string $classes A space-separated list of CSS classes
4401 * @param string $id An optional ID
4402 * @return string A template fragment for a heading
4404 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4408 return '=>' . $text;
4410 return '-->' . $text;
4417 * Returns a template fragment representing a fatal error.
4419 * @param string $message The message to output
4420 * @param string $moreinfourl URL where more info can be found about the error
4421 * @param string $link Link for the Continue button
4422 * @param array $backtrace The execution backtrace
4423 * @param string $debuginfo Debugging information
4424 * @return string A template fragment for a fatal error
4426 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4429 $output = "!!! $message !!!\n";
4431 if ($CFG->debugdeveloper
) {
4432 if (!empty($debuginfo)) {
4433 $output .= $this->notification($debuginfo, 'notifytiny');
4435 if (!empty($backtrace)) {
4436 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
4444 * Returns a template fragment representing a notification.
4446 * @param string $message The message to print out.
4447 * @param string $type The type of notification. See constants on \core\output\notification.
4448 * @return string A template fragment for a notification
4450 public function notification($message, $type = null) {
4451 $message = clean_text($message);
4452 if ($type === 'notifysuccess' ||
$type === 'success') {
4453 return "++ $message ++\n";
4455 return "!! $message !!\n";
4459 * There is no footer for a cli request, however we must override the
4460 * footer method to prevent the default footer.
4462 public function footer() {}
4465 * Render a notification (that is, a status message about something that has
4468 * @param \core\output\notification $notification the notification to print out
4469 * @return string plain text output
4471 public function render_notification(\core\output\notification
$notification) {
4472 return $this->notification($notification->get_message(), $notification->get_message_type());
4478 * A renderer that generates output for ajax scripts.
4480 * This renderer prevents accidental sends back only json
4481 * encoded error messages, all other output is ignored.
4483 * @copyright 2010 Petr Skoda
4484 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4489 class core_renderer_ajax
extends core_renderer
{
4492 * Returns a template fragment representing a fatal error.
4494 * @param string $message The message to output
4495 * @param string $moreinfourl URL where more info can be found about the error
4496 * @param string $link Link for the Continue button
4497 * @param array $backtrace The execution backtrace
4498 * @param string $debuginfo Debugging information
4499 * @return string A template fragment for a fatal error
4501 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
4504 $this->page
->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
4506 $e = new stdClass();
4507 $e->error
= $message;
4508 $e->errorcode
= $errorcode;
4509 $e->stacktrace
= NULL;
4510 $e->debuginfo
= NULL;
4511 $e->reproductionlink
= NULL;
4512 if (!empty($CFG->debug
) and $CFG->debug
>= DEBUG_DEVELOPER
) {
4513 $link = (string) $link;
4515 $e->reproductionlink
= $link;
4517 if (!empty($debuginfo)) {
4518 $e->debuginfo
= $debuginfo;
4520 if (!empty($backtrace)) {
4521 $e->stacktrace
= format_backtrace($backtrace, true);
4525 return json_encode($e);
4529 * Used to display a notification.
4530 * For the AJAX notifications are discarded.
4532 * @param string $message The message to print out.
4533 * @param string $type The type of notification. See constants on \core\output\notification.
4535 public function notification($message, $type = null) {}
4538 * Used to display a redirection message.
4539 * AJAX redirections should not occur and as such redirection messages
4542 * @param moodle_url|string $encodedurl
4543 * @param string $message
4545 * @param bool $debugdisableredirect
4546 * @param string $messagetype The type of notification to show the message in.
4547 * See constants on \core\output\notification.
4549 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
4550 $messagetype = \core\output\notification
::NOTIFY_INFO
) {}
4553 * Prepares the start of an AJAX output.
4555 public function header() {
4556 // unfortunately YUI iframe upload does not support application/json
4557 if (!empty($_FILES)) {
4558 @header
('Content-type: text/plain; charset=utf-8');
4559 if (!core_useragent
::supports_json_contenttype()) {
4560 @header
('X-Content-Type-Options: nosniff');
4562 } else if (!core_useragent
::supports_json_contenttype()) {
4563 @header
('Content-type: text/plain; charset=utf-8');
4564 @header
('X-Content-Type-Options: nosniff');
4566 @header
('Content-type: application/json; charset=utf-8');
4569 // Headers to make it not cacheable and json
4570 @header
('Cache-Control: no-store, no-cache, must-revalidate');
4571 @header
('Cache-Control: post-check=0, pre-check=0', false);
4572 @header
('Pragma: no-cache');
4573 @header
('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
4574 @header
('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
4575 @header
('Accept-Ranges: none');
4579 * There is no footer for an AJAX request, however we must override the
4580 * footer method to prevent the default footer.
4582 public function footer() {}
4585 * No need for headers in an AJAX request... this should never happen.
4586 * @param string $text
4588 * @param string $classes
4591 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
4596 * Renderer for media files.
4598 * Used in file resources, media filter, and any other places that need to
4599 * output embedded media.
4601 * @deprecated since Moodle 3.2
4602 * @copyright 2011 The Open University
4603 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4605 class core_media_renderer
extends plugin_renderer_base
{
4606 /** @var array Array of available 'player' objects */
4608 /** @var string Regex pattern for links which may contain embeddable content */
4609 private $embeddablemarkers;
4614 * This is needed in the constructor (not later) so that you can use the
4615 * constants and static functions that are defined in core_media class
4616 * before you call renderer functions.
4618 public function __construct() {
4619 debugging('Class core_media_renderer is deprecated, please use core_media_manager::instance()', DEBUG_DEVELOPER
);
4623 * Renders a media file (audio or video) using suitable embedded player.
4625 * See embed_alternatives function for full description of parameters.
4626 * This function calls through to that one.
4628 * When using this function you can also specify width and height in the
4629 * URL by including ?d=100x100 at the end. If specified in the URL, this
4630 * will override the $width and $height parameters.
4632 * @param moodle_url $url Full URL of media file
4633 * @param string $name Optional user-readable name to display in download link
4634 * @param int $width Width in pixels (optional)
4635 * @param int $height Height in pixels (optional)
4636 * @param array $options Array of key/value pairs
4637 * @return string HTML content of embed
4639 public function embed_url(moodle_url
$url, $name = '', $width = 0, $height = 0,
4640 $options = array()) {
4641 return core_media_manager
::instance()->embed_url($url, $name, $width, $height, $options);
4645 * Renders media files (audio or video) using suitable embedded player.
4646 * The list of URLs should be alternative versions of the same content in
4647 * multiple formats. If there is only one format it should have a single
4650 * If the media files are not in a supported format, this will give students
4651 * a download link to each format. The download link uses the filename
4652 * unless you supply the optional name parameter.
4654 * Width and height are optional. If specified, these are suggested sizes
4655 * and should be the exact values supplied by the user, if they come from
4656 * user input. These will be treated as relating to the size of the video
4657 * content, not including any player control bar.
4659 * For audio files, height will be ignored. For video files, a few formats
4660 * work if you specify only width, but in general if you specify width
4661 * you must specify height as well.
4663 * The $options array is passed through to the core_media_player classes
4664 * that render the object tag. The keys can contain values from
4665 * core_media::OPTION_xx.
4667 * @param array $alternatives Array of moodle_url to media files
4668 * @param string $name Optional user-readable name to display in download link
4669 * @param int $width Width in pixels (optional)
4670 * @param int $height Height in pixels (optional)
4671 * @param array $options Array of key/value pairs
4672 * @return string HTML content of embed
4674 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
4675 $options = array()) {
4676 return core_media_manager
::instance()->embed_alternatives($alternatives, $name, $width, $height, $options);
4680 * Checks whether a file can be embedded. If this returns true you will get
4681 * an embedded player; if this returns false, you will just get a download
4684 * This is a wrapper for can_embed_urls.
4686 * @param moodle_url $url URL of media file
4687 * @param array $options Options (same as when embedding)
4688 * @return bool True if file can be embedded
4690 public function can_embed_url(moodle_url
$url, $options = array()) {
4691 return core_media_manager
::instance()->can_embed_url($url, $options);
4695 * Checks whether a file can be embedded. If this returns true you will get
4696 * an embedded player; if this returns false, you will just get a download
4699 * @param array $urls URL of media file and any alternatives (moodle_url)
4700 * @param array $options Options (same as when embedding)
4701 * @return bool True if file can be embedded
4703 public function can_embed_urls(array $urls, $options = array()) {
4704 return core_media_manager
::instance()->can_embed_urls($urls, $options);
4708 * Obtains a list of markers that can be used in a regular expression when
4709 * searching for URLs that can be embedded by any player type.
4711 * This string is used to improve peformance of regex matching by ensuring
4712 * that the (presumably C) regex code can do a quick keyword check on the
4713 * URL part of a link to see if it matches one of these, rather than having
4714 * to go into PHP code for every single link to see if it can be embedded.
4716 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
4718 public function get_embeddable_markers() {
4719 return core_media_manager
::instance()->get_embeddable_markers();
4724 * The maintenance renderer.
4726 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
4727 * is running a maintenance related task.
4728 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
4733 * @copyright 2013 Sam Hemelryk
4734 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4736 class core_renderer_maintenance
extends core_renderer
{
4739 * Initialises the renderer instance.
4740 * @param moodle_page $page
4741 * @param string $target
4742 * @throws coding_exception
4744 public function __construct(moodle_page
$page, $target) {
4745 if ($target !== RENDERER_TARGET_MAINTENANCE ||
$page->pagelayout
!== 'maintenance') {
4746 throw new coding_exception('Invalid request for the maintenance renderer.');
4748 parent
::__construct($page, $target);
4752 * Does nothing. The maintenance renderer cannot produce blocks.
4754 * @param block_contents $bc
4755 * @param string $region
4758 public function block(block_contents
$bc, $region) {
4759 // Computer says no blocks.
4760 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4765 * Does nothing. The maintenance renderer cannot produce blocks.
4767 * @param string $region
4768 * @param array $classes
4769 * @param string $tag
4772 public function blocks($region, $classes = array(), $tag = 'aside') {
4773 // Computer says no blocks.
4774 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4779 * Does nothing. The maintenance renderer cannot produce blocks.
4781 * @param string $region
4784 public function blocks_for_region($region) {
4785 // Computer says no blocks for region.
4786 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4791 * Does nothing. The maintenance renderer cannot produce a course content header.
4793 * @param bool $onlyifnotcalledbefore
4796 public function course_content_header($onlyifnotcalledbefore = false) {
4797 // Computer says no course content header.
4798 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4803 * Does nothing. The maintenance renderer cannot produce a course content footer.
4805 * @param bool $onlyifnotcalledbefore
4808 public function course_content_footer($onlyifnotcalledbefore = false) {
4809 // Computer says no course content footer.
4810 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4815 * Does nothing. The maintenance renderer cannot produce a course header.
4819 public function course_header() {
4820 // Computer says no course header.
4821 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4826 * Does nothing. The maintenance renderer cannot produce a course footer.
4830 public function course_footer() {
4831 // Computer says no course footer.
4832 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4837 * Does nothing. The maintenance renderer cannot produce a custom menu.
4839 * @param string $custommenuitems
4842 public function custom_menu($custommenuitems = '') {
4843 // Computer says no custom menu.
4844 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4849 * Does nothing. The maintenance renderer cannot produce a file picker.
4851 * @param array $options
4854 public function file_picker($options) {
4855 // Computer says no file picker.
4856 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4861 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
4866 public function htmllize_file_tree($dir) {
4867 // Hell no we don't want no htmllized file tree.
4868 // Also why on earth is this function on the core renderer???
4869 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4875 * Overridden confirm message for upgrades.
4877 * @param string $message The question to ask the user
4878 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
4879 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
4880 * @return string HTML fragment
4882 public function confirm($message, $continue, $cancel) {
4883 // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
4884 // from any previous version of Moodle).
4885 if ($continue instanceof single_button
) {
4886 $continue->primary
= true;
4887 } else if (is_string($continue)) {
4888 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
4889 } else if ($continue instanceof moodle_url
) {
4890 $continue = new single_button($continue, get_string('continue'), 'post', true);
4892 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
4893 ' (string/moodle_url) or a single_button instance.');
4896 if ($cancel instanceof single_button
) {
4898 } else if (is_string($cancel)) {
4899 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
4900 } else if ($cancel instanceof moodle_url
) {
4901 $cancel = new single_button($cancel, get_string('cancel'), 'get');
4903 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
4904 ' (string/moodle_url) or a single_button instance.');
4907 $output = $this->box_start('generalbox', 'notice');
4908 $output .= html_writer
::tag('h4', get_string('confirm'));
4909 $output .= html_writer
::tag('p', $message);
4910 $output .= html_writer
::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
4911 $output .= $this->box_end();
4916 * Does nothing. The maintenance renderer does not support JS.
4918 * @param block_contents $bc
4920 public function init_block_hider_js(block_contents
$bc) {
4921 // Computer says no JavaScript.
4922 // Do nothing, ridiculous method.
4926 * Does nothing. The maintenance renderer cannot produce language menus.
4930 public function lang_menu() {
4931 // Computer says no lang menu.
4932 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4937 * Does nothing. The maintenance renderer has no need for login information.
4939 * @param null $withlinks
4942 public function login_info($withlinks = null) {
4943 // Computer says no login info.
4944 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4949 * Does nothing. The maintenance renderer cannot produce user pictures.
4951 * @param stdClass $user
4952 * @param array $options
4955 public function user_picture(stdClass
$user, array $options = null) {
4956 // Computer says no user pictures.
4957 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);