MDL-51579 course: Bump version to update mobile service
[moodle.git] / lib / outputrenderers.php
bloba42d377b6114d3b95139d9ea7df9ad28fffdc68f
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,
110 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS]));
114 return $this->mustache;
119 * Constructor
121 * The constructor takes two arguments. The first is the page that the renderer
122 * has been created to assist with, and the second is the target.
123 * The target is an additional identifier that can be used to load different
124 * renderers for different options.
126 * @param moodle_page $page the page we are doing output for.
127 * @param string $target one of rendering target constants
129 public function __construct(moodle_page $page, $target) {
130 $this->opencontainers = $page->opencontainers;
131 $this->page = $page;
132 $this->target = $target;
136 * Renders a template by name with the given context.
138 * The provided data needs to be array/stdClass made up of only simple types.
139 * Simple types are array,stdClass,bool,int,float,string
141 * @since 2.9
142 * @param array|stdClass $context Context containing data for the template.
143 * @return string|boolean
145 public function render_from_template($templatename, $context) {
146 static $templatecache = array();
147 $mustache = $this->get_mustache();
149 // Provide 1 random value that will not change within a template
150 // but will be different from template to template. This is useful for
151 // e.g. aria attributes that only work with id attributes and must be
152 // unique in a page.
153 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
154 if (isset($templatecache[$templatename])) {
155 $template = $templatecache[$templatename];
156 } else {
157 try {
158 $template = $mustache->loadTemplate($templatename);
159 $templatecache[$templatename] = $template;
160 } catch (Mustache_Exception_UnknownTemplateException $e) {
161 throw new moodle_exception('Unknown template: ' . $templatename);
164 return trim($template->render($context));
169 * Returns rendered widget.
171 * The provided widget needs to be an object that extends the renderable
172 * interface.
173 * If will then be rendered by a method based upon the classname for the widget.
174 * For instance a widget of class `crazywidget` will be rendered by a protected
175 * render_crazywidget method of this renderer.
177 * @param renderable $widget instance with renderable interface
178 * @return string
180 public function render(renderable $widget) {
181 $classname = get_class($widget);
182 // Strip namespaces.
183 $classname = preg_replace('/^.*\\\/', '', $classname);
184 // Remove _renderable suffixes
185 $classname = preg_replace('/_renderable$/', '', $classname);
187 $rendermethod = 'render_'.$classname;
188 if (method_exists($this, $rendermethod)) {
189 return $this->$rendermethod($widget);
191 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
195 * Adds a JS action for the element with the provided id.
197 * This method adds a JS event for the provided component action to the page
198 * and then returns the id that the event has been attached to.
199 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
201 * @param component_action $action
202 * @param string $id
203 * @return string id of element, either original submitted or random new if not supplied
205 public function add_action_handler(component_action $action, $id = null) {
206 if (!$id) {
207 $id = html_writer::random_id($action->event);
209 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
210 return $id;
214 * Returns true is output has already started, and false if not.
216 * @return boolean true if the header has been printed.
218 public function has_started() {
219 return $this->page->state >= moodle_page::STATE_IN_BODY;
223 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
225 * @param mixed $classes Space-separated string or array of classes
226 * @return string HTML class attribute value
228 public static function prepare_classes($classes) {
229 if (is_array($classes)) {
230 return implode(' ', array_unique($classes));
232 return $classes;
236 * Return the moodle_url for an image.
238 * The exact image location and extension is determined
239 * automatically by searching for gif|png|jpg|jpeg, please
240 * note there can not be diferent images with the different
241 * extension. The imagename is for historical reasons
242 * a relative path name, it may be changed later for core
243 * images. It is recommended to not use subdirectories
244 * in plugin and theme pix directories.
246 * There are three types of images:
247 * 1/ theme images - stored in theme/mytheme/pix/,
248 * use component 'theme'
249 * 2/ core images - stored in /pix/,
250 * overridden via theme/mytheme/pix_core/
251 * 3/ plugin images - stored in mod/mymodule/pix,
252 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
253 * example: pix_url('comment', 'mod_glossary')
255 * @param string $imagename the pathname of the image
256 * @param string $component full plugin name (aka component) or 'theme'
257 * @return moodle_url
259 public function pix_url($imagename, $component = 'moodle') {
260 return $this->page->theme->pix_url($imagename, $component);
266 * Basis for all plugin renderers.
268 * @copyright Petr Skoda (skodak)
269 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
270 * @since Moodle 2.0
271 * @package core
272 * @category output
274 class plugin_renderer_base extends renderer_base {
277 * @var renderer_base|core_renderer A reference to the current renderer.
278 * The renderer provided here will be determined by the page but will in 90%
279 * of cases by the {@link core_renderer}
281 protected $output;
284 * Constructor method, calls the parent constructor
286 * @param moodle_page $page
287 * @param string $target one of rendering target constants
289 public function __construct(moodle_page $page, $target) {
290 if (empty($target) && $page->pagelayout === 'maintenance') {
291 // If the page is using the maintenance layout then we're going to force the target to maintenance.
292 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
293 // unavailable for this page layout.
294 $target = RENDERER_TARGET_MAINTENANCE;
296 $this->output = $page->get_renderer('core', null, $target);
297 parent::__construct($page, $target);
301 * Renders the provided widget and returns the HTML to display it.
303 * @param renderable $widget instance with renderable interface
304 * @return string
306 public function render(renderable $widget) {
307 $classname = get_class($widget);
308 // Strip namespaces.
309 $classname = preg_replace('/^.*\\\/', '', $classname);
310 // Keep a copy at this point, we may need to look for a deprecated method.
311 $deprecatedmethod = 'render_'.$classname;
312 // Remove _renderable suffixes
313 $classname = preg_replace('/_renderable$/', '', $classname);
315 $rendermethod = 'render_'.$classname;
316 if (method_exists($this, $rendermethod)) {
317 return $this->$rendermethod($widget);
319 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
320 // This is exactly where we don't want to be.
321 // If you have arrived here you have a renderable component within your plugin that has the name
322 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
323 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
324 // and the _renderable suffix now gets removed when looking for a render method.
325 // You need to change your renderers render_blah_renderable to render_blah.
326 // Until you do this it will not be possible for a theme to override the renderer to override your method.
327 // Please do it ASAP.
328 static $debugged = array();
329 if (!isset($debugged[$deprecatedmethod])) {
330 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
331 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
332 $debugged[$deprecatedmethod] = true;
334 return $this->$deprecatedmethod($widget);
336 // pass to core renderer if method not found here
337 return $this->output->render($widget);
341 * Magic method used to pass calls otherwise meant for the standard renderer
342 * to it to ensure we don't go causing unnecessary grief.
344 * @param string $method
345 * @param array $arguments
346 * @return mixed
348 public function __call($method, $arguments) {
349 if (method_exists('renderer_base', $method)) {
350 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
352 if (method_exists($this->output, $method)) {
353 return call_user_func_array(array($this->output, $method), $arguments);
354 } else {
355 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
362 * The standard implementation of the core_renderer interface.
364 * @copyright 2009 Tim Hunt
365 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
366 * @since Moodle 2.0
367 * @package core
368 * @category output
370 class core_renderer extends renderer_base {
372 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
373 * in layout files instead.
374 * @deprecated
375 * @var string used in {@link core_renderer::header()}.
377 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
380 * @var string Used to pass information from {@link core_renderer::doctype()} to
381 * {@link core_renderer::standard_head_html()}.
383 protected $contenttype;
386 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
387 * with {@link core_renderer::header()}.
389 protected $metarefreshtag = '';
392 * @var string Unique token for the closing HTML
394 protected $unique_end_html_token;
397 * @var string Unique token for performance information
399 protected $unique_performance_info_token;
402 * @var string Unique token for the main content.
404 protected $unique_main_content_token;
407 * Constructor
409 * @param moodle_page $page the page we are doing output for.
410 * @param string $target one of rendering target constants
412 public function __construct(moodle_page $page, $target) {
413 $this->opencontainers = $page->opencontainers;
414 $this->page = $page;
415 $this->target = $target;
417 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
418 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
419 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
423 * Get the DOCTYPE declaration that should be used with this page. Designed to
424 * be called in theme layout.php files.
426 * @return string the DOCTYPE declaration that should be used.
428 public function doctype() {
429 if ($this->page->theme->doctype === 'html5') {
430 $this->contenttype = 'text/html; charset=utf-8';
431 return "<!DOCTYPE html>\n";
433 } else if ($this->page->theme->doctype === 'xhtml5') {
434 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
435 return "<!DOCTYPE html>\n";
437 } else {
438 // legacy xhtml 1.0
439 $this->contenttype = 'text/html; charset=utf-8';
440 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
445 * The attributes that should be added to the <html> tag. Designed to
446 * be called in theme layout.php files.
448 * @return string HTML fragment.
450 public function htmlattributes() {
451 $return = get_html_lang(true);
452 if ($this->page->theme->doctype !== 'html5') {
453 $return .= ' xmlns="http://www.w3.org/1999/xhtml"';
455 return $return;
459 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
460 * that should be included in the <head> tag. Designed to be called in theme
461 * layout.php files.
463 * @return string HTML fragment.
465 public function standard_head_html() {
466 global $CFG, $SESSION;
468 // Before we output any content, we need to ensure that certain
469 // page components are set up.
471 // Blocks must be set up early as they may require javascript which
472 // has to be included in the page header before output is created.
473 foreach ($this->page->blocks->get_regions() as $region) {
474 $this->page->blocks->ensure_content_created($region, $this);
477 $output = '';
478 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
479 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
480 // This is only set by the {@link redirect()} method
481 $output .= $this->metarefreshtag;
483 // Check if a periodic refresh delay has been set and make sure we arn't
484 // already meta refreshing
485 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
486 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
489 // flow player embedding support
490 $this->page->requires->js_function_call('M.util.load_flowplayer');
492 // Set up help link popups for all links with the helptooltip class
493 $this->page->requires->js_init_call('M.util.help_popups.setup');
495 // Setup help icon overlays.
496 $this->page->requires->yui_module('moodle-core-popuphelp', 'M.core.init_popuphelp');
497 $this->page->requires->strings_for_js(array(
498 'morehelp',
499 'loadinghelp',
500 ), 'moodle');
502 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
504 $focus = $this->page->focuscontrol;
505 if (!empty($focus)) {
506 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
507 // This is a horrifically bad way to handle focus but it is passed in
508 // through messy formslib::moodleform
509 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
510 } else if (strpos($focus, '.')!==false) {
511 // Old style of focus, bad way to do it
512 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);
513 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
514 } else {
515 // Focus element with given id
516 $this->page->requires->js_function_call('focuscontrol', array($focus));
520 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
521 // any other custom CSS can not be overridden via themes and is highly discouraged
522 $urls = $this->page->theme->css_urls($this->page);
523 foreach ($urls as $url) {
524 $this->page->requires->css_theme($url);
527 // Get the theme javascript head and footer
528 if ($jsurl = $this->page->theme->javascript_url(true)) {
529 $this->page->requires->js($jsurl, true);
531 if ($jsurl = $this->page->theme->javascript_url(false)) {
532 $this->page->requires->js($jsurl);
535 // Get any HTML from the page_requirements_manager.
536 $output .= $this->page->requires->get_head_code($this->page, $this);
538 // List alternate versions.
539 foreach ($this->page->alternateversions as $type => $alt) {
540 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
541 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
544 if (!empty($CFG->additionalhtmlhead)) {
545 $output .= "\n".$CFG->additionalhtmlhead;
548 return $output;
552 * The standard tags (typically skip links) that should be output just inside
553 * the start of the <body> tag. Designed to be called in theme layout.php files.
555 * @return string HTML fragment.
557 public function standard_top_of_body_html() {
558 global $CFG;
559 $output = $this->page->requires->get_top_of_body_code();
560 if (!empty($CFG->additionalhtmltopofbody)) {
561 $output .= "\n".$CFG->additionalhtmltopofbody;
563 $output .= $this->maintenance_warning();
564 return $output;
568 * Scheduled maintenance warning message.
570 * Note: This is a nasty hack to display maintenance notice, this should be moved
571 * to some general notification area once we have it.
573 * @return string
575 public function maintenance_warning() {
576 global $CFG;
578 $output = '';
579 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
580 $timeleft = $CFG->maintenance_later - time();
581 // If timeleft less than 30 sec, set the class on block to error to highlight.
582 $errorclass = ($timeleft < 30) ? 'error' : 'warning';
583 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning');
584 $a = new stdClass();
585 $a->min = (int)($timeleft/60);
586 $a->sec = (int)($timeleft % 60);
587 $output .= get_string('maintenancemodeisscheduled', 'admin', $a) ;
588 $output .= $this->box_end();
589 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
590 array(array('timeleftinsec' => $timeleft)));
591 $this->page->requires->strings_for_js(
592 array('maintenancemodeisscheduled', 'sitemaintenance'),
593 'admin');
595 return $output;
599 * The standard tags (typically performance information and validation links,
600 * if we are in developer debug mode) that should be output in the footer area
601 * of the page. Designed to be called in theme layout.php files.
603 * @return string HTML fragment.
605 public function standard_footer_html() {
606 global $CFG, $SCRIPT;
608 if (during_initial_install()) {
609 // Debugging info can not work before install is finished,
610 // in any case we do not want any links during installation!
611 return '';
614 // This function is normally called from a layout.php file in {@link core_renderer::header()}
615 // but some of the content won't be known until later, so we return a placeholder
616 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
617 $output = $this->unique_performance_info_token;
618 if ($this->page->devicetypeinuse == 'legacy') {
619 // The legacy theme is in use print the notification
620 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
623 // Get links to switch device types (only shown for users not on a default device)
624 $output .= $this->theme_switch_links();
626 if (!empty($CFG->debugpageinfo)) {
627 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
629 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
630 // Add link to profiling report if necessary
631 if (function_exists('profiling_is_running') && profiling_is_running()) {
632 $txt = get_string('profiledscript', 'admin');
633 $title = get_string('profiledscriptview', 'admin');
634 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
635 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
636 $output .= '<div class="profilingfooter">' . $link . '</div>';
638 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
639 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
640 $output .= '<div class="purgecaches">' .
641 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
643 if (!empty($CFG->debugvalidators)) {
644 // 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
645 $output .= '<div class="validators"><ul>
646 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
647 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
648 <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>
649 </ul></div>';
651 return $output;
655 * Returns standard main content placeholder.
656 * Designed to be called in theme layout.php files.
658 * @return string HTML fragment.
660 public function main_content() {
661 // This is here because it is the only place we can inject the "main" role over the entire main content area
662 // without requiring all theme's to manually do it, and without creating yet another thing people need to
663 // remember in the theme.
664 // This is an unfortunate hack. DO NO EVER add anything more here.
665 // DO NOT add classes.
666 // DO NOT add an id.
667 return '<div role="main">'.$this->unique_main_content_token.'</div>';
671 * The standard tags (typically script tags that are not needed earlier) that
672 * should be output after everything else. Designed to be called in theme layout.php files.
674 * @return string HTML fragment.
676 public function standard_end_of_body_html() {
677 global $CFG;
679 // This function is normally called from a layout.php file in {@link core_renderer::header()}
680 // but some of the content won't be known until later, so we return a placeholder
681 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
682 $output = '';
683 if (!empty($CFG->additionalhtmlfooter)) {
684 $output .= "\n".$CFG->additionalhtmlfooter;
686 $output .= $this->unique_end_html_token;
687 return $output;
691 * Return the standard string that says whether you are logged in (and switched
692 * roles/logged in as another user).
693 * @param bool $withlinks if false, then don't include any links in the HTML produced.
694 * If not set, the default is the nologinlinks option from the theme config.php file,
695 * and if that is not set, then links are included.
696 * @return string HTML fragment.
698 public function login_info($withlinks = null) {
699 global $USER, $CFG, $DB, $SESSION;
701 if (during_initial_install()) {
702 return '';
705 if (is_null($withlinks)) {
706 $withlinks = empty($this->page->layout_options['nologinlinks']);
709 $course = $this->page->course;
710 if (\core\session\manager::is_loggedinas()) {
711 $realuser = \core\session\manager::get_realuser();
712 $fullname = fullname($realuser, true);
713 if ($withlinks) {
714 $loginastitle = get_string('loginas');
715 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
716 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
717 } else {
718 $realuserinfo = " [$fullname] ";
720 } else {
721 $realuserinfo = '';
724 $loginpage = $this->is_login_page();
725 $loginurl = get_login_url();
727 if (empty($course->id)) {
728 // $course->id is not defined during installation
729 return '';
730 } else if (isloggedin()) {
731 $context = context_course::instance($course->id);
733 $fullname = fullname($USER, true);
734 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
735 if ($withlinks) {
736 $linktitle = get_string('viewprofile');
737 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
738 } else {
739 $username = $fullname;
741 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
742 if ($withlinks) {
743 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
744 } else {
745 $username .= " from {$idprovider->name}";
748 if (isguestuser()) {
749 $loggedinas = $realuserinfo.get_string('loggedinasguest');
750 if (!$loginpage && $withlinks) {
751 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
753 } else if (is_role_switched($course->id)) { // Has switched roles
754 $rolename = '';
755 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
756 $rolename = ': '.role_get_name($role, $context);
758 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
759 if ($withlinks) {
760 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
761 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
763 } else {
764 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
765 if ($withlinks) {
766 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
769 } else {
770 $loggedinas = get_string('loggedinnot', 'moodle');
771 if (!$loginpage && $withlinks) {
772 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
776 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
778 if (isset($SESSION->justloggedin)) {
779 unset($SESSION->justloggedin);
780 if (!empty($CFG->displayloginfailures)) {
781 if (!isguestuser()) {
782 // Include this file only when required.
783 require_once($CFG->dirroot . '/user/lib.php');
784 if ($count = user_count_login_failures($USER)) {
785 $loggedinas .= '<div class="loginfailures">';
786 $a = new stdClass();
787 $a->attempts = $count;
788 $loggedinas .= get_string('failedloginattempts', '', $a);
789 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
790 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
791 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
793 $loggedinas .= '</div>';
799 return $loggedinas;
803 * Check whether the current page is a login page.
805 * @since Moodle 2.9
806 * @return bool
808 protected function is_login_page() {
809 // This is a real bit of a hack, but its a rarety that we need to do something like this.
810 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
811 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
812 return in_array(
813 $this->page->url->out_as_local_url(false, array()),
814 array(
815 '/login/index.php',
816 '/login/forgot_password.php',
822 * Return the 'back' link that normally appears in the footer.
824 * @return string HTML fragment.
826 public function home_link() {
827 global $CFG, $SITE;
829 if ($this->page->pagetype == 'site-index') {
830 // Special case for site home page - please do not remove
831 return '<div class="sitelink">' .
832 '<a title="Moodle" href="http://moodle.org/">' .
833 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
835 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
836 // Special case for during install/upgrade.
837 return '<div class="sitelink">'.
838 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
839 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
841 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
842 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
843 get_string('home') . '</a></div>';
845 } else {
846 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
847 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
852 * Redirects the user by any means possible given the current state
854 * This function should not be called directly, it should always be called using
855 * the redirect function in lib/weblib.php
857 * The redirect function should really only be called before page output has started
858 * however it will allow itself to be called during the state STATE_IN_BODY
860 * @param string $encodedurl The URL to send to encoded if required
861 * @param string $message The message to display to the user if any
862 * @param int $delay The delay before redirecting a user, if $message has been
863 * set this is a requirement and defaults to 3, set to 0 no delay
864 * @param boolean $debugdisableredirect this redirect has been disabled for
865 * debugging purposes. Display a message that explains, and don't
866 * trigger the redirect.
867 * @return string The HTML to display to the user before dying, may contain
868 * meta refresh, javascript refresh, and may have set header redirects
870 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
871 global $CFG;
872 $url = str_replace('&amp;', '&', $encodedurl);
874 switch ($this->page->state) {
875 case moodle_page::STATE_BEFORE_HEADER :
876 // No output yet it is safe to delivery the full arsenal of redirect methods
877 if (!$debugdisableredirect) {
878 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
879 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
880 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
882 $output = $this->header();
883 break;
884 case moodle_page::STATE_PRINTING_HEADER :
885 // We should hopefully never get here
886 throw new coding_exception('You cannot redirect while printing the page header');
887 break;
888 case moodle_page::STATE_IN_BODY :
889 // We really shouldn't be here but we can deal with this
890 debugging("You should really redirect before you start page output");
891 if (!$debugdisableredirect) {
892 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
894 $output = $this->opencontainers->pop_all_but_last();
895 break;
896 case moodle_page::STATE_DONE :
897 // Too late to be calling redirect now
898 throw new coding_exception('You cannot redirect after the entire page has been generated');
899 break;
901 $output .= $this->notification($message, 'redirectmessage');
902 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
903 if ($debugdisableredirect) {
904 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
906 $output .= $this->footer();
907 return $output;
911 * Start output by sending the HTTP headers, and printing the HTML <head>
912 * and the start of the <body>.
914 * To control what is printed, you should set properties on $PAGE. If you
915 * are familiar with the old {@link print_header()} function from Moodle 1.9
916 * you will find that there are properties on $PAGE that correspond to most
917 * of the old parameters to could be passed to print_header.
919 * Not that, in due course, the remaining $navigation, $menu parameters here
920 * will be replaced by more properties of $PAGE, but that is still to do.
922 * @return string HTML that you must output this, preferably immediately.
924 public function header() {
925 global $USER, $CFG;
927 if (\core\session\manager::is_loggedinas()) {
928 $this->page->add_body_class('userloggedinas');
931 // If the user is logged in, and we're not in initial install,
932 // check to see if the user is role-switched and add the appropriate
933 // CSS class to the body element.
934 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
935 $this->page->add_body_class('userswitchedrole');
938 // Give themes a chance to init/alter the page object.
939 $this->page->theme->init_page($this->page);
941 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
943 // Find the appropriate page layout file, based on $this->page->pagelayout.
944 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
945 // Render the layout using the layout file.
946 $rendered = $this->render_page_layout($layoutfile);
948 // Slice the rendered output into header and footer.
949 $cutpos = strpos($rendered, $this->unique_main_content_token);
950 if ($cutpos === false) {
951 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
952 $token = self::MAIN_CONTENT_TOKEN;
953 } else {
954 $token = $this->unique_main_content_token;
957 if ($cutpos === false) {
958 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.');
960 $header = substr($rendered, 0, $cutpos);
961 $footer = substr($rendered, $cutpos + strlen($token));
963 if (empty($this->contenttype)) {
964 debugging('The page layout file did not call $OUTPUT->doctype()');
965 $header = $this->doctype() . $header;
968 // If this theme version is below 2.4 release and this is a course view page
969 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
970 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
971 // check if course content header/footer have not been output during render of theme layout
972 $coursecontentheader = $this->course_content_header(true);
973 $coursecontentfooter = $this->course_content_footer(true);
974 if (!empty($coursecontentheader)) {
975 // display debug message and add header and footer right above and below main content
976 // Please note that course header and footer (to be displayed above and below the whole page)
977 // are not displayed in this case at all.
978 // Besides the content header and footer are not displayed on any other course page
979 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);
980 $header .= $coursecontentheader;
981 $footer = $coursecontentfooter. $footer;
985 send_headers($this->contenttype, $this->page->cacheable);
987 $this->opencontainers->push('header/footer', $footer);
988 $this->page->set_state(moodle_page::STATE_IN_BODY);
990 return $header . $this->skip_link_target('maincontent');
994 * Renders and outputs the page layout file.
996 * This is done by preparing the normal globals available to a script, and
997 * then including the layout file provided by the current theme for the
998 * requested layout.
1000 * @param string $layoutfile The name of the layout file
1001 * @return string HTML code
1003 protected function render_page_layout($layoutfile) {
1004 global $CFG, $SITE, $USER;
1005 // The next lines are a bit tricky. The point is, here we are in a method
1006 // of a renderer class, and this object may, or may not, be the same as
1007 // the global $OUTPUT object. When rendering the page layout file, we want to use
1008 // this object. However, people writing Moodle code expect the current
1009 // renderer to be called $OUTPUT, not $this, so define a variable called
1010 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1011 $OUTPUT = $this;
1012 $PAGE = $this->page;
1013 $COURSE = $this->page->course;
1015 ob_start();
1016 include($layoutfile);
1017 $rendered = ob_get_contents();
1018 ob_end_clean();
1019 return $rendered;
1023 * Outputs the page's footer
1025 * @return string HTML fragment
1027 public function footer() {
1028 global $CFG, $DB;
1030 $output = $this->container_end_all(true);
1032 $footer = $this->opencontainers->pop('header/footer');
1034 if (debugging() and $DB and $DB->is_transaction_started()) {
1035 // TODO: MDL-20625 print warning - transaction will be rolled back
1038 // Provide some performance info if required
1039 $performanceinfo = '';
1040 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1041 $perf = get_performance_info();
1042 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1043 $performanceinfo = $perf['html'];
1047 // We always want performance data when running a performance test, even if the user is redirected to another page.
1048 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1049 $footer = $this->unique_performance_info_token . $footer;
1051 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1053 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1055 $this->page->set_state(moodle_page::STATE_DONE);
1057 return $output . $footer;
1061 * Close all but the last open container. This is useful in places like error
1062 * handling, where you want to close all the open containers (apart from <body>)
1063 * before outputting the error message.
1065 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1066 * developer debug warning if it isn't.
1067 * @return string the HTML required to close any open containers inside <body>.
1069 public function container_end_all($shouldbenone = false) {
1070 return $this->opencontainers->pop_all_but_last($shouldbenone);
1074 * Returns course-specific information to be output immediately above content on any course page
1075 * (for the current course)
1077 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1078 * @return string
1080 public function course_content_header($onlyifnotcalledbefore = false) {
1081 global $CFG;
1082 if ($this->page->course->id == SITEID) {
1083 // return immediately and do not include /course/lib.php if not necessary
1084 return '';
1086 static $functioncalled = false;
1087 if ($functioncalled && $onlyifnotcalledbefore) {
1088 // we have already output the content header
1089 return '';
1091 require_once($CFG->dirroot.'/course/lib.php');
1092 $functioncalled = true;
1093 $courseformat = course_get_format($this->page->course);
1094 if (($obj = $courseformat->course_content_header()) !== null) {
1095 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1097 return '';
1101 * Returns course-specific information to be output immediately below content on any course page
1102 * (for the current course)
1104 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1105 * @return string
1107 public function course_content_footer($onlyifnotcalledbefore = false) {
1108 global $CFG;
1109 if ($this->page->course->id == SITEID) {
1110 // return immediately and do not include /course/lib.php if not necessary
1111 return '';
1113 static $functioncalled = false;
1114 if ($functioncalled && $onlyifnotcalledbefore) {
1115 // we have already output the content footer
1116 return '';
1118 $functioncalled = true;
1119 require_once($CFG->dirroot.'/course/lib.php');
1120 $courseformat = course_get_format($this->page->course);
1121 if (($obj = $courseformat->course_content_footer()) !== null) {
1122 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1124 return '';
1128 * Returns course-specific information to be output on any course page in the header area
1129 * (for the current course)
1131 * @return string
1133 public function course_header() {
1134 global $CFG;
1135 if ($this->page->course->id == SITEID) {
1136 // return immediately and do not include /course/lib.php if not necessary
1137 return '';
1139 require_once($CFG->dirroot.'/course/lib.php');
1140 $courseformat = course_get_format($this->page->course);
1141 if (($obj = $courseformat->course_header()) !== null) {
1142 return $courseformat->get_renderer($this->page)->render($obj);
1144 return '';
1148 * Returns course-specific information to be output on any course page in the footer area
1149 * (for the current course)
1151 * @return string
1153 public function course_footer() {
1154 global $CFG;
1155 if ($this->page->course->id == SITEID) {
1156 // return immediately and do not include /course/lib.php if not necessary
1157 return '';
1159 require_once($CFG->dirroot.'/course/lib.php');
1160 $courseformat = course_get_format($this->page->course);
1161 if (($obj = $courseformat->course_footer()) !== null) {
1162 return $courseformat->get_renderer($this->page)->render($obj);
1164 return '';
1168 * Returns lang menu or '', this method also checks forcing of languages in courses.
1170 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1172 * @return string The lang menu HTML or empty string
1174 public function lang_menu() {
1175 global $CFG;
1177 if (empty($CFG->langmenu)) {
1178 return '';
1181 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1182 // do not show lang menu if language forced
1183 return '';
1186 $currlang = current_language();
1187 $langs = get_string_manager()->get_list_of_translations();
1189 if (count($langs) < 2) {
1190 return '';
1193 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1194 $s->label = get_accesshide(get_string('language'));
1195 $s->class = 'langmenu';
1196 return $this->render($s);
1200 * Output the row of editing icons for a block, as defined by the controls array.
1202 * @param array $controls an array like {@link block_contents::$controls}.
1203 * @param string $blockid The ID given to the block.
1204 * @return string HTML fragment.
1206 public function block_controls($actions, $blockid = null) {
1207 global $CFG;
1208 if (empty($actions)) {
1209 return '';
1211 $menu = new action_menu($actions);
1212 if ($blockid !== null) {
1213 $menu->set_owner_selector('#'.$blockid);
1215 $menu->set_constraint('.block-region');
1216 $menu->attributes['class'] .= ' block-control-actions commands';
1217 if (isset($CFG->blockeditingmenu) && !$CFG->blockeditingmenu) {
1218 $menu->do_not_enhance();
1220 return $this->render($menu);
1224 * Renders an action menu component.
1226 * ARIA references:
1227 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1228 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1230 * @param action_menu $menu
1231 * @return string HTML
1233 public function render_action_menu(action_menu $menu) {
1234 $menu->initialise_js($this->page);
1236 $output = html_writer::start_tag('div', $menu->attributes);
1237 $output .= html_writer::start_tag('ul', $menu->attributesprimary);
1238 foreach ($menu->get_primary_actions($this) as $action) {
1239 if ($action instanceof renderable) {
1240 $content = $this->render($action);
1241 } else {
1242 $content = $action;
1244 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1246 $output .= html_writer::end_tag('ul');
1247 $output .= html_writer::start_tag('ul', $menu->attributessecondary);
1248 foreach ($menu->get_secondary_actions() as $action) {
1249 if ($action instanceof renderable) {
1250 $content = $this->render($action);
1251 } else {
1252 $content = $action;
1254 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1256 $output .= html_writer::end_tag('ul');
1257 $output .= html_writer::end_tag('div');
1258 return $output;
1262 * Renders an action_menu_link item.
1264 * @param action_menu_link $action
1265 * @return string HTML fragment
1267 protected function render_action_menu_link(action_menu_link $action) {
1268 static $actioncount = 0;
1269 $actioncount++;
1271 $comparetoalt = '';
1272 $text = '';
1273 if (!$action->icon || $action->primary === false) {
1274 $text .= html_writer::start_tag('span', array('class'=>'menu-action-text', 'id' => 'actionmenuaction-'.$actioncount));
1275 if ($action->text instanceof renderable) {
1276 $text .= $this->render($action->text);
1277 } else {
1278 $text .= $action->text;
1279 $comparetoalt = (string)$action->text;
1281 $text .= html_writer::end_tag('span');
1284 $icon = '';
1285 if ($action->icon) {
1286 $icon = $action->icon;
1287 if ($action->primary || !$action->actionmenu->will_be_enhanced()) {
1288 $action->attributes['title'] = $action->text;
1290 if (!$action->primary && $action->actionmenu->will_be_enhanced()) {
1291 if ((string)$icon->attributes['alt'] === $comparetoalt) {
1292 $icon->attributes['alt'] = '';
1294 if (isset($icon->attributes['title']) && (string)$icon->attributes['title'] === $comparetoalt) {
1295 unset($icon->attributes['title']);
1298 $icon = $this->render($icon);
1301 // A disabled link is rendered as formatted text.
1302 if (!empty($action->attributes['disabled'])) {
1303 // Do not use div here due to nesting restriction in xhtml strict.
1304 return html_writer::tag('span', $icon.$text, array('class'=>'currentlink', 'role' => 'menuitem'));
1307 $attributes = $action->attributes;
1308 unset($action->attributes['disabled']);
1309 $attributes['href'] = $action->url;
1310 if ($text !== '') {
1311 $attributes['aria-labelledby'] = 'actionmenuaction-'.$actioncount;
1314 return html_writer::tag('a', $icon.$text, $attributes);
1318 * Renders a primary action_menu_filler item.
1320 * @param action_menu_link_filler $action
1321 * @return string HTML fragment
1323 protected function render_action_menu_filler(action_menu_filler $action) {
1324 return html_writer::span('&nbsp;', 'filler');
1328 * Renders a primary action_menu_link item.
1330 * @param action_menu_link_primary $action
1331 * @return string HTML fragment
1333 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1334 return $this->render_action_menu_link($action);
1338 * Renders a secondary action_menu_link item.
1340 * @param action_menu_link_secondary $action
1341 * @return string HTML fragment
1343 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1344 return $this->render_action_menu_link($action);
1348 * Prints a nice side block with an optional header.
1350 * The content is described
1351 * by a {@link core_renderer::block_contents} object.
1353 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1354 * <div class="header"></div>
1355 * <div class="content">
1356 * ...CONTENT...
1357 * <div class="footer">
1358 * </div>
1359 * </div>
1360 * <div class="annotation">
1361 * </div>
1362 * </div>
1364 * @param block_contents $bc HTML for the content
1365 * @param string $region the region the block is appearing in.
1366 * @return string the HTML to be output.
1368 public function block(block_contents $bc, $region) {
1369 $bc = clone($bc); // Avoid messing up the object passed in.
1370 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1371 $bc->collapsible = block_contents::NOT_HIDEABLE;
1373 if (!empty($bc->blockinstanceid)) {
1374 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1376 $skiptitle = strip_tags($bc->title);
1377 if ($bc->blockinstanceid && !empty($skiptitle)) {
1378 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1379 } else if (!empty($bc->arialabel)) {
1380 $bc->attributes['aria-label'] = $bc->arialabel;
1382 if ($bc->dockable) {
1383 $bc->attributes['data-dockable'] = 1;
1385 if ($bc->collapsible == block_contents::HIDDEN) {
1386 $bc->add_class('hidden');
1388 if (!empty($bc->controls)) {
1389 $bc->add_class('block_with_controls');
1393 if (empty($skiptitle)) {
1394 $output = '';
1395 $skipdest = '';
1396 } else {
1397 $output = html_writer::link('#', get_string('skipa', 'access', $skiptitle),
1398 array('class' => 'skip skip-block', 'id'=>'fsb-' . $bc->skipid,
1399 'data-target' => '#sb-'.$bc->skipid));
1400 $skipdest = html_writer::span('', 'skip-block-to',
1401 array('id' => 'sb-' . $bc->skipid, 'tabindex' => '-1'));
1404 $output .= html_writer::start_tag('div', $bc->attributes);
1406 $output .= $this->block_header($bc);
1407 $output .= $this->block_content($bc);
1409 $output .= html_writer::end_tag('div');
1411 $output .= $this->block_annotation($bc);
1413 $output .= $skipdest;
1415 $this->init_block_hider_js($bc);
1416 return $output;
1420 * Produces a header for a block
1422 * @param block_contents $bc
1423 * @return string
1425 protected function block_header(block_contents $bc) {
1427 $title = '';
1428 if ($bc->title) {
1429 $attributes = array();
1430 if ($bc->blockinstanceid) {
1431 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1433 $title = html_writer::tag('h2', $bc->title, $attributes);
1436 $blockid = null;
1437 if (isset($bc->attributes['id'])) {
1438 $blockid = $bc->attributes['id'];
1440 $controlshtml = $this->block_controls($bc->controls, $blockid);
1442 $output = '';
1443 if ($title || $controlshtml) {
1444 $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'));
1446 return $output;
1450 * Produces the content area for a block
1452 * @param block_contents $bc
1453 * @return string
1455 protected function block_content(block_contents $bc) {
1456 $output = html_writer::start_tag('div', array('class' => 'content'));
1457 if (!$bc->title && !$this->block_controls($bc->controls)) {
1458 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1460 $output .= $bc->content;
1461 $output .= $this->block_footer($bc);
1462 $output .= html_writer::end_tag('div');
1464 return $output;
1468 * Produces the footer for a block
1470 * @param block_contents $bc
1471 * @return string
1473 protected function block_footer(block_contents $bc) {
1474 $output = '';
1475 if ($bc->footer) {
1476 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1478 return $output;
1482 * Produces the annotation for a block
1484 * @param block_contents $bc
1485 * @return string
1487 protected function block_annotation(block_contents $bc) {
1488 $output = '';
1489 if ($bc->annotation) {
1490 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1492 return $output;
1496 * Calls the JS require function to hide a block.
1498 * @param block_contents $bc A block_contents object
1500 protected function init_block_hider_js(block_contents $bc) {
1501 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1502 $config = new stdClass;
1503 $config->id = $bc->attributes['id'];
1504 $config->title = strip_tags($bc->title);
1505 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1506 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1507 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1509 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1510 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1515 * Render the contents of a block_list.
1517 * @param array $icons the icon for each item.
1518 * @param array $items the content of each item.
1519 * @return string HTML
1521 public function list_block_contents($icons, $items) {
1522 $row = 0;
1523 $lis = array();
1524 foreach ($items as $key => $string) {
1525 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1526 if (!empty($icons[$key])) { //test if the content has an assigned icon
1527 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1529 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1530 $item .= html_writer::end_tag('li');
1531 $lis[] = $item;
1532 $row = 1 - $row; // Flip even/odd.
1534 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1538 * Output all the blocks in a particular region.
1540 * @param string $region the name of a region on this page.
1541 * @return string the HTML to be output.
1543 public function blocks_for_region($region) {
1544 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1545 $blocks = $this->page->blocks->get_blocks_for_region($region);
1546 $lastblock = null;
1547 $zones = array();
1548 foreach ($blocks as $block) {
1549 $zones[] = $block->title;
1551 $output = '';
1553 foreach ($blockcontents as $bc) {
1554 if ($bc instanceof block_contents) {
1555 $output .= $this->block($bc, $region);
1556 $lastblock = $bc->title;
1557 } else if ($bc instanceof block_move_target) {
1558 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1559 } else {
1560 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1563 return $output;
1567 * Output a place where the block that is currently being moved can be dropped.
1569 * @param block_move_target $target with the necessary details.
1570 * @param array $zones array of areas where the block can be moved to
1571 * @param string $previous the block located before the area currently being rendered.
1572 * @param string $region the name of the region
1573 * @return string the HTML to be output.
1575 public function block_move_target($target, $zones, $previous, $region) {
1576 if ($previous == null) {
1577 if (empty($zones)) {
1578 // There are no zones, probably because there are no blocks.
1579 $regions = $this->page->theme->get_all_block_regions();
1580 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1581 } else {
1582 $position = get_string('moveblockbefore', 'block', $zones[0]);
1584 } else {
1585 $position = get_string('moveblockafter', 'block', $previous);
1587 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1591 * Renders a special html link with attached action
1593 * Theme developers: DO NOT OVERRIDE! Please override function
1594 * {@link core_renderer::render_action_link()} instead.
1596 * @param string|moodle_url $url
1597 * @param string $text HTML fragment
1598 * @param component_action $action
1599 * @param array $attributes associative array of html link attributes + disabled
1600 * @param pix_icon optional pix icon to render with the link
1601 * @return string HTML fragment
1603 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1604 if (!($url instanceof moodle_url)) {
1605 $url = new moodle_url($url);
1607 $link = new action_link($url, $text, $action, $attributes, $icon);
1609 return $this->render($link);
1613 * Renders an action_link object.
1615 * The provided link is renderer and the HTML returned. At the same time the
1616 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1618 * @param action_link $link
1619 * @return string HTML fragment
1621 protected function render_action_link(action_link $link) {
1622 global $CFG;
1624 $text = '';
1625 if ($link->icon) {
1626 $text .= $this->render($link->icon);
1629 if ($link->text instanceof renderable) {
1630 $text .= $this->render($link->text);
1631 } else {
1632 $text .= $link->text;
1635 // A disabled link is rendered as formatted text
1636 if (!empty($link->attributes['disabled'])) {
1637 // do not use div here due to nesting restriction in xhtml strict
1638 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1641 $attributes = $link->attributes;
1642 unset($link->attributes['disabled']);
1643 $attributes['href'] = $link->url;
1645 if ($link->actions) {
1646 if (empty($attributes['id'])) {
1647 $id = html_writer::random_id('action_link');
1648 $attributes['id'] = $id;
1649 } else {
1650 $id = $attributes['id'];
1652 foreach ($link->actions as $action) {
1653 $this->add_action_handler($action, $id);
1657 return html_writer::tag('a', $text, $attributes);
1662 * Renders an action_icon.
1664 * This function uses the {@link core_renderer::action_link()} method for the
1665 * most part. What it does different is prepare the icon as HTML and use it
1666 * as the link text.
1668 * Theme developers: If you want to change how action links and/or icons are rendered,
1669 * consider overriding function {@link core_renderer::render_action_link()} and
1670 * {@link core_renderer::render_pix_icon()}.
1672 * @param string|moodle_url $url A string URL or moodel_url
1673 * @param pix_icon $pixicon
1674 * @param component_action $action
1675 * @param array $attributes associative array of html link attributes + disabled
1676 * @param bool $linktext show title next to image in link
1677 * @return string HTML fragment
1679 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1680 if (!($url instanceof moodle_url)) {
1681 $url = new moodle_url($url);
1683 $attributes = (array)$attributes;
1685 if (empty($attributes['class'])) {
1686 // let ppl override the class via $options
1687 $attributes['class'] = 'action-icon';
1690 $icon = $this->render($pixicon);
1692 if ($linktext) {
1693 $text = $pixicon->attributes['alt'];
1694 } else {
1695 $text = '';
1698 return $this->action_link($url, $text.$icon, $action, $attributes);
1702 * Print a message along with button choices for Continue/Cancel
1704 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1706 * @param string $message The question to ask the user
1707 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1708 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1709 * @return string HTML fragment
1711 public function confirm($message, $continue, $cancel) {
1712 if ($continue instanceof single_button) {
1713 // ok
1714 } else if (is_string($continue)) {
1715 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1716 } else if ($continue instanceof moodle_url) {
1717 $continue = new single_button($continue, get_string('continue'), 'post');
1718 } else {
1719 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1722 if ($cancel instanceof single_button) {
1723 // ok
1724 } else if (is_string($cancel)) {
1725 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1726 } else if ($cancel instanceof moodle_url) {
1727 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1728 } else {
1729 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1732 $output = $this->box_start('generalbox', 'notice');
1733 $output .= html_writer::tag('p', $message);
1734 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1735 $output .= $this->box_end();
1736 return $output;
1740 * Returns a form with a single button.
1742 * Theme developers: DO NOT OVERRIDE! Please override function
1743 * {@link core_renderer::render_single_button()} instead.
1745 * @param string|moodle_url $url
1746 * @param string $label button text
1747 * @param string $method get or post submit method
1748 * @param array $options associative array {disabled, title, etc.}
1749 * @return string HTML fragment
1751 public function single_button($url, $label, $method='post', array $options=null) {
1752 if (!($url instanceof moodle_url)) {
1753 $url = new moodle_url($url);
1755 $button = new single_button($url, $label, $method);
1757 foreach ((array)$options as $key=>$value) {
1758 if (array_key_exists($key, $button)) {
1759 $button->$key = $value;
1763 return $this->render($button);
1767 * Renders a single button widget.
1769 * This will return HTML to display a form containing a single button.
1771 * @param single_button $button
1772 * @return string HTML fragment
1774 protected function render_single_button(single_button $button) {
1775 $attributes = array('type' => 'submit',
1776 'value' => $button->label,
1777 'disabled' => $button->disabled ? 'disabled' : null,
1778 'title' => $button->tooltip);
1780 if ($button->actions) {
1781 $id = html_writer::random_id('single_button');
1782 $attributes['id'] = $id;
1783 foreach ($button->actions as $action) {
1784 $this->add_action_handler($action, $id);
1788 // first the input element
1789 $output = html_writer::empty_tag('input', $attributes);
1791 // then hidden fields
1792 $params = $button->url->params();
1793 if ($button->method === 'post') {
1794 $params['sesskey'] = sesskey();
1796 foreach ($params as $var => $val) {
1797 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1800 // then div wrapper for xhtml strictness
1801 $output = html_writer::tag('div', $output);
1803 // now the form itself around it
1804 if ($button->method === 'get') {
1805 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1806 } else {
1807 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1809 if ($url === '') {
1810 $url = '#'; // there has to be always some action
1812 $attributes = array('method' => $button->method,
1813 'action' => $url,
1814 'id' => $button->formid);
1815 $output = html_writer::tag('form', $output, $attributes);
1817 // and finally one more wrapper with class
1818 return html_writer::tag('div', $output, array('class' => $button->class));
1822 * Returns a form with a single select widget.
1824 * Theme developers: DO NOT OVERRIDE! Please override function
1825 * {@link core_renderer::render_single_select()} instead.
1827 * @param moodle_url $url form action target, includes hidden fields
1828 * @param string $name name of selection field - the changing parameter in url
1829 * @param array $options list of options
1830 * @param string $selected selected element
1831 * @param array $nothing
1832 * @param string $formid
1833 * @param array $attributes other attributes for the single select
1834 * @return string HTML fragment
1836 public function single_select($url, $name, array $options, $selected = '',
1837 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
1838 if (!($url instanceof moodle_url)) {
1839 $url = new moodle_url($url);
1841 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1843 if (array_key_exists('label', $attributes)) {
1844 $select->set_label($attributes['label']);
1845 unset($attributes['label']);
1847 $select->attributes = $attributes;
1849 return $this->render($select);
1853 * Internal implementation of single_select rendering
1855 * @param single_select $select
1856 * @return string HTML fragment
1858 protected function render_single_select(single_select $select) {
1859 $select = clone($select);
1860 if (empty($select->formid)) {
1861 $select->formid = html_writer::random_id('single_select_f');
1864 $output = '';
1865 $params = $select->url->params();
1866 if ($select->method === 'post') {
1867 $params['sesskey'] = sesskey();
1869 foreach ($params as $name=>$value) {
1870 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1873 if (empty($select->attributes['id'])) {
1874 $select->attributes['id'] = html_writer::random_id('single_select');
1877 if ($select->disabled) {
1878 $select->attributes['disabled'] = 'disabled';
1881 if ($select->tooltip) {
1882 $select->attributes['title'] = $select->tooltip;
1885 $select->attributes['class'] = 'autosubmit';
1886 if ($select->class) {
1887 $select->attributes['class'] .= ' ' . $select->class;
1890 if ($select->label) {
1891 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1894 if ($select->helpicon instanceof help_icon) {
1895 $output .= $this->render($select->helpicon);
1897 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1899 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1900 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1902 $nothing = empty($select->nothing) ? false : key($select->nothing);
1903 $this->page->requires->yui_module('moodle-core-formautosubmit',
1904 'M.core.init_formautosubmit',
1905 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1908 // then div wrapper for xhtml strictness
1909 $output = html_writer::tag('div', $output);
1911 // now the form itself around it
1912 if ($select->method === 'get') {
1913 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1914 } else {
1915 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1917 $formattributes = array('method' => $select->method,
1918 'action' => $url,
1919 'id' => $select->formid);
1920 $output = html_writer::tag('form', $output, $formattributes);
1922 // and finally one more wrapper with class
1923 return html_writer::tag('div', $output, array('class' => $select->class));
1927 * Returns a form with a url select widget.
1929 * Theme developers: DO NOT OVERRIDE! Please override function
1930 * {@link core_renderer::render_url_select()} instead.
1932 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1933 * @param string $selected selected element
1934 * @param array $nothing
1935 * @param string $formid
1936 * @return string HTML fragment
1938 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1939 $select = new url_select($urls, $selected, $nothing, $formid);
1940 return $this->render($select);
1944 * Internal implementation of url_select rendering
1946 * @param url_select $select
1947 * @return string HTML fragment
1949 protected function render_url_select(url_select $select) {
1950 global $CFG;
1952 $select = clone($select);
1953 if (empty($select->formid)) {
1954 $select->formid = html_writer::random_id('url_select_f');
1957 if (empty($select->attributes['id'])) {
1958 $select->attributes['id'] = html_writer::random_id('url_select');
1961 if ($select->disabled) {
1962 $select->attributes['disabled'] = 'disabled';
1965 if ($select->tooltip) {
1966 $select->attributes['title'] = $select->tooltip;
1969 $output = '';
1971 if ($select->label) {
1972 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1975 $classes = array();
1976 if (!$select->showbutton) {
1977 $classes[] = 'autosubmit';
1979 if ($select->class) {
1980 $classes[] = $select->class;
1982 if (count($classes)) {
1983 $select->attributes['class'] = implode(' ', $classes);
1986 if ($select->helpicon instanceof help_icon) {
1987 $output .= $this->render($select->helpicon);
1990 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1991 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1992 $urls = array();
1993 foreach ($select->urls as $k=>$v) {
1994 if (is_array($v)) {
1995 // optgroup structure
1996 foreach ($v as $optgrouptitle => $optgroupoptions) {
1997 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1998 if (empty($optionurl)) {
1999 $safeoptionurl = '';
2000 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
2001 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
2002 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
2003 } else if (strpos($optionurl, '/') !== 0) {
2004 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
2005 continue;
2006 } else {
2007 $safeoptionurl = $optionurl;
2009 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
2012 } else {
2013 // plain list structure
2014 if (empty($k)) {
2015 // nothing selected option
2016 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
2017 $k = str_replace($CFG->wwwroot, '', $k);
2018 } else if (strpos($k, '/') !== 0) {
2019 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
2020 continue;
2022 $urls[$k] = $v;
2025 $selected = $select->selected;
2026 if (!empty($selected)) {
2027 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
2028 $selected = str_replace($CFG->wwwroot, '', $selected);
2029 } else if (strpos($selected, '/') !== 0) {
2030 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
2034 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
2035 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
2037 if (!$select->showbutton) {
2038 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
2039 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
2040 $nothing = empty($select->nothing) ? false : key($select->nothing);
2041 $this->page->requires->yui_module('moodle-core-formautosubmit',
2042 'M.core.init_formautosubmit',
2043 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
2045 } else {
2046 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
2049 // then div wrapper for xhtml strictness
2050 $output = html_writer::tag('div', $output);
2052 // now the form itself around it
2053 $formattributes = array('method' => 'post',
2054 'action' => new moodle_url('/course/jumpto.php'),
2055 'id' => $select->formid);
2056 $output = html_writer::tag('form', $output, $formattributes);
2058 // and finally one more wrapper with class
2059 return html_writer::tag('div', $output, array('class' => $select->class));
2063 * Returns a string containing a link to the user documentation.
2064 * Also contains an icon by default. Shown to teachers and admin only.
2066 * @param string $path The page link after doc root and language, no leading slash.
2067 * @param string $text The text to be displayed for the link
2068 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2069 * @return string
2071 public function doc_link($path, $text = '', $forcepopup = false) {
2072 global $CFG;
2074 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
2076 $url = new moodle_url(get_docs_url($path));
2078 $attributes = array('href'=>$url);
2079 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2080 $attributes['class'] = 'helplinkpopup';
2083 return html_writer::tag('a', $icon.$text, $attributes);
2087 * Return HTML for a pix_icon.
2089 * Theme developers: DO NOT OVERRIDE! Please override function
2090 * {@link core_renderer::render_pix_icon()} instead.
2092 * @param string $pix short pix name
2093 * @param string $alt mandatory alt attribute
2094 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2095 * @param array $attributes htm lattributes
2096 * @return string HTML fragment
2098 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2099 $icon = new pix_icon($pix, $alt, $component, $attributes);
2100 return $this->render($icon);
2104 * Renders a pix_icon widget and returns the HTML to display it.
2106 * @param pix_icon $icon
2107 * @return string HTML fragment
2109 protected function render_pix_icon(pix_icon $icon) {
2110 $data = $icon->export_for_template($this);
2111 return $this->render_from_template('core/pix_icon', $data);
2115 * Return HTML to display an emoticon icon.
2117 * @param pix_emoticon $emoticon
2118 * @return string HTML fragment
2120 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2121 $attributes = $emoticon->attributes;
2122 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
2123 return html_writer::empty_tag('img', $attributes);
2127 * Produces the html that represents this rating in the UI
2129 * @param rating $rating the page object on which this rating will appear
2130 * @return string
2132 function render_rating(rating $rating) {
2133 global $CFG, $USER;
2135 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2136 return null;//ratings are turned off
2139 $ratingmanager = new rating_manager();
2140 // Initialise the JavaScript so ratings can be done by AJAX.
2141 $ratingmanager->initialise_rating_javascript($this->page);
2143 $strrate = get_string("rate", "rating");
2144 $ratinghtml = ''; //the string we'll return
2146 // permissions check - can they view the aggregate?
2147 if ($rating->user_can_view_aggregate()) {
2149 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2150 $aggregatestr = $rating->get_aggregate_string();
2152 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2153 if ($rating->count > 0) {
2154 $countstr = "({$rating->count})";
2155 } else {
2156 $countstr = '-';
2158 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2160 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2161 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2163 $nonpopuplink = $rating->get_view_ratings_url();
2164 $popuplink = $rating->get_view_ratings_url(true);
2166 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2167 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2168 } else {
2169 $ratinghtml .= $aggregatehtml;
2173 $formstart = null;
2174 // if the item doesn't belong to the current user, the user has permission to rate
2175 // and we're within the assessable period
2176 if ($rating->user_can_rate()) {
2178 $rateurl = $rating->get_rate_url();
2179 $inputs = $rateurl->params();
2181 //start the rating form
2182 $formattrs = array(
2183 'id' => "postrating{$rating->itemid}",
2184 'class' => 'postratingform',
2185 'method' => 'post',
2186 'action' => $rateurl->out_omit_querystring()
2188 $formstart = html_writer::start_tag('form', $formattrs);
2189 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2191 // add the hidden inputs
2192 foreach ($inputs as $name => $value) {
2193 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2194 $formstart .= html_writer::empty_tag('input', $attributes);
2197 if (empty($ratinghtml)) {
2198 $ratinghtml .= $strrate.': ';
2200 $ratinghtml = $formstart.$ratinghtml;
2202 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2203 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2204 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2205 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2207 //output submit button
2208 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2210 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2211 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2213 if (!$rating->settings->scale->isnumeric) {
2214 // If a global scale, try to find current course ID from the context
2215 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2216 $courseid = $coursecontext->instanceid;
2217 } else {
2218 $courseid = $rating->settings->scale->courseid;
2220 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2222 $ratinghtml .= html_writer::end_tag('span');
2223 $ratinghtml .= html_writer::end_tag('div');
2224 $ratinghtml .= html_writer::end_tag('form');
2227 return $ratinghtml;
2231 * Centered heading with attached help button (same title text)
2232 * and optional icon attached.
2234 * @param string $text A heading text
2235 * @param string $helpidentifier The keyword that defines a help page
2236 * @param string $component component name
2237 * @param string|moodle_url $icon
2238 * @param string $iconalt icon alt text
2239 * @param int $level The level of importance of the heading. Defaulting to 2
2240 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2241 * @return string HTML fragment
2243 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2244 $image = '';
2245 if ($icon) {
2246 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2249 $help = '';
2250 if ($helpidentifier) {
2251 $help = $this->help_icon($helpidentifier, $component);
2254 return $this->heading($image.$text.$help, $level, $classnames);
2258 * Returns HTML to display a help icon.
2260 * @deprecated since Moodle 2.0
2262 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2263 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2267 * Returns HTML to display a help icon.
2269 * Theme developers: DO NOT OVERRIDE! Please override function
2270 * {@link core_renderer::render_help_icon()} instead.
2272 * @param string $identifier The keyword that defines a help page
2273 * @param string $component component name
2274 * @param string|bool $linktext true means use $title as link text, string means link text value
2275 * @return string HTML fragment
2277 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2278 $icon = new help_icon($identifier, $component);
2279 $icon->diag_strings();
2280 if ($linktext === true) {
2281 $icon->linktext = get_string($icon->identifier, $icon->component);
2282 } else if (!empty($linktext)) {
2283 $icon->linktext = $linktext;
2285 return $this->render($icon);
2289 * Implementation of user image rendering.
2291 * @param help_icon $helpicon A help icon instance
2292 * @return string HTML fragment
2294 protected function render_help_icon(help_icon $helpicon) {
2295 global $CFG;
2297 // first get the help image icon
2298 $src = $this->pix_url('help');
2300 $title = get_string($helpicon->identifier, $helpicon->component);
2302 if (empty($helpicon->linktext)) {
2303 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
2304 } else {
2305 $alt = get_string('helpwiththis');
2308 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
2309 $output = html_writer::empty_tag('img', $attributes);
2311 // add the link text if given
2312 if (!empty($helpicon->linktext)) {
2313 // the spacing has to be done through CSS
2314 $output .= $helpicon->linktext;
2317 // now create the link around it - we need https on loginhttps pages
2318 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
2320 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
2321 $title = get_string('helpprefix2', '', trim($title, ". \t"));
2323 $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true', 'target'=>'_blank');
2324 $output = html_writer::tag('a', $output, $attributes);
2326 // and finally span
2327 return html_writer::tag('span', $output, array('class' => 'helptooltip'));
2331 * Returns HTML to display a scale help icon.
2333 * @param int $courseid
2334 * @param stdClass $scale instance
2335 * @return string HTML fragment
2337 public function help_icon_scale($courseid, stdClass $scale) {
2338 global $CFG;
2340 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2342 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2344 $scaleid = abs($scale->id);
2346 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2347 $action = new popup_action('click', $link, 'ratingscale');
2349 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2353 * Creates and returns a spacer image with optional line break.
2355 * @param array $attributes Any HTML attributes to add to the spaced.
2356 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2357 * laxy do it with CSS which is a much better solution.
2358 * @return string HTML fragment
2360 public function spacer(array $attributes = null, $br = false) {
2361 $attributes = (array)$attributes;
2362 if (empty($attributes['width'])) {
2363 $attributes['width'] = 1;
2365 if (empty($attributes['height'])) {
2366 $attributes['height'] = 1;
2368 $attributes['class'] = 'spacer';
2370 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2372 if (!empty($br)) {
2373 $output .= '<br />';
2376 return $output;
2380 * Returns HTML to display the specified user's avatar.
2382 * User avatar may be obtained in two ways:
2383 * <pre>
2384 * // Option 1: (shortcut for simple cases, preferred way)
2385 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2386 * $OUTPUT->user_picture($user, array('popup'=>true));
2388 * // Option 2:
2389 * $userpic = new user_picture($user);
2390 * // Set properties of $userpic
2391 * $userpic->popup = true;
2392 * $OUTPUT->render($userpic);
2393 * </pre>
2395 * Theme developers: DO NOT OVERRIDE! Please override function
2396 * {@link core_renderer::render_user_picture()} instead.
2398 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2399 * If any of these are missing, the database is queried. Avoid this
2400 * if at all possible, particularly for reports. It is very bad for performance.
2401 * @param array $options associative array with user picture options, used only if not a user_picture object,
2402 * options are:
2403 * - courseid=$this->page->course->id (course id of user profile in link)
2404 * - size=35 (size of image)
2405 * - link=true (make image clickable - the link leads to user profile)
2406 * - popup=false (open in popup)
2407 * - alttext=true (add image alt attribute)
2408 * - class = image class attribute (default 'userpicture')
2409 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2410 * @return string HTML fragment
2412 public function user_picture(stdClass $user, array $options = null) {
2413 $userpicture = new user_picture($user);
2414 foreach ((array)$options as $key=>$value) {
2415 if (array_key_exists($key, $userpicture)) {
2416 $userpicture->$key = $value;
2419 return $this->render($userpicture);
2423 * Internal implementation of user image rendering.
2425 * @param user_picture $userpicture
2426 * @return string
2428 protected function render_user_picture(user_picture $userpicture) {
2429 global $CFG, $DB;
2431 $user = $userpicture->user;
2433 if ($userpicture->alttext) {
2434 if (!empty($user->imagealt)) {
2435 $alt = $user->imagealt;
2436 } else {
2437 $alt = get_string('pictureof', '', fullname($user));
2439 } else {
2440 $alt = '';
2443 if (empty($userpicture->size)) {
2444 $size = 35;
2445 } else if ($userpicture->size === true or $userpicture->size == 1) {
2446 $size = 100;
2447 } else {
2448 $size = $userpicture->size;
2451 $class = $userpicture->class;
2453 if ($user->picture == 0) {
2454 $class .= ' defaultuserpic';
2457 $src = $userpicture->get_url($this->page, $this);
2459 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2460 if (!$userpicture->visibletoscreenreaders) {
2461 $attributes['role'] = 'presentation';
2464 // get the image html output fisrt
2465 $output = html_writer::empty_tag('img', $attributes);
2467 // then wrap it in link if needed
2468 if (!$userpicture->link) {
2469 return $output;
2472 if (empty($userpicture->courseid)) {
2473 $courseid = $this->page->course->id;
2474 } else {
2475 $courseid = $userpicture->courseid;
2478 if ($courseid == SITEID) {
2479 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2480 } else {
2481 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2484 $attributes = array('href'=>$url);
2485 if (!$userpicture->visibletoscreenreaders) {
2486 $attributes['tabindex'] = '-1';
2487 $attributes['aria-hidden'] = 'true';
2490 if ($userpicture->popup) {
2491 $id = html_writer::random_id('userpicture');
2492 $attributes['id'] = $id;
2493 $this->add_action_handler(new popup_action('click', $url), $id);
2496 return html_writer::tag('a', $output, $attributes);
2500 * Internal implementation of file tree viewer items rendering.
2502 * @param array $dir
2503 * @return string
2505 public function htmllize_file_tree($dir) {
2506 if (empty($dir['subdirs']) and empty($dir['files'])) {
2507 return '';
2509 $result = '<ul>';
2510 foreach ($dir['subdirs'] as $subdir) {
2511 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2513 foreach ($dir['files'] as $file) {
2514 $filename = $file->get_filename();
2515 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2517 $result .= '</ul>';
2519 return $result;
2523 * Returns HTML to display the file picker
2525 * <pre>
2526 * $OUTPUT->file_picker($options);
2527 * </pre>
2529 * Theme developers: DO NOT OVERRIDE! Please override function
2530 * {@link core_renderer::render_file_picker()} instead.
2532 * @param array $options associative array with file manager options
2533 * options are:
2534 * maxbytes=>-1,
2535 * itemid=>0,
2536 * client_id=>uniqid(),
2537 * acepted_types=>'*',
2538 * return_types=>FILE_INTERNAL,
2539 * context=>$PAGE->context
2540 * @return string HTML fragment
2542 public function file_picker($options) {
2543 $fp = new file_picker($options);
2544 return $this->render($fp);
2548 * Internal implementation of file picker rendering.
2550 * @param file_picker $fp
2551 * @return string
2553 public function render_file_picker(file_picker $fp) {
2554 global $CFG, $OUTPUT, $USER;
2555 $options = $fp->options;
2556 $client_id = $options->client_id;
2557 $strsaved = get_string('filesaved', 'repository');
2558 $straddfile = get_string('openpicker', 'repository');
2559 $strloading = get_string('loading', 'repository');
2560 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2561 $strdroptoupload = get_string('droptoupload', 'moodle');
2562 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2564 $currentfile = $options->currentfile;
2565 if (empty($currentfile)) {
2566 $currentfile = '';
2567 } else {
2568 $currentfile .= ' - ';
2570 if ($options->maxbytes) {
2571 $size = $options->maxbytes;
2572 } else {
2573 $size = get_max_upload_file_size();
2575 if ($size == -1) {
2576 $maxsize = '';
2577 } else {
2578 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2580 if ($options->buttonname) {
2581 $buttonname = ' name="' . $options->buttonname . '"';
2582 } else {
2583 $buttonname = '';
2585 $html = <<<EOD
2586 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2587 $icon_progress
2588 </div>
2589 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2590 <div>
2591 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2592 <span> $maxsize </span>
2593 </div>
2594 EOD;
2595 if ($options->env != 'url') {
2596 $html .= <<<EOD
2597 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2598 <div class="filepicker-filename">
2599 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2600 <div class="dndupload-progressbars"></div>
2601 </div>
2602 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2603 </div>
2604 EOD;
2606 $html .= '</div>';
2607 return $html;
2611 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2613 * @param string $cmid the course_module id.
2614 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2615 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2617 public function update_module_button($cmid, $modulename) {
2618 global $CFG;
2619 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2620 $modulename = get_string('modulename', $modulename);
2621 $string = get_string('updatethis', '', $modulename);
2622 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2623 return $this->single_button($url, $string);
2624 } else {
2625 return '';
2630 * Returns HTML to display a "Turn editing on/off" button in a form.
2632 * @param moodle_url $url The URL + params to send through when clicking the button
2633 * @return string HTML the button
2635 public function edit_button(moodle_url $url) {
2637 $url->param('sesskey', sesskey());
2638 if ($this->page->user_is_editing()) {
2639 $url->param('edit', 'off');
2640 $editstring = get_string('turneditingoff');
2641 } else {
2642 $url->param('edit', 'on');
2643 $editstring = get_string('turneditingon');
2646 return $this->single_button($url, $editstring);
2650 * Returns HTML to display a simple button to close a window
2652 * @param string $text The lang string for the button's label (already output from get_string())
2653 * @return string html fragment
2655 public function close_window_button($text='') {
2656 if (empty($text)) {
2657 $text = get_string('closewindow');
2659 $button = new single_button(new moodle_url('#'), $text, 'get');
2660 $button->add_action(new component_action('click', 'close_window'));
2662 return $this->container($this->render($button), 'closewindow');
2666 * Output an error message. By default wraps the error message in <span class="error">.
2667 * If the error message is blank, nothing is output.
2669 * @param string $message the error message.
2670 * @return string the HTML to output.
2672 public function error_text($message) {
2673 if (empty($message)) {
2674 return '';
2676 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2677 return html_writer::tag('span', $message, array('class' => 'error'));
2681 * Do not call this function directly.
2683 * To terminate the current script with a fatal error, call the {@link print_error}
2684 * function, or throw an exception. Doing either of those things will then call this
2685 * function to display the error, before terminating the execution.
2687 * @param string $message The message to output
2688 * @param string $moreinfourl URL where more info can be found about the error
2689 * @param string $link Link for the Continue button
2690 * @param array $backtrace The execution backtrace
2691 * @param string $debuginfo Debugging information
2692 * @return string the HTML to output.
2694 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2695 global $CFG;
2697 $output = '';
2698 $obbuffer = '';
2700 if ($this->has_started()) {
2701 // we can not always recover properly here, we have problems with output buffering,
2702 // html tables, etc.
2703 $output .= $this->opencontainers->pop_all_but_last();
2705 } else {
2706 // It is really bad if library code throws exception when output buffering is on,
2707 // because the buffered text would be printed before our start of page.
2708 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2709 error_reporting(0); // disable notices from gzip compression, etc.
2710 while (ob_get_level() > 0) {
2711 $buff = ob_get_clean();
2712 if ($buff === false) {
2713 break;
2715 $obbuffer .= $buff;
2717 error_reporting($CFG->debug);
2719 // Output not yet started.
2720 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2721 if (empty($_SERVER['HTTP_RANGE'])) {
2722 @header($protocol . ' 404 Not Found');
2723 } else {
2724 // Must stop byteserving attempts somehow,
2725 // this is weird but Chrome PDF viewer can be stopped only with 407!
2726 @header($protocol . ' 407 Proxy Authentication Required');
2729 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2730 $this->page->set_url('/'); // no url
2731 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2732 $this->page->set_title(get_string('error'));
2733 $this->page->set_heading($this->page->course->fullname);
2734 $output .= $this->header();
2737 $message = '<p class="errormessage">' . $message . '</p>'.
2738 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2739 get_string('moreinformation') . '</a></p>';
2740 if (empty($CFG->rolesactive)) {
2741 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2742 //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.
2744 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
2746 if ($CFG->debugdeveloper) {
2747 if (!empty($debuginfo)) {
2748 $debuginfo = s($debuginfo); // removes all nasty JS
2749 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2750 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2752 if (!empty($backtrace)) {
2753 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2755 if ($obbuffer !== '' ) {
2756 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2760 if (empty($CFG->rolesactive)) {
2761 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2762 } else if (!empty($link)) {
2763 $output .= $this->continue_button($link);
2766 $output .= $this->footer();
2768 // Padding to encourage IE to display our error page, rather than its own.
2769 $output .= str_repeat(' ', 512);
2771 return $output;
2775 * Output a notification (that is, a status message about something that has
2776 * just happened).
2778 * @param string $message the message to print out
2779 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2780 * @return string the HTML to output.
2782 public function notification($message, $classes = 'notifyproblem') {
2784 $classmappings = array(
2785 'notifyproblem' => \core\output\notification::NOTIFY_PROBLEM,
2786 'notifytiny' => \core\output\notification::NOTIFY_PROBLEM,
2787 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2788 'notifymessage' => \core\output\notification::NOTIFY_MESSAGE,
2789 'redirectmessage' => \core\output\notification::NOTIFY_REDIRECT
2792 // Identify what type of notification this is.
2793 $type = \core\output\notification::NOTIFY_PROBLEM;
2794 $classarray = explode(' ', self::prepare_classes($classes));
2795 if (count($classarray) > 0) {
2796 foreach ($classarray as $class) {
2797 if (isset($classmappings[$class])) {
2798 $type = $classmappings[$class];
2799 break;
2804 $n = new \core\output\notification($message, $type);
2805 return $this->render($n);
2810 * Output a notification at a particular level - in this case, NOTIFY_PROBLEM.
2812 * @param string $message the message to print out
2813 * @return string HTML fragment.
2815 public function notify_problem($message) {
2816 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_PROBLEM);
2817 return $this->render($n);
2821 * Output a notification at a particular level - in this case, NOTIFY_SUCCESS.
2823 * @param string $message the message to print out
2824 * @return string HTML fragment.
2826 public function notify_success($message) {
2827 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_SUCCESS);
2828 return $this->render($n);
2832 * Output a notification at a particular level - in this case, NOTIFY_MESSAGE.
2834 * @param string $message the message to print out
2835 * @return string HTML fragment.
2837 public function notify_message($message) {
2838 $n = new notification($message, notification::NOTIFY_MESSAGE);
2839 return $this->render($n);
2843 * Output a notification at a particular level - in this case, NOTIFY_REDIRECT.
2845 * @param string $message the message to print out
2846 * @return string HTML fragment.
2848 public function notify_redirect($message) {
2849 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_REDIRECT);
2850 return $this->render($n);
2854 * Render a notification (that is, a status message about something that has
2855 * just happened).
2857 * @param \core\output\notification $notification the notification to print out
2858 * @return string the HTML to output.
2860 protected function render_notification(\core\output\notification $notification) {
2862 $data = $notification->export_for_template($this);
2864 $templatename = '';
2865 switch($data->type) {
2866 case \core\output\notification::NOTIFY_MESSAGE:
2867 $templatename = 'core/notification_message';
2868 break;
2869 case \core\output\notification::NOTIFY_SUCCESS:
2870 $templatename = 'core/notification_success';
2871 break;
2872 case \core\output\notification::NOTIFY_PROBLEM:
2873 $templatename = 'core/notification_problem';
2874 break;
2875 case \core\output\notification::NOTIFY_REDIRECT:
2876 $templatename = 'core/notification_redirect';
2877 break;
2878 default:
2879 $templatename = 'core/notification_message';
2880 break;
2883 return self::render_from_template($templatename, $data);
2888 * Returns HTML to display a continue button that goes to a particular URL.
2890 * @param string|moodle_url $url The url the button goes to.
2891 * @return string the HTML to output.
2893 public function continue_button($url) {
2894 if (!($url instanceof moodle_url)) {
2895 $url = new moodle_url($url);
2897 $button = new single_button($url, get_string('continue'), 'get');
2898 $button->class = 'continuebutton';
2900 return $this->render($button);
2904 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2906 * Theme developers: DO NOT OVERRIDE! Please override function
2907 * {@link core_renderer::render_paging_bar()} instead.
2909 * @param int $totalcount The total number of entries available to be paged through
2910 * @param int $page The page you are currently viewing
2911 * @param int $perpage The number of entries that should be shown per page
2912 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2913 * @param string $pagevar name of page parameter that holds the page number
2914 * @return string the HTML to output.
2916 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2917 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2918 return $this->render($pb);
2922 * Internal implementation of paging bar rendering.
2924 * @param paging_bar $pagingbar
2925 * @return string
2927 protected function render_paging_bar(paging_bar $pagingbar) {
2928 $output = '';
2929 $pagingbar = clone($pagingbar);
2930 $pagingbar->prepare($this, $this->page, $this->target);
2932 if ($pagingbar->totalcount > $pagingbar->perpage) {
2933 $output .= get_string('page') . ':';
2935 if (!empty($pagingbar->previouslink)) {
2936 $output .= ' (' . $pagingbar->previouslink . ') ';
2939 if (!empty($pagingbar->firstlink)) {
2940 $output .= ' ' . $pagingbar->firstlink . ' ...';
2943 foreach ($pagingbar->pagelinks as $link) {
2944 $output .= " $link";
2947 if (!empty($pagingbar->lastlink)) {
2948 $output .= ' ...' . $pagingbar->lastlink . ' ';
2951 if (!empty($pagingbar->nextlink)) {
2952 $output .= ' (' . $pagingbar->nextlink . ')';
2956 return html_writer::tag('div', $output, array('class' => 'paging'));
2960 * Output the place a skip link goes to.
2962 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2963 * @return string the HTML to output.
2965 public function skip_link_target($id = null) {
2966 return html_writer::span('', '', array('id' => $id, 'tabindex' => '-1'));
2970 * Outputs a heading
2972 * @param string $text The text of the heading
2973 * @param int $level The level of importance of the heading. Defaulting to 2
2974 * @param string $classes A space-separated list of CSS classes. Defaulting to null
2975 * @param string $id An optional ID
2976 * @return string the HTML to output.
2978 public function heading($text, $level = 2, $classes = null, $id = null) {
2979 $level = (integer) $level;
2980 if ($level < 1 or $level > 6) {
2981 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2983 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2987 * Outputs a box.
2989 * @param string $contents The contents of the box
2990 * @param string $classes A space-separated list of CSS classes
2991 * @param string $id An optional ID
2992 * @param array $attributes An array of other attributes to give the box.
2993 * @return string the HTML to output.
2995 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
2996 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3000 * Outputs the opening section of a box.
3002 * @param string $classes A space-separated list of CSS classes
3003 * @param string $id An optional ID
3004 * @param array $attributes An array of other attributes to give the box.
3005 * @return string the HTML to output.
3007 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3008 $this->opencontainers->push('box', html_writer::end_tag('div'));
3009 $attributes['id'] = $id;
3010 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
3011 return html_writer::start_tag('div', $attributes);
3015 * Outputs the closing section of a box.
3017 * @return string the HTML to output.
3019 public function box_end() {
3020 return $this->opencontainers->pop('box');
3024 * Outputs a container.
3026 * @param string $contents The contents of the box
3027 * @param string $classes A space-separated list of CSS classes
3028 * @param string $id An optional ID
3029 * @return string the HTML to output.
3031 public function container($contents, $classes = null, $id = null) {
3032 return $this->container_start($classes, $id) . $contents . $this->container_end();
3036 * Outputs the opening section of a container.
3038 * @param string $classes A space-separated list of CSS classes
3039 * @param string $id An optional ID
3040 * @return string the HTML to output.
3042 public function container_start($classes = null, $id = null) {
3043 $this->opencontainers->push('container', html_writer::end_tag('div'));
3044 return html_writer::start_tag('div', array('id' => $id,
3045 'class' => renderer_base::prepare_classes($classes)));
3049 * Outputs the closing section of a container.
3051 * @return string the HTML to output.
3053 public function container_end() {
3054 return $this->opencontainers->pop('container');
3058 * Make nested HTML lists out of the items
3060 * The resulting list will look something like this:
3062 * <pre>
3063 * <<ul>>
3064 * <<li>><div class='tree_item parent'>(item contents)</div>
3065 * <<ul>
3066 * <<li>><div class='tree_item'>(item contents)</div><</li>>
3067 * <</ul>>
3068 * <</li>>
3069 * <</ul>>
3070 * </pre>
3072 * @param array $items
3073 * @param array $attrs html attributes passed to the top ofs the list
3074 * @return string HTML
3076 public function tree_block_contents($items, $attrs = array()) {
3077 // exit if empty, we don't want an empty ul element
3078 if (empty($items)) {
3079 return '';
3081 // array of nested li elements
3082 $lis = array();
3083 foreach ($items as $item) {
3084 // this applies to the li item which contains all child lists too
3085 $content = $item->content($this);
3086 $liclasses = array($item->get_css_type());
3087 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3088 $liclasses[] = 'collapsed';
3090 if ($item->isactive === true) {
3091 $liclasses[] = 'current_branch';
3093 $liattr = array('class'=>join(' ',$liclasses));
3094 // class attribute on the div item which only contains the item content
3095 $divclasses = array('tree_item');
3096 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3097 $divclasses[] = 'branch';
3098 } else {
3099 $divclasses[] = 'leaf';
3101 if (!empty($item->classes) && count($item->classes)>0) {
3102 $divclasses[] = join(' ', $item->classes);
3104 $divattr = array('class'=>join(' ', $divclasses));
3105 if (!empty($item->id)) {
3106 $divattr['id'] = $item->id;
3108 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3109 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3110 $content = html_writer::empty_tag('hr') . $content;
3112 $content = html_writer::tag('li', $content, $liattr);
3113 $lis[] = $content;
3115 return html_writer::tag('ul', implode("\n", $lis), $attrs);
3119 * Construct a user menu, returning HTML that can be echoed out by a
3120 * layout file.
3122 * @param stdClass $user A user object, usually $USER.
3123 * @param bool $withlinks true if a dropdown should be built.
3124 * @return string HTML fragment.
3126 public function user_menu($user = null, $withlinks = null) {
3127 global $USER, $CFG;
3128 require_once($CFG->dirroot . '/user/lib.php');
3130 if (is_null($user)) {
3131 $user = $USER;
3134 // Note: this behaviour is intended to match that of core_renderer::login_info,
3135 // but should not be considered to be good practice; layout options are
3136 // intended to be theme-specific. Please don't copy this snippet anywhere else.
3137 if (is_null($withlinks)) {
3138 $withlinks = empty($this->page->layout_options['nologinlinks']);
3141 // Add a class for when $withlinks is false.
3142 $usermenuclasses = 'usermenu';
3143 if (!$withlinks) {
3144 $usermenuclasses .= ' withoutlinks';
3147 $returnstr = "";
3149 // If during initial install, return the empty return string.
3150 if (during_initial_install()) {
3151 return $returnstr;
3154 $loginpage = $this->is_login_page();
3155 $loginurl = get_login_url();
3156 // If not logged in, show the typical not-logged-in string.
3157 if (!isloggedin()) {
3158 $returnstr = get_string('loggedinnot', 'moodle');
3159 if (!$loginpage) {
3160 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3162 return html_writer::div(
3163 html_writer::span(
3164 $returnstr,
3165 'login'
3167 $usermenuclasses
3172 // If logged in as a guest user, show a string to that effect.
3173 if (isguestuser()) {
3174 $returnstr = get_string('loggedinasguest');
3175 if (!$loginpage && $withlinks) {
3176 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
3179 return html_writer::div(
3180 html_writer::span(
3181 $returnstr,
3182 'login'
3184 $usermenuclasses
3188 // Get some navigation opts.
3189 $opts = user_get_user_navigation_info($user, $this->page);
3191 $avatarclasses = "avatars";
3192 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3193 $usertextcontents = $opts->metadata['userfullname'];
3195 // Other user.
3196 if (!empty($opts->metadata['asotheruser'])) {
3197 $avatarcontents .= html_writer::span(
3198 $opts->metadata['realuseravatar'],
3199 'avatar realuser'
3201 $usertextcontents = $opts->metadata['realuserfullname'];
3202 $usertextcontents .= html_writer::tag(
3203 'span',
3204 get_string(
3205 'loggedinas',
3206 'moodle',
3207 html_writer::span(
3208 $opts->metadata['userfullname'],
3209 'value'
3212 array('class' => 'meta viewingas')
3216 // Role.
3217 if (!empty($opts->metadata['asotherrole'])) {
3218 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3219 $usertextcontents .= html_writer::span(
3220 $opts->metadata['rolename'],
3221 'meta role role-' . $role
3225 // User login failures.
3226 if (!empty($opts->metadata['userloginfail'])) {
3227 $usertextcontents .= html_writer::span(
3228 $opts->metadata['userloginfail'],
3229 'meta loginfailures'
3233 // MNet.
3234 if (!empty($opts->metadata['asmnetuser'])) {
3235 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3236 $usertextcontents .= html_writer::span(
3237 $opts->metadata['mnetidprovidername'],
3238 'meta mnet mnet-' . $mnet
3242 $returnstr .= html_writer::span(
3243 html_writer::span($usertextcontents, 'usertext') .
3244 html_writer::span($avatarcontents, $avatarclasses),
3245 'userbutton'
3248 // Create a divider (well, a filler).
3249 $divider = new action_menu_filler();
3250 $divider->primary = false;
3252 $am = new action_menu();
3253 $am->initialise_js($this->page);
3254 $am->set_menu_trigger(
3255 $returnstr
3257 $am->set_alignment(action_menu::TR, action_menu::BR);
3258 $am->set_nowrap_on_items();
3259 if ($withlinks) {
3260 $navitemcount = count($opts->navitems);
3261 $idx = 0;
3262 foreach ($opts->navitems as $key => $value) {
3264 switch ($value->itemtype) {
3265 case 'divider':
3266 // If the nav item is a divider, add one and skip link processing.
3267 $am->add($divider);
3268 break;
3270 case 'invalid':
3271 // Silently skip invalid entries (should we post a notification?).
3272 break;
3274 case 'link':
3275 // Process this as a link item.
3276 $pix = null;
3277 if (isset($value->pix) && !empty($value->pix)) {
3278 $pix = new pix_icon($value->pix, $value->title, null, array('class' => 'iconsmall'));
3279 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3280 $value->title = html_writer::img(
3281 $value->imgsrc,
3282 $value->title,
3283 array('class' => 'iconsmall')
3284 ) . $value->title;
3286 $al = new action_menu_link_secondary(
3287 $value->url,
3288 $pix,
3289 $value->title,
3290 array('class' => 'icon')
3292 $am->add($al);
3293 break;
3296 $idx++;
3298 // Add dividers after the first item and before the last item.
3299 if ($idx == 1 || $idx == $navitemcount - 1) {
3300 $am->add($divider);
3305 return html_writer::div(
3306 $this->render($am),
3307 $usermenuclasses
3312 * Return the navbar content so that it can be echoed out by the layout
3314 * @return string XHTML navbar
3316 public function navbar() {
3317 $items = $this->page->navbar->get_items();
3318 $itemcount = count($items);
3319 if ($itemcount === 0) {
3320 return '';
3323 $htmlblocks = array();
3324 // Iterate the navarray and display each node
3325 $separator = get_separator();
3326 for ($i=0;$i < $itemcount;$i++) {
3327 $item = $items[$i];
3328 $item->hideicon = true;
3329 if ($i===0) {
3330 $content = html_writer::tag('li', $this->render($item));
3331 } else {
3332 $content = html_writer::tag('li', $separator.$this->render($item));
3334 $htmlblocks[] = $content;
3337 //accessibility: heading for navbar list (MDL-20446)
3338 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
3339 $navbarcontent .= html_writer::tag('nav', html_writer::tag('ul', join('', $htmlblocks)));
3340 // XHTML
3341 return $navbarcontent;
3345 * Renders a navigation node object.
3347 * @param navigation_node $item The navigation node to render.
3348 * @return string HTML fragment
3350 protected function render_navigation_node(navigation_node $item) {
3351 $content = $item->get_content();
3352 $title = $item->get_title();
3353 if ($item->icon instanceof renderable && !$item->hideicon) {
3354 $icon = $this->render($item->icon);
3355 $content = $icon.$content; // use CSS for spacing of icons
3357 if ($item->helpbutton !== null) {
3358 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3360 if ($content === '') {
3361 return '';
3363 if ($item->action instanceof action_link) {
3364 $link = $item->action;
3365 if ($item->hidden) {
3366 $link->add_class('dimmed');
3368 if (!empty($content)) {
3369 // Providing there is content we will use that for the link content.
3370 $link->text = $content;
3372 $content = $this->render($link);
3373 } else if ($item->action instanceof moodle_url) {
3374 $attributes = array();
3375 if ($title !== '') {
3376 $attributes['title'] = $title;
3378 if ($item->hidden) {
3379 $attributes['class'] = 'dimmed_text';
3381 $content = html_writer::link($item->action, $content, $attributes);
3383 } else if (is_string($item->action) || empty($item->action)) {
3384 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3385 if ($title !== '') {
3386 $attributes['title'] = $title;
3388 if ($item->hidden) {
3389 $attributes['class'] = 'dimmed_text';
3391 $content = html_writer::tag('span', $content, $attributes);
3393 return $content;
3397 * Accessibility: Right arrow-like character is
3398 * used in the breadcrumb trail, course navigation menu
3399 * (previous/next activity), calendar, and search forum block.
3400 * If the theme does not set characters, appropriate defaults
3401 * are set automatically. Please DO NOT
3402 * use &lt; &gt; &raquo; - these are confusing for blind users.
3404 * @return string
3406 public function rarrow() {
3407 return $this->page->theme->rarrow;
3411 * Accessibility: Left arrow-like character is
3412 * used in the breadcrumb trail, course navigation menu
3413 * (previous/next activity), calendar, and search forum block.
3414 * If the theme does not set characters, appropriate defaults
3415 * are set automatically. Please DO NOT
3416 * use &lt; &gt; &raquo; - these are confusing for blind users.
3418 * @return string
3420 public function larrow() {
3421 return $this->page->theme->larrow;
3425 * Accessibility: Up arrow-like character is used in
3426 * the book heirarchical navigation.
3427 * If the theme does not set characters, appropriate defaults
3428 * are set automatically. Please DO NOT
3429 * use ^ - this is confusing for blind users.
3431 * @return string
3433 public function uarrow() {
3434 return $this->page->theme->uarrow;
3438 * Returns the custom menu if one has been set
3440 * A custom menu can be configured by browsing to
3441 * Settings: Administration > Appearance > Themes > Theme settings
3442 * and then configuring the custommenu config setting as described.
3444 * Theme developers: DO NOT OVERRIDE! Please override function
3445 * {@link core_renderer::render_custom_menu()} instead.
3447 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3448 * @return string
3450 public function custom_menu($custommenuitems = '') {
3451 global $CFG;
3452 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3453 $custommenuitems = $CFG->custommenuitems;
3455 if (empty($custommenuitems)) {
3456 return '';
3458 $custommenu = new custom_menu($custommenuitems, current_language());
3459 return $this->render($custommenu);
3463 * Renders a custom menu object (located in outputcomponents.php)
3465 * The custom menu this method produces makes use of the YUI3 menunav widget
3466 * and requires very specific html elements and classes.
3468 * @staticvar int $menucount
3469 * @param custom_menu $menu
3470 * @return string
3472 protected function render_custom_menu(custom_menu $menu) {
3473 static $menucount = 0;
3474 // If the menu has no children return an empty string
3475 if (!$menu->has_children()) {
3476 return '';
3478 // Increment the menu count. This is used for ID's that get worked with
3479 // in JavaScript as is essential
3480 $menucount++;
3481 // Initialise this custom menu (the custom menu object is contained in javascript-static
3482 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
3483 $jscode = "(function(){{$jscode}})";
3484 $this->page->requires->yui_module('node-menunav', $jscode);
3485 // Build the root nodes as required by YUI
3486 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
3487 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3488 $content .= html_writer::start_tag('ul');
3489 // Render each child
3490 foreach ($menu->get_children() as $item) {
3491 $content .= $this->render_custom_menu_item($item);
3493 // Close the open tags
3494 $content .= html_writer::end_tag('ul');
3495 $content .= html_writer::end_tag('div');
3496 $content .= html_writer::end_tag('div');
3497 // Return the custom menu
3498 return $content;
3502 * Renders a custom menu node as part of a submenu
3504 * The custom menu this method produces makes use of the YUI3 menunav widget
3505 * and requires very specific html elements and classes.
3507 * @see core:renderer::render_custom_menu()
3509 * @staticvar int $submenucount
3510 * @param custom_menu_item $menunode
3511 * @return string
3513 protected function render_custom_menu_item(custom_menu_item $menunode) {
3514 // Required to ensure we get unique trackable id's
3515 static $submenucount = 0;
3516 if ($menunode->has_children()) {
3517 // If the child has menus render it as a sub menu
3518 $submenucount++;
3519 $content = html_writer::start_tag('li');
3520 if ($menunode->get_url() !== null) {
3521 $url = $menunode->get_url();
3522 } else {
3523 $url = '#cm_submenu_'.$submenucount;
3525 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3526 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3527 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3528 $content .= html_writer::start_tag('ul');
3529 foreach ($menunode->get_children() as $menunode) {
3530 $content .= $this->render_custom_menu_item($menunode);
3532 $content .= html_writer::end_tag('ul');
3533 $content .= html_writer::end_tag('div');
3534 $content .= html_writer::end_tag('div');
3535 $content .= html_writer::end_tag('li');
3536 } else {
3537 // The node doesn't have children so produce a final menuitem.
3538 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3539 $content = '';
3540 if (preg_match("/^#+$/", $menunode->get_text())) {
3542 // This is a divider.
3543 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3544 } else {
3545 $content = html_writer::start_tag(
3546 'li',
3547 array(
3548 'class' => 'yui3-menuitem'
3551 if ($menunode->get_url() !== null) {
3552 $url = $menunode->get_url();
3553 } else {
3554 $url = '#';
3556 $content .= html_writer::link(
3557 $url,
3558 $menunode->get_text(),
3559 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3562 $content .= html_writer::end_tag('li');
3564 // Return the sub menu
3565 return $content;
3569 * Renders theme links for switching between default and other themes.
3571 * @return string
3573 protected function theme_switch_links() {
3575 $actualdevice = core_useragent::get_device_type();
3576 $currentdevice = $this->page->devicetypeinuse;
3577 $switched = ($actualdevice != $currentdevice);
3579 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3580 // The user is using the a default device and hasn't switched so don't shown the switch
3581 // device links.
3582 return '';
3585 if ($switched) {
3586 $linktext = get_string('switchdevicerecommended');
3587 $devicetype = $actualdevice;
3588 } else {
3589 $linktext = get_string('switchdevicedefault');
3590 $devicetype = 'default';
3592 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3594 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3595 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3596 $content .= html_writer::end_tag('div');
3598 return $content;
3602 * Renders tabs
3604 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3606 * Theme developers: In order to change how tabs are displayed please override functions
3607 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3609 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3610 * @param string|null $selected which tab to mark as selected, all parent tabs will
3611 * automatically be marked as activated
3612 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3613 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3614 * @return string
3616 public final function tabtree($tabs, $selected = null, $inactive = null) {
3617 return $this->render(new tabtree($tabs, $selected, $inactive));
3621 * Renders tabtree
3623 * @param tabtree $tabtree
3624 * @return string
3626 protected function render_tabtree(tabtree $tabtree) {
3627 if (empty($tabtree->subtree)) {
3628 return '';
3630 $str = '';
3631 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
3632 $str .= $this->render_tabobject($tabtree);
3633 $str .= html_writer::end_tag('div').
3634 html_writer::tag('div', ' ', array('class' => 'clearer'));
3635 return $str;
3639 * Renders tabobject (part of tabtree)
3641 * This function is called from {@link core_renderer::render_tabtree()}
3642 * and also it calls itself when printing the $tabobject subtree recursively.
3644 * Property $tabobject->level indicates the number of row of tabs.
3646 * @param tabobject $tabobject
3647 * @return string HTML fragment
3649 protected function render_tabobject(tabobject $tabobject) {
3650 $str = '';
3652 // Print name of the current tab.
3653 if ($tabobject instanceof tabtree) {
3654 // No name for tabtree root.
3655 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3656 // Tab name without a link. The <a> tag is used for styling.
3657 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3658 } else {
3659 // Tab name with a link.
3660 if (!($tabobject->link instanceof moodle_url)) {
3661 // backward compartibility when link was passed as quoted string
3662 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3663 } else {
3664 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3668 if (empty($tabobject->subtree)) {
3669 if ($tabobject->selected) {
3670 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3672 return $str;
3675 // Print subtree
3676 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3677 $cnt = 0;
3678 foreach ($tabobject->subtree as $tab) {
3679 $liclass = '';
3680 if (!$cnt) {
3681 $liclass .= ' first';
3683 if ($cnt == count($tabobject->subtree) - 1) {
3684 $liclass .= ' last';
3686 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3687 $liclass .= ' onerow';
3690 if ($tab->selected) {
3691 $liclass .= ' here selected';
3692 } else if ($tab->activated) {
3693 $liclass .= ' here active';
3696 // This will recursively call function render_tabobject() for each item in subtree
3697 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3698 $cnt++;
3700 $str .= html_writer::end_tag('ul');
3702 return $str;
3706 * Get the HTML for blocks in the given region.
3708 * @since Moodle 2.5.1 2.6
3709 * @param string $region The region to get HTML for.
3710 * @return string HTML.
3712 public function blocks($region, $classes = array(), $tag = 'aside') {
3713 $displayregion = $this->page->apply_theme_region_manipulations($region);
3714 $classes = (array)$classes;
3715 $classes[] = 'block-region';
3716 $attributes = array(
3717 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3718 'class' => join(' ', $classes),
3719 'data-blockregion' => $displayregion,
3720 'data-droptarget' => '1'
3722 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3723 $content = $this->blocks_for_region($displayregion);
3724 } else {
3725 $content = '';
3727 return html_writer::tag($tag, $content, $attributes);
3731 * Renders a custom block region.
3733 * Use this method if you want to add an additional block region to the content of the page.
3734 * Please note this should only be used in special situations.
3735 * We want to leave the theme is control where ever possible!
3737 * This method must use the same method that the theme uses within its layout file.
3738 * As such it asks the theme what method it is using.
3739 * It can be one of two values, blocks or blocks_for_region (deprecated).
3741 * @param string $regionname The name of the custom region to add.
3742 * @return string HTML for the block region.
3744 public function custom_block_region($regionname) {
3745 if ($this->page->theme->get_block_render_method() === 'blocks') {
3746 return $this->blocks($regionname);
3747 } else {
3748 return $this->blocks_for_region($regionname);
3753 * Returns the CSS classes to apply to the body tag.
3755 * @since Moodle 2.5.1 2.6
3756 * @param array $additionalclasses Any additional classes to apply.
3757 * @return string
3759 public function body_css_classes(array $additionalclasses = array()) {
3760 // Add a class for each block region on the page.
3761 // We use the block manager here because the theme object makes get_string calls.
3762 $usedregions = array();
3763 foreach ($this->page->blocks->get_regions() as $region) {
3764 $additionalclasses[] = 'has-region-'.$region;
3765 if ($this->page->blocks->region_has_content($region, $this)) {
3766 $additionalclasses[] = 'used-region-'.$region;
3767 $usedregions[] = $region;
3768 } else {
3769 $additionalclasses[] = 'empty-region-'.$region;
3771 if ($this->page->blocks->region_completely_docked($region, $this)) {
3772 $additionalclasses[] = 'docked-region-'.$region;
3775 if (!$usedregions) {
3776 // No regions means there is only content, add 'content-only' class.
3777 $additionalclasses[] = 'content-only';
3778 } else if (count($usedregions) === 1) {
3779 // Add the -only class for the only used region.
3780 $region = array_shift($usedregions);
3781 $additionalclasses[] = $region . '-only';
3783 foreach ($this->page->layout_options as $option => $value) {
3784 if ($value) {
3785 $additionalclasses[] = 'layout-option-'.$option;
3788 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
3789 return $css;
3793 * The ID attribute to apply to the body tag.
3795 * @since Moodle 2.5.1 2.6
3796 * @return string
3798 public function body_id() {
3799 return $this->page->bodyid;
3803 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
3805 * @since Moodle 2.5.1 2.6
3806 * @param string|array $additionalclasses Any additional classes to give the body tag,
3807 * @return string
3809 public function body_attributes($additionalclasses = array()) {
3810 if (!is_array($additionalclasses)) {
3811 $additionalclasses = explode(' ', $additionalclasses);
3813 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
3817 * Gets HTML for the page heading.
3819 * @since Moodle 2.5.1 2.6
3820 * @param string $tag The tag to encase the heading in. h1 by default.
3821 * @return string HTML.
3823 public function page_heading($tag = 'h1') {
3824 return html_writer::tag($tag, $this->page->heading);
3828 * Gets the HTML for the page heading button.
3830 * @since Moodle 2.5.1 2.6
3831 * @return string HTML.
3833 public function page_heading_button() {
3834 return $this->page->button;
3838 * Returns the Moodle docs link to use for this page.
3840 * @since Moodle 2.5.1 2.6
3841 * @param string $text
3842 * @return string
3844 public function page_doc_link($text = null) {
3845 if ($text === null) {
3846 $text = get_string('moodledocslink');
3848 $path = page_get_doc_link_path($this->page);
3849 if (!$path) {
3850 return '';
3852 return $this->doc_link($path, $text);
3856 * Returns the page heading menu.
3858 * @since Moodle 2.5.1 2.6
3859 * @return string HTML.
3861 public function page_heading_menu() {
3862 return $this->page->headingmenu;
3866 * Returns the title to use on the page.
3868 * @since Moodle 2.5.1 2.6
3869 * @return string
3871 public function page_title() {
3872 return $this->page->title;
3876 * Returns the URL for the favicon.
3878 * @since Moodle 2.5.1 2.6
3879 * @return string The favicon URL
3881 public function favicon() {
3882 return $this->pix_url('favicon', 'theme');
3886 * Renders preferences groups.
3888 * @param preferences_groups $renderable The renderable
3889 * @return string The output.
3891 public function render_preferences_groups(preferences_groups $renderable) {
3892 $html = '';
3893 $html .= html_writer::start_div('row-fluid');
3894 $html .= html_writer::start_tag('div', array('class' => 'span12 preferences-groups'));
3895 $i = 0;
3896 $open = false;
3897 foreach ($renderable->groups as $group) {
3898 if ($i == 0 || $i % 3 == 0) {
3899 if ($open) {
3900 $html .= html_writer::end_tag('div');
3902 $html .= html_writer::start_tag('div', array('class' => 'row-fluid'));
3903 $open = true;
3905 $html .= $this->render($group);
3906 $i++;
3909 $html .= html_writer::end_tag('div');
3911 $html .= html_writer::end_tag('ul');
3912 $html .= html_writer::end_tag('div');
3913 $html .= html_writer::end_div();
3914 return $html;
3918 * Renders preferences group.
3920 * @param preferences_group $renderable The renderable
3921 * @return string The output.
3923 public function render_preferences_group(preferences_group $renderable) {
3924 $html = '';
3925 $html .= html_writer::start_tag('div', array('class' => 'span4 preferences-group'));
3926 $html .= $this->heading($renderable->title, 3);
3927 $html .= html_writer::start_tag('ul');
3928 foreach ($renderable->nodes as $node) {
3929 if ($node->has_children()) {
3930 debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
3932 $html .= html_writer::tag('li', $this->render($node));
3934 $html .= html_writer::end_tag('ul');
3935 $html .= html_writer::end_tag('div');
3936 return $html;
3940 * Returns the header bar.
3942 * @since Moodle 2.9
3943 * @param array $headerinfo An array of header information, dependant on what type of header is being displayed. The following
3944 * array example is user specific.
3945 * heading => Override the page heading.
3946 * user => User object.
3947 * usercontext => user context.
3948 * @param int $headinglevel What level the 'h' tag will be.
3949 * @return string HTML for the header bar.
3951 public function context_header($headerinfo = null, $headinglevel = 1) {
3952 global $DB, $USER, $CFG;
3953 $context = $this->page->context;
3954 // Make sure to use the heading if it has been set.
3955 if (isset($headerinfo['heading'])) {
3956 $heading = $headerinfo['heading'];
3957 } else {
3958 $heading = null;
3960 $imagedata = null;
3961 $subheader = null;
3962 $userbuttons = null;
3963 // The user context currently has images and buttons. Other contexts may follow.
3964 if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
3965 if (isset($headerinfo['user'])) {
3966 $user = $headerinfo['user'];
3967 } else {
3968 // Look up the user information if it is not supplied.
3969 $user = $DB->get_record('user', array('id' => $context->instanceid));
3971 // If the user context is set, then use that for capability checks.
3972 if (isset($headerinfo['usercontext'])) {
3973 $context = $headerinfo['usercontext'];
3975 // Use the user's full name if the heading isn't set.
3976 if (!isset($heading)) {
3977 $heading = fullname($user);
3980 $imagedata = $this->user_picture($user, array('size' => 100));
3981 // Check to see if we should be displaying a message button.
3982 if (!empty($CFG->messaging) && $USER->id != $user->id && has_capability('moodle/site:sendmessage', $context)) {
3983 $userbuttons = array(
3984 'messages' => array(
3985 'buttontype' => 'message',
3986 'title' => get_string('message', 'message'),
3987 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
3988 'image' => 'message',
3989 'linkattributes' => message_messenger_sendmessage_link_params($user),
3990 'page' => $this->page
3993 $this->page->requires->string_for_js('changesmadereallygoaway', 'moodle');
3997 $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
3998 return $this->render_context_header($contextheader);
4002 * Renders the header bar.
4004 * @param context_header $contextheader Header bar object.
4005 * @return string HTML for the header bar.
4007 protected function render_context_header(context_header $contextheader) {
4009 // All the html stuff goes here.
4010 $html = html_writer::start_div('page-context-header');
4012 // Image data.
4013 if (isset($contextheader->imagedata)) {
4014 // Header specific image.
4015 $html .= html_writer::div($contextheader->imagedata, 'page-header-image');
4018 // Headings.
4019 if (!isset($contextheader->heading)) {
4020 $headings = $this->heading($this->page->heading, $contextheader->headinglevel);
4021 } else {
4022 $headings = $this->heading($contextheader->heading, $contextheader->headinglevel);
4025 $html .= html_writer::tag('div', $headings, array('class' => 'page-header-headings'));
4027 // Buttons.
4028 if (isset($contextheader->additionalbuttons)) {
4029 $html .= html_writer::start_div('btn-group header-button-group');
4030 foreach ($contextheader->additionalbuttons as $button) {
4031 if (!isset($button->page)) {
4032 // Include js for messaging.
4033 if ($button['buttontype'] === 'message') {
4034 message_messenger_requirejs();
4036 $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4037 'class' => 'iconsmall',
4038 'role' => 'presentation'
4040 $image .= html_writer::span($button['title'], 'header-button-title');
4041 } else {
4042 $image = html_writer::empty_tag('img', array(
4043 'src' => $button['formattedimage'],
4044 'role' => 'presentation'
4047 $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4049 $html .= html_writer::end_div();
4051 $html .= html_writer::end_div();
4053 return $html;
4057 * Wrapper for header elements.
4059 * @return string HTML to display the main header.
4061 public function full_header() {
4062 $html = html_writer::start_tag('header', array('id' => 'page-header', 'class' => 'clearfix'));
4063 $html .= $this->context_header();
4064 $html .= html_writer::start_div('clearfix', array('id' => 'page-navbar'));
4065 $html .= html_writer::tag('nav', $this->navbar(), array('class' => 'breadcrumb-nav'));
4066 $html .= html_writer::div($this->page_heading_button(), 'breadcrumb-button');
4067 $html .= html_writer::end_div();
4068 $html .= html_writer::tag('div', $this->course_header(), array('id' => 'course-header'));
4069 $html .= html_writer::end_tag('header');
4070 return $html;
4075 * A renderer that generates output for command-line scripts.
4077 * The implementation of this renderer is probably incomplete.
4079 * @copyright 2009 Tim Hunt
4080 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4081 * @since Moodle 2.0
4082 * @package core
4083 * @category output
4085 class core_renderer_cli extends core_renderer {
4088 * Returns the page header.
4090 * @return string HTML fragment
4092 public function header() {
4093 return $this->page->heading . "\n";
4097 * Returns a template fragment representing a Heading.
4099 * @param string $text The text of the heading
4100 * @param int $level The level of importance of the heading
4101 * @param string $classes A space-separated list of CSS classes
4102 * @param string $id An optional ID
4103 * @return string A template fragment for a heading
4105 public function heading($text, $level = 2, $classes = 'main', $id = null) {
4106 $text .= "\n";
4107 switch ($level) {
4108 case 1:
4109 return '=>' . $text;
4110 case 2:
4111 return '-->' . $text;
4112 default:
4113 return $text;
4118 * Returns a template fragment representing a fatal error.
4120 * @param string $message The message to output
4121 * @param string $moreinfourl URL where more info can be found about the error
4122 * @param string $link Link for the Continue button
4123 * @param array $backtrace The execution backtrace
4124 * @param string $debuginfo Debugging information
4125 * @return string A template fragment for a fatal error
4127 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
4128 global $CFG;
4130 $output = "!!! $message !!!\n";
4132 if ($CFG->debugdeveloper) {
4133 if (!empty($debuginfo)) {
4134 $output .= $this->notification($debuginfo, 'notifytiny');
4136 if (!empty($backtrace)) {
4137 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
4141 return $output;
4145 * Returns a template fragment representing a notification.
4147 * @param string $message The message to include
4148 * @param string $classes A space-separated list of CSS classes
4149 * @return string A template fragment for a notification
4151 public function notification($message, $classes = 'notifyproblem') {
4152 $message = clean_text($message);
4153 if ($classes === 'notifysuccess') {
4154 return "++ $message ++\n";
4156 return "!! $message !!\n";
4160 * There is no footer for a cli request, however we must override the
4161 * footer method to prevent the default footer.
4163 public function footer() {}
4168 * A renderer that generates output for ajax scripts.
4170 * This renderer prevents accidental sends back only json
4171 * encoded error messages, all other output is ignored.
4173 * @copyright 2010 Petr Skoda
4174 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4175 * @since Moodle 2.0
4176 * @package core
4177 * @category output
4179 class core_renderer_ajax extends core_renderer {
4182 * Returns a template fragment representing a fatal error.
4184 * @param string $message The message to output
4185 * @param string $moreinfourl URL where more info can be found about the error
4186 * @param string $link Link for the Continue button
4187 * @param array $backtrace The execution backtrace
4188 * @param string $debuginfo Debugging information
4189 * @return string A template fragment for a fatal error
4191 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
4192 global $CFG;
4194 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
4196 $e = new stdClass();
4197 $e->error = $message;
4198 $e->stacktrace = NULL;
4199 $e->debuginfo = NULL;
4200 $e->reproductionlink = NULL;
4201 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
4202 $link = (string) $link;
4203 if ($link) {
4204 $e->reproductionlink = $link;
4206 if (!empty($debuginfo)) {
4207 $e->debuginfo = $debuginfo;
4209 if (!empty($backtrace)) {
4210 $e->stacktrace = format_backtrace($backtrace, true);
4213 $this->header();
4214 return json_encode($e);
4218 * Used to display a notification.
4219 * For the AJAX notifications are discarded.
4221 * @param string $message
4222 * @param string $classes
4224 public function notification($message, $classes = 'notifyproblem') {}
4227 * Used to display a redirection message.
4228 * AJAX redirections should not occur and as such redirection messages
4229 * are discarded.
4231 * @param moodle_url|string $encodedurl
4232 * @param string $message
4233 * @param int $delay
4234 * @param bool $debugdisableredirect
4236 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
4239 * Prepares the start of an AJAX output.
4241 public function header() {
4242 // unfortunately YUI iframe upload does not support application/json
4243 if (!empty($_FILES)) {
4244 @header('Content-type: text/plain; charset=utf-8');
4245 if (!core_useragent::supports_json_contenttype()) {
4246 @header('X-Content-Type-Options: nosniff');
4248 } else if (!core_useragent::supports_json_contenttype()) {
4249 @header('Content-type: text/plain; charset=utf-8');
4250 @header('X-Content-Type-Options: nosniff');
4251 } else {
4252 @header('Content-type: application/json; charset=utf-8');
4255 // Headers to make it not cacheable and json
4256 @header('Cache-Control: no-store, no-cache, must-revalidate');
4257 @header('Cache-Control: post-check=0, pre-check=0', false);
4258 @header('Pragma: no-cache');
4259 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
4260 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
4261 @header('Accept-Ranges: none');
4265 * There is no footer for an AJAX request, however we must override the
4266 * footer method to prevent the default footer.
4268 public function footer() {}
4271 * No need for headers in an AJAX request... this should never happen.
4272 * @param string $text
4273 * @param int $level
4274 * @param string $classes
4275 * @param string $id
4277 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
4282 * Renderer for media files.
4284 * Used in file resources, media filter, and any other places that need to
4285 * output embedded media.
4287 * @copyright 2011 The Open University
4288 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4290 class core_media_renderer extends plugin_renderer_base {
4291 /** @var array Array of available 'player' objects */
4292 private $players;
4293 /** @var string Regex pattern for links which may contain embeddable content */
4294 private $embeddablemarkers;
4297 * Constructor requires medialib.php.
4299 * This is needed in the constructor (not later) so that you can use the
4300 * constants and static functions that are defined in core_media class
4301 * before you call renderer functions.
4303 public function __construct() {
4304 global $CFG;
4305 require_once($CFG->libdir . '/medialib.php');
4309 * Obtains the list of core_media_player objects currently in use to render
4310 * items.
4312 * The list is in rank order (highest first) and does not include players
4313 * which are disabled.
4315 * @return array Array of core_media_player objects in rank order
4317 protected function get_players() {
4318 global $CFG;
4320 // Save time by only building the list once.
4321 if (!$this->players) {
4322 // Get raw list of players.
4323 $players = $this->get_players_raw();
4325 // Chuck all the ones that are disabled.
4326 foreach ($players as $key => $player) {
4327 if (!$player->is_enabled()) {
4328 unset($players[$key]);
4332 // Sort in rank order (highest first).
4333 usort($players, array('core_media_player', 'compare_by_rank'));
4334 $this->players = $players;
4336 return $this->players;
4340 * Obtains a raw list of player objects that includes objects regardless
4341 * of whether they are disabled or not, and without sorting.
4343 * You can override this in a subclass if you need to add additional
4344 * players.
4346 * The return array is be indexed by player name to make it easier to
4347 * remove players in a subclass.
4349 * @return array $players Array of core_media_player objects in any order
4351 protected function get_players_raw() {
4352 return array(
4353 'vimeo' => new core_media_player_vimeo(),
4354 'youtube' => new core_media_player_youtube(),
4355 'youtube_playlist' => new core_media_player_youtube_playlist(),
4356 'html5video' => new core_media_player_html5video(),
4357 'html5audio' => new core_media_player_html5audio(),
4358 'mp3' => new core_media_player_mp3(),
4359 'flv' => new core_media_player_flv(),
4360 'wmp' => new core_media_player_wmp(),
4361 'qt' => new core_media_player_qt(),
4362 'rm' => new core_media_player_rm(),
4363 'swf' => new core_media_player_swf(),
4364 'link' => new core_media_player_link(),
4369 * Renders a media file (audio or video) using suitable embedded player.
4371 * See embed_alternatives function for full description of parameters.
4372 * This function calls through to that one.
4374 * When using this function you can also specify width and height in the
4375 * URL by including ?d=100x100 at the end. If specified in the URL, this
4376 * will override the $width and $height parameters.
4378 * @param moodle_url $url Full URL of media file
4379 * @param string $name Optional user-readable name to display in download link
4380 * @param int $width Width in pixels (optional)
4381 * @param int $height Height in pixels (optional)
4382 * @param array $options Array of key/value pairs
4383 * @return string HTML content of embed
4385 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
4386 $options = array()) {
4388 // Get width and height from URL if specified (overrides parameters in
4389 // function call).
4390 $rawurl = $url->out(false);
4391 if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
4392 $width = $matches[1];
4393 $height = $matches[2];
4394 $url = new moodle_url(str_replace($matches[0], '', $rawurl));
4397 // Defer to array version of function.
4398 return $this->embed_alternatives(array($url), $name, $width, $height, $options);
4402 * Renders media files (audio or video) using suitable embedded player.
4403 * The list of URLs should be alternative versions of the same content in
4404 * multiple formats. If there is only one format it should have a single
4405 * entry.
4407 * If the media files are not in a supported format, this will give students
4408 * a download link to each format. The download link uses the filename
4409 * unless you supply the optional name parameter.
4411 * Width and height are optional. If specified, these are suggested sizes
4412 * and should be the exact values supplied by the user, if they come from
4413 * user input. These will be treated as relating to the size of the video
4414 * content, not including any player control bar.
4416 * For audio files, height will be ignored. For video files, a few formats
4417 * work if you specify only width, but in general if you specify width
4418 * you must specify height as well.
4420 * The $options array is passed through to the core_media_player classes
4421 * that render the object tag. The keys can contain values from
4422 * core_media::OPTION_xx.
4424 * @param array $alternatives Array of moodle_url to media files
4425 * @param string $name Optional user-readable name to display in download link
4426 * @param int $width Width in pixels (optional)
4427 * @param int $height Height in pixels (optional)
4428 * @param array $options Array of key/value pairs
4429 * @return string HTML content of embed
4431 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
4432 $options = array()) {
4434 // Get list of player plugins (will also require the library).
4435 $players = $this->get_players();
4437 // Set up initial text which will be replaced by first player that
4438 // supports any of the formats.
4439 $out = core_media_player::PLACEHOLDER;
4441 // Loop through all players that support any of these URLs.
4442 foreach ($players as $player) {
4443 // Option: When no other player matched, don't do the default link player.
4444 if (!empty($options[core_media::OPTION_FALLBACK_TO_BLANK]) &&
4445 $player->get_rank() === 0 && $out === core_media_player::PLACEHOLDER) {
4446 continue;
4449 $supported = $player->list_supported_urls($alternatives, $options);
4450 if ($supported) {
4451 // Embed.
4452 $text = $player->embed($supported, $name, $width, $height, $options);
4454 // Put this in place of the 'fallback' slot in the previous text.
4455 $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
4459 // Remove 'fallback' slot from final version and return it.
4460 $out = str_replace(core_media_player::PLACEHOLDER, '', $out);
4461 if (!empty($options[core_media::OPTION_BLOCK]) && $out !== '') {
4462 $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
4464 return $out;
4468 * Checks whether a file can be embedded. If this returns true you will get
4469 * an embedded player; if this returns false, you will just get a download
4470 * link.
4472 * This is a wrapper for can_embed_urls.
4474 * @param moodle_url $url URL of media file
4475 * @param array $options Options (same as when embedding)
4476 * @return bool True if file can be embedded
4478 public function can_embed_url(moodle_url $url, $options = array()) {
4479 return $this->can_embed_urls(array($url), $options);
4483 * Checks whether a file can be embedded. If this returns true you will get
4484 * an embedded player; if this returns false, you will just get a download
4485 * link.
4487 * @param array $urls URL of media file and any alternatives (moodle_url)
4488 * @param array $options Options (same as when embedding)
4489 * @return bool True if file can be embedded
4491 public function can_embed_urls(array $urls, $options = array()) {
4492 // Check all players to see if any of them support it.
4493 foreach ($this->get_players() as $player) {
4494 // Link player (always last on list) doesn't count!
4495 if ($player->get_rank() <= 0) {
4496 break;
4498 // First player that supports it, return true.
4499 if ($player->list_supported_urls($urls, $options)) {
4500 return true;
4503 return false;
4507 * Obtains a list of markers that can be used in a regular expression when
4508 * searching for URLs that can be embedded by any player type.
4510 * This string is used to improve peformance of regex matching by ensuring
4511 * that the (presumably C) regex code can do a quick keyword check on the
4512 * URL part of a link to see if it matches one of these, rather than having
4513 * to go into PHP code for every single link to see if it can be embedded.
4515 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
4517 public function get_embeddable_markers() {
4518 if (empty($this->embeddablemarkers)) {
4519 $markers = '';
4520 foreach ($this->get_players() as $player) {
4521 foreach ($player->get_embeddable_markers() as $marker) {
4522 if ($markers !== '') {
4523 $markers .= '|';
4525 $markers .= preg_quote($marker);
4528 $this->embeddablemarkers = $markers;
4530 return $this->embeddablemarkers;
4535 * The maintenance renderer.
4537 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
4538 * is running a maintenance related task.
4539 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
4541 * @since Moodle 2.6
4542 * @package core
4543 * @category output
4544 * @copyright 2013 Sam Hemelryk
4545 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4547 class core_renderer_maintenance extends core_renderer {
4550 * Initialises the renderer instance.
4551 * @param moodle_page $page
4552 * @param string $target
4553 * @throws coding_exception
4555 public function __construct(moodle_page $page, $target) {
4556 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
4557 throw new coding_exception('Invalid request for the maintenance renderer.');
4559 parent::__construct($page, $target);
4563 * Does nothing. The maintenance renderer cannot produce blocks.
4565 * @param block_contents $bc
4566 * @param string $region
4567 * @return string
4569 public function block(block_contents $bc, $region) {
4570 // Computer says no blocks.
4571 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4572 return '';
4576 * Does nothing. The maintenance renderer cannot produce blocks.
4578 * @param string $region
4579 * @param array $classes
4580 * @param string $tag
4581 * @return string
4583 public function blocks($region, $classes = array(), $tag = 'aside') {
4584 // Computer says no blocks.
4585 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4586 return '';
4590 * Does nothing. The maintenance renderer cannot produce blocks.
4592 * @param string $region
4593 * @return string
4595 public function blocks_for_region($region) {
4596 // Computer says no blocks for region.
4597 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4598 return '';
4602 * Does nothing. The maintenance renderer cannot produce a course content header.
4604 * @param bool $onlyifnotcalledbefore
4605 * @return string
4607 public function course_content_header($onlyifnotcalledbefore = false) {
4608 // Computer says no course content header.
4609 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4610 return '';
4614 * Does nothing. The maintenance renderer cannot produce a course content footer.
4616 * @param bool $onlyifnotcalledbefore
4617 * @return string
4619 public function course_content_footer($onlyifnotcalledbefore = false) {
4620 // Computer says no course content footer.
4621 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4622 return '';
4626 * Does nothing. The maintenance renderer cannot produce a course header.
4628 * @return string
4630 public function course_header() {
4631 // Computer says no course header.
4632 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4633 return '';
4637 * Does nothing. The maintenance renderer cannot produce a course footer.
4639 * @return string
4641 public function course_footer() {
4642 // Computer says no course footer.
4643 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4644 return '';
4648 * Does nothing. The maintenance renderer cannot produce a custom menu.
4650 * @param string $custommenuitems
4651 * @return string
4653 public function custom_menu($custommenuitems = '') {
4654 // Computer says no custom menu.
4655 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4656 return '';
4660 * Does nothing. The maintenance renderer cannot produce a file picker.
4662 * @param array $options
4663 * @return string
4665 public function file_picker($options) {
4666 // Computer says no file picker.
4667 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4668 return '';
4672 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
4674 * @param array $dir
4675 * @return string
4677 public function htmllize_file_tree($dir) {
4678 // Hell no we don't want no htmllized file tree.
4679 // Also why on earth is this function on the core renderer???
4680 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4681 return '';
4686 * Does nothing. The maintenance renderer does not support JS.
4688 * @param block_contents $bc
4690 public function init_block_hider_js(block_contents $bc) {
4691 // Computer says no JavaScript.
4692 // Do nothing, ridiculous method.
4696 * Does nothing. The maintenance renderer cannot produce language menus.
4698 * @return string
4700 public function lang_menu() {
4701 // Computer says no lang menu.
4702 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4703 return '';
4707 * Does nothing. The maintenance renderer has no need for login information.
4709 * @param null $withlinks
4710 * @return string
4712 public function login_info($withlinks = null) {
4713 // Computer says no login info.
4714 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4715 return '';
4719 * Does nothing. The maintenance renderer cannot produce user pictures.
4721 * @param stdClass $user
4722 * @param array $options
4723 * @return string
4725 public function user_picture(stdClass $user, array $options = null) {
4726 // Computer says no user pictures.
4727 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4728 return '';