MDL-35883 Accessibility: Added title for login as user link in header and footer...
[moodle.git] / lib / outputrenderers.php
blobf358c4adb58edc720a266f4048561db9021661ea
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 $this->output = $page->get_renderer('core', null, $target);
203 parent::__construct($page, $target);
207 * Renders the provided widget and returns the HTML to display it.
209 * @param renderable $widget instance with renderable interface
210 * @return string
212 public function render(renderable $widget) {
213 $rendermethod = 'render_'.get_class($widget);
214 if (method_exists($this, $rendermethod)) {
215 return $this->$rendermethod($widget);
217 // pass to core renderer if method not found here
218 return $this->output->render($widget);
222 * Magic method used to pass calls otherwise meant for the standard renderer
223 * to it to ensure we don't go causing unnecessary grief.
225 * @param string $method
226 * @param array $arguments
227 * @return mixed
229 public function __call($method, $arguments) {
230 if (method_exists('renderer_base', $method)) {
231 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
233 if (method_exists($this->output, $method)) {
234 return call_user_func_array(array($this->output, $method), $arguments);
235 } else {
236 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
243 * The standard implementation of the core_renderer interface.
245 * @copyright 2009 Tim Hunt
246 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
247 * @since Moodle 2.0
248 * @package core
249 * @category output
251 class core_renderer extends renderer_base {
253 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
254 * in layout files instead.
255 * @deprecated
256 * @var string used in {@link core_renderer::header()}.
258 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
261 * @var string Used to pass information from {@link core_renderer::doctype()} to
262 * {@link core_renderer::standard_head_html()}.
264 protected $contenttype;
267 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
268 * with {@link core_renderer::header()}.
270 protected $metarefreshtag = '';
273 * @var string Unique token for the closing HTML
275 protected $unique_end_html_token;
278 * @var string Unique token for performance information
280 protected $unique_performance_info_token;
283 * @var string Unique token for the main content.
285 protected $unique_main_content_token;
288 * Constructor
290 * @param moodle_page $page the page we are doing output for.
291 * @param string $target one of rendering target constants
293 public function __construct(moodle_page $page, $target) {
294 $this->opencontainers = $page->opencontainers;
295 $this->page = $page;
296 $this->target = $target;
298 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
299 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
300 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
304 * Get the DOCTYPE declaration that should be used with this page. Designed to
305 * be called in theme layout.php files.
307 * @return string the DOCTYPE declaration that should be used.
309 public function doctype() {
310 if ($this->page->theme->doctype === 'html5') {
311 $this->contenttype = 'text/html; charset=utf-8';
312 return "<!DOCTYPE html>\n";
314 } else if ($this->page->theme->doctype === 'xhtml5') {
315 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
316 return "<!DOCTYPE html>\n";
318 } else {
319 // legacy xhtml 1.0
320 $this->contenttype = 'text/html; charset=utf-8';
321 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
326 * The attributes that should be added to the <html> tag. Designed to
327 * be called in theme layout.php files.
329 * @return string HTML fragment.
331 public function htmlattributes() {
332 $return = get_html_lang(true);
333 if ($this->page->theme->doctype !== 'html5') {
334 $return .= ' xmlns="http://www.w3.org/1999/xhtml"';
336 return $return;
340 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
341 * that should be included in the <head> tag. Designed to be called in theme
342 * layout.php files.
344 * @return string HTML fragment.
346 public function standard_head_html() {
347 global $CFG, $SESSION;
348 $output = '';
349 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
350 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
351 if (!$this->page->cacheable) {
352 $output .= '<meta http-equiv="pragma" content="no-cache" />' . "\n";
353 $output .= '<meta http-equiv="expires" content="0" />' . "\n";
355 // This is only set by the {@link redirect()} method
356 $output .= $this->metarefreshtag;
358 // Check if a periodic refresh delay has been set and make sure we arn't
359 // already meta refreshing
360 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
361 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
364 // flow player embedding support
365 $this->page->requires->js_function_call('M.util.load_flowplayer');
367 // Set up help link popups for all links with the helptooltip class
368 $this->page->requires->js_init_call('M.util.help_popups.setup');
370 // Setup help icon overlays.
371 $this->page->requires->yui_module('moodle-core-popuphelp', 'M.core.init_popuphelp');
372 $this->page->requires->strings_for_js(array(
373 'morehelp',
374 'loadinghelp',
375 ), 'moodle');
377 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
379 $focus = $this->page->focuscontrol;
380 if (!empty($focus)) {
381 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
382 // This is a horrifically bad way to handle focus but it is passed in
383 // through messy formslib::moodleform
384 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
385 } else if (strpos($focus, '.')!==false) {
386 // Old style of focus, bad way to do it
387 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);
388 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
389 } else {
390 // Focus element with given id
391 $this->page->requires->js_function_call('focuscontrol', array($focus));
395 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
396 // any other custom CSS can not be overridden via themes and is highly discouraged
397 $urls = $this->page->theme->css_urls($this->page);
398 foreach ($urls as $url) {
399 $this->page->requires->css_theme($url);
402 // Get the theme javascript head and footer
403 if ($jsurl = $this->page->theme->javascript_url(true)) {
404 $this->page->requires->js($jsurl, true);
406 if ($jsurl = $this->page->theme->javascript_url(false)) {
407 $this->page->requires->js($jsurl);
410 // Get any HTML from the page_requirements_manager.
411 $output .= $this->page->requires->get_head_code($this->page, $this);
413 // List alternate versions.
414 foreach ($this->page->alternateversions as $type => $alt) {
415 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
416 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
419 if (!empty($CFG->additionalhtmlhead)) {
420 $output .= "\n".$CFG->additionalhtmlhead;
423 return $output;
427 * The standard tags (typically skip links) that should be output just inside
428 * the start of the <body> tag. Designed to be called in theme layout.php files.
430 * @return string HTML fragment.
432 public function standard_top_of_body_html() {
433 global $CFG;
434 $output = $this->page->requires->get_top_of_body_code();
435 if (!empty($CFG->additionalhtmltopofbody)) {
436 $output .= "\n".$CFG->additionalhtmltopofbody;
438 $output .= $this->maintenance_warning();
439 return $output;
443 * Scheduled maintenance warning message.
445 * Note: This is a nasty hack to display maintenance notice, this should be moved
446 * to some general notification area once we have it.
448 * @return string
450 public function maintenance_warning() {
451 global $CFG;
453 $output = '';
454 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
455 $output .= $this->box_start('errorbox maintenancewarning');
456 $output .= get_string('maintenancemodeisscheduled', 'admin', (int)(($CFG->maintenance_later-time())/60));
457 $output .= $this->box_end();
459 return $output;
463 * The standard tags (typically performance information and validation links,
464 * if we are in developer debug mode) that should be output in the footer area
465 * of the page. Designed to be called in theme layout.php files.
467 * @return string HTML fragment.
469 public function standard_footer_html() {
470 global $CFG, $SCRIPT;
472 // This function is normally called from a layout.php file in {@link core_renderer::header()}
473 // but some of the content won't be known until later, so we return a placeholder
474 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
475 $output = $this->unique_performance_info_token;
476 if ($this->page->devicetypeinuse == 'legacy') {
477 // The legacy theme is in use print the notification
478 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
481 // Get links to switch device types (only shown for users not on a default device)
482 $output .= $this->theme_switch_links();
484 if (!empty($CFG->debugpageinfo)) {
485 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
487 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
488 // Add link to profiling report if necessary
489 if (function_exists('profiling_is_running') && profiling_is_running()) {
490 $txt = get_string('profiledscript', 'admin');
491 $title = get_string('profiledscriptview', 'admin');
492 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
493 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
494 $output .= '<div class="profilingfooter">' . $link . '</div>';
496 $output .= '<div class="purgecaches"><a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/purgecaches.php?confirm=1&amp;sesskey='.sesskey().'">'.get_string('purgecaches', 'admin').'</a></div>';
498 if (!empty($CFG->debugvalidators)) {
499 // 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
500 $output .= '<div class="validators"><ul>
501 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
502 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
503 <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>
504 </ul></div>';
506 if (!empty($CFG->additionalhtmlfooter)) {
507 $output .= "\n".$CFG->additionalhtmlfooter;
509 return $output;
513 * Returns standard main content placeholder.
514 * Designed to be called in theme layout.php files.
516 * @return string HTML fragment.
518 public function main_content() {
519 // This is here because it is the only place we can inject the "main" role over the entire main content area
520 // without requiring all theme's to manually do it, and without creating yet another thing people need to
521 // remember in the theme.
522 // This is an unfortunate hack. DO NO EVER add anything more here.
523 // DO NOT add classes.
524 // DO NOT add an id.
525 return '<div role="main">'.$this->unique_main_content_token.'</div>';
529 * The standard tags (typically script tags that are not needed earlier) that
530 * should be output after everything else, . Designed to be called in theme layout.php files.
532 * @return string HTML fragment.
534 public function standard_end_of_body_html() {
535 // This function is normally called from a layout.php file in {@link core_renderer::header()}
536 // but some of the content won't be known until later, so we return a placeholder
537 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
538 return $this->unique_end_html_token;
542 * Return the standard string that says whether you are logged in (and switched
543 * roles/logged in as another user).
544 * @param bool $withlinks if false, then don't include any links in the HTML produced.
545 * If not set, the default is the nologinlinks option from the theme config.php file,
546 * and if that is not set, then links are included.
547 * @return string HTML fragment.
549 public function login_info($withlinks = null) {
550 global $USER, $CFG, $DB, $SESSION;
552 if (during_initial_install()) {
553 return '';
556 if (is_null($withlinks)) {
557 $withlinks = empty($this->page->layout_options['nologinlinks']);
560 $loginpage = ((string)$this->page->url === get_login_url());
561 $course = $this->page->course;
562 if (session_is_loggedinas()) {
563 $realuser = session_get_realuser();
564 $fullname = fullname($realuser, true);
565 if ($withlinks) {
566 $loginastitle = get_string('loginas');
567 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
568 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
569 } else {
570 $realuserinfo = " [$fullname] ";
572 } else {
573 $realuserinfo = '';
576 $loginurl = get_login_url();
578 if (empty($course->id)) {
579 // $course->id is not defined during installation
580 return '';
581 } else if (isloggedin()) {
582 $context = context_course::instance($course->id);
584 $fullname = fullname($USER, true);
585 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
586 if ($withlinks) {
587 $linktitle = get_string('viewprofile');
588 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
589 } else {
590 $username = $fullname;
592 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
593 if ($withlinks) {
594 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
595 } else {
596 $username .= " from {$idprovider->name}";
599 if (isguestuser()) {
600 $loggedinas = $realuserinfo.get_string('loggedinasguest');
601 if (!$loginpage && $withlinks) {
602 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
604 } else if (is_role_switched($course->id)) { // Has switched roles
605 $rolename = '';
606 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
607 $rolename = ': '.role_get_name($role, $context);
609 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
610 if ($withlinks) {
611 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
612 $loggedinas .= '('.html_writer::tag('a', get_string('switchrolereturn'), array('href'=>$url)).')';
614 } else {
615 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
616 if ($withlinks) {
617 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
620 } else {
621 $loggedinas = get_string('loggedinnot', 'moodle');
622 if (!$loginpage && $withlinks) {
623 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
627 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
629 if (isset($SESSION->justloggedin)) {
630 unset($SESSION->justloggedin);
631 if (!empty($CFG->displayloginfailures)) {
632 if (!isguestuser()) {
633 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
634 $loggedinas .= '&nbsp;<div class="loginfailures">';
635 if (empty($count->accounts)) {
636 $loggedinas .= get_string('failedloginattempts', '', $count);
637 } else {
638 $loggedinas .= get_string('failedloginattemptsall', '', $count);
640 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
641 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/report/log/index.php'.
642 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
644 $loggedinas .= '</div>';
650 return $loggedinas;
654 * Return the 'back' link that normally appears in the footer.
656 * @return string HTML fragment.
658 public function home_link() {
659 global $CFG, $SITE;
661 if ($this->page->pagetype == 'site-index') {
662 // Special case for site home page - please do not remove
663 return '<div class="sitelink">' .
664 '<a title="Moodle" href="http://moodle.org/">' .
665 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
667 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
668 // Special case for during install/upgrade.
669 return '<div class="sitelink">'.
670 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
671 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
673 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
674 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
675 get_string('home') . '</a></div>';
677 } else {
678 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
679 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
684 * Redirects the user by any means possible given the current state
686 * This function should not be called directly, it should always be called using
687 * the redirect function in lib/weblib.php
689 * The redirect function should really only be called before page output has started
690 * however it will allow itself to be called during the state STATE_IN_BODY
692 * @param string $encodedurl The URL to send to encoded if required
693 * @param string $message The message to display to the user if any
694 * @param int $delay The delay before redirecting a user, if $message has been
695 * set this is a requirement and defaults to 3, set to 0 no delay
696 * @param boolean $debugdisableredirect this redirect has been disabled for
697 * debugging purposes. Display a message that explains, and don't
698 * trigger the redirect.
699 * @return string The HTML to display to the user before dying, may contain
700 * meta refresh, javascript refresh, and may have set header redirects
702 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
703 global $CFG;
704 $url = str_replace('&amp;', '&', $encodedurl);
706 switch ($this->page->state) {
707 case moodle_page::STATE_BEFORE_HEADER :
708 // No output yet it is safe to delivery the full arsenal of redirect methods
709 if (!$debugdisableredirect) {
710 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
711 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
712 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
714 $output = $this->header();
715 break;
716 case moodle_page::STATE_PRINTING_HEADER :
717 // We should hopefully never get here
718 throw new coding_exception('You cannot redirect while printing the page header');
719 break;
720 case moodle_page::STATE_IN_BODY :
721 // We really shouldn't be here but we can deal with this
722 debugging("You should really redirect before you start page output");
723 if (!$debugdisableredirect) {
724 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
726 $output = $this->opencontainers->pop_all_but_last();
727 break;
728 case moodle_page::STATE_DONE :
729 // Too late to be calling redirect now
730 throw new coding_exception('You cannot redirect after the entire page has been generated');
731 break;
733 $output .= $this->notification($message, 'redirectmessage');
734 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
735 if ($debugdisableredirect) {
736 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
738 $output .= $this->footer();
739 return $output;
743 * Start output by sending the HTTP headers, and printing the HTML <head>
744 * and the start of the <body>.
746 * To control what is printed, you should set properties on $PAGE. If you
747 * are familiar with the old {@link print_header()} function from Moodle 1.9
748 * you will find that there are properties on $PAGE that correspond to most
749 * of the old parameters to could be passed to print_header.
751 * Not that, in due course, the remaining $navigation, $menu parameters here
752 * will be replaced by more properties of $PAGE, but that is still to do.
754 * @return string HTML that you must output this, preferably immediately.
756 public function header() {
757 global $USER, $CFG;
759 if (session_is_loggedinas()) {
760 $this->page->add_body_class('userloggedinas');
763 // Give themes a chance to init/alter the page object.
764 $this->page->theme->init_page($this->page);
766 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
768 // Find the appropriate page layout file, based on $this->page->pagelayout.
769 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
770 // Render the layout using the layout file.
771 $rendered = $this->render_page_layout($layoutfile);
773 // Slice the rendered output into header and footer.
774 $cutpos = strpos($rendered, $this->unique_main_content_token);
775 if ($cutpos === false) {
776 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
777 $token = self::MAIN_CONTENT_TOKEN;
778 } else {
779 $token = $this->unique_main_content_token;
782 if ($cutpos === false) {
783 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.');
785 $header = substr($rendered, 0, $cutpos);
786 $footer = substr($rendered, $cutpos + strlen($token));
788 if (empty($this->contenttype)) {
789 debugging('The page layout file did not call $OUTPUT->doctype()');
790 $header = $this->doctype() . $header;
793 // If this theme version is below 2.4 release and this is a course view page
794 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
795 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
796 // check if course content header/footer have not been output during render of theme layout
797 $coursecontentheader = $this->course_content_header(true);
798 $coursecontentfooter = $this->course_content_footer(true);
799 if (!empty($coursecontentheader)) {
800 // display debug message and add header and footer right above and below main content
801 // Please note that course header and footer (to be displayed above and below the whole page)
802 // are not displayed in this case at all.
803 // Besides the content header and footer are not displayed on any other course page
804 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);
805 $header .= $coursecontentheader;
806 $footer = $coursecontentfooter. $footer;
810 send_headers($this->contenttype, $this->page->cacheable);
812 $this->opencontainers->push('header/footer', $footer);
813 $this->page->set_state(moodle_page::STATE_IN_BODY);
815 return $header . $this->skip_link_target('maincontent');
819 * Renders and outputs the page layout file.
821 * This is done by preparing the normal globals available to a script, and
822 * then including the layout file provided by the current theme for the
823 * requested layout.
825 * @param string $layoutfile The name of the layout file
826 * @return string HTML code
828 protected function render_page_layout($layoutfile) {
829 global $CFG, $SITE, $USER;
830 // The next lines are a bit tricky. The point is, here we are in a method
831 // of a renderer class, and this object may, or may not, be the same as
832 // the global $OUTPUT object. When rendering the page layout file, we want to use
833 // this object. However, people writing Moodle code expect the current
834 // renderer to be called $OUTPUT, not $this, so define a variable called
835 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
836 $OUTPUT = $this;
837 $PAGE = $this->page;
838 $COURSE = $this->page->course;
840 ob_start();
841 include($layoutfile);
842 $rendered = ob_get_contents();
843 ob_end_clean();
844 return $rendered;
848 * Outputs the page's footer
850 * @return string HTML fragment
852 public function footer() {
853 global $CFG, $DB;
855 $output = $this->container_end_all(true);
857 $footer = $this->opencontainers->pop('header/footer');
859 if (debugging() and $DB and $DB->is_transaction_started()) {
860 // TODO: MDL-20625 print warning - transaction will be rolled back
863 // Provide some performance info if required
864 $performanceinfo = '';
865 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
866 $perf = get_performance_info();
867 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
868 error_log("PERF: " . $perf['txt']);
870 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
871 $performanceinfo = $perf['html'];
874 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
876 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
878 $this->page->set_state(moodle_page::STATE_DONE);
880 return $output . $footer;
884 * Close all but the last open container. This is useful in places like error
885 * handling, where you want to close all the open containers (apart from <body>)
886 * before outputting the error message.
888 * @param bool $shouldbenone assert that the stack should be empty now - causes a
889 * developer debug warning if it isn't.
890 * @return string the HTML required to close any open containers inside <body>.
892 public function container_end_all($shouldbenone = false) {
893 return $this->opencontainers->pop_all_but_last($shouldbenone);
897 * Returns course-specific information to be output immediately above content on any course page
898 * (for the current course)
900 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
901 * @return string
903 public function course_content_header($onlyifnotcalledbefore = false) {
904 global $CFG;
905 if ($this->page->course->id == SITEID) {
906 // return immediately and do not include /course/lib.php if not necessary
907 return '';
909 static $functioncalled = false;
910 if ($functioncalled && $onlyifnotcalledbefore) {
911 // we have already output the content header
912 return '';
914 require_once($CFG->dirroot.'/course/lib.php');
915 $functioncalled = true;
916 $courseformat = course_get_format($this->page->course);
917 if (($obj = $courseformat->course_content_header()) !== null) {
918 return $courseformat->get_renderer($this->page)->render($obj);
920 return '';
924 * Returns course-specific information to be output immediately below content on any course page
925 * (for the current course)
927 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
928 * @return string
930 public function course_content_footer($onlyifnotcalledbefore = false) {
931 global $CFG;
932 if ($this->page->course->id == SITEID) {
933 // return immediately and do not include /course/lib.php if not necessary
934 return '';
936 static $functioncalled = false;
937 if ($functioncalled && $onlyifnotcalledbefore) {
938 // we have already output the content footer
939 return '';
941 $functioncalled = true;
942 require_once($CFG->dirroot.'/course/lib.php');
943 $courseformat = course_get_format($this->page->course);
944 if (($obj = $courseformat->course_content_footer()) !== null) {
945 return $courseformat->get_renderer($this->page)->render($obj);
947 return '';
951 * Returns course-specific information to be output on any course page in the header area
952 * (for the current course)
954 * @return string
956 public function course_header() {
957 global $CFG;
958 if ($this->page->course->id == SITEID) {
959 // return immediately and do not include /course/lib.php if not necessary
960 return '';
962 require_once($CFG->dirroot.'/course/lib.php');
963 $courseformat = course_get_format($this->page->course);
964 if (($obj = $courseformat->course_header()) !== null) {
965 return $courseformat->get_renderer($this->page)->render($obj);
967 return '';
971 * Returns course-specific information to be output on any course page in the footer area
972 * (for the current course)
974 * @return string
976 public function course_footer() {
977 global $CFG;
978 if ($this->page->course->id == SITEID) {
979 // return immediately and do not include /course/lib.php if not necessary
980 return '';
982 require_once($CFG->dirroot.'/course/lib.php');
983 $courseformat = course_get_format($this->page->course);
984 if (($obj = $courseformat->course_footer()) !== null) {
985 return $courseformat->get_renderer($this->page)->render($obj);
987 return '';
991 * Returns lang menu or '', this method also checks forcing of languages in courses.
993 * @return string The lang menu HTML or empty string
995 public function lang_menu() {
996 global $CFG;
998 if (empty($CFG->langmenu)) {
999 return '';
1002 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1003 // do not show lang menu if language forced
1004 return '';
1007 $currlang = current_language();
1008 $langs = get_string_manager()->get_list_of_translations();
1010 if (count($langs) < 2) {
1011 return '';
1014 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1015 $s->label = get_accesshide(get_string('language'));
1016 $s->class = 'langmenu';
1017 return $this->render($s);
1021 * Output the row of editing icons for a block, as defined by the controls array.
1023 * @param array $controls an array like {@link block_contents::$controls}.
1024 * @return string HTML fragment.
1026 public function block_controls($controls) {
1027 if (empty($controls)) {
1028 return '';
1030 $controlshtml = array();
1031 foreach ($controls as $control) {
1032 $controlshtml[] = html_writer::tag('a',
1033 html_writer::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
1034 array('class' => 'icon ' . $control['class'],'title' => $control['caption'], 'href' => $control['url']));
1036 return html_writer::tag('div', implode('', $controlshtml), array('class' => 'commands'));
1040 * Prints a nice side block with an optional header.
1042 * The content is described
1043 * by a {@link core_renderer::block_contents} object.
1045 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1046 * <div class="header"></div>
1047 * <div class="content">
1048 * ...CONTENT...
1049 * <div class="footer">
1050 * </div>
1051 * </div>
1052 * <div class="annotation">
1053 * </div>
1054 * </div>
1056 * @param block_contents $bc HTML for the content
1057 * @param string $region the region the block is appearing in.
1058 * @return string the HTML to be output.
1060 public function block(block_contents $bc, $region) {
1061 $bc = clone($bc); // Avoid messing up the object passed in.
1062 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1063 $bc->collapsible = block_contents::NOT_HIDEABLE;
1065 $skiptitle = strip_tags($bc->title);
1066 if ($bc->blockinstanceid && !empty($skiptitle)) {
1067 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1068 } else if (!empty($bc->arialabel)) {
1069 $bc->attributes['aria-label'] = $bc->arialabel;
1071 if ($bc->collapsible == block_contents::HIDDEN) {
1072 $bc->add_class('hidden');
1074 if (!empty($bc->controls)) {
1075 $bc->add_class('block_with_controls');
1079 if (empty($skiptitle)) {
1080 $output = '';
1081 $skipdest = '';
1082 } else {
1083 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
1084 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
1087 $output .= html_writer::start_tag('div', $bc->attributes);
1089 $output .= $this->block_header($bc);
1090 $output .= $this->block_content($bc);
1092 $output .= html_writer::end_tag('div');
1094 $output .= $this->block_annotation($bc);
1096 $output .= $skipdest;
1098 $this->init_block_hider_js($bc);
1099 return $output;
1103 * Produces a header for a block
1105 * @param block_contents $bc
1106 * @return string
1108 protected function block_header(block_contents $bc) {
1110 $title = '';
1111 if ($bc->title) {
1112 $attributes = array();
1113 if ($bc->blockinstanceid) {
1114 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1116 $title = html_writer::tag('h2', $bc->title, $attributes);
1119 $controlshtml = $this->block_controls($bc->controls);
1121 $output = '';
1122 if ($title || $controlshtml) {
1123 $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'));
1125 return $output;
1129 * Produces the content area for a block
1131 * @param block_contents $bc
1132 * @return string
1134 protected function block_content(block_contents $bc) {
1135 $output = html_writer::start_tag('div', array('class' => 'content'));
1136 if (!$bc->title && !$this->block_controls($bc->controls)) {
1137 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1139 $output .= $bc->content;
1140 $output .= $this->block_footer($bc);
1141 $output .= html_writer::end_tag('div');
1143 return $output;
1147 * Produces the footer for a block
1149 * @param block_contents $bc
1150 * @return string
1152 protected function block_footer(block_contents $bc) {
1153 $output = '';
1154 if ($bc->footer) {
1155 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1157 return $output;
1161 * Produces the annotation for a block
1163 * @param block_contents $bc
1164 * @return string
1166 protected function block_annotation(block_contents $bc) {
1167 $output = '';
1168 if ($bc->annotation) {
1169 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1171 return $output;
1175 * Calls the JS require function to hide a block.
1177 * @param block_contents $bc A block_contents object
1179 protected function init_block_hider_js(block_contents $bc) {
1180 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1181 $config = new stdClass;
1182 $config->id = $bc->attributes['id'];
1183 $config->title = strip_tags($bc->title);
1184 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1185 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1186 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1188 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1189 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1194 * Render the contents of a block_list.
1196 * @param array $icons the icon for each item.
1197 * @param array $items the content of each item.
1198 * @return string HTML
1200 public function list_block_contents($icons, $items) {
1201 $row = 0;
1202 $lis = array();
1203 foreach ($items as $key => $string) {
1204 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1205 if (!empty($icons[$key])) { //test if the content has an assigned icon
1206 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1208 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1209 $item .= html_writer::end_tag('li');
1210 $lis[] = $item;
1211 $row = 1 - $row; // Flip even/odd.
1213 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1217 * Output all the blocks in a particular region.
1219 * @param string $region the name of a region on this page.
1220 * @return string the HTML to be output.
1222 public function blocks_for_region($region) {
1223 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1224 $blocks = $this->page->blocks->get_blocks_for_region($region);
1225 $lastblock = null;
1226 $zones = array();
1227 foreach ($blocks as $block) {
1228 $zones[] = $block->title;
1230 $output = '';
1232 foreach ($blockcontents as $bc) {
1233 if ($bc instanceof block_contents) {
1234 $output .= $this->block($bc, $region);
1235 $lastblock = $bc->title;
1236 } else if ($bc instanceof block_move_target) {
1237 $output .= $this->block_move_target($bc, $zones, $lastblock);
1238 } else {
1239 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1242 return $output;
1246 * Output a place where the block that is currently being moved can be dropped.
1248 * @param block_move_target $target with the necessary details.
1249 * @param array $zones array of areas where the block can be moved to
1250 * @param string $previous the block located before the area currently being rendered.
1251 * @return string the HTML to be output.
1253 public function block_move_target($target, $zones, $previous) {
1254 if ($previous == null) {
1255 $position = get_string('moveblockbefore', 'block', $zones[0]);
1256 } else {
1257 $position = get_string('moveblockafter', 'block', $previous);
1259 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1263 * Renders a special html link with attached action
1265 * @param string|moodle_url $url
1266 * @param string $text HTML fragment
1267 * @param component_action $action
1268 * @param array $attributes associative array of html link attributes + disabled
1269 * @return string HTML fragment
1271 public function action_link($url, $text, component_action $action = null, array $attributes=null) {
1272 if (!($url instanceof moodle_url)) {
1273 $url = new moodle_url($url);
1275 $link = new action_link($url, $text, $action, $attributes);
1277 return $this->render($link);
1281 * Renders an action_link object.
1283 * The provided link is renderer and the HTML returned. At the same time the
1284 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1286 * @param action_link $link
1287 * @return string HTML fragment
1289 protected function render_action_link(action_link $link) {
1290 global $CFG;
1292 if ($link->text instanceof renderable) {
1293 $text = $this->render($link->text);
1294 } else {
1295 $text = $link->text;
1298 // A disabled link is rendered as formatted text
1299 if (!empty($link->attributes['disabled'])) {
1300 // do not use div here due to nesting restriction in xhtml strict
1301 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1304 $attributes = $link->attributes;
1305 unset($link->attributes['disabled']);
1306 $attributes['href'] = $link->url;
1308 if ($link->actions) {
1309 if (empty($attributes['id'])) {
1310 $id = html_writer::random_id('action_link');
1311 $attributes['id'] = $id;
1312 } else {
1313 $id = $attributes['id'];
1315 foreach ($link->actions as $action) {
1316 $this->add_action_handler($action, $id);
1320 return html_writer::tag('a', $text, $attributes);
1325 * Renders an action_icon.
1327 * This function uses the {@link core_renderer::action_link()} method for the
1328 * most part. What it does different is prepare the icon as HTML and use it
1329 * as the link text.
1331 * @param string|moodle_url $url A string URL or moodel_url
1332 * @param pix_icon $pixicon
1333 * @param component_action $action
1334 * @param array $attributes associative array of html link attributes + disabled
1335 * @param bool $linktext show title next to image in link
1336 * @return string HTML fragment
1338 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1339 if (!($url instanceof moodle_url)) {
1340 $url = new moodle_url($url);
1342 $attributes = (array)$attributes;
1344 if (empty($attributes['class'])) {
1345 // let ppl override the class via $options
1346 $attributes['class'] = 'action-icon';
1349 $icon = $this->render($pixicon);
1351 if ($linktext) {
1352 $text = $pixicon->attributes['alt'];
1353 } else {
1354 $text = '';
1357 return $this->action_link($url, $text.$icon, $action, $attributes);
1361 * Print a message along with button choices for Continue/Cancel
1363 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1365 * @param string $message The question to ask the user
1366 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1367 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1368 * @return string HTML fragment
1370 public function confirm($message, $continue, $cancel) {
1371 if ($continue instanceof single_button) {
1372 // ok
1373 } else if (is_string($continue)) {
1374 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1375 } else if ($continue instanceof moodle_url) {
1376 $continue = new single_button($continue, get_string('continue'), 'post');
1377 } else {
1378 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1381 if ($cancel instanceof single_button) {
1382 // ok
1383 } else if (is_string($cancel)) {
1384 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1385 } else if ($cancel instanceof moodle_url) {
1386 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1387 } else {
1388 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1391 $output = $this->box_start('generalbox', 'notice');
1392 $output .= html_writer::tag('p', $message);
1393 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1394 $output .= $this->box_end();
1395 return $output;
1399 * Returns a form with a single button.
1401 * @param string|moodle_url $url
1402 * @param string $label button text
1403 * @param string $method get or post submit method
1404 * @param array $options associative array {disabled, title, etc.}
1405 * @return string HTML fragment
1407 public function single_button($url, $label, $method='post', array $options=null) {
1408 if (!($url instanceof moodle_url)) {
1409 $url = new moodle_url($url);
1411 $button = new single_button($url, $label, $method);
1413 foreach ((array)$options as $key=>$value) {
1414 if (array_key_exists($key, $button)) {
1415 $button->$key = $value;
1419 return $this->render($button);
1423 * Renders a single button widget.
1425 * This will return HTML to display a form containing a single button.
1427 * @param single_button $button
1428 * @return string HTML fragment
1430 protected function render_single_button(single_button $button) {
1431 $attributes = array('type' => 'submit',
1432 'value' => $button->label,
1433 'disabled' => $button->disabled ? 'disabled' : null,
1434 'title' => $button->tooltip);
1436 if ($button->actions) {
1437 $id = html_writer::random_id('single_button');
1438 $attributes['id'] = $id;
1439 foreach ($button->actions as $action) {
1440 $this->add_action_handler($action, $id);
1444 // first the input element
1445 $output = html_writer::empty_tag('input', $attributes);
1447 // then hidden fields
1448 $params = $button->url->params();
1449 if ($button->method === 'post') {
1450 $params['sesskey'] = sesskey();
1452 foreach ($params as $var => $val) {
1453 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1456 // then div wrapper for xhtml strictness
1457 $output = html_writer::tag('div', $output);
1459 // now the form itself around it
1460 if ($button->method === 'get') {
1461 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1462 } else {
1463 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1465 if ($url === '') {
1466 $url = '#'; // there has to be always some action
1468 $attributes = array('method' => $button->method,
1469 'action' => $url,
1470 'id' => $button->formid);
1471 $output = html_writer::tag('form', $output, $attributes);
1473 // and finally one more wrapper with class
1474 return html_writer::tag('div', $output, array('class' => $button->class));
1478 * Returns a form with a single select widget.
1480 * @param moodle_url $url form action target, includes hidden fields
1481 * @param string $name name of selection field - the changing parameter in url
1482 * @param array $options list of options
1483 * @param string $selected selected element
1484 * @param array $nothing
1485 * @param string $formid
1486 * @return string HTML fragment
1488 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1489 if (!($url instanceof moodle_url)) {
1490 $url = new moodle_url($url);
1492 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1494 return $this->render($select);
1498 * Internal implementation of single_select rendering
1500 * @param single_select $select
1501 * @return string HTML fragment
1503 protected function render_single_select(single_select $select) {
1504 $select = clone($select);
1505 if (empty($select->formid)) {
1506 $select->formid = html_writer::random_id('single_select_f');
1509 $output = '';
1510 $params = $select->url->params();
1511 if ($select->method === 'post') {
1512 $params['sesskey'] = sesskey();
1514 foreach ($params as $name=>$value) {
1515 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1518 if (empty($select->attributes['id'])) {
1519 $select->attributes['id'] = html_writer::random_id('single_select');
1522 if ($select->disabled) {
1523 $select->attributes['disabled'] = 'disabled';
1526 if ($select->tooltip) {
1527 $select->attributes['title'] = $select->tooltip;
1530 $select->attributes['class'] = 'autosubmit';
1531 if ($select->class) {
1532 $select->attributes['class'] .= ' ' . $select->class;
1535 if ($select->label) {
1536 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1539 if ($select->helpicon instanceof help_icon) {
1540 $output .= $this->render($select->helpicon);
1542 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1544 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1545 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1547 $nothing = empty($select->nothing) ? false : key($select->nothing);
1548 $this->page->requires->yui_module('moodle-core-formautosubmit',
1549 'M.core.init_formautosubmit',
1550 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1553 // then div wrapper for xhtml strictness
1554 $output = html_writer::tag('div', $output);
1556 // now the form itself around it
1557 if ($select->method === 'get') {
1558 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1559 } else {
1560 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1562 $formattributes = array('method' => $select->method,
1563 'action' => $url,
1564 'id' => $select->formid);
1565 $output = html_writer::tag('form', $output, $formattributes);
1567 // and finally one more wrapper with class
1568 return html_writer::tag('div', $output, array('class' => $select->class));
1572 * Returns a form with a url select widget.
1574 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1575 * @param string $selected selected element
1576 * @param array $nothing
1577 * @param string $formid
1578 * @return string HTML fragment
1580 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1581 $select = new url_select($urls, $selected, $nothing, $formid);
1582 return $this->render($select);
1586 * Internal implementation of url_select rendering
1588 * @param url_select $select
1589 * @return string HTML fragment
1591 protected function render_url_select(url_select $select) {
1592 global $CFG;
1594 $select = clone($select);
1595 if (empty($select->formid)) {
1596 $select->formid = html_writer::random_id('url_select_f');
1599 if (empty($select->attributes['id'])) {
1600 $select->attributes['id'] = html_writer::random_id('url_select');
1603 if ($select->disabled) {
1604 $select->attributes['disabled'] = 'disabled';
1607 if ($select->tooltip) {
1608 $select->attributes['title'] = $select->tooltip;
1611 $output = '';
1613 if ($select->label) {
1614 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1617 $classes = array();
1618 if (!$select->showbutton) {
1619 $classes[] = 'autosubmit';
1621 if ($select->class) {
1622 $classes[] = $select->class;
1624 if (count($classes)) {
1625 $select->attributes['class'] = implode(' ', $classes);
1628 if ($select->helpicon instanceof help_icon) {
1629 $output .= $this->render($select->helpicon);
1632 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1633 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1634 $urls = array();
1635 foreach ($select->urls as $k=>$v) {
1636 if (is_array($v)) {
1637 // optgroup structure
1638 foreach ($v as $optgrouptitle => $optgroupoptions) {
1639 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1640 if (empty($optionurl)) {
1641 $safeoptionurl = '';
1642 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1643 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1644 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1645 } else if (strpos($optionurl, '/') !== 0) {
1646 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1647 continue;
1648 } else {
1649 $safeoptionurl = $optionurl;
1651 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1654 } else {
1655 // plain list structure
1656 if (empty($k)) {
1657 // nothing selected option
1658 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1659 $k = str_replace($CFG->wwwroot, '', $k);
1660 } else if (strpos($k, '/') !== 0) {
1661 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1662 continue;
1664 $urls[$k] = $v;
1667 $selected = $select->selected;
1668 if (!empty($selected)) {
1669 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1670 $selected = str_replace($CFG->wwwroot, '', $selected);
1671 } else if (strpos($selected, '/') !== 0) {
1672 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1676 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1677 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1679 if (!$select->showbutton) {
1680 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1681 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1682 $nothing = empty($select->nothing) ? false : key($select->nothing);
1683 $this->page->requires->yui_module('moodle-core-formautosubmit',
1684 'M.core.init_formautosubmit',
1685 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1687 } else {
1688 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1691 // then div wrapper for xhtml strictness
1692 $output = html_writer::tag('div', $output);
1694 // now the form itself around it
1695 $formattributes = array('method' => 'post',
1696 'action' => new moodle_url('/course/jumpto.php'),
1697 'id' => $select->formid);
1698 $output = html_writer::tag('form', $output, $formattributes);
1700 // and finally one more wrapper with class
1701 return html_writer::tag('div', $output, array('class' => $select->class));
1705 * Returns a string containing a link to the user documentation.
1706 * Also contains an icon by default. Shown to teachers and admin only.
1708 * @param string $path The page link after doc root and language, no leading slash.
1709 * @param string $text The text to be displayed for the link
1710 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
1711 * @return string
1713 public function doc_link($path, $text = '', $forcepopup = false) {
1714 global $CFG;
1716 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp icon-pre'));
1718 $url = new moodle_url(get_docs_url($path));
1720 $attributes = array('href'=>$url);
1721 if (!empty($CFG->doctonewwindow) || $forcepopup) {
1722 $attributes['class'] = 'helplinkpopup';
1725 return html_writer::tag('a', $icon.$text, $attributes);
1729 * Return HTML for a pix_icon.
1731 * @param string $pix short pix name
1732 * @param string $alt mandatory alt attribute
1733 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1734 * @param array $attributes htm lattributes
1735 * @return string HTML fragment
1737 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1738 $icon = new pix_icon($pix, $alt, $component, $attributes);
1739 return $this->render($icon);
1743 * Renders a pix_icon widget and returns the HTML to display it.
1745 * @param pix_icon $icon
1746 * @return string HTML fragment
1748 protected function render_pix_icon(pix_icon $icon) {
1749 $attributes = $icon->attributes;
1750 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1751 return html_writer::empty_tag('img', $attributes);
1755 * Return HTML to display an emoticon icon.
1757 * @param pix_emoticon $emoticon
1758 * @return string HTML fragment
1760 protected function render_pix_emoticon(pix_emoticon $emoticon) {
1761 $attributes = $emoticon->attributes;
1762 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
1763 return html_writer::empty_tag('img', $attributes);
1767 * Produces the html that represents this rating in the UI
1769 * @param rating $rating the page object on which this rating will appear
1770 * @return string
1772 function render_rating(rating $rating) {
1773 global $CFG, $USER;
1775 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
1776 return null;//ratings are turned off
1779 $ratingmanager = new rating_manager();
1780 // Initialise the JavaScript so ratings can be done by AJAX.
1781 $ratingmanager->initialise_rating_javascript($this->page);
1783 $strrate = get_string("rate", "rating");
1784 $ratinghtml = ''; //the string we'll return
1786 // permissions check - can they view the aggregate?
1787 if ($rating->user_can_view_aggregate()) {
1789 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
1790 $aggregatestr = $rating->get_aggregate_string();
1792 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
1793 if ($rating->count > 0) {
1794 $countstr = "({$rating->count})";
1795 } else {
1796 $countstr = '-';
1798 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
1800 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
1801 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
1803 $nonpopuplink = $rating->get_view_ratings_url();
1804 $popuplink = $rating->get_view_ratings_url(true);
1806 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
1807 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
1808 } else {
1809 $ratinghtml .= $aggregatehtml;
1813 $formstart = null;
1814 // if the item doesn't belong to the current user, the user has permission to rate
1815 // and we're within the assessable period
1816 if ($rating->user_can_rate()) {
1818 $rateurl = $rating->get_rate_url();
1819 $inputs = $rateurl->params();
1821 //start the rating form
1822 $formattrs = array(
1823 'id' => "postrating{$rating->itemid}",
1824 'class' => 'postratingform',
1825 'method' => 'post',
1826 'action' => $rateurl->out_omit_querystring()
1828 $formstart = html_writer::start_tag('form', $formattrs);
1829 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
1831 // add the hidden inputs
1832 foreach ($inputs as $name => $value) {
1833 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
1834 $formstart .= html_writer::empty_tag('input', $attributes);
1837 if (empty($ratinghtml)) {
1838 $ratinghtml .= $strrate.': ';
1840 $ratinghtml = $formstart.$ratinghtml;
1842 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
1843 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
1844 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
1845 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
1847 //output submit button
1848 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
1850 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
1851 $ratinghtml .= html_writer::empty_tag('input', $attributes);
1853 if (!$rating->settings->scale->isnumeric) {
1854 // If a global scale, try to find current course ID from the context
1855 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
1856 $courseid = $coursecontext->instanceid;
1857 } else {
1858 $courseid = $rating->settings->scale->courseid;
1860 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
1862 $ratinghtml .= html_writer::end_tag('span');
1863 $ratinghtml .= html_writer::end_tag('div');
1864 $ratinghtml .= html_writer::end_tag('form');
1867 return $ratinghtml;
1871 * Centered heading with attached help button (same title text)
1872 * and optional icon attached.
1874 * @param string $text A heading text
1875 * @param string $helpidentifier The keyword that defines a help page
1876 * @param string $component component name
1877 * @param string|moodle_url $icon
1878 * @param string $iconalt icon alt text
1879 * @return string HTML fragment
1881 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '') {
1882 $image = '';
1883 if ($icon) {
1884 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
1887 $help = '';
1888 if ($helpidentifier) {
1889 $help = $this->help_icon($helpidentifier, $component);
1892 return $this->heading($image.$text.$help, 2, 'main help');
1896 * Returns HTML to display a help icon.
1898 * @deprecated since Moodle 2.0
1900 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
1901 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
1905 * Returns HTML to display a help icon.
1907 * @param string $identifier The keyword that defines a help page
1908 * @param string $component component name
1909 * @param string|bool $linktext true means use $title as link text, string means link text value
1910 * @return string HTML fragment
1912 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
1913 $icon = new help_icon($identifier, $component);
1914 $icon->diag_strings();
1915 if ($linktext === true) {
1916 $icon->linktext = get_string($icon->identifier, $icon->component);
1917 } else if (!empty($linktext)) {
1918 $icon->linktext = $linktext;
1920 return $this->render($icon);
1924 * Implementation of user image rendering.
1926 * @param help_icon $helpicon A help icon instance
1927 * @return string HTML fragment
1929 protected function render_help_icon(help_icon $helpicon) {
1930 global $CFG;
1932 // first get the help image icon
1933 $src = $this->pix_url('help');
1935 $title = get_string($helpicon->identifier, $helpicon->component);
1937 if (empty($helpicon->linktext)) {
1938 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
1939 } else {
1940 $alt = get_string('helpwiththis');
1943 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1944 $output = html_writer::empty_tag('img', $attributes);
1946 // add the link text if given
1947 if (!empty($helpicon->linktext)) {
1948 // the spacing has to be done through CSS
1949 $output .= $helpicon->linktext;
1952 // now create the link around it - we need https on loginhttps pages
1953 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
1955 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1956 $title = get_string('helpprefix2', '', trim($title, ". \t"));
1958 $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true');
1959 $output = html_writer::tag('a', $output, $attributes);
1961 // and finally span
1962 return html_writer::tag('span', $output, array('class' => 'helptooltip'));
1966 * Returns HTML to display a scale help icon.
1968 * @param int $courseid
1969 * @param stdClass $scale instance
1970 * @return string HTML fragment
1972 public function help_icon_scale($courseid, stdClass $scale) {
1973 global $CFG;
1975 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
1977 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
1979 $scaleid = abs($scale->id);
1981 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
1982 $action = new popup_action('click', $link, 'ratingscale');
1984 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
1988 * Creates and returns a spacer image with optional line break.
1990 * @param array $attributes Any HTML attributes to add to the spaced.
1991 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
1992 * laxy do it with CSS which is a much better solution.
1993 * @return string HTML fragment
1995 public function spacer(array $attributes = null, $br = false) {
1996 $attributes = (array)$attributes;
1997 if (empty($attributes['width'])) {
1998 $attributes['width'] = 1;
2000 if (empty($attributes['height'])) {
2001 $attributes['height'] = 1;
2003 $attributes['class'] = 'spacer';
2005 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2007 if (!empty($br)) {
2008 $output .= '<br />';
2011 return $output;
2015 * Returns HTML to display the specified user's avatar.
2017 * User avatar may be obtained in two ways:
2018 * <pre>
2019 * // Option 1: (shortcut for simple cases, preferred way)
2020 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2021 * $OUTPUT->user_picture($user, array('popup'=>true));
2023 * // Option 2:
2024 * $userpic = new user_picture($user);
2025 * // Set properties of $userpic
2026 * $userpic->popup = true;
2027 * $OUTPUT->render($userpic);
2028 * </pre>
2030 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2031 * If any of these are missing, the database is queried. Avoid this
2032 * if at all possible, particularly for reports. It is very bad for performance.
2033 * @param array $options associative array with user picture options, used only if not a user_picture object,
2034 * options are:
2035 * - courseid=$this->page->course->id (course id of user profile in link)
2036 * - size=35 (size of image)
2037 * - link=true (make image clickable - the link leads to user profile)
2038 * - popup=false (open in popup)
2039 * - alttext=true (add image alt attribute)
2040 * - class = image class attribute (default 'userpicture')
2041 * @return string HTML fragment
2043 public function user_picture(stdClass $user, array $options = null) {
2044 $userpicture = new user_picture($user);
2045 foreach ((array)$options as $key=>$value) {
2046 if (array_key_exists($key, $userpicture)) {
2047 $userpicture->$key = $value;
2050 return $this->render($userpicture);
2054 * Internal implementation of user image rendering.
2056 * @param user_picture $userpicture
2057 * @return string
2059 protected function render_user_picture(user_picture $userpicture) {
2060 global $CFG, $DB;
2062 $user = $userpicture->user;
2064 if ($userpicture->alttext) {
2065 if (!empty($user->imagealt)) {
2066 $alt = $user->imagealt;
2067 } else {
2068 $alt = get_string('pictureof', '', fullname($user));
2070 } else {
2071 $alt = '';
2074 if (empty($userpicture->size)) {
2075 $size = 35;
2076 } else if ($userpicture->size === true or $userpicture->size == 1) {
2077 $size = 100;
2078 } else {
2079 $size = $userpicture->size;
2082 $class = $userpicture->class;
2084 if ($user->picture == 0) {
2085 $class .= ' defaultuserpic';
2088 $src = $userpicture->get_url($this->page, $this);
2090 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2092 // get the image html output fisrt
2093 $output = html_writer::empty_tag('img', $attributes);
2095 // then wrap it in link if needed
2096 if (!$userpicture->link) {
2097 return $output;
2100 if (empty($userpicture->courseid)) {
2101 $courseid = $this->page->course->id;
2102 } else {
2103 $courseid = $userpicture->courseid;
2106 if ($courseid == SITEID) {
2107 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2108 } else {
2109 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2112 $attributes = array('href'=>$url);
2114 if ($userpicture->popup) {
2115 $id = html_writer::random_id('userpicture');
2116 $attributes['id'] = $id;
2117 $this->add_action_handler(new popup_action('click', $url), $id);
2120 return html_writer::tag('a', $output, $attributes);
2124 * Internal implementation of file tree viewer items rendering.
2126 * @param array $dir
2127 * @return string
2129 public function htmllize_file_tree($dir) {
2130 if (empty($dir['subdirs']) and empty($dir['files'])) {
2131 return '';
2133 $result = '<ul>';
2134 foreach ($dir['subdirs'] as $subdir) {
2135 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2137 foreach ($dir['files'] as $file) {
2138 $filename = $file->get_filename();
2139 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2141 $result .= '</ul>';
2143 return $result;
2147 * Returns HTML to display the file picker
2149 * <pre>
2150 * $OUTPUT->file_picker($options);
2151 * </pre>
2153 * @param array $options associative array with file manager options
2154 * options are:
2155 * maxbytes=>-1,
2156 * itemid=>0,
2157 * client_id=>uniqid(),
2158 * acepted_types=>'*',
2159 * return_types=>FILE_INTERNAL,
2160 * context=>$PAGE->context
2161 * @return string HTML fragment
2163 public function file_picker($options) {
2164 $fp = new file_picker($options);
2165 return $this->render($fp);
2169 * Internal implementation of file picker rendering.
2171 * @param file_picker $fp
2172 * @return string
2174 public function render_file_picker(file_picker $fp) {
2175 global $CFG, $OUTPUT, $USER;
2176 $options = $fp->options;
2177 $client_id = $options->client_id;
2178 $strsaved = get_string('filesaved', 'repository');
2179 $straddfile = get_string('openpicker', 'repository');
2180 $strloading = get_string('loading', 'repository');
2181 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2182 $strdroptoupload = get_string('droptoupload', 'moodle');
2183 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2185 $currentfile = $options->currentfile;
2186 if (empty($currentfile)) {
2187 $currentfile = '';
2188 } else {
2189 $currentfile .= ' - ';
2191 if ($options->maxbytes) {
2192 $size = $options->maxbytes;
2193 } else {
2194 $size = get_max_upload_file_size();
2196 if ($size == -1) {
2197 $maxsize = '';
2198 } else {
2199 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2201 if ($options->buttonname) {
2202 $buttonname = ' name="' . $options->buttonname . '"';
2203 } else {
2204 $buttonname = '';
2206 $html = <<<EOD
2207 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2208 $icon_progress
2209 </div>
2210 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2211 <div>
2212 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2213 <span> $maxsize </span>
2214 </div>
2215 EOD;
2216 if ($options->env != 'url') {
2217 $html .= <<<EOD
2218 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2219 <div class="filepicker-filename">
2220 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2221 <div class="dndupload-progressbars"></div>
2222 </div>
2223 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2224 </div>
2225 EOD;
2227 $html .= '</div>';
2228 return $html;
2232 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2234 * @param string $cmid the course_module id.
2235 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2236 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2238 public function update_module_button($cmid, $modulename) {
2239 global $CFG;
2240 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2241 $modulename = get_string('modulename', $modulename);
2242 $string = get_string('updatethis', '', $modulename);
2243 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2244 return $this->single_button($url, $string);
2245 } else {
2246 return '';
2251 * Returns HTML to display a "Turn editing on/off" button in a form.
2253 * @param moodle_url $url The URL + params to send through when clicking the button
2254 * @return string HTML the button
2256 public function edit_button(moodle_url $url) {
2258 $url->param('sesskey', sesskey());
2259 if ($this->page->user_is_editing()) {
2260 $url->param('edit', 'off');
2261 $editstring = get_string('turneditingoff');
2262 } else {
2263 $url->param('edit', 'on');
2264 $editstring = get_string('turneditingon');
2267 return $this->single_button($url, $editstring);
2271 * Returns HTML to display a simple button to close a window
2273 * @param string $text The lang string for the button's label (already output from get_string())
2274 * @return string html fragment
2276 public function close_window_button($text='') {
2277 if (empty($text)) {
2278 $text = get_string('closewindow');
2280 $button = new single_button(new moodle_url('#'), $text, 'get');
2281 $button->add_action(new component_action('click', 'close_window'));
2283 return $this->container($this->render($button), 'closewindow');
2287 * Output an error message. By default wraps the error message in <span class="error">.
2288 * If the error message is blank, nothing is output.
2290 * @param string $message the error message.
2291 * @return string the HTML to output.
2293 public function error_text($message) {
2294 if (empty($message)) {
2295 return '';
2297 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2298 return html_writer::tag('span', $message, array('class' => 'error'));
2302 * Do not call this function directly.
2304 * To terminate the current script with a fatal error, call the {@link print_error}
2305 * function, or throw an exception. Doing either of those things will then call this
2306 * function to display the error, before terminating the execution.
2308 * @param string $message The message to output
2309 * @param string $moreinfourl URL where more info can be found about the error
2310 * @param string $link Link for the Continue button
2311 * @param array $backtrace The execution backtrace
2312 * @param string $debuginfo Debugging information
2313 * @return string the HTML to output.
2315 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2316 global $CFG;
2318 $output = '';
2319 $obbuffer = '';
2321 if ($this->has_started()) {
2322 // we can not always recover properly here, we have problems with output buffering,
2323 // html tables, etc.
2324 $output .= $this->opencontainers->pop_all_but_last();
2326 } else {
2327 // It is really bad if library code throws exception when output buffering is on,
2328 // because the buffered text would be printed before our start of page.
2329 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2330 error_reporting(0); // disable notices from gzip compression, etc.
2331 while (ob_get_level() > 0) {
2332 $buff = ob_get_clean();
2333 if ($buff === false) {
2334 break;
2336 $obbuffer .= $buff;
2338 error_reporting($CFG->debug);
2340 // Header not yet printed
2341 if (isset($_SERVER['SERVER_PROTOCOL'])) {
2342 // server protocol should be always present, because this render
2343 // can not be used from command line or when outputting custom XML
2344 @header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
2346 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2347 $this->page->set_url('/'); // no url
2348 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2349 $this->page->set_title(get_string('error'));
2350 $this->page->set_heading($this->page->course->fullname);
2351 $output .= $this->header();
2354 $message = '<p class="errormessage">' . $message . '</p>'.
2355 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2356 get_string('moreinformation') . '</a></p>';
2357 if (empty($CFG->rolesactive)) {
2358 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2359 //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.
2361 $output .= $this->box($message, 'errorbox');
2363 if (debugging('', DEBUG_DEVELOPER)) {
2364 if (!empty($debuginfo)) {
2365 $debuginfo = s($debuginfo); // removes all nasty JS
2366 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2367 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2369 if (!empty($backtrace)) {
2370 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2372 if ($obbuffer !== '' ) {
2373 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2377 if (empty($CFG->rolesactive)) {
2378 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2379 } else if (!empty($link)) {
2380 $output .= $this->continue_button($link);
2383 $output .= $this->footer();
2385 // Padding to encourage IE to display our error page, rather than its own.
2386 $output .= str_repeat(' ', 512);
2388 return $output;
2392 * Output a notification (that is, a status message about something that has
2393 * just happened).
2395 * @param string $message the message to print out
2396 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2397 * @return string the HTML to output.
2399 public function notification($message, $classes = 'notifyproblem') {
2400 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2404 * Returns HTML to display a continue button that goes to a particular URL.
2406 * @param string|moodle_url $url The url the button goes to.
2407 * @return string the HTML to output.
2409 public function continue_button($url) {
2410 if (!($url instanceof moodle_url)) {
2411 $url = new moodle_url($url);
2413 $button = new single_button($url, get_string('continue'), 'get');
2414 $button->class = 'continuebutton';
2416 return $this->render($button);
2420 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2422 * @param int $totalcount The total number of entries available to be paged through
2423 * @param int $page The page you are currently viewing
2424 * @param int $perpage The number of entries that should be shown per page
2425 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2426 * @param string $pagevar name of page parameter that holds the page number
2427 * @return string the HTML to output.
2429 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2430 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2431 return $this->render($pb);
2435 * Internal implementation of paging bar rendering.
2437 * @param paging_bar $pagingbar
2438 * @return string
2440 protected function render_paging_bar(paging_bar $pagingbar) {
2441 $output = '';
2442 $pagingbar = clone($pagingbar);
2443 $pagingbar->prepare($this, $this->page, $this->target);
2445 if ($pagingbar->totalcount > $pagingbar->perpage) {
2446 $output .= get_string('page') . ':';
2448 if (!empty($pagingbar->previouslink)) {
2449 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
2452 if (!empty($pagingbar->firstlink)) {
2453 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
2456 foreach ($pagingbar->pagelinks as $link) {
2457 $output .= "&#160;&#160;$link";
2460 if (!empty($pagingbar->lastlink)) {
2461 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
2464 if (!empty($pagingbar->nextlink)) {
2465 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
2469 return html_writer::tag('div', $output, array('class' => 'paging'));
2473 * Output the place a skip link goes to.
2475 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2476 * @return string the HTML to output.
2478 public function skip_link_target($id = null) {
2479 return html_writer::tag('span', '', array('id' => $id));
2483 * Outputs a heading
2485 * @param string $text The text of the heading
2486 * @param int $level The level of importance of the heading. Defaulting to 2
2487 * @param string $classes A space-separated list of CSS classes
2488 * @param string $id An optional ID
2489 * @return string the HTML to output.
2491 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2492 $level = (integer) $level;
2493 if ($level < 1 or $level > 6) {
2494 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2496 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2500 * Outputs a box.
2502 * @param string $contents The contents of the box
2503 * @param string $classes A space-separated list of CSS classes
2504 * @param string $id An optional ID
2505 * @return string the HTML to output.
2507 public function box($contents, $classes = 'generalbox', $id = null) {
2508 return $this->box_start($classes, $id) . $contents . $this->box_end();
2512 * Outputs the opening section of a box.
2514 * @param string $classes A space-separated list of CSS classes
2515 * @param string $id An optional ID
2516 * @return string the HTML to output.
2518 public function box_start($classes = 'generalbox', $id = null) {
2519 $this->opencontainers->push('box', html_writer::end_tag('div'));
2520 return html_writer::start_tag('div', array('id' => $id,
2521 'class' => 'box ' . renderer_base::prepare_classes($classes)));
2525 * Outputs the closing section of a box.
2527 * @return string the HTML to output.
2529 public function box_end() {
2530 return $this->opencontainers->pop('box');
2534 * Outputs a container.
2536 * @param string $contents The contents of the box
2537 * @param string $classes A space-separated list of CSS classes
2538 * @param string $id An optional ID
2539 * @return string the HTML to output.
2541 public function container($contents, $classes = null, $id = null) {
2542 return $this->container_start($classes, $id) . $contents . $this->container_end();
2546 * Outputs the opening section of a container.
2548 * @param string $classes A space-separated list of CSS classes
2549 * @param string $id An optional ID
2550 * @return string the HTML to output.
2552 public function container_start($classes = null, $id = null) {
2553 $this->opencontainers->push('container', html_writer::end_tag('div'));
2554 return html_writer::start_tag('div', array('id' => $id,
2555 'class' => renderer_base::prepare_classes($classes)));
2559 * Outputs the closing section of a container.
2561 * @return string the HTML to output.
2563 public function container_end() {
2564 return $this->opencontainers->pop('container');
2568 * Make nested HTML lists out of the items
2570 * The resulting list will look something like this:
2572 * <pre>
2573 * <<ul>>
2574 * <<li>><div class='tree_item parent'>(item contents)</div>
2575 * <<ul>
2576 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2577 * <</ul>>
2578 * <</li>>
2579 * <</ul>>
2580 * </pre>
2582 * @param array $items
2583 * @param array $attrs html attributes passed to the top ofs the list
2584 * @return string HTML
2586 public function tree_block_contents($items, $attrs = array()) {
2587 // exit if empty, we don't want an empty ul element
2588 if (empty($items)) {
2589 return '';
2591 // array of nested li elements
2592 $lis = array();
2593 foreach ($items as $item) {
2594 // this applies to the li item which contains all child lists too
2595 $content = $item->content($this);
2596 $liclasses = array($item->get_css_type());
2597 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2598 $liclasses[] = 'collapsed';
2600 if ($item->isactive === true) {
2601 $liclasses[] = 'current_branch';
2603 $liattr = array('class'=>join(' ',$liclasses));
2604 // class attribute on the div item which only contains the item content
2605 $divclasses = array('tree_item');
2606 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2607 $divclasses[] = 'branch';
2608 } else {
2609 $divclasses[] = 'leaf';
2611 if (!empty($item->classes) && count($item->classes)>0) {
2612 $divclasses[] = join(' ', $item->classes);
2614 $divattr = array('class'=>join(' ', $divclasses));
2615 if (!empty($item->id)) {
2616 $divattr['id'] = $item->id;
2618 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2619 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2620 $content = html_writer::empty_tag('hr') . $content;
2622 $content = html_writer::tag('li', $content, $liattr);
2623 $lis[] = $content;
2625 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2629 * Return the navbar content so that it can be echoed out by the layout
2631 * @return string XHTML navbar
2633 public function navbar() {
2634 $items = $this->page->navbar->get_items();
2636 $htmlblocks = array();
2637 // Iterate the navarray and display each node
2638 $itemcount = count($items);
2639 $separator = get_separator();
2640 for ($i=0;$i < $itemcount;$i++) {
2641 $item = $items[$i];
2642 $item->hideicon = true;
2643 if ($i===0) {
2644 $content = html_writer::tag('li', $this->render($item));
2645 } else {
2646 $content = html_writer::tag('li', $separator.$this->render($item));
2648 $htmlblocks[] = $content;
2651 //accessibility: heading for navbar list (MDL-20446)
2652 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2653 $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks), array('role'=>'navigation'));
2654 // XHTML
2655 return $navbarcontent;
2659 * Renders a navigation node object.
2661 * @param navigation_node $item The navigation node to render.
2662 * @return string HTML fragment
2664 protected function render_navigation_node(navigation_node $item) {
2665 $content = $item->get_content();
2666 $title = $item->get_title();
2667 if ($item->icon instanceof renderable && !$item->hideicon) {
2668 $icon = $this->render($item->icon);
2669 $content = $icon.$content; // use CSS for spacing of icons
2671 if ($item->helpbutton !== null) {
2672 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2674 if ($content === '') {
2675 return '';
2677 if ($item->action instanceof action_link) {
2678 $link = $item->action;
2679 if ($item->hidden) {
2680 $link->add_class('dimmed');
2682 if (!empty($content)) {
2683 // Providing there is content we will use that for the link content.
2684 $link->text = $content;
2686 $content = $this->render($link);
2687 } else if ($item->action instanceof moodle_url) {
2688 $attributes = array();
2689 if ($title !== '') {
2690 $attributes['title'] = $title;
2692 if ($item->hidden) {
2693 $attributes['class'] = 'dimmed_text';
2695 $content = html_writer::link($item->action, $content, $attributes);
2697 } else if (is_string($item->action) || empty($item->action)) {
2698 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2699 if ($title !== '') {
2700 $attributes['title'] = $title;
2702 if ($item->hidden) {
2703 $attributes['class'] = 'dimmed_text';
2705 $content = html_writer::tag('span', $content, $attributes);
2707 return $content;
2711 * Accessibility: Right arrow-like character is
2712 * used in the breadcrumb trail, course navigation menu
2713 * (previous/next activity), calendar, and search forum block.
2714 * If the theme does not set characters, appropriate defaults
2715 * are set automatically. Please DO NOT
2716 * use &lt; &gt; &raquo; - these are confusing for blind users.
2718 * @return string
2720 public function rarrow() {
2721 return $this->page->theme->rarrow;
2725 * Accessibility: Right arrow-like character is
2726 * used in the breadcrumb trail, course navigation menu
2727 * (previous/next activity), calendar, and search forum block.
2728 * If the theme does not set characters, appropriate defaults
2729 * are set automatically. Please DO NOT
2730 * use &lt; &gt; &raquo; - these are confusing for blind users.
2732 * @return string
2734 public function larrow() {
2735 return $this->page->theme->larrow;
2739 * Returns the custom menu if one has been set
2741 * A custom menu can be configured by browsing to
2742 * Settings: Administration > Appearance > Themes > Theme settings
2743 * and then configuring the custommenu config setting as described.
2745 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
2746 * @return string
2748 public function custom_menu($custommenuitems = '') {
2749 global $CFG;
2750 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
2751 $custommenuitems = $CFG->custommenuitems;
2753 if (empty($custommenuitems)) {
2754 return '';
2756 $custommenu = new custom_menu($custommenuitems, current_language());
2757 return $this->render_custom_menu($custommenu);
2761 * Renders a custom menu object (located in outputcomponents.php)
2763 * The custom menu this method produces makes use of the YUI3 menunav widget
2764 * and requires very specific html elements and classes.
2766 * @staticvar int $menucount
2767 * @param custom_menu $menu
2768 * @return string
2770 protected function render_custom_menu(custom_menu $menu) {
2771 static $menucount = 0;
2772 // If the menu has no children return an empty string
2773 if (!$menu->has_children()) {
2774 return '';
2776 // Increment the menu count. This is used for ID's that get worked with
2777 // in JavaScript as is essential
2778 $menucount++;
2779 // Initialise this custom menu (the custom menu object is contained in javascript-static
2780 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
2781 $jscode = "(function(){{$jscode}})";
2782 $this->page->requires->yui_module('node-menunav', $jscode);
2783 // Build the root nodes as required by YUI
2784 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled'));
2785 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2786 $content .= html_writer::start_tag('ul');
2787 // Render each child
2788 foreach ($menu->get_children() as $item) {
2789 $content .= $this->render_custom_menu_item($item);
2791 // Close the open tags
2792 $content .= html_writer::end_tag('ul');
2793 $content .= html_writer::end_tag('div');
2794 $content .= html_writer::end_tag('div');
2795 // Return the custom menu
2796 return $content;
2800 * Renders a custom menu node as part of a submenu
2802 * The custom menu this method produces makes use of the YUI3 menunav widget
2803 * and requires very specific html elements and classes.
2805 * @see core:renderer::render_custom_menu()
2807 * @staticvar int $submenucount
2808 * @param custom_menu_item $menunode
2809 * @return string
2811 protected function render_custom_menu_item(custom_menu_item $menunode) {
2812 // Required to ensure we get unique trackable id's
2813 static $submenucount = 0;
2814 if ($menunode->has_children()) {
2815 // If the child has menus render it as a sub menu
2816 $submenucount++;
2817 $content = html_writer::start_tag('li');
2818 if ($menunode->get_url() !== null) {
2819 $url = $menunode->get_url();
2820 } else {
2821 $url = '#cm_submenu_'.$submenucount;
2823 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
2824 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
2825 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2826 $content .= html_writer::start_tag('ul');
2827 foreach ($menunode->get_children() as $menunode) {
2828 $content .= $this->render_custom_menu_item($menunode);
2830 $content .= html_writer::end_tag('ul');
2831 $content .= html_writer::end_tag('div');
2832 $content .= html_writer::end_tag('div');
2833 $content .= html_writer::end_tag('li');
2834 } else {
2835 // The node doesn't have children so produce a final menuitem
2836 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
2837 if ($menunode->get_url() !== null) {
2838 $url = $menunode->get_url();
2839 } else {
2840 $url = '#';
2842 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
2843 $content .= html_writer::end_tag('li');
2845 // Return the sub menu
2846 return $content;
2850 * Renders theme links for switching between default and other themes.
2852 * @return string
2854 protected function theme_switch_links() {
2856 $actualdevice = get_device_type();
2857 $currentdevice = $this->page->devicetypeinuse;
2858 $switched = ($actualdevice != $currentdevice);
2860 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
2861 // The user is using the a default device and hasn't switched so don't shown the switch
2862 // device links.
2863 return '';
2866 if ($switched) {
2867 $linktext = get_string('switchdevicerecommended');
2868 $devicetype = $actualdevice;
2869 } else {
2870 $linktext = get_string('switchdevicedefault');
2871 $devicetype = 'default';
2873 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
2875 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
2876 $content .= html_writer::link($linkurl, $linktext);
2877 $content .= html_writer::end_tag('div');
2879 return $content;
2884 * A renderer that generates output for command-line scripts.
2886 * The implementation of this renderer is probably incomplete.
2888 * @copyright 2009 Tim Hunt
2889 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2890 * @since Moodle 2.0
2891 * @package core
2892 * @category output
2894 class core_renderer_cli extends core_renderer {
2897 * Returns the page header.
2899 * @return string HTML fragment
2901 public function header() {
2902 return $this->page->heading . "\n";
2906 * Returns a template fragment representing a Heading.
2908 * @param string $text The text of the heading
2909 * @param int $level The level of importance of the heading
2910 * @param string $classes A space-separated list of CSS classes
2911 * @param string $id An optional ID
2912 * @return string A template fragment for a heading
2914 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2915 $text .= "\n";
2916 switch ($level) {
2917 case 1:
2918 return '=>' . $text;
2919 case 2:
2920 return '-->' . $text;
2921 default:
2922 return $text;
2927 * Returns a template fragment representing a fatal error.
2929 * @param string $message The message to output
2930 * @param string $moreinfourl URL where more info can be found about the error
2931 * @param string $link Link for the Continue button
2932 * @param array $backtrace The execution backtrace
2933 * @param string $debuginfo Debugging information
2934 * @return string A template fragment for a fatal error
2936 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2937 $output = "!!! $message !!!\n";
2939 if (debugging('', DEBUG_DEVELOPER)) {
2940 if (!empty($debuginfo)) {
2941 $output .= $this->notification($debuginfo, 'notifytiny');
2943 if (!empty($backtrace)) {
2944 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
2948 return $output;
2952 * Returns a template fragment representing a notification.
2954 * @param string $message The message to include
2955 * @param string $classes A space-separated list of CSS classes
2956 * @return string A template fragment for a notification
2958 public function notification($message, $classes = 'notifyproblem') {
2959 $message = clean_text($message);
2960 if ($classes === 'notifysuccess') {
2961 return "++ $message ++\n";
2963 return "!! $message !!\n";
2969 * A renderer that generates output for ajax scripts.
2971 * This renderer prevents accidental sends back only json
2972 * encoded error messages, all other output is ignored.
2974 * @copyright 2010 Petr Skoda
2975 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2976 * @since Moodle 2.0
2977 * @package core
2978 * @category output
2980 class core_renderer_ajax extends core_renderer {
2983 * Returns a template fragment representing a fatal error.
2985 * @param string $message The message to output
2986 * @param string $moreinfourl URL where more info can be found about the error
2987 * @param string $link Link for the Continue button
2988 * @param array $backtrace The execution backtrace
2989 * @param string $debuginfo Debugging information
2990 * @return string A template fragment for a fatal error
2992 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2993 global $CFG;
2995 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2997 $e = new stdClass();
2998 $e->error = $message;
2999 $e->stacktrace = NULL;
3000 $e->debuginfo = NULL;
3001 $e->reproductionlink = NULL;
3002 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
3003 $e->reproductionlink = $link;
3004 if (!empty($debuginfo)) {
3005 $e->debuginfo = $debuginfo;
3007 if (!empty($backtrace)) {
3008 $e->stacktrace = format_backtrace($backtrace, true);
3011 $this->header();
3012 return json_encode($e);
3016 * Used to display a notification.
3017 * For the AJAX notifications are discarded.
3019 * @param string $message
3020 * @param string $classes
3022 public function notification($message, $classes = 'notifyproblem') {}
3025 * Used to display a redirection message.
3026 * AJAX redirections should not occur and as such redirection messages
3027 * are discarded.
3029 * @param moodle_url|string $encodedurl
3030 * @param string $message
3031 * @param int $delay
3032 * @param bool $debugdisableredirect
3034 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
3037 * Prepares the start of an AJAX output.
3039 public function header() {
3040 // unfortunately YUI iframe upload does not support application/json
3041 if (!empty($_FILES)) {
3042 @header('Content-type: text/plain; charset=utf-8');
3043 } else {
3044 @header('Content-type: application/json; charset=utf-8');
3047 // Headers to make it not cacheable and json
3048 @header('Cache-Control: no-store, no-cache, must-revalidate');
3049 @header('Cache-Control: post-check=0, pre-check=0', false);
3050 @header('Pragma: no-cache');
3051 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
3052 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
3053 @header('Accept-Ranges: none');
3057 * There is no footer for an AJAX request, however we must override the
3058 * footer method to prevent the default footer.
3060 public function footer() {}
3063 * No need for headers in an AJAX request... this should never happen.
3064 * @param string $text
3065 * @param int $level
3066 * @param string $classes
3067 * @param string $id
3069 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
3074 * Renderer for media files.
3076 * Used in file resources, media filter, and any other places that need to
3077 * output embedded media.
3079 * @copyright 2011 The Open University
3080 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3082 class core_media_renderer extends plugin_renderer_base {
3083 /** @var array Array of available 'player' objects */
3084 private $players;
3085 /** @var string Regex pattern for links which may contain embeddable content */
3086 private $embeddablemarkers;
3089 * Constructor requires medialib.php.
3091 * This is needed in the constructor (not later) so that you can use the
3092 * constants and static functions that are defined in core_media class
3093 * before you call renderer functions.
3095 public function __construct() {
3096 global $CFG;
3097 require_once($CFG->libdir . '/medialib.php');
3101 * Obtains the list of core_media_player objects currently in use to render
3102 * items.
3104 * The list is in rank order (highest first) and does not include players
3105 * which are disabled.
3107 * @return array Array of core_media_player objects in rank order
3109 protected function get_players() {
3110 global $CFG;
3112 // Save time by only building the list once.
3113 if (!$this->players) {
3114 // Get raw list of players.
3115 $players = $this->get_players_raw();
3117 // Chuck all the ones that are disabled.
3118 foreach ($players as $key => $player) {
3119 if (!$player->is_enabled()) {
3120 unset($players[$key]);
3124 // Sort in rank order (highest first).
3125 usort($players, array('core_media_player', 'compare_by_rank'));
3126 $this->players = $players;
3128 return $this->players;
3132 * Obtains a raw list of player objects that includes objects regardless
3133 * of whether they are disabled or not, and without sorting.
3135 * You can override this in a subclass if you need to add additional
3136 * players.
3138 * The return array is be indexed by player name to make it easier to
3139 * remove players in a subclass.
3141 * @return array $players Array of core_media_player objects in any order
3143 protected function get_players_raw() {
3144 return array(
3145 'vimeo' => new core_media_player_vimeo(),
3146 'youtube' => new core_media_player_youtube(),
3147 'youtube_playlist' => new core_media_player_youtube_playlist(),
3148 'html5video' => new core_media_player_html5video(),
3149 'html5audio' => new core_media_player_html5audio(),
3150 'mp3' => new core_media_player_mp3(),
3151 'flv' => new core_media_player_flv(),
3152 'wmp' => new core_media_player_wmp(),
3153 'qt' => new core_media_player_qt(),
3154 'rm' => new core_media_player_rm(),
3155 'swf' => new core_media_player_swf(),
3156 'link' => new core_media_player_link(),
3161 * Renders a media file (audio or video) using suitable embedded player.
3163 * See embed_alternatives function for full description of parameters.
3164 * This function calls through to that one.
3166 * When using this function you can also specify width and height in the
3167 * URL by including ?d=100x100 at the end. If specified in the URL, this
3168 * will override the $width and $height parameters.
3170 * @param moodle_url $url Full URL of media file
3171 * @param string $name Optional user-readable name to display in download link
3172 * @param int $width Width in pixels (optional)
3173 * @param int $height Height in pixels (optional)
3174 * @param array $options Array of key/value pairs
3175 * @return string HTML content of embed
3177 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
3178 $options = array()) {
3180 // Get width and height from URL if specified (overrides parameters in
3181 // function call).
3182 $rawurl = $url->out(false);
3183 if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
3184 $width = $matches[1];
3185 $height = $matches[2];
3186 $url = new moodle_url(str_replace($matches[0], '', $rawurl));
3189 // Defer to array version of function.
3190 return $this->embed_alternatives(array($url), $name, $width, $height, $options);
3194 * Renders media files (audio or video) using suitable embedded player.
3195 * The list of URLs should be alternative versions of the same content in
3196 * multiple formats. If there is only one format it should have a single
3197 * entry.
3199 * If the media files are not in a supported format, this will give students
3200 * a download link to each format. The download link uses the filename
3201 * unless you supply the optional name parameter.
3203 * Width and height are optional. If specified, these are suggested sizes
3204 * and should be the exact values supplied by the user, if they come from
3205 * user input. These will be treated as relating to the size of the video
3206 * content, not including any player control bar.
3208 * For audio files, height will be ignored. For video files, a few formats
3209 * work if you specify only width, but in general if you specify width
3210 * you must specify height as well.
3212 * The $options array is passed through to the core_media_player classes
3213 * that render the object tag. The keys can contain values from
3214 * core_media::OPTION_xx.
3216 * @param array $alternatives Array of moodle_url to media files
3217 * @param string $name Optional user-readable name to display in download link
3218 * @param int $width Width in pixels (optional)
3219 * @param int $height Height in pixels (optional)
3220 * @param array $options Array of key/value pairs
3221 * @return string HTML content of embed
3223 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
3224 $options = array()) {
3226 // Get list of player plugins (will also require the library).
3227 $players = $this->get_players();
3229 // Set up initial text which will be replaced by first player that
3230 // supports any of the formats.
3231 $out = core_media_player::PLACEHOLDER;
3233 // Loop through all players that support any of these URLs.
3234 foreach ($players as $player) {
3235 // Option: When no other player matched, don't do the default link player.
3236 if (!empty($options[core_media::OPTION_FALLBACK_TO_BLANK]) &&
3237 $player->get_rank() === 0 && $out === core_media_player::PLACEHOLDER) {
3238 continue;
3241 $supported = $player->list_supported_urls($alternatives, $options);
3242 if ($supported) {
3243 // Embed.
3244 $text = $player->embed($supported, $name, $width, $height, $options);
3246 // Put this in place of the 'fallback' slot in the previous text.
3247 $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
3251 // Remove 'fallback' slot from final version and return it.
3252 $out = str_replace(core_media_player::PLACEHOLDER, '', $out);
3253 if (!empty($options[core_media::OPTION_BLOCK]) && $out !== '') {
3254 $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
3256 return $out;
3260 * Checks whether a file can be embedded. If this returns true you will get
3261 * an embedded player; if this returns false, you will just get a download
3262 * link.
3264 * This is a wrapper for can_embed_urls.
3266 * @param moodle_url $url URL of media file
3267 * @param array $options Options (same as when embedding)
3268 * @return bool True if file can be embedded
3270 public function can_embed_url(moodle_url $url, $options = array()) {
3271 return $this->can_embed_urls(array($url), $options);
3275 * Checks whether a file can be embedded. If this returns true you will get
3276 * an embedded player; if this returns false, you will just get a download
3277 * link.
3279 * @param array $urls URL of media file and any alternatives (moodle_url)
3280 * @param array $options Options (same as when embedding)
3281 * @return bool True if file can be embedded
3283 public function can_embed_urls(array $urls, $options = array()) {
3284 // Check all players to see if any of them support it.
3285 foreach ($this->get_players() as $player) {
3286 // Link player (always last on list) doesn't count!
3287 if ($player->get_rank() <= 0) {
3288 break;
3290 // First player that supports it, return true.
3291 if ($player->list_supported_urls($urls, $options)) {
3292 return true;
3295 return false;
3299 * Obtains a list of markers that can be used in a regular expression when
3300 * searching for URLs that can be embedded by any player type.
3302 * This string is used to improve peformance of regex matching by ensuring
3303 * that the (presumably C) regex code can do a quick keyword check on the
3304 * URL part of a link to see if it matches one of these, rather than having
3305 * to go into PHP code for every single link to see if it can be embedded.
3307 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
3309 public function get_embeddable_markers() {
3310 if (empty($this->embeddablemarkers)) {
3311 $markers = '';
3312 foreach ($this->get_players() as $player) {
3313 foreach ($player->get_embeddable_markers() as $marker) {
3314 if ($markers !== '') {
3315 $markers .= '|';
3317 $markers .= preg_quote($marker);
3320 $this->embeddablemarkers = $markers;
3322 return $this->embeddablemarkers;