2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
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
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') || die();
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
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
65 * @var string The requested rendering target.
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;
83 $this->target = $target;
87 * Returns rendered widget.
89 * The provided widget needs to be an object that extends the renderable
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
98 public function render(renderable $widget) {
99 $classname = get_class($widget);
101 $classname = preg_replace('/^.*\\\/', '', $classname);
102 // Remove _renderable suffixes
103 $classname = preg_replace('/_renderable$/', '', $classname);
105 $rendermethod = 'render_'.$classname;
106 if (method_exists($this, $rendermethod)) {
107 return $this->$rendermethod($widget);
109 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
113 * Adds a JS action for the element with the provided id.
115 * This method adds a JS event for the provided component action to the page
116 * and then returns the id that the event has been attached to.
117 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
119 * @param component_action $action
121 * @return string id of element, either original submitted or random new if not supplied
123 public function add_action_handler(component_action $action, $id = null) {
125 $id = html_writer::random_id($action->event);
127 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
132 * Returns true is output has already started, and false if not.
134 * @return boolean true if the header has been printed.
136 public function has_started() {
137 return $this->page->state >= moodle_page::STATE_IN_BODY;
141 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
143 * @param mixed $classes Space-separated string or array of classes
144 * @return string HTML class attribute value
146 public static function prepare_classes($classes) {
147 if (is_array($classes)) {
148 return implode(' ', array_unique($classes));
154 * Return the moodle_url for an image.
156 * The exact image location and extension is determined
157 * automatically by searching for gif|png|jpg|jpeg, please
158 * note there can not be diferent images with the different
159 * extension. The imagename is for historical reasons
160 * a relative path name, it may be changed later for core
161 * images. It is recommended to not use subdirectories
162 * in plugin and theme pix directories.
164 * There are three types of images:
165 * 1/ theme images - stored in theme/mytheme/pix/,
166 * use component 'theme'
167 * 2/ core images - stored in /pix/,
168 * overridden via theme/mytheme/pix_core/
169 * 3/ plugin images - stored in mod/mymodule/pix,
170 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
171 * example: pix_url('comment', 'mod_glossary')
173 * @param string $imagename the pathname of the image
174 * @param string $component full plugin name (aka component) or 'theme'
177 public function pix_url($imagename, $component = 'moodle') {
178 return $this->page->theme->pix_url($imagename, $component);
184 * Basis for all plugin renderers.
186 * @copyright Petr Skoda (skodak)
187 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
192 class plugin_renderer_base extends renderer_base {
195 * @var renderer_base|core_renderer A reference to the current renderer.
196 * The renderer provided here will be determined by the page but will in 90%
197 * of cases by the {@link core_renderer}
202 * Constructor method, calls the parent constructor
204 * @param moodle_page $page
205 * @param string $target one of rendering target constants
207 public function __construct(moodle_page $page, $target) {
208 if (empty($target) && $page->pagelayout === 'maintenance') {
209 // If the page is using the maintenance layout then we're going to force the target to maintenance.
210 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
211 // unavailable for this page layout.
212 $target = RENDERER_TARGET_MAINTENANCE;
214 $this->output = $page->get_renderer('core', null, $target);
215 parent::__construct($page, $target);
219 * Renders the provided widget and returns the HTML to display it.
221 * @param renderable $widget instance with renderable interface
224 public function render(renderable $widget) {
225 $classname = get_class($widget);
227 $classname = preg_replace('/^.*\\\/', '', $classname);
228 // Keep a copy at this point, we may need to look for a deprecated method.
229 $deprecatedmethod = 'render_'.$classname;
230 // Remove _renderable suffixes
231 $classname = preg_replace('/_renderable$/', '', $classname);
233 $rendermethod = 'render_'.$classname;
234 if (method_exists($this, $rendermethod)) {
235 return $this->$rendermethod($widget);
237 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
238 // This is exactly where we don't want to be.
239 // If you have arrived here you have a renderable component within your plugin that has the name
240 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
241 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
242 // and the _renderable suffix now gets removed when looking for a render method.
243 // You need to change your renderers render_blah_renderable to render_blah.
244 // Until you do this it will not be possible for a theme to override the renderer to override your method.
245 // Please do it ASAP.
246 static $debugged = array();
247 if (!isset($debugged[$deprecatedmethod])) {
248 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
249 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
250 $debugged[$deprecatedmethod] = true;
252 return $this->$deprecatedmethod($widget);
254 // pass to core renderer if method not found here
255 return $this->output->render($widget);
259 * Magic method used to pass calls otherwise meant for the standard renderer
260 * to it to ensure we don't go causing unnecessary grief.
262 * @param string $method
263 * @param array $arguments
266 public function __call($method, $arguments) {
267 if (method_exists('renderer_base', $method)) {
268 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
270 if (method_exists($this->output, $method)) {
271 return call_user_func_array(array($this->output, $method), $arguments);
273 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
280 * The standard implementation of the core_renderer interface.
282 * @copyright 2009 Tim Hunt
283 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
288 class core_renderer extends renderer_base {
290 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
291 * in layout files instead.
293 * @var string used in {@link core_renderer::header()}.
295 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
298 * @var string Used to pass information from {@link core_renderer::doctype()} to
299 * {@link core_renderer::standard_head_html()}.
301 protected $contenttype;
304 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
305 * with {@link core_renderer::header()}.
307 protected $metarefreshtag = '';
310 * @var string Unique token for the closing HTML
312 protected $unique_end_html_token;
315 * @var string Unique token for performance information
317 protected $unique_performance_info_token;
320 * @var string Unique token for the main content.
322 protected $unique_main_content_token;
327 * @param moodle_page $page the page we are doing output for.
328 * @param string $target one of rendering target constants
330 public function __construct(moodle_page $page, $target) {
331 $this->opencontainers = $page->opencontainers;
333 $this->target = $target;
335 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
336 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
337 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
341 * Get the DOCTYPE declaration that should be used with this page. Designed to
342 * be called in theme layout.php files.
344 * @return string the DOCTYPE declaration that should be used.
346 public function doctype() {
347 if ($this->page->theme->doctype === 'html5') {
348 $this->contenttype = 'text/html; charset=utf-8';
349 return "<!DOCTYPE html>\n";
351 } else if ($this->page->theme->doctype === 'xhtml5') {
352 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
353 return "<!DOCTYPE html>\n";
357 $this->contenttype = 'text/html; charset=utf-8';
358 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
363 * The attributes that should be added to the <html> tag. Designed to
364 * be called in theme layout.php files.
366 * @return string HTML fragment.
368 public function htmlattributes() {
369 $return = get_html_lang(true);
370 if ($this->page->theme->doctype !== 'html5') {
371 $return .= ' xmlns="http://www.w3.org/1999/xhtml"';
377 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
378 * that should be included in the <head> tag. Designed to be called in theme
381 * @return string HTML fragment.
383 public function standard_head_html() {
384 global $CFG, $SESSION;
386 // Before we output any content, we need to ensure that certain
387 // page components are set up.
389 // Blocks must be set up early as they may require javascript which
390 // has to be included in the page header before output is created.
391 foreach ($this->page->blocks->get_regions() as $region) {
392 $this->page->blocks->ensure_content_created($region, $this);
396 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
397 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
398 // This is only set by the {@link redirect()} method
399 $output .= $this->metarefreshtag;
401 // Check if a periodic refresh delay has been set and make sure we arn't
402 // already meta refreshing
403 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
404 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
407 // flow player embedding support
408 $this->page->requires->js_function_call('M.util.load_flowplayer');
410 // Set up help link popups for all links with the helptooltip class
411 $this->page->requires->js_init_call('M.util.help_popups.setup');
413 // Setup help icon overlays.
414 $this->page->requires->yui_module('moodle-core-popuphelp', 'M.core.init_popuphelp');
415 $this->page->requires->strings_for_js(array(
420 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
422 $focus = $this->page->focuscontrol;
423 if (!empty($focus)) {
424 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
425 // This is a horrifically bad way to handle focus but it is passed in
426 // through messy formslib::moodleform
427 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
428 } else if (strpos($focus, '.')!==false) {
429 // Old style of focus, bad way to do it
430 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);
431 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
433 // Focus element with given id
434 $this->page->requires->js_function_call('focuscontrol', array($focus));
438 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
439 // any other custom CSS can not be overridden via themes and is highly discouraged
440 $urls = $this->page->theme->css_urls($this->page);
441 foreach ($urls as $url) {
442 $this->page->requires->css_theme($url);
445 // Get the theme javascript head and footer
446 if ($jsurl = $this->page->theme->javascript_url(true)) {
447 $this->page->requires->js($jsurl, true);
449 if ($jsurl = $this->page->theme->javascript_url(false)) {
450 $this->page->requires->js($jsurl);
453 // Get any HTML from the page_requirements_manager.
454 $output .= $this->page->requires->get_head_code($this->page, $this);
456 // List alternate versions.
457 foreach ($this->page->alternateversions as $type => $alt) {
458 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
459 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
462 if (!empty($CFG->additionalhtmlhead)) {
463 $output .= "\n".$CFG->additionalhtmlhead;
470 * The standard tags (typically skip links) that should be output just inside
471 * the start of the <body> tag. Designed to be called in theme layout.php files.
473 * @return string HTML fragment.
475 public function standard_top_of_body_html() {
477 $output = $this->page->requires->get_top_of_body_code();
478 if (!empty($CFG->additionalhtmltopofbody)) {
479 $output .= "\n".$CFG->additionalhtmltopofbody;
481 $output .= $this->maintenance_warning();
486 * Scheduled maintenance warning message.
488 * Note: This is a nasty hack to display maintenance notice, this should be moved
489 * to some general notification area once we have it.
493 public function maintenance_warning() {
497 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
498 $timeleft = $CFG->maintenance_later - time();
499 // If timeleft less than 30 sec, set the class on block to error to highlight.
500 $errorclass = ($timeleft < 30) ? 'error' : 'warning';
501 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning');
503 $a->min = (int)($timeleft/60);
504 $a->sec = (int)($timeleft % 60);
505 $output .= get_string('maintenancemodeisscheduled', 'admin', $a) ;
506 $output .= $this->box_end();
507 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
508 array(array('timeleftinsec' => $timeleft)));
509 $this->page->requires->strings_for_js(
510 array('maintenancemodeisscheduled', 'sitemaintenance'),
517 * The standard tags (typically performance information and validation links,
518 * if we are in developer debug mode) that should be output in the footer area
519 * of the page. Designed to be called in theme layout.php files.
521 * @return string HTML fragment.
523 public function standard_footer_html() {
524 global $CFG, $SCRIPT;
526 if (during_initial_install()) {
527 // Debugging info can not work before install is finished,
528 // in any case we do not want any links during installation!
532 // This function is normally called from a layout.php file in {@link core_renderer::header()}
533 // but some of the content won't be known until later, so we return a placeholder
534 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
535 $output = $this->unique_performance_info_token;
536 if ($this->page->devicetypeinuse == 'legacy') {
537 // The legacy theme is in use print the notification
538 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
541 // Get links to switch device types (only shown for users not on a default device)
542 $output .= $this->theme_switch_links();
544 if (!empty($CFG->debugpageinfo)) {
545 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
547 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
548 // Add link to profiling report if necessary
549 if (function_exists('profiling_is_running') && profiling_is_running()) {
550 $txt = get_string('profiledscript', 'admin');
551 $title = get_string('profiledscriptview', 'admin');
552 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
553 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
554 $output .= '<div class="profilingfooter">' . $link . '</div>';
556 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
557 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
558 $output .= '<div class="purgecaches">' .
559 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
561 if (!empty($CFG->debugvalidators)) {
562 // 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
563 $output .= '<div class="validators"><ul>
564 <li><a href="http://validator.w3.org/check?verbose=1&ss=1&uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
565 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
566 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&warnp2n3e=1&url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
573 * Returns standard main content placeholder.
574 * Designed to be called in theme layout.php files.
576 * @return string HTML fragment.
578 public function main_content() {
579 // This is here because it is the only place we can inject the "main" role over the entire main content area
580 // without requiring all theme's to manually do it, and without creating yet another thing people need to
581 // remember in the theme.
582 // This is an unfortunate hack. DO NO EVER add anything more here.
583 // DO NOT add classes.
585 return '<div role="main">'.$this->unique_main_content_token.'</div>';
589 * The standard tags (typically script tags that are not needed earlier) that
590 * should be output after everything else. Designed to be called in theme layout.php files.
592 * @return string HTML fragment.
594 public function standard_end_of_body_html() {
597 // This function is normally called from a layout.php file in {@link core_renderer::header()}
598 // but some of the content won't be known until later, so we return a placeholder
599 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
601 if (!empty($CFG->additionalhtmlfooter)) {
602 $output .= "\n".$CFG->additionalhtmlfooter;
604 $output .= $this->unique_end_html_token;
609 * Return the standard string that says whether you are logged in (and switched
610 * roles/logged in as another user).
611 * @param bool $withlinks if false, then don't include any links in the HTML produced.
612 * If not set, the default is the nologinlinks option from the theme config.php file,
613 * and if that is not set, then links are included.
614 * @return string HTML fragment.
616 public function login_info($withlinks = null) {
617 global $USER, $CFG, $DB, $SESSION;
619 if (during_initial_install()) {
623 if (is_null($withlinks)) {
624 $withlinks = empty($this->page->layout_options['nologinlinks']);
627 $loginpage = ((string)$this->page->url === get_login_url());
628 $course = $this->page->course;
629 if (\core\session\manager::is_loggedinas()) {
630 $realuser = \core\session\manager::get_realuser();
631 $fullname = fullname($realuser, true);
633 $loginastitle = get_string('loginas');
634 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&sesskey=".sesskey()."\"";
635 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
637 $realuserinfo = " [$fullname] ";
643 $loginurl = get_login_url();
645 if (empty($course->id)) {
646 // $course->id is not defined during installation
648 } else if (isloggedin()) {
649 $context = context_course::instance($course->id);
651 $fullname = fullname($USER, true);
652 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
654 $linktitle = get_string('viewprofile');
655 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
657 $username = $fullname;
659 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
661 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
663 $username .= " from {$idprovider->name}";
667 $loggedinas = $realuserinfo.get_string('loggedinasguest');
668 if (!$loginpage && $withlinks) {
669 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
671 } else if (is_role_switched($course->id)) { // Has switched roles
673 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
674 $rolename = ': '.role_get_name($role, $context);
676 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
678 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
679 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
682 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
684 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
688 $loggedinas = get_string('loggedinnot', 'moodle');
689 if (!$loginpage && $withlinks) {
690 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
694 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
696 if (isset($SESSION->justloggedin)) {
697 unset($SESSION->justloggedin);
698 if (!empty($CFG->displayloginfailures)) {
699 if (!isguestuser()) {
700 // Include this file only when required.
701 require_once($CFG->dirroot . '/user/lib.php');
702 if ($count = user_count_login_failures($USER)) {
703 $loggedinas .= '<div class="loginfailures">';
705 $a->attempts = $count;
706 $loggedinas .= get_string('failedloginattempts', '', $a);
707 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
708 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
709 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
711 $loggedinas .= '</div>';
721 * Return the 'back' link that normally appears in the footer.
723 * @return string HTML fragment.
725 public function home_link() {
728 if ($this->page->pagetype == 'site-index') {
729 // Special case for site home page - please do not remove
730 return '<div class="sitelink">' .
731 '<a title="Moodle" href="http://moodle.org/">' .
732 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
734 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
735 // Special case for during install/upgrade.
736 return '<div class="sitelink">'.
737 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
738 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
740 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
741 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
742 get_string('home') . '</a></div>';
745 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
746 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
751 * Redirects the user by any means possible given the current state
753 * This function should not be called directly, it should always be called using
754 * the redirect function in lib/weblib.php
756 * The redirect function should really only be called before page output has started
757 * however it will allow itself to be called during the state STATE_IN_BODY
759 * @param string $encodedurl The URL to send to encoded if required
760 * @param string $message The message to display to the user if any
761 * @param int $delay The delay before redirecting a user, if $message has been
762 * set this is a requirement and defaults to 3, set to 0 no delay
763 * @param boolean $debugdisableredirect this redirect has been disabled for
764 * debugging purposes. Display a message that explains, and don't
765 * trigger the redirect.
766 * @return string The HTML to display to the user before dying, may contain
767 * meta refresh, javascript refresh, and may have set header redirects
769 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
771 $url = str_replace('&', '&', $encodedurl);
773 switch ($this->page->state) {
774 case moodle_page::STATE_BEFORE_HEADER :
775 // No output yet it is safe to delivery the full arsenal of redirect methods
776 if (!$debugdisableredirect) {
777 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
778 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
779 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
781 $output = $this->header();
783 case moodle_page::STATE_PRINTING_HEADER :
784 // We should hopefully never get here
785 throw new coding_exception('You cannot redirect while printing the page header');
787 case moodle_page::STATE_IN_BODY :
788 // We really shouldn't be here but we can deal with this
789 debugging("You should really redirect before you start page output");
790 if (!$debugdisableredirect) {
791 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
793 $output = $this->opencontainers->pop_all_but_last();
795 case moodle_page::STATE_DONE :
796 // Too late to be calling redirect now
797 throw new coding_exception('You cannot redirect after the entire page has been generated');
800 $output .= $this->notification($message, 'redirectmessage');
801 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
802 if ($debugdisableredirect) {
803 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
805 $output .= $this->footer();
810 * Start output by sending the HTTP headers, and printing the HTML <head>
811 * and the start of the <body>.
813 * To control what is printed, you should set properties on $PAGE. If you
814 * are familiar with the old {@link print_header()} function from Moodle 1.9
815 * you will find that there are properties on $PAGE that correspond to most
816 * of the old parameters to could be passed to print_header.
818 * Not that, in due course, the remaining $navigation, $menu parameters here
819 * will be replaced by more properties of $PAGE, but that is still to do.
821 * @return string HTML that you must output this, preferably immediately.
823 public function header() {
826 if (\core\session\manager::is_loggedinas()) {
827 $this->page->add_body_class('userloggedinas');
830 // Give themes a chance to init/alter the page object.
831 $this->page->theme->init_page($this->page);
833 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
835 // Find the appropriate page layout file, based on $this->page->pagelayout.
836 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
837 // Render the layout using the layout file.
838 $rendered = $this->render_page_layout($layoutfile);
840 // Slice the rendered output into header and footer.
841 $cutpos = strpos($rendered, $this->unique_main_content_token);
842 if ($cutpos === false) {
843 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
844 $token = self::MAIN_CONTENT_TOKEN;
846 $token = $this->unique_main_content_token;
849 if ($cutpos === false) {
850 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.');
852 $header = substr($rendered, 0, $cutpos);
853 $footer = substr($rendered, $cutpos + strlen($token));
855 if (empty($this->contenttype)) {
856 debugging('The page layout file did not call $OUTPUT->doctype()');
857 $header = $this->doctype() . $header;
860 // If this theme version is below 2.4 release and this is a course view page
861 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
862 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
863 // check if course content header/footer have not been output during render of theme layout
864 $coursecontentheader = $this->course_content_header(true);
865 $coursecontentfooter = $this->course_content_footer(true);
866 if (!empty($coursecontentheader)) {
867 // display debug message and add header and footer right above and below main content
868 // Please note that course header and footer (to be displayed above and below the whole page)
869 // are not displayed in this case at all.
870 // Besides the content header and footer are not displayed on any other course page
871 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);
872 $header .= $coursecontentheader;
873 $footer = $coursecontentfooter. $footer;
877 send_headers($this->contenttype, $this->page->cacheable);
879 $this->opencontainers->push('header/footer', $footer);
880 $this->page->set_state(moodle_page::STATE_IN_BODY);
882 return $header . $this->skip_link_target('maincontent');
886 * Renders and outputs the page layout file.
888 * This is done by preparing the normal globals available to a script, and
889 * then including the layout file provided by the current theme for the
892 * @param string $layoutfile The name of the layout file
893 * @return string HTML code
895 protected function render_page_layout($layoutfile) {
896 global $CFG, $SITE, $USER;
897 // The next lines are a bit tricky. The point is, here we are in a method
898 // of a renderer class, and this object may, or may not, be the same as
899 // the global $OUTPUT object. When rendering the page layout file, we want to use
900 // this object. However, people writing Moodle code expect the current
901 // renderer to be called $OUTPUT, not $this, so define a variable called
902 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
905 $COURSE = $this->page->course;
908 include($layoutfile);
909 $rendered = ob_get_contents();
915 * Outputs the page's footer
917 * @return string HTML fragment
919 public function footer() {
922 $output = $this->container_end_all(true);
924 $footer = $this->opencontainers->pop('header/footer');
926 if (debugging() and $DB and $DB->is_transaction_started()) {
927 // TODO: MDL-20625 print warning - transaction will be rolled back
930 // Provide some performance info if required
931 $performanceinfo = '';
932 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
933 $perf = get_performance_info();
934 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
935 $performanceinfo = $perf['html'];
939 // We always want performance data when running a performance test, even if the user is redirected to another page.
940 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
941 $footer = $this->unique_performance_info_token . $footer;
943 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
945 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
947 $this->page->set_state(moodle_page::STATE_DONE);
949 return $output . $footer;
953 * Close all but the last open container. This is useful in places like error
954 * handling, where you want to close all the open containers (apart from <body>)
955 * before outputting the error message.
957 * @param bool $shouldbenone assert that the stack should be empty now - causes a
958 * developer debug warning if it isn't.
959 * @return string the HTML required to close any open containers inside <body>.
961 public function container_end_all($shouldbenone = false) {
962 return $this->opencontainers->pop_all_but_last($shouldbenone);
966 * Returns course-specific information to be output immediately above content on any course page
967 * (for the current course)
969 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
972 public function course_content_header($onlyifnotcalledbefore = false) {
974 if ($this->page->course->id == SITEID) {
975 // return immediately and do not include /course/lib.php if not necessary
978 static $functioncalled = false;
979 if ($functioncalled && $onlyifnotcalledbefore) {
980 // we have already output the content header
983 require_once($CFG->dirroot.'/course/lib.php');
984 $functioncalled = true;
985 $courseformat = course_get_format($this->page->course);
986 if (($obj = $courseformat->course_content_header()) !== null) {
987 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
993 * Returns course-specific information to be output immediately below content on any course page
994 * (for the current course)
996 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
999 public function course_content_footer($onlyifnotcalledbefore = false) {
1001 if ($this->page->course->id == SITEID) {
1002 // return immediately and do not include /course/lib.php if not necessary
1005 static $functioncalled = false;
1006 if ($functioncalled && $onlyifnotcalledbefore) {
1007 // we have already output the content footer
1010 $functioncalled = true;
1011 require_once($CFG->dirroot.'/course/lib.php');
1012 $courseformat = course_get_format($this->page->course);
1013 if (($obj = $courseformat->course_content_footer()) !== null) {
1014 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1020 * Returns course-specific information to be output on any course page in the header area
1021 * (for the current course)
1025 public function course_header() {
1027 if ($this->page->course->id == SITEID) {
1028 // return immediately and do not include /course/lib.php if not necessary
1031 require_once($CFG->dirroot.'/course/lib.php');
1032 $courseformat = course_get_format($this->page->course);
1033 if (($obj = $courseformat->course_header()) !== null) {
1034 return $courseformat->get_renderer($this->page)->render($obj);
1040 * Returns course-specific information to be output on any course page in the footer area
1041 * (for the current course)
1045 public function course_footer() {
1047 if ($this->page->course->id == SITEID) {
1048 // return immediately and do not include /course/lib.php if not necessary
1051 require_once($CFG->dirroot.'/course/lib.php');
1052 $courseformat = course_get_format($this->page->course);
1053 if (($obj = $courseformat->course_footer()) !== null) {
1054 return $courseformat->get_renderer($this->page)->render($obj);
1060 * Returns lang menu or '', this method also checks forcing of languages in courses.
1062 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1064 * @return string The lang menu HTML or empty string
1066 public function lang_menu() {
1069 if (empty($CFG->langmenu)) {
1073 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1074 // do not show lang menu if language forced
1078 $currlang = current_language();
1079 $langs = get_string_manager()->get_list_of_translations();
1081 if (count($langs) < 2) {
1085 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1086 $s->label = get_accesshide(get_string('language'));
1087 $s->class = 'langmenu';
1088 return $this->render($s);
1092 * Output the row of editing icons for a block, as defined by the controls array.
1094 * @param array $controls an array like {@link block_contents::$controls}.
1095 * @param string $blockid The ID given to the block.
1096 * @return string HTML fragment.
1098 public function block_controls($actions, $blockid = null) {
1100 if (empty($actions)) {
1103 $menu = new action_menu($actions);
1104 if ($blockid !== null) {
1105 $menu->set_owner_selector('#'.$blockid);
1107 $menu->set_constraint('.block-region');
1108 $menu->attributes['class'] .= ' block-control-actions commands';
1109 if (isset($CFG->blockeditingmenu) && !$CFG->blockeditingmenu) {
1110 $menu->do_not_enhance();
1112 return $this->render($menu);
1116 * Renders an action menu component.
1119 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1120 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1122 * @param action_menu $menu
1123 * @return string HTML
1125 public function render_action_menu(action_menu $menu) {
1126 $menu->initialise_js($this->page);
1128 $output = html_writer::start_tag('div', $menu->attributes);
1129 $output .= html_writer::start_tag('ul', $menu->attributesprimary);
1130 foreach ($menu->get_primary_actions($this) as $action) {
1131 if ($action instanceof renderable) {
1132 $content = $this->render($action);
1136 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1138 $output .= html_writer::end_tag('ul');
1139 $output .= html_writer::start_tag('ul', $menu->attributessecondary);
1140 foreach ($menu->get_secondary_actions() as $action) {
1141 if ($action instanceof renderable) {
1142 $content = $this->render($action);
1146 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1148 $output .= html_writer::end_tag('ul');
1149 $output .= html_writer::end_tag('div');
1154 * Renders an action_menu_link item.
1156 * @param action_menu_link $action
1157 * @return string HTML fragment
1159 protected function render_action_menu_link(action_menu_link $action) {
1160 static $actioncount = 0;
1165 if (!$action->icon || $action->primary === false) {
1166 $text .= html_writer::start_tag('span', array('class'=>'menu-action-text', 'id' => 'actionmenuaction-'.$actioncount));
1167 if ($action->text instanceof renderable) {
1168 $text .= $this->render($action->text);
1170 $text .= $action->text;
1171 $comparetoalt = (string)$action->text;
1173 $text .= html_writer::end_tag('span');
1177 if ($action->icon) {
1178 $icon = $action->icon;
1179 if ($action->primary || !$action->actionmenu->will_be_enhanced()) {
1180 $action->attributes['title'] = $action->text;
1182 if (!$action->primary && $action->actionmenu->will_be_enhanced()) {
1183 if ((string)$icon->attributes['alt'] === $comparetoalt) {
1184 $icon->attributes['alt'] = '';
1186 if (isset($icon->attributes['title']) && (string)$icon->attributes['title'] === $comparetoalt) {
1187 unset($icon->attributes['title']);
1190 $icon = $this->render($icon);
1193 // A disabled link is rendered as formatted text.
1194 if (!empty($action->attributes['disabled'])) {
1195 // Do not use div here due to nesting restriction in xhtml strict.
1196 return html_writer::tag('span', $icon.$text, array('class'=>'currentlink', 'role' => 'menuitem'));
1199 $attributes = $action->attributes;
1200 unset($action->attributes['disabled']);
1201 $attributes['href'] = $action->url;
1203 $attributes['aria-labelledby'] = 'actionmenuaction-'.$actioncount;
1206 return html_writer::tag('a', $icon.$text, $attributes);
1210 * Renders a primary action_menu_filler item.
1212 * @param action_menu_link_filler $action
1213 * @return string HTML fragment
1215 protected function render_action_menu_filler(action_menu_filler $action) {
1216 return html_writer::span(' ', 'filler');
1220 * Renders a primary action_menu_link item.
1222 * @param action_menu_link_primary $action
1223 * @return string HTML fragment
1225 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1226 return $this->render_action_menu_link($action);
1230 * Renders a secondary action_menu_link item.
1232 * @param action_menu_link_secondary $action
1233 * @return string HTML fragment
1235 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1236 return $this->render_action_menu_link($action);
1240 * Prints a nice side block with an optional header.
1242 * The content is described
1243 * by a {@link core_renderer::block_contents} object.
1245 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1246 * <div class="header"></div>
1247 * <div class="content">
1249 * <div class="footer">
1252 * <div class="annotation">
1256 * @param block_contents $bc HTML for the content
1257 * @param string $region the region the block is appearing in.
1258 * @return string the HTML to be output.
1260 public function block(block_contents $bc, $region) {
1261 $bc = clone($bc); // Avoid messing up the object passed in.
1262 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1263 $bc->collapsible = block_contents::NOT_HIDEABLE;
1265 if (!empty($bc->blockinstanceid)) {
1266 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1268 $skiptitle = strip_tags($bc->title);
1269 if ($bc->blockinstanceid && !empty($skiptitle)) {
1270 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1271 } else if (!empty($bc->arialabel)) {
1272 $bc->attributes['aria-label'] = $bc->arialabel;
1274 if ($bc->dockable) {
1275 $bc->attributes['data-dockable'] = 1;
1277 if ($bc->collapsible == block_contents::HIDDEN) {
1278 $bc->add_class('hidden');
1280 if (!empty($bc->controls)) {
1281 $bc->add_class('block_with_controls');
1285 if (empty($skiptitle)) {
1289 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
1290 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
1293 $output .= html_writer::start_tag('div', $bc->attributes);
1295 $output .= $this->block_header($bc);
1296 $output .= $this->block_content($bc);
1298 $output .= html_writer::end_tag('div');
1300 $output .= $this->block_annotation($bc);
1302 $output .= $skipdest;
1304 $this->init_block_hider_js($bc);
1309 * Produces a header for a block
1311 * @param block_contents $bc
1314 protected function block_header(block_contents $bc) {
1318 $attributes = array();
1319 if ($bc->blockinstanceid) {
1320 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1322 $title = html_writer::tag('h2', $bc->title, $attributes);
1326 if (isset($bc->attributes['id'])) {
1327 $blockid = $bc->attributes['id'];
1329 $controlshtml = $this->block_controls($bc->controls, $blockid);
1332 if ($title || $controlshtml) {
1333 $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'));
1339 * Produces the content area for a block
1341 * @param block_contents $bc
1344 protected function block_content(block_contents $bc) {
1345 $output = html_writer::start_tag('div', array('class' => 'content'));
1346 if (!$bc->title && !$this->block_controls($bc->controls)) {
1347 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1349 $output .= $bc->content;
1350 $output .= $this->block_footer($bc);
1351 $output .= html_writer::end_tag('div');
1357 * Produces the footer for a block
1359 * @param block_contents $bc
1362 protected function block_footer(block_contents $bc) {
1365 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1371 * Produces the annotation for a block
1373 * @param block_contents $bc
1376 protected function block_annotation(block_contents $bc) {
1378 if ($bc->annotation) {
1379 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1385 * Calls the JS require function to hide a block.
1387 * @param block_contents $bc A block_contents object
1389 protected function init_block_hider_js(block_contents $bc) {
1390 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1391 $config = new stdClass;
1392 $config->id = $bc->attributes['id'];
1393 $config->title = strip_tags($bc->title);
1394 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1395 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1396 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1398 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1399 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1404 * Render the contents of a block_list.
1406 * @param array $icons the icon for each item.
1407 * @param array $items the content of each item.
1408 * @return string HTML
1410 public function list_block_contents($icons, $items) {
1413 foreach ($items as $key => $string) {
1414 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1415 if (!empty($icons[$key])) { //test if the content has an assigned icon
1416 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1418 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1419 $item .= html_writer::end_tag('li');
1421 $row = 1 - $row; // Flip even/odd.
1423 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1427 * Output all the blocks in a particular region.
1429 * @param string $region the name of a region on this page.
1430 * @return string the HTML to be output.
1432 public function blocks_for_region($region) {
1433 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1434 $blocks = $this->page->blocks->get_blocks_for_region($region);
1437 foreach ($blocks as $block) {
1438 $zones[] = $block->title;
1442 foreach ($blockcontents as $bc) {
1443 if ($bc instanceof block_contents) {
1444 $output .= $this->block($bc, $region);
1445 $lastblock = $bc->title;
1446 } else if ($bc instanceof block_move_target) {
1447 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1449 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1456 * Output a place where the block that is currently being moved can be dropped.
1458 * @param block_move_target $target with the necessary details.
1459 * @param array $zones array of areas where the block can be moved to
1460 * @param string $previous the block located before the area currently being rendered.
1461 * @param string $region the name of the region
1462 * @return string the HTML to be output.
1464 public function block_move_target($target, $zones, $previous, $region) {
1465 if ($previous == null) {
1466 if (empty($zones)) {
1467 // There are no zones, probably because there are no blocks.
1468 $regions = $this->page->theme->get_all_block_regions();
1469 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1471 $position = get_string('moveblockbefore', 'block', $zones[0]);
1474 $position = get_string('moveblockafter', 'block', $previous);
1476 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1480 * Renders a special html link with attached action
1482 * Theme developers: DO NOT OVERRIDE! Please override function
1483 * {@link core_renderer::render_action_link()} instead.
1485 * @param string|moodle_url $url
1486 * @param string $text HTML fragment
1487 * @param component_action $action
1488 * @param array $attributes associative array of html link attributes + disabled
1489 * @param pix_icon optional pix icon to render with the link
1490 * @return string HTML fragment
1492 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1493 if (!($url instanceof moodle_url)) {
1494 $url = new moodle_url($url);
1496 $link = new action_link($url, $text, $action, $attributes, $icon);
1498 return $this->render($link);
1502 * Renders an action_link object.
1504 * The provided link is renderer and the HTML returned. At the same time the
1505 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1507 * @param action_link $link
1508 * @return string HTML fragment
1510 protected function render_action_link(action_link $link) {
1515 $text .= $this->render($link->icon);
1518 if ($link->text instanceof renderable) {
1519 $text .= $this->render($link->text);
1521 $text .= $link->text;
1524 // A disabled link is rendered as formatted text
1525 if (!empty($link->attributes['disabled'])) {
1526 // do not use div here due to nesting restriction in xhtml strict
1527 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1530 $attributes = $link->attributes;
1531 unset($link->attributes['disabled']);
1532 $attributes['href'] = $link->url;
1534 if ($link->actions) {
1535 if (empty($attributes['id'])) {
1536 $id = html_writer::random_id('action_link');
1537 $attributes['id'] = $id;
1539 $id = $attributes['id'];
1541 foreach ($link->actions as $action) {
1542 $this->add_action_handler($action, $id);
1546 return html_writer::tag('a', $text, $attributes);
1551 * Renders an action_icon.
1553 * This function uses the {@link core_renderer::action_link()} method for the
1554 * most part. What it does different is prepare the icon as HTML and use it
1557 * Theme developers: If you want to change how action links and/or icons are rendered,
1558 * consider overriding function {@link core_renderer::render_action_link()} and
1559 * {@link core_renderer::render_pix_icon()}.
1561 * @param string|moodle_url $url A string URL or moodel_url
1562 * @param pix_icon $pixicon
1563 * @param component_action $action
1564 * @param array $attributes associative array of html link attributes + disabled
1565 * @param bool $linktext show title next to image in link
1566 * @return string HTML fragment
1568 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1569 if (!($url instanceof moodle_url)) {
1570 $url = new moodle_url($url);
1572 $attributes = (array)$attributes;
1574 if (empty($attributes['class'])) {
1575 // let ppl override the class via $options
1576 $attributes['class'] = 'action-icon';
1579 $icon = $this->render($pixicon);
1582 $text = $pixicon->attributes['alt'];
1587 return $this->action_link($url, $text.$icon, $action, $attributes);
1591 * Print a message along with button choices for Continue/Cancel
1593 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1595 * @param string $message The question to ask the user
1596 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1597 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1598 * @return string HTML fragment
1600 public function confirm($message, $continue, $cancel) {
1601 if ($continue instanceof single_button) {
1603 } else if (is_string($continue)) {
1604 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1605 } else if ($continue instanceof moodle_url) {
1606 $continue = new single_button($continue, get_string('continue'), 'post');
1608 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1611 if ($cancel instanceof single_button) {
1613 } else if (is_string($cancel)) {
1614 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1615 } else if ($cancel instanceof moodle_url) {
1616 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1618 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1621 $output = $this->box_start('generalbox', 'notice');
1622 $output .= html_writer::tag('p', $message);
1623 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1624 $output .= $this->box_end();
1629 * Returns a form with a single button.
1631 * Theme developers: DO NOT OVERRIDE! Please override function
1632 * {@link core_renderer::render_single_button()} instead.
1634 * @param string|moodle_url $url
1635 * @param string $label button text
1636 * @param string $method get or post submit method
1637 * @param array $options associative array {disabled, title, etc.}
1638 * @return string HTML fragment
1640 public function single_button($url, $label, $method='post', array $options=null) {
1641 if (!($url instanceof moodle_url)) {
1642 $url = new moodle_url($url);
1644 $button = new single_button($url, $label, $method);
1646 foreach ((array)$options as $key=>$value) {
1647 if (array_key_exists($key, $button)) {
1648 $button->$key = $value;
1652 return $this->render($button);
1656 * Renders a single button widget.
1658 * This will return HTML to display a form containing a single button.
1660 * @param single_button $button
1661 * @return string HTML fragment
1663 protected function render_single_button(single_button $button) {
1664 $attributes = array('type' => 'submit',
1665 'value' => $button->label,
1666 'disabled' => $button->disabled ? 'disabled' : null,
1667 'title' => $button->tooltip);
1669 if ($button->actions) {
1670 $id = html_writer::random_id('single_button');
1671 $attributes['id'] = $id;
1672 foreach ($button->actions as $action) {
1673 $this->add_action_handler($action, $id);
1677 // first the input element
1678 $output = html_writer::empty_tag('input', $attributes);
1680 // then hidden fields
1681 $params = $button->url->params();
1682 if ($button->method === 'post') {
1683 $params['sesskey'] = sesskey();
1685 foreach ($params as $var => $val) {
1686 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1689 // then div wrapper for xhtml strictness
1690 $output = html_writer::tag('div', $output);
1692 // now the form itself around it
1693 if ($button->method === 'get') {
1694 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1696 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1699 $url = '#'; // there has to be always some action
1701 $attributes = array('method' => $button->method,
1703 'id' => $button->formid);
1704 $output = html_writer::tag('form', $output, $attributes);
1706 // and finally one more wrapper with class
1707 return html_writer::tag('div', $output, array('class' => $button->class));
1711 * Returns a form with a single select widget.
1713 * Theme developers: DO NOT OVERRIDE! Please override function
1714 * {@link core_renderer::render_single_select()} instead.
1716 * @param moodle_url $url form action target, includes hidden fields
1717 * @param string $name name of selection field - the changing parameter in url
1718 * @param array $options list of options
1719 * @param string $selected selected element
1720 * @param array $nothing
1721 * @param string $formid
1722 * @return string HTML fragment
1724 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1725 if (!($url instanceof moodle_url)) {
1726 $url = new moodle_url($url);
1728 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1730 return $this->render($select);
1734 * Internal implementation of single_select rendering
1736 * @param single_select $select
1737 * @return string HTML fragment
1739 protected function render_single_select(single_select $select) {
1740 $select = clone($select);
1741 if (empty($select->formid)) {
1742 $select->formid = html_writer::random_id('single_select_f');
1746 $params = $select->url->params();
1747 if ($select->method === 'post') {
1748 $params['sesskey'] = sesskey();
1750 foreach ($params as $name=>$value) {
1751 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1754 if (empty($select->attributes['id'])) {
1755 $select->attributes['id'] = html_writer::random_id('single_select');
1758 if ($select->disabled) {
1759 $select->attributes['disabled'] = 'disabled';
1762 if ($select->tooltip) {
1763 $select->attributes['title'] = $select->tooltip;
1766 $select->attributes['class'] = 'autosubmit';
1767 if ($select->class) {
1768 $select->attributes['class'] .= ' ' . $select->class;
1771 if ($select->label) {
1772 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1775 if ($select->helpicon instanceof help_icon) {
1776 $output .= $this->render($select->helpicon);
1778 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1780 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1781 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1783 $nothing = empty($select->nothing) ? false : key($select->nothing);
1784 $this->page->requires->yui_module('moodle-core-formautosubmit',
1785 'M.core.init_formautosubmit',
1786 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1789 // then div wrapper for xhtml strictness
1790 $output = html_writer::tag('div', $output);
1792 // now the form itself around it
1793 if ($select->method === 'get') {
1794 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1796 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1798 $formattributes = array('method' => $select->method,
1800 'id' => $select->formid);
1801 $output = html_writer::tag('form', $output, $formattributes);
1803 // and finally one more wrapper with class
1804 return html_writer::tag('div', $output, array('class' => $select->class));
1808 * Returns a form with a url select widget.
1810 * Theme developers: DO NOT OVERRIDE! Please override function
1811 * {@link core_renderer::render_url_select()} instead.
1813 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1814 * @param string $selected selected element
1815 * @param array $nothing
1816 * @param string $formid
1817 * @return string HTML fragment
1819 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1820 $select = new url_select($urls, $selected, $nothing, $formid);
1821 return $this->render($select);
1825 * Internal implementation of url_select rendering
1827 * @param url_select $select
1828 * @return string HTML fragment
1830 protected function render_url_select(url_select $select) {
1833 $select = clone($select);
1834 if (empty($select->formid)) {
1835 $select->formid = html_writer::random_id('url_select_f');
1838 if (empty($select->attributes['id'])) {
1839 $select->attributes['id'] = html_writer::random_id('url_select');
1842 if ($select->disabled) {
1843 $select->attributes['disabled'] = 'disabled';
1846 if ($select->tooltip) {
1847 $select->attributes['title'] = $select->tooltip;
1852 if ($select->label) {
1853 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1857 if (!$select->showbutton) {
1858 $classes[] = 'autosubmit';
1860 if ($select->class) {
1861 $classes[] = $select->class;
1863 if (count($classes)) {
1864 $select->attributes['class'] = implode(' ', $classes);
1867 if ($select->helpicon instanceof help_icon) {
1868 $output .= $this->render($select->helpicon);
1871 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1872 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1874 foreach ($select->urls as $k=>$v) {
1876 // optgroup structure
1877 foreach ($v as $optgrouptitle => $optgroupoptions) {
1878 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1879 if (empty($optionurl)) {
1880 $safeoptionurl = '';
1881 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1882 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1883 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1884 } else if (strpos($optionurl, '/') !== 0) {
1885 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1888 $safeoptionurl = $optionurl;
1890 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1894 // plain list structure
1896 // nothing selected option
1897 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1898 $k = str_replace($CFG->wwwroot, '', $k);
1899 } else if (strpos($k, '/') !== 0) {
1900 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1906 $selected = $select->selected;
1907 if (!empty($selected)) {
1908 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1909 $selected = str_replace($CFG->wwwroot, '', $selected);
1910 } else if (strpos($selected, '/') !== 0) {
1911 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1915 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1916 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1918 if (!$select->showbutton) {
1919 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1920 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1921 $nothing = empty($select->nothing) ? false : key($select->nothing);
1922 $this->page->requires->yui_module('moodle-core-formautosubmit',
1923 'M.core.init_formautosubmit',
1924 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1927 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1930 // then div wrapper for xhtml strictness
1931 $output = html_writer::tag('div', $output);
1933 // now the form itself around it
1934 $formattributes = array('method' => 'post',
1935 'action' => new moodle_url('/course/jumpto.php'),
1936 'id' => $select->formid);
1937 $output = html_writer::tag('form', $output, $formattributes);
1939 // and finally one more wrapper with class
1940 return html_writer::tag('div', $output, array('class' => $select->class));
1944 * Returns a string containing a link to the user documentation.
1945 * Also contains an icon by default. Shown to teachers and admin only.
1947 * @param string $path The page link after doc root and language, no leading slash.
1948 * @param string $text The text to be displayed for the link
1949 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
1952 public function doc_link($path, $text = '', $forcepopup = false) {
1955 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp icon-pre'));
1957 $url = new moodle_url(get_docs_url($path));
1959 $attributes = array('href'=>$url);
1960 if (!empty($CFG->doctonewwindow) || $forcepopup) {
1961 $attributes['class'] = 'helplinkpopup';
1964 return html_writer::tag('a', $icon.$text, $attributes);
1968 * Return HTML for a pix_icon.
1970 * Theme developers: DO NOT OVERRIDE! Please override function
1971 * {@link core_renderer::render_pix_icon()} instead.
1973 * @param string $pix short pix name
1974 * @param string $alt mandatory alt attribute
1975 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1976 * @param array $attributes htm lattributes
1977 * @return string HTML fragment
1979 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1980 $icon = new pix_icon($pix, $alt, $component, $attributes);
1981 return $this->render($icon);
1985 * Renders a pix_icon widget and returns the HTML to display it.
1987 * @param pix_icon $icon
1988 * @return string HTML fragment
1990 protected function render_pix_icon(pix_icon $icon) {
1991 $attributes = $icon->attributes;
1992 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1993 return html_writer::empty_tag('img', $attributes);
1997 * Return HTML to display an emoticon icon.
1999 * @param pix_emoticon $emoticon
2000 * @return string HTML fragment
2002 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2003 $attributes = $emoticon->attributes;
2004 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
2005 return html_writer::empty_tag('img', $attributes);
2009 * Produces the html that represents this rating in the UI
2011 * @param rating $rating the page object on which this rating will appear
2014 function render_rating(rating $rating) {
2017 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2018 return null;//ratings are turned off
2021 $ratingmanager = new rating_manager();
2022 // Initialise the JavaScript so ratings can be done by AJAX.
2023 $ratingmanager->initialise_rating_javascript($this->page);
2025 $strrate = get_string("rate", "rating");
2026 $ratinghtml = ''; //the string we'll return
2028 // permissions check - can they view the aggregate?
2029 if ($rating->user_can_view_aggregate()) {
2031 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2032 $aggregatestr = $rating->get_aggregate_string();
2034 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2035 if ($rating->count > 0) {
2036 $countstr = "({$rating->count})";
2040 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2042 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2043 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2045 $nonpopuplink = $rating->get_view_ratings_url();
2046 $popuplink = $rating->get_view_ratings_url(true);
2048 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2049 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2051 $ratinghtml .= $aggregatehtml;
2056 // if the item doesn't belong to the current user, the user has permission to rate
2057 // and we're within the assessable period
2058 if ($rating->user_can_rate()) {
2060 $rateurl = $rating->get_rate_url();
2061 $inputs = $rateurl->params();
2063 //start the rating form
2065 'id' => "postrating{$rating->itemid}",
2066 'class' => 'postratingform',
2068 'action' => $rateurl->out_omit_querystring()
2070 $formstart = html_writer::start_tag('form', $formattrs);
2071 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2073 // add the hidden inputs
2074 foreach ($inputs as $name => $value) {
2075 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2076 $formstart .= html_writer::empty_tag('input', $attributes);
2079 if (empty($ratinghtml)) {
2080 $ratinghtml .= $strrate.': ';
2082 $ratinghtml = $formstart.$ratinghtml;
2084 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2085 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2086 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2087 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2089 //output submit button
2090 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2092 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2093 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2095 if (!$rating->settings->scale->isnumeric) {
2096 // If a global scale, try to find current course ID from the context
2097 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2098 $courseid = $coursecontext->instanceid;
2100 $courseid = $rating->settings->scale->courseid;
2102 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2104 $ratinghtml .= html_writer::end_tag('span');
2105 $ratinghtml .= html_writer::end_tag('div');
2106 $ratinghtml .= html_writer::end_tag('form');
2113 * Centered heading with attached help button (same title text)
2114 * and optional icon attached.
2116 * @param string $text A heading text
2117 * @param string $helpidentifier The keyword that defines a help page
2118 * @param string $component component name
2119 * @param string|moodle_url $icon
2120 * @param string $iconalt icon alt text
2121 * @param int $level The level of importance of the heading. Defaulting to 2
2122 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2123 * @return string HTML fragment
2125 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2128 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2132 if ($helpidentifier) {
2133 $help = $this->help_icon($helpidentifier, $component);
2136 return $this->heading($image.$text.$help, $level, $classnames);
2140 * Returns HTML to display a help icon.
2142 * @deprecated since Moodle 2.0
2144 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2145 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2149 * Returns HTML to display a help icon.
2151 * Theme developers: DO NOT OVERRIDE! Please override function
2152 * {@link core_renderer::render_help_icon()} instead.
2154 * @param string $identifier The keyword that defines a help page
2155 * @param string $component component name
2156 * @param string|bool $linktext true means use $title as link text, string means link text value
2157 * @return string HTML fragment
2159 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2160 $icon = new help_icon($identifier, $component);
2161 $icon->diag_strings();
2162 if ($linktext === true) {
2163 $icon->linktext = get_string($icon->identifier, $icon->component);
2164 } else if (!empty($linktext)) {
2165 $icon->linktext = $linktext;
2167 return $this->render($icon);
2171 * Implementation of user image rendering.
2173 * @param help_icon $helpicon A help icon instance
2174 * @return string HTML fragment
2176 protected function render_help_icon(help_icon $helpicon) {
2179 // first get the help image icon
2180 $src = $this->pix_url('help');
2182 $title = get_string($helpicon->identifier, $helpicon->component);
2184 if (empty($helpicon->linktext)) {
2185 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
2187 $alt = get_string('helpwiththis');
2190 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
2191 $output = html_writer::empty_tag('img', $attributes);
2193 // add the link text if given
2194 if (!empty($helpicon->linktext)) {
2195 // the spacing has to be done through CSS
2196 $output .= $helpicon->linktext;
2199 // now create the link around it - we need https on loginhttps pages
2200 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
2202 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
2203 $title = get_string('helpprefix2', '', trim($title, ". \t"));
2205 $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true', 'target'=>'_blank');
2206 $output = html_writer::tag('a', $output, $attributes);
2209 return html_writer::tag('span', $output, array('class' => 'helptooltip'));
2213 * Returns HTML to display a scale help icon.
2215 * @param int $courseid
2216 * @param stdClass $scale instance
2217 * @return string HTML fragment
2219 public function help_icon_scale($courseid, stdClass $scale) {
2222 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2224 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2226 $scaleid = abs($scale->id);
2228 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2229 $action = new popup_action('click', $link, 'ratingscale');
2231 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2235 * Creates and returns a spacer image with optional line break.
2237 * @param array $attributes Any HTML attributes to add to the spaced.
2238 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2239 * laxy do it with CSS which is a much better solution.
2240 * @return string HTML fragment
2242 public function spacer(array $attributes = null, $br = false) {
2243 $attributes = (array)$attributes;
2244 if (empty($attributes['width'])) {
2245 $attributes['width'] = 1;
2247 if (empty($attributes['height'])) {
2248 $attributes['height'] = 1;
2250 $attributes['class'] = 'spacer';
2252 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2255 $output .= '<br />';
2262 * Returns HTML to display the specified user's avatar.
2264 * User avatar may be obtained in two ways:
2266 * // Option 1: (shortcut for simple cases, preferred way)
2267 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2268 * $OUTPUT->user_picture($user, array('popup'=>true));
2271 * $userpic = new user_picture($user);
2272 * // Set properties of $userpic
2273 * $userpic->popup = true;
2274 * $OUTPUT->render($userpic);
2277 * Theme developers: DO NOT OVERRIDE! Please override function
2278 * {@link core_renderer::render_user_picture()} instead.
2280 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2281 * If any of these are missing, the database is queried. Avoid this
2282 * if at all possible, particularly for reports. It is very bad for performance.
2283 * @param array $options associative array with user picture options, used only if not a user_picture object,
2285 * - courseid=$this->page->course->id (course id of user profile in link)
2286 * - size=35 (size of image)
2287 * - link=true (make image clickable - the link leads to user profile)
2288 * - popup=false (open in popup)
2289 * - alttext=true (add image alt attribute)
2290 * - class = image class attribute (default 'userpicture')
2291 * @return string HTML fragment
2293 public function user_picture(stdClass $user, array $options = null) {
2294 $userpicture = new user_picture($user);
2295 foreach ((array)$options as $key=>$value) {
2296 if (array_key_exists($key, $userpicture)) {
2297 $userpicture->$key = $value;
2300 return $this->render($userpicture);
2304 * Internal implementation of user image rendering.
2306 * @param user_picture $userpicture
2309 protected function render_user_picture(user_picture $userpicture) {
2312 $user = $userpicture->user;
2314 if ($userpicture->alttext) {
2315 if (!empty($user->imagealt)) {
2316 $alt = $user->imagealt;
2318 $alt = get_string('pictureof', '', fullname($user));
2324 if (empty($userpicture->size)) {
2326 } else if ($userpicture->size === true or $userpicture->size == 1) {
2329 $size = $userpicture->size;
2332 $class = $userpicture->class;
2334 if ($user->picture == 0) {
2335 $class .= ' defaultuserpic';
2338 $src = $userpicture->get_url($this->page, $this);
2340 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2342 // get the image html output fisrt
2343 $output = html_writer::empty_tag('img', $attributes);
2345 // then wrap it in link if needed
2346 if (!$userpicture->link) {
2350 if (empty($userpicture->courseid)) {
2351 $courseid = $this->page->course->id;
2353 $courseid = $userpicture->courseid;
2356 if ($courseid == SITEID) {
2357 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2359 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2362 $attributes = array('href'=>$url);
2364 if ($userpicture->popup) {
2365 $id = html_writer::random_id('userpicture');
2366 $attributes['id'] = $id;
2367 $this->add_action_handler(new popup_action('click', $url), $id);
2370 return html_writer::tag('a', $output, $attributes);
2374 * Internal implementation of file tree viewer items rendering.
2379 public function htmllize_file_tree($dir) {
2380 if (empty($dir['subdirs']) and empty($dir['files'])) {
2384 foreach ($dir['subdirs'] as $subdir) {
2385 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2387 foreach ($dir['files'] as $file) {
2388 $filename = $file->get_filename();
2389 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2397 * Returns HTML to display the file picker
2400 * $OUTPUT->file_picker($options);
2403 * Theme developers: DO NOT OVERRIDE! Please override function
2404 * {@link core_renderer::render_file_picker()} instead.
2406 * @param array $options associative array with file manager options
2410 * client_id=>uniqid(),
2411 * acepted_types=>'*',
2412 * return_types=>FILE_INTERNAL,
2413 * context=>$PAGE->context
2414 * @return string HTML fragment
2416 public function file_picker($options) {
2417 $fp = new file_picker($options);
2418 return $this->render($fp);
2422 * Internal implementation of file picker rendering.
2424 * @param file_picker $fp
2427 public function render_file_picker(file_picker $fp) {
2428 global $CFG, $OUTPUT, $USER;
2429 $options = $fp->options;
2430 $client_id = $options->client_id;
2431 $strsaved = get_string('filesaved', 'repository');
2432 $straddfile = get_string('openpicker', 'repository');
2433 $strloading = get_string('loading', 'repository');
2434 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2435 $strdroptoupload = get_string('droptoupload', 'moodle');
2436 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2438 $currentfile = $options->currentfile;
2439 if (empty($currentfile)) {
2442 $currentfile .= ' - ';
2444 if ($options->maxbytes) {
2445 $size = $options->maxbytes;
2447 $size = get_max_upload_file_size();
2452 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2454 if ($options->buttonname) {
2455 $buttonname = ' name="' . $options->buttonname . '"';
2460 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2463 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2465 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2466 <span> $maxsize </span>
2469 if ($options->env != 'url') {
2471 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2472 <div class="filepicker-filename">
2473 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2474 <div class="dndupload-progressbars"></div>
2476 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2485 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2487 * @param string $cmid the course_module id.
2488 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2489 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2491 public function update_module_button($cmid, $modulename) {
2493 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2494 $modulename = get_string('modulename', $modulename);
2495 $string = get_string('updatethis', '', $modulename);
2496 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2497 return $this->single_button($url, $string);
2504 * Returns HTML to display a "Turn editing on/off" button in a form.
2506 * @param moodle_url $url The URL + params to send through when clicking the button
2507 * @return string HTML the button
2509 public function edit_button(moodle_url $url) {
2511 $url->param('sesskey', sesskey());
2512 if ($this->page->user_is_editing()) {
2513 $url->param('edit', 'off');
2514 $editstring = get_string('turneditingoff');
2516 $url->param('edit', 'on');
2517 $editstring = get_string('turneditingon');
2520 return $this->single_button($url, $editstring);
2524 * Returns HTML to display a simple button to close a window
2526 * @param string $text The lang string for the button's label (already output from get_string())
2527 * @return string html fragment
2529 public function close_window_button($text='') {
2531 $text = get_string('closewindow');
2533 $button = new single_button(new moodle_url('#'), $text, 'get');
2534 $button->add_action(new component_action('click', 'close_window'));
2536 return $this->container($this->render($button), 'closewindow');
2540 * Output an error message. By default wraps the error message in <span class="error">.
2541 * If the error message is blank, nothing is output.
2543 * @param string $message the error message.
2544 * @return string the HTML to output.
2546 public function error_text($message) {
2547 if (empty($message)) {
2550 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2551 return html_writer::tag('span', $message, array('class' => 'error'));
2555 * Do not call this function directly.
2557 * To terminate the current script with a fatal error, call the {@link print_error}
2558 * function, or throw an exception. Doing either of those things will then call this
2559 * function to display the error, before terminating the execution.
2561 * @param string $message The message to output
2562 * @param string $moreinfourl URL where more info can be found about the error
2563 * @param string $link Link for the Continue button
2564 * @param array $backtrace The execution backtrace
2565 * @param string $debuginfo Debugging information
2566 * @return string the HTML to output.
2568 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2574 if ($this->has_started()) {
2575 // we can not always recover properly here, we have problems with output buffering,
2576 // html tables, etc.
2577 $output .= $this->opencontainers->pop_all_but_last();
2580 // It is really bad if library code throws exception when output buffering is on,
2581 // because the buffered text would be printed before our start of page.
2582 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2583 error_reporting(0); // disable notices from gzip compression, etc.
2584 while (ob_get_level() > 0) {
2585 $buff = ob_get_clean();
2586 if ($buff === false) {
2591 error_reporting($CFG->debug);
2593 // Output not yet started.
2594 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2595 if (empty($_SERVER['HTTP_RANGE'])) {
2596 @header($protocol . ' 404 Not Found');
2598 // Must stop byteserving attempts somehow,
2599 // this is weird but Chrome PDF viewer can be stopped only with 407!
2600 @header($protocol . ' 407 Proxy Authentication Required');
2603 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2604 $this->page->set_url('/'); // no url
2605 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2606 $this->page->set_title(get_string('error'));
2607 $this->page->set_heading($this->page->course->fullname);
2608 $output .= $this->header();
2611 $message = '<p class="errormessage">' . $message . '</p>'.
2612 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2613 get_string('moreinformation') . '</a></p>';
2614 if (empty($CFG->rolesactive)) {
2615 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2616 //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.
2618 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
2620 if ($CFG->debugdeveloper) {
2621 if (!empty($debuginfo)) {
2622 $debuginfo = s($debuginfo); // removes all nasty JS
2623 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2624 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2626 if (!empty($backtrace)) {
2627 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2629 if ($obbuffer !== '' ) {
2630 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2634 if (empty($CFG->rolesactive)) {
2635 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2636 } else if (!empty($link)) {
2637 $output .= $this->continue_button($link);
2640 $output .= $this->footer();
2642 // Padding to encourage IE to display our error page, rather than its own.
2643 $output .= str_repeat(' ', 512);
2649 * Output a notification (that is, a status message about something that has
2652 * @param string $message the message to print out
2653 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2654 * @return string the HTML to output.
2656 public function notification($message, $classes = 'notifyproblem') {
2657 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2661 * Returns HTML to display a continue button that goes to a particular URL.
2663 * @param string|moodle_url $url The url the button goes to.
2664 * @return string the HTML to output.
2666 public function continue_button($url) {
2667 if (!($url instanceof moodle_url)) {
2668 $url = new moodle_url($url);
2670 $button = new single_button($url, get_string('continue'), 'get');
2671 $button->class = 'continuebutton';
2673 return $this->render($button);
2677 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2679 * Theme developers: DO NOT OVERRIDE! Please override function
2680 * {@link core_renderer::render_paging_bar()} instead.
2682 * @param int $totalcount The total number of entries available to be paged through
2683 * @param int $page The page you are currently viewing
2684 * @param int $perpage The number of entries that should be shown per page
2685 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2686 * @param string $pagevar name of page parameter that holds the page number
2687 * @return string the HTML to output.
2689 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2690 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2691 return $this->render($pb);
2695 * Internal implementation of paging bar rendering.
2697 * @param paging_bar $pagingbar
2700 protected function render_paging_bar(paging_bar $pagingbar) {
2702 $pagingbar = clone($pagingbar);
2703 $pagingbar->prepare($this, $this->page, $this->target);
2705 if ($pagingbar->totalcount > $pagingbar->perpage) {
2706 $output .= get_string('page') . ':';
2708 if (!empty($pagingbar->previouslink)) {
2709 $output .= ' (' . $pagingbar->previouslink . ') ';
2712 if (!empty($pagingbar->firstlink)) {
2713 $output .= ' ' . $pagingbar->firstlink . ' ...';
2716 foreach ($pagingbar->pagelinks as $link) {
2717 $output .= "  $link";
2720 if (!empty($pagingbar->lastlink)) {
2721 $output .= ' ...' . $pagingbar->lastlink . ' ';
2724 if (!empty($pagingbar->nextlink)) {
2725 $output .= '  (' . $pagingbar->nextlink . ')';
2729 return html_writer::tag('div', $output, array('class' => 'paging'));
2733 * Output the place a skip link goes to.
2735 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2736 * @return string the HTML to output.
2738 public function skip_link_target($id = null) {
2739 return html_writer::tag('span', '', array('id' => $id));
2745 * @param string $text The text of the heading
2746 * @param int $level The level of importance of the heading. Defaulting to 2
2747 * @param string $classes A space-separated list of CSS classes. Defaulting to null
2748 * @param string $id An optional ID
2749 * @return string the HTML to output.
2751 public function heading($text, $level = 2, $classes = null, $id = null) {
2752 $level = (integer) $level;
2753 if ($level < 1 or $level > 6) {
2754 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2756 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2762 * @param string $contents The contents of the box
2763 * @param string $classes A space-separated list of CSS classes
2764 * @param string $id An optional ID
2765 * @param array $attributes An array of other attributes to give the box.
2766 * @return string the HTML to output.
2768 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
2769 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
2773 * Outputs the opening section of a box.
2775 * @param string $classes A space-separated list of CSS classes
2776 * @param string $id An optional ID
2777 * @param array $attributes An array of other attributes to give the box.
2778 * @return string the HTML to output.
2780 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
2781 $this->opencontainers->push('box', html_writer::end_tag('div'));
2782 $attributes['id'] = $id;
2783 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
2784 return html_writer::start_tag('div', $attributes);
2788 * Outputs the closing section of a box.
2790 * @return string the HTML to output.
2792 public function box_end() {
2793 return $this->opencontainers->pop('box');
2797 * Outputs a container.
2799 * @param string $contents The contents of the box
2800 * @param string $classes A space-separated list of CSS classes
2801 * @param string $id An optional ID
2802 * @return string the HTML to output.
2804 public function container($contents, $classes = null, $id = null) {
2805 return $this->container_start($classes, $id) . $contents . $this->container_end();
2809 * Outputs the opening section of a container.
2811 * @param string $classes A space-separated list of CSS classes
2812 * @param string $id An optional ID
2813 * @return string the HTML to output.
2815 public function container_start($classes = null, $id = null) {
2816 $this->opencontainers->push('container', html_writer::end_tag('div'));
2817 return html_writer::start_tag('div', array('id' => $id,
2818 'class' => renderer_base::prepare_classes($classes)));
2822 * Outputs the closing section of a container.
2824 * @return string the HTML to output.
2826 public function container_end() {
2827 return $this->opencontainers->pop('container');
2831 * Make nested HTML lists out of the items
2833 * The resulting list will look something like this:
2837 * <<li>><div class='tree_item parent'>(item contents)</div>
2839 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2845 * @param array $items
2846 * @param array $attrs html attributes passed to the top ofs the list
2847 * @return string HTML
2849 public function tree_block_contents($items, $attrs = array()) {
2850 // exit if empty, we don't want an empty ul element
2851 if (empty($items)) {
2854 // array of nested li elements
2856 foreach ($items as $item) {
2857 // this applies to the li item which contains all child lists too
2858 $content = $item->content($this);
2859 $liclasses = array($item->get_css_type());
2860 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2861 $liclasses[] = 'collapsed';
2863 if ($item->isactive === true) {
2864 $liclasses[] = 'current_branch';
2866 $liattr = array('class'=>join(' ',$liclasses));
2867 // class attribute on the div item which only contains the item content
2868 $divclasses = array('tree_item');
2869 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2870 $divclasses[] = 'branch';
2872 $divclasses[] = 'leaf';
2874 if (!empty($item->classes) && count($item->classes)>0) {
2875 $divclasses[] = join(' ', $item->classes);
2877 $divattr = array('class'=>join(' ', $divclasses));
2878 if (!empty($item->id)) {
2879 $divattr['id'] = $item->id;
2881 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2882 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2883 $content = html_writer::empty_tag('hr') . $content;
2885 $content = html_writer::tag('li', $content, $liattr);
2888 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2892 * Return the navbar content so that it can be echoed out by the layout
2894 * @return string XHTML navbar
2896 public function navbar() {
2897 $items = $this->page->navbar->get_items();
2898 $itemcount = count($items);
2899 if ($itemcount === 0) {
2903 $htmlblocks = array();
2904 // Iterate the navarray and display each node
2905 $separator = get_separator();
2906 for ($i=0;$i < $itemcount;$i++) {
2908 $item->hideicon = true;
2910 $content = html_writer::tag('li', $this->render($item));
2912 $content = html_writer::tag('li', $separator.$this->render($item));
2914 $htmlblocks[] = $content;
2917 //accessibility: heading for navbar list (MDL-20446)
2918 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2919 $navbarcontent .= html_writer::tag('nav', html_writer::tag('ul', join('', $htmlblocks)));
2921 return $navbarcontent;
2925 * Renders a navigation node object.
2927 * @param navigation_node $item The navigation node to render.
2928 * @return string HTML fragment
2930 protected function render_navigation_node(navigation_node $item) {
2931 $content = $item->get_content();
2932 $title = $item->get_title();
2933 if ($item->icon instanceof renderable && !$item->hideicon) {
2934 $icon = $this->render($item->icon);
2935 $content = $icon.$content; // use CSS for spacing of icons
2937 if ($item->helpbutton !== null) {
2938 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2940 if ($content === '') {
2943 if ($item->action instanceof action_link) {
2944 $link = $item->action;
2945 if ($item->hidden) {
2946 $link->add_class('dimmed');
2948 if (!empty($content)) {
2949 // Providing there is content we will use that for the link content.
2950 $link->text = $content;
2952 $content = $this->render($link);
2953 } else if ($item->action instanceof moodle_url) {
2954 $attributes = array();
2955 if ($title !== '') {
2956 $attributes['title'] = $title;
2958 if ($item->hidden) {
2959 $attributes['class'] = 'dimmed_text';
2961 $content = html_writer::link($item->action, $content, $attributes);
2963 } else if (is_string($item->action) || empty($item->action)) {
2964 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2965 if ($title !== '') {
2966 $attributes['title'] = $title;
2968 if ($item->hidden) {
2969 $attributes['class'] = 'dimmed_text';
2971 $content = html_writer::tag('span', $content, $attributes);
2977 * Accessibility: Right arrow-like character is
2978 * used in the breadcrumb trail, course navigation menu
2979 * (previous/next activity), calendar, and search forum block.
2980 * If the theme does not set characters, appropriate defaults
2981 * are set automatically. Please DO NOT
2982 * use < > » - these are confusing for blind users.
2986 public function rarrow() {
2987 return $this->page->theme->rarrow;
2991 * Accessibility: Right arrow-like character is
2992 * used in the breadcrumb trail, course navigation menu
2993 * (previous/next activity), calendar, and search forum block.
2994 * If the theme does not set characters, appropriate defaults
2995 * are set automatically. Please DO NOT
2996 * use < > » - these are confusing for blind users.
3000 public function larrow() {
3001 return $this->page->theme->larrow;
3005 * Returns the custom menu if one has been set
3007 * A custom menu can be configured by browsing to
3008 * Settings: Administration > Appearance > Themes > Theme settings
3009 * and then configuring the custommenu config setting as described.
3011 * Theme developers: DO NOT OVERRIDE! Please override function
3012 * {@link core_renderer::render_custom_menu()} instead.
3014 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3017 public function custom_menu($custommenuitems = '') {
3019 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3020 $custommenuitems = $CFG->custommenuitems;
3022 if (empty($custommenuitems)) {
3025 $custommenu = new custom_menu($custommenuitems, current_language());
3026 return $this->render($custommenu);
3030 * Renders a custom menu object (located in outputcomponents.php)
3032 * The custom menu this method produces makes use of the YUI3 menunav widget
3033 * and requires very specific html elements and classes.
3035 * @staticvar int $menucount
3036 * @param custom_menu $menu
3039 protected function render_custom_menu(custom_menu $menu) {
3040 static $menucount = 0;
3041 // If the menu has no children return an empty string
3042 if (!$menu->has_children()) {
3045 // Increment the menu count. This is used for ID's that get worked with
3046 // in JavaScript as is essential
3048 // Initialise this custom menu (the custom menu object is contained in javascript-static
3049 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
3050 $jscode = "(function(){{$jscode}})";
3051 $this->page->requires->yui_module('node-menunav', $jscode);
3052 // Build the root nodes as required by YUI
3053 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
3054 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3055 $content .= html_writer::start_tag('ul');
3056 // Render each child
3057 foreach ($menu->get_children() as $item) {
3058 $content .= $this->render_custom_menu_item($item);
3060 // Close the open tags
3061 $content .= html_writer::end_tag('ul');
3062 $content .= html_writer::end_tag('div');
3063 $content .= html_writer::end_tag('div');
3064 // Return the custom menu
3069 * Renders a custom menu node as part of a submenu
3071 * The custom menu this method produces makes use of the YUI3 menunav widget
3072 * and requires very specific html elements and classes.
3074 * @see core:renderer::render_custom_menu()
3076 * @staticvar int $submenucount
3077 * @param custom_menu_item $menunode
3080 protected function render_custom_menu_item(custom_menu_item $menunode) {
3081 // Required to ensure we get unique trackable id's
3082 static $submenucount = 0;
3083 if ($menunode->has_children()) {
3084 // If the child has menus render it as a sub menu
3086 $content = html_writer::start_tag('li');
3087 if ($menunode->get_url() !== null) {
3088 $url = $menunode->get_url();
3090 $url = '#cm_submenu_'.$submenucount;
3092 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3093 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3094 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3095 $content .= html_writer::start_tag('ul');
3096 foreach ($menunode->get_children() as $menunode) {
3097 $content .= $this->render_custom_menu_item($menunode);
3099 $content .= html_writer::end_tag('ul');
3100 $content .= html_writer::end_tag('div');
3101 $content .= html_writer::end_tag('div');
3102 $content .= html_writer::end_tag('li');
3104 // The node doesn't have children so produce a final menuitem.
3105 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3107 if (preg_match("/^#+$/", $menunode->get_text())) {
3109 // This is a divider.
3110 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3112 $content = html_writer::start_tag(
3115 'class' => 'yui3-menuitem'
3118 if ($menunode->get_url() !== null) {
3119 $url = $menunode->get_url();
3123 $content .= html_writer::link(
3125 $menunode->get_text(),
3126 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3129 $content .= html_writer::end_tag('li');
3131 // Return the sub menu
3136 * Renders theme links for switching between default and other themes.
3140 protected function theme_switch_links() {
3142 $actualdevice = core_useragent::get_device_type();
3143 $currentdevice = $this->page->devicetypeinuse;
3144 $switched = ($actualdevice != $currentdevice);
3146 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3147 // The user is using the a default device and hasn't switched so don't shown the switch
3153 $linktext = get_string('switchdevicerecommended');
3154 $devicetype = $actualdevice;
3156 $linktext = get_string('switchdevicedefault');
3157 $devicetype = 'default';
3159 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3161 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3162 $content .= html_writer::link($linkurl, $linktext);
3163 $content .= html_writer::end_tag('div');
3171 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3173 * Theme developers: In order to change how tabs are displayed please override functions
3174 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3176 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3177 * @param string|null $selected which tab to mark as selected, all parent tabs will
3178 * automatically be marked as activated
3179 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3180 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3183 public final function tabtree($tabs, $selected = null, $inactive = null) {
3184 return $this->render(new tabtree($tabs, $selected, $inactive));
3190 * @param tabtree $tabtree
3193 protected function render_tabtree(tabtree $tabtree) {
3194 if (empty($tabtree->subtree)) {
3198 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
3199 $str .= $this->render_tabobject($tabtree);
3200 $str .= html_writer::end_tag('div').
3201 html_writer::tag('div', ' ', array('class' => 'clearer'));
3206 * Renders tabobject (part of tabtree)
3208 * This function is called from {@link core_renderer::render_tabtree()}
3209 * and also it calls itself when printing the $tabobject subtree recursively.
3211 * Property $tabobject->level indicates the number of row of tabs.
3213 * @param tabobject $tabobject
3214 * @return string HTML fragment
3216 protected function render_tabobject(tabobject $tabobject) {
3219 // Print name of the current tab.
3220 if ($tabobject instanceof tabtree) {
3221 // No name for tabtree root.
3222 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3223 // Tab name without a link. The <a> tag is used for styling.
3224 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3226 // Tab name with a link.
3227 if (!($tabobject->link instanceof moodle_url)) {
3228 // backward compartibility when link was passed as quoted string
3229 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3231 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3235 if (empty($tabobject->subtree)) {
3236 if ($tabobject->selected) {
3237 $str .= html_writer::tag('div', ' ', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3243 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3245 foreach ($tabobject->subtree as $tab) {
3248 $liclass .= ' first';
3250 if ($cnt == count($tabobject->subtree) - 1) {
3251 $liclass .= ' last';
3253 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3254 $liclass .= ' onerow';
3257 if ($tab->selected) {
3258 $liclass .= ' here selected';
3259 } else if ($tab->activated) {
3260 $liclass .= ' here active';
3263 // This will recursively call function render_tabobject() for each item in subtree
3264 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3267 $str .= html_writer::end_tag('ul');
3273 * Get the HTML for blocks in the given region.
3275 * @since Moodle 2.5.1 2.6
3276 * @param string $region The region to get HTML for.
3277 * @return string HTML.
3279 public function blocks($region, $classes = array(), $tag = 'aside') {
3280 $displayregion = $this->page->apply_theme_region_manipulations($region);
3281 $classes = (array)$classes;
3282 $classes[] = 'block-region';
3283 $attributes = array(
3284 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3285 'class' => join(' ', $classes),
3286 'data-blockregion' => $displayregion,
3287 'data-droptarget' => '1'
3289 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3290 $content = $this->blocks_for_region($displayregion);
3294 return html_writer::tag($tag, $content, $attributes);
3298 * Renders a custom block region.
3300 * Use this method if you want to add an additional block region to the content of the page.
3301 * Please note this should only be used in special situations.
3302 * We want to leave the theme is control where ever possible!
3304 * This method must use the same method that the theme uses within its layout file.
3305 * As such it asks the theme what method it is using.
3306 * It can be one of two values, blocks or blocks_for_region (deprecated).
3308 * @param string $regionname The name of the custom region to add.
3309 * @return string HTML for the block region.
3311 public function custom_block_region($regionname) {
3312 if ($this->page->theme->get_block_render_method() === 'blocks') {
3313 return $this->blocks($regionname);
3315 return $this->blocks_for_region($regionname);
3320 * Returns the CSS classes to apply to the body tag.
3322 * @since Moodle 2.5.1 2.6
3323 * @param array $additionalclasses Any additional classes to apply.
3326 public function body_css_classes(array $additionalclasses = array()) {
3327 // Add a class for each block region on the page.
3328 // We use the block manager here because the theme object makes get_string calls.
3329 foreach ($this->page->blocks->get_regions() as $region) {
3330 $additionalclasses[] = 'has-region-'.$region;
3331 if ($this->page->blocks->region_has_content($region, $this)) {
3332 $additionalclasses[] = 'used-region-'.$region;
3334 $additionalclasses[] = 'empty-region-'.$region;
3336 if ($this->page->blocks->region_completely_docked($region, $this)) {
3337 $additionalclasses[] = 'docked-region-'.$region;
3340 foreach ($this->page->layout_options as $option => $value) {
3342 $additionalclasses[] = 'layout-option-'.$option;
3345 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
3350 * The ID attribute to apply to the body tag.
3352 * @since Moodle 2.5.1 2.6
3355 public function body_id() {
3356 return $this->page->bodyid;
3360 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
3362 * @since Moodle 2.5.1 2.6
3363 * @param string|array $additionalclasses Any additional classes to give the body tag,
3366 public function body_attributes($additionalclasses = array()) {
3367 if (!is_array($additionalclasses)) {
3368 $additionalclasses = explode(' ', $additionalclasses);
3370 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
3374 * Gets HTML for the page heading.
3376 * @since Moodle 2.5.1 2.6
3377 * @param string $tag The tag to encase the heading in. h1 by default.
3378 * @return string HTML.
3380 public function page_heading($tag = 'h1') {
3381 return html_writer::tag($tag, $this->page->heading);