Merge branch 'MDL-40255_M25' of git://github.com/lazydaisy/moodle into MOODLE_25_STABLE
[moodle.git] / lib / outputrenderers.php
blob0e5c9599fccb03e0109ce595e5118c9a190bb027
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 if (during_initial_install()) {
473 // Debugging info can not work before install is finished,
474 // in any case we do not want any links during installation!
475 return '';
478 // This function is normally called from a layout.php file in {@link core_renderer::header()}
479 // but some of the content won't be known until later, so we return a placeholder
480 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
481 $output = $this->unique_performance_info_token;
482 if ($this->page->devicetypeinuse == 'legacy') {
483 // The legacy theme is in use print the notification
484 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
487 // Get links to switch device types (only shown for users not on a default device)
488 $output .= $this->theme_switch_links();
490 if (!empty($CFG->debugpageinfo)) {
491 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
493 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
494 // Add link to profiling report if necessary
495 if (function_exists('profiling_is_running') && profiling_is_running()) {
496 $txt = get_string('profiledscript', 'admin');
497 $title = get_string('profiledscriptview', 'admin');
498 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
499 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
500 $output .= '<div class="profilingfooter">' . $link . '</div>';
502 $output .= '<div class="purgecaches"><a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/purgecaches.php?confirm=1&amp;sesskey='.sesskey().'">'.get_string('purgecaches', 'admin').'</a></div>';
504 if (!empty($CFG->debugvalidators)) {
505 // 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
506 $output .= '<div class="validators"><ul>
507 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
508 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
509 <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>
510 </ul></div>';
512 if (!empty($CFG->additionalhtmlfooter)) {
513 $output .= "\n".$CFG->additionalhtmlfooter;
515 return $output;
519 * Returns standard main content placeholder.
520 * Designed to be called in theme layout.php files.
522 * @return string HTML fragment.
524 public function main_content() {
525 // This is here because it is the only place we can inject the "main" role over the entire main content area
526 // without requiring all theme's to manually do it, and without creating yet another thing people need to
527 // remember in the theme.
528 // This is an unfortunate hack. DO NO EVER add anything more here.
529 // DO NOT add classes.
530 // DO NOT add an id.
531 return '<div role="main">'.$this->unique_main_content_token.'</div>';
535 * The standard tags (typically script tags that are not needed earlier) that
536 * should be output after everything else, . Designed to be called in theme layout.php files.
538 * @return string HTML fragment.
540 public function standard_end_of_body_html() {
541 // This function is normally called from a layout.php file in {@link core_renderer::header()}
542 // but some of the content won't be known until later, so we return a placeholder
543 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
544 return $this->unique_end_html_token;
548 * Return the standard string that says whether you are logged in (and switched
549 * roles/logged in as another user).
550 * @param bool $withlinks if false, then don't include any links in the HTML produced.
551 * If not set, the default is the nologinlinks option from the theme config.php file,
552 * and if that is not set, then links are included.
553 * @return string HTML fragment.
555 public function login_info($withlinks = null) {
556 global $USER, $CFG, $DB, $SESSION;
558 if (during_initial_install()) {
559 return '';
562 if (is_null($withlinks)) {
563 $withlinks = empty($this->page->layout_options['nologinlinks']);
566 $loginpage = ((string)$this->page->url === get_login_url());
567 $course = $this->page->course;
568 if (session_is_loggedinas()) {
569 $realuser = session_get_realuser();
570 $fullname = fullname($realuser, true);
571 if ($withlinks) {
572 $loginastitle = get_string('loginas');
573 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
574 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
575 } else {
576 $realuserinfo = " [$fullname] ";
578 } else {
579 $realuserinfo = '';
582 $loginurl = get_login_url();
584 if (empty($course->id)) {
585 // $course->id is not defined during installation
586 return '';
587 } else if (isloggedin()) {
588 $context = context_course::instance($course->id);
590 $fullname = fullname($USER, true);
591 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
592 if ($withlinks) {
593 $linktitle = get_string('viewprofile');
594 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
595 } else {
596 $username = $fullname;
598 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
599 if ($withlinks) {
600 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
601 } else {
602 $username .= " from {$idprovider->name}";
605 if (isguestuser()) {
606 $loggedinas = $realuserinfo.get_string('loggedinasguest');
607 if (!$loginpage && $withlinks) {
608 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
610 } else if (is_role_switched($course->id)) { // Has switched roles
611 $rolename = '';
612 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
613 $rolename = ': '.role_get_name($role, $context);
615 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
616 if ($withlinks) {
617 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
618 $loggedinas .= '('.html_writer::tag('a', get_string('switchrolereturn'), array('href'=>$url)).')';
620 } else {
621 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
622 if ($withlinks) {
623 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
626 } else {
627 $loggedinas = get_string('loggedinnot', 'moodle');
628 if (!$loginpage && $withlinks) {
629 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
633 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
635 if (isset($SESSION->justloggedin)) {
636 unset($SESSION->justloggedin);
637 if (!empty($CFG->displayloginfailures)) {
638 if (!isguestuser()) {
639 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
640 $loggedinas .= '&nbsp;<div class="loginfailures">';
641 if (empty($count->accounts)) {
642 $loggedinas .= get_string('failedloginattempts', '', $count);
643 } else {
644 $loggedinas .= get_string('failedloginattemptsall', '', $count);
646 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
647 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/report/log/index.php'.
648 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
650 $loggedinas .= '</div>';
656 return $loggedinas;
660 * Return the 'back' link that normally appears in the footer.
662 * @return string HTML fragment.
664 public function home_link() {
665 global $CFG, $SITE;
667 if ($this->page->pagetype == 'site-index') {
668 // Special case for site home page - please do not remove
669 return '<div class="sitelink">' .
670 '<a title="Moodle" href="http://moodle.org/">' .
671 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
673 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
674 // Special case for during install/upgrade.
675 return '<div class="sitelink">'.
676 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
677 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
679 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
680 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
681 get_string('home') . '</a></div>';
683 } else {
684 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
685 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
690 * Redirects the user by any means possible given the current state
692 * This function should not be called directly, it should always be called using
693 * the redirect function in lib/weblib.php
695 * The redirect function should really only be called before page output has started
696 * however it will allow itself to be called during the state STATE_IN_BODY
698 * @param string $encodedurl The URL to send to encoded if required
699 * @param string $message The message to display to the user if any
700 * @param int $delay The delay before redirecting a user, if $message has been
701 * set this is a requirement and defaults to 3, set to 0 no delay
702 * @param boolean $debugdisableredirect this redirect has been disabled for
703 * debugging purposes. Display a message that explains, and don't
704 * trigger the redirect.
705 * @return string The HTML to display to the user before dying, may contain
706 * meta refresh, javascript refresh, and may have set header redirects
708 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
709 global $CFG;
710 $url = str_replace('&amp;', '&', $encodedurl);
712 switch ($this->page->state) {
713 case moodle_page::STATE_BEFORE_HEADER :
714 // No output yet it is safe to delivery the full arsenal of redirect methods
715 if (!$debugdisableredirect) {
716 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
717 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
718 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
720 $output = $this->header();
721 break;
722 case moodle_page::STATE_PRINTING_HEADER :
723 // We should hopefully never get here
724 throw new coding_exception('You cannot redirect while printing the page header');
725 break;
726 case moodle_page::STATE_IN_BODY :
727 // We really shouldn't be here but we can deal with this
728 debugging("You should really redirect before you start page output");
729 if (!$debugdisableredirect) {
730 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
732 $output = $this->opencontainers->pop_all_but_last();
733 break;
734 case moodle_page::STATE_DONE :
735 // Too late to be calling redirect now
736 throw new coding_exception('You cannot redirect after the entire page has been generated');
737 break;
739 $output .= $this->notification($message, 'redirectmessage');
740 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
741 if ($debugdisableredirect) {
742 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
744 $output .= $this->footer();
745 return $output;
749 * Start output by sending the HTTP headers, and printing the HTML <head>
750 * and the start of the <body>.
752 * To control what is printed, you should set properties on $PAGE. If you
753 * are familiar with the old {@link print_header()} function from Moodle 1.9
754 * you will find that there are properties on $PAGE that correspond to most
755 * of the old parameters to could be passed to print_header.
757 * Not that, in due course, the remaining $navigation, $menu parameters here
758 * will be replaced by more properties of $PAGE, but that is still to do.
760 * @return string HTML that you must output this, preferably immediately.
762 public function header() {
763 global $USER, $CFG;
765 if (session_is_loggedinas()) {
766 $this->page->add_body_class('userloggedinas');
769 // Give themes a chance to init/alter the page object.
770 $this->page->theme->init_page($this->page);
772 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
774 // Find the appropriate page layout file, based on $this->page->pagelayout.
775 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
776 // Render the layout using the layout file.
777 $rendered = $this->render_page_layout($layoutfile);
779 // Slice the rendered output into header and footer.
780 $cutpos = strpos($rendered, $this->unique_main_content_token);
781 if ($cutpos === false) {
782 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
783 $token = self::MAIN_CONTENT_TOKEN;
784 } else {
785 $token = $this->unique_main_content_token;
788 if ($cutpos === false) {
789 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.');
791 $header = substr($rendered, 0, $cutpos);
792 $footer = substr($rendered, $cutpos + strlen($token));
794 if (empty($this->contenttype)) {
795 debugging('The page layout file did not call $OUTPUT->doctype()');
796 $header = $this->doctype() . $header;
799 // If this theme version is below 2.4 release and this is a course view page
800 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
801 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
802 // check if course content header/footer have not been output during render of theme layout
803 $coursecontentheader = $this->course_content_header(true);
804 $coursecontentfooter = $this->course_content_footer(true);
805 if (!empty($coursecontentheader)) {
806 // display debug message and add header and footer right above and below main content
807 // Please note that course header and footer (to be displayed above and below the whole page)
808 // are not displayed in this case at all.
809 // Besides the content header and footer are not displayed on any other course page
810 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);
811 $header .= $coursecontentheader;
812 $footer = $coursecontentfooter. $footer;
816 send_headers($this->contenttype, $this->page->cacheable);
818 $this->opencontainers->push('header/footer', $footer);
819 $this->page->set_state(moodle_page::STATE_IN_BODY);
821 return $header . $this->skip_link_target('maincontent');
825 * Renders and outputs the page layout file.
827 * This is done by preparing the normal globals available to a script, and
828 * then including the layout file provided by the current theme for the
829 * requested layout.
831 * @param string $layoutfile The name of the layout file
832 * @return string HTML code
834 protected function render_page_layout($layoutfile) {
835 global $CFG, $SITE, $USER;
836 // The next lines are a bit tricky. The point is, here we are in a method
837 // of a renderer class, and this object may, or may not, be the same as
838 // the global $OUTPUT object. When rendering the page layout file, we want to use
839 // this object. However, people writing Moodle code expect the current
840 // renderer to be called $OUTPUT, not $this, so define a variable called
841 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
842 $OUTPUT = $this;
843 $PAGE = $this->page;
844 $COURSE = $this->page->course;
846 ob_start();
847 include($layoutfile);
848 $rendered = ob_get_contents();
849 ob_end_clean();
850 return $rendered;
854 * Outputs the page's footer
856 * @return string HTML fragment
858 public function footer() {
859 global $CFG, $DB;
861 $output = $this->container_end_all(true);
863 $footer = $this->opencontainers->pop('header/footer');
865 if (debugging() and $DB and $DB->is_transaction_started()) {
866 // TODO: MDL-20625 print warning - transaction will be rolled back
869 // Provide some performance info if required
870 $performanceinfo = '';
871 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
872 $perf = get_performance_info();
873 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
874 error_log("PERF: " . $perf['txt']);
876 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
877 $performanceinfo = $perf['html'];
880 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
882 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
884 $this->page->set_state(moodle_page::STATE_DONE);
886 return $output . $footer;
890 * Close all but the last open container. This is useful in places like error
891 * handling, where you want to close all the open containers (apart from <body>)
892 * before outputting the error message.
894 * @param bool $shouldbenone assert that the stack should be empty now - causes a
895 * developer debug warning if it isn't.
896 * @return string the HTML required to close any open containers inside <body>.
898 public function container_end_all($shouldbenone = false) {
899 return $this->opencontainers->pop_all_but_last($shouldbenone);
903 * Returns course-specific information to be output immediately above content on any course page
904 * (for the current course)
906 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
907 * @return string
909 public function course_content_header($onlyifnotcalledbefore = false) {
910 global $CFG;
911 if ($this->page->course->id == SITEID) {
912 // return immediately and do not include /course/lib.php if not necessary
913 return '';
915 static $functioncalled = false;
916 if ($functioncalled && $onlyifnotcalledbefore) {
917 // we have already output the content header
918 return '';
920 require_once($CFG->dirroot.'/course/lib.php');
921 $functioncalled = true;
922 $courseformat = course_get_format($this->page->course);
923 if (($obj = $courseformat->course_content_header()) !== null) {
924 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
926 return '';
930 * Returns course-specific information to be output immediately below content on any course page
931 * (for the current course)
933 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
934 * @return string
936 public function course_content_footer($onlyifnotcalledbefore = false) {
937 global $CFG;
938 if ($this->page->course->id == SITEID) {
939 // return immediately and do not include /course/lib.php if not necessary
940 return '';
942 static $functioncalled = false;
943 if ($functioncalled && $onlyifnotcalledbefore) {
944 // we have already output the content footer
945 return '';
947 $functioncalled = true;
948 require_once($CFG->dirroot.'/course/lib.php');
949 $courseformat = course_get_format($this->page->course);
950 if (($obj = $courseformat->course_content_footer()) !== null) {
951 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
953 return '';
957 * Returns course-specific information to be output on any course page in the header area
958 * (for the current course)
960 * @return string
962 public function course_header() {
963 global $CFG;
964 if ($this->page->course->id == SITEID) {
965 // return immediately and do not include /course/lib.php if not necessary
966 return '';
968 require_once($CFG->dirroot.'/course/lib.php');
969 $courseformat = course_get_format($this->page->course);
970 if (($obj = $courseformat->course_header()) !== null) {
971 return $courseformat->get_renderer($this->page)->render($obj);
973 return '';
977 * Returns course-specific information to be output on any course page in the footer area
978 * (for the current course)
980 * @return string
982 public function course_footer() {
983 global $CFG;
984 if ($this->page->course->id == SITEID) {
985 // return immediately and do not include /course/lib.php if not necessary
986 return '';
988 require_once($CFG->dirroot.'/course/lib.php');
989 $courseformat = course_get_format($this->page->course);
990 if (($obj = $courseformat->course_footer()) !== null) {
991 return $courseformat->get_renderer($this->page)->render($obj);
993 return '';
997 * Returns lang menu or '', this method also checks forcing of languages in courses.
999 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1001 * @return string The lang menu HTML or empty string
1003 public function lang_menu() {
1004 global $CFG;
1006 if (empty($CFG->langmenu)) {
1007 return '';
1010 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1011 // do not show lang menu if language forced
1012 return '';
1015 $currlang = current_language();
1016 $langs = get_string_manager()->get_list_of_translations();
1018 if (count($langs) < 2) {
1019 return '';
1022 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1023 $s->label = get_accesshide(get_string('language'));
1024 $s->class = 'langmenu';
1025 return $this->render($s);
1029 * Output the row of editing icons for a block, as defined by the controls array.
1031 * @param array $controls an array like {@link block_contents::$controls}.
1032 * @return string HTML fragment.
1034 public function block_controls($controls) {
1035 if (empty($controls)) {
1036 return '';
1038 $controlshtml = array();
1039 foreach ($controls as $control) {
1040 $controlshtml[] = html_writer::tag('a',
1041 html_writer::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
1042 array('class' => 'icon ' . $control['class'],'title' => $control['caption'], 'href' => $control['url']));
1044 return html_writer::tag('div', implode('', $controlshtml), array('class' => 'commands'));
1048 * Prints a nice side block with an optional header.
1050 * The content is described
1051 * by a {@link core_renderer::block_contents} object.
1053 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1054 * <div class="header"></div>
1055 * <div class="content">
1056 * ...CONTENT...
1057 * <div class="footer">
1058 * </div>
1059 * </div>
1060 * <div class="annotation">
1061 * </div>
1062 * </div>
1064 * @param block_contents $bc HTML for the content
1065 * @param string $region the region the block is appearing in.
1066 * @return string the HTML to be output.
1068 public function block(block_contents $bc, $region) {
1069 $bc = clone($bc); // Avoid messing up the object passed in.
1070 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1071 $bc->collapsible = block_contents::NOT_HIDEABLE;
1073 $skiptitle = strip_tags($bc->title);
1074 if ($bc->blockinstanceid && !empty($skiptitle)) {
1075 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1076 } else if (!empty($bc->arialabel)) {
1077 $bc->attributes['aria-label'] = $bc->arialabel;
1079 if ($bc->collapsible == block_contents::HIDDEN) {
1080 $bc->add_class('hidden');
1082 if (!empty($bc->controls)) {
1083 $bc->add_class('block_with_controls');
1087 if (empty($skiptitle)) {
1088 $output = '';
1089 $skipdest = '';
1090 } else {
1091 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
1092 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
1095 $output .= html_writer::start_tag('div', $bc->attributes);
1097 $output .= $this->block_header($bc);
1098 $output .= $this->block_content($bc);
1100 $output .= html_writer::end_tag('div');
1102 $output .= $this->block_annotation($bc);
1104 $output .= $skipdest;
1106 $this->init_block_hider_js($bc);
1107 return $output;
1111 * Produces a header for a block
1113 * @param block_contents $bc
1114 * @return string
1116 protected function block_header(block_contents $bc) {
1118 $title = '';
1119 if ($bc->title) {
1120 $attributes = array();
1121 if ($bc->blockinstanceid) {
1122 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1124 $title = html_writer::tag('h2', $bc->title, $attributes);
1127 $controlshtml = $this->block_controls($bc->controls);
1129 $output = '';
1130 if ($title || $controlshtml) {
1131 $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'));
1133 return $output;
1137 * Produces the content area for a block
1139 * @param block_contents $bc
1140 * @return string
1142 protected function block_content(block_contents $bc) {
1143 $output = html_writer::start_tag('div', array('class' => 'content'));
1144 if (!$bc->title && !$this->block_controls($bc->controls)) {
1145 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1147 $output .= $bc->content;
1148 $output .= $this->block_footer($bc);
1149 $output .= html_writer::end_tag('div');
1151 return $output;
1155 * Produces the footer for a block
1157 * @param block_contents $bc
1158 * @return string
1160 protected function block_footer(block_contents $bc) {
1161 $output = '';
1162 if ($bc->footer) {
1163 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1165 return $output;
1169 * Produces the annotation for a block
1171 * @param block_contents $bc
1172 * @return string
1174 protected function block_annotation(block_contents $bc) {
1175 $output = '';
1176 if ($bc->annotation) {
1177 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1179 return $output;
1183 * Calls the JS require function to hide a block.
1185 * @param block_contents $bc A block_contents object
1187 protected function init_block_hider_js(block_contents $bc) {
1188 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1189 $config = new stdClass;
1190 $config->id = $bc->attributes['id'];
1191 $config->title = strip_tags($bc->title);
1192 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1193 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1194 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1196 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1197 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1202 * Render the contents of a block_list.
1204 * @param array $icons the icon for each item.
1205 * @param array $items the content of each item.
1206 * @return string HTML
1208 public function list_block_contents($icons, $items) {
1209 $row = 0;
1210 $lis = array();
1211 foreach ($items as $key => $string) {
1212 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1213 if (!empty($icons[$key])) { //test if the content has an assigned icon
1214 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1216 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1217 $item .= html_writer::end_tag('li');
1218 $lis[] = $item;
1219 $row = 1 - $row; // Flip even/odd.
1221 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1225 * Output all the blocks in a particular region.
1227 * @param string $region the name of a region on this page.
1228 * @return string the HTML to be output.
1230 public function blocks_for_region($region) {
1231 $region = $this->page->apply_theme_region_manipulations($region);
1232 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1233 $blocks = $this->page->blocks->get_blocks_for_region($region);
1234 $lastblock = null;
1235 $zones = array();
1236 foreach ($blocks as $block) {
1237 $zones[] = $block->title;
1239 $output = '';
1241 foreach ($blockcontents as $bc) {
1242 if ($bc instanceof block_contents) {
1243 $output .= $this->block($bc, $region);
1244 $lastblock = $bc->title;
1245 } else if ($bc instanceof block_move_target) {
1246 $output .= $this->block_move_target($bc, $zones, $lastblock);
1247 } else {
1248 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1251 return $output;
1255 * Output a place where the block that is currently being moved can be dropped.
1257 * @param block_move_target $target with the necessary details.
1258 * @param array $zones array of areas where the block can be moved to
1259 * @param string $previous the block located before the area currently being rendered.
1260 * @return string the HTML to be output.
1262 public function block_move_target($target, $zones, $previous) {
1263 if ($previous == null) {
1264 $position = get_string('moveblockbefore', 'block', $zones[0]);
1265 } else {
1266 $position = get_string('moveblockafter', 'block', $previous);
1268 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1272 * Renders a special html link with attached action
1274 * Theme developers: DO NOT OVERRIDE! Please override function
1275 * {@link core_renderer::render_action_link()} instead.
1277 * @param string|moodle_url $url
1278 * @param string $text HTML fragment
1279 * @param component_action $action
1280 * @param array $attributes associative array of html link attributes + disabled
1281 * @return string HTML fragment
1283 public function action_link($url, $text, component_action $action = null, array $attributes=null) {
1284 if (!($url instanceof moodle_url)) {
1285 $url = new moodle_url($url);
1287 $link = new action_link($url, $text, $action, $attributes);
1289 return $this->render($link);
1293 * Renders an action_link object.
1295 * The provided link is renderer and the HTML returned. At the same time the
1296 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1298 * @param action_link $link
1299 * @return string HTML fragment
1301 protected function render_action_link(action_link $link) {
1302 global $CFG;
1304 if ($link->text instanceof renderable) {
1305 $text = $this->render($link->text);
1306 } else {
1307 $text = $link->text;
1310 // A disabled link is rendered as formatted text
1311 if (!empty($link->attributes['disabled'])) {
1312 // do not use div here due to nesting restriction in xhtml strict
1313 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1316 $attributes = $link->attributes;
1317 unset($link->attributes['disabled']);
1318 $attributes['href'] = $link->url;
1320 if ($link->actions) {
1321 if (empty($attributes['id'])) {
1322 $id = html_writer::random_id('action_link');
1323 $attributes['id'] = $id;
1324 } else {
1325 $id = $attributes['id'];
1327 foreach ($link->actions as $action) {
1328 $this->add_action_handler($action, $id);
1332 return html_writer::tag('a', $text, $attributes);
1337 * Renders an action_icon.
1339 * This function uses the {@link core_renderer::action_link()} method for the
1340 * most part. What it does different is prepare the icon as HTML and use it
1341 * as the link text.
1343 * Theme developers: If you want to change how action links and/or icons are rendered,
1344 * consider overriding function {@link core_renderer::render_action_link()} and
1345 * {@link core_renderer::render_pix_icon()}.
1347 * @param string|moodle_url $url A string URL or moodel_url
1348 * @param pix_icon $pixicon
1349 * @param component_action $action
1350 * @param array $attributes associative array of html link attributes + disabled
1351 * @param bool $linktext show title next to image in link
1352 * @return string HTML fragment
1354 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1355 if (!($url instanceof moodle_url)) {
1356 $url = new moodle_url($url);
1358 $attributes = (array)$attributes;
1360 if (empty($attributes['class'])) {
1361 // let ppl override the class via $options
1362 $attributes['class'] = 'action-icon';
1365 $icon = $this->render($pixicon);
1367 if ($linktext) {
1368 $text = $pixicon->attributes['alt'];
1369 } else {
1370 $text = '';
1373 return $this->action_link($url, $text.$icon, $action, $attributes);
1377 * Print a message along with button choices for Continue/Cancel
1379 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1381 * @param string $message The question to ask the user
1382 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1383 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1384 * @return string HTML fragment
1386 public function confirm($message, $continue, $cancel) {
1387 if ($continue instanceof single_button) {
1388 // ok
1389 } else if (is_string($continue)) {
1390 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1391 } else if ($continue instanceof moodle_url) {
1392 $continue = new single_button($continue, get_string('continue'), 'post');
1393 } else {
1394 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1397 if ($cancel instanceof single_button) {
1398 // ok
1399 } else if (is_string($cancel)) {
1400 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1401 } else if ($cancel instanceof moodle_url) {
1402 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1403 } else {
1404 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1407 $output = $this->box_start('generalbox', 'notice');
1408 $output .= html_writer::tag('p', $message);
1409 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1410 $output .= $this->box_end();
1411 return $output;
1415 * Returns a form with a single button.
1417 * Theme developers: DO NOT OVERRIDE! Please override function
1418 * {@link core_renderer::render_single_button()} instead.
1420 * @param string|moodle_url $url
1421 * @param string $label button text
1422 * @param string $method get or post submit method
1423 * @param array $options associative array {disabled, title, etc.}
1424 * @return string HTML fragment
1426 public function single_button($url, $label, $method='post', array $options=null) {
1427 if (!($url instanceof moodle_url)) {
1428 $url = new moodle_url($url);
1430 $button = new single_button($url, $label, $method);
1432 foreach ((array)$options as $key=>$value) {
1433 if (array_key_exists($key, $button)) {
1434 $button->$key = $value;
1438 return $this->render($button);
1442 * Renders a single button widget.
1444 * This will return HTML to display a form containing a single button.
1446 * @param single_button $button
1447 * @return string HTML fragment
1449 protected function render_single_button(single_button $button) {
1450 $attributes = array('type' => 'submit',
1451 'value' => $button->label,
1452 'disabled' => $button->disabled ? 'disabled' : null,
1453 'title' => $button->tooltip);
1455 if ($button->actions) {
1456 $id = html_writer::random_id('single_button');
1457 $attributes['id'] = $id;
1458 foreach ($button->actions as $action) {
1459 $this->add_action_handler($action, $id);
1463 // first the input element
1464 $output = html_writer::empty_tag('input', $attributes);
1466 // then hidden fields
1467 $params = $button->url->params();
1468 if ($button->method === 'post') {
1469 $params['sesskey'] = sesskey();
1471 foreach ($params as $var => $val) {
1472 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1475 // then div wrapper for xhtml strictness
1476 $output = html_writer::tag('div', $output);
1478 // now the form itself around it
1479 if ($button->method === 'get') {
1480 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1481 } else {
1482 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1484 if ($url === '') {
1485 $url = '#'; // there has to be always some action
1487 $attributes = array('method' => $button->method,
1488 'action' => $url,
1489 'id' => $button->formid);
1490 $output = html_writer::tag('form', $output, $attributes);
1492 // and finally one more wrapper with class
1493 return html_writer::tag('div', $output, array('class' => $button->class));
1497 * Returns a form with a single select widget.
1499 * Theme developers: DO NOT OVERRIDE! Please override function
1500 * {@link core_renderer::render_single_select()} instead.
1502 * @param moodle_url $url form action target, includes hidden fields
1503 * @param string $name name of selection field - the changing parameter in url
1504 * @param array $options list of options
1505 * @param string $selected selected element
1506 * @param array $nothing
1507 * @param string $formid
1508 * @return string HTML fragment
1510 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1511 if (!($url instanceof moodle_url)) {
1512 $url = new moodle_url($url);
1514 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1516 return $this->render($select);
1520 * Internal implementation of single_select rendering
1522 * @param single_select $select
1523 * @return string HTML fragment
1525 protected function render_single_select(single_select $select) {
1526 $select = clone($select);
1527 if (empty($select->formid)) {
1528 $select->formid = html_writer::random_id('single_select_f');
1531 $output = '';
1532 $params = $select->url->params();
1533 if ($select->method === 'post') {
1534 $params['sesskey'] = sesskey();
1536 foreach ($params as $name=>$value) {
1537 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1540 if (empty($select->attributes['id'])) {
1541 $select->attributes['id'] = html_writer::random_id('single_select');
1544 if ($select->disabled) {
1545 $select->attributes['disabled'] = 'disabled';
1548 if ($select->tooltip) {
1549 $select->attributes['title'] = $select->tooltip;
1552 $select->attributes['class'] = 'autosubmit';
1553 if ($select->class) {
1554 $select->attributes['class'] .= ' ' . $select->class;
1557 if ($select->label) {
1558 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1561 if ($select->helpicon instanceof help_icon) {
1562 $output .= $this->render($select->helpicon);
1564 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1566 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1567 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1569 $nothing = empty($select->nothing) ? false : key($select->nothing);
1570 $this->page->requires->yui_module('moodle-core-formautosubmit',
1571 'M.core.init_formautosubmit',
1572 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1575 // then div wrapper for xhtml strictness
1576 $output = html_writer::tag('div', $output);
1578 // now the form itself around it
1579 if ($select->method === 'get') {
1580 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1581 } else {
1582 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1584 $formattributes = array('method' => $select->method,
1585 'action' => $url,
1586 'id' => $select->formid);
1587 $output = html_writer::tag('form', $output, $formattributes);
1589 // and finally one more wrapper with class
1590 return html_writer::tag('div', $output, array('class' => $select->class));
1594 * Returns a form with a url select widget.
1596 * Theme developers: DO NOT OVERRIDE! Please override function
1597 * {@link core_renderer::render_url_select()} instead.
1599 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1600 * @param string $selected selected element
1601 * @param array $nothing
1602 * @param string $formid
1603 * @return string HTML fragment
1605 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1606 $select = new url_select($urls, $selected, $nothing, $formid);
1607 return $this->render($select);
1611 * Internal implementation of url_select rendering
1613 * @param url_select $select
1614 * @return string HTML fragment
1616 protected function render_url_select(url_select $select) {
1617 global $CFG;
1619 $select = clone($select);
1620 if (empty($select->formid)) {
1621 $select->formid = html_writer::random_id('url_select_f');
1624 if (empty($select->attributes['id'])) {
1625 $select->attributes['id'] = html_writer::random_id('url_select');
1628 if ($select->disabled) {
1629 $select->attributes['disabled'] = 'disabled';
1632 if ($select->tooltip) {
1633 $select->attributes['title'] = $select->tooltip;
1636 $output = '';
1638 if ($select->label) {
1639 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1642 $classes = array();
1643 if (!$select->showbutton) {
1644 $classes[] = 'autosubmit';
1646 if ($select->class) {
1647 $classes[] = $select->class;
1649 if (count($classes)) {
1650 $select->attributes['class'] = implode(' ', $classes);
1653 if ($select->helpicon instanceof help_icon) {
1654 $output .= $this->render($select->helpicon);
1657 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1658 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1659 $urls = array();
1660 foreach ($select->urls as $k=>$v) {
1661 if (is_array($v)) {
1662 // optgroup structure
1663 foreach ($v as $optgrouptitle => $optgroupoptions) {
1664 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1665 if (empty($optionurl)) {
1666 $safeoptionurl = '';
1667 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1668 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1669 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1670 } else if (strpos($optionurl, '/') !== 0) {
1671 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1672 continue;
1673 } else {
1674 $safeoptionurl = $optionurl;
1676 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1679 } else {
1680 // plain list structure
1681 if (empty($k)) {
1682 // nothing selected option
1683 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1684 $k = str_replace($CFG->wwwroot, '', $k);
1685 } else if (strpos($k, '/') !== 0) {
1686 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1687 continue;
1689 $urls[$k] = $v;
1692 $selected = $select->selected;
1693 if (!empty($selected)) {
1694 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1695 $selected = str_replace($CFG->wwwroot, '', $selected);
1696 } else if (strpos($selected, '/') !== 0) {
1697 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1701 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1702 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1704 if (!$select->showbutton) {
1705 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1706 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1707 $nothing = empty($select->nothing) ? false : key($select->nothing);
1708 $this->page->requires->yui_module('moodle-core-formautosubmit',
1709 'M.core.init_formautosubmit',
1710 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1712 } else {
1713 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1716 // then div wrapper for xhtml strictness
1717 $output = html_writer::tag('div', $output);
1719 // now the form itself around it
1720 $formattributes = array('method' => 'post',
1721 'action' => new moodle_url('/course/jumpto.php'),
1722 'id' => $select->formid);
1723 $output = html_writer::tag('form', $output, $formattributes);
1725 // and finally one more wrapper with class
1726 return html_writer::tag('div', $output, array('class' => $select->class));
1730 * Returns a string containing a link to the user documentation.
1731 * Also contains an icon by default. Shown to teachers and admin only.
1733 * @param string $path The page link after doc root and language, no leading slash.
1734 * @param string $text The text to be displayed for the link
1735 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
1736 * @return string
1738 public function doc_link($path, $text = '', $forcepopup = false) {
1739 global $CFG;
1741 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp icon-pre'));
1743 $url = new moodle_url(get_docs_url($path));
1745 $attributes = array('href'=>$url);
1746 if (!empty($CFG->doctonewwindow) || $forcepopup) {
1747 $attributes['class'] = 'helplinkpopup';
1750 return html_writer::tag('a', $icon.$text, $attributes);
1754 * Return HTML for a pix_icon.
1756 * Theme developers: DO NOT OVERRIDE! Please override function
1757 * {@link core_renderer::render_pix_icon()} instead.
1759 * @param string $pix short pix name
1760 * @param string $alt mandatory alt attribute
1761 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1762 * @param array $attributes htm lattributes
1763 * @return string HTML fragment
1765 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1766 $icon = new pix_icon($pix, $alt, $component, $attributes);
1767 return $this->render($icon);
1771 * Renders a pix_icon widget and returns the HTML to display it.
1773 * @param pix_icon $icon
1774 * @return string HTML fragment
1776 protected function render_pix_icon(pix_icon $icon) {
1777 $attributes = $icon->attributes;
1778 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1779 return html_writer::empty_tag('img', $attributes);
1783 * Return HTML to display an emoticon icon.
1785 * @param pix_emoticon $emoticon
1786 * @return string HTML fragment
1788 protected function render_pix_emoticon(pix_emoticon $emoticon) {
1789 $attributes = $emoticon->attributes;
1790 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
1791 return html_writer::empty_tag('img', $attributes);
1795 * Produces the html that represents this rating in the UI
1797 * @param rating $rating the page object on which this rating will appear
1798 * @return string
1800 function render_rating(rating $rating) {
1801 global $CFG, $USER;
1803 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
1804 return null;//ratings are turned off
1807 $ratingmanager = new rating_manager();
1808 // Initialise the JavaScript so ratings can be done by AJAX.
1809 $ratingmanager->initialise_rating_javascript($this->page);
1811 $strrate = get_string("rate", "rating");
1812 $ratinghtml = ''; //the string we'll return
1814 // permissions check - can they view the aggregate?
1815 if ($rating->user_can_view_aggregate()) {
1817 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
1818 $aggregatestr = $rating->get_aggregate_string();
1820 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
1821 if ($rating->count > 0) {
1822 $countstr = "({$rating->count})";
1823 } else {
1824 $countstr = '-';
1826 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
1828 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
1829 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
1831 $nonpopuplink = $rating->get_view_ratings_url();
1832 $popuplink = $rating->get_view_ratings_url(true);
1834 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
1835 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
1836 } else {
1837 $ratinghtml .= $aggregatehtml;
1841 $formstart = null;
1842 // if the item doesn't belong to the current user, the user has permission to rate
1843 // and we're within the assessable period
1844 if ($rating->user_can_rate()) {
1846 $rateurl = $rating->get_rate_url();
1847 $inputs = $rateurl->params();
1849 //start the rating form
1850 $formattrs = array(
1851 'id' => "postrating{$rating->itemid}",
1852 'class' => 'postratingform',
1853 'method' => 'post',
1854 'action' => $rateurl->out_omit_querystring()
1856 $formstart = html_writer::start_tag('form', $formattrs);
1857 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
1859 // add the hidden inputs
1860 foreach ($inputs as $name => $value) {
1861 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
1862 $formstart .= html_writer::empty_tag('input', $attributes);
1865 if (empty($ratinghtml)) {
1866 $ratinghtml .= $strrate.': ';
1868 $ratinghtml = $formstart.$ratinghtml;
1870 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
1871 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
1872 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
1873 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
1875 //output submit button
1876 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
1878 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
1879 $ratinghtml .= html_writer::empty_tag('input', $attributes);
1881 if (!$rating->settings->scale->isnumeric) {
1882 // If a global scale, try to find current course ID from the context
1883 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
1884 $courseid = $coursecontext->instanceid;
1885 } else {
1886 $courseid = $rating->settings->scale->courseid;
1888 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
1890 $ratinghtml .= html_writer::end_tag('span');
1891 $ratinghtml .= html_writer::end_tag('div');
1892 $ratinghtml .= html_writer::end_tag('form');
1895 return $ratinghtml;
1899 * Centered heading with attached help button (same title text)
1900 * and optional icon attached.
1902 * @param string $text A heading text
1903 * @param string $helpidentifier The keyword that defines a help page
1904 * @param string $component component name
1905 * @param string|moodle_url $icon
1906 * @param string $iconalt icon alt text
1907 * @return string HTML fragment
1909 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '') {
1910 $image = '';
1911 if ($icon) {
1912 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
1915 $help = '';
1916 if ($helpidentifier) {
1917 $help = $this->help_icon($helpidentifier, $component);
1920 return $this->heading($image.$text.$help, 2, 'main help');
1924 * Returns HTML to display a help icon.
1926 * @deprecated since Moodle 2.0
1928 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
1929 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
1933 * Returns HTML to display a help icon.
1935 * Theme developers: DO NOT OVERRIDE! Please override function
1936 * {@link core_renderer::render_help_icon()} instead.
1938 * @param string $identifier The keyword that defines a help page
1939 * @param string $component component name
1940 * @param string|bool $linktext true means use $title as link text, string means link text value
1941 * @return string HTML fragment
1943 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
1944 $icon = new help_icon($identifier, $component);
1945 $icon->diag_strings();
1946 if ($linktext === true) {
1947 $icon->linktext = get_string($icon->identifier, $icon->component);
1948 } else if (!empty($linktext)) {
1949 $icon->linktext = $linktext;
1951 return $this->render($icon);
1955 * Implementation of user image rendering.
1957 * @param help_icon $helpicon A help icon instance
1958 * @return string HTML fragment
1960 protected function render_help_icon(help_icon $helpicon) {
1961 global $CFG;
1963 // first get the help image icon
1964 $src = $this->pix_url('help');
1966 $title = get_string($helpicon->identifier, $helpicon->component);
1968 if (empty($helpicon->linktext)) {
1969 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
1970 } else {
1971 $alt = get_string('helpwiththis');
1974 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1975 $output = html_writer::empty_tag('img', $attributes);
1977 // add the link text if given
1978 if (!empty($helpicon->linktext)) {
1979 // the spacing has to be done through CSS
1980 $output .= $helpicon->linktext;
1983 // now create the link around it - we need https on loginhttps pages
1984 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
1986 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1987 $title = get_string('helpprefix2', '', trim($title, ". \t"));
1989 $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true', 'target'=>'_blank');
1990 $output = html_writer::tag('a', $output, $attributes);
1992 // and finally span
1993 return html_writer::tag('span', $output, array('class' => 'helptooltip'));
1997 * Returns HTML to display a scale help icon.
1999 * @param int $courseid
2000 * @param stdClass $scale instance
2001 * @return string HTML fragment
2003 public function help_icon_scale($courseid, stdClass $scale) {
2004 global $CFG;
2006 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2008 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2010 $scaleid = abs($scale->id);
2012 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2013 $action = new popup_action('click', $link, 'ratingscale');
2015 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2019 * Creates and returns a spacer image with optional line break.
2021 * @param array $attributes Any HTML attributes to add to the spaced.
2022 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2023 * laxy do it with CSS which is a much better solution.
2024 * @return string HTML fragment
2026 public function spacer(array $attributes = null, $br = false) {
2027 $attributes = (array)$attributes;
2028 if (empty($attributes['width'])) {
2029 $attributes['width'] = 1;
2031 if (empty($attributes['height'])) {
2032 $attributes['height'] = 1;
2034 $attributes['class'] = 'spacer';
2036 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2038 if (!empty($br)) {
2039 $output .= '<br />';
2042 return $output;
2046 * Returns HTML to display the specified user's avatar.
2048 * User avatar may be obtained in two ways:
2049 * <pre>
2050 * // Option 1: (shortcut for simple cases, preferred way)
2051 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2052 * $OUTPUT->user_picture($user, array('popup'=>true));
2054 * // Option 2:
2055 * $userpic = new user_picture($user);
2056 * // Set properties of $userpic
2057 * $userpic->popup = true;
2058 * $OUTPUT->render($userpic);
2059 * </pre>
2061 * Theme developers: DO NOT OVERRIDE! Please override function
2062 * {@link core_renderer::render_user_picture()} instead.
2064 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2065 * If any of these are missing, the database is queried. Avoid this
2066 * if at all possible, particularly for reports. It is very bad for performance.
2067 * @param array $options associative array with user picture options, used only if not a user_picture object,
2068 * options are:
2069 * - courseid=$this->page->course->id (course id of user profile in link)
2070 * - size=35 (size of image)
2071 * - link=true (make image clickable - the link leads to user profile)
2072 * - popup=false (open in popup)
2073 * - alttext=true (add image alt attribute)
2074 * - class = image class attribute (default 'userpicture')
2075 * @return string HTML fragment
2077 public function user_picture(stdClass $user, array $options = null) {
2078 $userpicture = new user_picture($user);
2079 foreach ((array)$options as $key=>$value) {
2080 if (array_key_exists($key, $userpicture)) {
2081 $userpicture->$key = $value;
2084 return $this->render($userpicture);
2088 * Internal implementation of user image rendering.
2090 * @param user_picture $userpicture
2091 * @return string
2093 protected function render_user_picture(user_picture $userpicture) {
2094 global $CFG, $DB;
2096 $user = $userpicture->user;
2098 if ($userpicture->alttext) {
2099 if (!empty($user->imagealt)) {
2100 $alt = $user->imagealt;
2101 } else {
2102 $alt = get_string('pictureof', '', fullname($user));
2104 } else {
2105 $alt = '';
2108 if (empty($userpicture->size)) {
2109 $size = 35;
2110 } else if ($userpicture->size === true or $userpicture->size == 1) {
2111 $size = 100;
2112 } else {
2113 $size = $userpicture->size;
2116 $class = $userpicture->class;
2118 if ($user->picture == 0) {
2119 $class .= ' defaultuserpic';
2122 $src = $userpicture->get_url($this->page, $this);
2124 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2126 // get the image html output fisrt
2127 $output = html_writer::empty_tag('img', $attributes);
2129 // then wrap it in link if needed
2130 if (!$userpicture->link) {
2131 return $output;
2134 if (empty($userpicture->courseid)) {
2135 $courseid = $this->page->course->id;
2136 } else {
2137 $courseid = $userpicture->courseid;
2140 if ($courseid == SITEID) {
2141 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2142 } else {
2143 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2146 $attributes = array('href'=>$url);
2148 if ($userpicture->popup) {
2149 $id = html_writer::random_id('userpicture');
2150 $attributes['id'] = $id;
2151 $this->add_action_handler(new popup_action('click', $url), $id);
2154 return html_writer::tag('a', $output, $attributes);
2158 * Internal implementation of file tree viewer items rendering.
2160 * @param array $dir
2161 * @return string
2163 public function htmllize_file_tree($dir) {
2164 if (empty($dir['subdirs']) and empty($dir['files'])) {
2165 return '';
2167 $result = '<ul>';
2168 foreach ($dir['subdirs'] as $subdir) {
2169 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2171 foreach ($dir['files'] as $file) {
2172 $filename = $file->get_filename();
2173 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2175 $result .= '</ul>';
2177 return $result;
2181 * Returns HTML to display the file picker
2183 * <pre>
2184 * $OUTPUT->file_picker($options);
2185 * </pre>
2187 * Theme developers: DO NOT OVERRIDE! Please override function
2188 * {@link core_renderer::render_file_picker()} instead.
2190 * @param array $options associative array with file manager options
2191 * options are:
2192 * maxbytes=>-1,
2193 * itemid=>0,
2194 * client_id=>uniqid(),
2195 * acepted_types=>'*',
2196 * return_types=>FILE_INTERNAL,
2197 * context=>$PAGE->context
2198 * @return string HTML fragment
2200 public function file_picker($options) {
2201 $fp = new file_picker($options);
2202 return $this->render($fp);
2206 * Internal implementation of file picker rendering.
2208 * @param file_picker $fp
2209 * @return string
2211 public function render_file_picker(file_picker $fp) {
2212 global $CFG, $OUTPUT, $USER;
2213 $options = $fp->options;
2214 $client_id = $options->client_id;
2215 $strsaved = get_string('filesaved', 'repository');
2216 $straddfile = get_string('openpicker', 'repository');
2217 $strloading = get_string('loading', 'repository');
2218 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2219 $strdroptoupload = get_string('droptoupload', 'moodle');
2220 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2222 $currentfile = $options->currentfile;
2223 if (empty($currentfile)) {
2224 $currentfile = '';
2225 } else {
2226 $currentfile .= ' - ';
2228 if ($options->maxbytes) {
2229 $size = $options->maxbytes;
2230 } else {
2231 $size = get_max_upload_file_size();
2233 if ($size == -1) {
2234 $maxsize = '';
2235 } else {
2236 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2238 if ($options->buttonname) {
2239 $buttonname = ' name="' . $options->buttonname . '"';
2240 } else {
2241 $buttonname = '';
2243 $html = <<<EOD
2244 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2245 $icon_progress
2246 </div>
2247 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2248 <div>
2249 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2250 <span> $maxsize </span>
2251 </div>
2252 EOD;
2253 if ($options->env != 'url') {
2254 $html .= <<<EOD
2255 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2256 <div class="filepicker-filename">
2257 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2258 <div class="dndupload-progressbars"></div>
2259 </div>
2260 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2261 </div>
2262 EOD;
2264 $html .= '</div>';
2265 return $html;
2269 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2271 * @param string $cmid the course_module id.
2272 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2273 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2275 public function update_module_button($cmid, $modulename) {
2276 global $CFG;
2277 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2278 $modulename = get_string('modulename', $modulename);
2279 $string = get_string('updatethis', '', $modulename);
2280 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2281 return $this->single_button($url, $string);
2282 } else {
2283 return '';
2288 * Returns HTML to display a "Turn editing on/off" button in a form.
2290 * @param moodle_url $url The URL + params to send through when clicking the button
2291 * @return string HTML the button
2293 public function edit_button(moodle_url $url) {
2295 $url->param('sesskey', sesskey());
2296 if ($this->page->user_is_editing()) {
2297 $url->param('edit', 'off');
2298 $editstring = get_string('turneditingoff');
2299 } else {
2300 $url->param('edit', 'on');
2301 $editstring = get_string('turneditingon');
2304 return $this->single_button($url, $editstring);
2308 * Returns HTML to display a simple button to close a window
2310 * @param string $text The lang string for the button's label (already output from get_string())
2311 * @return string html fragment
2313 public function close_window_button($text='') {
2314 if (empty($text)) {
2315 $text = get_string('closewindow');
2317 $button = new single_button(new moodle_url('#'), $text, 'get');
2318 $button->add_action(new component_action('click', 'close_window'));
2320 return $this->container($this->render($button), 'closewindow');
2324 * Output an error message. By default wraps the error message in <span class="error">.
2325 * If the error message is blank, nothing is output.
2327 * @param string $message the error message.
2328 * @return string the HTML to output.
2330 public function error_text($message) {
2331 if (empty($message)) {
2332 return '';
2334 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2335 return html_writer::tag('span', $message, array('class' => 'error'));
2339 * Do not call this function directly.
2341 * To terminate the current script with a fatal error, call the {@link print_error}
2342 * function, or throw an exception. Doing either of those things will then call this
2343 * function to display the error, before terminating the execution.
2345 * @param string $message The message to output
2346 * @param string $moreinfourl URL where more info can be found about the error
2347 * @param string $link Link for the Continue button
2348 * @param array $backtrace The execution backtrace
2349 * @param string $debuginfo Debugging information
2350 * @return string the HTML to output.
2352 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2353 global $CFG;
2355 $output = '';
2356 $obbuffer = '';
2358 if ($this->has_started()) {
2359 // we can not always recover properly here, we have problems with output buffering,
2360 // html tables, etc.
2361 $output .= $this->opencontainers->pop_all_but_last();
2363 } else {
2364 // It is really bad if library code throws exception when output buffering is on,
2365 // because the buffered text would be printed before our start of page.
2366 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2367 error_reporting(0); // disable notices from gzip compression, etc.
2368 while (ob_get_level() > 0) {
2369 $buff = ob_get_clean();
2370 if ($buff === false) {
2371 break;
2373 $obbuffer .= $buff;
2375 error_reporting($CFG->debug);
2377 // Output not yet started.
2378 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2379 if (empty($_SERVER['HTTP_RANGE'])) {
2380 @header($protocol . ' 404 Not Found');
2381 } else {
2382 // Must stop byteserving attempts somehow,
2383 // this is weird but Chrome PDF viewer can be stopped only with 407!
2384 @header($protocol . ' 407 Proxy Authentication Required');
2387 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2388 $this->page->set_url('/'); // no url
2389 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2390 $this->page->set_title(get_string('error'));
2391 $this->page->set_heading($this->page->course->fullname);
2392 $output .= $this->header();
2395 $message = '<p class="errormessage">' . $message . '</p>'.
2396 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2397 get_string('moreinformation') . '</a></p>';
2398 if (empty($CFG->rolesactive)) {
2399 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2400 //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.
2402 $output .= $this->box($message, 'errorbox');
2404 if (debugging('', DEBUG_DEVELOPER)) {
2405 if (!empty($debuginfo)) {
2406 $debuginfo = s($debuginfo); // removes all nasty JS
2407 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2408 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2410 if (!empty($backtrace)) {
2411 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2413 if ($obbuffer !== '' ) {
2414 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2418 if (empty($CFG->rolesactive)) {
2419 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2420 } else if (!empty($link)) {
2421 $output .= $this->continue_button($link);
2424 $output .= $this->footer();
2426 // Padding to encourage IE to display our error page, rather than its own.
2427 $output .= str_repeat(' ', 512);
2429 return $output;
2433 * Output a notification (that is, a status message about something that has
2434 * just happened).
2436 * @param string $message the message to print out
2437 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2438 * @return string the HTML to output.
2440 public function notification($message, $classes = 'notifyproblem') {
2441 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2445 * Returns HTML to display a continue button that goes to a particular URL.
2447 * @param string|moodle_url $url The url the button goes to.
2448 * @return string the HTML to output.
2450 public function continue_button($url) {
2451 if (!($url instanceof moodle_url)) {
2452 $url = new moodle_url($url);
2454 $button = new single_button($url, get_string('continue'), 'get');
2455 $button->class = 'continuebutton';
2457 return $this->render($button);
2461 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2463 * Theme developers: DO NOT OVERRIDE! Please override function
2464 * {@link core_renderer::render_paging_bar()} instead.
2466 * @param int $totalcount The total number of entries available to be paged through
2467 * @param int $page The page you are currently viewing
2468 * @param int $perpage The number of entries that should be shown per page
2469 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2470 * @param string $pagevar name of page parameter that holds the page number
2471 * @return string the HTML to output.
2473 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2474 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2475 return $this->render($pb);
2479 * Internal implementation of paging bar rendering.
2481 * @param paging_bar $pagingbar
2482 * @return string
2484 protected function render_paging_bar(paging_bar $pagingbar) {
2485 $output = '';
2486 $pagingbar = clone($pagingbar);
2487 $pagingbar->prepare($this, $this->page, $this->target);
2489 if ($pagingbar->totalcount > $pagingbar->perpage) {
2490 $output .= get_string('page') . ':';
2492 if (!empty($pagingbar->previouslink)) {
2493 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
2496 if (!empty($pagingbar->firstlink)) {
2497 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
2500 foreach ($pagingbar->pagelinks as $link) {
2501 $output .= "&#160;&#160;$link";
2504 if (!empty($pagingbar->lastlink)) {
2505 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
2508 if (!empty($pagingbar->nextlink)) {
2509 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
2513 return html_writer::tag('div', $output, array('class' => 'paging'));
2517 * Output the place a skip link goes to.
2519 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2520 * @return string the HTML to output.
2522 public function skip_link_target($id = null) {
2523 return html_writer::tag('span', '', array('id' => $id));
2527 * Outputs a heading
2529 * @param string $text The text of the heading
2530 * @param int $level The level of importance of the heading. Defaulting to 2
2531 * @param string $classes A space-separated list of CSS classes
2532 * @param string $id An optional ID
2533 * @return string the HTML to output.
2535 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2536 $level = (integer) $level;
2537 if ($level < 1 or $level > 6) {
2538 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2540 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2544 * Outputs a box.
2546 * @param string $contents The contents of the box
2547 * @param string $classes A space-separated list of CSS classes
2548 * @param string $id An optional ID
2549 * @return string the HTML to output.
2551 public function box($contents, $classes = 'generalbox', $id = null) {
2552 return $this->box_start($classes, $id) . $contents . $this->box_end();
2556 * Outputs the opening section of a box.
2558 * @param string $classes A space-separated list of CSS classes
2559 * @param string $id An optional ID
2560 * @return string the HTML to output.
2562 public function box_start($classes = 'generalbox', $id = null) {
2563 $this->opencontainers->push('box', html_writer::end_tag('div'));
2564 return html_writer::start_tag('div', array('id' => $id,
2565 'class' => 'box ' . renderer_base::prepare_classes($classes)));
2569 * Outputs the closing section of a box.
2571 * @return string the HTML to output.
2573 public function box_end() {
2574 return $this->opencontainers->pop('box');
2578 * Outputs a container.
2580 * @param string $contents The contents of the box
2581 * @param string $classes A space-separated list of CSS classes
2582 * @param string $id An optional ID
2583 * @return string the HTML to output.
2585 public function container($contents, $classes = null, $id = null) {
2586 return $this->container_start($classes, $id) . $contents . $this->container_end();
2590 * Outputs the opening section of a container.
2592 * @param string $classes A space-separated list of CSS classes
2593 * @param string $id An optional ID
2594 * @return string the HTML to output.
2596 public function container_start($classes = null, $id = null) {
2597 $this->opencontainers->push('container', html_writer::end_tag('div'));
2598 return html_writer::start_tag('div', array('id' => $id,
2599 'class' => renderer_base::prepare_classes($classes)));
2603 * Outputs the closing section of a container.
2605 * @return string the HTML to output.
2607 public function container_end() {
2608 return $this->opencontainers->pop('container');
2612 * Make nested HTML lists out of the items
2614 * The resulting list will look something like this:
2616 * <pre>
2617 * <<ul>>
2618 * <<li>><div class='tree_item parent'>(item contents)</div>
2619 * <<ul>
2620 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2621 * <</ul>>
2622 * <</li>>
2623 * <</ul>>
2624 * </pre>
2626 * @param array $items
2627 * @param array $attrs html attributes passed to the top ofs the list
2628 * @return string HTML
2630 public function tree_block_contents($items, $attrs = array()) {
2631 // exit if empty, we don't want an empty ul element
2632 if (empty($items)) {
2633 return '';
2635 // array of nested li elements
2636 $lis = array();
2637 foreach ($items as $item) {
2638 // this applies to the li item which contains all child lists too
2639 $content = $item->content($this);
2640 $liclasses = array($item->get_css_type());
2641 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2642 $liclasses[] = 'collapsed';
2644 if ($item->isactive === true) {
2645 $liclasses[] = 'current_branch';
2647 $liattr = array('class'=>join(' ',$liclasses));
2648 // class attribute on the div item which only contains the item content
2649 $divclasses = array('tree_item');
2650 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2651 $divclasses[] = 'branch';
2652 } else {
2653 $divclasses[] = 'leaf';
2655 if (!empty($item->classes) && count($item->classes)>0) {
2656 $divclasses[] = join(' ', $item->classes);
2658 $divattr = array('class'=>join(' ', $divclasses));
2659 if (!empty($item->id)) {
2660 $divattr['id'] = $item->id;
2662 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2663 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2664 $content = html_writer::empty_tag('hr') . $content;
2666 $content = html_writer::tag('li', $content, $liattr);
2667 $lis[] = $content;
2669 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2673 * Return the navbar content so that it can be echoed out by the layout
2675 * @return string XHTML navbar
2677 public function navbar() {
2678 $items = $this->page->navbar->get_items();
2679 $itemcount = count($items);
2680 if ($itemcount === 0) {
2681 return '';
2684 $htmlblocks = array();
2685 // Iterate the navarray and display each node
2686 $separator = get_separator();
2687 for ($i=0;$i < $itemcount;$i++) {
2688 $item = $items[$i];
2689 $item->hideicon = true;
2690 if ($i===0) {
2691 $content = html_writer::tag('li', $this->render($item));
2692 } else {
2693 $content = html_writer::tag('li', $separator.$this->render($item));
2695 $htmlblocks[] = $content;
2698 //accessibility: heading for navbar list (MDL-20446)
2699 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2700 $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks), array('role'=>'navigation'));
2701 // XHTML
2702 return $navbarcontent;
2706 * Renders a navigation node object.
2708 * @param navigation_node $item The navigation node to render.
2709 * @return string HTML fragment
2711 protected function render_navigation_node(navigation_node $item) {
2712 $content = $item->get_content();
2713 $title = $item->get_title();
2714 if ($item->icon instanceof renderable && !$item->hideicon) {
2715 $icon = $this->render($item->icon);
2716 $content = $icon.$content; // use CSS for spacing of icons
2718 if ($item->helpbutton !== null) {
2719 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2721 if ($content === '') {
2722 return '';
2724 if ($item->action instanceof action_link) {
2725 $link = $item->action;
2726 if ($item->hidden) {
2727 $link->add_class('dimmed');
2729 if (!empty($content)) {
2730 // Providing there is content we will use that for the link content.
2731 $link->text = $content;
2733 $content = $this->render($link);
2734 } else if ($item->action instanceof moodle_url) {
2735 $attributes = array();
2736 if ($title !== '') {
2737 $attributes['title'] = $title;
2739 if ($item->hidden) {
2740 $attributes['class'] = 'dimmed_text';
2742 $content = html_writer::link($item->action, $content, $attributes);
2744 } else if (is_string($item->action) || empty($item->action)) {
2745 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2746 if ($title !== '') {
2747 $attributes['title'] = $title;
2749 if ($item->hidden) {
2750 $attributes['class'] = 'dimmed_text';
2752 $content = html_writer::tag('span', $content, $attributes);
2754 return $content;
2758 * Accessibility: Right arrow-like character is
2759 * used in the breadcrumb trail, course navigation menu
2760 * (previous/next activity), calendar, and search forum block.
2761 * If the theme does not set characters, appropriate defaults
2762 * are set automatically. Please DO NOT
2763 * use &lt; &gt; &raquo; - these are confusing for blind users.
2765 * @return string
2767 public function rarrow() {
2768 return $this->page->theme->rarrow;
2772 * Accessibility: Right arrow-like character is
2773 * used in the breadcrumb trail, course navigation menu
2774 * (previous/next activity), calendar, and search forum block.
2775 * If the theme does not set characters, appropriate defaults
2776 * are set automatically. Please DO NOT
2777 * use &lt; &gt; &raquo; - these are confusing for blind users.
2779 * @return string
2781 public function larrow() {
2782 return $this->page->theme->larrow;
2786 * Returns the custom menu if one has been set
2788 * A custom menu can be configured by browsing to
2789 * Settings: Administration > Appearance > Themes > Theme settings
2790 * and then configuring the custommenu config setting as described.
2792 * Theme developers: DO NOT OVERRIDE! Please override function
2793 * {@link core_renderer::render_custom_menu()} instead.
2795 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
2796 * @return string
2798 public function custom_menu($custommenuitems = '') {
2799 global $CFG;
2800 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
2801 $custommenuitems = $CFG->custommenuitems;
2803 if (empty($custommenuitems)) {
2804 return '';
2806 $custommenu = new custom_menu($custommenuitems, current_language());
2807 return $this->render($custommenu);
2811 * Renders a custom menu object (located in outputcomponents.php)
2813 * The custom menu this method produces makes use of the YUI3 menunav widget
2814 * and requires very specific html elements and classes.
2816 * @staticvar int $menucount
2817 * @param custom_menu $menu
2818 * @return string
2820 protected function render_custom_menu(custom_menu $menu) {
2821 static $menucount = 0;
2822 // If the menu has no children return an empty string
2823 if (!$menu->has_children()) {
2824 return '';
2826 // Increment the menu count. This is used for ID's that get worked with
2827 // in JavaScript as is essential
2828 $menucount++;
2829 // Initialise this custom menu (the custom menu object is contained in javascript-static
2830 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
2831 $jscode = "(function(){{$jscode}})";
2832 $this->page->requires->yui_module('node-menunav', $jscode);
2833 // Build the root nodes as required by YUI
2834 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
2835 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2836 $content .= html_writer::start_tag('ul');
2837 // Render each child
2838 foreach ($menu->get_children() as $item) {
2839 $content .= $this->render_custom_menu_item($item);
2841 // Close the open tags
2842 $content .= html_writer::end_tag('ul');
2843 $content .= html_writer::end_tag('div');
2844 $content .= html_writer::end_tag('div');
2845 // Return the custom menu
2846 return $content;
2850 * Renders a custom menu node as part of a submenu
2852 * The custom menu this method produces makes use of the YUI3 menunav widget
2853 * and requires very specific html elements and classes.
2855 * @see core:renderer::render_custom_menu()
2857 * @staticvar int $submenucount
2858 * @param custom_menu_item $menunode
2859 * @return string
2861 protected function render_custom_menu_item(custom_menu_item $menunode) {
2862 // Required to ensure we get unique trackable id's
2863 static $submenucount = 0;
2864 if ($menunode->has_children()) {
2865 // If the child has menus render it as a sub menu
2866 $submenucount++;
2867 $content = html_writer::start_tag('li');
2868 if ($menunode->get_url() !== null) {
2869 $url = $menunode->get_url();
2870 } else {
2871 $url = '#cm_submenu_'.$submenucount;
2873 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
2874 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
2875 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2876 $content .= html_writer::start_tag('ul');
2877 foreach ($menunode->get_children() as $menunode) {
2878 $content .= $this->render_custom_menu_item($menunode);
2880 $content .= html_writer::end_tag('ul');
2881 $content .= html_writer::end_tag('div');
2882 $content .= html_writer::end_tag('div');
2883 $content .= html_writer::end_tag('li');
2884 } else {
2885 // The node doesn't have children so produce a final menuitem
2886 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
2887 if ($menunode->get_url() !== null) {
2888 $url = $menunode->get_url();
2889 } else {
2890 $url = '#';
2892 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
2893 $content .= html_writer::end_tag('li');
2895 // Return the sub menu
2896 return $content;
2900 * Renders theme links for switching between default and other themes.
2902 * @return string
2904 protected function theme_switch_links() {
2906 $actualdevice = get_device_type();
2907 $currentdevice = $this->page->devicetypeinuse;
2908 $switched = ($actualdevice != $currentdevice);
2910 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
2911 // The user is using the a default device and hasn't switched so don't shown the switch
2912 // device links.
2913 return '';
2916 if ($switched) {
2917 $linktext = get_string('switchdevicerecommended');
2918 $devicetype = $actualdevice;
2919 } else {
2920 $linktext = get_string('switchdevicedefault');
2921 $devicetype = 'default';
2923 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
2925 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
2926 $content .= html_writer::link($linkurl, $linktext);
2927 $content .= html_writer::end_tag('div');
2929 return $content;
2933 * Renders tabs
2935 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
2937 * Theme developers: In order to change how tabs are displayed please override functions
2938 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
2940 * @param array $tabs array of tabs, each of them may have it's own ->subtree
2941 * @param string|null $selected which tab to mark as selected, all parent tabs will
2942 * automatically be marked as activated
2943 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
2944 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
2945 * @return string
2947 public final function tabtree($tabs, $selected = null, $inactive = null) {
2948 return $this->render(new tabtree($tabs, $selected, $inactive));
2952 * Renders tabtree
2954 * @param tabtree $tabtree
2955 * @return string
2957 protected function render_tabtree(tabtree $tabtree) {
2958 if (empty($tabtree->subtree)) {
2959 return '';
2961 $str = '';
2962 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
2963 $str .= $this->render_tabobject($tabtree);
2964 $str .= html_writer::end_tag('div').
2965 html_writer::tag('div', ' ', array('class' => 'clearer'));
2966 return $str;
2970 * Renders tabobject (part of tabtree)
2972 * This function is called from {@link core_renderer::render_tabtree()}
2973 * and also it calls itself when printing the $tabobject subtree recursively.
2975 * Property $tabobject->level indicates the number of row of tabs.
2977 * @param tabobject $tabobject
2978 * @return string HTML fragment
2980 protected function render_tabobject(tabobject $tabobject) {
2981 $str = '';
2983 // Print name of the current tab.
2984 if ($tabobject instanceof tabtree) {
2985 // No name for tabtree root.
2986 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
2987 // Tab name without a link. The <a> tag is used for styling.
2988 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink'));
2989 } else {
2990 // Tab name with a link.
2991 if (!($tabobject->link instanceof moodle_url)) {
2992 // backward compartibility when link was passed as quoted string
2993 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
2994 } else {
2995 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
2999 if (empty($tabobject->subtree)) {
3000 if ($tabobject->selected) {
3001 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3003 return $str;
3006 // Print subtree
3007 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3008 $cnt = 0;
3009 foreach ($tabobject->subtree as $tab) {
3010 $liclass = '';
3011 if (!$cnt) {
3012 $liclass .= ' first';
3014 if ($cnt == count($tabobject->subtree) - 1) {
3015 $liclass .= ' last';
3017 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3018 $liclass .= ' onerow';
3021 if ($tab->selected) {
3022 $liclass .= ' here selected';
3023 } else if ($tab->activated) {
3024 $liclass .= ' here active';
3027 // This will recursively call function render_tabobject() for each item in subtree
3028 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3029 $cnt++;
3031 $str .= html_writer::end_tag('ul');
3033 return $str;
3037 * Get the HTML for blocks in the given region.
3039 * @since 2.5.1 2.6
3040 * @param string $region The region to get HTML for.
3041 * @return string HTML.
3043 public function blocks($region, $classes = array(), $tag = 'aside') {
3044 $displayregion = $this->page->apply_theme_region_manipulations($region);
3045 $classes = (array)$classes;
3046 $classes[] = 'block-region';
3047 $attributes = array(
3048 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3049 'class' => join(' ', $classes),
3050 'data-blockregion' => $displayregion,
3051 'data-droptarget' => '1'
3053 return html_writer::tag($tag, $this->blocks_for_region($region), $attributes);
3057 * Returns the CSS classes to apply to the body tag.
3059 * @since 2.5.1 2.6
3060 * @param array $additionalclasses Any additional classes to apply.
3061 * @return string
3063 public function body_css_classes(array $additionalclasses = array()) {
3064 // Add a class for each block region on the page.
3065 // We use the block manager here because the theme object makes get_string calls.
3066 foreach ($this->page->blocks->get_regions() as $region) {
3067 $additionalclasses[] = 'has-region-'.$region;
3068 if ($this->page->blocks->region_has_content($region, $this)) {
3069 $additionalclasses[] = 'used-region-'.$region;
3070 } else {
3071 $additionalclasses[] = 'empty-region-'.$region;
3074 foreach ($this->page->layout_options as $option => $value) {
3075 if ($value) {
3076 $additionalclasses[] = 'layout-option-'.$option;
3079 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
3080 return $css;
3084 * The ID attribute to apply to the body tag.
3086 * @since 2.5.1 2.6
3087 * @return string
3089 public function body_id() {
3090 return $this->page->bodyid;
3094 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
3096 * @since 2.5.1 2.6
3097 * @param string|array $additionalclasses Any additional classes to give the body tag,
3098 * @return string
3100 public function body_attributes($additionalclasses = array()) {
3101 if (!is_array($additionalclasses)) {
3102 $additionalclasses = explode(' ', $additionalclasses);
3104 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
3108 * Gets HTML for the page heading.
3110 * @since 2.5.1 2.6
3111 * @param string $tag The tag to encase the heading in. h1 by default.
3112 * @return string HTML.
3114 public function page_heading($tag = 'h1') {
3115 return html_writer::tag($tag, $this->page->heading);
3119 * Gets the HTML for the page heading button.
3121 * @since 2.5.1 2.6
3122 * @return string HTML.
3124 public function page_heading_button() {
3125 return $this->page->button;
3129 * Returns the Moodle docs link to use for this page.
3131 * @since 2.5.1 2.6
3132 * @param string $text
3133 * @return string
3135 public function page_doc_link($text = null) {
3136 if ($text === null) {
3137 $text = get_string('moodledocslink');
3139 $path = page_get_doc_link_path($this->page);
3140 if (!$path) {
3141 return '';
3143 return $this->doc_link($path, $text);
3147 * Returns the page heading menu.
3149 * @since 2.5.1 2.6
3150 * @return string HTML.
3152 public function page_heading_menu() {
3153 return $this->page->headingmenu;
3157 * Returns the title to use on the page.
3159 * @since 2.5.1 2.6
3160 * @return string
3162 public function page_title() {
3163 return $this->page->title;
3167 * Returns the URL for the favicon.
3169 * @since 2.5.1 2.6
3170 * @return string The favicon URL
3172 public function favicon() {
3173 return $this->pix_url('favicon', 'theme');
3178 * A renderer that generates output for command-line scripts.
3180 * The implementation of this renderer is probably incomplete.
3182 * @copyright 2009 Tim Hunt
3183 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3184 * @since Moodle 2.0
3185 * @package core
3186 * @category output
3188 class core_renderer_cli extends core_renderer {
3191 * Returns the page header.
3193 * @return string HTML fragment
3195 public function header() {
3196 return $this->page->heading . "\n";
3200 * Returns a template fragment representing a Heading.
3202 * @param string $text The text of the heading
3203 * @param int $level The level of importance of the heading
3204 * @param string $classes A space-separated list of CSS classes
3205 * @param string $id An optional ID
3206 * @return string A template fragment for a heading
3208 public function heading($text, $level = 2, $classes = 'main', $id = null) {
3209 $text .= "\n";
3210 switch ($level) {
3211 case 1:
3212 return '=>' . $text;
3213 case 2:
3214 return '-->' . $text;
3215 default:
3216 return $text;
3221 * Returns a template fragment representing a fatal error.
3223 * @param string $message The message to output
3224 * @param string $moreinfourl URL where more info can be found about the error
3225 * @param string $link Link for the Continue button
3226 * @param array $backtrace The execution backtrace
3227 * @param string $debuginfo Debugging information
3228 * @return string A template fragment for a fatal error
3230 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
3231 $output = "!!! $message !!!\n";
3233 if (debugging('', DEBUG_DEVELOPER)) {
3234 if (!empty($debuginfo)) {
3235 $output .= $this->notification($debuginfo, 'notifytiny');
3237 if (!empty($backtrace)) {
3238 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
3242 return $output;
3246 * Returns a template fragment representing a notification.
3248 * @param string $message The message to include
3249 * @param string $classes A space-separated list of CSS classes
3250 * @return string A template fragment for a notification
3252 public function notification($message, $classes = 'notifyproblem') {
3253 $message = clean_text($message);
3254 if ($classes === 'notifysuccess') {
3255 return "++ $message ++\n";
3257 return "!! $message !!\n";
3263 * A renderer that generates output for ajax scripts.
3265 * This renderer prevents accidental sends back only json
3266 * encoded error messages, all other output is ignored.
3268 * @copyright 2010 Petr Skoda
3269 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3270 * @since Moodle 2.0
3271 * @package core
3272 * @category output
3274 class core_renderer_ajax extends core_renderer {
3277 * Returns a template fragment representing a fatal error.
3279 * @param string $message The message to output
3280 * @param string $moreinfourl URL where more info can be found about the error
3281 * @param string $link Link for the Continue button
3282 * @param array $backtrace The execution backtrace
3283 * @param string $debuginfo Debugging information
3284 * @return string A template fragment for a fatal error
3286 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
3287 global $CFG;
3289 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
3291 $e = new stdClass();
3292 $e->error = $message;
3293 $e->stacktrace = NULL;
3294 $e->debuginfo = NULL;
3295 $e->reproductionlink = NULL;
3296 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
3297 $e->reproductionlink = $link;
3298 if (!empty($debuginfo)) {
3299 $e->debuginfo = $debuginfo;
3301 if (!empty($backtrace)) {
3302 $e->stacktrace = format_backtrace($backtrace, true);
3305 $this->header();
3306 return json_encode($e);
3310 * Used to display a notification.
3311 * For the AJAX notifications are discarded.
3313 * @param string $message
3314 * @param string $classes
3316 public function notification($message, $classes = 'notifyproblem') {}
3319 * Used to display a redirection message.
3320 * AJAX redirections should not occur and as such redirection messages
3321 * are discarded.
3323 * @param moodle_url|string $encodedurl
3324 * @param string $message
3325 * @param int $delay
3326 * @param bool $debugdisableredirect
3328 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
3331 * Prepares the start of an AJAX output.
3333 public function header() {
3334 // unfortunately YUI iframe upload does not support application/json
3335 if (!empty($_FILES)) {
3336 @header('Content-type: text/plain; charset=utf-8');
3337 } else {
3338 @header('Content-type: application/json; charset=utf-8');
3341 // Headers to make it not cacheable and json
3342 @header('Cache-Control: no-store, no-cache, must-revalidate');
3343 @header('Cache-Control: post-check=0, pre-check=0', false);
3344 @header('Pragma: no-cache');
3345 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
3346 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
3347 @header('Accept-Ranges: none');
3351 * There is no footer for an AJAX request, however we must override the
3352 * footer method to prevent the default footer.
3354 public function footer() {}
3357 * No need for headers in an AJAX request... this should never happen.
3358 * @param string $text
3359 * @param int $level
3360 * @param string $classes
3361 * @param string $id
3363 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
3368 * Renderer for media files.
3370 * Used in file resources, media filter, and any other places that need to
3371 * output embedded media.
3373 * @copyright 2011 The Open University
3374 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3376 class core_media_renderer extends plugin_renderer_base {
3377 /** @var array Array of available 'player' objects */
3378 private $players;
3379 /** @var string Regex pattern for links which may contain embeddable content */
3380 private $embeddablemarkers;
3383 * Constructor requires medialib.php.
3385 * This is needed in the constructor (not later) so that you can use the
3386 * constants and static functions that are defined in core_media class
3387 * before you call renderer functions.
3389 public function __construct() {
3390 global $CFG;
3391 require_once($CFG->libdir . '/medialib.php');
3395 * Obtains the list of core_media_player objects currently in use to render
3396 * items.
3398 * The list is in rank order (highest first) and does not include players
3399 * which are disabled.
3401 * @return array Array of core_media_player objects in rank order
3403 protected function get_players() {
3404 global $CFG;
3406 // Save time by only building the list once.
3407 if (!$this->players) {
3408 // Get raw list of players.
3409 $players = $this->get_players_raw();
3411 // Chuck all the ones that are disabled.
3412 foreach ($players as $key => $player) {
3413 if (!$player->is_enabled()) {
3414 unset($players[$key]);
3418 // Sort in rank order (highest first).
3419 usort($players, array('core_media_player', 'compare_by_rank'));
3420 $this->players = $players;
3422 return $this->players;
3426 * Obtains a raw list of player objects that includes objects regardless
3427 * of whether they are disabled or not, and without sorting.
3429 * You can override this in a subclass if you need to add additional
3430 * players.
3432 * The return array is be indexed by player name to make it easier to
3433 * remove players in a subclass.
3435 * @return array $players Array of core_media_player objects in any order
3437 protected function get_players_raw() {
3438 return array(
3439 'vimeo' => new core_media_player_vimeo(),
3440 'youtube' => new core_media_player_youtube(),
3441 'youtube_playlist' => new core_media_player_youtube_playlist(),
3442 'html5video' => new core_media_player_html5video(),
3443 'html5audio' => new core_media_player_html5audio(),
3444 'mp3' => new core_media_player_mp3(),
3445 'flv' => new core_media_player_flv(),
3446 'wmp' => new core_media_player_wmp(),
3447 'qt' => new core_media_player_qt(),
3448 'rm' => new core_media_player_rm(),
3449 'swf' => new core_media_player_swf(),
3450 'link' => new core_media_player_link(),
3455 * Renders a media file (audio or video) using suitable embedded player.
3457 * See embed_alternatives function for full description of parameters.
3458 * This function calls through to that one.
3460 * When using this function you can also specify width and height in the
3461 * URL by including ?d=100x100 at the end. If specified in the URL, this
3462 * will override the $width and $height parameters.
3464 * @param moodle_url $url Full URL of media file
3465 * @param string $name Optional user-readable name to display in download link
3466 * @param int $width Width in pixels (optional)
3467 * @param int $height Height in pixels (optional)
3468 * @param array $options Array of key/value pairs
3469 * @return string HTML content of embed
3471 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
3472 $options = array()) {
3474 // Get width and height from URL if specified (overrides parameters in
3475 // function call).
3476 $rawurl = $url->out(false);
3477 if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
3478 $width = $matches[1];
3479 $height = $matches[2];
3480 $url = new moodle_url(str_replace($matches[0], '', $rawurl));
3483 // Defer to array version of function.
3484 return $this->embed_alternatives(array($url), $name, $width, $height, $options);
3488 * Renders media files (audio or video) using suitable embedded player.
3489 * The list of URLs should be alternative versions of the same content in
3490 * multiple formats. If there is only one format it should have a single
3491 * entry.
3493 * If the media files are not in a supported format, this will give students
3494 * a download link to each format. The download link uses the filename
3495 * unless you supply the optional name parameter.
3497 * Width and height are optional. If specified, these are suggested sizes
3498 * and should be the exact values supplied by the user, if they come from
3499 * user input. These will be treated as relating to the size of the video
3500 * content, not including any player control bar.
3502 * For audio files, height will be ignored. For video files, a few formats
3503 * work if you specify only width, but in general if you specify width
3504 * you must specify height as well.
3506 * The $options array is passed through to the core_media_player classes
3507 * that render the object tag. The keys can contain values from
3508 * core_media::OPTION_xx.
3510 * @param array $alternatives Array of moodle_url to media files
3511 * @param string $name Optional user-readable name to display in download link
3512 * @param int $width Width in pixels (optional)
3513 * @param int $height Height in pixels (optional)
3514 * @param array $options Array of key/value pairs
3515 * @return string HTML content of embed
3517 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
3518 $options = array()) {
3520 // Get list of player plugins (will also require the library).
3521 $players = $this->get_players();
3523 // Set up initial text which will be replaced by first player that
3524 // supports any of the formats.
3525 $out = core_media_player::PLACEHOLDER;
3527 // Loop through all players that support any of these URLs.
3528 foreach ($players as $player) {
3529 // Option: When no other player matched, don't do the default link player.
3530 if (!empty($options[core_media::OPTION_FALLBACK_TO_BLANK]) &&
3531 $player->get_rank() === 0 && $out === core_media_player::PLACEHOLDER) {
3532 continue;
3535 $supported = $player->list_supported_urls($alternatives, $options);
3536 if ($supported) {
3537 // Embed.
3538 $text = $player->embed($supported, $name, $width, $height, $options);
3540 // Put this in place of the 'fallback' slot in the previous text.
3541 $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
3545 // Remove 'fallback' slot from final version and return it.
3546 $out = str_replace(core_media_player::PLACEHOLDER, '', $out);
3547 if (!empty($options[core_media::OPTION_BLOCK]) && $out !== '') {
3548 $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
3550 return $out;
3554 * Checks whether a file can be embedded. If this returns true you will get
3555 * an embedded player; if this returns false, you will just get a download
3556 * link.
3558 * This is a wrapper for can_embed_urls.
3560 * @param moodle_url $url URL of media file
3561 * @param array $options Options (same as when embedding)
3562 * @return bool True if file can be embedded
3564 public function can_embed_url(moodle_url $url, $options = array()) {
3565 return $this->can_embed_urls(array($url), $options);
3569 * Checks whether a file can be embedded. If this returns true you will get
3570 * an embedded player; if this returns false, you will just get a download
3571 * link.
3573 * @param array $urls URL of media file and any alternatives (moodle_url)
3574 * @param array $options Options (same as when embedding)
3575 * @return bool True if file can be embedded
3577 public function can_embed_urls(array $urls, $options = array()) {
3578 // Check all players to see if any of them support it.
3579 foreach ($this->get_players() as $player) {
3580 // Link player (always last on list) doesn't count!
3581 if ($player->get_rank() <= 0) {
3582 break;
3584 // First player that supports it, return true.
3585 if ($player->list_supported_urls($urls, $options)) {
3586 return true;
3589 return false;
3593 * Obtains a list of markers that can be used in a regular expression when
3594 * searching for URLs that can be embedded by any player type.
3596 * This string is used to improve peformance of regex matching by ensuring
3597 * that the (presumably C) regex code can do a quick keyword check on the
3598 * URL part of a link to see if it matches one of these, rather than having
3599 * to go into PHP code for every single link to see if it can be embedded.
3601 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
3603 public function get_embeddable_markers() {
3604 if (empty($this->embeddablemarkers)) {
3605 $markers = '';
3606 foreach ($this->get_players() as $player) {
3607 foreach ($player->get_embeddable_markers() as $marker) {
3608 if ($markers !== '') {
3609 $markers .= '|';
3611 $markers .= preg_quote($marker);
3614 $this->embeddablemarkers = $markers;
3616 return $this->embeddablemarkers;