Merge branch 'MDL-41041-master' of git://github.com/FMCorz/moodle
[moodle.git] / lib / outputrenderers.php
blob39a7cec3c818301633331c236af524ed554f773c
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 * Constructor
72 * The constructor takes two arguments. The first is the page that the renderer
73 * has been created to assist with, and the second is the target.
74 * The target is an additional identifier that can be used to load different
75 * renderers for different options.
77 * @param moodle_page $page the page we are doing output for.
78 * @param string $target one of rendering target constants
80 public function __construct(moodle_page $page, $target) {
81 $this->opencontainers = $page->opencontainers;
82 $this->page = $page;
83 $this->target = $target;
86 /**
87 * Returns rendered widget.
89 * The provided widget needs to be an object that extends the renderable
90 * interface.
91 * If will then be rendered by a method based upon the classname for the widget.
92 * For instance a widget of class `crazywidget` will be rendered by a protected
93 * render_crazywidget method of this renderer.
95 * @param renderable $widget instance with renderable interface
96 * @return string
98 public function render(renderable $widget) {
99 $rendermethod = 'render_'.get_class($widget);
100 if (method_exists($this, $rendermethod)) {
101 return $this->$rendermethod($widget);
103 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
107 * Adds a JS action for the element with the provided id.
109 * This method adds a JS event for the provided component action to the page
110 * and then returns the id that the event has been attached to.
111 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
113 * @param component_action $action
114 * @param string $id
115 * @return string id of element, either original submitted or random new if not supplied
117 public function add_action_handler(component_action $action, $id = null) {
118 if (!$id) {
119 $id = html_writer::random_id($action->event);
121 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
122 return $id;
126 * Returns true is output has already started, and false if not.
128 * @return boolean true if the header has been printed.
130 public function has_started() {
131 return $this->page->state >= moodle_page::STATE_IN_BODY;
135 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
137 * @param mixed $classes Space-separated string or array of classes
138 * @return string HTML class attribute value
140 public static function prepare_classes($classes) {
141 if (is_array($classes)) {
142 return implode(' ', array_unique($classes));
144 return $classes;
148 * Return the moodle_url for an image.
150 * The exact image location and extension is determined
151 * automatically by searching for gif|png|jpg|jpeg, please
152 * note there can not be diferent images with the different
153 * extension. The imagename is for historical reasons
154 * a relative path name, it may be changed later for core
155 * images. It is recommended to not use subdirectories
156 * in plugin and theme pix directories.
158 * There are three types of images:
159 * 1/ theme images - stored in theme/mytheme/pix/,
160 * use component 'theme'
161 * 2/ core images - stored in /pix/,
162 * overridden via theme/mytheme/pix_core/
163 * 3/ plugin images - stored in mod/mymodule/pix,
164 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
165 * example: pix_url('comment', 'mod_glossary')
167 * @param string $imagename the pathname of the image
168 * @param string $component full plugin name (aka component) or 'theme'
169 * @return moodle_url
171 public function pix_url($imagename, $component = 'moodle') {
172 return $this->page->theme->pix_url($imagename, $component);
178 * Basis for all plugin renderers.
180 * @copyright Petr Skoda (skodak)
181 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
182 * @since Moodle 2.0
183 * @package core
184 * @category output
186 class plugin_renderer_base extends renderer_base {
189 * @var renderer_base|core_renderer A reference to the current renderer.
190 * The renderer provided here will be determined by the page but will in 90%
191 * of cases by the {@link core_renderer}
193 protected $output;
196 * Constructor method, calls the parent constructor
198 * @param moodle_page $page
199 * @param string $target one of rendering target constants
201 public function __construct(moodle_page $page, $target) {
202 if (empty($target) && $page->pagelayout === 'maintenance') {
203 // If the page is using the maintenance layout then we're going to force the target to maintenance.
204 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
205 // unavailable for this page layout.
206 $target = RENDERER_TARGET_MAINTENANCE;
208 $this->output = $page->get_renderer('core', null, $target);
209 parent::__construct($page, $target);
213 * Renders the provided widget and returns the HTML to display it.
215 * @param renderable $widget instance with renderable interface
216 * @return string
218 public function render(renderable $widget) {
219 $rendermethod = 'render_'.get_class($widget);
220 if (method_exists($this, $rendermethod)) {
221 return $this->$rendermethod($widget);
223 // pass to core renderer if method not found here
224 return $this->output->render($widget);
228 * Magic method used to pass calls otherwise meant for the standard renderer
229 * to it to ensure we don't go causing unnecessary grief.
231 * @param string $method
232 * @param array $arguments
233 * @return mixed
235 public function __call($method, $arguments) {
236 if (method_exists('renderer_base', $method)) {
237 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
239 if (method_exists($this->output, $method)) {
240 return call_user_func_array(array($this->output, $method), $arguments);
241 } else {
242 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
249 * The standard implementation of the core_renderer interface.
251 * @copyright 2009 Tim Hunt
252 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
253 * @since Moodle 2.0
254 * @package core
255 * @category output
257 class core_renderer extends renderer_base {
259 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
260 * in layout files instead.
261 * @deprecated
262 * @var string used in {@link core_renderer::header()}.
264 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
267 * @var string Used to pass information from {@link core_renderer::doctype()} to
268 * {@link core_renderer::standard_head_html()}.
270 protected $contenttype;
273 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
274 * with {@link core_renderer::header()}.
276 protected $metarefreshtag = '';
279 * @var string Unique token for the closing HTML
281 protected $unique_end_html_token;
284 * @var string Unique token for performance information
286 protected $unique_performance_info_token;
289 * @var string Unique token for the main content.
291 protected $unique_main_content_token;
294 * Constructor
296 * @param moodle_page $page the page we are doing output for.
297 * @param string $target one of rendering target constants
299 public function __construct(moodle_page $page, $target) {
300 $this->opencontainers = $page->opencontainers;
301 $this->page = $page;
302 $this->target = $target;
304 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
305 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
306 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
310 * Get the DOCTYPE declaration that should be used with this page. Designed to
311 * be called in theme layout.php files.
313 * @return string the DOCTYPE declaration that should be used.
315 public function doctype() {
316 if ($this->page->theme->doctype === 'html5') {
317 $this->contenttype = 'text/html; charset=utf-8';
318 return "<!DOCTYPE html>\n";
320 } else if ($this->page->theme->doctype === 'xhtml5') {
321 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
322 return "<!DOCTYPE html>\n";
324 } else {
325 // legacy xhtml 1.0
326 $this->contenttype = 'text/html; charset=utf-8';
327 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
332 * The attributes that should be added to the <html> tag. Designed to
333 * be called in theme layout.php files.
335 * @return string HTML fragment.
337 public function htmlattributes() {
338 $return = get_html_lang(true);
339 if ($this->page->theme->doctype !== 'html5') {
340 $return .= ' xmlns="http://www.w3.org/1999/xhtml"';
342 return $return;
346 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
347 * that should be included in the <head> tag. Designed to be called in theme
348 * layout.php files.
350 * @return string HTML fragment.
352 public function standard_head_html() {
353 global $CFG, $SESSION;
355 // Before we output any content, we need to ensure that certain
356 // page components are set up.
358 // Blocks must be set up early as they may require javascript which
359 // has to be included in the page header before output is created.
360 foreach ($this->page->blocks->get_regions() as $region) {
361 $this->page->blocks->ensure_content_created($region, $this);
364 $output = '';
365 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
366 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
367 if (!$this->page->cacheable) {
368 $output .= '<meta http-equiv="pragma" content="no-cache" />' . "\n";
369 $output .= '<meta http-equiv="expires" content="0" />' . "\n";
371 // This is only set by the {@link redirect()} method
372 $output .= $this->metarefreshtag;
374 // Check if a periodic refresh delay has been set and make sure we arn't
375 // already meta refreshing
376 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
377 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
380 // flow player embedding support
381 $this->page->requires->js_function_call('M.util.load_flowplayer');
383 // Set up help link popups for all links with the helptooltip class
384 $this->page->requires->js_init_call('M.util.help_popups.setup');
386 // Setup help icon overlays.
387 $this->page->requires->yui_module('moodle-core-popuphelp', 'M.core.init_popuphelp');
388 $this->page->requires->strings_for_js(array(
389 'morehelp',
390 'loadinghelp',
391 ), 'moodle');
393 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
395 $focus = $this->page->focuscontrol;
396 if (!empty($focus)) {
397 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
398 // This is a horrifically bad way to handle focus but it is passed in
399 // through messy formslib::moodleform
400 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
401 } else if (strpos($focus, '.')!==false) {
402 // Old style of focus, bad way to do it
403 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);
404 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
405 } else {
406 // Focus element with given id
407 $this->page->requires->js_function_call('focuscontrol', array($focus));
411 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
412 // any other custom CSS can not be overridden via themes and is highly discouraged
413 $urls = $this->page->theme->css_urls($this->page);
414 foreach ($urls as $url) {
415 $this->page->requires->css_theme($url);
418 // Get the theme javascript head and footer
419 if ($jsurl = $this->page->theme->javascript_url(true)) {
420 $this->page->requires->js($jsurl, true);
422 if ($jsurl = $this->page->theme->javascript_url(false)) {
423 $this->page->requires->js($jsurl);
426 // Get any HTML from the page_requirements_manager.
427 $output .= $this->page->requires->get_head_code($this->page, $this);
429 // List alternate versions.
430 foreach ($this->page->alternateversions as $type => $alt) {
431 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
432 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
435 if (!empty($CFG->additionalhtmlhead)) {
436 $output .= "\n".$CFG->additionalhtmlhead;
439 return $output;
443 * The standard tags (typically skip links) that should be output just inside
444 * the start of the <body> tag. Designed to be called in theme layout.php files.
446 * @return string HTML fragment.
448 public function standard_top_of_body_html() {
449 global $CFG;
450 $output = $this->page->requires->get_top_of_body_code();
451 if (!empty($CFG->additionalhtmltopofbody)) {
452 $output .= "\n".$CFG->additionalhtmltopofbody;
454 $output .= $this->maintenance_warning();
455 return $output;
459 * Scheduled maintenance warning message.
461 * Note: This is a nasty hack to display maintenance notice, this should be moved
462 * to some general notification area once we have it.
464 * @return string
466 public function maintenance_warning() {
467 global $CFG;
469 $output = '';
470 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
471 $output .= $this->box_start('errorbox maintenancewarning');
472 $output .= get_string('maintenancemodeisscheduled', 'admin', (int)(($CFG->maintenance_later-time())/60));
473 $output .= $this->box_end();
475 return $output;
479 * The standard tags (typically performance information and validation links,
480 * if we are in developer debug mode) that should be output in the footer area
481 * of the page. Designed to be called in theme layout.php files.
483 * @return string HTML fragment.
485 public function standard_footer_html() {
486 global $CFG, $SCRIPT;
488 if (during_initial_install()) {
489 // Debugging info can not work before install is finished,
490 // in any case we do not want any links during installation!
491 return '';
494 // This function is normally called from a layout.php file in {@link core_renderer::header()}
495 // but some of the content won't be known until later, so we return a placeholder
496 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
497 $output = $this->unique_performance_info_token;
498 if ($this->page->devicetypeinuse == 'legacy') {
499 // The legacy theme is in use print the notification
500 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
503 // Get links to switch device types (only shown for users not on a default device)
504 $output .= $this->theme_switch_links();
506 if (!empty($CFG->debugpageinfo)) {
507 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
509 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
510 // Add link to profiling report if necessary
511 if (function_exists('profiling_is_running') && profiling_is_running()) {
512 $txt = get_string('profiledscript', 'admin');
513 $title = get_string('profiledscriptview', 'admin');
514 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
515 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
516 $output .= '<div class="profilingfooter">' . $link . '</div>';
518 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
519 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
520 $output .= '<div class="purgecaches">' .
521 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
523 if (!empty($CFG->debugvalidators)) {
524 // 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
525 $output .= '<div class="validators"><ul>
526 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
527 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
528 <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>
529 </ul></div>';
531 if (!empty($CFG->additionalhtmlfooter)) {
532 $output .= "\n".$CFG->additionalhtmlfooter;
534 return $output;
538 * Returns standard main content placeholder.
539 * Designed to be called in theme layout.php files.
541 * @return string HTML fragment.
543 public function main_content() {
544 // This is here because it is the only place we can inject the "main" role over the entire main content area
545 // without requiring all theme's to manually do it, and without creating yet another thing people need to
546 // remember in the theme.
547 // This is an unfortunate hack. DO NO EVER add anything more here.
548 // DO NOT add classes.
549 // DO NOT add an id.
550 return '<div role="main">'.$this->unique_main_content_token.'</div>';
554 * The standard tags (typically script tags that are not needed earlier) that
555 * should be output after everything else, . Designed to be called in theme layout.php files.
557 * @return string HTML fragment.
559 public function standard_end_of_body_html() {
560 // This function is normally called from a layout.php file in {@link core_renderer::header()}
561 // but some of the content won't be known until later, so we return a placeholder
562 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
563 return $this->unique_end_html_token;
567 * Return the standard string that says whether you are logged in (and switched
568 * roles/logged in as another user).
569 * @param bool $withlinks if false, then don't include any links in the HTML produced.
570 * If not set, the default is the nologinlinks option from the theme config.php file,
571 * and if that is not set, then links are included.
572 * @return string HTML fragment.
574 public function login_info($withlinks = null) {
575 global $USER, $CFG, $DB, $SESSION;
577 if (during_initial_install()) {
578 return '';
581 if (is_null($withlinks)) {
582 $withlinks = empty($this->page->layout_options['nologinlinks']);
585 $loginpage = ((string)$this->page->url === get_login_url());
586 $course = $this->page->course;
587 if (\core\session\manager::is_loggedinas()) {
588 $realuser = \core\session\manager::get_realuser();
589 $fullname = fullname($realuser, true);
590 if ($withlinks) {
591 $loginastitle = get_string('loginas');
592 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
593 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
594 } else {
595 $realuserinfo = " [$fullname] ";
597 } else {
598 $realuserinfo = '';
601 $loginurl = get_login_url();
603 if (empty($course->id)) {
604 // $course->id is not defined during installation
605 return '';
606 } else if (isloggedin()) {
607 $context = context_course::instance($course->id);
609 $fullname = fullname($USER, true);
610 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
611 if ($withlinks) {
612 $linktitle = get_string('viewprofile');
613 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
614 } else {
615 $username = $fullname;
617 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
618 if ($withlinks) {
619 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
620 } else {
621 $username .= " from {$idprovider->name}";
624 if (isguestuser()) {
625 $loggedinas = $realuserinfo.get_string('loggedinasguest');
626 if (!$loginpage && $withlinks) {
627 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
629 } else if (is_role_switched($course->id)) { // Has switched roles
630 $rolename = '';
631 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
632 $rolename = ': '.role_get_name($role, $context);
634 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
635 if ($withlinks) {
636 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
637 $loggedinas .= '('.html_writer::tag('a', get_string('switchrolereturn'), array('href'=>$url)).')';
639 } else {
640 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
641 if ($withlinks) {
642 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
645 } else {
646 $loggedinas = get_string('loggedinnot', 'moodle');
647 if (!$loginpage && $withlinks) {
648 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
652 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
654 if (isset($SESSION->justloggedin)) {
655 unset($SESSION->justloggedin);
656 if (!empty($CFG->displayloginfailures)) {
657 if (!isguestuser()) {
658 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
659 $loggedinas .= '&nbsp;<div class="loginfailures">';
660 if (empty($count->accounts)) {
661 $loggedinas .= get_string('failedloginattempts', '', $count);
662 } else {
663 $loggedinas .= get_string('failedloginattemptsall', '', $count);
665 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
666 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/report/log/index.php'.
667 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
669 $loggedinas .= '</div>';
675 return $loggedinas;
679 * Return the 'back' link that normally appears in the footer.
681 * @return string HTML fragment.
683 public function home_link() {
684 global $CFG, $SITE;
686 if ($this->page->pagetype == 'site-index') {
687 // Special case for site home page - please do not remove
688 return '<div class="sitelink">' .
689 '<a title="Moodle" href="http://moodle.org/">' .
690 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
692 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
693 // Special case for during install/upgrade.
694 return '<div class="sitelink">'.
695 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
696 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
698 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
699 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
700 get_string('home') . '</a></div>';
702 } else {
703 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
704 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
709 * Redirects the user by any means possible given the current state
711 * This function should not be called directly, it should always be called using
712 * the redirect function in lib/weblib.php
714 * The redirect function should really only be called before page output has started
715 * however it will allow itself to be called during the state STATE_IN_BODY
717 * @param string $encodedurl The URL to send to encoded if required
718 * @param string $message The message to display to the user if any
719 * @param int $delay The delay before redirecting a user, if $message has been
720 * set this is a requirement and defaults to 3, set to 0 no delay
721 * @param boolean $debugdisableredirect this redirect has been disabled for
722 * debugging purposes. Display a message that explains, and don't
723 * trigger the redirect.
724 * @return string The HTML to display to the user before dying, may contain
725 * meta refresh, javascript refresh, and may have set header redirects
727 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
728 global $CFG;
729 $url = str_replace('&amp;', '&', $encodedurl);
731 switch ($this->page->state) {
732 case moodle_page::STATE_BEFORE_HEADER :
733 // No output yet it is safe to delivery the full arsenal of redirect methods
734 if (!$debugdisableredirect) {
735 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
736 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
737 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
739 $output = $this->header();
740 break;
741 case moodle_page::STATE_PRINTING_HEADER :
742 // We should hopefully never get here
743 throw new coding_exception('You cannot redirect while printing the page header');
744 break;
745 case moodle_page::STATE_IN_BODY :
746 // We really shouldn't be here but we can deal with this
747 debugging("You should really redirect before you start page output");
748 if (!$debugdisableredirect) {
749 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
751 $output = $this->opencontainers->pop_all_but_last();
752 break;
753 case moodle_page::STATE_DONE :
754 // Too late to be calling redirect now
755 throw new coding_exception('You cannot redirect after the entire page has been generated');
756 break;
758 $output .= $this->notification($message, 'redirectmessage');
759 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
760 if ($debugdisableredirect) {
761 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
763 $output .= $this->footer();
764 return $output;
768 * Start output by sending the HTTP headers, and printing the HTML <head>
769 * and the start of the <body>.
771 * To control what is printed, you should set properties on $PAGE. If you
772 * are familiar with the old {@link print_header()} function from Moodle 1.9
773 * you will find that there are properties on $PAGE that correspond to most
774 * of the old parameters to could be passed to print_header.
776 * Not that, in due course, the remaining $navigation, $menu parameters here
777 * will be replaced by more properties of $PAGE, but that is still to do.
779 * @return string HTML that you must output this, preferably immediately.
781 public function header() {
782 global $USER, $CFG;
784 if (\core\session\manager::is_loggedinas()) {
785 $this->page->add_body_class('userloggedinas');
788 // Give themes a chance to init/alter the page object.
789 $this->page->theme->init_page($this->page);
791 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
793 // Find the appropriate page layout file, based on $this->page->pagelayout.
794 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
795 // Render the layout using the layout file.
796 $rendered = $this->render_page_layout($layoutfile);
798 // Slice the rendered output into header and footer.
799 $cutpos = strpos($rendered, $this->unique_main_content_token);
800 if ($cutpos === false) {
801 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
802 $token = self::MAIN_CONTENT_TOKEN;
803 } else {
804 $token = $this->unique_main_content_token;
807 if ($cutpos === false) {
808 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.');
810 $header = substr($rendered, 0, $cutpos);
811 $footer = substr($rendered, $cutpos + strlen($token));
813 if (empty($this->contenttype)) {
814 debugging('The page layout file did not call $OUTPUT->doctype()');
815 $header = $this->doctype() . $header;
818 // If this theme version is below 2.4 release and this is a course view page
819 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
820 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
821 // check if course content header/footer have not been output during render of theme layout
822 $coursecontentheader = $this->course_content_header(true);
823 $coursecontentfooter = $this->course_content_footer(true);
824 if (!empty($coursecontentheader)) {
825 // display debug message and add header and footer right above and below main content
826 // Please note that course header and footer (to be displayed above and below the whole page)
827 // are not displayed in this case at all.
828 // Besides the content header and footer are not displayed on any other course page
829 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);
830 $header .= $coursecontentheader;
831 $footer = $coursecontentfooter. $footer;
835 send_headers($this->contenttype, $this->page->cacheable);
837 $this->opencontainers->push('header/footer', $footer);
838 $this->page->set_state(moodle_page::STATE_IN_BODY);
840 return $header . $this->skip_link_target('maincontent');
844 * Renders and outputs the page layout file.
846 * This is done by preparing the normal globals available to a script, and
847 * then including the layout file provided by the current theme for the
848 * requested layout.
850 * @param string $layoutfile The name of the layout file
851 * @return string HTML code
853 protected function render_page_layout($layoutfile) {
854 global $CFG, $SITE, $USER;
855 // The next lines are a bit tricky. The point is, here we are in a method
856 // of a renderer class, and this object may, or may not, be the same as
857 // the global $OUTPUT object. When rendering the page layout file, we want to use
858 // this object. However, people writing Moodle code expect the current
859 // renderer to be called $OUTPUT, not $this, so define a variable called
860 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
861 $OUTPUT = $this;
862 $PAGE = $this->page;
863 $COURSE = $this->page->course;
865 ob_start();
866 include($layoutfile);
867 $rendered = ob_get_contents();
868 ob_end_clean();
869 return $rendered;
873 * Outputs the page's footer
875 * @return string HTML fragment
877 public function footer() {
878 global $CFG, $DB;
880 $output = $this->container_end_all(true);
882 $footer = $this->opencontainers->pop('header/footer');
884 if (debugging() and $DB and $DB->is_transaction_started()) {
885 // TODO: MDL-20625 print warning - transaction will be rolled back
888 // Provide some performance info if required
889 $performanceinfo = '';
890 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
891 $perf = get_performance_info();
892 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
893 $performanceinfo = $perf['html'];
896 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
898 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
900 $this->page->set_state(moodle_page::STATE_DONE);
902 return $output . $footer;
906 * Close all but the last open container. This is useful in places like error
907 * handling, where you want to close all the open containers (apart from <body>)
908 * before outputting the error message.
910 * @param bool $shouldbenone assert that the stack should be empty now - causes a
911 * developer debug warning if it isn't.
912 * @return string the HTML required to close any open containers inside <body>.
914 public function container_end_all($shouldbenone = false) {
915 return $this->opencontainers->pop_all_but_last($shouldbenone);
919 * Returns course-specific information to be output immediately above content on any course page
920 * (for the current course)
922 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
923 * @return string
925 public function course_content_header($onlyifnotcalledbefore = false) {
926 global $CFG;
927 if ($this->page->course->id == SITEID) {
928 // return immediately and do not include /course/lib.php if not necessary
929 return '';
931 static $functioncalled = false;
932 if ($functioncalled && $onlyifnotcalledbefore) {
933 // we have already output the content header
934 return '';
936 require_once($CFG->dirroot.'/course/lib.php');
937 $functioncalled = true;
938 $courseformat = course_get_format($this->page->course);
939 if (($obj = $courseformat->course_content_header()) !== null) {
940 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
942 return '';
946 * Returns course-specific information to be output immediately below content on any course page
947 * (for the current course)
949 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
950 * @return string
952 public function course_content_footer($onlyifnotcalledbefore = false) {
953 global $CFG;
954 if ($this->page->course->id == SITEID) {
955 // return immediately and do not include /course/lib.php if not necessary
956 return '';
958 static $functioncalled = false;
959 if ($functioncalled && $onlyifnotcalledbefore) {
960 // we have already output the content footer
961 return '';
963 $functioncalled = true;
964 require_once($CFG->dirroot.'/course/lib.php');
965 $courseformat = course_get_format($this->page->course);
966 if (($obj = $courseformat->course_content_footer()) !== null) {
967 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
969 return '';
973 * Returns course-specific information to be output on any course page in the header area
974 * (for the current course)
976 * @return string
978 public function course_header() {
979 global $CFG;
980 if ($this->page->course->id == SITEID) {
981 // return immediately and do not include /course/lib.php if not necessary
982 return '';
984 require_once($CFG->dirroot.'/course/lib.php');
985 $courseformat = course_get_format($this->page->course);
986 if (($obj = $courseformat->course_header()) !== null) {
987 return $courseformat->get_renderer($this->page)->render($obj);
989 return '';
993 * Returns course-specific information to be output on any course page in the footer area
994 * (for the current course)
996 * @return string
998 public function course_footer() {
999 global $CFG;
1000 if ($this->page->course->id == SITEID) {
1001 // return immediately and do not include /course/lib.php if not necessary
1002 return '';
1004 require_once($CFG->dirroot.'/course/lib.php');
1005 $courseformat = course_get_format($this->page->course);
1006 if (($obj = $courseformat->course_footer()) !== null) {
1007 return $courseformat->get_renderer($this->page)->render($obj);
1009 return '';
1013 * Returns lang menu or '', this method also checks forcing of languages in courses.
1015 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1017 * @return string The lang menu HTML or empty string
1019 public function lang_menu() {
1020 global $CFG;
1022 if (empty($CFG->langmenu)) {
1023 return '';
1026 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1027 // do not show lang menu if language forced
1028 return '';
1031 $currlang = current_language();
1032 $langs = get_string_manager()->get_list_of_translations();
1034 if (count($langs) < 2) {
1035 return '';
1038 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1039 $s->label = get_accesshide(get_string('language'));
1040 $s->class = 'langmenu';
1041 return $this->render($s);
1045 * Output the row of editing icons for a block, as defined by the controls array.
1047 * @param array $controls an array like {@link block_contents::$controls}.
1048 * @param string $blockid The ID given to the block.
1049 * @return string HTML fragment.
1051 public function block_controls($actions, $blockid = null) {
1052 global $CFG;
1053 if (empty($actions)) {
1054 return '';
1056 $menu = new action_menu($actions);
1057 if ($blockid !== null) {
1058 $menu->set_owner_selector('#'.$blockid);
1060 $menu->attributes['class'] .= ' block-control-actions commands';
1061 if (isset($CFG->blockeditingmenu) && !$CFG->blockeditingmenu) {
1062 $menu->do_not_enhance();
1064 return $this->render($menu);
1068 * Renders an action menu component.
1070 * ARIA references:
1071 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1072 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1074 * @param action_menu $menu
1075 * @return string HTML
1077 public function render_action_menu(action_menu $menu) {
1078 $menu->initialise_js($this->page);
1080 $output = html_writer::start_tag('div', $menu->attributes);
1081 $output .= html_writer::start_tag('ul', $menu->attributesprimary);
1082 foreach ($menu->get_primary_actions($this) as $action) {
1083 if ($action instanceof renderable) {
1084 $content = $this->render($action);
1085 $role = 'presentation';
1086 } else {
1087 $content = $action;
1088 $role = 'menuitem';
1090 $output .= html_writer::tag('li', $content, array('role' => $role));
1092 $output .= html_writer::end_tag('ul');
1093 $output .= html_writer::start_tag('ul', $menu->attributessecondary);
1094 foreach ($menu->get_secondary_actions() as $action) {
1095 if ($action instanceof renderable) {
1096 $content = $this->render($action);
1097 $role = 'presentation';
1098 } else {
1099 $content = $action;
1100 $role = 'menuitem';
1102 $output .= html_writer::tag('li', $content, array('role' => $role));
1104 $output .= html_writer::end_tag('ul');
1105 $output .= html_writer::end_tag('div');
1106 return $output;
1110 * Renders an action_menu_link item.
1112 * @param action_menu_link $action
1113 * @return string HTML fragment
1115 protected function render_action_menu_link(action_menu_link $action) {
1117 $comparetoalt = '';
1118 $text = '';
1119 if (!$action->icon || $action->primary === false) {
1120 $text .= html_writer::start_tag('span', array('class'=>'menu-action-text'));
1121 if ($action->text instanceof renderable) {
1122 $text .= $this->render($action->text);
1123 } else {
1124 $text .= $action->text;
1125 $comparetoalt = $action->text;
1127 $text .= html_writer::end_tag('span');
1130 $icon = '';
1131 if ($action->icon) {
1132 $icon = $action->icon;
1133 if ($action->primary || !$action->actionmenu->will_be_enhanced()) {
1134 $action->attributes['title'] = $action->text;
1136 if ($icon->attributes['alt'] === $comparetoalt && $action->actionmenu->will_be_enhanced()) {
1137 $icon->attributes['alt'] = ' ';
1139 $icon = $this->render($icon);
1142 // A disabled link is rendered as formatted text.
1143 if (!empty($action->attributes['disabled'])) {
1144 // Do not use div here due to nesting restriction in xhtml strict.
1145 return html_writer::tag('span', $icon.$text, array('class'=>'currentlink', 'role' => 'menuitem'));
1148 $attributes = $action->attributes;
1149 unset($action->attributes['disabled']);
1150 $attributes['href'] = $action->url;
1152 return html_writer::tag('a', $icon.$text, $attributes);
1156 * Renders a primary action_menu_link item.
1158 * @param action_menu_link_primary $action
1159 * @return string HTML fragment
1161 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1162 return $this->render_action_menu_link($action);
1166 * Renders a secondary action_menu_link item.
1168 * @param action_menu_link_secondary $action
1169 * @return string HTML fragment
1171 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1172 return $this->render_action_menu_link($action);
1176 * Prints a nice side block with an optional header.
1178 * The content is described
1179 * by a {@link core_renderer::block_contents} object.
1181 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1182 * <div class="header"></div>
1183 * <div class="content">
1184 * ...CONTENT...
1185 * <div class="footer">
1186 * </div>
1187 * </div>
1188 * <div class="annotation">
1189 * </div>
1190 * </div>
1192 * @param block_contents $bc HTML for the content
1193 * @param string $region the region the block is appearing in.
1194 * @return string the HTML to be output.
1196 public function block(block_contents $bc, $region) {
1197 $bc = clone($bc); // Avoid messing up the object passed in.
1198 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1199 $bc->collapsible = block_contents::NOT_HIDEABLE;
1201 if (!empty($bc->blockinstanceid)) {
1202 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1204 $skiptitle = strip_tags($bc->title);
1205 if ($bc->blockinstanceid && !empty($skiptitle)) {
1206 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1207 } else if (!empty($bc->arialabel)) {
1208 $bc->attributes['aria-label'] = $bc->arialabel;
1210 if ($bc->dockable) {
1211 $bc->attributes['data-dockable'] = 1;
1213 if ($bc->collapsible == block_contents::HIDDEN) {
1214 $bc->add_class('hidden');
1216 if (!empty($bc->controls)) {
1217 $bc->add_class('block_with_controls');
1221 if (empty($skiptitle)) {
1222 $output = '';
1223 $skipdest = '';
1224 } else {
1225 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
1226 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
1229 $output .= html_writer::start_tag('div', $bc->attributes);
1231 $output .= $this->block_header($bc);
1232 $output .= $this->block_content($bc);
1234 $output .= html_writer::end_tag('div');
1236 $output .= $this->block_annotation($bc);
1238 $output .= $skipdest;
1240 $this->init_block_hider_js($bc);
1241 return $output;
1245 * Produces a header for a block
1247 * @param block_contents $bc
1248 * @return string
1250 protected function block_header(block_contents $bc) {
1252 $title = '';
1253 if ($bc->title) {
1254 $attributes = array();
1255 if ($bc->blockinstanceid) {
1256 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1258 $title = html_writer::tag('h2', $bc->title, $attributes);
1261 $blockid = null;
1262 if (isset($bc->attributes['id'])) {
1263 $blockid = $bc->attributes['id'];
1265 $controlshtml = $this->block_controls($bc->controls, $blockid);
1267 $output = '';
1268 if ($title || $controlshtml) {
1269 $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'));
1271 return $output;
1275 * Produces the content area for a block
1277 * @param block_contents $bc
1278 * @return string
1280 protected function block_content(block_contents $bc) {
1281 $output = html_writer::start_tag('div', array('class' => 'content'));
1282 if (!$bc->title && !$this->block_controls($bc->controls)) {
1283 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1285 $output .= $bc->content;
1286 $output .= $this->block_footer($bc);
1287 $output .= html_writer::end_tag('div');
1289 return $output;
1293 * Produces the footer for a block
1295 * @param block_contents $bc
1296 * @return string
1298 protected function block_footer(block_contents $bc) {
1299 $output = '';
1300 if ($bc->footer) {
1301 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1303 return $output;
1307 * Produces the annotation for a block
1309 * @param block_contents $bc
1310 * @return string
1312 protected function block_annotation(block_contents $bc) {
1313 $output = '';
1314 if ($bc->annotation) {
1315 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1317 return $output;
1321 * Calls the JS require function to hide a block.
1323 * @param block_contents $bc A block_contents object
1325 protected function init_block_hider_js(block_contents $bc) {
1326 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1327 $config = new stdClass;
1328 $config->id = $bc->attributes['id'];
1329 $config->title = strip_tags($bc->title);
1330 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1331 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1332 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1334 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1335 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1340 * Render the contents of a block_list.
1342 * @param array $icons the icon for each item.
1343 * @param array $items the content of each item.
1344 * @return string HTML
1346 public function list_block_contents($icons, $items) {
1347 $row = 0;
1348 $lis = array();
1349 foreach ($items as $key => $string) {
1350 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1351 if (!empty($icons[$key])) { //test if the content has an assigned icon
1352 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1354 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1355 $item .= html_writer::end_tag('li');
1356 $lis[] = $item;
1357 $row = 1 - $row; // Flip even/odd.
1359 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1363 * Output all the blocks in a particular region.
1365 * @param string $region the name of a region on this page.
1366 * @return string the HTML to be output.
1368 public function blocks_for_region($region) {
1369 $region = $this->page->apply_theme_region_manipulations($region);
1370 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1371 $blocks = $this->page->blocks->get_blocks_for_region($region);
1372 $lastblock = null;
1373 $zones = array();
1374 foreach ($blocks as $block) {
1375 $zones[] = $block->title;
1377 $output = '';
1379 foreach ($blockcontents as $bc) {
1380 if ($bc instanceof block_contents) {
1381 $output .= $this->block($bc, $region);
1382 $lastblock = $bc->title;
1383 } else if ($bc instanceof block_move_target) {
1384 $output .= $this->block_move_target($bc, $zones, $lastblock);
1385 } else {
1386 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1389 return $output;
1393 * Output a place where the block that is currently being moved can be dropped.
1395 * @param block_move_target $target with the necessary details.
1396 * @param array $zones array of areas where the block can be moved to
1397 * @param string $previous the block located before the area currently being rendered.
1398 * @return string the HTML to be output.
1400 public function block_move_target($target, $zones, $previous) {
1401 if ($previous == null) {
1402 $position = get_string('moveblockbefore', 'block', $zones[0]);
1403 } else {
1404 $position = get_string('moveblockafter', 'block', $previous);
1406 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1410 * Renders a special html link with attached action
1412 * Theme developers: DO NOT OVERRIDE! Please override function
1413 * {@link core_renderer::render_action_link()} instead.
1415 * @param string|moodle_url $url
1416 * @param string $text HTML fragment
1417 * @param component_action $action
1418 * @param array $attributes associative array of html link attributes + disabled
1419 * @param pix_icon optional pix icon to render with the link
1420 * @return string HTML fragment
1422 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1423 if (!($url instanceof moodle_url)) {
1424 $url = new moodle_url($url);
1426 $link = new action_link($url, $text, $action, $attributes, $icon);
1428 return $this->render($link);
1432 * Renders an action_link object.
1434 * The provided link is renderer and the HTML returned. At the same time the
1435 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1437 * @param action_link $link
1438 * @return string HTML fragment
1440 protected function render_action_link(action_link $link) {
1441 global $CFG;
1443 $text = '';
1444 if ($link->icon) {
1445 $text .= $this->render($link->icon);
1448 if ($link->text instanceof renderable) {
1449 $text .= $this->render($link->text);
1450 } else {
1451 $text .= $link->text;
1454 // A disabled link is rendered as formatted text
1455 if (!empty($link->attributes['disabled'])) {
1456 // do not use div here due to nesting restriction in xhtml strict
1457 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1460 $attributes = $link->attributes;
1461 unset($link->attributes['disabled']);
1462 $attributes['href'] = $link->url;
1464 if ($link->actions) {
1465 if (empty($attributes['id'])) {
1466 $id = html_writer::random_id('action_link');
1467 $attributes['id'] = $id;
1468 } else {
1469 $id = $attributes['id'];
1471 foreach ($link->actions as $action) {
1472 $this->add_action_handler($action, $id);
1476 return html_writer::tag('a', $text, $attributes);
1481 * Renders an action_icon.
1483 * This function uses the {@link core_renderer::action_link()} method for the
1484 * most part. What it does different is prepare the icon as HTML and use it
1485 * as the link text.
1487 * Theme developers: If you want to change how action links and/or icons are rendered,
1488 * consider overriding function {@link core_renderer::render_action_link()} and
1489 * {@link core_renderer::render_pix_icon()}.
1491 * @param string|moodle_url $url A string URL or moodel_url
1492 * @param pix_icon $pixicon
1493 * @param component_action $action
1494 * @param array $attributes associative array of html link attributes + disabled
1495 * @param bool $linktext show title next to image in link
1496 * @return string HTML fragment
1498 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1499 if (!($url instanceof moodle_url)) {
1500 $url = new moodle_url($url);
1502 $attributes = (array)$attributes;
1504 if (empty($attributes['class'])) {
1505 // let ppl override the class via $options
1506 $attributes['class'] = 'action-icon';
1509 $icon = $this->render($pixicon);
1511 if ($linktext) {
1512 $text = $pixicon->attributes['alt'];
1513 } else {
1514 $text = '';
1517 return $this->action_link($url, $text.$icon, $action, $attributes);
1521 * Print a message along with button choices for Continue/Cancel
1523 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1525 * @param string $message The question to ask the user
1526 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1527 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1528 * @return string HTML fragment
1530 public function confirm($message, $continue, $cancel) {
1531 if ($continue instanceof single_button) {
1532 // ok
1533 } else if (is_string($continue)) {
1534 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1535 } else if ($continue instanceof moodle_url) {
1536 $continue = new single_button($continue, get_string('continue'), 'post');
1537 } else {
1538 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1541 if ($cancel instanceof single_button) {
1542 // ok
1543 } else if (is_string($cancel)) {
1544 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1545 } else if ($cancel instanceof moodle_url) {
1546 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1547 } else {
1548 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1551 $output = $this->box_start('generalbox', 'notice');
1552 $output .= html_writer::tag('p', $message);
1553 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1554 $output .= $this->box_end();
1555 return $output;
1559 * Returns a form with a single button.
1561 * Theme developers: DO NOT OVERRIDE! Please override function
1562 * {@link core_renderer::render_single_button()} instead.
1564 * @param string|moodle_url $url
1565 * @param string $label button text
1566 * @param string $method get or post submit method
1567 * @param array $options associative array {disabled, title, etc.}
1568 * @return string HTML fragment
1570 public function single_button($url, $label, $method='post', array $options=null) {
1571 if (!($url instanceof moodle_url)) {
1572 $url = new moodle_url($url);
1574 $button = new single_button($url, $label, $method);
1576 foreach ((array)$options as $key=>$value) {
1577 if (array_key_exists($key, $button)) {
1578 $button->$key = $value;
1582 return $this->render($button);
1586 * Renders a single button widget.
1588 * This will return HTML to display a form containing a single button.
1590 * @param single_button $button
1591 * @return string HTML fragment
1593 protected function render_single_button(single_button $button) {
1594 $attributes = array('type' => 'submit',
1595 'value' => $button->label,
1596 'disabled' => $button->disabled ? 'disabled' : null,
1597 'title' => $button->tooltip);
1599 if ($button->actions) {
1600 $id = html_writer::random_id('single_button');
1601 $attributes['id'] = $id;
1602 foreach ($button->actions as $action) {
1603 $this->add_action_handler($action, $id);
1607 // first the input element
1608 $output = html_writer::empty_tag('input', $attributes);
1610 // then hidden fields
1611 $params = $button->url->params();
1612 if ($button->method === 'post') {
1613 $params['sesskey'] = sesskey();
1615 foreach ($params as $var => $val) {
1616 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1619 // then div wrapper for xhtml strictness
1620 $output = html_writer::tag('div', $output);
1622 // now the form itself around it
1623 if ($button->method === 'get') {
1624 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1625 } else {
1626 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1628 if ($url === '') {
1629 $url = '#'; // there has to be always some action
1631 $attributes = array('method' => $button->method,
1632 'action' => $url,
1633 'id' => $button->formid);
1634 $output = html_writer::tag('form', $output, $attributes);
1636 // and finally one more wrapper with class
1637 return html_writer::tag('div', $output, array('class' => $button->class));
1641 * Returns a form with a single select widget.
1643 * Theme developers: DO NOT OVERRIDE! Please override function
1644 * {@link core_renderer::render_single_select()} instead.
1646 * @param moodle_url $url form action target, includes hidden fields
1647 * @param string $name name of selection field - the changing parameter in url
1648 * @param array $options list of options
1649 * @param string $selected selected element
1650 * @param array $nothing
1651 * @param string $formid
1652 * @return string HTML fragment
1654 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1655 if (!($url instanceof moodle_url)) {
1656 $url = new moodle_url($url);
1658 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1660 return $this->render($select);
1664 * Internal implementation of single_select rendering
1666 * @param single_select $select
1667 * @return string HTML fragment
1669 protected function render_single_select(single_select $select) {
1670 $select = clone($select);
1671 if (empty($select->formid)) {
1672 $select->formid = html_writer::random_id('single_select_f');
1675 $output = '';
1676 $params = $select->url->params();
1677 if ($select->method === 'post') {
1678 $params['sesskey'] = sesskey();
1680 foreach ($params as $name=>$value) {
1681 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1684 if (empty($select->attributes['id'])) {
1685 $select->attributes['id'] = html_writer::random_id('single_select');
1688 if ($select->disabled) {
1689 $select->attributes['disabled'] = 'disabled';
1692 if ($select->tooltip) {
1693 $select->attributes['title'] = $select->tooltip;
1696 $select->attributes['class'] = 'autosubmit';
1697 if ($select->class) {
1698 $select->attributes['class'] .= ' ' . $select->class;
1701 if ($select->label) {
1702 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1705 if ($select->helpicon instanceof help_icon) {
1706 $output .= $this->render($select->helpicon);
1708 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1710 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1711 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1713 $nothing = empty($select->nothing) ? false : key($select->nothing);
1714 $this->page->requires->yui_module('moodle-core-formautosubmit',
1715 'M.core.init_formautosubmit',
1716 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1719 // then div wrapper for xhtml strictness
1720 $output = html_writer::tag('div', $output);
1722 // now the form itself around it
1723 if ($select->method === 'get') {
1724 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1725 } else {
1726 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1728 $formattributes = array('method' => $select->method,
1729 'action' => $url,
1730 'id' => $select->formid);
1731 $output = html_writer::tag('form', $output, $formattributes);
1733 // and finally one more wrapper with class
1734 return html_writer::tag('div', $output, array('class' => $select->class));
1738 * Returns a form with a url select widget.
1740 * Theme developers: DO NOT OVERRIDE! Please override function
1741 * {@link core_renderer::render_url_select()} instead.
1743 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1744 * @param string $selected selected element
1745 * @param array $nothing
1746 * @param string $formid
1747 * @return string HTML fragment
1749 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1750 $select = new url_select($urls, $selected, $nothing, $formid);
1751 return $this->render($select);
1755 * Internal implementation of url_select rendering
1757 * @param url_select $select
1758 * @return string HTML fragment
1760 protected function render_url_select(url_select $select) {
1761 global $CFG;
1763 $select = clone($select);
1764 if (empty($select->formid)) {
1765 $select->formid = html_writer::random_id('url_select_f');
1768 if (empty($select->attributes['id'])) {
1769 $select->attributes['id'] = html_writer::random_id('url_select');
1772 if ($select->disabled) {
1773 $select->attributes['disabled'] = 'disabled';
1776 if ($select->tooltip) {
1777 $select->attributes['title'] = $select->tooltip;
1780 $output = '';
1782 if ($select->label) {
1783 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1786 $classes = array();
1787 if (!$select->showbutton) {
1788 $classes[] = 'autosubmit';
1790 if ($select->class) {
1791 $classes[] = $select->class;
1793 if (count($classes)) {
1794 $select->attributes['class'] = implode(' ', $classes);
1797 if ($select->helpicon instanceof help_icon) {
1798 $output .= $this->render($select->helpicon);
1801 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1802 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1803 $urls = array();
1804 foreach ($select->urls as $k=>$v) {
1805 if (is_array($v)) {
1806 // optgroup structure
1807 foreach ($v as $optgrouptitle => $optgroupoptions) {
1808 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1809 if (empty($optionurl)) {
1810 $safeoptionurl = '';
1811 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1812 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1813 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1814 } else if (strpos($optionurl, '/') !== 0) {
1815 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1816 continue;
1817 } else {
1818 $safeoptionurl = $optionurl;
1820 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1823 } else {
1824 // plain list structure
1825 if (empty($k)) {
1826 // nothing selected option
1827 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1828 $k = str_replace($CFG->wwwroot, '', $k);
1829 } else if (strpos($k, '/') !== 0) {
1830 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1831 continue;
1833 $urls[$k] = $v;
1836 $selected = $select->selected;
1837 if (!empty($selected)) {
1838 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1839 $selected = str_replace($CFG->wwwroot, '', $selected);
1840 } else if (strpos($selected, '/') !== 0) {
1841 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1845 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1846 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1848 if (!$select->showbutton) {
1849 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1850 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1851 $nothing = empty($select->nothing) ? false : key($select->nothing);
1852 $this->page->requires->yui_module('moodle-core-formautosubmit',
1853 'M.core.init_formautosubmit',
1854 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1856 } else {
1857 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1860 // then div wrapper for xhtml strictness
1861 $output = html_writer::tag('div', $output);
1863 // now the form itself around it
1864 $formattributes = array('method' => 'post',
1865 'action' => new moodle_url('/course/jumpto.php'),
1866 'id' => $select->formid);
1867 $output = html_writer::tag('form', $output, $formattributes);
1869 // and finally one more wrapper with class
1870 return html_writer::tag('div', $output, array('class' => $select->class));
1874 * Returns a string containing a link to the user documentation.
1875 * Also contains an icon by default. Shown to teachers and admin only.
1877 * @param string $path The page link after doc root and language, no leading slash.
1878 * @param string $text The text to be displayed for the link
1879 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
1880 * @return string
1882 public function doc_link($path, $text = '', $forcepopup = false) {
1883 global $CFG;
1885 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp icon-pre'));
1887 $url = new moodle_url(get_docs_url($path));
1889 $attributes = array('href'=>$url);
1890 if (!empty($CFG->doctonewwindow) || $forcepopup) {
1891 $attributes['class'] = 'helplinkpopup';
1894 return html_writer::tag('a', $icon.$text, $attributes);
1898 * Return HTML for a pix_icon.
1900 * Theme developers: DO NOT OVERRIDE! Please override function
1901 * {@link core_renderer::render_pix_icon()} instead.
1903 * @param string $pix short pix name
1904 * @param string $alt mandatory alt attribute
1905 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1906 * @param array $attributes htm lattributes
1907 * @return string HTML fragment
1909 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1910 $icon = new pix_icon($pix, $alt, $component, $attributes);
1911 return $this->render($icon);
1915 * Renders a pix_icon widget and returns the HTML to display it.
1917 * @param pix_icon $icon
1918 * @return string HTML fragment
1920 protected function render_pix_icon(pix_icon $icon) {
1921 $attributes = $icon->attributes;
1922 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1923 return html_writer::empty_tag('img', $attributes);
1927 * Return HTML to display an emoticon icon.
1929 * @param pix_emoticon $emoticon
1930 * @return string HTML fragment
1932 protected function render_pix_emoticon(pix_emoticon $emoticon) {
1933 $attributes = $emoticon->attributes;
1934 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
1935 return html_writer::empty_tag('img', $attributes);
1939 * Produces the html that represents this rating in the UI
1941 * @param rating $rating the page object on which this rating will appear
1942 * @return string
1944 function render_rating(rating $rating) {
1945 global $CFG, $USER;
1947 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
1948 return null;//ratings are turned off
1951 $ratingmanager = new rating_manager();
1952 // Initialise the JavaScript so ratings can be done by AJAX.
1953 $ratingmanager->initialise_rating_javascript($this->page);
1955 $strrate = get_string("rate", "rating");
1956 $ratinghtml = ''; //the string we'll return
1958 // permissions check - can they view the aggregate?
1959 if ($rating->user_can_view_aggregate()) {
1961 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
1962 $aggregatestr = $rating->get_aggregate_string();
1964 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
1965 if ($rating->count > 0) {
1966 $countstr = "({$rating->count})";
1967 } else {
1968 $countstr = '-';
1970 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
1972 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
1973 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
1975 $nonpopuplink = $rating->get_view_ratings_url();
1976 $popuplink = $rating->get_view_ratings_url(true);
1978 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
1979 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
1980 } else {
1981 $ratinghtml .= $aggregatehtml;
1985 $formstart = null;
1986 // if the item doesn't belong to the current user, the user has permission to rate
1987 // and we're within the assessable period
1988 if ($rating->user_can_rate()) {
1990 $rateurl = $rating->get_rate_url();
1991 $inputs = $rateurl->params();
1993 //start the rating form
1994 $formattrs = array(
1995 'id' => "postrating{$rating->itemid}",
1996 'class' => 'postratingform',
1997 'method' => 'post',
1998 'action' => $rateurl->out_omit_querystring()
2000 $formstart = html_writer::start_tag('form', $formattrs);
2001 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2003 // add the hidden inputs
2004 foreach ($inputs as $name => $value) {
2005 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2006 $formstart .= html_writer::empty_tag('input', $attributes);
2009 if (empty($ratinghtml)) {
2010 $ratinghtml .= $strrate.': ';
2012 $ratinghtml = $formstart.$ratinghtml;
2014 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2015 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2016 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2017 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2019 //output submit button
2020 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2022 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2023 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2025 if (!$rating->settings->scale->isnumeric) {
2026 // If a global scale, try to find current course ID from the context
2027 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2028 $courseid = $coursecontext->instanceid;
2029 } else {
2030 $courseid = $rating->settings->scale->courseid;
2032 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2034 $ratinghtml .= html_writer::end_tag('span');
2035 $ratinghtml .= html_writer::end_tag('div');
2036 $ratinghtml .= html_writer::end_tag('form');
2039 return $ratinghtml;
2043 * Centered heading with attached help button (same title text)
2044 * and optional icon attached.
2046 * @param string $text A heading text
2047 * @param string $helpidentifier The keyword that defines a help page
2048 * @param string $component component name
2049 * @param string|moodle_url $icon
2050 * @param string $iconalt icon alt text
2051 * @param int $level The level of importance of the heading. Defaulting to 2
2052 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2053 * @return string HTML fragment
2055 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2056 $image = '';
2057 if ($icon) {
2058 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
2061 $help = '';
2062 if ($helpidentifier) {
2063 $help = $this->help_icon($helpidentifier, $component);
2066 return $this->heading($image.$text.$help, $level, $classnames);
2070 * Returns HTML to display a help icon.
2072 * @deprecated since Moodle 2.0
2074 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2075 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2079 * Returns HTML to display a help icon.
2081 * Theme developers: DO NOT OVERRIDE! Please override function
2082 * {@link core_renderer::render_help_icon()} instead.
2084 * @param string $identifier The keyword that defines a help page
2085 * @param string $component component name
2086 * @param string|bool $linktext true means use $title as link text, string means link text value
2087 * @return string HTML fragment
2089 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2090 $icon = new help_icon($identifier, $component);
2091 $icon->diag_strings();
2092 if ($linktext === true) {
2093 $icon->linktext = get_string($icon->identifier, $icon->component);
2094 } else if (!empty($linktext)) {
2095 $icon->linktext = $linktext;
2097 return $this->render($icon);
2101 * Implementation of user image rendering.
2103 * @param help_icon $helpicon A help icon instance
2104 * @return string HTML fragment
2106 protected function render_help_icon(help_icon $helpicon) {
2107 global $CFG;
2109 // first get the help image icon
2110 $src = $this->pix_url('help');
2112 $title = get_string($helpicon->identifier, $helpicon->component);
2114 if (empty($helpicon->linktext)) {
2115 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
2116 } else {
2117 $alt = get_string('helpwiththis');
2120 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
2121 $output = html_writer::empty_tag('img', $attributes);
2123 // add the link text if given
2124 if (!empty($helpicon->linktext)) {
2125 // the spacing has to be done through CSS
2126 $output .= $helpicon->linktext;
2129 // now create the link around it - we need https on loginhttps pages
2130 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
2132 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
2133 $title = get_string('helpprefix2', '', trim($title, ". \t"));
2135 $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true', 'target'=>'_blank');
2136 $output = html_writer::tag('a', $output, $attributes);
2138 // and finally span
2139 return html_writer::tag('span', $output, array('class' => 'helptooltip'));
2143 * Returns HTML to display a scale help icon.
2145 * @param int $courseid
2146 * @param stdClass $scale instance
2147 * @return string HTML fragment
2149 public function help_icon_scale($courseid, stdClass $scale) {
2150 global $CFG;
2152 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2154 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2156 $scaleid = abs($scale->id);
2158 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2159 $action = new popup_action('click', $link, 'ratingscale');
2161 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2165 * Creates and returns a spacer image with optional line break.
2167 * @param array $attributes Any HTML attributes to add to the spaced.
2168 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2169 * laxy do it with CSS which is a much better solution.
2170 * @return string HTML fragment
2172 public function spacer(array $attributes = null, $br = false) {
2173 $attributes = (array)$attributes;
2174 if (empty($attributes['width'])) {
2175 $attributes['width'] = 1;
2177 if (empty($attributes['height'])) {
2178 $attributes['height'] = 1;
2180 $attributes['class'] = 'spacer';
2182 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2184 if (!empty($br)) {
2185 $output .= '<br />';
2188 return $output;
2192 * Returns HTML to display the specified user's avatar.
2194 * User avatar may be obtained in two ways:
2195 * <pre>
2196 * // Option 1: (shortcut for simple cases, preferred way)
2197 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2198 * $OUTPUT->user_picture($user, array('popup'=>true));
2200 * // Option 2:
2201 * $userpic = new user_picture($user);
2202 * // Set properties of $userpic
2203 * $userpic->popup = true;
2204 * $OUTPUT->render($userpic);
2205 * </pre>
2207 * Theme developers: DO NOT OVERRIDE! Please override function
2208 * {@link core_renderer::render_user_picture()} instead.
2210 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2211 * If any of these are missing, the database is queried. Avoid this
2212 * if at all possible, particularly for reports. It is very bad for performance.
2213 * @param array $options associative array with user picture options, used only if not a user_picture object,
2214 * options are:
2215 * - courseid=$this->page->course->id (course id of user profile in link)
2216 * - size=35 (size of image)
2217 * - link=true (make image clickable - the link leads to user profile)
2218 * - popup=false (open in popup)
2219 * - alttext=true (add image alt attribute)
2220 * - class = image class attribute (default 'userpicture')
2221 * @return string HTML fragment
2223 public function user_picture(stdClass $user, array $options = null) {
2224 $userpicture = new user_picture($user);
2225 foreach ((array)$options as $key=>$value) {
2226 if (array_key_exists($key, $userpicture)) {
2227 $userpicture->$key = $value;
2230 return $this->render($userpicture);
2234 * Internal implementation of user image rendering.
2236 * @param user_picture $userpicture
2237 * @return string
2239 protected function render_user_picture(user_picture $userpicture) {
2240 global $CFG, $DB;
2242 $user = $userpicture->user;
2244 if ($userpicture->alttext) {
2245 if (!empty($user->imagealt)) {
2246 $alt = $user->imagealt;
2247 } else {
2248 $alt = get_string('pictureof', '', fullname($user));
2250 } else {
2251 $alt = '';
2254 if (empty($userpicture->size)) {
2255 $size = 35;
2256 } else if ($userpicture->size === true or $userpicture->size == 1) {
2257 $size = 100;
2258 } else {
2259 $size = $userpicture->size;
2262 $class = $userpicture->class;
2264 if ($user->picture == 0) {
2265 $class .= ' defaultuserpic';
2268 $src = $userpicture->get_url($this->page, $this);
2270 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2272 // get the image html output fisrt
2273 $output = html_writer::empty_tag('img', $attributes);
2275 // then wrap it in link if needed
2276 if (!$userpicture->link) {
2277 return $output;
2280 if (empty($userpicture->courseid)) {
2281 $courseid = $this->page->course->id;
2282 } else {
2283 $courseid = $userpicture->courseid;
2286 if ($courseid == SITEID) {
2287 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2288 } else {
2289 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2292 $attributes = array('href'=>$url);
2294 if ($userpicture->popup) {
2295 $id = html_writer::random_id('userpicture');
2296 $attributes['id'] = $id;
2297 $this->add_action_handler(new popup_action('click', $url), $id);
2300 return html_writer::tag('a', $output, $attributes);
2304 * Internal implementation of file tree viewer items rendering.
2306 * @param array $dir
2307 * @return string
2309 public function htmllize_file_tree($dir) {
2310 if (empty($dir['subdirs']) and empty($dir['files'])) {
2311 return '';
2313 $result = '<ul>';
2314 foreach ($dir['subdirs'] as $subdir) {
2315 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2317 foreach ($dir['files'] as $file) {
2318 $filename = $file->get_filename();
2319 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2321 $result .= '</ul>';
2323 return $result;
2327 * Returns HTML to display the file picker
2329 * <pre>
2330 * $OUTPUT->file_picker($options);
2331 * </pre>
2333 * Theme developers: DO NOT OVERRIDE! Please override function
2334 * {@link core_renderer::render_file_picker()} instead.
2336 * @param array $options associative array with file manager options
2337 * options are:
2338 * maxbytes=>-1,
2339 * itemid=>0,
2340 * client_id=>uniqid(),
2341 * acepted_types=>'*',
2342 * return_types=>FILE_INTERNAL,
2343 * context=>$PAGE->context
2344 * @return string HTML fragment
2346 public function file_picker($options) {
2347 $fp = new file_picker($options);
2348 return $this->render($fp);
2352 * Internal implementation of file picker rendering.
2354 * @param file_picker $fp
2355 * @return string
2357 public function render_file_picker(file_picker $fp) {
2358 global $CFG, $OUTPUT, $USER;
2359 $options = $fp->options;
2360 $client_id = $options->client_id;
2361 $strsaved = get_string('filesaved', 'repository');
2362 $straddfile = get_string('openpicker', 'repository');
2363 $strloading = get_string('loading', 'repository');
2364 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2365 $strdroptoupload = get_string('droptoupload', 'moodle');
2366 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2368 $currentfile = $options->currentfile;
2369 if (empty($currentfile)) {
2370 $currentfile = '';
2371 } else {
2372 $currentfile .= ' - ';
2374 if ($options->maxbytes) {
2375 $size = $options->maxbytes;
2376 } else {
2377 $size = get_max_upload_file_size();
2379 if ($size == -1) {
2380 $maxsize = '';
2381 } else {
2382 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2384 if ($options->buttonname) {
2385 $buttonname = ' name="' . $options->buttonname . '"';
2386 } else {
2387 $buttonname = '';
2389 $html = <<<EOD
2390 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2391 $icon_progress
2392 </div>
2393 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2394 <div>
2395 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2396 <span> $maxsize </span>
2397 </div>
2398 EOD;
2399 if ($options->env != 'url') {
2400 $html .= <<<EOD
2401 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2402 <div class="filepicker-filename">
2403 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2404 <div class="dndupload-progressbars"></div>
2405 </div>
2406 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2407 </div>
2408 EOD;
2410 $html .= '</div>';
2411 return $html;
2415 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2417 * @param string $cmid the course_module id.
2418 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2419 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2421 public function update_module_button($cmid, $modulename) {
2422 global $CFG;
2423 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2424 $modulename = get_string('modulename', $modulename);
2425 $string = get_string('updatethis', '', $modulename);
2426 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2427 return $this->single_button($url, $string);
2428 } else {
2429 return '';
2434 * Returns HTML to display a "Turn editing on/off" button in a form.
2436 * @param moodle_url $url The URL + params to send through when clicking the button
2437 * @return string HTML the button
2439 public function edit_button(moodle_url $url) {
2441 $url->param('sesskey', sesskey());
2442 if ($this->page->user_is_editing()) {
2443 $url->param('edit', 'off');
2444 $editstring = get_string('turneditingoff');
2445 } else {
2446 $url->param('edit', 'on');
2447 $editstring = get_string('turneditingon');
2450 return $this->single_button($url, $editstring);
2454 * Returns HTML to display a simple button to close a window
2456 * @param string $text The lang string for the button's label (already output from get_string())
2457 * @return string html fragment
2459 public function close_window_button($text='') {
2460 if (empty($text)) {
2461 $text = get_string('closewindow');
2463 $button = new single_button(new moodle_url('#'), $text, 'get');
2464 $button->add_action(new component_action('click', 'close_window'));
2466 return $this->container($this->render($button), 'closewindow');
2470 * Output an error message. By default wraps the error message in <span class="error">.
2471 * If the error message is blank, nothing is output.
2473 * @param string $message the error message.
2474 * @return string the HTML to output.
2476 public function error_text($message) {
2477 if (empty($message)) {
2478 return '';
2480 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2481 return html_writer::tag('span', $message, array('class' => 'error'));
2485 * Do not call this function directly.
2487 * To terminate the current script with a fatal error, call the {@link print_error}
2488 * function, or throw an exception. Doing either of those things will then call this
2489 * function to display the error, before terminating the execution.
2491 * @param string $message The message to output
2492 * @param string $moreinfourl URL where more info can be found about the error
2493 * @param string $link Link for the Continue button
2494 * @param array $backtrace The execution backtrace
2495 * @param string $debuginfo Debugging information
2496 * @return string the HTML to output.
2498 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2499 global $CFG;
2501 $output = '';
2502 $obbuffer = '';
2504 if ($this->has_started()) {
2505 // we can not always recover properly here, we have problems with output buffering,
2506 // html tables, etc.
2507 $output .= $this->opencontainers->pop_all_but_last();
2509 } else {
2510 // It is really bad if library code throws exception when output buffering is on,
2511 // because the buffered text would be printed before our start of page.
2512 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2513 error_reporting(0); // disable notices from gzip compression, etc.
2514 while (ob_get_level() > 0) {
2515 $buff = ob_get_clean();
2516 if ($buff === false) {
2517 break;
2519 $obbuffer .= $buff;
2521 error_reporting($CFG->debug);
2523 // Output not yet started.
2524 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2525 if (empty($_SERVER['HTTP_RANGE'])) {
2526 @header($protocol . ' 404 Not Found');
2527 } else {
2528 // Must stop byteserving attempts somehow,
2529 // this is weird but Chrome PDF viewer can be stopped only with 407!
2530 @header($protocol . ' 407 Proxy Authentication Required');
2533 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2534 $this->page->set_url('/'); // no url
2535 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2536 $this->page->set_title(get_string('error'));
2537 $this->page->set_heading($this->page->course->fullname);
2538 $output .= $this->header();
2541 $message = '<p class="errormessage">' . $message . '</p>'.
2542 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2543 get_string('moreinformation') . '</a></p>';
2544 if (empty($CFG->rolesactive)) {
2545 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2546 //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.
2548 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
2550 if ($CFG->debugdeveloper) {
2551 if (!empty($debuginfo)) {
2552 $debuginfo = s($debuginfo); // removes all nasty JS
2553 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2554 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2556 if (!empty($backtrace)) {
2557 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2559 if ($obbuffer !== '' ) {
2560 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2564 if (empty($CFG->rolesactive)) {
2565 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2566 } else if (!empty($link)) {
2567 $output .= $this->continue_button($link);
2570 $output .= $this->footer();
2572 // Padding to encourage IE to display our error page, rather than its own.
2573 $output .= str_repeat(' ', 512);
2575 return $output;
2579 * Output a notification (that is, a status message about something that has
2580 * just happened).
2582 * @param string $message the message to print out
2583 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2584 * @return string the HTML to output.
2586 public function notification($message, $classes = 'notifyproblem') {
2587 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2591 * Returns HTML to display a continue button that goes to a particular URL.
2593 * @param string|moodle_url $url The url the button goes to.
2594 * @return string the HTML to output.
2596 public function continue_button($url) {
2597 if (!($url instanceof moodle_url)) {
2598 $url = new moodle_url($url);
2600 $button = new single_button($url, get_string('continue'), 'get');
2601 $button->class = 'continuebutton';
2603 return $this->render($button);
2607 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2609 * Theme developers: DO NOT OVERRIDE! Please override function
2610 * {@link core_renderer::render_paging_bar()} instead.
2612 * @param int $totalcount The total number of entries available to be paged through
2613 * @param int $page The page you are currently viewing
2614 * @param int $perpage The number of entries that should be shown per page
2615 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2616 * @param string $pagevar name of page parameter that holds the page number
2617 * @return string the HTML to output.
2619 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2620 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2621 return $this->render($pb);
2625 * Internal implementation of paging bar rendering.
2627 * @param paging_bar $pagingbar
2628 * @return string
2630 protected function render_paging_bar(paging_bar $pagingbar) {
2631 $output = '';
2632 $pagingbar = clone($pagingbar);
2633 $pagingbar->prepare($this, $this->page, $this->target);
2635 if ($pagingbar->totalcount > $pagingbar->perpage) {
2636 $output .= get_string('page') . ':';
2638 if (!empty($pagingbar->previouslink)) {
2639 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
2642 if (!empty($pagingbar->firstlink)) {
2643 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
2646 foreach ($pagingbar->pagelinks as $link) {
2647 $output .= "&#160;&#160;$link";
2650 if (!empty($pagingbar->lastlink)) {
2651 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
2654 if (!empty($pagingbar->nextlink)) {
2655 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
2659 return html_writer::tag('div', $output, array('class' => 'paging'));
2663 * Output the place a skip link goes to.
2665 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2666 * @return string the HTML to output.
2668 public function skip_link_target($id = null) {
2669 return html_writer::tag('span', '', array('id' => $id));
2673 * Outputs a heading
2675 * @param string $text The text of the heading
2676 * @param int $level The level of importance of the heading. Defaulting to 2
2677 * @param string $classes A space-separated list of CSS classes. Defaulting to null
2678 * @param string $id An optional ID
2679 * @return string the HTML to output.
2681 public function heading($text, $level = 2, $classes = null, $id = null) {
2682 $level = (integer) $level;
2683 if ($level < 1 or $level > 6) {
2684 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2686 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2690 * Outputs a box.
2692 * @param string $contents The contents of the box
2693 * @param string $classes A space-separated list of CSS classes
2694 * @param string $id An optional ID
2695 * @param array $attributes An array of other attributes to give the box.
2696 * @return string the HTML to output.
2698 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
2699 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
2703 * Outputs the opening section of a box.
2705 * @param string $classes A space-separated list of CSS classes
2706 * @param string $id An optional ID
2707 * @param array $attributes An array of other attributes to give the box.
2708 * @return string the HTML to output.
2710 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
2711 $this->opencontainers->push('box', html_writer::end_tag('div'));
2712 $attributes['id'] = $id;
2713 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
2714 return html_writer::start_tag('div', $attributes);
2718 * Outputs the closing section of a box.
2720 * @return string the HTML to output.
2722 public function box_end() {
2723 return $this->opencontainers->pop('box');
2727 * Outputs a container.
2729 * @param string $contents The contents of the box
2730 * @param string $classes A space-separated list of CSS classes
2731 * @param string $id An optional ID
2732 * @return string the HTML to output.
2734 public function container($contents, $classes = null, $id = null) {
2735 return $this->container_start($classes, $id) . $contents . $this->container_end();
2739 * Outputs the opening section of a container.
2741 * @param string $classes A space-separated list of CSS classes
2742 * @param string $id An optional ID
2743 * @return string the HTML to output.
2745 public function container_start($classes = null, $id = null) {
2746 $this->opencontainers->push('container', html_writer::end_tag('div'));
2747 return html_writer::start_tag('div', array('id' => $id,
2748 'class' => renderer_base::prepare_classes($classes)));
2752 * Outputs the closing section of a container.
2754 * @return string the HTML to output.
2756 public function container_end() {
2757 return $this->opencontainers->pop('container');
2761 * Make nested HTML lists out of the items
2763 * The resulting list will look something like this:
2765 * <pre>
2766 * <<ul>>
2767 * <<li>><div class='tree_item parent'>(item contents)</div>
2768 * <<ul>
2769 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2770 * <</ul>>
2771 * <</li>>
2772 * <</ul>>
2773 * </pre>
2775 * @param array $items
2776 * @param array $attrs html attributes passed to the top ofs the list
2777 * @return string HTML
2779 public function tree_block_contents($items, $attrs = array()) {
2780 // exit if empty, we don't want an empty ul element
2781 if (empty($items)) {
2782 return '';
2784 // array of nested li elements
2785 $lis = array();
2786 foreach ($items as $item) {
2787 // this applies to the li item which contains all child lists too
2788 $content = $item->content($this);
2789 $liclasses = array($item->get_css_type());
2790 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2791 $liclasses[] = 'collapsed';
2793 if ($item->isactive === true) {
2794 $liclasses[] = 'current_branch';
2796 $liattr = array('class'=>join(' ',$liclasses));
2797 // class attribute on the div item which only contains the item content
2798 $divclasses = array('tree_item');
2799 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2800 $divclasses[] = 'branch';
2801 } else {
2802 $divclasses[] = 'leaf';
2804 if (!empty($item->classes) && count($item->classes)>0) {
2805 $divclasses[] = join(' ', $item->classes);
2807 $divattr = array('class'=>join(' ', $divclasses));
2808 if (!empty($item->id)) {
2809 $divattr['id'] = $item->id;
2811 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2812 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2813 $content = html_writer::empty_tag('hr') . $content;
2815 $content = html_writer::tag('li', $content, $liattr);
2816 $lis[] = $content;
2818 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2822 * Return the navbar content so that it can be echoed out by the layout
2824 * @return string XHTML navbar
2826 public function navbar() {
2827 $items = $this->page->navbar->get_items();
2828 $itemcount = count($items);
2829 if ($itemcount === 0) {
2830 return '';
2833 $htmlblocks = array();
2834 // Iterate the navarray and display each node
2835 $separator = get_separator();
2836 for ($i=0;$i < $itemcount;$i++) {
2837 $item = $items[$i];
2838 $item->hideicon = true;
2839 if ($i===0) {
2840 $content = html_writer::tag('li', $this->render($item));
2841 } else {
2842 $content = html_writer::tag('li', $separator.$this->render($item));
2844 $htmlblocks[] = $content;
2847 //accessibility: heading for navbar list (MDL-20446)
2848 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2849 $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks), array('role'=>'navigation'));
2850 // XHTML
2851 return $navbarcontent;
2855 * Renders a navigation node object.
2857 * @param navigation_node $item The navigation node to render.
2858 * @return string HTML fragment
2860 protected function render_navigation_node(navigation_node $item) {
2861 $content = $item->get_content();
2862 $title = $item->get_title();
2863 if ($item->icon instanceof renderable && !$item->hideicon) {
2864 $icon = $this->render($item->icon);
2865 $content = $icon.$content; // use CSS for spacing of icons
2867 if ($item->helpbutton !== null) {
2868 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2870 if ($content === '') {
2871 return '';
2873 if ($item->action instanceof action_link) {
2874 $link = $item->action;
2875 if ($item->hidden) {
2876 $link->add_class('dimmed');
2878 if (!empty($content)) {
2879 // Providing there is content we will use that for the link content.
2880 $link->text = $content;
2882 $content = $this->render($link);
2883 } else if ($item->action instanceof moodle_url) {
2884 $attributes = array();
2885 if ($title !== '') {
2886 $attributes['title'] = $title;
2888 if ($item->hidden) {
2889 $attributes['class'] = 'dimmed_text';
2891 $content = html_writer::link($item->action, $content, $attributes);
2893 } else if (is_string($item->action) || empty($item->action)) {
2894 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2895 if ($title !== '') {
2896 $attributes['title'] = $title;
2898 if ($item->hidden) {
2899 $attributes['class'] = 'dimmed_text';
2901 $content = html_writer::tag('span', $content, $attributes);
2903 return $content;
2907 * Accessibility: Right arrow-like character is
2908 * used in the breadcrumb trail, course navigation menu
2909 * (previous/next activity), calendar, and search forum block.
2910 * If the theme does not set characters, appropriate defaults
2911 * are set automatically. Please DO NOT
2912 * use &lt; &gt; &raquo; - these are confusing for blind users.
2914 * @return string
2916 public function rarrow() {
2917 return $this->page->theme->rarrow;
2921 * Accessibility: Right arrow-like character is
2922 * used in the breadcrumb trail, course navigation menu
2923 * (previous/next activity), calendar, and search forum block.
2924 * If the theme does not set characters, appropriate defaults
2925 * are set automatically. Please DO NOT
2926 * use &lt; &gt; &raquo; - these are confusing for blind users.
2928 * @return string
2930 public function larrow() {
2931 return $this->page->theme->larrow;
2935 * Returns the custom menu if one has been set
2937 * A custom menu can be configured by browsing to
2938 * Settings: Administration > Appearance > Themes > Theme settings
2939 * and then configuring the custommenu config setting as described.
2941 * Theme developers: DO NOT OVERRIDE! Please override function
2942 * {@link core_renderer::render_custom_menu()} instead.
2944 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
2945 * @return string
2947 public function custom_menu($custommenuitems = '') {
2948 global $CFG;
2949 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
2950 $custommenuitems = $CFG->custommenuitems;
2952 if (empty($custommenuitems)) {
2953 return '';
2955 $custommenu = new custom_menu($custommenuitems, current_language());
2956 return $this->render($custommenu);
2960 * Renders a custom menu object (located in outputcomponents.php)
2962 * The custom menu this method produces makes use of the YUI3 menunav widget
2963 * and requires very specific html elements and classes.
2965 * @staticvar int $menucount
2966 * @param custom_menu $menu
2967 * @return string
2969 protected function render_custom_menu(custom_menu $menu) {
2970 static $menucount = 0;
2971 // If the menu has no children return an empty string
2972 if (!$menu->has_children()) {
2973 return '';
2975 // Increment the menu count. This is used for ID's that get worked with
2976 // in JavaScript as is essential
2977 $menucount++;
2978 // Initialise this custom menu (the custom menu object is contained in javascript-static
2979 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
2980 $jscode = "(function(){{$jscode}})";
2981 $this->page->requires->yui_module('node-menunav', $jscode);
2982 // Build the root nodes as required by YUI
2983 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
2984 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2985 $content .= html_writer::start_tag('ul');
2986 // Render each child
2987 foreach ($menu->get_children() as $item) {
2988 $content .= $this->render_custom_menu_item($item);
2990 // Close the open tags
2991 $content .= html_writer::end_tag('ul');
2992 $content .= html_writer::end_tag('div');
2993 $content .= html_writer::end_tag('div');
2994 // Return the custom menu
2995 return $content;
2999 * Renders a custom menu node as part of a submenu
3001 * The custom menu this method produces makes use of the YUI3 menunav widget
3002 * and requires very specific html elements and classes.
3004 * @see core:renderer::render_custom_menu()
3006 * @staticvar int $submenucount
3007 * @param custom_menu_item $menunode
3008 * @return string
3010 protected function render_custom_menu_item(custom_menu_item $menunode) {
3011 // Required to ensure we get unique trackable id's
3012 static $submenucount = 0;
3013 if ($menunode->has_children()) {
3014 // If the child has menus render it as a sub menu
3015 $submenucount++;
3016 $content = html_writer::start_tag('li');
3017 if ($menunode->get_url() !== null) {
3018 $url = $menunode->get_url();
3019 } else {
3020 $url = '#cm_submenu_'.$submenucount;
3022 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3023 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3024 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3025 $content .= html_writer::start_tag('ul');
3026 foreach ($menunode->get_children() as $menunode) {
3027 $content .= $this->render_custom_menu_item($menunode);
3029 $content .= html_writer::end_tag('ul');
3030 $content .= html_writer::end_tag('div');
3031 $content .= html_writer::end_tag('div');
3032 $content .= html_writer::end_tag('li');
3033 } else {
3034 // The node doesn't have children so produce a final menuitem
3035 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
3036 if ($menunode->get_url() !== null) {
3037 $url = $menunode->get_url();
3038 } else {
3039 $url = '#';
3041 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
3042 $content .= html_writer::end_tag('li');
3044 // Return the sub menu
3045 return $content;
3049 * Renders theme links for switching between default and other themes.
3051 * @return string
3053 protected function theme_switch_links() {
3055 $actualdevice = core_useragent::get_device_type();
3056 $currentdevice = $this->page->devicetypeinuse;
3057 $switched = ($actualdevice != $currentdevice);
3059 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3060 // The user is using the a default device and hasn't switched so don't shown the switch
3061 // device links.
3062 return '';
3065 if ($switched) {
3066 $linktext = get_string('switchdevicerecommended');
3067 $devicetype = $actualdevice;
3068 } else {
3069 $linktext = get_string('switchdevicedefault');
3070 $devicetype = 'default';
3072 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3074 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3075 $content .= html_writer::link($linkurl, $linktext);
3076 $content .= html_writer::end_tag('div');
3078 return $content;
3082 * Renders tabs
3084 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3086 * Theme developers: In order to change how tabs are displayed please override functions
3087 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3089 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3090 * @param string|null $selected which tab to mark as selected, all parent tabs will
3091 * automatically be marked as activated
3092 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3093 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3094 * @return string
3096 public final function tabtree($tabs, $selected = null, $inactive = null) {
3097 return $this->render(new tabtree($tabs, $selected, $inactive));
3101 * Renders tabtree
3103 * @param tabtree $tabtree
3104 * @return string
3106 protected function render_tabtree(tabtree $tabtree) {
3107 if (empty($tabtree->subtree)) {
3108 return '';
3110 $str = '';
3111 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
3112 $str .= $this->render_tabobject($tabtree);
3113 $str .= html_writer::end_tag('div').
3114 html_writer::tag('div', ' ', array('class' => 'clearer'));
3115 return $str;
3119 * Renders tabobject (part of tabtree)
3121 * This function is called from {@link core_renderer::render_tabtree()}
3122 * and also it calls itself when printing the $tabobject subtree recursively.
3124 * Property $tabobject->level indicates the number of row of tabs.
3126 * @param tabobject $tabobject
3127 * @return string HTML fragment
3129 protected function render_tabobject(tabobject $tabobject) {
3130 $str = '';
3132 // Print name of the current tab.
3133 if ($tabobject instanceof tabtree) {
3134 // No name for tabtree root.
3135 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3136 // Tab name without a link. The <a> tag is used for styling.
3137 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink'));
3138 } else {
3139 // Tab name with a link.
3140 if (!($tabobject->link instanceof moodle_url)) {
3141 // backward compartibility when link was passed as quoted string
3142 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3143 } else {
3144 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3148 if (empty($tabobject->subtree)) {
3149 if ($tabobject->selected) {
3150 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3152 return $str;
3155 // Print subtree
3156 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3157 $cnt = 0;
3158 foreach ($tabobject->subtree as $tab) {
3159 $liclass = '';
3160 if (!$cnt) {
3161 $liclass .= ' first';
3163 if ($cnt == count($tabobject->subtree) - 1) {
3164 $liclass .= ' last';
3166 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3167 $liclass .= ' onerow';
3170 if ($tab->selected) {
3171 $liclass .= ' here selected';
3172 } else if ($tab->activated) {
3173 $liclass .= ' here active';
3176 // This will recursively call function render_tabobject() for each item in subtree
3177 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3178 $cnt++;
3180 $str .= html_writer::end_tag('ul');
3182 return $str;
3186 * Get the HTML for blocks in the given region.
3188 * @since 2.5.1 2.6
3189 * @param string $region The region to get HTML for.
3190 * @return string HTML.
3192 public function blocks($region, $classes = array(), $tag = 'aside') {
3193 $displayregion = $this->page->apply_theme_region_manipulations($region);
3194 $classes = (array)$classes;
3195 $classes[] = 'block-region';
3196 $attributes = array(
3197 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3198 'class' => join(' ', $classes),
3199 'data-blockregion' => $displayregion,
3200 'data-droptarget' => '1'
3202 return html_writer::tag($tag, $this->blocks_for_region($region), $attributes);
3206 * Returns the CSS classes to apply to the body tag.
3208 * @since 2.5.1 2.6
3209 * @param array $additionalclasses Any additional classes to apply.
3210 * @return string
3212 public function body_css_classes(array $additionalclasses = array()) {
3213 // Add a class for each block region on the page.
3214 // We use the block manager here because the theme object makes get_string calls.
3215 foreach ($this->page->blocks->get_regions() as $region) {
3216 $additionalclasses[] = 'has-region-'.$region;
3217 if ($this->page->blocks->region_has_content($region, $this)) {
3218 $additionalclasses[] = 'used-region-'.$region;
3219 } else {
3220 $additionalclasses[] = 'empty-region-'.$region;
3223 foreach ($this->page->layout_options as $option => $value) {
3224 if ($value) {
3225 $additionalclasses[] = 'layout-option-'.$option;
3228 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
3229 return $css;
3233 * The ID attribute to apply to the body tag.
3235 * @since 2.5.1 2.6
3236 * @return string
3238 public function body_id() {
3239 return $this->page->bodyid;
3243 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
3245 * @since 2.5.1 2.6
3246 * @param string|array $additionalclasses Any additional classes to give the body tag,
3247 * @return string
3249 public function body_attributes($additionalclasses = array()) {
3250 if (!is_array($additionalclasses)) {
3251 $additionalclasses = explode(' ', $additionalclasses);
3253 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
3257 * Gets HTML for the page heading.
3259 * @since 2.5.1 2.6
3260 * @param string $tag The tag to encase the heading in. h1 by default.
3261 * @return string HTML.
3263 public function page_heading($tag = 'h1') {
3264 return html_writer::tag($tag, $this->page->heading);
3268 * Gets the HTML for the page heading button.
3270 * @since 2.5.1 2.6
3271 * @return string HTML.
3273 public function page_heading_button() {
3274 return $this->page->button;
3278 * Returns the Moodle docs link to use for this page.
3280 * @since 2.5.1 2.6
3281 * @param string $text
3282 * @return string
3284 public function page_doc_link($text = null) {
3285 if ($text === null) {
3286 $text = get_string('moodledocslink');
3288 $path = page_get_doc_link_path($this->page);
3289 if (!$path) {
3290 return '';
3292 return $this->doc_link($path, $text);
3296 * Returns the page heading menu.
3298 * @since 2.5.1 2.6
3299 * @return string HTML.
3301 public function page_heading_menu() {
3302 return $this->page->headingmenu;
3306 * Returns the title to use on the page.
3308 * @since 2.5.1 2.6
3309 * @return string
3311 public function page_title() {
3312 return $this->page->title;
3316 * Returns the URL for the favicon.
3318 * @since 2.5.1 2.6
3319 * @return string The favicon URL
3321 public function favicon() {
3322 return $this->pix_url('favicon', 'theme');
3327 * A renderer that generates output for command-line scripts.
3329 * The implementation of this renderer is probably incomplete.
3331 * @copyright 2009 Tim Hunt
3332 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3333 * @since Moodle 2.0
3334 * @package core
3335 * @category output
3337 class core_renderer_cli extends core_renderer {
3340 * Returns the page header.
3342 * @return string HTML fragment
3344 public function header() {
3345 return $this->page->heading . "\n";
3349 * Returns a template fragment representing a Heading.
3351 * @param string $text The text of the heading
3352 * @param int $level The level of importance of the heading
3353 * @param string $classes A space-separated list of CSS classes
3354 * @param string $id An optional ID
3355 * @return string A template fragment for a heading
3357 public function heading($text, $level = 2, $classes = 'main', $id = null) {
3358 $text .= "\n";
3359 switch ($level) {
3360 case 1:
3361 return '=>' . $text;
3362 case 2:
3363 return '-->' . $text;
3364 default:
3365 return $text;
3370 * Returns a template fragment representing a fatal error.
3372 * @param string $message The message to output
3373 * @param string $moreinfourl URL where more info can be found about the error
3374 * @param string $link Link for the Continue button
3375 * @param array $backtrace The execution backtrace
3376 * @param string $debuginfo Debugging information
3377 * @return string A template fragment for a fatal error
3379 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
3380 global $CFG;
3382 $output = "!!! $message !!!\n";
3384 if ($CFG->debugdeveloper) {
3385 if (!empty($debuginfo)) {
3386 $output .= $this->notification($debuginfo, 'notifytiny');
3388 if (!empty($backtrace)) {
3389 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
3393 return $output;
3397 * Returns a template fragment representing a notification.
3399 * @param string $message The message to include
3400 * @param string $classes A space-separated list of CSS classes
3401 * @return string A template fragment for a notification
3403 public function notification($message, $classes = 'notifyproblem') {
3404 $message = clean_text($message);
3405 if ($classes === 'notifysuccess') {
3406 return "++ $message ++\n";
3408 return "!! $message !!\n";
3414 * A renderer that generates output for ajax scripts.
3416 * This renderer prevents accidental sends back only json
3417 * encoded error messages, all other output is ignored.
3419 * @copyright 2010 Petr Skoda
3420 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3421 * @since Moodle 2.0
3422 * @package core
3423 * @category output
3425 class core_renderer_ajax extends core_renderer {
3428 * Returns a template fragment representing a fatal error.
3430 * @param string $message The message to output
3431 * @param string $moreinfourl URL where more info can be found about the error
3432 * @param string $link Link for the Continue button
3433 * @param array $backtrace The execution backtrace
3434 * @param string $debuginfo Debugging information
3435 * @return string A template fragment for a fatal error
3437 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
3438 global $CFG;
3440 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
3442 $e = new stdClass();
3443 $e->error = $message;
3444 $e->stacktrace = NULL;
3445 $e->debuginfo = NULL;
3446 $e->reproductionlink = NULL;
3447 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
3448 $e->reproductionlink = $link;
3449 if (!empty($debuginfo)) {
3450 $e->debuginfo = $debuginfo;
3452 if (!empty($backtrace)) {
3453 $e->stacktrace = format_backtrace($backtrace, true);
3456 $this->header();
3457 return json_encode($e);
3461 * Used to display a notification.
3462 * For the AJAX notifications are discarded.
3464 * @param string $message
3465 * @param string $classes
3467 public function notification($message, $classes = 'notifyproblem') {}
3470 * Used to display a redirection message.
3471 * AJAX redirections should not occur and as such redirection messages
3472 * are discarded.
3474 * @param moodle_url|string $encodedurl
3475 * @param string $message
3476 * @param int $delay
3477 * @param bool $debugdisableredirect
3479 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
3482 * Prepares the start of an AJAX output.
3484 public function header() {
3485 // unfortunately YUI iframe upload does not support application/json
3486 if (!empty($_FILES)) {
3487 @header('Content-type: text/plain; charset=utf-8');
3488 if (!core_useragent::supports_json_contenttype()) {
3489 @header('X-Content-Type-Options: nosniff');
3491 } else if (!core_useragent::supports_json_contenttype()) {
3492 @header('Content-type: text/plain; charset=utf-8');
3493 @header('X-Content-Type-Options: nosniff');
3494 } else {
3495 @header('Content-type: application/json; charset=utf-8');
3498 // Headers to make it not cacheable and json
3499 @header('Cache-Control: no-store, no-cache, must-revalidate');
3500 @header('Cache-Control: post-check=0, pre-check=0', false);
3501 @header('Pragma: no-cache');
3502 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
3503 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
3504 @header('Accept-Ranges: none');
3508 * There is no footer for an AJAX request, however we must override the
3509 * footer method to prevent the default footer.
3511 public function footer() {}
3514 * No need for headers in an AJAX request... this should never happen.
3515 * @param string $text
3516 * @param int $level
3517 * @param string $classes
3518 * @param string $id
3520 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
3525 * Renderer for media files.
3527 * Used in file resources, media filter, and any other places that need to
3528 * output embedded media.
3530 * @copyright 2011 The Open University
3531 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3533 class core_media_renderer extends plugin_renderer_base {
3534 /** @var array Array of available 'player' objects */
3535 private $players;
3536 /** @var string Regex pattern for links which may contain embeddable content */
3537 private $embeddablemarkers;
3540 * Constructor requires medialib.php.
3542 * This is needed in the constructor (not later) so that you can use the
3543 * constants and static functions that are defined in core_media class
3544 * before you call renderer functions.
3546 public function __construct() {
3547 global $CFG;
3548 require_once($CFG->libdir . '/medialib.php');
3552 * Obtains the list of core_media_player objects currently in use to render
3553 * items.
3555 * The list is in rank order (highest first) and does not include players
3556 * which are disabled.
3558 * @return array Array of core_media_player objects in rank order
3560 protected function get_players() {
3561 global $CFG;
3563 // Save time by only building the list once.
3564 if (!$this->players) {
3565 // Get raw list of players.
3566 $players = $this->get_players_raw();
3568 // Chuck all the ones that are disabled.
3569 foreach ($players as $key => $player) {
3570 if (!$player->is_enabled()) {
3571 unset($players[$key]);
3575 // Sort in rank order (highest first).
3576 usort($players, array('core_media_player', 'compare_by_rank'));
3577 $this->players = $players;
3579 return $this->players;
3583 * Obtains a raw list of player objects that includes objects regardless
3584 * of whether they are disabled or not, and without sorting.
3586 * You can override this in a subclass if you need to add additional
3587 * players.
3589 * The return array is be indexed by player name to make it easier to
3590 * remove players in a subclass.
3592 * @return array $players Array of core_media_player objects in any order
3594 protected function get_players_raw() {
3595 return array(
3596 'vimeo' => new core_media_player_vimeo(),
3597 'youtube' => new core_media_player_youtube(),
3598 'youtube_playlist' => new core_media_player_youtube_playlist(),
3599 'html5video' => new core_media_player_html5video(),
3600 'html5audio' => new core_media_player_html5audio(),
3601 'mp3' => new core_media_player_mp3(),
3602 'flv' => new core_media_player_flv(),
3603 'wmp' => new core_media_player_wmp(),
3604 'qt' => new core_media_player_qt(),
3605 'rm' => new core_media_player_rm(),
3606 'swf' => new core_media_player_swf(),
3607 'link' => new core_media_player_link(),
3612 * Renders a media file (audio or video) using suitable embedded player.
3614 * See embed_alternatives function for full description of parameters.
3615 * This function calls through to that one.
3617 * When using this function you can also specify width and height in the
3618 * URL by including ?d=100x100 at the end. If specified in the URL, this
3619 * will override the $width and $height parameters.
3621 * @param moodle_url $url Full URL of media file
3622 * @param string $name Optional user-readable name to display in download link
3623 * @param int $width Width in pixels (optional)
3624 * @param int $height Height in pixels (optional)
3625 * @param array $options Array of key/value pairs
3626 * @return string HTML content of embed
3628 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
3629 $options = array()) {
3631 // Get width and height from URL if specified (overrides parameters in
3632 // function call).
3633 $rawurl = $url->out(false);
3634 if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
3635 $width = $matches[1];
3636 $height = $matches[2];
3637 $url = new moodle_url(str_replace($matches[0], '', $rawurl));
3640 // Defer to array version of function.
3641 return $this->embed_alternatives(array($url), $name, $width, $height, $options);
3645 * Renders media files (audio or video) using suitable embedded player.
3646 * The list of URLs should be alternative versions of the same content in
3647 * multiple formats. If there is only one format it should have a single
3648 * entry.
3650 * If the media files are not in a supported format, this will give students
3651 * a download link to each format. The download link uses the filename
3652 * unless you supply the optional name parameter.
3654 * Width and height are optional. If specified, these are suggested sizes
3655 * and should be the exact values supplied by the user, if they come from
3656 * user input. These will be treated as relating to the size of the video
3657 * content, not including any player control bar.
3659 * For audio files, height will be ignored. For video files, a few formats
3660 * work if you specify only width, but in general if you specify width
3661 * you must specify height as well.
3663 * The $options array is passed through to the core_media_player classes
3664 * that render the object tag. The keys can contain values from
3665 * core_media::OPTION_xx.
3667 * @param array $alternatives Array of moodle_url to media files
3668 * @param string $name Optional user-readable name to display in download link
3669 * @param int $width Width in pixels (optional)
3670 * @param int $height Height in pixels (optional)
3671 * @param array $options Array of key/value pairs
3672 * @return string HTML content of embed
3674 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
3675 $options = array()) {
3677 // Get list of player plugins (will also require the library).
3678 $players = $this->get_players();
3680 // Set up initial text which will be replaced by first player that
3681 // supports any of the formats.
3682 $out = core_media_player::PLACEHOLDER;
3684 // Loop through all players that support any of these URLs.
3685 foreach ($players as $player) {
3686 // Option: When no other player matched, don't do the default link player.
3687 if (!empty($options[core_media::OPTION_FALLBACK_TO_BLANK]) &&
3688 $player->get_rank() === 0 && $out === core_media_player::PLACEHOLDER) {
3689 continue;
3692 $supported = $player->list_supported_urls($alternatives, $options);
3693 if ($supported) {
3694 // Embed.
3695 $text = $player->embed($supported, $name, $width, $height, $options);
3697 // Put this in place of the 'fallback' slot in the previous text.
3698 $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
3702 // Remove 'fallback' slot from final version and return it.
3703 $out = str_replace(core_media_player::PLACEHOLDER, '', $out);
3704 if (!empty($options[core_media::OPTION_BLOCK]) && $out !== '') {
3705 $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
3707 return $out;
3711 * Checks whether a file can be embedded. If this returns true you will get
3712 * an embedded player; if this returns false, you will just get a download
3713 * link.
3715 * This is a wrapper for can_embed_urls.
3717 * @param moodle_url $url URL of media file
3718 * @param array $options Options (same as when embedding)
3719 * @return bool True if file can be embedded
3721 public function can_embed_url(moodle_url $url, $options = array()) {
3722 return $this->can_embed_urls(array($url), $options);
3726 * Checks whether a file can be embedded. If this returns true you will get
3727 * an embedded player; if this returns false, you will just get a download
3728 * link.
3730 * @param array $urls URL of media file and any alternatives (moodle_url)
3731 * @param array $options Options (same as when embedding)
3732 * @return bool True if file can be embedded
3734 public function can_embed_urls(array $urls, $options = array()) {
3735 // Check all players to see if any of them support it.
3736 foreach ($this->get_players() as $player) {
3737 // Link player (always last on list) doesn't count!
3738 if ($player->get_rank() <= 0) {
3739 break;
3741 // First player that supports it, return true.
3742 if ($player->list_supported_urls($urls, $options)) {
3743 return true;
3746 return false;
3750 * Obtains a list of markers that can be used in a regular expression when
3751 * searching for URLs that can be embedded by any player type.
3753 * This string is used to improve peformance of regex matching by ensuring
3754 * that the (presumably C) regex code can do a quick keyword check on the
3755 * URL part of a link to see if it matches one of these, rather than having
3756 * to go into PHP code for every single link to see if it can be embedded.
3758 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
3760 public function get_embeddable_markers() {
3761 if (empty($this->embeddablemarkers)) {
3762 $markers = '';
3763 foreach ($this->get_players() as $player) {
3764 foreach ($player->get_embeddable_markers() as $marker) {
3765 if ($markers !== '') {
3766 $markers .= '|';
3768 $markers .= preg_quote($marker);
3771 $this->embeddablemarkers = $markers;
3773 return $this->embeddablemarkers;
3778 * The maintenance renderer.
3780 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
3781 * is running a maintenance related task.
3782 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
3784 * @since 2.6
3785 * @package core
3786 * @category output
3787 * @copyright 2013 Sam Hemelryk
3788 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3790 class core_renderer_maintenance extends core_renderer {
3793 * Initialises the renderer instance.
3794 * @param moodle_page $page
3795 * @param string $target
3796 * @throws coding_exception
3798 public function __construct(moodle_page $page, $target) {
3799 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
3800 throw new coding_exception('Invalid request for the maintenance renderer.');
3802 parent::__construct($page, $target);
3806 * Does nothing. The maintenance renderer cannot produce blocks.
3808 * @param block_contents $bc
3809 * @param string $region
3810 * @return string
3812 public function block(block_contents $bc, $region) {
3813 // Computer says no blocks.
3814 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3815 return '';
3819 * Does nothing. The maintenance renderer cannot produce blocks.
3821 * @param string $region
3822 * @param array $classes
3823 * @param string $tag
3824 * @return string
3826 public function blocks($region, $classes = array(), $tag = 'aside') {
3827 // Computer says no blocks.
3828 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3829 return '';
3833 * Does nothing. The maintenance renderer cannot produce blocks.
3835 * @param string $region
3836 * @return string
3838 public function blocks_for_region($region) {
3839 // Computer says no blocks for region.
3840 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3841 return '';
3845 * Does nothing. The maintenance renderer cannot produce a course content header.
3847 * @param bool $onlyifnotcalledbefore
3848 * @return string
3850 public function course_content_header($onlyifnotcalledbefore = false) {
3851 // Computer says no course content header.
3852 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3853 return '';
3857 * Does nothing. The maintenance renderer cannot produce a course content footer.
3859 * @param bool $onlyifnotcalledbefore
3860 * @return string
3862 public function course_content_footer($onlyifnotcalledbefore = false) {
3863 // Computer says no course content footer.
3864 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3865 return '';
3869 * Does nothing. The maintenance renderer cannot produce a course header.
3871 * @return string
3873 public function course_header() {
3874 // Computer says no course header.
3875 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3876 return '';
3880 * Does nothing. The maintenance renderer cannot produce a course footer.
3882 * @return string
3884 public function course_footer() {
3885 // Computer says no course footer.
3886 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3887 return '';
3891 * Does nothing. The maintenance renderer cannot produce a custom menu.
3893 * @param string $custommenuitems
3894 * @return string
3896 public function custom_menu($custommenuitems = '') {
3897 // Computer says no custom menu.
3898 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3899 return '';
3903 * Does nothing. The maintenance renderer cannot produce a file picker.
3905 * @param array $options
3906 * @return string
3908 public function file_picker($options) {
3909 // Computer says no file picker.
3910 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3911 return '';
3915 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
3917 * @param array $dir
3918 * @return string
3920 public function htmllize_file_tree($dir) {
3921 // Hell no we don't want no htmllized file tree.
3922 // Also why on earth is this function on the core renderer???
3923 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3924 return '';
3929 * Does nothing. The maintenance renderer does not support JS.
3931 * @param block_contents $bc
3933 public function init_block_hider_js(block_contents $bc) {
3934 // Computer says no JavaScript.
3935 // Do nothing, ridiculous method.
3939 * Does nothing. The maintenance renderer cannot produce language menus.
3941 * @return string
3943 public function lang_menu() {
3944 // Computer says no lang menu.
3945 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3946 return '';
3950 * Does nothing. The maintenance renderer has no need for login information.
3952 * @param null $withlinks
3953 * @return string
3955 public function login_info($withlinks = null) {
3956 // Computer says no login info.
3957 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3958 return '';
3962 * Does nothing. The maintenance renderer cannot produce user pictures.
3964 * @param stdClass $user
3965 * @param array $options
3966 * @return string
3968 public function user_picture(stdClass $user, array $options = null) {
3969 // Computer says no user pictures.
3970 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3971 return '';