Merge branch 'MDL-48202-M30' of git://github.com/lazydaisy/moodle
[moodle.git] / lib / outputrenderers.php
blob53e5e70093f1c28c4ed9e34e0e8a343606d14ce9
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
21 * for an overview.
23 * Included in this file are the primary renderer classes:
24 * - renderer_base: The renderer outline class that all renderers
25 * should inherit from.
26 * - core_renderer: The standard HTML renderer.
27 * - core_renderer_cli: An adaption of the standard renderer for CLI scripts.
28 * - core_renderer_ajax: An adaption of the standard renderer for AJAX scripts.
29 * - plugin_renderer_base: A renderer class that should be extended by all
30 * plugin renderers.
32 * @package core
33 * @category output
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') || die();
40 /**
41 * Simple base class for Moodle renderers.
43 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
45 * Also has methods to facilitate generating HTML output.
47 * @copyright 2009 Tim Hunt
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 * @since Moodle 2.0
50 * @package core
51 * @category output
53 class renderer_base {
54 /**
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
59 /**
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
62 protected $page;
64 /**
65 * @var string The requested rendering target.
67 protected $target;
69 /**
70 * @var Mustache_Engine $mustache The mustache template compiler
72 private $mustache;
74 /**
75 * Return an instance of the mustache class.
77 * @since 2.9
78 * @return Mustache_Engine
80 protected function get_mustache() {
81 global $CFG;
83 if ($this->mustache === null) {
84 require_once($CFG->dirroot . '/lib/mustache/src/Mustache/Autoloader.php');
85 Mustache_Autoloader::register();
87 $themename = $this->page->theme->name;
88 $themerev = theme_get_revision();
90 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
92 $loader = new \core\output\mustache_filesystem_loader();
93 $stringhelper = new \core\output\mustache_string_helper();
94 $jshelper = new \core\output\mustache_javascript_helper($this->page->requires);
95 $pixhelper = new \core\output\mustache_pix_helper($this);
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 'js' => array($jshelper, 'help'),
103 'pix' => array($pixhelper, 'pix'));
105 $this->mustache = new Mustache_Engine(array(
106 'cache' => $cachedir,
107 'escape' => 's',
108 'loader' => $loader,
109 'helpers' => $helpers));
113 return $this->mustache;
118 * Constructor
120 * The constructor takes two arguments. The first is the page that the renderer
121 * has been created to assist with, and the second is the target.
122 * The target is an additional identifier that can be used to load different
123 * renderers for different options.
125 * @param moodle_page $page the page we are doing output for.
126 * @param string $target one of rendering target constants
128 public function __construct(moodle_page $page, $target) {
129 $this->opencontainers = $page->opencontainers;
130 $this->page = $page;
131 $this->target = $target;
135 * Renders a template by name with the given context.
137 * The provided data needs to be array/stdClass made up of only simple types.
138 * Simple types are array,stdClass,bool,int,float,string
140 * @since 2.9
141 * @param array|stdClass $context Context containing data for the template.
142 * @return string|boolean
144 public function render_from_template($templatename, $context) {
145 static $templatecache = array();
146 $mustache = $this->get_mustache();
148 // Provide 1 random value that will not change within a template
149 // but will be different from template to template. This is useful for
150 // e.g. aria attributes that only work with id attributes and must be
151 // unique in a page.
152 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
153 if (isset($templatecache[$templatename])) {
154 $template = $templatecache[$templatename];
155 } else {
156 try {
157 $template = $mustache->loadTemplate($templatename);
158 $templatecache[$templatename] = $template;
159 } catch (Mustache_Exception_UnknownTemplateException $e) {
160 throw new moodle_exception('Unknown template: ' . $templatename);
163 return trim($template->render($context));
168 * Returns rendered widget.
170 * The provided widget needs to be an object that extends the renderable
171 * interface.
172 * If will then be rendered by a method based upon the classname for the widget.
173 * For instance a widget of class `crazywidget` will be rendered by a protected
174 * render_crazywidget method of this renderer.
176 * @param renderable $widget instance with renderable interface
177 * @return string
179 public function render(renderable $widget) {
180 $classname = get_class($widget);
181 // Strip namespaces.
182 $classname = preg_replace('/^.*\\\/', '', $classname);
183 // Remove _renderable suffixes
184 $classname = preg_replace('/_renderable$/', '', $classname);
186 $rendermethod = 'render_'.$classname;
187 if (method_exists($this, $rendermethod)) {
188 return $this->$rendermethod($widget);
190 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
194 * Adds a JS action for the element with the provided id.
196 * This method adds a JS event for the provided component action to the page
197 * and then returns the id that the event has been attached to.
198 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
200 * @param component_action $action
201 * @param string $id
202 * @return string id of element, either original submitted or random new if not supplied
204 public function add_action_handler(component_action $action, $id = null) {
205 if (!$id) {
206 $id = html_writer::random_id($action->event);
208 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
209 return $id;
213 * Returns true is output has already started, and false if not.
215 * @return boolean true if the header has been printed.
217 public function has_started() {
218 return $this->page->state >= moodle_page::STATE_IN_BODY;
222 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
224 * @param mixed $classes Space-separated string or array of classes
225 * @return string HTML class attribute value
227 public static function prepare_classes($classes) {
228 if (is_array($classes)) {
229 return implode(' ', array_unique($classes));
231 return $classes;
235 * Return the moodle_url for an image.
237 * The exact image location and extension is determined
238 * automatically by searching for gif|png|jpg|jpeg, please
239 * note there can not be diferent images with the different
240 * extension. The imagename is for historical reasons
241 * a relative path name, it may be changed later for core
242 * images. It is recommended to not use subdirectories
243 * in plugin and theme pix directories.
245 * There are three types of images:
246 * 1/ theme images - stored in theme/mytheme/pix/,
247 * use component 'theme'
248 * 2/ core images - stored in /pix/,
249 * overridden via theme/mytheme/pix_core/
250 * 3/ plugin images - stored in mod/mymodule/pix,
251 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
252 * example: pix_url('comment', 'mod_glossary')
254 * @param string $imagename the pathname of the image
255 * @param string $component full plugin name (aka component) or 'theme'
256 * @return moodle_url
258 public function pix_url($imagename, $component = 'moodle') {
259 return $this->page->theme->pix_url($imagename, $component);
265 * Basis for all plugin renderers.
267 * @copyright Petr Skoda (skodak)
268 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
269 * @since Moodle 2.0
270 * @package core
271 * @category output
273 class plugin_renderer_base extends renderer_base {
276 * @var renderer_base|core_renderer A reference to the current renderer.
277 * The renderer provided here will be determined by the page but will in 90%
278 * of cases by the {@link core_renderer}
280 protected $output;
283 * Constructor method, calls the parent constructor
285 * @param moodle_page $page
286 * @param string $target one of rendering target constants
288 public function __construct(moodle_page $page, $target) {
289 if (empty($target) && $page->pagelayout === 'maintenance') {
290 // If the page is using the maintenance layout then we're going to force the target to maintenance.
291 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
292 // unavailable for this page layout.
293 $target = RENDERER_TARGET_MAINTENANCE;
295 $this->output = $page->get_renderer('core', null, $target);
296 parent::__construct($page, $target);
300 * Renders the provided widget and returns the HTML to display it.
302 * @param renderable $widget instance with renderable interface
303 * @return string
305 public function render(renderable $widget) {
306 $classname = get_class($widget);
307 // Strip namespaces.
308 $classname = preg_replace('/^.*\\\/', '', $classname);
309 // Keep a copy at this point, we may need to look for a deprecated method.
310 $deprecatedmethod = 'render_'.$classname;
311 // Remove _renderable suffixes
312 $classname = preg_replace('/_renderable$/', '', $classname);
314 $rendermethod = 'render_'.$classname;
315 if (method_exists($this, $rendermethod)) {
316 return $this->$rendermethod($widget);
318 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
319 // This is exactly where we don't want to be.
320 // If you have arrived here you have a renderable component within your plugin that has the name
321 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
322 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
323 // and the _renderable suffix now gets removed when looking for a render method.
324 // You need to change your renderers render_blah_renderable to render_blah.
325 // Until you do this it will not be possible for a theme to override the renderer to override your method.
326 // Please do it ASAP.
327 static $debugged = array();
328 if (!isset($debugged[$deprecatedmethod])) {
329 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
330 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
331 $debugged[$deprecatedmethod] = true;
333 return $this->$deprecatedmethod($widget);
335 // pass to core renderer if method not found here
336 return $this->output->render($widget);
340 * Magic method used to pass calls otherwise meant for the standard renderer
341 * to it to ensure we don't go causing unnecessary grief.
343 * @param string $method
344 * @param array $arguments
345 * @return mixed
347 public function __call($method, $arguments) {
348 if (method_exists('renderer_base', $method)) {
349 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
351 if (method_exists($this->output, $method)) {
352 return call_user_func_array(array($this->output, $method), $arguments);
353 } else {
354 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
361 * The standard implementation of the core_renderer interface.
363 * @copyright 2009 Tim Hunt
364 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
365 * @since Moodle 2.0
366 * @package core
367 * @category output
369 class core_renderer extends renderer_base {
371 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
372 * in layout files instead.
373 * @deprecated
374 * @var string used in {@link core_renderer::header()}.
376 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
379 * @var string Used to pass information from {@link core_renderer::doctype()} to
380 * {@link core_renderer::standard_head_html()}.
382 protected $contenttype;
385 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
386 * with {@link core_renderer::header()}.
388 protected $metarefreshtag = '';
391 * @var string Unique token for the closing HTML
393 protected $unique_end_html_token;
396 * @var string Unique token for performance information
398 protected $unique_performance_info_token;
401 * @var string Unique token for the main content.
403 protected $unique_main_content_token;
406 * Constructor
408 * @param moodle_page $page the page we are doing output for.
409 * @param string $target one of rendering target constants
411 public function __construct(moodle_page $page, $target) {
412 $this->opencontainers = $page->opencontainers;
413 $this->page = $page;
414 $this->target = $target;
416 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
417 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
418 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
422 * Get the DOCTYPE declaration that should be used with this page. Designed to
423 * be called in theme layout.php files.
425 * @return string the DOCTYPE declaration that should be used.
427 public function doctype() {
428 if ($this->page->theme->doctype === 'html5') {
429 $this->contenttype = 'text/html; charset=utf-8';
430 return "<!DOCTYPE html>\n";
432 } else if ($this->page->theme->doctype === 'xhtml5') {
433 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
434 return "<!DOCTYPE html>\n";
436 } else {
437 // legacy xhtml 1.0
438 $this->contenttype = 'text/html; charset=utf-8';
439 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
444 * The attributes that should be added to the <html> tag. Designed to
445 * be called in theme layout.php files.
447 * @return string HTML fragment.
449 public function htmlattributes() {
450 $return = get_html_lang(true);
451 if ($this->page->theme->doctype !== 'html5') {
452 $return .= ' xmlns="http://www.w3.org/1999/xhtml"';
454 return $return;
458 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
459 * that should be included in the <head> tag. Designed to be called in theme
460 * layout.php files.
462 * @return string HTML fragment.
464 public function standard_head_html() {
465 global $CFG, $SESSION;
467 // Before we output any content, we need to ensure that certain
468 // page components are set up.
470 // Blocks must be set up early as they may require javascript which
471 // has to be included in the page header before output is created.
472 foreach ($this->page->blocks->get_regions() as $region) {
473 $this->page->blocks->ensure_content_created($region, $this);
476 $output = '';
477 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
478 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
479 // This is only set by the {@link redirect()} method
480 $output .= $this->metarefreshtag;
482 // Check if a periodic refresh delay has been set and make sure we arn't
483 // already meta refreshing
484 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
485 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
488 // flow player embedding support
489 $this->page->requires->js_function_call('M.util.load_flowplayer');
491 // Set up help link popups for all links with the helptooltip class
492 $this->page->requires->js_init_call('M.util.help_popups.setup');
494 // Setup help icon overlays.
495 $this->page->requires->yui_module('moodle-core-popuphelp', 'M.core.init_popuphelp');
496 $this->page->requires->strings_for_js(array(
497 'morehelp',
498 'loadinghelp',
499 ), 'moodle');
501 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
503 $focus = $this->page->focuscontrol;
504 if (!empty($focus)) {
505 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
506 // This is a horrifically bad way to handle focus but it is passed in
507 // through messy formslib::moodleform
508 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
509 } else if (strpos($focus, '.')!==false) {
510 // Old style of focus, bad way to do it
511 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);
512 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
513 } else {
514 // Focus element with given id
515 $this->page->requires->js_function_call('focuscontrol', array($focus));
519 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
520 // any other custom CSS can not be overridden via themes and is highly discouraged
521 $urls = $this->page->theme->css_urls($this->page);
522 foreach ($urls as $url) {
523 $this->page->requires->css_theme($url);
526 // Get the theme javascript head and footer
527 if ($jsurl = $this->page->theme->javascript_url(true)) {
528 $this->page->requires->js($jsurl, true);
530 if ($jsurl = $this->page->theme->javascript_url(false)) {
531 $this->page->requires->js($jsurl);
534 // Get any HTML from the page_requirements_manager.
535 $output .= $this->page->requires->get_head_code($this->page, $this);
537 // List alternate versions.
538 foreach ($this->page->alternateversions as $type => $alt) {
539 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
540 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
543 if (!empty($CFG->additionalhtmlhead)) {
544 $output .= "\n".$CFG->additionalhtmlhead;
547 return $output;
551 * The standard tags (typically skip links) that should be output just inside
552 * the start of the <body> tag. Designed to be called in theme layout.php files.
554 * @return string HTML fragment.
556 public function standard_top_of_body_html() {
557 global $CFG;
558 $output = $this->page->requires->get_top_of_body_code();
559 if (!empty($CFG->additionalhtmltopofbody)) {
560 $output .= "\n".$CFG->additionalhtmltopofbody;
562 $output .= $this->maintenance_warning();
563 return $output;
567 * Scheduled maintenance warning message.
569 * Note: This is a nasty hack to display maintenance notice, this should be moved
570 * to some general notification area once we have it.
572 * @return string
574 public function maintenance_warning() {
575 global $CFG;
577 $output = '';
578 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
579 $timeleft = $CFG->maintenance_later - time();
580 // If timeleft less than 30 sec, set the class on block to error to highlight.
581 $errorclass = ($timeleft < 30) ? 'error' : 'warning';
582 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning');
583 $a = new stdClass();
584 $a->min = (int)($timeleft/60);
585 $a->sec = (int)($timeleft % 60);
586 $output .= get_string('maintenancemodeisscheduled', 'admin', $a) ;
587 $output .= $this->box_end();
588 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
589 array(array('timeleftinsec' => $timeleft)));
590 $this->page->requires->strings_for_js(
591 array('maintenancemodeisscheduled', 'sitemaintenance'),
592 'admin');
594 return $output;
598 * The standard tags (typically performance information and validation links,
599 * if we are in developer debug mode) that should be output in the footer area
600 * of the page. Designed to be called in theme layout.php files.
602 * @return string HTML fragment.
604 public function standard_footer_html() {
605 global $CFG, $SCRIPT;
607 if (during_initial_install()) {
608 // Debugging info can not work before install is finished,
609 // in any case we do not want any links during installation!
610 return '';
613 // This function is normally called from a layout.php file in {@link core_renderer::header()}
614 // but some of the content won't be known until later, so we return a placeholder
615 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
616 $output = $this->unique_performance_info_token;
617 if ($this->page->devicetypeinuse == 'legacy') {
618 // The legacy theme is in use print the notification
619 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
622 // Get links to switch device types (only shown for users not on a default device)
623 $output .= $this->theme_switch_links();
625 if (!empty($CFG->debugpageinfo)) {
626 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
628 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
629 // Add link to profiling report if necessary
630 if (function_exists('profiling_is_running') && profiling_is_running()) {
631 $txt = get_string('profiledscript', 'admin');
632 $title = get_string('profiledscriptview', 'admin');
633 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
634 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
635 $output .= '<div class="profilingfooter">' . $link . '</div>';
637 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
638 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
639 $output .= '<div class="purgecaches">' .
640 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
642 if (!empty($CFG->debugvalidators)) {
643 // 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
644 $output .= '<div class="validators"><ul>
645 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
646 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
647 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&amp;warnp2n3e=1&amp;url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
648 </ul></div>';
650 return $output;
654 * Returns standard main content placeholder.
655 * Designed to be called in theme layout.php files.
657 * @return string HTML fragment.
659 public function main_content() {
660 // This is here because it is the only place we can inject the "main" role over the entire main content area
661 // without requiring all theme's to manually do it, and without creating yet another thing people need to
662 // remember in the theme.
663 // This is an unfortunate hack. DO NO EVER add anything more here.
664 // DO NOT add classes.
665 // DO NOT add an id.
666 return '<div role="main">'.$this->unique_main_content_token.'</div>';
670 * The standard tags (typically script tags that are not needed earlier) that
671 * should be output after everything else. Designed to be called in theme layout.php files.
673 * @return string HTML fragment.
675 public function standard_end_of_body_html() {
676 global $CFG;
678 // This function is normally called from a layout.php file in {@link core_renderer::header()}
679 // but some of the content won't be known until later, so we return a placeholder
680 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
681 $output = '';
682 if (!empty($CFG->additionalhtmlfooter)) {
683 $output .= "\n".$CFG->additionalhtmlfooter;
685 $output .= $this->unique_end_html_token;
686 return $output;
690 * Return the standard string that says whether you are logged in (and switched
691 * roles/logged in as another user).
692 * @param bool $withlinks if false, then don't include any links in the HTML produced.
693 * If not set, the default is the nologinlinks option from the theme config.php file,
694 * and if that is not set, then links are included.
695 * @return string HTML fragment.
697 public function login_info($withlinks = null) {
698 global $USER, $CFG, $DB, $SESSION;
700 if (during_initial_install()) {
701 return '';
704 if (is_null($withlinks)) {
705 $withlinks = empty($this->page->layout_options['nologinlinks']);
708 $course = $this->page->course;
709 if (\core\session\manager::is_loggedinas()) {
710 $realuser = \core\session\manager::get_realuser();
711 $fullname = fullname($realuser, true);
712 if ($withlinks) {
713 $loginastitle = get_string('loginas');
714 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
715 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
716 } else {
717 $realuserinfo = " [$fullname] ";
719 } else {
720 $realuserinfo = '';
723 $loginpage = $this->is_login_page();
724 $loginurl = get_login_url();
726 if (empty($course->id)) {
727 // $course->id is not defined during installation
728 return '';
729 } else if (isloggedin()) {
730 $context = context_course::instance($course->id);
732 $fullname = fullname($USER, true);
733 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
734 if ($withlinks) {
735 $linktitle = get_string('viewprofile');
736 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
737 } else {
738 $username = $fullname;
740 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
741 if ($withlinks) {
742 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
743 } else {
744 $username .= " from {$idprovider->name}";
747 if (isguestuser()) {
748 $loggedinas = $realuserinfo.get_string('loggedinasguest');
749 if (!$loginpage && $withlinks) {
750 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
752 } else if (is_role_switched($course->id)) { // Has switched roles
753 $rolename = '';
754 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
755 $rolename = ': '.role_get_name($role, $context);
757 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
758 if ($withlinks) {
759 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
760 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
762 } else {
763 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
764 if ($withlinks) {
765 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
768 } else {
769 $loggedinas = get_string('loggedinnot', 'moodle');
770 if (!$loginpage && $withlinks) {
771 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
775 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
777 if (isset($SESSION->justloggedin)) {
778 unset($SESSION->justloggedin);
779 if (!empty($CFG->displayloginfailures)) {
780 if (!isguestuser()) {
781 // Include this file only when required.
782 require_once($CFG->dirroot . '/user/lib.php');
783 if ($count = user_count_login_failures($USER)) {
784 $loggedinas .= '<div class="loginfailures">';
785 $a = new stdClass();
786 $a->attempts = $count;
787 $loggedinas .= get_string('failedloginattempts', '', $a);
788 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
789 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
790 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
792 $loggedinas .= '</div>';
798 return $loggedinas;
802 * Check whether the current page is a login page.
804 * @since Moodle 2.9
805 * @return bool
807 protected function is_login_page() {
808 // This is a real bit of a hack, but its a rarety that we need to do something like this.
809 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
810 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
811 return in_array(
812 $this->page->url->out_as_local_url(false, array()),
813 array(
814 '/login/index.php',
815 '/login/forgot_password.php',
821 * Return the 'back' link that normally appears in the footer.
823 * @return string HTML fragment.
825 public function home_link() {
826 global $CFG, $SITE;
828 if ($this->page->pagetype == 'site-index') {
829 // Special case for site home page - please do not remove
830 return '<div class="sitelink">' .
831 '<a title="Moodle" href="http://moodle.org/">' .
832 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
834 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
835 // Special case for during install/upgrade.
836 return '<div class="sitelink">'.
837 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
838 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
840 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
841 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
842 get_string('home') . '</a></div>';
844 } else {
845 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
846 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
851 * Redirects the user by any means possible given the current state
853 * This function should not be called directly, it should always be called using
854 * the redirect function in lib/weblib.php
856 * The redirect function should really only be called before page output has started
857 * however it will allow itself to be called during the state STATE_IN_BODY
859 * @param string $encodedurl The URL to send to encoded if required
860 * @param string $message The message to display to the user if any
861 * @param int $delay The delay before redirecting a user, if $message has been
862 * set this is a requirement and defaults to 3, set to 0 no delay
863 * @param boolean $debugdisableredirect this redirect has been disabled for
864 * debugging purposes. Display a message that explains, and don't
865 * trigger the redirect.
866 * @return string The HTML to display to the user before dying, may contain
867 * meta refresh, javascript refresh, and may have set header redirects
869 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
870 global $CFG;
871 $url = str_replace('&amp;', '&', $encodedurl);
873 switch ($this->page->state) {
874 case moodle_page::STATE_BEFORE_HEADER :
875 // No output yet it is safe to delivery the full arsenal of redirect methods
876 if (!$debugdisableredirect) {
877 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
878 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
879 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
881 $output = $this->header();
882 break;
883 case moodle_page::STATE_PRINTING_HEADER :
884 // We should hopefully never get here
885 throw new coding_exception('You cannot redirect while printing the page header');
886 break;
887 case moodle_page::STATE_IN_BODY :
888 // We really shouldn't be here but we can deal with this
889 debugging("You should really redirect before you start page output");
890 if (!$debugdisableredirect) {
891 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
893 $output = $this->opencontainers->pop_all_but_last();
894 break;
895 case moodle_page::STATE_DONE :
896 // Too late to be calling redirect now
897 throw new coding_exception('You cannot redirect after the entire page has been generated');
898 break;
900 $output .= $this->notification($message, 'redirectmessage');
901 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
902 if ($debugdisableredirect) {
903 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
905 $output .= $this->footer();
906 return $output;
910 * Start output by sending the HTTP headers, and printing the HTML <head>
911 * and the start of the <body>.
913 * To control what is printed, you should set properties on $PAGE. If you
914 * are familiar with the old {@link print_header()} function from Moodle 1.9
915 * you will find that there are properties on $PAGE that correspond to most
916 * of the old parameters to could be passed to print_header.
918 * Not that, in due course, the remaining $navigation, $menu parameters here
919 * will be replaced by more properties of $PAGE, but that is still to do.
921 * @return string HTML that you must output this, preferably immediately.
923 public function header() {
924 global $USER, $CFG;
926 if (\core\session\manager::is_loggedinas()) {
927 $this->page->add_body_class('userloggedinas');
930 // If the user is logged in, and we're not in initial install,
931 // check to see if the user is role-switched and add the appropriate
932 // CSS class to the body element.
933 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
934 $this->page->add_body_class('userswitchedrole');
937 // Give themes a chance to init/alter the page object.
938 $this->page->theme->init_page($this->page);
940 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
942 // Find the appropriate page layout file, based on $this->page->pagelayout.
943 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
944 // Render the layout using the layout file.
945 $rendered = $this->render_page_layout($layoutfile);
947 // Slice the rendered output into header and footer.
948 $cutpos = strpos($rendered, $this->unique_main_content_token);
949 if ($cutpos === false) {
950 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
951 $token = self::MAIN_CONTENT_TOKEN;
952 } else {
953 $token = $this->unique_main_content_token;
956 if ($cutpos === false) {
957 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.');
959 $header = substr($rendered, 0, $cutpos);
960 $footer = substr($rendered, $cutpos + strlen($token));
962 if (empty($this->contenttype)) {
963 debugging('The page layout file did not call $OUTPUT->doctype()');
964 $header = $this->doctype() . $header;
967 // If this theme version is below 2.4 release and this is a course view page
968 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
969 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
970 // check if course content header/footer have not been output during render of theme layout
971 $coursecontentheader = $this->course_content_header(true);
972 $coursecontentfooter = $this->course_content_footer(true);
973 if (!empty($coursecontentheader)) {
974 // display debug message and add header and footer right above and below main content
975 // Please note that course header and footer (to be displayed above and below the whole page)
976 // are not displayed in this case at all.
977 // Besides the content header and footer are not displayed on any other course page
978 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);
979 $header .= $coursecontentheader;
980 $footer = $coursecontentfooter. $footer;
984 send_headers($this->contenttype, $this->page->cacheable);
986 $this->opencontainers->push('header/footer', $footer);
987 $this->page->set_state(moodle_page::STATE_IN_BODY);
989 return $header . $this->skip_link_target('maincontent');
993 * Renders and outputs the page layout file.
995 * This is done by preparing the normal globals available to a script, and
996 * then including the layout file provided by the current theme for the
997 * requested layout.
999 * @param string $layoutfile The name of the layout file
1000 * @return string HTML code
1002 protected function render_page_layout($layoutfile) {
1003 global $CFG, $SITE, $USER;
1004 // The next lines are a bit tricky. The point is, here we are in a method
1005 // of a renderer class, and this object may, or may not, be the same as
1006 // the global $OUTPUT object. When rendering the page layout file, we want to use
1007 // this object. However, people writing Moodle code expect the current
1008 // renderer to be called $OUTPUT, not $this, so define a variable called
1009 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1010 $OUTPUT = $this;
1011 $PAGE = $this->page;
1012 $COURSE = $this->page->course;
1014 ob_start();
1015 include($layoutfile);
1016 $rendered = ob_get_contents();
1017 ob_end_clean();
1018 return $rendered;
1022 * Outputs the page's footer
1024 * @return string HTML fragment
1026 public function footer() {
1027 global $CFG, $DB;
1029 $output = $this->container_end_all(true);
1031 $footer = $this->opencontainers->pop('header/footer');
1033 if (debugging() and $DB and $DB->is_transaction_started()) {
1034 // TODO: MDL-20625 print warning - transaction will be rolled back
1037 // Provide some performance info if required
1038 $performanceinfo = '';
1039 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1040 $perf = get_performance_info();
1041 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1042 $performanceinfo = $perf['html'];
1046 // We always want performance data when running a performance test, even if the user is redirected to another page.
1047 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1048 $footer = $this->unique_performance_info_token . $footer;
1050 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1052 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1054 $this->page->set_state(moodle_page::STATE_DONE);
1056 return $output . $footer;
1060 * Close all but the last open container. This is useful in places like error
1061 * handling, where you want to close all the open containers (apart from <body>)
1062 * before outputting the error message.
1064 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1065 * developer debug warning if it isn't.
1066 * @return string the HTML required to close any open containers inside <body>.
1068 public function container_end_all($shouldbenone = false) {
1069 return $this->opencontainers->pop_all_but_last($shouldbenone);
1073 * Returns course-specific information to be output immediately above content on any course page
1074 * (for the current course)
1076 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1077 * @return string
1079 public function course_content_header($onlyifnotcalledbefore = false) {
1080 global $CFG;
1081 if ($this->page->course->id == SITEID) {
1082 // return immediately and do not include /course/lib.php if not necessary
1083 return '';
1085 static $functioncalled = false;
1086 if ($functioncalled && $onlyifnotcalledbefore) {
1087 // we have already output the content header
1088 return '';
1090 require_once($CFG->dirroot.'/course/lib.php');
1091 $functioncalled = true;
1092 $courseformat = course_get_format($this->page->course);
1093 if (($obj = $courseformat->course_content_header()) !== null) {
1094 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1096 return '';
1100 * Returns course-specific information to be output immediately below content on any course page
1101 * (for the current course)
1103 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1104 * @return string
1106 public function course_content_footer($onlyifnotcalledbefore = false) {
1107 global $CFG;
1108 if ($this->page->course->id == SITEID) {
1109 // return immediately and do not include /course/lib.php if not necessary
1110 return '';
1112 static $functioncalled = false;
1113 if ($functioncalled && $onlyifnotcalledbefore) {
1114 // we have already output the content footer
1115 return '';
1117 $functioncalled = true;
1118 require_once($CFG->dirroot.'/course/lib.php');
1119 $courseformat = course_get_format($this->page->course);
1120 if (($obj = $courseformat->course_content_footer()) !== null) {
1121 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1123 return '';
1127 * Returns course-specific information to be output on any course page in the header area
1128 * (for the current course)
1130 * @return string
1132 public function course_header() {
1133 global $CFG;
1134 if ($this->page->course->id == SITEID) {
1135 // return immediately and do not include /course/lib.php if not necessary
1136 return '';
1138 require_once($CFG->dirroot.'/course/lib.php');
1139 $courseformat = course_get_format($this->page->course);
1140 if (($obj = $courseformat->course_header()) !== null) {
1141 return $courseformat->get_renderer($this->page)->render($obj);
1143 return '';
1147 * Returns course-specific information to be output on any course page in the footer area
1148 * (for the current course)
1150 * @return string
1152 public function course_footer() {
1153 global $CFG;
1154 if ($this->page->course->id == SITEID) {
1155 // return immediately and do not include /course/lib.php if not necessary
1156 return '';
1158 require_once($CFG->dirroot.'/course/lib.php');
1159 $courseformat = course_get_format($this->page->course);
1160 if (($obj = $courseformat->course_footer()) !== null) {
1161 return $courseformat->get_renderer($this->page)->render($obj);
1163 return '';
1167 * Returns lang menu or '', this method also checks forcing of languages in courses.
1169 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1171 * @return string The lang menu HTML or empty string
1173 public function lang_menu() {
1174 global $CFG;
1176 if (empty($CFG->langmenu)) {
1177 return '';
1180 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1181 // do not show lang menu if language forced
1182 return '';
1185 $currlang = current_language();
1186 $langs = get_string_manager()->get_list_of_translations();
1188 if (count($langs) < 2) {
1189 return '';
1192 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1193 $s->label = get_accesshide(get_string('language'));
1194 $s->class = 'langmenu';
1195 return $this->render($s);
1199 * Output the row of editing icons for a block, as defined by the controls array.
1201 * @param array $controls an array like {@link block_contents::$controls}.
1202 * @param string $blockid The ID given to the block.
1203 * @return string HTML fragment.
1205 public function block_controls($actions, $blockid = null) {
1206 global $CFG;
1207 if (empty($actions)) {
1208 return '';
1210 $menu = new action_menu($actions);
1211 if ($blockid !== null) {
1212 $menu->set_owner_selector('#'.$blockid);
1214 $menu->set_constraint('.block-region');
1215 $menu->attributes['class'] .= ' block-control-actions commands';
1216 if (isset($CFG->blockeditingmenu) && !$CFG->blockeditingmenu) {
1217 $menu->do_not_enhance();
1219 return $this->render($menu);
1223 * Renders an action menu component.
1225 * ARIA references:
1226 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1227 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1229 * @param action_menu $menu
1230 * @return string HTML
1232 public function render_action_menu(action_menu $menu) {
1233 $menu->initialise_js($this->page);
1235 $output = html_writer::start_tag('div', $menu->attributes);
1236 $output .= html_writer::start_tag('ul', $menu->attributesprimary);
1237 foreach ($menu->get_primary_actions($this) as $action) {
1238 if ($action instanceof renderable) {
1239 $content = $this->render($action);
1240 } else {
1241 $content = $action;
1243 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1245 $output .= html_writer::end_tag('ul');
1246 $output .= html_writer::start_tag('ul', $menu->attributessecondary);
1247 foreach ($menu->get_secondary_actions() as $action) {
1248 if ($action instanceof renderable) {
1249 $content = $this->render($action);
1250 } else {
1251 $content = $action;
1253 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1255 $output .= html_writer::end_tag('ul');
1256 $output .= html_writer::end_tag('div');
1257 return $output;
1261 * Renders an action_menu_link item.
1263 * @param action_menu_link $action
1264 * @return string HTML fragment
1266 protected function render_action_menu_link(action_menu_link $action) {
1267 static $actioncount = 0;
1268 $actioncount++;
1270 $comparetoalt = '';
1271 $text = '';
1272 if (!$action->icon || $action->primary === false) {
1273 $text .= html_writer::start_tag('span', array('class'=>'menu-action-text', 'id' => 'actionmenuaction-'.$actioncount));
1274 if ($action->text instanceof renderable) {
1275 $text .= $this->render($action->text);
1276 } else {
1277 $text .= $action->text;
1278 $comparetoalt = (string)$action->text;
1280 $text .= html_writer::end_tag('span');
1283 $icon = '';
1284 if ($action->icon) {
1285 $icon = $action->icon;
1286 if ($action->primary || !$action->actionmenu->will_be_enhanced()) {
1287 $action->attributes['title'] = $action->text;
1289 if (!$action->primary && $action->actionmenu->will_be_enhanced()) {
1290 if ((string)$icon->attributes['alt'] === $comparetoalt) {
1291 $icon->attributes['alt'] = '';
1293 if (isset($icon->attributes['title']) && (string)$icon->attributes['title'] === $comparetoalt) {
1294 unset($icon->attributes['title']);
1297 $icon = $this->render($icon);
1300 // A disabled link is rendered as formatted text.
1301 if (!empty($action->attributes['disabled'])) {
1302 // Do not use div here due to nesting restriction in xhtml strict.
1303 return html_writer::tag('span', $icon.$text, array('class'=>'currentlink', 'role' => 'menuitem'));
1306 $attributes = $action->attributes;
1307 unset($action->attributes['disabled']);
1308 $attributes['href'] = $action->url;
1309 if ($text !== '') {
1310 $attributes['aria-labelledby'] = 'actionmenuaction-'.$actioncount;
1313 return html_writer::tag('a', $icon.$text, $attributes);
1317 * Renders a primary action_menu_filler item.
1319 * @param action_menu_link_filler $action
1320 * @return string HTML fragment
1322 protected function render_action_menu_filler(action_menu_filler $action) {
1323 return html_writer::span('&nbsp;', 'filler');
1327 * Renders a primary action_menu_link item.
1329 * @param action_menu_link_primary $action
1330 * @return string HTML fragment
1332 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1333 return $this->render_action_menu_link($action);
1337 * Renders a secondary action_menu_link item.
1339 * @param action_menu_link_secondary $action
1340 * @return string HTML fragment
1342 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1343 return $this->render_action_menu_link($action);
1347 * Prints a nice side block with an optional header.
1349 * The content is described
1350 * by a {@link core_renderer::block_contents} object.
1352 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1353 * <div class="header"></div>
1354 * <div class="content">
1355 * ...CONTENT...
1356 * <div class="footer">
1357 * </div>
1358 * </div>
1359 * <div class="annotation">
1360 * </div>
1361 * </div>
1363 * @param block_contents $bc HTML for the content
1364 * @param string $region the region the block is appearing in.
1365 * @return string the HTML to be output.
1367 public function block(block_contents $bc, $region) {
1368 $bc = clone($bc); // Avoid messing up the object passed in.
1369 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1370 $bc->collapsible = block_contents::NOT_HIDEABLE;
1372 if (!empty($bc->blockinstanceid)) {
1373 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1375 $skiptitle = strip_tags($bc->title);
1376 if ($bc->blockinstanceid && !empty($skiptitle)) {
1377 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1378 } else if (!empty($bc->arialabel)) {
1379 $bc->attributes['aria-label'] = $bc->arialabel;
1381 if ($bc->dockable) {
1382 $bc->attributes['data-dockable'] = 1;
1384 if ($bc->collapsible == block_contents::HIDDEN) {
1385 $bc->add_class('hidden');
1387 if (!empty($bc->controls)) {
1388 $bc->add_class('block_with_controls');
1392 if (empty($skiptitle)) {
1393 $output = '';
1394 $skipdest = '';
1395 } else {
1396 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
1397 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
1400 $output .= html_writer::start_tag('div', $bc->attributes);
1402 $output .= $this->block_header($bc);
1403 $output .= $this->block_content($bc);
1405 $output .= html_writer::end_tag('div');
1407 $output .= $this->block_annotation($bc);
1409 $output .= $skipdest;
1411 $this->init_block_hider_js($bc);
1412 return $output;
1416 * Produces a header for a block
1418 * @param block_contents $bc
1419 * @return string
1421 protected function block_header(block_contents $bc) {
1423 $title = '';
1424 if ($bc->title) {
1425 $attributes = array();
1426 if ($bc->blockinstanceid) {
1427 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1429 $title = html_writer::tag('h2', $bc->title, $attributes);
1432 $blockid = null;
1433 if (isset($bc->attributes['id'])) {
1434 $blockid = $bc->attributes['id'];
1436 $controlshtml = $this->block_controls($bc->controls, $blockid);
1438 $output = '';
1439 if ($title || $controlshtml) {
1440 $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'));
1442 return $output;
1446 * Produces the content area for a block
1448 * @param block_contents $bc
1449 * @return string
1451 protected function block_content(block_contents $bc) {
1452 $output = html_writer::start_tag('div', array('class' => 'content'));
1453 if (!$bc->title && !$this->block_controls($bc->controls)) {
1454 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1456 $output .= $bc->content;
1457 $output .= $this->block_footer($bc);
1458 $output .= html_writer::end_tag('div');
1460 return $output;
1464 * Produces the footer for a block
1466 * @param block_contents $bc
1467 * @return string
1469 protected function block_footer(block_contents $bc) {
1470 $output = '';
1471 if ($bc->footer) {
1472 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1474 return $output;
1478 * Produces the annotation for a block
1480 * @param block_contents $bc
1481 * @return string
1483 protected function block_annotation(block_contents $bc) {
1484 $output = '';
1485 if ($bc->annotation) {
1486 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1488 return $output;
1492 * Calls the JS require function to hide a block.
1494 * @param block_contents $bc A block_contents object
1496 protected function init_block_hider_js(block_contents $bc) {
1497 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1498 $config = new stdClass;
1499 $config->id = $bc->attributes['id'];
1500 $config->title = strip_tags($bc->title);
1501 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1502 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1503 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1505 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1506 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1511 * Render the contents of a block_list.
1513 * @param array $icons the icon for each item.
1514 * @param array $items the content of each item.
1515 * @return string HTML
1517 public function list_block_contents($icons, $items) {
1518 $row = 0;
1519 $lis = array();
1520 foreach ($items as $key => $string) {
1521 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1522 if (!empty($icons[$key])) { //test if the content has an assigned icon
1523 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1525 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1526 $item .= html_writer::end_tag('li');
1527 $lis[] = $item;
1528 $row = 1 - $row; // Flip even/odd.
1530 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1534 * Output all the blocks in a particular region.
1536 * @param string $region the name of a region on this page.
1537 * @return string the HTML to be output.
1539 public function blocks_for_region($region) {
1540 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1541 $blocks = $this->page->blocks->get_blocks_for_region($region);
1542 $lastblock = null;
1543 $zones = array();
1544 foreach ($blocks as $block) {
1545 $zones[] = $block->title;
1547 $output = '';
1549 foreach ($blockcontents as $bc) {
1550 if ($bc instanceof block_contents) {
1551 $output .= $this->block($bc, $region);
1552 $lastblock = $bc->title;
1553 } else if ($bc instanceof block_move_target) {
1554 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1555 } else {
1556 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1559 return $output;
1563 * Output a place where the block that is currently being moved can be dropped.
1565 * @param block_move_target $target with the necessary details.
1566 * @param array $zones array of areas where the block can be moved to
1567 * @param string $previous the block located before the area currently being rendered.
1568 * @param string $region the name of the region
1569 * @return string the HTML to be output.
1571 public function block_move_target($target, $zones, $previous, $region) {
1572 if ($previous == null) {
1573 if (empty($zones)) {
1574 // There are no zones, probably because there are no blocks.
1575 $regions = $this->page->theme->get_all_block_regions();
1576 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1577 } else {
1578 $position = get_string('moveblockbefore', 'block', $zones[0]);
1580 } else {
1581 $position = get_string('moveblockafter', 'block', $previous);
1583 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1587 * Renders a special html link with attached action
1589 * Theme developers: DO NOT OVERRIDE! Please override function
1590 * {@link core_renderer::render_action_link()} instead.
1592 * @param string|moodle_url $url
1593 * @param string $text HTML fragment
1594 * @param component_action $action
1595 * @param array $attributes associative array of html link attributes + disabled
1596 * @param pix_icon optional pix icon to render with the link
1597 * @return string HTML fragment
1599 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1600 if (!($url instanceof moodle_url)) {
1601 $url = new moodle_url($url);
1603 $link = new action_link($url, $text, $action, $attributes, $icon);
1605 return $this->render($link);
1609 * Renders an action_link object.
1611 * The provided link is renderer and the HTML returned. At the same time the
1612 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1614 * @param action_link $link
1615 * @return string HTML fragment
1617 protected function render_action_link(action_link $link) {
1618 global $CFG;
1620 $text = '';
1621 if ($link->icon) {
1622 $text .= $this->render($link->icon);
1625 if ($link->text instanceof renderable) {
1626 $text .= $this->render($link->text);
1627 } else {
1628 $text .= $link->text;
1631 // A disabled link is rendered as formatted text
1632 if (!empty($link->attributes['disabled'])) {
1633 // do not use div here due to nesting restriction in xhtml strict
1634 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1637 $attributes = $link->attributes;
1638 unset($link->attributes['disabled']);
1639 $attributes['href'] = $link->url;
1641 if ($link->actions) {
1642 if (empty($attributes['id'])) {
1643 $id = html_writer::random_id('action_link');
1644 $attributes['id'] = $id;
1645 } else {
1646 $id = $attributes['id'];
1648 foreach ($link->actions as $action) {
1649 $this->add_action_handler($action, $id);
1653 return html_writer::tag('a', $text, $attributes);
1658 * Renders an action_icon.
1660 * This function uses the {@link core_renderer::action_link()} method for the
1661 * most part. What it does different is prepare the icon as HTML and use it
1662 * as the link text.
1664 * Theme developers: If you want to change how action links and/or icons are rendered,
1665 * consider overriding function {@link core_renderer::render_action_link()} and
1666 * {@link core_renderer::render_pix_icon()}.
1668 * @param string|moodle_url $url A string URL or moodel_url
1669 * @param pix_icon $pixicon
1670 * @param component_action $action
1671 * @param array $attributes associative array of html link attributes + disabled
1672 * @param bool $linktext show title next to image in link
1673 * @return string HTML fragment
1675 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1676 if (!($url instanceof moodle_url)) {
1677 $url = new moodle_url($url);
1679 $attributes = (array)$attributes;
1681 if (empty($attributes['class'])) {
1682 // let ppl override the class via $options
1683 $attributes['class'] = 'action-icon';
1686 $icon = $this->render($pixicon);
1688 if ($linktext) {
1689 $text = $pixicon->attributes['alt'];
1690 } else {
1691 $text = '';
1694 return $this->action_link($url, $text.$icon, $action, $attributes);
1698 * Print a message along with button choices for Continue/Cancel
1700 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1702 * @param string $message The question to ask the user
1703 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1704 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1705 * @return string HTML fragment
1707 public function confirm($message, $continue, $cancel) {
1708 if ($continue instanceof single_button) {
1709 // ok
1710 } else if (is_string($continue)) {
1711 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1712 } else if ($continue instanceof moodle_url) {
1713 $continue = new single_button($continue, get_string('continue'), 'post');
1714 } else {
1715 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1718 if ($cancel instanceof single_button) {
1719 // ok
1720 } else if (is_string($cancel)) {
1721 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1722 } else if ($cancel instanceof moodle_url) {
1723 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1724 } else {
1725 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1728 $output = $this->box_start('generalbox', 'notice');
1729 $output .= html_writer::tag('p', $message);
1730 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1731 $output .= $this->box_end();
1732 return $output;
1736 * Returns a form with a single button.
1738 * Theme developers: DO NOT OVERRIDE! Please override function
1739 * {@link core_renderer::render_single_button()} instead.
1741 * @param string|moodle_url $url
1742 * @param string $label button text
1743 * @param string $method get or post submit method
1744 * @param array $options associative array {disabled, title, etc.}
1745 * @return string HTML fragment
1747 public function single_button($url, $label, $method='post', array $options=null) {
1748 if (!($url instanceof moodle_url)) {
1749 $url = new moodle_url($url);
1751 $button = new single_button($url, $label, $method);
1753 foreach ((array)$options as $key=>$value) {
1754 if (array_key_exists($key, $button)) {
1755 $button->$key = $value;
1759 return $this->render($button);
1763 * Renders a single button widget.
1765 * This will return HTML to display a form containing a single button.
1767 * @param single_button $button
1768 * @return string HTML fragment
1770 protected function render_single_button(single_button $button) {
1771 $attributes = array('type' => 'submit',
1772 'value' => $button->label,
1773 'disabled' => $button->disabled ? 'disabled' : null,
1774 'title' => $button->tooltip);
1776 if ($button->actions) {
1777 $id = html_writer::random_id('single_button');
1778 $attributes['id'] = $id;
1779 foreach ($button->actions as $action) {
1780 $this->add_action_handler($action, $id);
1784 // first the input element
1785 $output = html_writer::empty_tag('input', $attributes);
1787 // then hidden fields
1788 $params = $button->url->params();
1789 if ($button->method === 'post') {
1790 $params['sesskey'] = sesskey();
1792 foreach ($params as $var => $val) {
1793 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1796 // then div wrapper for xhtml strictness
1797 $output = html_writer::tag('div', $output);
1799 // now the form itself around it
1800 if ($button->method === 'get') {
1801 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1802 } else {
1803 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1805 if ($url === '') {
1806 $url = '#'; // there has to be always some action
1808 $attributes = array('method' => $button->method,
1809 'action' => $url,
1810 'id' => $button->formid);
1811 $output = html_writer::tag('form', $output, $attributes);
1813 // and finally one more wrapper with class
1814 return html_writer::tag('div', $output, array('class' => $button->class));
1818 * Returns a form with a single select widget.
1820 * Theme developers: DO NOT OVERRIDE! Please override function
1821 * {@link core_renderer::render_single_select()} instead.
1823 * @param moodle_url $url form action target, includes hidden fields
1824 * @param string $name name of selection field - the changing parameter in url
1825 * @param array $options list of options
1826 * @param string $selected selected element
1827 * @param array $nothing
1828 * @param string $formid
1829 * @param array $attributes other attributes for the single select
1830 * @return string HTML fragment
1832 public function single_select($url, $name, array $options, $selected = '',
1833 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
1834 if (!($url instanceof moodle_url)) {
1835 $url = new moodle_url($url);
1837 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1839 if (array_key_exists('label', $attributes)) {
1840 $select->set_label($attributes['label']);
1841 unset($attributes['label']);
1843 $select->attributes = $attributes;
1845 return $this->render($select);
1849 * Internal implementation of single_select rendering
1851 * @param single_select $select
1852 * @return string HTML fragment
1854 protected function render_single_select(single_select $select) {
1855 $select = clone($select);
1856 if (empty($select->formid)) {
1857 $select->formid = html_writer::random_id('single_select_f');
1860 $output = '';
1861 $params = $select->url->params();
1862 if ($select->method === 'post') {
1863 $params['sesskey'] = sesskey();
1865 foreach ($params as $name=>$value) {
1866 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1869 if (empty($select->attributes['id'])) {
1870 $select->attributes['id'] = html_writer::random_id('single_select');
1873 if ($select->disabled) {
1874 $select->attributes['disabled'] = 'disabled';
1877 if ($select->tooltip) {
1878 $select->attributes['title'] = $select->tooltip;
1881 $select->attributes['class'] = 'autosubmit';
1882 if ($select->class) {
1883 $select->attributes['class'] .= ' ' . $select->class;
1886 if ($select->label) {
1887 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1890 if ($select->helpicon instanceof help_icon) {
1891 $output .= $this->render($select->helpicon);
1893 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1895 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1896 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1898 $nothing = empty($select->nothing) ? false : key($select->nothing);
1899 $this->page->requires->yui_module('moodle-core-formautosubmit',
1900 'M.core.init_formautosubmit',
1901 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1904 // then div wrapper for xhtml strictness
1905 $output = html_writer::tag('div', $output);
1907 // now the form itself around it
1908 if ($select->method === 'get') {
1909 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1910 } else {
1911 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1913 $formattributes = array('method' => $select->method,
1914 'action' => $url,
1915 'id' => $select->formid);
1916 $output = html_writer::tag('form', $output, $formattributes);
1918 // and finally one more wrapper with class
1919 return html_writer::tag('div', $output, array('class' => $select->class));
1923 * Returns a form with a url select widget.
1925 * Theme developers: DO NOT OVERRIDE! Please override function
1926 * {@link core_renderer::render_url_select()} instead.
1928 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1929 * @param string $selected selected element
1930 * @param array $nothing
1931 * @param string $formid
1932 * @return string HTML fragment
1934 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1935 $select = new url_select($urls, $selected, $nothing, $formid);
1936 return $this->render($select);
1940 * Internal implementation of url_select rendering
1942 * @param url_select $select
1943 * @return string HTML fragment
1945 protected function render_url_select(url_select $select) {
1946 global $CFG;
1948 $select = clone($select);
1949 if (empty($select->formid)) {
1950 $select->formid = html_writer::random_id('url_select_f');
1953 if (empty($select->attributes['id'])) {
1954 $select->attributes['id'] = html_writer::random_id('url_select');
1957 if ($select->disabled) {
1958 $select->attributes['disabled'] = 'disabled';
1961 if ($select->tooltip) {
1962 $select->attributes['title'] = $select->tooltip;
1965 $output = '';
1967 if ($select->label) {
1968 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1971 $classes = array();
1972 if (!$select->showbutton) {
1973 $classes[] = 'autosubmit';
1975 if ($select->class) {
1976 $classes[] = $select->class;
1978 if (count($classes)) {
1979 $select->attributes['class'] = implode(' ', $classes);
1982 if ($select->helpicon instanceof help_icon) {
1983 $output .= $this->render($select->helpicon);
1986 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1987 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1988 $urls = array();
1989 foreach ($select->urls as $k=>$v) {
1990 if (is_array($v)) {
1991 // optgroup structure
1992 foreach ($v as $optgrouptitle => $optgroupoptions) {
1993 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1994 if (empty($optionurl)) {
1995 $safeoptionurl = '';
1996 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1997 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1998 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1999 } else if (strpos($optionurl, '/') !== 0) {
2000 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
2001 continue;
2002 } else {
2003 $safeoptionurl = $optionurl;
2005 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
2008 } else {
2009 // plain list structure
2010 if (empty($k)) {
2011 // nothing selected option
2012 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
2013 $k = str_replace($CFG->wwwroot, '', $k);
2014 } else if (strpos($k, '/') !== 0) {
2015 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
2016 continue;
2018 $urls[$k] = $v;
2021 $selected = $select->selected;
2022 if (!empty($selected)) {
2023 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
2024 $selected = str_replace($CFG->wwwroot, '', $selected);
2025 } else if (strpos($selected, '/') !== 0) {
2026 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
2030 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
2031 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
2033 if (!$select->showbutton) {
2034 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
2035 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
2036 $nothing = empty($select->nothing) ? false : key($select->nothing);
2037 $this->page->requires->yui_module('moodle-core-formautosubmit',
2038 'M.core.init_formautosubmit',
2039 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
2041 } else {
2042 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
2045 // then div wrapper for xhtml strictness
2046 $output = html_writer::tag('div', $output);
2048 // now the form itself around it
2049 $formattributes = array('method' => 'post',
2050 'action' => new moodle_url('/course/jumpto.php'),
2051 'id' => $select->formid);
2052 $output = html_writer::tag('form', $output, $formattributes);
2054 // and finally one more wrapper with class
2055 return html_writer::tag('div', $output, array('class' => $select->class));
2059 * Returns a string containing a link to the user documentation.
2060 * Also contains an icon by default. Shown to teachers and admin only.
2062 * @param string $path The page link after doc root and language, no leading slash.
2063 * @param string $text The text to be displayed for the link
2064 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2065 * @return string
2067 public function doc_link($path, $text = '', $forcepopup = false) {
2068 global $CFG;
2070 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2072 $url = new moodle_url(get_docs_url($path));
2074 $attributes = array('href'=>$url);
2075 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2076 $attributes['class'] = 'helplinkpopup';
2079 return html_writer::tag('a', $icon.$text, $attributes);
2083 * Return HTML for a pix_icon.
2085 * Theme developers: DO NOT OVERRIDE! Please override function
2086 * {@link core_renderer::render_pix_icon()} instead.
2088 * @param string $pix short pix name
2089 * @param string $alt mandatory alt attribute
2090 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2091 * @param array $attributes htm lattributes
2092 * @return string HTML fragment
2094 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2095 $icon = new pix_icon($pix, $alt, $component, $attributes);
2096 return $this->render($icon);
2100 * Renders a pix_icon widget and returns the HTML to display it.
2102 * @param pix_icon $icon
2103 * @return string HTML fragment
2105 protected function render_pix_icon(pix_icon $icon) {
2106 $data = $icon->export_for_template($this);
2107 return $this->render_from_template('core/pix_icon', $data);
2111 * Return HTML to display an emoticon icon.
2113 * @param pix_emoticon $emoticon
2114 * @return string HTML fragment
2116 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2117 $attributes = $emoticon->attributes;
2118 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
2119 return html_writer::empty_tag('img', $attributes);
2123 * Produces the html that represents this rating in the UI
2125 * @param rating $rating the page object on which this rating will appear
2126 * @return string
2128 function render_rating(rating $rating) {
2129 global $CFG, $USER;
2131 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2132 return null;//ratings are turned off
2135 $ratingmanager = new rating_manager();
2136 // Initialise the JavaScript so ratings can be done by AJAX.
2137 $ratingmanager->initialise_rating_javascript($this->page);
2139 $strrate = get_string("rate", "rating");
2140 $ratinghtml = ''; //the string we'll return
2142 // permissions check - can they view the aggregate?
2143 if ($rating->user_can_view_aggregate()) {
2145 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2146 $aggregatestr = $rating->get_aggregate_string();
2148 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2149 if ($rating->count > 0) {
2150 $countstr = "({$rating->count})";
2151 } else {
2152 $countstr = '-';
2154 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2156 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2157 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2159 $nonpopuplink = $rating->get_view_ratings_url();
2160 $popuplink = $rating->get_view_ratings_url(true);
2162 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2163 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2164 } else {
2165 $ratinghtml .= $aggregatehtml;
2169 $formstart = null;
2170 // if the item doesn't belong to the current user, the user has permission to rate
2171 // and we're within the assessable period
2172 if ($rating->user_can_rate()) {
2174 $rateurl = $rating->get_rate_url();
2175 $inputs = $rateurl->params();
2177 //start the rating form
2178 $formattrs = array(
2179 'id' => "postrating{$rating->itemid}",
2180 'class' => 'postratingform',
2181 'method' => 'post',
2182 'action' => $rateurl->out_omit_querystring()
2184 $formstart = html_writer::start_tag('form', $formattrs);
2185 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2187 // add the hidden inputs
2188 foreach ($inputs as $name => $value) {
2189 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2190 $formstart .= html_writer::empty_tag('input', $attributes);
2193 if (empty($ratinghtml)) {
2194 $ratinghtml .= $strrate.': ';
2196 $ratinghtml = $formstart.$ratinghtml;
2198 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2199 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2200 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2201 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2203 //output submit button
2204 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2206 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2207 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2209 if (!$rating->settings->scale->isnumeric) {
2210 // If a global scale, try to find current course ID from the context
2211 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2212 $courseid = $coursecontext->instanceid;
2213 } else {
2214 $courseid = $rating->settings->scale->courseid;
2216 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2218 $ratinghtml .= html_writer::end_tag('span');
2219 $ratinghtml .= html_writer::end_tag('div');
2220 $ratinghtml .= html_writer::end_tag('form');
2223 return $ratinghtml;
2227 * Centered heading with attached help button (same title text)
2228 * and optional icon attached.
2230 * @param string $text A heading text
2231 * @param string $helpidentifier The keyword that defines a help page
2232 * @param string $component component name
2233 * @param string|moodle_url $icon
2234 * @param string $iconalt icon alt text
2235 * @param int $level The level of importance of the heading. Defaulting to 2
2236 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2237 * @return string HTML fragment
2239 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2240 $image = '';
2241 if ($icon) {
2242 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2245 $help = '';
2246 if ($helpidentifier) {
2247 $help = $this->help_icon($helpidentifier, $component);
2250 return $this->heading($image.$text.$help, $level, $classnames);
2254 * Returns HTML to display a help icon.
2256 * @deprecated since Moodle 2.0
2258 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2259 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2263 * Returns HTML to display a help icon.
2265 * Theme developers: DO NOT OVERRIDE! Please override function
2266 * {@link core_renderer::render_help_icon()} instead.
2268 * @param string $identifier The keyword that defines a help page
2269 * @param string $component component name
2270 * @param string|bool $linktext true means use $title as link text, string means link text value
2271 * @return string HTML fragment
2273 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2274 $icon = new help_icon($identifier, $component);
2275 $icon->diag_strings();
2276 if ($linktext === true) {
2277 $icon->linktext = get_string($icon->identifier, $icon->component);
2278 } else if (!empty($linktext)) {
2279 $icon->linktext = $linktext;
2281 return $this->render($icon);
2285 * Implementation of user image rendering.
2287 * @param help_icon $helpicon A help icon instance
2288 * @return string HTML fragment
2290 protected function render_help_icon(help_icon $helpicon) {
2291 global $CFG;
2293 // first get the help image icon
2294 $src = $this->pix_url('help');
2296 $title = get_string($helpicon->identifier, $helpicon->component);
2298 if (empty($helpicon->linktext)) {
2299 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
2300 } else {
2301 $alt = get_string('helpwiththis');
2304 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
2305 $output = html_writer::empty_tag('img', $attributes);
2307 // add the link text if given
2308 if (!empty($helpicon->linktext)) {
2309 // the spacing has to be done through CSS
2310 $output .= $helpicon->linktext;
2313 // now create the link around it - we need https on loginhttps pages
2314 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
2316 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
2317 $title = get_string('helpprefix2', '', trim($title, ". \t"));
2319 $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true', 'target'=>'_blank');
2320 $output = html_writer::tag('a', $output, $attributes);
2322 // and finally span
2323 return html_writer::tag('span', $output, array('class' => 'helptooltip'));
2327 * Returns HTML to display a scale help icon.
2329 * @param int $courseid
2330 * @param stdClass $scale instance
2331 * @return string HTML fragment
2333 public function help_icon_scale($courseid, stdClass $scale) {
2334 global $CFG;
2336 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2338 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2340 $scaleid = abs($scale->id);
2342 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2343 $action = new popup_action('click', $link, 'ratingscale');
2345 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2349 * Creates and returns a spacer image with optional line break.
2351 * @param array $attributes Any HTML attributes to add to the spaced.
2352 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2353 * laxy do it with CSS which is a much better solution.
2354 * @return string HTML fragment
2356 public function spacer(array $attributes = null, $br = false) {
2357 $attributes = (array)$attributes;
2358 if (empty($attributes['width'])) {
2359 $attributes['width'] = 1;
2361 if (empty($attributes['height'])) {
2362 $attributes['height'] = 1;
2364 $attributes['class'] = 'spacer';
2366 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2368 if (!empty($br)) {
2369 $output .= '<br />';
2372 return $output;
2376 * Returns HTML to display the specified user's avatar.
2378 * User avatar may be obtained in two ways:
2379 * <pre>
2380 * // Option 1: (shortcut for simple cases, preferred way)
2381 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2382 * $OUTPUT->user_picture($user, array('popup'=>true));
2384 * // Option 2:
2385 * $userpic = new user_picture($user);
2386 * // Set properties of $userpic
2387 * $userpic->popup = true;
2388 * $OUTPUT->render($userpic);
2389 * </pre>
2391 * Theme developers: DO NOT OVERRIDE! Please override function
2392 * {@link core_renderer::render_user_picture()} instead.
2394 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2395 * If any of these are missing, the database is queried. Avoid this
2396 * if at all possible, particularly for reports. It is very bad for performance.
2397 * @param array $options associative array with user picture options, used only if not a user_picture object,
2398 * options are:
2399 * - courseid=$this->page->course->id (course id of user profile in link)
2400 * - size=35 (size of image)
2401 * - link=true (make image clickable - the link leads to user profile)
2402 * - popup=false (open in popup)
2403 * - alttext=true (add image alt attribute)
2404 * - class = image class attribute (default 'userpicture')
2405 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2406 * @return string HTML fragment
2408 public function user_picture(stdClass $user, array $options = null) {
2409 $userpicture = new user_picture($user);
2410 foreach ((array)$options as $key=>$value) {
2411 if (array_key_exists($key, $userpicture)) {
2412 $userpicture->$key = $value;
2415 return $this->render($userpicture);
2419 * Internal implementation of user image rendering.
2421 * @param user_picture $userpicture
2422 * @return string
2424 protected function render_user_picture(user_picture $userpicture) {
2425 global $CFG, $DB;
2427 $user = $userpicture->user;
2429 if ($userpicture->alttext) {
2430 if (!empty($user->imagealt)) {
2431 $alt = $user->imagealt;
2432 } else {
2433 $alt = get_string('pictureof', '', fullname($user));
2435 } else {
2436 $alt = '';
2439 if (empty($userpicture->size)) {
2440 $size = 35;
2441 } else if ($userpicture->size === true or $userpicture->size == 1) {
2442 $size = 100;
2443 } else {
2444 $size = $userpicture->size;
2447 $class = $userpicture->class;
2449 if ($user->picture == 0) {
2450 $class .= ' defaultuserpic';
2453 $src = $userpicture->get_url($this->page, $this);
2455 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2456 if (!$userpicture->visibletoscreenreaders) {
2457 $attributes['role'] = 'presentation';
2460 // get the image html output fisrt
2461 $output = html_writer::empty_tag('img', $attributes);
2463 // then wrap it in link if needed
2464 if (!$userpicture->link) {
2465 return $output;
2468 if (empty($userpicture->courseid)) {
2469 $courseid = $this->page->course->id;
2470 } else {
2471 $courseid = $userpicture->courseid;
2474 if ($courseid == SITEID) {
2475 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2476 } else {
2477 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2480 $attributes = array('href'=>$url);
2481 if (!$userpicture->visibletoscreenreaders) {
2482 $attributes['tabindex'] = '-1';
2483 $attributes['aria-hidden'] = 'true';
2486 if ($userpicture->popup) {
2487 $id = html_writer::random_id('userpicture');
2488 $attributes['id'] = $id;
2489 $this->add_action_handler(new popup_action('click', $url), $id);
2492 return html_writer::tag('a', $output, $attributes);
2496 * Internal implementation of file tree viewer items rendering.
2498 * @param array $dir
2499 * @return string
2501 public function htmllize_file_tree($dir) {
2502 if (empty($dir['subdirs']) and empty($dir['files'])) {
2503 return '';
2505 $result = '<ul>';
2506 foreach ($dir['subdirs'] as $subdir) {
2507 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2509 foreach ($dir['files'] as $file) {
2510 $filename = $file->get_filename();
2511 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2513 $result .= '</ul>';
2515 return $result;
2519 * Returns HTML to display the file picker
2521 * <pre>
2522 * $OUTPUT->file_picker($options);
2523 * </pre>
2525 * Theme developers: DO NOT OVERRIDE! Please override function
2526 * {@link core_renderer::render_file_picker()} instead.
2528 * @param array $options associative array with file manager options
2529 * options are:
2530 * maxbytes=>-1,
2531 * itemid=>0,
2532 * client_id=>uniqid(),
2533 * acepted_types=>'*',
2534 * return_types=>FILE_INTERNAL,
2535 * context=>$PAGE->context
2536 * @return string HTML fragment
2538 public function file_picker($options) {
2539 $fp = new file_picker($options);
2540 return $this->render($fp);
2544 * Internal implementation of file picker rendering.
2546 * @param file_picker $fp
2547 * @return string
2549 public function render_file_picker(file_picker $fp) {
2550 global $CFG, $OUTPUT, $USER;
2551 $options = $fp->options;
2552 $client_id = $options->client_id;
2553 $strsaved = get_string('filesaved', 'repository');
2554 $straddfile = get_string('openpicker', 'repository');
2555 $strloading = get_string('loading', 'repository');
2556 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2557 $strdroptoupload = get_string('droptoupload', 'moodle');
2558 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2560 $currentfile = $options->currentfile;
2561 if (empty($currentfile)) {
2562 $currentfile = '';
2563 } else {
2564 $currentfile .= ' - ';
2566 if ($options->maxbytes) {
2567 $size = $options->maxbytes;
2568 } else {
2569 $size = get_max_upload_file_size();
2571 if ($size == -1) {
2572 $maxsize = '';
2573 } else {
2574 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2576 if ($options->buttonname) {
2577 $buttonname = ' name="' . $options->buttonname . '"';
2578 } else {
2579 $buttonname = '';
2581 $html = <<<EOD
2582 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2583 $icon_progress
2584 </div>
2585 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2586 <div>
2587 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2588 <span> $maxsize </span>
2589 </div>
2590 EOD;
2591 if ($options->env != 'url') {
2592 $html .= <<<EOD
2593 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2594 <div class="filepicker-filename">
2595 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2596 <div class="dndupload-progressbars"></div>
2597 </div>
2598 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2599 </div>
2600 EOD;
2602 $html .= '</div>';
2603 return $html;
2607 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2609 * @param string $cmid the course_module id.
2610 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2611 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2613 public function update_module_button($cmid, $modulename) {
2614 global $CFG;
2615 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2616 $modulename = get_string('modulename', $modulename);
2617 $string = get_string('updatethis', '', $modulename);
2618 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2619 return $this->single_button($url, $string);
2620 } else {
2621 return '';
2626 * Returns HTML to display a "Turn editing on/off" button in a form.
2628 * @param moodle_url $url The URL + params to send through when clicking the button
2629 * @return string HTML the button
2631 public function edit_button(moodle_url $url) {
2633 $url->param('sesskey', sesskey());
2634 if ($this->page->user_is_editing()) {
2635 $url->param('edit', 'off');
2636 $editstring = get_string('turneditingoff');
2637 } else {
2638 $url->param('edit', 'on');
2639 $editstring = get_string('turneditingon');
2642 return $this->single_button($url, $editstring);
2646 * Returns HTML to display a simple button to close a window
2648 * @param string $text The lang string for the button's label (already output from get_string())
2649 * @return string html fragment
2651 public function close_window_button($text='') {
2652 if (empty($text)) {
2653 $text = get_string('closewindow');
2655 $button = new single_button(new moodle_url('#'), $text, 'get');
2656 $button->add_action(new component_action('click', 'close_window'));
2658 return $this->container($this->render($button), 'closewindow');
2662 * Output an error message. By default wraps the error message in <span class="error">.
2663 * If the error message is blank, nothing is output.
2665 * @param string $message the error message.
2666 * @return string the HTML to output.
2668 public function error_text($message) {
2669 if (empty($message)) {
2670 return '';
2672 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2673 return html_writer::tag('span', $message, array('class' => 'error'));
2677 * Do not call this function directly.
2679 * To terminate the current script with a fatal error, call the {@link print_error}
2680 * function, or throw an exception. Doing either of those things will then call this
2681 * function to display the error, before terminating the execution.
2683 * @param string $message The message to output
2684 * @param string $moreinfourl URL where more info can be found about the error
2685 * @param string $link Link for the Continue button
2686 * @param array $backtrace The execution backtrace
2687 * @param string $debuginfo Debugging information
2688 * @return string the HTML to output.
2690 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2691 global $CFG;
2693 $output = '';
2694 $obbuffer = '';
2696 if ($this->has_started()) {
2697 // we can not always recover properly here, we have problems with output buffering,
2698 // html tables, etc.
2699 $output .= $this->opencontainers->pop_all_but_last();
2701 } else {
2702 // It is really bad if library code throws exception when output buffering is on,
2703 // because the buffered text would be printed before our start of page.
2704 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2705 error_reporting(0); // disable notices from gzip compression, etc.
2706 while (ob_get_level() > 0) {
2707 $buff = ob_get_clean();
2708 if ($buff === false) {
2709 break;
2711 $obbuffer .= $buff;
2713 error_reporting($CFG->debug);
2715 // Output not yet started.
2716 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2717 if (empty($_SERVER['HTTP_RANGE'])) {
2718 @header($protocol . ' 404 Not Found');
2719 } else {
2720 // Must stop byteserving attempts somehow,
2721 // this is weird but Chrome PDF viewer can be stopped only with 407!
2722 @header($protocol . ' 407 Proxy Authentication Required');
2725 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2726 $this->page->set_url('/'); // no url
2727 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2728 $this->page->set_title(get_string('error'));
2729 $this->page->set_heading($this->page->course->fullname);
2730 $output .= $this->header();
2733 $message = '<p class="errormessage">' . $message . '</p>'.
2734 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2735 get_string('moreinformation') . '</a></p>';
2736 if (empty($CFG->rolesactive)) {
2737 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2738 //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.
2740 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
2742 if ($CFG->debugdeveloper) {
2743 if (!empty($debuginfo)) {
2744 $debuginfo = s($debuginfo); // removes all nasty JS
2745 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2746 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2748 if (!empty($backtrace)) {
2749 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2751 if ($obbuffer !== '' ) {
2752 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2756 if (empty($CFG->rolesactive)) {
2757 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2758 } else if (!empty($link)) {
2759 $output .= $this->continue_button($link);
2762 $output .= $this->footer();
2764 // Padding to encourage IE to display our error page, rather than its own.
2765 $output .= str_repeat(' ', 512);
2767 return $output;
2771 * Output a notification (that is, a status message about something that has
2772 * just happened).
2774 * @param string $message the message to print out
2775 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2776 * @return string the HTML to output.
2778 public function notification($message, $classes = 'notifyproblem') {
2780 $classmappings = array(
2781 'notifyproblem' => \core\output\notification::NOTIFY_PROBLEM,
2782 'notifytiny' => \core\output\notification::NOTIFY_PROBLEM,
2783 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2784 'notifymessage' => \core\output\notification::NOTIFY_MESSAGE,
2785 'redirectmessage' => \core\output\notification::NOTIFY_REDIRECT
2788 // Identify what type of notification this is.
2789 $type = \core\output\notification::NOTIFY_PROBLEM;
2790 $classarray = explode(' ', self::prepare_classes($classes));
2791 if (count($classarray) > 0) {
2792 foreach ($classarray as $class) {
2793 if (isset($classmappings[$class])) {
2794 $type = $classmappings[$class];
2795 break;
2800 $n = new \core\output\notification($message, $type);
2801 return $this->render($n);
2806 * Output a notification at a particular level - in this case, NOTIFY_PROBLEM.
2808 * @param string $message the message to print out
2809 * @return string HTML fragment.
2811 public function notify_problem($message) {
2812 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_PROBLEM);
2813 return $this->render($n);
2817 * Output a notification at a particular level - in this case, NOTIFY_SUCCESS.
2819 * @param string $message the message to print out
2820 * @return string HTML fragment.
2822 public function notify_success($message) {
2823 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_SUCCESS);
2824 return $this->render($n);
2828 * Output a notification at a particular level - in this case, NOTIFY_MESSAGE.
2830 * @param string $message the message to print out
2831 * @return string HTML fragment.
2833 public function notify_message($message) {
2834 $n = new notification($message, notification::NOTIFY_MESSAGE);
2835 return $this->render($n);
2839 * Output a notification at a particular level - in this case, NOTIFY_REDIRECT.
2841 * @param string $message the message to print out
2842 * @return string HTML fragment.
2844 public function notify_redirect($message) {
2845 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_REDIRECT);
2846 return $this->render($n);
2850 * Render a notification (that is, a status message about something that has
2851 * just happened).
2853 * @param \core\output\notification $notification the notification to print out
2854 * @return string the HTML to output.
2856 protected function render_notification(\core\output\notification $notification) {
2858 $data = $notification->export_for_template($this);
2860 $templatename = '';
2861 switch($data->type) {
2862 case \core\output\notification::NOTIFY_MESSAGE:
2863 $templatename = 'core/notification_message';
2864 break;
2865 case \core\output\notification::NOTIFY_SUCCESS:
2866 $templatename = 'core/notification_success';
2867 break;
2868 case \core\output\notification::NOTIFY_PROBLEM:
2869 $templatename = 'core/notification_problem';
2870 break;
2871 case \core\output\notification::NOTIFY_REDIRECT:
2872 $templatename = 'core/notification_redirect';
2873 break;
2874 default:
2875 $templatename = 'core/notification_message';
2876 break;
2879 return self::render_from_template($templatename, $data);
2884 * Returns HTML to display a continue button that goes to a particular URL.
2886 * @param string|moodle_url $url The url the button goes to.
2887 * @return string the HTML to output.
2889 public function continue_button($url) {
2890 if (!($url instanceof moodle_url)) {
2891 $url = new moodle_url($url);
2893 $button = new single_button($url, get_string('continue'), 'get');
2894 $button->class = 'continuebutton';
2896 return $this->render($button);
2900 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2902 * Theme developers: DO NOT OVERRIDE! Please override function
2903 * {@link core_renderer::render_paging_bar()} instead.
2905 * @param int $totalcount The total number of entries available to be paged through
2906 * @param int $page The page you are currently viewing
2907 * @param int $perpage The number of entries that should be shown per page
2908 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2909 * @param string $pagevar name of page parameter that holds the page number
2910 * @return string the HTML to output.
2912 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2913 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2914 return $this->render($pb);
2918 * Internal implementation of paging bar rendering.
2920 * @param paging_bar $pagingbar
2921 * @return string
2923 protected function render_paging_bar(paging_bar $pagingbar) {
2924 $output = '';
2925 $pagingbar = clone($pagingbar);
2926 $pagingbar->prepare($this, $this->page, $this->target);
2928 if ($pagingbar->totalcount > $pagingbar->perpage) {
2929 $output .= get_string('page') . ':';
2931 if (!empty($pagingbar->previouslink)) {
2932 $output .= ' (' . $pagingbar->previouslink . ') ';
2935 if (!empty($pagingbar->firstlink)) {
2936 $output .= ' ' . $pagingbar->firstlink . ' ...';
2939 foreach ($pagingbar->pagelinks as $link) {
2940 $output .= " $link";
2943 if (!empty($pagingbar->lastlink)) {
2944 $output .= ' ...' . $pagingbar->lastlink . ' ';
2947 if (!empty($pagingbar->nextlink)) {
2948 $output .= ' (' . $pagingbar->nextlink . ')';
2952 return html_writer::tag('div', $output, array('class' => 'paging'));
2956 * Output the place a skip link goes to.
2958 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2959 * @return string the HTML to output.
2961 public function skip_link_target($id = null) {
2962 return html_writer::tag('span', '', array('id' => $id));
2966 * Outputs a heading
2968 * @param string $text The text of the heading
2969 * @param int $level The level of importance of the heading. Defaulting to 2
2970 * @param string $classes A space-separated list of CSS classes. Defaulting to null
2971 * @param string $id An optional ID
2972 * @return string the HTML to output.
2974 public function heading($text, $level = 2, $classes = null, $id = null) {
2975 $level = (integer) $level;
2976 if ($level < 1 or $level > 6) {
2977 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2979 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2983 * Outputs a box.
2985 * @param string $contents The contents of the box
2986 * @param string $classes A space-separated list of CSS classes
2987 * @param string $id An optional ID
2988 * @param array $attributes An array of other attributes to give the box.
2989 * @return string the HTML to output.
2991 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
2992 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
2996 * Outputs the opening section of a box.
2998 * @param string $classes A space-separated list of CSS classes
2999 * @param string $id An optional ID
3000 * @param array $attributes An array of other attributes to give the box.
3001 * @return string the HTML to output.
3003 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3004 $this->opencontainers->push('box', html_writer::end_tag('div'));
3005 $attributes['id'] = $id;
3006 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
3007 return html_writer::start_tag('div', $attributes);
3011 * Outputs the closing section of a box.
3013 * @return string the HTML to output.
3015 public function box_end() {
3016 return $this->opencontainers->pop('box');
3020 * Outputs a container.
3022 * @param string $contents The contents of the box
3023 * @param string $classes A space-separated list of CSS classes
3024 * @param string $id An optional ID
3025 * @return string the HTML to output.
3027 public function container($contents, $classes = null, $id = null) {
3028 return $this->container_start($classes, $id) . $contents . $this->container_end();
3032 * Outputs the opening section of a container.
3034 * @param string $classes A space-separated list of CSS classes
3035 * @param string $id An optional ID
3036 * @return string the HTML to output.
3038 public function container_start($classes = null, $id = null) {
3039 $this->opencontainers->push('container', html_writer::end_tag('div'));
3040 return html_writer::start_tag('div', array('id' => $id,
3041 'class' => renderer_base::prepare_classes($classes)));
3045 * Outputs the closing section of a container.
3047 * @return string the HTML to output.
3049 public function container_end() {
3050 return $this->opencontainers->pop('container');
3054 * Make nested HTML lists out of the items
3056 * The resulting list will look something like this:
3058 * <pre>
3059 * <<ul>>
3060 * <<li>><div class='tree_item parent'>(item contents)</div>
3061 * <<ul>
3062 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3063 * <</ul>>
3064 * <</li>>
3065 * <</ul>>
3066 * </pre>
3068 * @param array $items
3069 * @param array $attrs html attributes passed to the top ofs the list
3070 * @return string HTML
3072 public function tree_block_contents($items, $attrs = array()) {
3073 // exit if empty, we don't want an empty ul element
3074 if (empty($items)) {
3075 return '';
3077 // array of nested li elements
3078 $lis = array();
3079 foreach ($items as $item) {
3080 // this applies to the li item which contains all child lists too
3081 $content = $item->content($this);
3082 $liclasses = array($item->get_css_type());
3083 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3084 $liclasses[] = 'collapsed';
3086 if ($item->isactive === true) {
3087 $liclasses[] = 'current_branch';
3089 $liattr = array('class'=>join(' ',$liclasses));
3090 // class attribute on the div item which only contains the item content
3091 $divclasses = array('tree_item');
3092 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3093 $divclasses[] = 'branch';
3094 } else {
3095 $divclasses[] = 'leaf';
3097 if (!empty($item->classes) && count($item->classes)>0) {
3098 $divclasses[] = join(' ', $item->classes);
3100 $divattr = array('class'=>join(' ', $divclasses));
3101 if (!empty($item->id)) {
3102 $divattr['id'] = $item->id;
3104 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3105 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3106 $content = html_writer::empty_tag('hr') . $content;
3108 $content = html_writer::tag('li', $content, $liattr);
3109 $lis[] = $content;
3111 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3115 * Construct a user menu, returning HTML that can be echoed out by a
3116 * layout file.
3118 * @param stdClass $user A user object, usually $USER.
3119 * @param bool $withlinks true if a dropdown should be built.
3120 * @return string HTML fragment.
3122 public function user_menu($user = null, $withlinks = null) {
3123 global $USER, $CFG;
3124 require_once($CFG->dirroot . '/user/lib.php');
3126 if (is_null($user)) {
3127 $user = $USER;
3130 // Note: this behaviour is intended to match that of core_renderer::login_info,
3131 // but should not be considered to be good practice; layout options are
3132 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3133 if (is_null($withlinks)) {
3134 $withlinks = empty($this->page->layout_options['nologinlinks']);
3137 // Add a class for when $withlinks is false.
3138 $usermenuclasses = 'usermenu';
3139 if (!$withlinks) {
3140 $usermenuclasses .= ' withoutlinks';
3143 $returnstr = "";
3145 // If during initial install, return the empty return string.
3146 if (during_initial_install()) {
3147 return $returnstr;
3150 $loginpage = $this->is_login_page();
3151 $loginurl = get_login_url();
3152 // If not logged in, show the typical not-logged-in string.
3153 if (!isloggedin()) {
3154 $returnstr = get_string('loggedinnot', 'moodle');
3155 if (!$loginpage) {
3156 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3158 return html_writer::div(
3159 html_writer::span(
3160 $returnstr,
3161 'login'
3163 $usermenuclasses
3168 // If logged in as a guest user, show a string to that effect.
3169 if (isguestuser()) {
3170 $returnstr = get_string('loggedinasguest');
3171 if (!$loginpage && $withlinks) {
3172 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3175 return html_writer::div(
3176 html_writer::span(
3177 $returnstr,
3178 'login'
3180 $usermenuclasses
3184 // Get some navigation opts.
3185 $opts = user_get_user_navigation_info($user, $this->page, $this->page->course);
3187 $avatarclasses = "avatars";
3188 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3189 $usertextcontents = $opts->metadata['userfullname'];
3191 // Other user.
3192 if (!empty($opts->metadata['asotheruser'])) {
3193 $avatarcontents .= html_writer::span(
3194 $opts->metadata['realuseravatar'],
3195 'avatar realuser'
3197 $usertextcontents = $opts->metadata['realuserfullname'];
3198 $usertextcontents .= html_writer::tag(
3199 'span',
3200 get_string(
3201 'loggedinas',
3202 'moodle',
3203 html_writer::span(
3204 $opts->metadata['userfullname'],
3205 'value'
3208 array('class' => 'meta viewingas')
3212 // Role.
3213 if (!empty($opts->metadata['asotherrole'])) {
3214 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3215 $usertextcontents .= html_writer::span(
3216 $opts->metadata['rolename'],
3217 'meta role role-' . $role
3221 // User login failures.
3222 if (!empty($opts->metadata['userloginfail'])) {
3223 $usertextcontents .= html_writer::span(
3224 $opts->metadata['userloginfail'],
3225 'meta loginfailures'
3229 // MNet.
3230 if (!empty($opts->metadata['asmnetuser'])) {
3231 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3232 $usertextcontents .= html_writer::span(
3233 $opts->metadata['mnetidprovidername'],
3234 'meta mnet mnet-' . $mnet
3238 $returnstr .= html_writer::span(
3239 html_writer::span($usertextcontents, 'usertext') .
3240 html_writer::span($avatarcontents, $avatarclasses),
3241 'userbutton'
3244 // Create a divider (well, a filler).
3245 $divider = new action_menu_filler();
3246 $divider->primary = false;
3248 $am = new action_menu();
3249 $am->initialise_js($this->page);
3250 $am->set_menu_trigger(
3251 $returnstr
3253 $am->set_alignment(action_menu::TR, action_menu::BR);
3254 $am->set_nowrap_on_items();
3255 if ($withlinks) {
3256 $navitemcount = count($opts->navitems);
3257 $idx = 0;
3258 foreach ($opts->navitems as $key => $value) {
3260 switch ($value->itemtype) {
3261 case 'divider':
3262 // If the nav item is a divider, add one and skip link processing.
3263 $am->add($divider);
3264 break;
3266 case 'invalid':
3267 // Silently skip invalid entries (should we post a notification?).
3268 break;
3270 case 'link':
3271 // Process this as a link item.
3272 $pix = null;
3273 if (isset($value->pix) && !empty($value->pix)) {
3274 $pix = new pix_icon($value->pix, $value->title, null, array('class' => 'iconsmall'));
3275 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3276 $value->title = html_writer::img(
3277 $value->imgsrc,
3278 $value->title,
3279 array('class' => 'iconsmall')
3280 ) . $value->title;
3282 $al = new action_menu_link_secondary(
3283 $value->url,
3284 $pix,
3285 $value->title,
3286 array('class' => 'icon')
3288 $am->add($al);
3289 break;
3292 $idx++;
3294 // Add dividers after the first item and before the last item.
3295 if ($idx == 1 || $idx == $navitemcount - 1) {
3296 $am->add($divider);
3301 return html_writer::div(
3302 $this->render($am),
3303 $usermenuclasses
3308 * Return the navbar content so that it can be echoed out by the layout
3310 * @return string XHTML navbar
3312 public function navbar() {
3313 $items = $this->page->navbar->get_items();
3314 $itemcount = count($items);
3315 if ($itemcount === 0) {
3316 return '';
3319 $htmlblocks = array();
3320 // Iterate the navarray and display each node
3321 $separator = get_separator();
3322 for ($i=0;$i < $itemcount;$i++) {
3323 $item = $items[$i];
3324 $item->hideicon = true;
3325 if ($i===0) {
3326 $content = html_writer::tag('li', $this->render($item));
3327 } else {
3328 $content = html_writer::tag('li', $separator.$this->render($item));
3330 $htmlblocks[] = $content;
3333 //accessibility: heading for navbar list (MDL-20446)
3334 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
3335 $navbarcontent .= html_writer::tag('nav', html_writer::tag('ul', join('', $htmlblocks)));
3336 // XHTML
3337 return $navbarcontent;
3341 * Renders a navigation node object.
3343 * @param navigation_node $item The navigation node to render.
3344 * @return string HTML fragment
3346 protected function render_navigation_node(navigation_node $item) {
3347 $content = $item->get_content();
3348 $title = $item->get_title();
3349 if ($item->icon instanceof renderable && !$item->hideicon) {
3350 $icon = $this->render($item->icon);
3351 $content = $icon.$content; // use CSS for spacing of icons
3353 if ($item->helpbutton !== null) {
3354 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3356 if ($content === '') {
3357 return '';
3359 if ($item->action instanceof action_link) {
3360 $link = $item->action;
3361 if ($item->hidden) {
3362 $link->add_class('dimmed');
3364 if (!empty($content)) {
3365 // Providing there is content we will use that for the link content.
3366 $link->text = $content;
3368 $content = $this->render($link);
3369 } else if ($item->action instanceof moodle_url) {
3370 $attributes = array();
3371 if ($title !== '') {
3372 $attributes['title'] = $title;
3374 if ($item->hidden) {
3375 $attributes['class'] = 'dimmed_text';
3377 $content = html_writer::link($item->action, $content, $attributes);
3379 } else if (is_string($item->action) || empty($item->action)) {
3380 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3381 if ($title !== '') {
3382 $attributes['title'] = $title;
3384 if ($item->hidden) {
3385 $attributes['class'] = 'dimmed_text';
3387 $content = html_writer::tag('span', $content, $attributes);
3389 return $content;
3393 * Accessibility: Right arrow-like character is
3394 * used in the breadcrumb trail, course navigation menu
3395 * (previous/next activity), calendar, and search forum block.
3396 * If the theme does not set characters, appropriate defaults
3397 * are set automatically. Please DO NOT
3398 * use &lt; &gt; &raquo; - these are confusing for blind users.
3400 * @return string
3402 public function rarrow() {
3403 return $this->page->theme->rarrow;
3407 * Accessibility: Left arrow-like character is
3408 * used in the breadcrumb trail, course navigation menu
3409 * (previous/next activity), calendar, and search forum block.
3410 * If the theme does not set characters, appropriate defaults
3411 * are set automatically. Please DO NOT
3412 * use &lt; &gt; &raquo; - these are confusing for blind users.
3414 * @return string
3416 public function larrow() {
3417 return $this->page->theme->larrow;
3421 * Accessibility: Up arrow-like character is used in
3422 * the book heirarchical navigation.
3423 * If the theme does not set characters, appropriate defaults
3424 * are set automatically. Please DO NOT
3425 * use ^ - this is confusing for blind users.
3427 * @return string
3429 public function uarrow() {
3430 return $this->page->theme->uarrow;
3434 * Returns the custom menu if one has been set
3436 * A custom menu can be configured by browsing to
3437 * Settings: Administration > Appearance > Themes > Theme settings
3438 * and then configuring the custommenu config setting as described.
3440 * Theme developers: DO NOT OVERRIDE! Please override function
3441 * {@link core_renderer::render_custom_menu()} instead.
3443 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3444 * @return string
3446 public function custom_menu($custommenuitems = '') {
3447 global $CFG;
3448 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3449 $custommenuitems = $CFG->custommenuitems;
3451 if (empty($custommenuitems)) {
3452 return '';
3454 $custommenu = new custom_menu($custommenuitems, current_language());
3455 return $this->render($custommenu);
3459 * Renders a custom menu object (located in outputcomponents.php)
3461 * The custom menu this method produces makes use of the YUI3 menunav widget
3462 * and requires very specific html elements and classes.
3464 * @staticvar int $menucount
3465 * @param custom_menu $menu
3466 * @return string
3468 protected function render_custom_menu(custom_menu $menu) {
3469 static $menucount = 0;
3470 // If the menu has no children return an empty string
3471 if (!$menu->has_children()) {
3472 return '';
3474 // Increment the menu count. This is used for ID's that get worked with
3475 // in JavaScript as is essential
3476 $menucount++;
3477 // Initialise this custom menu (the custom menu object is contained in javascript-static
3478 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
3479 $jscode = "(function(){{$jscode}})";
3480 $this->page->requires->yui_module('node-menunav', $jscode);
3481 // Build the root nodes as required by YUI
3482 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
3483 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3484 $content .= html_writer::start_tag('ul');
3485 // Render each child
3486 foreach ($menu->get_children() as $item) {
3487 $content .= $this->render_custom_menu_item($item);
3489 // Close the open tags
3490 $content .= html_writer::end_tag('ul');
3491 $content .= html_writer::end_tag('div');
3492 $content .= html_writer::end_tag('div');
3493 // Return the custom menu
3494 return $content;
3498 * Renders a custom menu node as part of a submenu
3500 * The custom menu this method produces makes use of the YUI3 menunav widget
3501 * and requires very specific html elements and classes.
3503 * @see core:renderer::render_custom_menu()
3505 * @staticvar int $submenucount
3506 * @param custom_menu_item $menunode
3507 * @return string
3509 protected function render_custom_menu_item(custom_menu_item $menunode) {
3510 // Required to ensure we get unique trackable id's
3511 static $submenucount = 0;
3512 if ($menunode->has_children()) {
3513 // If the child has menus render it as a sub menu
3514 $submenucount++;
3515 $content = html_writer::start_tag('li');
3516 if ($menunode->get_url() !== null) {
3517 $url = $menunode->get_url();
3518 } else {
3519 $url = '#cm_submenu_'.$submenucount;
3521 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3522 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3523 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3524 $content .= html_writer::start_tag('ul');
3525 foreach ($menunode->get_children() as $menunode) {
3526 $content .= $this->render_custom_menu_item($menunode);
3528 $content .= html_writer::end_tag('ul');
3529 $content .= html_writer::end_tag('div');
3530 $content .= html_writer::end_tag('div');
3531 $content .= html_writer::end_tag('li');
3532 } else {
3533 // The node doesn't have children so produce a final menuitem.
3534 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3535 $content = '';
3536 if (preg_match("/^#+$/", $menunode->get_text())) {
3538 // This is a divider.
3539 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3540 } else {
3541 $content = html_writer::start_tag(
3542 'li',
3543 array(
3544 'class' => 'yui3-menuitem'
3547 if ($menunode->get_url() !== null) {
3548 $url = $menunode->get_url();
3549 } else {
3550 $url = '#';
3552 $content .= html_writer::link(
3553 $url,
3554 $menunode->get_text(),
3555 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3558 $content .= html_writer::end_tag('li');
3560 // Return the sub menu
3561 return $content;
3565 * Renders theme links for switching between default and other themes.
3567 * @return string
3569 protected function theme_switch_links() {
3571 $actualdevice = core_useragent::get_device_type();
3572 $currentdevice = $this->page->devicetypeinuse;
3573 $switched = ($actualdevice != $currentdevice);
3575 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3576 // The user is using the a default device and hasn't switched so don't shown the switch
3577 // device links.
3578 return '';
3581 if ($switched) {
3582 $linktext = get_string('switchdevicerecommended');
3583 $devicetype = $actualdevice;
3584 } else {
3585 $linktext = get_string('switchdevicedefault');
3586 $devicetype = 'default';
3588 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3590 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3591 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3592 $content .= html_writer::end_tag('div');
3594 return $content;
3598 * Renders tabs
3600 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3602 * Theme developers: In order to change how tabs are displayed please override functions
3603 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3605 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3606 * @param string|null $selected which tab to mark as selected, all parent tabs will
3607 * automatically be marked as activated
3608 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3609 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3610 * @return string
3612 public final function tabtree($tabs, $selected = null, $inactive = null) {
3613 return $this->render(new tabtree($tabs, $selected, $inactive));
3617 * Renders tabtree
3619 * @param tabtree $tabtree
3620 * @return string
3622 protected function render_tabtree(tabtree $tabtree) {
3623 if (empty($tabtree->subtree)) {
3624 return '';
3626 $str = '';
3627 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
3628 $str .= $this->render_tabobject($tabtree);
3629 $str .= html_writer::end_tag('div').
3630 html_writer::tag('div', ' ', array('class' => 'clearer'));
3631 return $str;
3635 * Renders tabobject (part of tabtree)
3637 * This function is called from {@link core_renderer::render_tabtree()}
3638 * and also it calls itself when printing the $tabobject subtree recursively.
3640 * Property $tabobject->level indicates the number of row of tabs.
3642 * @param tabobject $tabobject
3643 * @return string HTML fragment
3645 protected function render_tabobject(tabobject $tabobject) {
3646 $str = '';
3648 // Print name of the current tab.
3649 if ($tabobject instanceof tabtree) {
3650 // No name for tabtree root.
3651 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3652 // Tab name without a link. The <a> tag is used for styling.
3653 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3654 } else {
3655 // Tab name with a link.
3656 if (!($tabobject->link instanceof moodle_url)) {
3657 // backward compartibility when link was passed as quoted string
3658 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3659 } else {
3660 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3664 if (empty($tabobject->subtree)) {
3665 if ($tabobject->selected) {
3666 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3668 return $str;
3671 // Print subtree
3672 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3673 $cnt = 0;
3674 foreach ($tabobject->subtree as $tab) {
3675 $liclass = '';
3676 if (!$cnt) {
3677 $liclass .= ' first';
3679 if ($cnt == count($tabobject->subtree) - 1) {
3680 $liclass .= ' last';
3682 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3683 $liclass .= ' onerow';
3686 if ($tab->selected) {
3687 $liclass .= ' here selected';
3688 } else if ($tab->activated) {
3689 $liclass .= ' here active';
3692 // This will recursively call function render_tabobject() for each item in subtree
3693 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3694 $cnt++;
3696 $str .= html_writer::end_tag('ul');
3698 return $str;
3702 * Get the HTML for blocks in the given region.
3704 * @since Moodle 2.5.1 2.6
3705 * @param string $region The region to get HTML for.
3706 * @return string HTML.
3708 public function blocks($region, $classes = array(), $tag = 'aside') {
3709 $displayregion = $this->page->apply_theme_region_manipulations($region);
3710 $classes = (array)$classes;
3711 $classes[] = 'block-region';
3712 $attributes = array(
3713 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3714 'class' => join(' ', $classes),
3715 'data-blockregion' => $displayregion,
3716 'data-droptarget' => '1'
3718 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3719 $content = $this->blocks_for_region($displayregion);
3720 } else {
3721 $content = '';
3723 return html_writer::tag($tag, $content, $attributes);
3727 * Renders a custom block region.
3729 * Use this method if you want to add an additional block region to the content of the page.
3730 * Please note this should only be used in special situations.
3731 * We want to leave the theme is control where ever possible!
3733 * This method must use the same method that the theme uses within its layout file.
3734 * As such it asks the theme what method it is using.
3735 * It can be one of two values, blocks or blocks_for_region (deprecated).
3737 * @param string $regionname The name of the custom region to add.
3738 * @return string HTML for the block region.
3740 public function custom_block_region($regionname) {
3741 if ($this->page->theme->get_block_render_method() === 'blocks') {
3742 return $this->blocks($regionname);
3743 } else {
3744 return $this->blocks_for_region($regionname);
3749 * Returns the CSS classes to apply to the body tag.
3751 * @since Moodle 2.5.1 2.6
3752 * @param array $additionalclasses Any additional classes to apply.
3753 * @return string
3755 public function body_css_classes(array $additionalclasses = array()) {
3756 // Add a class for each block region on the page.
3757 // We use the block manager here because the theme object makes get_string calls.
3758 $usedregions = array();
3759 foreach ($this->page->blocks->get_regions() as $region) {
3760 $additionalclasses[] = 'has-region-'.$region;
3761 if ($this->page->blocks->region_has_content($region, $this)) {
3762 $additionalclasses[] = 'used-region-'.$region;
3763 $usedregions[] = $region;
3764 } else {
3765 $additionalclasses[] = 'empty-region-'.$region;
3767 if ($this->page->blocks->region_completely_docked($region, $this)) {
3768 $additionalclasses[] = 'docked-region-'.$region;
3771 if (count($usedregions) === 1) {
3772 // Add the -only class for the only used region.
3773 $region = array_shift($usedregions);
3774 $additionalclasses[] = $region . '-only';
3776 foreach ($this->page->layout_options as $option => $value) {
3777 if ($value) {
3778 $additionalclasses[] = 'layout-option-'.$option;
3781 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
3782 return $css;
3786 * The ID attribute to apply to the body tag.
3788 * @since Moodle 2.5.1 2.6
3789 * @return string
3791 public function body_id() {
3792 return $this->page->bodyid;
3796 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
3798 * @since Moodle 2.5.1 2.6
3799 * @param string|array $additionalclasses Any additional classes to give the body tag,
3800 * @return string
3802 public function body_attributes($additionalclasses = array()) {
3803 if (!is_array($additionalclasses)) {
3804 $additionalclasses = explode(' ', $additionalclasses);
3806 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
3810 * Gets HTML for the page heading.
3812 * @since Moodle 2.5.1 2.6
3813 * @param string $tag The tag to encase the heading in. h1 by default.
3814 * @return string HTML.
3816 public function page_heading($tag = 'h1') {
3817 return html_writer::tag($tag, $this->page->heading);
3821 * Gets the HTML for the page heading button.
3823 * @since Moodle 2.5.1 2.6
3824 * @return string HTML.
3826 public function page_heading_button() {
3827 return $this->page->button;
3831 * Returns the Moodle docs link to use for this page.
3833 * @since Moodle 2.5.1 2.6
3834 * @param string $text
3835 * @return string
3837 public function page_doc_link($text = null) {
3838 if ($text === null) {
3839 $text = get_string('moodledocslink');
3841 $path = page_get_doc_link_path($this->page);
3842 if (!$path) {
3843 return '';
3845 return $this->doc_link($path, $text);
3849 * Returns the page heading menu.
3851 * @since Moodle 2.5.1 2.6
3852 * @return string HTML.
3854 public function page_heading_menu() {
3855 return $this->page->headingmenu;
3859 * Returns the title to use on the page.
3861 * @since Moodle 2.5.1 2.6
3862 * @return string
3864 public function page_title() {
3865 return $this->page->title;
3869 * Returns the URL for the favicon.
3871 * @since Moodle 2.5.1 2.6
3872 * @return string The favicon URL
3874 public function favicon() {
3875 return $this->pix_url('favicon', 'theme');
3879 * Renders preferences groups.
3881 * @param preferences_groups $renderable The renderable
3882 * @return string The output.
3884 public function render_preferences_groups(preferences_groups $renderable) {
3885 $html = '';
3886 $html .= html_writer::start_div('row-fluid');
3887 $html .= html_writer::start_tag('div', array('class' => 'span12 preferences-groups'));
3888 $i = 0;
3889 $open = false;
3890 foreach ($renderable->groups as $group) {
3891 if ($i == 0 || $i % 3 == 0) {
3892 if ($open) {
3893 $html .= html_writer::end_tag('div');
3895 $html .= html_writer::start_tag('div', array('class' => 'row-fluid'));
3896 $open = true;
3898 $html .= $this->render($group);
3899 $i++;
3902 $html .= html_writer::end_tag('div');
3904 $html .= html_writer::end_tag('ul');
3905 $html .= html_writer::end_tag('div');
3906 $html .= html_writer::end_div();
3907 return $html;
3911 * Renders preferences group.
3913 * @param preferences_group $renderable The renderable
3914 * @return string The output.
3916 public function render_preferences_group(preferences_group $renderable) {
3917 $html = '';
3918 $html .= html_writer::start_tag('div', array('class' => 'span4 preferences-group'));
3919 $html .= $this->heading($renderable->title, 3);
3920 $html .= html_writer::start_tag('ul');
3921 foreach ($renderable->nodes as $node) {
3922 if ($node->has_children()) {
3923 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
3925 $html .= html_writer::tag('li', $this->render($node));
3927 $html .= html_writer::end_tag('ul');
3928 $html .= html_writer::end_tag('div');
3929 return $html;
3933 * Returns the header bar.
3935 * @since Moodle 2.9
3936 * @param array $headerinfo An array of header information, dependant on what type of header is being displayed. The following
3937 * array example is user specific.
3938 * heading => Override the page heading.
3939 * user => User object.
3940 * usercontext => user context.
3941 * @param int $headinglevel What level the 'h' tag will be.
3942 * @return string HTML for the header bar.
3944 public function context_header($headerinfo = null, $headinglevel = 1) {
3945 global $DB, $USER;
3946 $context = $this->page->context;
3947 // Make sure to use the heading if it has been set.
3948 if (isset($headerinfo['heading'])) {
3949 $heading = $headerinfo['heading'];
3950 } else {
3951 $heading = null;
3953 $imagedata = null;
3954 $subheader = null;
3955 $userbuttons = null;
3956 // The user context currently has images and buttons. Other contexts may follow.
3957 if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
3958 if (isset($headerinfo['user'])) {
3959 $user = $headerinfo['user'];
3960 } else {
3961 // Look up the user information if it is not supplied.
3962 $user = $DB->get_record('user', array('id' => $context->instanceid));
3964 // If the user context is set, then use that for capability checks.
3965 if (isset($headerinfo['usercontext'])) {
3966 $context = $headerinfo['usercontext'];
3968 // Use the user's full name if the heading isn't set.
3969 if (!isset($heading)) {
3970 $heading = fullname($user);
3973 $imagedata = $this->user_picture($user, array('size' => 100));
3974 // Check to see if we should be displaying a message button.
3975 if ($USER->id != $user->id && has_capability('moodle/site:sendmessage', $context)) {
3976 $userbuttons = array(
3977 'messages' => array(
3978 'buttontype' => 'message',
3979 'title' => get_string('message', 'message'),
3980 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
3981 'image' => 'message',
3982 'linkattributes' => message_messenger_sendmessage_link_params($user),
3983 'page' => $this->page
3989 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
3990 return $this->render_context_header($contextheader);
3994 * Renders the header bar.
3996 * @param context_header $contextheader Header bar object.
3997 * @return string HTML for the header bar.
3999 protected function render_context_header(context_header $contextheader) {
4001 // All the html stuff goes here.
4002 $html = html_writer::start_div('page-context-header');
4004 // Image data.
4005 if (isset($contextheader->imagedata)) {
4006 // Header specific image.
4007 $html .= html_writer::div($contextheader->imagedata, 'page-header-image');
4010 // Headings.
4011 if (!isset($contextheader->heading)) {
4012 $headings = $this->heading($this->page->heading, $contextheader->headinglevel);
4013 } else {
4014 $headings = $this->heading($contextheader->heading, $contextheader->headinglevel);
4017 $html .= html_writer::tag('div', $headings, array('class' => 'page-header-headings'));
4019 // Buttons.
4020 if (isset($contextheader->additionalbuttons)) {
4021 $html .= html_writer::start_div('btn-group header-button-group');
4022 foreach ($contextheader->additionalbuttons as $button) {
4023 if (!isset($button->page)) {
4024 // Include js for messaging.
4025 if ($button['buttontype'] === 'message') {
4026 message_messenger_requirejs();
4028 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4029 'class' => 'iconsmall',
4030 'role' => 'presentation'
4032 $image .= html_writer::span($button['title'], 'header-button-title');
4033 } else {
4034 $image = html_writer::empty_tag('img', array(
4035 'src' => $button['formattedimage'],
4036 'role' => 'presentation'
4039 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4041 $html .= html_writer::end_div();
4043 $html .= html_writer::end_div();
4045 return $html;
4049 * Wrapper for header elements.
4051 * @return string HTML to display the main header.
4053 public function full_header() {
4054 $html = html_writer::start_tag('header', array('id' => 'page-header', 'class' => 'clearfix'));
4055 $html .= $this->context_header();
4056 $html .= html_writer::start_div('clearfix', array('id' => 'page-navbar'));
4057 $html .= html_writer::tag('nav', $this->navbar(), array('class' => 'breadcrumb-nav'));
4058 $html .= html_writer::div($this->page_heading_button(), 'breadcrumb-button');
4059 $html .= html_writer::end_div();
4060 $html .= html_writer::tag('div', $this->course_header(), array('id' => 'course-header'));
4061 $html .= html_writer::end_tag('header');
4062 return $html;
4067 * A renderer that generates output for command-line scripts.
4069 * The implementation of this renderer is probably incomplete.
4071 * @copyright 2009 Tim Hunt
4072 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4073 * @since Moodle 2.0
4074 * @package core
4075 * @category output
4077 class core_renderer_cli extends core_renderer {
4080 * Returns the page header.
4082 * @return string HTML fragment
4084 public function header() {
4085 return $this->page->heading . "\n";
4089 * Returns a template fragment representing a Heading.
4091 * @param string $text The text of the heading
4092 * @param int $level The level of importance of the heading
4093 * @param string $classes A space-separated list of CSS classes
4094 * @param string $id An optional ID
4095 * @return string A template fragment for a heading
4097 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4098 $text .= "\n";
4099 switch ($level) {
4100 case 1:
4101 return '=>' . $text;
4102 case 2:
4103 return '-->' . $text;
4104 default:
4105 return $text;
4110 * Returns a template fragment representing a fatal error.
4112 * @param string $message The message to output
4113 * @param string $moreinfourl URL where more info can be found about the error
4114 * @param string $link Link for the Continue button
4115 * @param array $backtrace The execution backtrace
4116 * @param string $debuginfo Debugging information
4117 * @return string A template fragment for a fatal error
4119 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
4120 global $CFG;
4122 $output = "!!! $message !!!\n";
4124 if ($CFG->debugdeveloper) {
4125 if (!empty($debuginfo)) {
4126 $output .= $this->notification($debuginfo, 'notifytiny');
4128 if (!empty($backtrace)) {
4129 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
4133 return $output;
4137 * Returns a template fragment representing a notification.
4139 * @param string $message The message to include
4140 * @param string $classes A space-separated list of CSS classes
4141 * @return string A template fragment for a notification
4143 public function notification($message, $classes = 'notifyproblem') {
4144 $message = clean_text($message);
4145 if ($classes === 'notifysuccess') {
4146 return "++ $message ++\n";
4148 return "!! $message !!\n";
4152 * There is no footer for a cli request, however we must override the
4153 * footer method to prevent the default footer.
4155 public function footer() {}
4160 * A renderer that generates output for ajax scripts.
4162 * This renderer prevents accidental sends back only json
4163 * encoded error messages, all other output is ignored.
4165 * @copyright 2010 Petr Skoda
4166 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4167 * @since Moodle 2.0
4168 * @package core
4169 * @category output
4171 class core_renderer_ajax extends core_renderer {
4174 * Returns a template fragment representing a fatal error.
4176 * @param string $message The message to output
4177 * @param string $moreinfourl URL where more info can be found about the error
4178 * @param string $link Link for the Continue button
4179 * @param array $backtrace The execution backtrace
4180 * @param string $debuginfo Debugging information
4181 * @return string A template fragment for a fatal error
4183 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
4184 global $CFG;
4186 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
4188 $e = new stdClass();
4189 $e->error = $message;
4190 $e->stacktrace = NULL;
4191 $e->debuginfo = NULL;
4192 $e->reproductionlink = NULL;
4193 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
4194 $link = (string) $link;
4195 if ($link) {
4196 $e->reproductionlink = $link;
4198 if (!empty($debuginfo)) {
4199 $e->debuginfo = $debuginfo;
4201 if (!empty($backtrace)) {
4202 $e->stacktrace = format_backtrace($backtrace, true);
4205 $this->header();
4206 return json_encode($e);
4210 * Used to display a notification.
4211 * For the AJAX notifications are discarded.
4213 * @param string $message
4214 * @param string $classes
4216 public function notification($message, $classes = 'notifyproblem') {}
4219 * Used to display a redirection message.
4220 * AJAX redirections should not occur and as such redirection messages
4221 * are discarded.
4223 * @param moodle_url|string $encodedurl
4224 * @param string $message
4225 * @param int $delay
4226 * @param bool $debugdisableredirect
4228 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
4231 * Prepares the start of an AJAX output.
4233 public function header() {
4234 // unfortunately YUI iframe upload does not support application/json
4235 if (!empty($_FILES)) {
4236 @header('Content-type: text/plain; charset=utf-8');
4237 if (!core_useragent::supports_json_contenttype()) {
4238 @header('X-Content-Type-Options: nosniff');
4240 } else if (!core_useragent::supports_json_contenttype()) {
4241 @header('Content-type: text/plain; charset=utf-8');
4242 @header('X-Content-Type-Options: nosniff');
4243 } else {
4244 @header('Content-type: application/json; charset=utf-8');
4247 // Headers to make it not cacheable and json
4248 @header('Cache-Control: no-store, no-cache, must-revalidate');
4249 @header('Cache-Control: post-check=0, pre-check=0', false);
4250 @header('Pragma: no-cache');
4251 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
4252 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
4253 @header('Accept-Ranges: none');
4257 * There is no footer for an AJAX request, however we must override the
4258 * footer method to prevent the default footer.
4260 public function footer() {}
4263 * No need for headers in an AJAX request... this should never happen.
4264 * @param string $text
4265 * @param int $level
4266 * @param string $classes
4267 * @param string $id
4269 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
4274 * Renderer for media files.
4276 * Used in file resources, media filter, and any other places that need to
4277 * output embedded media.
4279 * @copyright 2011 The Open University
4280 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4282 class core_media_renderer extends plugin_renderer_base {
4283 /** @var array Array of available 'player' objects */
4284 private $players;
4285 /** @var string Regex pattern for links which may contain embeddable content */
4286 private $embeddablemarkers;
4289 * Constructor requires medialib.php.
4291 * This is needed in the constructor (not later) so that you can use the
4292 * constants and static functions that are defined in core_media class
4293 * before you call renderer functions.
4295 public function __construct() {
4296 global $CFG;
4297 require_once($CFG->libdir . '/medialib.php');
4301 * Obtains the list of core_media_player objects currently in use to render
4302 * items.
4304 * The list is in rank order (highest first) and does not include players
4305 * which are disabled.
4307 * @return array Array of core_media_player objects in rank order
4309 protected function get_players() {
4310 global $CFG;
4312 // Save time by only building the list once.
4313 if (!$this->players) {
4314 // Get raw list of players.
4315 $players = $this->get_players_raw();
4317 // Chuck all the ones that are disabled.
4318 foreach ($players as $key => $player) {
4319 if (!$player->is_enabled()) {
4320 unset($players[$key]);
4324 // Sort in rank order (highest first).
4325 usort($players, array('core_media_player', 'compare_by_rank'));
4326 $this->players = $players;
4328 return $this->players;
4332 * Obtains a raw list of player objects that includes objects regardless
4333 * of whether they are disabled or not, and without sorting.
4335 * You can override this in a subclass if you need to add additional
4336 * players.
4338 * The return array is be indexed by player name to make it easier to
4339 * remove players in a subclass.
4341 * @return array $players Array of core_media_player objects in any order
4343 protected function get_players_raw() {
4344 return array(
4345 'vimeo' => new core_media_player_vimeo(),
4346 'youtube' => new core_media_player_youtube(),
4347 'youtube_playlist' => new core_media_player_youtube_playlist(),
4348 'html5video' => new core_media_player_html5video(),
4349 'html5audio' => new core_media_player_html5audio(),
4350 'mp3' => new core_media_player_mp3(),
4351 'flv' => new core_media_player_flv(),
4352 'wmp' => new core_media_player_wmp(),
4353 'qt' => new core_media_player_qt(),
4354 'rm' => new core_media_player_rm(),
4355 'swf' => new core_media_player_swf(),
4356 'link' => new core_media_player_link(),
4361 * Renders a media file (audio or video) using suitable embedded player.
4363 * See embed_alternatives function for full description of parameters.
4364 * This function calls through to that one.
4366 * When using this function you can also specify width and height in the
4367 * URL by including ?d=100x100 at the end. If specified in the URL, this
4368 * will override the $width and $height parameters.
4370 * @param moodle_url $url Full URL of media file
4371 * @param string $name Optional user-readable name to display in download link
4372 * @param int $width Width in pixels (optional)
4373 * @param int $height Height in pixels (optional)
4374 * @param array $options Array of key/value pairs
4375 * @return string HTML content of embed
4377 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
4378 $options = array()) {
4380 // Get width and height from URL if specified (overrides parameters in
4381 // function call).
4382 $rawurl = $url->out(false);
4383 if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
4384 $width = $matches[1];
4385 $height = $matches[2];
4386 $url = new moodle_url(str_replace($matches[0], '', $rawurl));
4389 // Defer to array version of function.
4390 return $this->embed_alternatives(array($url), $name, $width, $height, $options);
4394 * Renders media files (audio or video) using suitable embedded player.
4395 * The list of URLs should be alternative versions of the same content in
4396 * multiple formats. If there is only one format it should have a single
4397 * entry.
4399 * If the media files are not in a supported format, this will give students
4400 * a download link to each format. The download link uses the filename
4401 * unless you supply the optional name parameter.
4403 * Width and height are optional. If specified, these are suggested sizes
4404 * and should be the exact values supplied by the user, if they come from
4405 * user input. These will be treated as relating to the size of the video
4406 * content, not including any player control bar.
4408 * For audio files, height will be ignored. For video files, a few formats
4409 * work if you specify only width, but in general if you specify width
4410 * you must specify height as well.
4412 * The $options array is passed through to the core_media_player classes
4413 * that render the object tag. The keys can contain values from
4414 * core_media::OPTION_xx.
4416 * @param array $alternatives Array of moodle_url to media files
4417 * @param string $name Optional user-readable name to display in download link
4418 * @param int $width Width in pixels (optional)
4419 * @param int $height Height in pixels (optional)
4420 * @param array $options Array of key/value pairs
4421 * @return string HTML content of embed
4423 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
4424 $options = array()) {
4426 // Get list of player plugins (will also require the library).
4427 $players = $this->get_players();
4429 // Set up initial text which will be replaced by first player that
4430 // supports any of the formats.
4431 $out = core_media_player::PLACEHOLDER;
4433 // Loop through all players that support any of these URLs.
4434 foreach ($players as $player) {
4435 // Option: When no other player matched, don't do the default link player.
4436 if (!empty($options[core_media::OPTION_FALLBACK_TO_BLANK]) &&
4437 $player->get_rank() === 0 && $out === core_media_player::PLACEHOLDER) {
4438 continue;
4441 $supported = $player->list_supported_urls($alternatives, $options);
4442 if ($supported) {
4443 // Embed.
4444 $text = $player->embed($supported, $name, $width, $height, $options);
4446 // Put this in place of the 'fallback' slot in the previous text.
4447 $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
4451 // Remove 'fallback' slot from final version and return it.
4452 $out = str_replace(core_media_player::PLACEHOLDER, '', $out);
4453 if (!empty($options[core_media::OPTION_BLOCK]) && $out !== '') {
4454 $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
4456 return $out;
4460 * Checks whether a file can be embedded. If this returns true you will get
4461 * an embedded player; if this returns false, you will just get a download
4462 * link.
4464 * This is a wrapper for can_embed_urls.
4466 * @param moodle_url $url URL of media file
4467 * @param array $options Options (same as when embedding)
4468 * @return bool True if file can be embedded
4470 public function can_embed_url(moodle_url $url, $options = array()) {
4471 return $this->can_embed_urls(array($url), $options);
4475 * Checks whether a file can be embedded. If this returns true you will get
4476 * an embedded player; if this returns false, you will just get a download
4477 * link.
4479 * @param array $urls URL of media file and any alternatives (moodle_url)
4480 * @param array $options Options (same as when embedding)
4481 * @return bool True if file can be embedded
4483 public function can_embed_urls(array $urls, $options = array()) {
4484 // Check all players to see if any of them support it.
4485 foreach ($this->get_players() as $player) {
4486 // Link player (always last on list) doesn't count!
4487 if ($player->get_rank() <= 0) {
4488 break;
4490 // First player that supports it, return true.
4491 if ($player->list_supported_urls($urls, $options)) {
4492 return true;
4495 return false;
4499 * Obtains a list of markers that can be used in a regular expression when
4500 * searching for URLs that can be embedded by any player type.
4502 * This string is used to improve peformance of regex matching by ensuring
4503 * that the (presumably C) regex code can do a quick keyword check on the
4504 * URL part of a link to see if it matches one of these, rather than having
4505 * to go into PHP code for every single link to see if it can be embedded.
4507 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
4509 public function get_embeddable_markers() {
4510 if (empty($this->embeddablemarkers)) {
4511 $markers = '';
4512 foreach ($this->get_players() as $player) {
4513 foreach ($player->get_embeddable_markers() as $marker) {
4514 if ($markers !== '') {
4515 $markers .= '|';
4517 $markers .= preg_quote($marker);
4520 $this->embeddablemarkers = $markers;
4522 return $this->embeddablemarkers;
4527 * The maintenance renderer.
4529 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
4530 * is running a maintenance related task.
4531 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
4533 * @since Moodle 2.6
4534 * @package core
4535 * @category output
4536 * @copyright 2013 Sam Hemelryk
4537 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4539 class core_renderer_maintenance extends core_renderer {
4542 * Initialises the renderer instance.
4543 * @param moodle_page $page
4544 * @param string $target
4545 * @throws coding_exception
4547 public function __construct(moodle_page $page, $target) {
4548 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
4549 throw new coding_exception('Invalid request for the maintenance renderer.');
4551 parent::__construct($page, $target);
4555 * Does nothing. The maintenance renderer cannot produce blocks.
4557 * @param block_contents $bc
4558 * @param string $region
4559 * @return string
4561 public function block(block_contents $bc, $region) {
4562 // Computer says no blocks.
4563 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4564 return '';
4568 * Does nothing. The maintenance renderer cannot produce blocks.
4570 * @param string $region
4571 * @param array $classes
4572 * @param string $tag
4573 * @return string
4575 public function blocks($region, $classes = array(), $tag = 'aside') {
4576 // Computer says no blocks.
4577 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4578 return '';
4582 * Does nothing. The maintenance renderer cannot produce blocks.
4584 * @param string $region
4585 * @return string
4587 public function blocks_for_region($region) {
4588 // Computer says no blocks for region.
4589 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4590 return '';
4594 * Does nothing. The maintenance renderer cannot produce a course content header.
4596 * @param bool $onlyifnotcalledbefore
4597 * @return string
4599 public function course_content_header($onlyifnotcalledbefore = false) {
4600 // Computer says no course content header.
4601 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4602 return '';
4606 * Does nothing. The maintenance renderer cannot produce a course content footer.
4608 * @param bool $onlyifnotcalledbefore
4609 * @return string
4611 public function course_content_footer($onlyifnotcalledbefore = false) {
4612 // Computer says no course content footer.
4613 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4614 return '';
4618 * Does nothing. The maintenance renderer cannot produce a course header.
4620 * @return string
4622 public function course_header() {
4623 // Computer says no course header.
4624 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4625 return '';
4629 * Does nothing. The maintenance renderer cannot produce a course footer.
4631 * @return string
4633 public function course_footer() {
4634 // Computer says no course footer.
4635 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4636 return '';
4640 * Does nothing. The maintenance renderer cannot produce a custom menu.
4642 * @param string $custommenuitems
4643 * @return string
4645 public function custom_menu($custommenuitems = '') {
4646 // Computer says no custom menu.
4647 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4648 return '';
4652 * Does nothing. The maintenance renderer cannot produce a file picker.
4654 * @param array $options
4655 * @return string
4657 public function file_picker($options) {
4658 // Computer says no file picker.
4659 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4660 return '';
4664 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
4666 * @param array $dir
4667 * @return string
4669 public function htmllize_file_tree($dir) {
4670 // Hell no we don't want no htmllized file tree.
4671 // Also why on earth is this function on the core renderer???
4672 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4673 return '';
4678 * Does nothing. The maintenance renderer does not support JS.
4680 * @param block_contents $bc
4682 public function init_block_hider_js(block_contents $bc) {
4683 // Computer says no JavaScript.
4684 // Do nothing, ridiculous method.
4688 * Does nothing. The maintenance renderer cannot produce language menus.
4690 * @return string
4692 public function lang_menu() {
4693 // Computer says no lang menu.
4694 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4695 return '';
4699 * Does nothing. The maintenance renderer has no need for login information.
4701 * @param null $withlinks
4702 * @return string
4704 public function login_info($withlinks = null) {
4705 // Computer says no login info.
4706 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4707 return '';
4711 * Does nothing. The maintenance renderer cannot produce user pictures.
4713 * @param stdClass $user
4714 * @param array $options
4715 * @return string
4717 public function user_picture(stdClass $user, array $options = null) {
4718 // Computer says no user pictures.
4719 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4720 return '';