MDL-41623 ensure all rss links are valid urls.
[moodle.git] / lib / outputrenderers.php
blobda3dbc73be96a8b4d7f53693723bcfb3965ee4e5
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
21 * for an overview.
23 * Included in this file are the primary renderer classes:
24 * - renderer_base: The renderer outline class that all renderers
25 * should inherit from.
26 * - core_renderer: The standard HTML renderer.
27 * - core_renderer_cli: An adaption of the standard renderer for CLI scripts.
28 * - core_renderer_ajax: An adaption of the standard renderer for AJAX scripts.
29 * - plugin_renderer_base: A renderer class that should be extended by all
30 * plugin renderers.
32 * @package core
33 * @category output
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') || die();
40 /**
41 * Simple base class for Moodle renderers.
43 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
45 * Also has methods to facilitate generating HTML output.
47 * @copyright 2009 Tim Hunt
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 * @since Moodle 2.0
50 * @package core
51 * @category output
53 class renderer_base {
54 /**
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
59 /**
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
62 protected $page;
64 /**
65 * @var string The requested rendering target.
67 protected $target;
69 /**
70 * Constructor
72 * The constructor takes two arguments. The first is the page that the renderer
73 * has been created to assist with, and the second is the target.
74 * The target is an additional identifier that can be used to load different
75 * renderers for different options.
77 * @param moodle_page $page the page we are doing output for.
78 * @param string $target one of rendering target constants
80 public function __construct(moodle_page $page, $target) {
81 $this->opencontainers = $page->opencontainers;
82 $this->page = $page;
83 $this->target = $target;
86 /**
87 * Returns rendered widget.
89 * The provided widget needs to be an object that extends the renderable
90 * interface.
91 * If will then be rendered by a method based upon the classname for the widget.
92 * For instance a widget of class `crazywidget` will be rendered by a protected
93 * render_crazywidget method of this renderer.
95 * @param renderable $widget instance with renderable interface
96 * @return string
98 public function render(renderable $widget) {
99 $rendermethod = 'render_'.get_class($widget);
100 if (method_exists($this, $rendermethod)) {
101 return $this->$rendermethod($widget);
103 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
107 * Adds a JS action for the element with the provided id.
109 * This method adds a JS event for the provided component action to the page
110 * and then returns the id that the event has been attached to.
111 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
113 * @param component_action $action
114 * @param string $id
115 * @return string id of element, either original submitted or random new if not supplied
117 public function add_action_handler(component_action $action, $id = null) {
118 if (!$id) {
119 $id = html_writer::random_id($action->event);
121 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
122 return $id;
126 * Returns true is output has already started, and false if not.
128 * @return boolean true if the header has been printed.
130 public function has_started() {
131 return $this->page->state >= moodle_page::STATE_IN_BODY;
135 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
137 * @param mixed $classes Space-separated string or array of classes
138 * @return string HTML class attribute value
140 public static function prepare_classes($classes) {
141 if (is_array($classes)) {
142 return implode(' ', array_unique($classes));
144 return $classes;
148 * Return the moodle_url for an image.
150 * The exact image location and extension is determined
151 * automatically by searching for gif|png|jpg|jpeg, please
152 * note there can not be diferent images with the different
153 * extension. The imagename is for historical reasons
154 * a relative path name, it may be changed later for core
155 * images. It is recommended to not use subdirectories
156 * in plugin and theme pix directories.
158 * There are three types of images:
159 * 1/ theme images - stored in theme/mytheme/pix/,
160 * use component 'theme'
161 * 2/ core images - stored in /pix/,
162 * overridden via theme/mytheme/pix_core/
163 * 3/ plugin images - stored in mod/mymodule/pix,
164 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
165 * example: pix_url('comment', 'mod_glossary')
167 * @param string $imagename the pathname of the image
168 * @param string $component full plugin name (aka component) or 'theme'
169 * @return moodle_url
171 public function pix_url($imagename, $component = 'moodle') {
172 return $this->page->theme->pix_url($imagename, $component);
178 * Basis for all plugin renderers.
180 * @copyright Petr Skoda (skodak)
181 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
182 * @since Moodle 2.0
183 * @package core
184 * @category output
186 class plugin_renderer_base extends renderer_base {
189 * @var renderer_base|core_renderer A reference to the current renderer.
190 * The renderer provided here will be determined by the page but will in 90%
191 * of cases by the {@link core_renderer}
193 protected $output;
196 * Constructor method, calls the parent constructor
198 * @param moodle_page $page
199 * @param string $target one of rendering target constants
201 public function __construct(moodle_page $page, $target) {
202 $this->output = $page->get_renderer('core', null, $target);
203 parent::__construct($page, $target);
207 * Renders the provided widget and returns the HTML to display it.
209 * @param renderable $widget instance with renderable interface
210 * @return string
212 public function render(renderable $widget) {
213 $rendermethod = 'render_'.get_class($widget);
214 if (method_exists($this, $rendermethod)) {
215 return $this->$rendermethod($widget);
217 // pass to core renderer if method not found here
218 return $this->output->render($widget);
222 * Magic method used to pass calls otherwise meant for the standard renderer
223 * to it to ensure we don't go causing unnecessary grief.
225 * @param string $method
226 * @param array $arguments
227 * @return mixed
229 public function __call($method, $arguments) {
230 if (method_exists('renderer_base', $method)) {
231 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
233 if (method_exists($this->output, $method)) {
234 return call_user_func_array(array($this->output, $method), $arguments);
235 } else {
236 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
243 * The standard implementation of the core_renderer interface.
245 * @copyright 2009 Tim Hunt
246 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
247 * @since Moodle 2.0
248 * @package core
249 * @category output
251 class core_renderer extends renderer_base {
253 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
254 * in layout files instead.
255 * @deprecated
256 * @var string used in {@link core_renderer::header()}.
258 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
261 * @var string Used to pass information from {@link core_renderer::doctype()} to
262 * {@link core_renderer::standard_head_html()}.
264 protected $contenttype;
267 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
268 * with {@link core_renderer::header()}.
270 protected $metarefreshtag = '';
273 * @var string Unique token for the closing HTML
275 protected $unique_end_html_token;
278 * @var string Unique token for performance information
280 protected $unique_performance_info_token;
283 * @var string Unique token for the main content.
285 protected $unique_main_content_token;
288 * Constructor
290 * @param moodle_page $page the page we are doing output for.
291 * @param string $target one of rendering target constants
293 public function __construct(moodle_page $page, $target) {
294 $this->opencontainers = $page->opencontainers;
295 $this->page = $page;
296 $this->target = $target;
298 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
299 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
300 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
304 * Get the DOCTYPE declaration that should be used with this page. Designed to
305 * be called in theme layout.php files.
307 * @return string the DOCTYPE declaration that should be used.
309 public function doctype() {
310 if ($this->page->theme->doctype === 'html5') {
311 $this->contenttype = 'text/html; charset=utf-8';
312 return "<!DOCTYPE html>\n";
314 } else if ($this->page->theme->doctype === 'xhtml5') {
315 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
316 return "<!DOCTYPE html>\n";
318 } else {
319 // legacy xhtml 1.0
320 $this->contenttype = 'text/html; charset=utf-8';
321 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
326 * The attributes that should be added to the <html> tag. Designed to
327 * be called in theme layout.php files.
329 * @return string HTML fragment.
331 public function htmlattributes() {
332 $return = get_html_lang(true);
333 if ($this->page->theme->doctype !== 'html5') {
334 $return .= ' xmlns="http://www.w3.org/1999/xhtml"';
336 return $return;
340 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
341 * that should be included in the <head> tag. Designed to be called in theme
342 * layout.php files.
344 * @return string HTML fragment.
346 public function standard_head_html() {
347 global $CFG, $SESSION;
349 // Before we output any content, we need to ensure that certain
350 // page components are set up.
352 // Blocks must be set up early as they may require javascript which
353 // has to be included in the page header before output is created.
354 foreach ($this->page->blocks->get_regions() as $region) {
355 $this->page->blocks->ensure_content_created($region, $this);
358 $output = '';
359 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
360 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
361 if (!$this->page->cacheable) {
362 $output .= '<meta http-equiv="pragma" content="no-cache" />' . "\n";
363 $output .= '<meta http-equiv="expires" content="0" />' . "\n";
365 // This is only set by the {@link redirect()} method
366 $output .= $this->metarefreshtag;
368 // Check if a periodic refresh delay has been set and make sure we arn't
369 // already meta refreshing
370 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
371 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
374 // flow player embedding support
375 $this->page->requires->js_function_call('M.util.load_flowplayer');
377 // Set up help link popups for all links with the helptooltip class
378 $this->page->requires->js_init_call('M.util.help_popups.setup');
380 // Setup help icon overlays.
381 $this->page->requires->yui_module('moodle-core-popuphelp', 'M.core.init_popuphelp');
382 $this->page->requires->strings_for_js(array(
383 'morehelp',
384 'loadinghelp',
385 ), 'moodle');
387 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
389 $focus = $this->page->focuscontrol;
390 if (!empty($focus)) {
391 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
392 // This is a horrifically bad way to handle focus but it is passed in
393 // through messy formslib::moodleform
394 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
395 } else if (strpos($focus, '.')!==false) {
396 // Old style of focus, bad way to do it
397 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);
398 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
399 } else {
400 // Focus element with given id
401 $this->page->requires->js_function_call('focuscontrol', array($focus));
405 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
406 // any other custom CSS can not be overridden via themes and is highly discouraged
407 $urls = $this->page->theme->css_urls($this->page);
408 foreach ($urls as $url) {
409 $this->page->requires->css_theme($url);
412 // Get the theme javascript head and footer
413 if ($jsurl = $this->page->theme->javascript_url(true)) {
414 $this->page->requires->js($jsurl, true);
416 if ($jsurl = $this->page->theme->javascript_url(false)) {
417 $this->page->requires->js($jsurl);
420 // Get any HTML from the page_requirements_manager.
421 $output .= $this->page->requires->get_head_code($this->page, $this);
423 // List alternate versions.
424 foreach ($this->page->alternateversions as $type => $alt) {
425 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
426 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
429 if (!empty($CFG->additionalhtmlhead)) {
430 $output .= "\n".$CFG->additionalhtmlhead;
433 return $output;
437 * The standard tags (typically skip links) that should be output just inside
438 * the start of the <body> tag. Designed to be called in theme layout.php files.
440 * @return string HTML fragment.
442 public function standard_top_of_body_html() {
443 global $CFG;
444 $output = $this->page->requires->get_top_of_body_code();
445 if (!empty($CFG->additionalhtmltopofbody)) {
446 $output .= "\n".$CFG->additionalhtmltopofbody;
448 $output .= $this->maintenance_warning();
449 return $output;
453 * Scheduled maintenance warning message.
455 * Note: This is a nasty hack to display maintenance notice, this should be moved
456 * to some general notification area once we have it.
458 * @return string
460 public function maintenance_warning() {
461 global $CFG;
463 $output = '';
464 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
465 $output .= $this->box_start('errorbox maintenancewarning');
466 $output .= get_string('maintenancemodeisscheduled', 'admin', (int)(($CFG->maintenance_later-time())/60));
467 $output .= $this->box_end();
469 return $output;
473 * The standard tags (typically performance information and validation links,
474 * if we are in developer debug mode) that should be output in the footer area
475 * of the page. Designed to be called in theme layout.php files.
477 * @return string HTML fragment.
479 public function standard_footer_html() {
480 global $CFG, $SCRIPT;
482 if (during_initial_install()) {
483 // Debugging info can not work before install is finished,
484 // in any case we do not want any links during installation!
485 return '';
488 // This function is normally called from a layout.php file in {@link core_renderer::header()}
489 // but some of the content won't be known until later, so we return a placeholder
490 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
491 $output = $this->unique_performance_info_token;
492 if ($this->page->devicetypeinuse == 'legacy') {
493 // The legacy theme is in use print the notification
494 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
497 // Get links to switch device types (only shown for users not on a default device)
498 $output .= $this->theme_switch_links();
500 if (!empty($CFG->debugpageinfo)) {
501 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
503 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
504 // Add link to profiling report if necessary
505 if (function_exists('profiling_is_running') && profiling_is_running()) {
506 $txt = get_string('profiledscript', 'admin');
507 $title = get_string('profiledscriptview', 'admin');
508 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
509 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
510 $output .= '<div class="profilingfooter">' . $link . '</div>';
512 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
513 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
514 $output .= '<div class="purgecaches">' .
515 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
517 if (!empty($CFG->debugvalidators)) {
518 // 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
519 $output .= '<div class="validators"><ul>
520 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
521 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
522 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&amp;warnp2n3e=1&amp;url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
523 </ul></div>';
525 if (!empty($CFG->additionalhtmlfooter)) {
526 $output .= "\n".$CFG->additionalhtmlfooter;
528 return $output;
532 * Returns standard main content placeholder.
533 * Designed to be called in theme layout.php files.
535 * @return string HTML fragment.
537 public function main_content() {
538 // This is here because it is the only place we can inject the "main" role over the entire main content area
539 // without requiring all theme's to manually do it, and without creating yet another thing people need to
540 // remember in the theme.
541 // This is an unfortunate hack. DO NO EVER add anything more here.
542 // DO NOT add classes.
543 // DO NOT add an id.
544 return '<div role="main">'.$this->unique_main_content_token.'</div>';
548 * The standard tags (typically script tags that are not needed earlier) that
549 * should be output after everything else, . Designed to be called in theme layout.php files.
551 * @return string HTML fragment.
553 public function standard_end_of_body_html() {
554 // This function is normally called from a layout.php file in {@link core_renderer::header()}
555 // but some of the content won't be known until later, so we return a placeholder
556 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
557 return $this->unique_end_html_token;
561 * Return the standard string that says whether you are logged in (and switched
562 * roles/logged in as another user).
563 * @param bool $withlinks if false, then don't include any links in the HTML produced.
564 * If not set, the default is the nologinlinks option from the theme config.php file,
565 * and if that is not set, then links are included.
566 * @return string HTML fragment.
568 public function login_info($withlinks = null) {
569 global $USER, $CFG, $DB, $SESSION;
571 if (during_initial_install()) {
572 return '';
575 if (is_null($withlinks)) {
576 $withlinks = empty($this->page->layout_options['nologinlinks']);
579 $loginpage = ((string)$this->page->url === get_login_url());
580 $course = $this->page->course;
581 if (session_is_loggedinas()) {
582 $realuser = session_get_realuser();
583 $fullname = fullname($realuser, true);
584 if ($withlinks) {
585 $loginastitle = get_string('loginas');
586 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
587 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
588 } else {
589 $realuserinfo = " [$fullname] ";
591 } else {
592 $realuserinfo = '';
595 $loginurl = get_login_url();
597 if (empty($course->id)) {
598 // $course->id is not defined during installation
599 return '';
600 } else if (isloggedin()) {
601 $context = context_course::instance($course->id);
603 $fullname = fullname($USER, true);
604 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
605 if ($withlinks) {
606 $linktitle = get_string('viewprofile');
607 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
608 } else {
609 $username = $fullname;
611 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
612 if ($withlinks) {
613 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
614 } else {
615 $username .= " from {$idprovider->name}";
618 if (isguestuser()) {
619 $loggedinas = $realuserinfo.get_string('loggedinasguest');
620 if (!$loginpage && $withlinks) {
621 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
623 } else if (is_role_switched($course->id)) { // Has switched roles
624 $rolename = '';
625 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
626 $rolename = ': '.role_get_name($role, $context);
628 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
629 if ($withlinks) {
630 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
631 $loggedinas .= '('.html_writer::tag('a', get_string('switchrolereturn'), array('href'=>$url)).')';
633 } else {
634 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
635 if ($withlinks) {
636 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
639 } else {
640 $loggedinas = get_string('loggedinnot', 'moodle');
641 if (!$loginpage && $withlinks) {
642 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
646 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
648 if (isset($SESSION->justloggedin)) {
649 unset($SESSION->justloggedin);
650 if (!empty($CFG->displayloginfailures)) {
651 if (!isguestuser()) {
652 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
653 $loggedinas .= '&nbsp;<div class="loginfailures">';
654 if (empty($count->accounts)) {
655 $loggedinas .= get_string('failedloginattempts', '', $count);
656 } else {
657 $loggedinas .= get_string('failedloginattemptsall', '', $count);
659 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
660 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/report/log/index.php'.
661 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
663 $loggedinas .= '</div>';
669 return $loggedinas;
673 * Return the 'back' link that normally appears in the footer.
675 * @return string HTML fragment.
677 public function home_link() {
678 global $CFG, $SITE;
680 if ($this->page->pagetype == 'site-index') {
681 // Special case for site home page - please do not remove
682 return '<div class="sitelink">' .
683 '<a title="Moodle" href="http://moodle.org/">' .
684 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
686 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
687 // Special case for during install/upgrade.
688 return '<div class="sitelink">'.
689 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
690 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
692 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
693 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
694 get_string('home') . '</a></div>';
696 } else {
697 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
698 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
703 * Redirects the user by any means possible given the current state
705 * This function should not be called directly, it should always be called using
706 * the redirect function in lib/weblib.php
708 * The redirect function should really only be called before page output has started
709 * however it will allow itself to be called during the state STATE_IN_BODY
711 * @param string $encodedurl The URL to send to encoded if required
712 * @param string $message The message to display to the user if any
713 * @param int $delay The delay before redirecting a user, if $message has been
714 * set this is a requirement and defaults to 3, set to 0 no delay
715 * @param boolean $debugdisableredirect this redirect has been disabled for
716 * debugging purposes. Display a message that explains, and don't
717 * trigger the redirect.
718 * @return string The HTML to display to the user before dying, may contain
719 * meta refresh, javascript refresh, and may have set header redirects
721 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
722 global $CFG;
723 $url = str_replace('&amp;', '&', $encodedurl);
725 switch ($this->page->state) {
726 case moodle_page::STATE_BEFORE_HEADER :
727 // No output yet it is safe to delivery the full arsenal of redirect methods
728 if (!$debugdisableredirect) {
729 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
730 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
731 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
733 $output = $this->header();
734 break;
735 case moodle_page::STATE_PRINTING_HEADER :
736 // We should hopefully never get here
737 throw new coding_exception('You cannot redirect while printing the page header');
738 break;
739 case moodle_page::STATE_IN_BODY :
740 // We really shouldn't be here but we can deal with this
741 debugging("You should really redirect before you start page output");
742 if (!$debugdisableredirect) {
743 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
745 $output = $this->opencontainers->pop_all_but_last();
746 break;
747 case moodle_page::STATE_DONE :
748 // Too late to be calling redirect now
749 throw new coding_exception('You cannot redirect after the entire page has been generated');
750 break;
752 $output .= $this->notification($message, 'redirectmessage');
753 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
754 if ($debugdisableredirect) {
755 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
757 $output .= $this->footer();
758 return $output;
762 * Start output by sending the HTTP headers, and printing the HTML <head>
763 * and the start of the <body>.
765 * To control what is printed, you should set properties on $PAGE. If you
766 * are familiar with the old {@link print_header()} function from Moodle 1.9
767 * you will find that there are properties on $PAGE that correspond to most
768 * of the old parameters to could be passed to print_header.
770 * Not that, in due course, the remaining $navigation, $menu parameters here
771 * will be replaced by more properties of $PAGE, but that is still to do.
773 * @return string HTML that you must output this, preferably immediately.
775 public function header() {
776 global $USER, $CFG;
778 if (session_is_loggedinas()) {
779 $this->page->add_body_class('userloggedinas');
782 // Give themes a chance to init/alter the page object.
783 $this->page->theme->init_page($this->page);
785 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
787 // Find the appropriate page layout file, based on $this->page->pagelayout.
788 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
789 // Render the layout using the layout file.
790 $rendered = $this->render_page_layout($layoutfile);
792 // Slice the rendered output into header and footer.
793 $cutpos = strpos($rendered, $this->unique_main_content_token);
794 if ($cutpos === false) {
795 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
796 $token = self::MAIN_CONTENT_TOKEN;
797 } else {
798 $token = $this->unique_main_content_token;
801 if ($cutpos === false) {
802 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.');
804 $header = substr($rendered, 0, $cutpos);
805 $footer = substr($rendered, $cutpos + strlen($token));
807 if (empty($this->contenttype)) {
808 debugging('The page layout file did not call $OUTPUT->doctype()');
809 $header = $this->doctype() . $header;
812 // If this theme version is below 2.4 release and this is a course view page
813 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
814 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
815 // check if course content header/footer have not been output during render of theme layout
816 $coursecontentheader = $this->course_content_header(true);
817 $coursecontentfooter = $this->course_content_footer(true);
818 if (!empty($coursecontentheader)) {
819 // display debug message and add header and footer right above and below main content
820 // Please note that course header and footer (to be displayed above and below the whole page)
821 // are not displayed in this case at all.
822 // Besides the content header and footer are not displayed on any other course page
823 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);
824 $header .= $coursecontentheader;
825 $footer = $coursecontentfooter. $footer;
829 send_headers($this->contenttype, $this->page->cacheable);
831 $this->opencontainers->push('header/footer', $footer);
832 $this->page->set_state(moodle_page::STATE_IN_BODY);
834 return $header . $this->skip_link_target('maincontent');
838 * Renders and outputs the page layout file.
840 * This is done by preparing the normal globals available to a script, and
841 * then including the layout file provided by the current theme for the
842 * requested layout.
844 * @param string $layoutfile The name of the layout file
845 * @return string HTML code
847 protected function render_page_layout($layoutfile) {
848 global $CFG, $SITE, $USER;
849 // The next lines are a bit tricky. The point is, here we are in a method
850 // of a renderer class, and this object may, or may not, be the same as
851 // the global $OUTPUT object. When rendering the page layout file, we want to use
852 // this object. However, people writing Moodle code expect the current
853 // renderer to be called $OUTPUT, not $this, so define a variable called
854 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
855 $OUTPUT = $this;
856 $PAGE = $this->page;
857 $COURSE = $this->page->course;
859 ob_start();
860 include($layoutfile);
861 $rendered = ob_get_contents();
862 ob_end_clean();
863 return $rendered;
867 * Outputs the page's footer
869 * @return string HTML fragment
871 public function footer() {
872 global $CFG, $DB;
874 $output = $this->container_end_all(true);
876 $footer = $this->opencontainers->pop('header/footer');
878 if (debugging() and $DB and $DB->is_transaction_started()) {
879 // TODO: MDL-20625 print warning - transaction will be rolled back
882 // Provide some performance info if required
883 $performanceinfo = '';
884 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
885 $perf = get_performance_info();
886 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
887 error_log("PERF: " . $perf['txt']);
889 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
890 $performanceinfo = $perf['html'];
893 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
895 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
897 $this->page->set_state(moodle_page::STATE_DONE);
899 return $output . $footer;
903 * Close all but the last open container. This is useful in places like error
904 * handling, where you want to close all the open containers (apart from <body>)
905 * before outputting the error message.
907 * @param bool $shouldbenone assert that the stack should be empty now - causes a
908 * developer debug warning if it isn't.
909 * @return string the HTML required to close any open containers inside <body>.
911 public function container_end_all($shouldbenone = false) {
912 return $this->opencontainers->pop_all_but_last($shouldbenone);
916 * Returns course-specific information to be output immediately above content on any course page
917 * (for the current course)
919 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
920 * @return string
922 public function course_content_header($onlyifnotcalledbefore = false) {
923 global $CFG;
924 if ($this->page->course->id == SITEID) {
925 // return immediately and do not include /course/lib.php if not necessary
926 return '';
928 static $functioncalled = false;
929 if ($functioncalled && $onlyifnotcalledbefore) {
930 // we have already output the content header
931 return '';
933 require_once($CFG->dirroot.'/course/lib.php');
934 $functioncalled = true;
935 $courseformat = course_get_format($this->page->course);
936 if (($obj = $courseformat->course_content_header()) !== null) {
937 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
939 return '';
943 * Returns course-specific information to be output immediately below content on any course page
944 * (for the current course)
946 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
947 * @return string
949 public function course_content_footer($onlyifnotcalledbefore = false) {
950 global $CFG;
951 if ($this->page->course->id == SITEID) {
952 // return immediately and do not include /course/lib.php if not necessary
953 return '';
955 static $functioncalled = false;
956 if ($functioncalled && $onlyifnotcalledbefore) {
957 // we have already output the content footer
958 return '';
960 $functioncalled = true;
961 require_once($CFG->dirroot.'/course/lib.php');
962 $courseformat = course_get_format($this->page->course);
963 if (($obj = $courseformat->course_content_footer()) !== null) {
964 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
966 return '';
970 * Returns course-specific information to be output on any course page in the header area
971 * (for the current course)
973 * @return string
975 public function course_header() {
976 global $CFG;
977 if ($this->page->course->id == SITEID) {
978 // return immediately and do not include /course/lib.php if not necessary
979 return '';
981 require_once($CFG->dirroot.'/course/lib.php');
982 $courseformat = course_get_format($this->page->course);
983 if (($obj = $courseformat->course_header()) !== null) {
984 return $courseformat->get_renderer($this->page)->render($obj);
986 return '';
990 * Returns course-specific information to be output on any course page in the footer area
991 * (for the current course)
993 * @return string
995 public function course_footer() {
996 global $CFG;
997 if ($this->page->course->id == SITEID) {
998 // return immediately and do not include /course/lib.php if not necessary
999 return '';
1001 require_once($CFG->dirroot.'/course/lib.php');
1002 $courseformat = course_get_format($this->page->course);
1003 if (($obj = $courseformat->course_footer()) !== null) {
1004 return $courseformat->get_renderer($this->page)->render($obj);
1006 return '';
1010 * Returns lang menu or '', this method also checks forcing of languages in courses.
1012 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1014 * @return string The lang menu HTML or empty string
1016 public function lang_menu() {
1017 global $CFG;
1019 if (empty($CFG->langmenu)) {
1020 return '';
1023 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1024 // do not show lang menu if language forced
1025 return '';
1028 $currlang = current_language();
1029 $langs = get_string_manager()->get_list_of_translations();
1031 if (count($langs) < 2) {
1032 return '';
1035 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1036 $s->label = get_accesshide(get_string('language'));
1037 $s->class = 'langmenu';
1038 return $this->render($s);
1042 * Output the row of editing icons for a block, as defined by the controls array.
1044 * @param array $controls an array like {@link block_contents::$controls}.
1045 * @return string HTML fragment.
1047 public function block_controls($controls) {
1048 if (empty($controls)) {
1049 return '';
1051 $controlshtml = array();
1052 foreach ($controls as $control) {
1053 $controlshtml[] = html_writer::tag('a',
1054 html_writer::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
1055 array('class' => 'icon ' . $control['class'],'title' => $control['caption'], 'href' => $control['url']));
1057 return html_writer::tag('div', implode('', $controlshtml), array('class' => 'commands'));
1061 * Prints a nice side block with an optional header.
1063 * The content is described
1064 * by a {@link core_renderer::block_contents} object.
1066 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1067 * <div class="header"></div>
1068 * <div class="content">
1069 * ...CONTENT...
1070 * <div class="footer">
1071 * </div>
1072 * </div>
1073 * <div class="annotation">
1074 * </div>
1075 * </div>
1077 * @param block_contents $bc HTML for the content
1078 * @param string $region the region the block is appearing in.
1079 * @return string the HTML to be output.
1081 public function block(block_contents $bc, $region) {
1082 $bc = clone($bc); // Avoid messing up the object passed in.
1083 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1084 $bc->collapsible = block_contents::NOT_HIDEABLE;
1086 $skiptitle = strip_tags($bc->title);
1087 if ($bc->blockinstanceid && !empty($skiptitle)) {
1088 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1089 } else if (!empty($bc->arialabel)) {
1090 $bc->attributes['aria-label'] = $bc->arialabel;
1092 if ($bc->collapsible == block_contents::HIDDEN) {
1093 $bc->add_class('hidden');
1095 if (!empty($bc->controls)) {
1096 $bc->add_class('block_with_controls');
1100 if (empty($skiptitle)) {
1101 $output = '';
1102 $skipdest = '';
1103 } else {
1104 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
1105 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
1108 $output .= html_writer::start_tag('div', $bc->attributes);
1110 $output .= $this->block_header($bc);
1111 $output .= $this->block_content($bc);
1113 $output .= html_writer::end_tag('div');
1115 $output .= $this->block_annotation($bc);
1117 $output .= $skipdest;
1119 $this->init_block_hider_js($bc);
1120 return $output;
1124 * Produces a header for a block
1126 * @param block_contents $bc
1127 * @return string
1129 protected function block_header(block_contents $bc) {
1131 $title = '';
1132 if ($bc->title) {
1133 $attributes = array();
1134 if ($bc->blockinstanceid) {
1135 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1137 $title = html_writer::tag('h2', $bc->title, $attributes);
1140 $controlshtml = $this->block_controls($bc->controls);
1142 $output = '';
1143 if ($title || $controlshtml) {
1144 $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'));
1146 return $output;
1150 * Produces the content area for a block
1152 * @param block_contents $bc
1153 * @return string
1155 protected function block_content(block_contents $bc) {
1156 $output = html_writer::start_tag('div', array('class' => 'content'));
1157 if (!$bc->title && !$this->block_controls($bc->controls)) {
1158 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1160 $output .= $bc->content;
1161 $output .= $this->block_footer($bc);
1162 $output .= html_writer::end_tag('div');
1164 return $output;
1168 * Produces the footer for a block
1170 * @param block_contents $bc
1171 * @return string
1173 protected function block_footer(block_contents $bc) {
1174 $output = '';
1175 if ($bc->footer) {
1176 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1178 return $output;
1182 * Produces the annotation for a block
1184 * @param block_contents $bc
1185 * @return string
1187 protected function block_annotation(block_contents $bc) {
1188 $output = '';
1189 if ($bc->annotation) {
1190 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1192 return $output;
1196 * Calls the JS require function to hide a block.
1198 * @param block_contents $bc A block_contents object
1200 protected function init_block_hider_js(block_contents $bc) {
1201 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1202 $config = new stdClass;
1203 $config->id = $bc->attributes['id'];
1204 $config->title = strip_tags($bc->title);
1205 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1206 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1207 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1209 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1210 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1215 * Render the contents of a block_list.
1217 * @param array $icons the icon for each item.
1218 * @param array $items the content of each item.
1219 * @return string HTML
1221 public function list_block_contents($icons, $items) {
1222 $row = 0;
1223 $lis = array();
1224 foreach ($items as $key => $string) {
1225 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1226 if (!empty($icons[$key])) { //test if the content has an assigned icon
1227 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1229 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1230 $item .= html_writer::end_tag('li');
1231 $lis[] = $item;
1232 $row = 1 - $row; // Flip even/odd.
1234 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1238 * Output all the blocks in a particular region.
1240 * @param string $region the name of a region on this page.
1241 * @return string the HTML to be output.
1243 public function blocks_for_region($region) {
1244 $region = $this->page->apply_theme_region_manipulations($region);
1245 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1246 $blocks = $this->page->blocks->get_blocks_for_region($region);
1247 $lastblock = null;
1248 $zones = array();
1249 foreach ($blocks as $block) {
1250 $zones[] = $block->title;
1252 $output = '';
1254 foreach ($blockcontents as $bc) {
1255 if ($bc instanceof block_contents) {
1256 $output .= $this->block($bc, $region);
1257 $lastblock = $bc->title;
1258 } else if ($bc instanceof block_move_target) {
1259 $output .= $this->block_move_target($bc, $zones, $lastblock);
1260 } else {
1261 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1264 return $output;
1268 * Output a place where the block that is currently being moved can be dropped.
1270 * @param block_move_target $target with the necessary details.
1271 * @param array $zones array of areas where the block can be moved to
1272 * @param string $previous the block located before the area currently being rendered.
1273 * @return string the HTML to be output.
1275 public function block_move_target($target, $zones, $previous) {
1276 if ($previous == null) {
1277 $position = get_string('moveblockbefore', 'block', $zones[0]);
1278 } else {
1279 $position = get_string('moveblockafter', 'block', $previous);
1281 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1285 * Renders a special html link with attached action
1287 * Theme developers: DO NOT OVERRIDE! Please override function
1288 * {@link core_renderer::render_action_link()} instead.
1290 * @param string|moodle_url $url
1291 * @param string $text HTML fragment
1292 * @param component_action $action
1293 * @param array $attributes associative array of html link attributes + disabled
1294 * @return string HTML fragment
1296 public function action_link($url, $text, component_action $action = null, array $attributes=null) {
1297 if (!($url instanceof moodle_url)) {
1298 $url = new moodle_url($url);
1300 $link = new action_link($url, $text, $action, $attributes);
1302 return $this->render($link);
1306 * Renders an action_link object.
1308 * The provided link is renderer and the HTML returned. At the same time the
1309 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1311 * @param action_link $link
1312 * @return string HTML fragment
1314 protected function render_action_link(action_link $link) {
1315 global $CFG;
1317 if ($link->text instanceof renderable) {
1318 $text = $this->render($link->text);
1319 } else {
1320 $text = $link->text;
1323 // A disabled link is rendered as formatted text
1324 if (!empty($link->attributes['disabled'])) {
1325 // do not use div here due to nesting restriction in xhtml strict
1326 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1329 $attributes = $link->attributes;
1330 unset($link->attributes['disabled']);
1331 $attributes['href'] = $link->url;
1333 if ($link->actions) {
1334 if (empty($attributes['id'])) {
1335 $id = html_writer::random_id('action_link');
1336 $attributes['id'] = $id;
1337 } else {
1338 $id = $attributes['id'];
1340 foreach ($link->actions as $action) {
1341 $this->add_action_handler($action, $id);
1345 return html_writer::tag('a', $text, $attributes);
1350 * Renders an action_icon.
1352 * This function uses the {@link core_renderer::action_link()} method for the
1353 * most part. What it does different is prepare the icon as HTML and use it
1354 * as the link text.
1356 * Theme developers: If you want to change how action links and/or icons are rendered,
1357 * consider overriding function {@link core_renderer::render_action_link()} and
1358 * {@link core_renderer::render_pix_icon()}.
1360 * @param string|moodle_url $url A string URL or moodel_url
1361 * @param pix_icon $pixicon
1362 * @param component_action $action
1363 * @param array $attributes associative array of html link attributes + disabled
1364 * @param bool $linktext show title next to image in link
1365 * @return string HTML fragment
1367 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1368 if (!($url instanceof moodle_url)) {
1369 $url = new moodle_url($url);
1371 $attributes = (array)$attributes;
1373 if (empty($attributes['class'])) {
1374 // let ppl override the class via $options
1375 $attributes['class'] = 'action-icon';
1378 $icon = $this->render($pixicon);
1380 if ($linktext) {
1381 $text = $pixicon->attributes['alt'];
1382 } else {
1383 $text = '';
1386 return $this->action_link($url, $text.$icon, $action, $attributes);
1390 * Print a message along with button choices for Continue/Cancel
1392 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1394 * @param string $message The question to ask the user
1395 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1396 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1397 * @return string HTML fragment
1399 public function confirm($message, $continue, $cancel) {
1400 if ($continue instanceof single_button) {
1401 // ok
1402 } else if (is_string($continue)) {
1403 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1404 } else if ($continue instanceof moodle_url) {
1405 $continue = new single_button($continue, get_string('continue'), 'post');
1406 } else {
1407 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1410 if ($cancel instanceof single_button) {
1411 // ok
1412 } else if (is_string($cancel)) {
1413 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1414 } else if ($cancel instanceof moodle_url) {
1415 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1416 } else {
1417 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1420 $output = $this->box_start('generalbox', 'notice');
1421 $output .= html_writer::tag('p', $message);
1422 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1423 $output .= $this->box_end();
1424 return $output;
1428 * Returns a form with a single button.
1430 * Theme developers: DO NOT OVERRIDE! Please override function
1431 * {@link core_renderer::render_single_button()} instead.
1433 * @param string|moodle_url $url
1434 * @param string $label button text
1435 * @param string $method get or post submit method
1436 * @param array $options associative array {disabled, title, etc.}
1437 * @return string HTML fragment
1439 public function single_button($url, $label, $method='post', array $options=null) {
1440 if (!($url instanceof moodle_url)) {
1441 $url = new moodle_url($url);
1443 $button = new single_button($url, $label, $method);
1445 foreach ((array)$options as $key=>$value) {
1446 if (array_key_exists($key, $button)) {
1447 $button->$key = $value;
1451 return $this->render($button);
1455 * Renders a single button widget.
1457 * This will return HTML to display a form containing a single button.
1459 * @param single_button $button
1460 * @return string HTML fragment
1462 protected function render_single_button(single_button $button) {
1463 $attributes = array('type' => 'submit',
1464 'value' => $button->label,
1465 'disabled' => $button->disabled ? 'disabled' : null,
1466 'title' => $button->tooltip);
1468 if ($button->actions) {
1469 $id = html_writer::random_id('single_button');
1470 $attributes['id'] = $id;
1471 foreach ($button->actions as $action) {
1472 $this->add_action_handler($action, $id);
1476 // first the input element
1477 $output = html_writer::empty_tag('input', $attributes);
1479 // then hidden fields
1480 $params = $button->url->params();
1481 if ($button->method === 'post') {
1482 $params['sesskey'] = sesskey();
1484 foreach ($params as $var => $val) {
1485 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1488 // then div wrapper for xhtml strictness
1489 $output = html_writer::tag('div', $output);
1491 // now the form itself around it
1492 if ($button->method === 'get') {
1493 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1494 } else {
1495 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1497 if ($url === '') {
1498 $url = '#'; // there has to be always some action
1500 $attributes = array('method' => $button->method,
1501 'action' => $url,
1502 'id' => $button->formid);
1503 $output = html_writer::tag('form', $output, $attributes);
1505 // and finally one more wrapper with class
1506 return html_writer::tag('div', $output, array('class' => $button->class));
1510 * Returns a form with a single select widget.
1512 * Theme developers: DO NOT OVERRIDE! Please override function
1513 * {@link core_renderer::render_single_select()} instead.
1515 * @param moodle_url $url form action target, includes hidden fields
1516 * @param string $name name of selection field - the changing parameter in url
1517 * @param array $options list of options
1518 * @param string $selected selected element
1519 * @param array $nothing
1520 * @param string $formid
1521 * @return string HTML fragment
1523 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1524 if (!($url instanceof moodle_url)) {
1525 $url = new moodle_url($url);
1527 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1529 return $this->render($select);
1533 * Internal implementation of single_select rendering
1535 * @param single_select $select
1536 * @return string HTML fragment
1538 protected function render_single_select(single_select $select) {
1539 $select = clone($select);
1540 if (empty($select->formid)) {
1541 $select->formid = html_writer::random_id('single_select_f');
1544 $output = '';
1545 $params = $select->url->params();
1546 if ($select->method === 'post') {
1547 $params['sesskey'] = sesskey();
1549 foreach ($params as $name=>$value) {
1550 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1553 if (empty($select->attributes['id'])) {
1554 $select->attributes['id'] = html_writer::random_id('single_select');
1557 if ($select->disabled) {
1558 $select->attributes['disabled'] = 'disabled';
1561 if ($select->tooltip) {
1562 $select->attributes['title'] = $select->tooltip;
1565 $select->attributes['class'] = 'autosubmit';
1566 if ($select->class) {
1567 $select->attributes['class'] .= ' ' . $select->class;
1570 if ($select->label) {
1571 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1574 if ($select->helpicon instanceof help_icon) {
1575 $output .= $this->render($select->helpicon);
1577 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1579 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1580 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1582 $nothing = empty($select->nothing) ? false : key($select->nothing);
1583 $this->page->requires->yui_module('moodle-core-formautosubmit',
1584 'M.core.init_formautosubmit',
1585 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1588 // then div wrapper for xhtml strictness
1589 $output = html_writer::tag('div', $output);
1591 // now the form itself around it
1592 if ($select->method === 'get') {
1593 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1594 } else {
1595 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1597 $formattributes = array('method' => $select->method,
1598 'action' => $url,
1599 'id' => $select->formid);
1600 $output = html_writer::tag('form', $output, $formattributes);
1602 // and finally one more wrapper with class
1603 return html_writer::tag('div', $output, array('class' => $select->class));
1607 * Returns a form with a url select widget.
1609 * Theme developers: DO NOT OVERRIDE! Please override function
1610 * {@link core_renderer::render_url_select()} instead.
1612 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1613 * @param string $selected selected element
1614 * @param array $nothing
1615 * @param string $formid
1616 * @return string HTML fragment
1618 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1619 $select = new url_select($urls, $selected, $nothing, $formid);
1620 return $this->render($select);
1624 * Internal implementation of url_select rendering
1626 * @param url_select $select
1627 * @return string HTML fragment
1629 protected function render_url_select(url_select $select) {
1630 global $CFG;
1632 $select = clone($select);
1633 if (empty($select->formid)) {
1634 $select->formid = html_writer::random_id('url_select_f');
1637 if (empty($select->attributes['id'])) {
1638 $select->attributes['id'] = html_writer::random_id('url_select');
1641 if ($select->disabled) {
1642 $select->attributes['disabled'] = 'disabled';
1645 if ($select->tooltip) {
1646 $select->attributes['title'] = $select->tooltip;
1649 $output = '';
1651 if ($select->label) {
1652 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1655 $classes = array();
1656 if (!$select->showbutton) {
1657 $classes[] = 'autosubmit';
1659 if ($select->class) {
1660 $classes[] = $select->class;
1662 if (count($classes)) {
1663 $select->attributes['class'] = implode(' ', $classes);
1666 if ($select->helpicon instanceof help_icon) {
1667 $output .= $this->render($select->helpicon);
1670 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1671 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1672 $urls = array();
1673 foreach ($select->urls as $k=>$v) {
1674 if (is_array($v)) {
1675 // optgroup structure
1676 foreach ($v as $optgrouptitle => $optgroupoptions) {
1677 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1678 if (empty($optionurl)) {
1679 $safeoptionurl = '';
1680 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1681 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1682 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1683 } else if (strpos($optionurl, '/') !== 0) {
1684 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1685 continue;
1686 } else {
1687 $safeoptionurl = $optionurl;
1689 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1692 } else {
1693 // plain list structure
1694 if (empty($k)) {
1695 // nothing selected option
1696 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1697 $k = str_replace($CFG->wwwroot, '', $k);
1698 } else if (strpos($k, '/') !== 0) {
1699 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1700 continue;
1702 $urls[$k] = $v;
1705 $selected = $select->selected;
1706 if (!empty($selected)) {
1707 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1708 $selected = str_replace($CFG->wwwroot, '', $selected);
1709 } else if (strpos($selected, '/') !== 0) {
1710 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1714 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1715 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1717 if (!$select->showbutton) {
1718 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1719 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1720 $nothing = empty($select->nothing) ? false : key($select->nothing);
1721 $this->page->requires->yui_module('moodle-core-formautosubmit',
1722 'M.core.init_formautosubmit',
1723 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1725 } else {
1726 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1729 // then div wrapper for xhtml strictness
1730 $output = html_writer::tag('div', $output);
1732 // now the form itself around it
1733 $formattributes = array('method' => 'post',
1734 'action' => new moodle_url('/course/jumpto.php'),
1735 'id' => $select->formid);
1736 $output = html_writer::tag('form', $output, $formattributes);
1738 // and finally one more wrapper with class
1739 return html_writer::tag('div', $output, array('class' => $select->class));
1743 * Returns a string containing a link to the user documentation.
1744 * Also contains an icon by default. Shown to teachers and admin only.
1746 * @param string $path The page link after doc root and language, no leading slash.
1747 * @param string $text The text to be displayed for the link
1748 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
1749 * @return string
1751 public function doc_link($path, $text = '', $forcepopup = false) {
1752 global $CFG;
1754 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp icon-pre'));
1756 $url = new moodle_url(get_docs_url($path));
1758 $attributes = array('href'=>$url);
1759 if (!empty($CFG->doctonewwindow) || $forcepopup) {
1760 $attributes['class'] = 'helplinkpopup';
1763 return html_writer::tag('a', $icon.$text, $attributes);
1767 * Return HTML for a pix_icon.
1769 * Theme developers: DO NOT OVERRIDE! Please override function
1770 * {@link core_renderer::render_pix_icon()} instead.
1772 * @param string $pix short pix name
1773 * @param string $alt mandatory alt attribute
1774 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1775 * @param array $attributes htm lattributes
1776 * @return string HTML fragment
1778 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1779 $icon = new pix_icon($pix, $alt, $component, $attributes);
1780 return $this->render($icon);
1784 * Renders a pix_icon widget and returns the HTML to display it.
1786 * @param pix_icon $icon
1787 * @return string HTML fragment
1789 protected function render_pix_icon(pix_icon $icon) {
1790 $attributes = $icon->attributes;
1791 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1792 return html_writer::empty_tag('img', $attributes);
1796 * Return HTML to display an emoticon icon.
1798 * @param pix_emoticon $emoticon
1799 * @return string HTML fragment
1801 protected function render_pix_emoticon(pix_emoticon $emoticon) {
1802 $attributes = $emoticon->attributes;
1803 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
1804 return html_writer::empty_tag('img', $attributes);
1808 * Produces the html that represents this rating in the UI
1810 * @param rating $rating the page object on which this rating will appear
1811 * @return string
1813 function render_rating(rating $rating) {
1814 global $CFG, $USER;
1816 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
1817 return null;//ratings are turned off
1820 $ratingmanager = new rating_manager();
1821 // Initialise the JavaScript so ratings can be done by AJAX.
1822 $ratingmanager->initialise_rating_javascript($this->page);
1824 $strrate = get_string("rate", "rating");
1825 $ratinghtml = ''; //the string we'll return
1827 // permissions check - can they view the aggregate?
1828 if ($rating->user_can_view_aggregate()) {
1830 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
1831 $aggregatestr = $rating->get_aggregate_string();
1833 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
1834 if ($rating->count > 0) {
1835 $countstr = "({$rating->count})";
1836 } else {
1837 $countstr = '-';
1839 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
1841 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
1842 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
1844 $nonpopuplink = $rating->get_view_ratings_url();
1845 $popuplink = $rating->get_view_ratings_url(true);
1847 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
1848 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
1849 } else {
1850 $ratinghtml .= $aggregatehtml;
1854 $formstart = null;
1855 // if the item doesn't belong to the current user, the user has permission to rate
1856 // and we're within the assessable period
1857 if ($rating->user_can_rate()) {
1859 $rateurl = $rating->get_rate_url();
1860 $inputs = $rateurl->params();
1862 //start the rating form
1863 $formattrs = array(
1864 'id' => "postrating{$rating->itemid}",
1865 'class' => 'postratingform',
1866 'method' => 'post',
1867 'action' => $rateurl->out_omit_querystring()
1869 $formstart = html_writer::start_tag('form', $formattrs);
1870 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
1872 // add the hidden inputs
1873 foreach ($inputs as $name => $value) {
1874 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
1875 $formstart .= html_writer::empty_tag('input', $attributes);
1878 if (empty($ratinghtml)) {
1879 $ratinghtml .= $strrate.': ';
1881 $ratinghtml = $formstart.$ratinghtml;
1883 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
1884 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
1885 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
1886 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
1888 //output submit button
1889 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
1891 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
1892 $ratinghtml .= html_writer::empty_tag('input', $attributes);
1894 if (!$rating->settings->scale->isnumeric) {
1895 // If a global scale, try to find current course ID from the context
1896 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
1897 $courseid = $coursecontext->instanceid;
1898 } else {
1899 $courseid = $rating->settings->scale->courseid;
1901 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
1903 $ratinghtml .= html_writer::end_tag('span');
1904 $ratinghtml .= html_writer::end_tag('div');
1905 $ratinghtml .= html_writer::end_tag('form');
1908 return $ratinghtml;
1912 * Centered heading with attached help button (same title text)
1913 * and optional icon attached.
1915 * @param string $text A heading text
1916 * @param string $helpidentifier The keyword that defines a help page
1917 * @param string $component component name
1918 * @param string|moodle_url $icon
1919 * @param string $iconalt icon alt text
1920 * @return string HTML fragment
1922 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '') {
1923 $image = '';
1924 if ($icon) {
1925 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
1928 $help = '';
1929 if ($helpidentifier) {
1930 $help = $this->help_icon($helpidentifier, $component);
1933 return $this->heading($image.$text.$help, 2, 'main help');
1937 * Returns HTML to display a help icon.
1939 * @deprecated since Moodle 2.0
1941 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
1942 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
1946 * Returns HTML to display a help icon.
1948 * Theme developers: DO NOT OVERRIDE! Please override function
1949 * {@link core_renderer::render_help_icon()} instead.
1951 * @param string $identifier The keyword that defines a help page
1952 * @param string $component component name
1953 * @param string|bool $linktext true means use $title as link text, string means link text value
1954 * @return string HTML fragment
1956 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
1957 $icon = new help_icon($identifier, $component);
1958 $icon->diag_strings();
1959 if ($linktext === true) {
1960 $icon->linktext = get_string($icon->identifier, $icon->component);
1961 } else if (!empty($linktext)) {
1962 $icon->linktext = $linktext;
1964 return $this->render($icon);
1968 * Implementation of user image rendering.
1970 * @param help_icon $helpicon A help icon instance
1971 * @return string HTML fragment
1973 protected function render_help_icon(help_icon $helpicon) {
1974 global $CFG;
1976 // first get the help image icon
1977 $src = $this->pix_url('help');
1979 $title = get_string($helpicon->identifier, $helpicon->component);
1981 if (empty($helpicon->linktext)) {
1982 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
1983 } else {
1984 $alt = get_string('helpwiththis');
1987 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1988 $output = html_writer::empty_tag('img', $attributes);
1990 // add the link text if given
1991 if (!empty($helpicon->linktext)) {
1992 // the spacing has to be done through CSS
1993 $output .= $helpicon->linktext;
1996 // now create the link around it - we need https on loginhttps pages
1997 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
1999 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
2000 $title = get_string('helpprefix2', '', trim($title, ". \t"));
2002 $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true', 'target'=>'_blank');
2003 $output = html_writer::tag('a', $output, $attributes);
2005 // and finally span
2006 return html_writer::tag('span', $output, array('class' => 'helptooltip'));
2010 * Returns HTML to display a scale help icon.
2012 * @param int $courseid
2013 * @param stdClass $scale instance
2014 * @return string HTML fragment
2016 public function help_icon_scale($courseid, stdClass $scale) {
2017 global $CFG;
2019 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2021 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2023 $scaleid = abs($scale->id);
2025 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2026 $action = new popup_action('click', $link, 'ratingscale');
2028 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2032 * Creates and returns a spacer image with optional line break.
2034 * @param array $attributes Any HTML attributes to add to the spaced.
2035 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2036 * laxy do it with CSS which is a much better solution.
2037 * @return string HTML fragment
2039 public function spacer(array $attributes = null, $br = false) {
2040 $attributes = (array)$attributes;
2041 if (empty($attributes['width'])) {
2042 $attributes['width'] = 1;
2044 if (empty($attributes['height'])) {
2045 $attributes['height'] = 1;
2047 $attributes['class'] = 'spacer';
2049 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2051 if (!empty($br)) {
2052 $output .= '<br />';
2055 return $output;
2059 * Returns HTML to display the specified user's avatar.
2061 * User avatar may be obtained in two ways:
2062 * <pre>
2063 * // Option 1: (shortcut for simple cases, preferred way)
2064 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2065 * $OUTPUT->user_picture($user, array('popup'=>true));
2067 * // Option 2:
2068 * $userpic = new user_picture($user);
2069 * // Set properties of $userpic
2070 * $userpic->popup = true;
2071 * $OUTPUT->render($userpic);
2072 * </pre>
2074 * Theme developers: DO NOT OVERRIDE! Please override function
2075 * {@link core_renderer::render_user_picture()} instead.
2077 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2078 * If any of these are missing, the database is queried. Avoid this
2079 * if at all possible, particularly for reports. It is very bad for performance.
2080 * @param array $options associative array with user picture options, used only if not a user_picture object,
2081 * options are:
2082 * - courseid=$this->page->course->id (course id of user profile in link)
2083 * - size=35 (size of image)
2084 * - link=true (make image clickable - the link leads to user profile)
2085 * - popup=false (open in popup)
2086 * - alttext=true (add image alt attribute)
2087 * - class = image class attribute (default 'userpicture')
2088 * @return string HTML fragment
2090 public function user_picture(stdClass $user, array $options = null) {
2091 $userpicture = new user_picture($user);
2092 foreach ((array)$options as $key=>$value) {
2093 if (array_key_exists($key, $userpicture)) {
2094 $userpicture->$key = $value;
2097 return $this->render($userpicture);
2101 * Internal implementation of user image rendering.
2103 * @param user_picture $userpicture
2104 * @return string
2106 protected function render_user_picture(user_picture $userpicture) {
2107 global $CFG, $DB;
2109 $user = $userpicture->user;
2111 if ($userpicture->alttext) {
2112 if (!empty($user->imagealt)) {
2113 $alt = $user->imagealt;
2114 } else {
2115 $alt = get_string('pictureof', '', fullname($user));
2117 } else {
2118 $alt = '';
2121 if (empty($userpicture->size)) {
2122 $size = 35;
2123 } else if ($userpicture->size === true or $userpicture->size == 1) {
2124 $size = 100;
2125 } else {
2126 $size = $userpicture->size;
2129 $class = $userpicture->class;
2131 if ($user->picture == 0) {
2132 $class .= ' defaultuserpic';
2135 $src = $userpicture->get_url($this->page, $this);
2137 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2139 // get the image html output fisrt
2140 $output = html_writer::empty_tag('img', $attributes);
2142 // then wrap it in link if needed
2143 if (!$userpicture->link) {
2144 return $output;
2147 if (empty($userpicture->courseid)) {
2148 $courseid = $this->page->course->id;
2149 } else {
2150 $courseid = $userpicture->courseid;
2153 if ($courseid == SITEID) {
2154 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2155 } else {
2156 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2159 $attributes = array('href'=>$url);
2161 if ($userpicture->popup) {
2162 $id = html_writer::random_id('userpicture');
2163 $attributes['id'] = $id;
2164 $this->add_action_handler(new popup_action('click', $url), $id);
2167 return html_writer::tag('a', $output, $attributes);
2171 * Internal implementation of file tree viewer items rendering.
2173 * @param array $dir
2174 * @return string
2176 public function htmllize_file_tree($dir) {
2177 if (empty($dir['subdirs']) and empty($dir['files'])) {
2178 return '';
2180 $result = '<ul>';
2181 foreach ($dir['subdirs'] as $subdir) {
2182 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2184 foreach ($dir['files'] as $file) {
2185 $filename = $file->get_filename();
2186 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2188 $result .= '</ul>';
2190 return $result;
2194 * Returns HTML to display the file picker
2196 * <pre>
2197 * $OUTPUT->file_picker($options);
2198 * </pre>
2200 * Theme developers: DO NOT OVERRIDE! Please override function
2201 * {@link core_renderer::render_file_picker()} instead.
2203 * @param array $options associative array with file manager options
2204 * options are:
2205 * maxbytes=>-1,
2206 * itemid=>0,
2207 * client_id=>uniqid(),
2208 * acepted_types=>'*',
2209 * return_types=>FILE_INTERNAL,
2210 * context=>$PAGE->context
2211 * @return string HTML fragment
2213 public function file_picker($options) {
2214 $fp = new file_picker($options);
2215 return $this->render($fp);
2219 * Internal implementation of file picker rendering.
2221 * @param file_picker $fp
2222 * @return string
2224 public function render_file_picker(file_picker $fp) {
2225 global $CFG, $OUTPUT, $USER;
2226 $options = $fp->options;
2227 $client_id = $options->client_id;
2228 $strsaved = get_string('filesaved', 'repository');
2229 $straddfile = get_string('openpicker', 'repository');
2230 $strloading = get_string('loading', 'repository');
2231 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2232 $strdroptoupload = get_string('droptoupload', 'moodle');
2233 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2235 $currentfile = $options->currentfile;
2236 if (empty($currentfile)) {
2237 $currentfile = '';
2238 } else {
2239 $currentfile .= ' - ';
2241 if ($options->maxbytes) {
2242 $size = $options->maxbytes;
2243 } else {
2244 $size = get_max_upload_file_size();
2246 if ($size == -1) {
2247 $maxsize = '';
2248 } else {
2249 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2251 if ($options->buttonname) {
2252 $buttonname = ' name="' . $options->buttonname . '"';
2253 } else {
2254 $buttonname = '';
2256 $html = <<<EOD
2257 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2258 $icon_progress
2259 </div>
2260 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2261 <div>
2262 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2263 <span> $maxsize </span>
2264 </div>
2265 EOD;
2266 if ($options->env != 'url') {
2267 $html .= <<<EOD
2268 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2269 <div class="filepicker-filename">
2270 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2271 <div class="dndupload-progressbars"></div>
2272 </div>
2273 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2274 </div>
2275 EOD;
2277 $html .= '</div>';
2278 return $html;
2282 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2284 * @param string $cmid the course_module id.
2285 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2286 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2288 public function update_module_button($cmid, $modulename) {
2289 global $CFG;
2290 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2291 $modulename = get_string('modulename', $modulename);
2292 $string = get_string('updatethis', '', $modulename);
2293 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2294 return $this->single_button($url, $string);
2295 } else {
2296 return '';
2301 * Returns HTML to display a "Turn editing on/off" button in a form.
2303 * @param moodle_url $url The URL + params to send through when clicking the button
2304 * @return string HTML the button
2306 public function edit_button(moodle_url $url) {
2308 $url->param('sesskey', sesskey());
2309 if ($this->page->user_is_editing()) {
2310 $url->param('edit', 'off');
2311 $editstring = get_string('turneditingoff');
2312 } else {
2313 $url->param('edit', 'on');
2314 $editstring = get_string('turneditingon');
2317 return $this->single_button($url, $editstring);
2321 * Returns HTML to display a simple button to close a window
2323 * @param string $text The lang string for the button's label (already output from get_string())
2324 * @return string html fragment
2326 public function close_window_button($text='') {
2327 if (empty($text)) {
2328 $text = get_string('closewindow');
2330 $button = new single_button(new moodle_url('#'), $text, 'get');
2331 $button->add_action(new component_action('click', 'close_window'));
2333 return $this->container($this->render($button), 'closewindow');
2337 * Output an error message. By default wraps the error message in <span class="error">.
2338 * If the error message is blank, nothing is output.
2340 * @param string $message the error message.
2341 * @return string the HTML to output.
2343 public function error_text($message) {
2344 if (empty($message)) {
2345 return '';
2347 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2348 return html_writer::tag('span', $message, array('class' => 'error'));
2352 * Do not call this function directly.
2354 * To terminate the current script with a fatal error, call the {@link print_error}
2355 * function, or throw an exception. Doing either of those things will then call this
2356 * function to display the error, before terminating the execution.
2358 * @param string $message The message to output
2359 * @param string $moreinfourl URL where more info can be found about the error
2360 * @param string $link Link for the Continue button
2361 * @param array $backtrace The execution backtrace
2362 * @param string $debuginfo Debugging information
2363 * @return string the HTML to output.
2365 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2366 global $CFG;
2368 $output = '';
2369 $obbuffer = '';
2371 if ($this->has_started()) {
2372 // we can not always recover properly here, we have problems with output buffering,
2373 // html tables, etc.
2374 $output .= $this->opencontainers->pop_all_but_last();
2376 } else {
2377 // It is really bad if library code throws exception when output buffering is on,
2378 // because the buffered text would be printed before our start of page.
2379 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2380 error_reporting(0); // disable notices from gzip compression, etc.
2381 while (ob_get_level() > 0) {
2382 $buff = ob_get_clean();
2383 if ($buff === false) {
2384 break;
2386 $obbuffer .= $buff;
2388 error_reporting($CFG->debug);
2390 // Output not yet started.
2391 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2392 if (empty($_SERVER['HTTP_RANGE'])) {
2393 @header($protocol . ' 404 Not Found');
2394 } else {
2395 // Must stop byteserving attempts somehow,
2396 // this is weird but Chrome PDF viewer can be stopped only with 407!
2397 @header($protocol . ' 407 Proxy Authentication Required');
2400 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2401 $this->page->set_url('/'); // no url
2402 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2403 $this->page->set_title(get_string('error'));
2404 $this->page->set_heading($this->page->course->fullname);
2405 $output .= $this->header();
2408 $message = '<p class="errormessage">' . $message . '</p>'.
2409 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2410 get_string('moreinformation') . '</a></p>';
2411 if (empty($CFG->rolesactive)) {
2412 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2413 //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.
2415 $output .= $this->box($message, 'errorbox');
2417 if (debugging('', DEBUG_DEVELOPER)) {
2418 if (!empty($debuginfo)) {
2419 $debuginfo = s($debuginfo); // removes all nasty JS
2420 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2421 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2423 if (!empty($backtrace)) {
2424 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2426 if ($obbuffer !== '' ) {
2427 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2431 if (empty($CFG->rolesactive)) {
2432 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2433 } else if (!empty($link)) {
2434 $output .= $this->continue_button($link);
2437 $output .= $this->footer();
2439 // Padding to encourage IE to display our error page, rather than its own.
2440 $output .= str_repeat(' ', 512);
2442 return $output;
2446 * Output a notification (that is, a status message about something that has
2447 * just happened).
2449 * @param string $message the message to print out
2450 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2451 * @return string the HTML to output.
2453 public function notification($message, $classes = 'notifyproblem') {
2454 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2458 * Returns HTML to display a continue button that goes to a particular URL.
2460 * @param string|moodle_url $url The url the button goes to.
2461 * @return string the HTML to output.
2463 public function continue_button($url) {
2464 if (!($url instanceof moodle_url)) {
2465 $url = new moodle_url($url);
2467 $button = new single_button($url, get_string('continue'), 'get');
2468 $button->class = 'continuebutton';
2470 return $this->render($button);
2474 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2476 * Theme developers: DO NOT OVERRIDE! Please override function
2477 * {@link core_renderer::render_paging_bar()} instead.
2479 * @param int $totalcount The total number of entries available to be paged through
2480 * @param int $page The page you are currently viewing
2481 * @param int $perpage The number of entries that should be shown per page
2482 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2483 * @param string $pagevar name of page parameter that holds the page number
2484 * @return string the HTML to output.
2486 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2487 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2488 return $this->render($pb);
2492 * Internal implementation of paging bar rendering.
2494 * @param paging_bar $pagingbar
2495 * @return string
2497 protected function render_paging_bar(paging_bar $pagingbar) {
2498 $output = '';
2499 $pagingbar = clone($pagingbar);
2500 $pagingbar->prepare($this, $this->page, $this->target);
2502 if ($pagingbar->totalcount > $pagingbar->perpage) {
2503 $output .= get_string('page') . ':';
2505 if (!empty($pagingbar->previouslink)) {
2506 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
2509 if (!empty($pagingbar->firstlink)) {
2510 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
2513 foreach ($pagingbar->pagelinks as $link) {
2514 $output .= "&#160;&#160;$link";
2517 if (!empty($pagingbar->lastlink)) {
2518 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
2521 if (!empty($pagingbar->nextlink)) {
2522 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
2526 return html_writer::tag('div', $output, array('class' => 'paging'));
2530 * Output the place a skip link goes to.
2532 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2533 * @return string the HTML to output.
2535 public function skip_link_target($id = null) {
2536 return html_writer::tag('span', '', array('id' => $id));
2540 * Outputs a heading
2542 * @param string $text The text of the heading
2543 * @param int $level The level of importance of the heading. Defaulting to 2
2544 * @param string $classes A space-separated list of CSS classes
2545 * @param string $id An optional ID
2546 * @return string the HTML to output.
2548 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2549 $level = (integer) $level;
2550 if ($level < 1 or $level > 6) {
2551 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2553 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2557 * Outputs a box.
2559 * @param string $contents The contents of the box
2560 * @param string $classes A space-separated list of CSS classes
2561 * @param string $id An optional ID
2562 * @return string the HTML to output.
2564 public function box($contents, $classes = 'generalbox', $id = null) {
2565 return $this->box_start($classes, $id) . $contents . $this->box_end();
2569 * Outputs the opening section of a box.
2571 * @param string $classes A space-separated list of CSS classes
2572 * @param string $id An optional ID
2573 * @return string the HTML to output.
2575 public function box_start($classes = 'generalbox', $id = null) {
2576 $this->opencontainers->push('box', html_writer::end_tag('div'));
2577 return html_writer::start_tag('div', array('id' => $id,
2578 'class' => 'box ' . renderer_base::prepare_classes($classes)));
2582 * Outputs the closing section of a box.
2584 * @return string the HTML to output.
2586 public function box_end() {
2587 return $this->opencontainers->pop('box');
2591 * Outputs a container.
2593 * @param string $contents The contents of the box
2594 * @param string $classes A space-separated list of CSS classes
2595 * @param string $id An optional ID
2596 * @return string the HTML to output.
2598 public function container($contents, $classes = null, $id = null) {
2599 return $this->container_start($classes, $id) . $contents . $this->container_end();
2603 * Outputs the opening section of a container.
2605 * @param string $classes A space-separated list of CSS classes
2606 * @param string $id An optional ID
2607 * @return string the HTML to output.
2609 public function container_start($classes = null, $id = null) {
2610 $this->opencontainers->push('container', html_writer::end_tag('div'));
2611 return html_writer::start_tag('div', array('id' => $id,
2612 'class' => renderer_base::prepare_classes($classes)));
2616 * Outputs the closing section of a container.
2618 * @return string the HTML to output.
2620 public function container_end() {
2621 return $this->opencontainers->pop('container');
2625 * Make nested HTML lists out of the items
2627 * The resulting list will look something like this:
2629 * <pre>
2630 * <<ul>>
2631 * <<li>><div class='tree_item parent'>(item contents)</div>
2632 * <<ul>
2633 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2634 * <</ul>>
2635 * <</li>>
2636 * <</ul>>
2637 * </pre>
2639 * @param array $items
2640 * @param array $attrs html attributes passed to the top ofs the list
2641 * @return string HTML
2643 public function tree_block_contents($items, $attrs = array()) {
2644 // exit if empty, we don't want an empty ul element
2645 if (empty($items)) {
2646 return '';
2648 // array of nested li elements
2649 $lis = array();
2650 foreach ($items as $item) {
2651 // this applies to the li item which contains all child lists too
2652 $content = $item->content($this);
2653 $liclasses = array($item->get_css_type());
2654 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2655 $liclasses[] = 'collapsed';
2657 if ($item->isactive === true) {
2658 $liclasses[] = 'current_branch';
2660 $liattr = array('class'=>join(' ',$liclasses));
2661 // class attribute on the div item which only contains the item content
2662 $divclasses = array('tree_item');
2663 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2664 $divclasses[] = 'branch';
2665 } else {
2666 $divclasses[] = 'leaf';
2668 if (!empty($item->classes) && count($item->classes)>0) {
2669 $divclasses[] = join(' ', $item->classes);
2671 $divattr = array('class'=>join(' ', $divclasses));
2672 if (!empty($item->id)) {
2673 $divattr['id'] = $item->id;
2675 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2676 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2677 $content = html_writer::empty_tag('hr') . $content;
2679 $content = html_writer::tag('li', $content, $liattr);
2680 $lis[] = $content;
2682 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2686 * Return the navbar content so that it can be echoed out by the layout
2688 * @return string XHTML navbar
2690 public function navbar() {
2691 $items = $this->page->navbar->get_items();
2692 $itemcount = count($items);
2693 if ($itemcount === 0) {
2694 return '';
2697 $htmlblocks = array();
2698 // Iterate the navarray and display each node
2699 $separator = get_separator();
2700 for ($i=0;$i < $itemcount;$i++) {
2701 $item = $items[$i];
2702 $item->hideicon = true;
2703 if ($i===0) {
2704 $content = html_writer::tag('li', $this->render($item));
2705 } else {
2706 $content = html_writer::tag('li', $separator.$this->render($item));
2708 $htmlblocks[] = $content;
2711 //accessibility: heading for navbar list (MDL-20446)
2712 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2713 $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks), array('role'=>'navigation'));
2714 // XHTML
2715 return $navbarcontent;
2719 * Renders a navigation node object.
2721 * @param navigation_node $item The navigation node to render.
2722 * @return string HTML fragment
2724 protected function render_navigation_node(navigation_node $item) {
2725 $content = $item->get_content();
2726 $title = $item->get_title();
2727 if ($item->icon instanceof renderable && !$item->hideicon) {
2728 $icon = $this->render($item->icon);
2729 $content = $icon.$content; // use CSS for spacing of icons
2731 if ($item->helpbutton !== null) {
2732 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2734 if ($content === '') {
2735 return '';
2737 if ($item->action instanceof action_link) {
2738 $link = $item->action;
2739 if ($item->hidden) {
2740 $link->add_class('dimmed');
2742 if (!empty($content)) {
2743 // Providing there is content we will use that for the link content.
2744 $link->text = $content;
2746 $content = $this->render($link);
2747 } else if ($item->action instanceof moodle_url) {
2748 $attributes = array();
2749 if ($title !== '') {
2750 $attributes['title'] = $title;
2752 if ($item->hidden) {
2753 $attributes['class'] = 'dimmed_text';
2755 $content = html_writer::link($item->action, $content, $attributes);
2757 } else if (is_string($item->action) || empty($item->action)) {
2758 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2759 if ($title !== '') {
2760 $attributes['title'] = $title;
2762 if ($item->hidden) {
2763 $attributes['class'] = 'dimmed_text';
2765 $content = html_writer::tag('span', $content, $attributes);
2767 return $content;
2771 * Accessibility: Right arrow-like character is
2772 * used in the breadcrumb trail, course navigation menu
2773 * (previous/next activity), calendar, and search forum block.
2774 * If the theme does not set characters, appropriate defaults
2775 * are set automatically. Please DO NOT
2776 * use &lt; &gt; &raquo; - these are confusing for blind users.
2778 * @return string
2780 public function rarrow() {
2781 return $this->page->theme->rarrow;
2785 * Accessibility: Right arrow-like character is
2786 * used in the breadcrumb trail, course navigation menu
2787 * (previous/next activity), calendar, and search forum block.
2788 * If the theme does not set characters, appropriate defaults
2789 * are set automatically. Please DO NOT
2790 * use &lt; &gt; &raquo; - these are confusing for blind users.
2792 * @return string
2794 public function larrow() {
2795 return $this->page->theme->larrow;
2799 * Returns the custom menu if one has been set
2801 * A custom menu can be configured by browsing to
2802 * Settings: Administration > Appearance > Themes > Theme settings
2803 * and then configuring the custommenu config setting as described.
2805 * Theme developers: DO NOT OVERRIDE! Please override function
2806 * {@link core_renderer::render_custom_menu()} instead.
2808 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
2809 * @return string
2811 public function custom_menu($custommenuitems = '') {
2812 global $CFG;
2813 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
2814 $custommenuitems = $CFG->custommenuitems;
2816 if (empty($custommenuitems)) {
2817 return '';
2819 $custommenu = new custom_menu($custommenuitems, current_language());
2820 return $this->render($custommenu);
2824 * Renders a custom menu object (located in outputcomponents.php)
2826 * The custom menu this method produces makes use of the YUI3 menunav widget
2827 * and requires very specific html elements and classes.
2829 * @staticvar int $menucount
2830 * @param custom_menu $menu
2831 * @return string
2833 protected function render_custom_menu(custom_menu $menu) {
2834 static $menucount = 0;
2835 // If the menu has no children return an empty string
2836 if (!$menu->has_children()) {
2837 return '';
2839 // Increment the menu count. This is used for ID's that get worked with
2840 // in JavaScript as is essential
2841 $menucount++;
2842 // Initialise this custom menu (the custom menu object is contained in javascript-static
2843 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
2844 $jscode = "(function(){{$jscode}})";
2845 $this->page->requires->yui_module('node-menunav', $jscode);
2846 // Build the root nodes as required by YUI
2847 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
2848 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2849 $content .= html_writer::start_tag('ul');
2850 // Render each child
2851 foreach ($menu->get_children() as $item) {
2852 $content .= $this->render_custom_menu_item($item);
2854 // Close the open tags
2855 $content .= html_writer::end_tag('ul');
2856 $content .= html_writer::end_tag('div');
2857 $content .= html_writer::end_tag('div');
2858 // Return the custom menu
2859 return $content;
2863 * Renders a custom menu node as part of a submenu
2865 * The custom menu this method produces makes use of the YUI3 menunav widget
2866 * and requires very specific html elements and classes.
2868 * @see core:renderer::render_custom_menu()
2870 * @staticvar int $submenucount
2871 * @param custom_menu_item $menunode
2872 * @return string
2874 protected function render_custom_menu_item(custom_menu_item $menunode) {
2875 // Required to ensure we get unique trackable id's
2876 static $submenucount = 0;
2877 if ($menunode->has_children()) {
2878 // If the child has menus render it as a sub menu
2879 $submenucount++;
2880 $content = html_writer::start_tag('li');
2881 if ($menunode->get_url() !== null) {
2882 $url = $menunode->get_url();
2883 } else {
2884 $url = '#cm_submenu_'.$submenucount;
2886 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
2887 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
2888 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2889 $content .= html_writer::start_tag('ul');
2890 foreach ($menunode->get_children() as $menunode) {
2891 $content .= $this->render_custom_menu_item($menunode);
2893 $content .= html_writer::end_tag('ul');
2894 $content .= html_writer::end_tag('div');
2895 $content .= html_writer::end_tag('div');
2896 $content .= html_writer::end_tag('li');
2897 } else {
2898 // The node doesn't have children so produce a final menuitem
2899 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
2900 if ($menunode->get_url() !== null) {
2901 $url = $menunode->get_url();
2902 } else {
2903 $url = '#';
2905 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
2906 $content .= html_writer::end_tag('li');
2908 // Return the sub menu
2909 return $content;
2913 * Renders theme links for switching between default and other themes.
2915 * @return string
2917 protected function theme_switch_links() {
2919 $actualdevice = get_device_type();
2920 $currentdevice = $this->page->devicetypeinuse;
2921 $switched = ($actualdevice != $currentdevice);
2923 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
2924 // The user is using the a default device and hasn't switched so don't shown the switch
2925 // device links.
2926 return '';
2929 if ($switched) {
2930 $linktext = get_string('switchdevicerecommended');
2931 $devicetype = $actualdevice;
2932 } else {
2933 $linktext = get_string('switchdevicedefault');
2934 $devicetype = 'default';
2936 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
2938 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
2939 $content .= html_writer::link($linkurl, $linktext);
2940 $content .= html_writer::end_tag('div');
2942 return $content;
2946 * Renders tabs
2948 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
2950 * Theme developers: In order to change how tabs are displayed please override functions
2951 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
2953 * @param array $tabs array of tabs, each of them may have it's own ->subtree
2954 * @param string|null $selected which tab to mark as selected, all parent tabs will
2955 * automatically be marked as activated
2956 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
2957 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
2958 * @return string
2960 public final function tabtree($tabs, $selected = null, $inactive = null) {
2961 return $this->render(new tabtree($tabs, $selected, $inactive));
2965 * Renders tabtree
2967 * @param tabtree $tabtree
2968 * @return string
2970 protected function render_tabtree(tabtree $tabtree) {
2971 if (empty($tabtree->subtree)) {
2972 return '';
2974 $str = '';
2975 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
2976 $str .= $this->render_tabobject($tabtree);
2977 $str .= html_writer::end_tag('div').
2978 html_writer::tag('div', ' ', array('class' => 'clearer'));
2979 return $str;
2983 * Renders tabobject (part of tabtree)
2985 * This function is called from {@link core_renderer::render_tabtree()}
2986 * and also it calls itself when printing the $tabobject subtree recursively.
2988 * Property $tabobject->level indicates the number of row of tabs.
2990 * @param tabobject $tabobject
2991 * @return string HTML fragment
2993 protected function render_tabobject(tabobject $tabobject) {
2994 $str = '';
2996 // Print name of the current tab.
2997 if ($tabobject instanceof tabtree) {
2998 // No name for tabtree root.
2999 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3000 // Tab name without a link. The <a> tag is used for styling.
3001 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink'));
3002 } else {
3003 // Tab name with a link.
3004 if (!($tabobject->link instanceof moodle_url)) {
3005 // backward compartibility when link was passed as quoted string
3006 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3007 } else {
3008 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3012 if (empty($tabobject->subtree)) {
3013 if ($tabobject->selected) {
3014 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3016 return $str;
3019 // Print subtree
3020 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3021 $cnt = 0;
3022 foreach ($tabobject->subtree as $tab) {
3023 $liclass = '';
3024 if (!$cnt) {
3025 $liclass .= ' first';
3027 if ($cnt == count($tabobject->subtree) - 1) {
3028 $liclass .= ' last';
3030 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3031 $liclass .= ' onerow';
3034 if ($tab->selected) {
3035 $liclass .= ' here selected';
3036 } else if ($tab->activated) {
3037 $liclass .= ' here active';
3040 // This will recursively call function render_tabobject() for each item in subtree
3041 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3042 $cnt++;
3044 $str .= html_writer::end_tag('ul');
3046 return $str;
3050 * Get the HTML for blocks in the given region.
3052 * @since 2.5.1 2.6
3053 * @param string $region The region to get HTML for.
3054 * @return string HTML.
3056 public function blocks($region, $classes = array(), $tag = 'aside') {
3057 $displayregion = $this->page->apply_theme_region_manipulations($region);
3058 $classes = (array)$classes;
3059 $classes[] = 'block-region';
3060 $attributes = array(
3061 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3062 'class' => join(' ', $classes),
3063 'data-blockregion' => $displayregion,
3064 'data-droptarget' => '1'
3066 return html_writer::tag($tag, $this->blocks_for_region($region), $attributes);
3070 * Returns the CSS classes to apply to the body tag.
3072 * @since 2.5.1 2.6
3073 * @param array $additionalclasses Any additional classes to apply.
3074 * @return string
3076 public function body_css_classes(array $additionalclasses = array()) {
3077 // Add a class for each block region on the page.
3078 // We use the block manager here because the theme object makes get_string calls.
3079 foreach ($this->page->blocks->get_regions() as $region) {
3080 $additionalclasses[] = 'has-region-'.$region;
3081 if ($this->page->blocks->region_has_content($region, $this)) {
3082 $additionalclasses[] = 'used-region-'.$region;
3083 } else {
3084 $additionalclasses[] = 'empty-region-'.$region;
3087 foreach ($this->page->layout_options as $option => $value) {
3088 if ($value) {
3089 $additionalclasses[] = 'layout-option-'.$option;
3092 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
3093 return $css;
3097 * The ID attribute to apply to the body tag.
3099 * @since 2.5.1 2.6
3100 * @return string
3102 public function body_id() {
3103 return $this->page->bodyid;
3107 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
3109 * @since 2.5.1 2.6
3110 * @param string|array $additionalclasses Any additional classes to give the body tag,
3111 * @return string
3113 public function body_attributes($additionalclasses = array()) {
3114 if (!is_array($additionalclasses)) {
3115 $additionalclasses = explode(' ', $additionalclasses);
3117 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
3121 * Gets HTML for the page heading.
3123 * @since 2.5.1 2.6
3124 * @param string $tag The tag to encase the heading in. h1 by default.
3125 * @return string HTML.
3127 public function page_heading($tag = 'h1') {
3128 return html_writer::tag($tag, $this->page->heading);
3132 * Gets the HTML for the page heading button.
3134 * @since 2.5.1 2.6
3135 * @return string HTML.
3137 public function page_heading_button() {
3138 return $this->page->button;
3142 * Returns the Moodle docs link to use for this page.
3144 * @since 2.5.1 2.6
3145 * @param string $text
3146 * @return string
3148 public function page_doc_link($text = null) {
3149 if ($text === null) {
3150 $text = get_string('moodledocslink');
3152 $path = page_get_doc_link_path($this->page);
3153 if (!$path) {
3154 return '';
3156 return $this->doc_link($path, $text);
3160 * Returns the page heading menu.
3162 * @since 2.5.1 2.6
3163 * @return string HTML.
3165 public function page_heading_menu() {
3166 return $this->page->headingmenu;
3170 * Returns the title to use on the page.
3172 * @since 2.5.1 2.6
3173 * @return string
3175 public function page_title() {
3176 return $this->page->title;
3180 * Returns the URL for the favicon.
3182 * @since 2.5.1 2.6
3183 * @return string The favicon URL
3185 public function favicon() {
3186 return $this->pix_url('favicon', 'theme');
3191 * A renderer that generates output for command-line scripts.
3193 * The implementation of this renderer is probably incomplete.
3195 * @copyright 2009 Tim Hunt
3196 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3197 * @since Moodle 2.0
3198 * @package core
3199 * @category output
3201 class core_renderer_cli extends core_renderer {
3204 * Returns the page header.
3206 * @return string HTML fragment
3208 public function header() {
3209 return $this->page->heading . "\n";
3213 * Returns a template fragment representing a Heading.
3215 * @param string $text The text of the heading
3216 * @param int $level The level of importance of the heading
3217 * @param string $classes A space-separated list of CSS classes
3218 * @param string $id An optional ID
3219 * @return string A template fragment for a heading
3221 public function heading($text, $level = 2, $classes = 'main', $id = null) {
3222 $text .= "\n";
3223 switch ($level) {
3224 case 1:
3225 return '=>' . $text;
3226 case 2:
3227 return '-->' . $text;
3228 default:
3229 return $text;
3234 * Returns a template fragment representing a fatal error.
3236 * @param string $message The message to output
3237 * @param string $moreinfourl URL where more info can be found about the error
3238 * @param string $link Link for the Continue button
3239 * @param array $backtrace The execution backtrace
3240 * @param string $debuginfo Debugging information
3241 * @return string A template fragment for a fatal error
3243 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
3244 $output = "!!! $message !!!\n";
3246 if (debugging('', DEBUG_DEVELOPER)) {
3247 if (!empty($debuginfo)) {
3248 $output .= $this->notification($debuginfo, 'notifytiny');
3250 if (!empty($backtrace)) {
3251 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
3255 return $output;
3259 * Returns a template fragment representing a notification.
3261 * @param string $message The message to include
3262 * @param string $classes A space-separated list of CSS classes
3263 * @return string A template fragment for a notification
3265 public function notification($message, $classes = 'notifyproblem') {
3266 $message = clean_text($message);
3267 if ($classes === 'notifysuccess') {
3268 return "++ $message ++\n";
3270 return "!! $message !!\n";
3276 * A renderer that generates output for ajax scripts.
3278 * This renderer prevents accidental sends back only json
3279 * encoded error messages, all other output is ignored.
3281 * @copyright 2010 Petr Skoda
3282 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3283 * @since Moodle 2.0
3284 * @package core
3285 * @category output
3287 class core_renderer_ajax extends core_renderer {
3290 * Returns a template fragment representing a fatal error.
3292 * @param string $message The message to output
3293 * @param string $moreinfourl URL where more info can be found about the error
3294 * @param string $link Link for the Continue button
3295 * @param array $backtrace The execution backtrace
3296 * @param string $debuginfo Debugging information
3297 * @return string A template fragment for a fatal error
3299 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
3300 global $CFG;
3302 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
3304 $e = new stdClass();
3305 $e->error = $message;
3306 $e->stacktrace = NULL;
3307 $e->debuginfo = NULL;
3308 $e->reproductionlink = NULL;
3309 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
3310 $e->reproductionlink = $link;
3311 if (!empty($debuginfo)) {
3312 $e->debuginfo = $debuginfo;
3314 if (!empty($backtrace)) {
3315 $e->stacktrace = format_backtrace($backtrace, true);
3318 $this->header();
3319 return json_encode($e);
3323 * Used to display a notification.
3324 * For the AJAX notifications are discarded.
3326 * @param string $message
3327 * @param string $classes
3329 public function notification($message, $classes = 'notifyproblem') {}
3332 * Used to display a redirection message.
3333 * AJAX redirections should not occur and as such redirection messages
3334 * are discarded.
3336 * @param moodle_url|string $encodedurl
3337 * @param string $message
3338 * @param int $delay
3339 * @param bool $debugdisableredirect
3341 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
3344 * Prepares the start of an AJAX output.
3346 public function header() {
3347 // unfortunately YUI iframe upload does not support application/json
3348 if (!empty($_FILES)) {
3349 @header('Content-type: text/plain; charset=utf-8');
3350 } else {
3351 @header('Content-type: application/json; charset=utf-8');
3354 // Headers to make it not cacheable and json
3355 @header('Cache-Control: no-store, no-cache, must-revalidate');
3356 @header('Cache-Control: post-check=0, pre-check=0', false);
3357 @header('Pragma: no-cache');
3358 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
3359 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
3360 @header('Accept-Ranges: none');
3364 * There is no footer for an AJAX request, however we must override the
3365 * footer method to prevent the default footer.
3367 public function footer() {}
3370 * No need for headers in an AJAX request... this should never happen.
3371 * @param string $text
3372 * @param int $level
3373 * @param string $classes
3374 * @param string $id
3376 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
3381 * Renderer for media files.
3383 * Used in file resources, media filter, and any other places that need to
3384 * output embedded media.
3386 * @copyright 2011 The Open University
3387 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3389 class core_media_renderer extends plugin_renderer_base {
3390 /** @var array Array of available 'player' objects */
3391 private $players;
3392 /** @var string Regex pattern for links which may contain embeddable content */
3393 private $embeddablemarkers;
3396 * Constructor requires medialib.php.
3398 * This is needed in the constructor (not later) so that you can use the
3399 * constants and static functions that are defined in core_media class
3400 * before you call renderer functions.
3402 public function __construct() {
3403 global $CFG;
3404 require_once($CFG->libdir . '/medialib.php');
3408 * Obtains the list of core_media_player objects currently in use to render
3409 * items.
3411 * The list is in rank order (highest first) and does not include players
3412 * which are disabled.
3414 * @return array Array of core_media_player objects in rank order
3416 protected function get_players() {
3417 global $CFG;
3419 // Save time by only building the list once.
3420 if (!$this->players) {
3421 // Get raw list of players.
3422 $players = $this->get_players_raw();
3424 // Chuck all the ones that are disabled.
3425 foreach ($players as $key => $player) {
3426 if (!$player->is_enabled()) {
3427 unset($players[$key]);
3431 // Sort in rank order (highest first).
3432 usort($players, array('core_media_player', 'compare_by_rank'));
3433 $this->players = $players;
3435 return $this->players;
3439 * Obtains a raw list of player objects that includes objects regardless
3440 * of whether they are disabled or not, and without sorting.
3442 * You can override this in a subclass if you need to add additional
3443 * players.
3445 * The return array is be indexed by player name to make it easier to
3446 * remove players in a subclass.
3448 * @return array $players Array of core_media_player objects in any order
3450 protected function get_players_raw() {
3451 return array(
3452 'vimeo' => new core_media_player_vimeo(),
3453 'youtube' => new core_media_player_youtube(),
3454 'youtube_playlist' => new core_media_player_youtube_playlist(),
3455 'html5video' => new core_media_player_html5video(),
3456 'html5audio' => new core_media_player_html5audio(),
3457 'mp3' => new core_media_player_mp3(),
3458 'flv' => new core_media_player_flv(),
3459 'wmp' => new core_media_player_wmp(),
3460 'qt' => new core_media_player_qt(),
3461 'rm' => new core_media_player_rm(),
3462 'swf' => new core_media_player_swf(),
3463 'link' => new core_media_player_link(),
3468 * Renders a media file (audio or video) using suitable embedded player.
3470 * See embed_alternatives function for full description of parameters.
3471 * This function calls through to that one.
3473 * When using this function you can also specify width and height in the
3474 * URL by including ?d=100x100 at the end. If specified in the URL, this
3475 * will override the $width and $height parameters.
3477 * @param moodle_url $url Full URL of media file
3478 * @param string $name Optional user-readable name to display in download link
3479 * @param int $width Width in pixels (optional)
3480 * @param int $height Height in pixels (optional)
3481 * @param array $options Array of key/value pairs
3482 * @return string HTML content of embed
3484 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
3485 $options = array()) {
3487 // Get width and height from URL if specified (overrides parameters in
3488 // function call).
3489 $rawurl = $url->out(false);
3490 if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
3491 $width = $matches[1];
3492 $height = $matches[2];
3493 $url = new moodle_url(str_replace($matches[0], '', $rawurl));
3496 // Defer to array version of function.
3497 return $this->embed_alternatives(array($url), $name, $width, $height, $options);
3501 * Renders media files (audio or video) using suitable embedded player.
3502 * The list of URLs should be alternative versions of the same content in
3503 * multiple formats. If there is only one format it should have a single
3504 * entry.
3506 * If the media files are not in a supported format, this will give students
3507 * a download link to each format. The download link uses the filename
3508 * unless you supply the optional name parameter.
3510 * Width and height are optional. If specified, these are suggested sizes
3511 * and should be the exact values supplied by the user, if they come from
3512 * user input. These will be treated as relating to the size of the video
3513 * content, not including any player control bar.
3515 * For audio files, height will be ignored. For video files, a few formats
3516 * work if you specify only width, but in general if you specify width
3517 * you must specify height as well.
3519 * The $options array is passed through to the core_media_player classes
3520 * that render the object tag. The keys can contain values from
3521 * core_media::OPTION_xx.
3523 * @param array $alternatives Array of moodle_url to media files
3524 * @param string $name Optional user-readable name to display in download link
3525 * @param int $width Width in pixels (optional)
3526 * @param int $height Height in pixels (optional)
3527 * @param array $options Array of key/value pairs
3528 * @return string HTML content of embed
3530 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
3531 $options = array()) {
3533 // Get list of player plugins (will also require the library).
3534 $players = $this->get_players();
3536 // Set up initial text which will be replaced by first player that
3537 // supports any of the formats.
3538 $out = core_media_player::PLACEHOLDER;
3540 // Loop through all players that support any of these URLs.
3541 foreach ($players as $player) {
3542 // Option: When no other player matched, don't do the default link player.
3543 if (!empty($options[core_media::OPTION_FALLBACK_TO_BLANK]) &&
3544 $player->get_rank() === 0 && $out === core_media_player::PLACEHOLDER) {
3545 continue;
3548 $supported = $player->list_supported_urls($alternatives, $options);
3549 if ($supported) {
3550 // Embed.
3551 $text = $player->embed($supported, $name, $width, $height, $options);
3553 // Put this in place of the 'fallback' slot in the previous text.
3554 $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
3558 // Remove 'fallback' slot from final version and return it.
3559 $out = str_replace(core_media_player::PLACEHOLDER, '', $out);
3560 if (!empty($options[core_media::OPTION_BLOCK]) && $out !== '') {
3561 $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
3563 return $out;
3567 * Checks whether a file can be embedded. If this returns true you will get
3568 * an embedded player; if this returns false, you will just get a download
3569 * link.
3571 * This is a wrapper for can_embed_urls.
3573 * @param moodle_url $url URL of media file
3574 * @param array $options Options (same as when embedding)
3575 * @return bool True if file can be embedded
3577 public function can_embed_url(moodle_url $url, $options = array()) {
3578 return $this->can_embed_urls(array($url), $options);
3582 * Checks whether a file can be embedded. If this returns true you will get
3583 * an embedded player; if this returns false, you will just get a download
3584 * link.
3586 * @param array $urls URL of media file and any alternatives (moodle_url)
3587 * @param array $options Options (same as when embedding)
3588 * @return bool True if file can be embedded
3590 public function can_embed_urls(array $urls, $options = array()) {
3591 // Check all players to see if any of them support it.
3592 foreach ($this->get_players() as $player) {
3593 // Link player (always last on list) doesn't count!
3594 if ($player->get_rank() <= 0) {
3595 break;
3597 // First player that supports it, return true.
3598 if ($player->list_supported_urls($urls, $options)) {
3599 return true;
3602 return false;
3606 * Obtains a list of markers that can be used in a regular expression when
3607 * searching for URLs that can be embedded by any player type.
3609 * This string is used to improve peformance of regex matching by ensuring
3610 * that the (presumably C) regex code can do a quick keyword check on the
3611 * URL part of a link to see if it matches one of these, rather than having
3612 * to go into PHP code for every single link to see if it can be embedded.
3614 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
3616 public function get_embeddable_markers() {
3617 if (empty($this->embeddablemarkers)) {
3618 $markers = '';
3619 foreach ($this->get_players() as $player) {
3620 foreach ($player->get_embeddable_markers() as $marker) {
3621 if ($markers !== '') {
3622 $markers .= '|';
3624 $markers .= preg_quote($marker);
3627 $this->embeddablemarkers = $markers;
3629 return $this->embeddablemarkers;