Merge branch 'MDL-42392-26' of git://github.com/andrewnicols/moodle into MOODLE_26_STABLE
[moodle.git] / lib / outputrenderers.php
blobdf70c7802c448b102ab1154d1b1db561d446d5c9
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
21 * for an overview.
23 * Included in this file are the primary renderer classes:
24 * - renderer_base: The renderer outline class that all renderers
25 * should inherit from.
26 * - core_renderer: The standard HTML renderer.
27 * - core_renderer_cli: An adaption of the standard renderer for CLI scripts.
28 * - core_renderer_ajax: An adaption of the standard renderer for AJAX scripts.
29 * - plugin_renderer_base: A renderer class that should be extended by all
30 * plugin renderers.
32 * @package core
33 * @category output
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') || die();
40 /**
41 * Simple base class for Moodle renderers.
43 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
45 * Also has methods to facilitate generating HTML output.
47 * @copyright 2009 Tim Hunt
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 * @since Moodle 2.0
50 * @package core
51 * @category output
53 class renderer_base {
54 /**
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
59 /**
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
62 protected $page;
64 /**
65 * @var string The requested rendering target.
67 protected $target;
69 /**
70 * Constructor
72 * The constructor takes two arguments. The first is the page that the renderer
73 * has been created to assist with, and the second is the target.
74 * The target is an additional identifier that can be used to load different
75 * renderers for different options.
77 * @param moodle_page $page the page we are doing output for.
78 * @param string $target one of rendering target constants
80 public function __construct(moodle_page $page, $target) {
81 $this->opencontainers = $page->opencontainers;
82 $this->page = $page;
83 $this->target = $target;
86 /**
87 * Returns rendered widget.
89 * The provided widget needs to be an object that extends the renderable
90 * interface.
91 * If will then be rendered by a method based upon the classname for the widget.
92 * For instance a widget of class `crazywidget` will be rendered by a protected
93 * render_crazywidget method of this renderer.
95 * @param renderable $widget instance with renderable interface
96 * @return string
98 public function render(renderable $widget) {
99 $rendermethod = 'render_'.get_class($widget);
100 if (method_exists($this, $rendermethod)) {
101 return $this->$rendermethod($widget);
103 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
107 * Adds a JS action for the element with the provided id.
109 * This method adds a JS event for the provided component action to the page
110 * and then returns the id that the event has been attached to.
111 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
113 * @param component_action $action
114 * @param string $id
115 * @return string id of element, either original submitted or random new if not supplied
117 public function add_action_handler(component_action $action, $id = null) {
118 if (!$id) {
119 $id = html_writer::random_id($action->event);
121 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
122 return $id;
126 * Returns true is output has already started, and false if not.
128 * @return boolean true if the header has been printed.
130 public function has_started() {
131 return $this->page->state >= moodle_page::STATE_IN_BODY;
135 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
137 * @param mixed $classes Space-separated string or array of classes
138 * @return string HTML class attribute value
140 public static function prepare_classes($classes) {
141 if (is_array($classes)) {
142 return implode(' ', array_unique($classes));
144 return $classes;
148 * Return the moodle_url for an image.
150 * The exact image location and extension is determined
151 * automatically by searching for gif|png|jpg|jpeg, please
152 * note there can not be diferent images with the different
153 * extension. The imagename is for historical reasons
154 * a relative path name, it may be changed later for core
155 * images. It is recommended to not use subdirectories
156 * in plugin and theme pix directories.
158 * There are three types of images:
159 * 1/ theme images - stored in theme/mytheme/pix/,
160 * use component 'theme'
161 * 2/ core images - stored in /pix/,
162 * overridden via theme/mytheme/pix_core/
163 * 3/ plugin images - stored in mod/mymodule/pix,
164 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
165 * example: pix_url('comment', 'mod_glossary')
167 * @param string $imagename the pathname of the image
168 * @param string $component full plugin name (aka component) or 'theme'
169 * @return moodle_url
171 public function pix_url($imagename, $component = 'moodle') {
172 return $this->page->theme->pix_url($imagename, $component);
178 * Basis for all plugin renderers.
180 * @copyright Petr Skoda (skodak)
181 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
182 * @since Moodle 2.0
183 * @package core
184 * @category output
186 class plugin_renderer_base extends renderer_base {
189 * @var renderer_base|core_renderer A reference to the current renderer.
190 * The renderer provided here will be determined by the page but will in 90%
191 * of cases by the {@link core_renderer}
193 protected $output;
196 * Constructor method, calls the parent constructor
198 * @param moodle_page $page
199 * @param string $target one of rendering target constants
201 public function __construct(moodle_page $page, $target) {
202 if (empty($target) && $page->pagelayout === 'maintenance') {
203 // If the page is using the maintenance layout then we're going to force the target to maintenance.
204 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
205 // unavailable for this page layout.
206 $target = RENDERER_TARGET_MAINTENANCE;
208 $this->output = $page->get_renderer('core', null, $target);
209 parent::__construct($page, $target);
213 * Renders the provided widget and returns the HTML to display it.
215 * @param renderable $widget instance with renderable interface
216 * @return string
218 public function render(renderable $widget) {
219 $rendermethod = 'render_'.get_class($widget);
220 if (method_exists($this, $rendermethod)) {
221 return $this->$rendermethod($widget);
223 // pass to core renderer if method not found here
224 return $this->output->render($widget);
228 * Magic method used to pass calls otherwise meant for the standard renderer
229 * to it to ensure we don't go causing unnecessary grief.
231 * @param string $method
232 * @param array $arguments
233 * @return mixed
235 public function __call($method, $arguments) {
236 if (method_exists('renderer_base', $method)) {
237 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
239 if (method_exists($this->output, $method)) {
240 return call_user_func_array(array($this->output, $method), $arguments);
241 } else {
242 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
249 * The standard implementation of the core_renderer interface.
251 * @copyright 2009 Tim Hunt
252 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
253 * @since Moodle 2.0
254 * @package core
255 * @category output
257 class core_renderer extends renderer_base {
259 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
260 * in layout files instead.
261 * @deprecated
262 * @var string used in {@link core_renderer::header()}.
264 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
267 * @var string Used to pass information from {@link core_renderer::doctype()} to
268 * {@link core_renderer::standard_head_html()}.
270 protected $contenttype;
273 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
274 * with {@link core_renderer::header()}.
276 protected $metarefreshtag = '';
279 * @var string Unique token for the closing HTML
281 protected $unique_end_html_token;
284 * @var string Unique token for performance information
286 protected $unique_performance_info_token;
289 * @var string Unique token for the main content.
291 protected $unique_main_content_token;
294 * Constructor
296 * @param moodle_page $page the page we are doing output for.
297 * @param string $target one of rendering target constants
299 public function __construct(moodle_page $page, $target) {
300 $this->opencontainers = $page->opencontainers;
301 $this->page = $page;
302 $this->target = $target;
304 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
305 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
306 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
310 * Get the DOCTYPE declaration that should be used with this page. Designed to
311 * be called in theme layout.php files.
313 * @return string the DOCTYPE declaration that should be used.
315 public function doctype() {
316 if ($this->page->theme->doctype === 'html5') {
317 $this->contenttype = 'text/html; charset=utf-8';
318 return "<!DOCTYPE html>\n";
320 } else if ($this->page->theme->doctype === 'xhtml5') {
321 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
322 return "<!DOCTYPE html>\n";
324 } else {
325 // legacy xhtml 1.0
326 $this->contenttype = 'text/html; charset=utf-8';
327 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
332 * The attributes that should be added to the <html> tag. Designed to
333 * be called in theme layout.php files.
335 * @return string HTML fragment.
337 public function htmlattributes() {
338 $return = get_html_lang(true);
339 if ($this->page->theme->doctype !== 'html5') {
340 $return .= ' xmlns="http://www.w3.org/1999/xhtml"';
342 return $return;
346 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
347 * that should be included in the <head> tag. Designed to be called in theme
348 * layout.php files.
350 * @return string HTML fragment.
352 public function standard_head_html() {
353 global $CFG, $SESSION;
355 // Before we output any content, we need to ensure that certain
356 // page components are set up.
358 // Blocks must be set up early as they may require javascript which
359 // has to be included in the page header before output is created.
360 foreach ($this->page->blocks->get_regions() as $region) {
361 $this->page->blocks->ensure_content_created($region, $this);
364 $output = '';
365 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
366 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
367 if (!$this->page->cacheable) {
368 $output .= '<meta http-equiv="pragma" content="no-cache" />' . "\n";
369 $output .= '<meta http-equiv="expires" content="0" />' . "\n";
371 // This is only set by the {@link redirect()} method
372 $output .= $this->metarefreshtag;
374 // Check if a periodic refresh delay has been set and make sure we arn't
375 // already meta refreshing
376 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
377 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
380 // flow player embedding support
381 $this->page->requires->js_function_call('M.util.load_flowplayer');
383 // Set up help link popups for all links with the helptooltip class
384 $this->page->requires->js_init_call('M.util.help_popups.setup');
386 // Setup help icon overlays.
387 $this->page->requires->yui_module('moodle-core-popuphelp', 'M.core.init_popuphelp');
388 $this->page->requires->strings_for_js(array(
389 'morehelp',
390 'loadinghelp',
391 ), 'moodle');
393 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
395 $focus = $this->page->focuscontrol;
396 if (!empty($focus)) {
397 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
398 // This is a horrifically bad way to handle focus but it is passed in
399 // through messy formslib::moodleform
400 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
401 } else if (strpos($focus, '.')!==false) {
402 // Old style of focus, bad way to do it
403 debugging('This code is using the old style focus event, Please update this code to focus on an element id or the moodleform focus method.', DEBUG_DEVELOPER);
404 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
405 } else {
406 // Focus element with given id
407 $this->page->requires->js_function_call('focuscontrol', array($focus));
411 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
412 // any other custom CSS can not be overridden via themes and is highly discouraged
413 $urls = $this->page->theme->css_urls($this->page);
414 foreach ($urls as $url) {
415 $this->page->requires->css_theme($url);
418 // Get the theme javascript head and footer
419 if ($jsurl = $this->page->theme->javascript_url(true)) {
420 $this->page->requires->js($jsurl, true);
422 if ($jsurl = $this->page->theme->javascript_url(false)) {
423 $this->page->requires->js($jsurl);
426 // Get any HTML from the page_requirements_manager.
427 $output .= $this->page->requires->get_head_code($this->page, $this);
429 // List alternate versions.
430 foreach ($this->page->alternateversions as $type => $alt) {
431 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
432 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
435 if (!empty($CFG->additionalhtmlhead)) {
436 $output .= "\n".$CFG->additionalhtmlhead;
439 return $output;
443 * The standard tags (typically skip links) that should be output just inside
444 * the start of the <body> tag. Designed to be called in theme layout.php files.
446 * @return string HTML fragment.
448 public function standard_top_of_body_html() {
449 global $CFG;
450 $output = $this->page->requires->get_top_of_body_code();
451 if (!empty($CFG->additionalhtmltopofbody)) {
452 $output .= "\n".$CFG->additionalhtmltopofbody;
454 $output .= $this->maintenance_warning();
455 return $output;
459 * Scheduled maintenance warning message.
461 * Note: This is a nasty hack to display maintenance notice, this should be moved
462 * to some general notification area once we have it.
464 * @return string
466 public function maintenance_warning() {
467 global $CFG;
469 $output = '';
470 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
471 $output .= $this->box_start('errorbox maintenancewarning');
472 $output .= get_string('maintenancemodeisscheduled', 'admin', (int)(($CFG->maintenance_later-time())/60));
473 $output .= $this->box_end();
475 return $output;
479 * The standard tags (typically performance information and validation links,
480 * if we are in developer debug mode) that should be output in the footer area
481 * of the page. Designed to be called in theme layout.php files.
483 * @return string HTML fragment.
485 public function standard_footer_html() {
486 global $CFG, $SCRIPT;
488 if (during_initial_install()) {
489 // Debugging info can not work before install is finished,
490 // in any case we do not want any links during installation!
491 return '';
494 // This function is normally called from a layout.php file in {@link core_renderer::header()}
495 // but some of the content won't be known until later, so we return a placeholder
496 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
497 $output = $this->unique_performance_info_token;
498 if ($this->page->devicetypeinuse == 'legacy') {
499 // The legacy theme is in use print the notification
500 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
503 // Get links to switch device types (only shown for users not on a default device)
504 $output .= $this->theme_switch_links();
506 if (!empty($CFG->debugpageinfo)) {
507 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
509 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
510 // Add link to profiling report if necessary
511 if (function_exists('profiling_is_running') && profiling_is_running()) {
512 $txt = get_string('profiledscript', 'admin');
513 $title = get_string('profiledscriptview', 'admin');
514 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
515 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
516 $output .= '<div class="profilingfooter">' . $link . '</div>';
518 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
519 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
520 $output .= '<div class="purgecaches">' .
521 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
523 if (!empty($CFG->debugvalidators)) {
524 // NOTE: this is not a nice hack, $PAGE->url is not always accurate and $FULLME neither, it is not a bug if it fails. --skodak
525 $output .= '<div class="validators"><ul>
526 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
527 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
528 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&amp;warnp2n3e=1&amp;url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
529 </ul></div>';
531 if (!empty($CFG->additionalhtmlfooter)) {
532 $output .= "\n".$CFG->additionalhtmlfooter;
534 return $output;
538 * Returns standard main content placeholder.
539 * Designed to be called in theme layout.php files.
541 * @return string HTML fragment.
543 public function main_content() {
544 // This is here because it is the only place we can inject the "main" role over the entire main content area
545 // without requiring all theme's to manually do it, and without creating yet another thing people need to
546 // remember in the theme.
547 // This is an unfortunate hack. DO NO EVER add anything more here.
548 // DO NOT add classes.
549 // DO NOT add an id.
550 return '<div role="main">'.$this->unique_main_content_token.'</div>';
554 * The standard tags (typically script tags that are not needed earlier) that
555 * should be output after everything else, . Designed to be called in theme layout.php files.
557 * @return string HTML fragment.
559 public function standard_end_of_body_html() {
560 // This function is normally called from a layout.php file in {@link core_renderer::header()}
561 // but some of the content won't be known until later, so we return a placeholder
562 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
563 return $this->unique_end_html_token;
567 * Return the standard string that says whether you are logged in (and switched
568 * roles/logged in as another user).
569 * @param bool $withlinks if false, then don't include any links in the HTML produced.
570 * If not set, the default is the nologinlinks option from the theme config.php file,
571 * and if that is not set, then links are included.
572 * @return string HTML fragment.
574 public function login_info($withlinks = null) {
575 global $USER, $CFG, $DB, $SESSION;
577 if (during_initial_install()) {
578 return '';
581 if (is_null($withlinks)) {
582 $withlinks = empty($this->page->layout_options['nologinlinks']);
585 $loginpage = ((string)$this->page->url === get_login_url());
586 $course = $this->page->course;
587 if (\core\session\manager::is_loggedinas()) {
588 $realuser = \core\session\manager::get_realuser();
589 $fullname = fullname($realuser, true);
590 if ($withlinks) {
591 $loginastitle = get_string('loginas');
592 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
593 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
594 } else {
595 $realuserinfo = " [$fullname] ";
597 } else {
598 $realuserinfo = '';
601 $loginurl = get_login_url();
603 if (empty($course->id)) {
604 // $course->id is not defined during installation
605 return '';
606 } else if (isloggedin()) {
607 $context = context_course::instance($course->id);
609 $fullname = fullname($USER, true);
610 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
611 if ($withlinks) {
612 $linktitle = get_string('viewprofile');
613 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
614 } else {
615 $username = $fullname;
617 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
618 if ($withlinks) {
619 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
620 } else {
621 $username .= " from {$idprovider->name}";
624 if (isguestuser()) {
625 $loggedinas = $realuserinfo.get_string('loggedinasguest');
626 if (!$loginpage && $withlinks) {
627 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
629 } else if (is_role_switched($course->id)) { // Has switched roles
630 $rolename = '';
631 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
632 $rolename = ': '.role_get_name($role, $context);
634 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
635 if ($withlinks) {
636 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
637 $loggedinas .= '('.html_writer::tag('a', get_string('switchrolereturn'), array('href'=>$url)).')';
639 } else {
640 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
641 if ($withlinks) {
642 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
645 } else {
646 $loggedinas = get_string('loggedinnot', 'moodle');
647 if (!$loginpage && $withlinks) {
648 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
652 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
654 if (isset($SESSION->justloggedin)) {
655 unset($SESSION->justloggedin);
656 if (!empty($CFG->displayloginfailures)) {
657 if (!isguestuser()) {
658 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
659 $loggedinas .= '&nbsp;<div class="loginfailures">';
660 if (empty($count->accounts)) {
661 $loggedinas .= get_string('failedloginattempts', '', $count);
662 } else {
663 $loggedinas .= get_string('failedloginattemptsall', '', $count);
665 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
666 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/report/log/index.php'.
667 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
669 $loggedinas .= '</div>';
675 return $loggedinas;
679 * Return the 'back' link that normally appears in the footer.
681 * @return string HTML fragment.
683 public function home_link() {
684 global $CFG, $SITE;
686 if ($this->page->pagetype == 'site-index') {
687 // Special case for site home page - please do not remove
688 return '<div class="sitelink">' .
689 '<a title="Moodle" href="http://moodle.org/">' .
690 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
692 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
693 // Special case for during install/upgrade.
694 return '<div class="sitelink">'.
695 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
696 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
698 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
699 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
700 get_string('home') . '</a></div>';
702 } else {
703 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
704 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
709 * Redirects the user by any means possible given the current state
711 * This function should not be called directly, it should always be called using
712 * the redirect function in lib/weblib.php
714 * The redirect function should really only be called before page output has started
715 * however it will allow itself to be called during the state STATE_IN_BODY
717 * @param string $encodedurl The URL to send to encoded if required
718 * @param string $message The message to display to the user if any
719 * @param int $delay The delay before redirecting a user, if $message has been
720 * set this is a requirement and defaults to 3, set to 0 no delay
721 * @param boolean $debugdisableredirect this redirect has been disabled for
722 * debugging purposes. Display a message that explains, and don't
723 * trigger the redirect.
724 * @return string The HTML to display to the user before dying, may contain
725 * meta refresh, javascript refresh, and may have set header redirects
727 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
728 global $CFG;
729 $url = str_replace('&amp;', '&', $encodedurl);
731 switch ($this->page->state) {
732 case moodle_page::STATE_BEFORE_HEADER :
733 // No output yet it is safe to delivery the full arsenal of redirect methods
734 if (!$debugdisableredirect) {
735 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
736 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
737 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
739 $output = $this->header();
740 break;
741 case moodle_page::STATE_PRINTING_HEADER :
742 // We should hopefully never get here
743 throw new coding_exception('You cannot redirect while printing the page header');
744 break;
745 case moodle_page::STATE_IN_BODY :
746 // We really shouldn't be here but we can deal with this
747 debugging("You should really redirect before you start page output");
748 if (!$debugdisableredirect) {
749 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
751 $output = $this->opencontainers->pop_all_but_last();
752 break;
753 case moodle_page::STATE_DONE :
754 // Too late to be calling redirect now
755 throw new coding_exception('You cannot redirect after the entire page has been generated');
756 break;
758 $output .= $this->notification($message, 'redirectmessage');
759 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
760 if ($debugdisableredirect) {
761 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
763 $output .= $this->footer();
764 return $output;
768 * Start output by sending the HTTP headers, and printing the HTML <head>
769 * and the start of the <body>.
771 * To control what is printed, you should set properties on $PAGE. If you
772 * are familiar with the old {@link print_header()} function from Moodle 1.9
773 * you will find that there are properties on $PAGE that correspond to most
774 * of the old parameters to could be passed to print_header.
776 * Not that, in due course, the remaining $navigation, $menu parameters here
777 * will be replaced by more properties of $PAGE, but that is still to do.
779 * @return string HTML that you must output this, preferably immediately.
781 public function header() {
782 global $USER, $CFG;
784 if (\core\session\manager::is_loggedinas()) {
785 $this->page->add_body_class('userloggedinas');
788 // Give themes a chance to init/alter the page object.
789 $this->page->theme->init_page($this->page);
791 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
793 // Find the appropriate page layout file, based on $this->page->pagelayout.
794 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
795 // Render the layout using the layout file.
796 $rendered = $this->render_page_layout($layoutfile);
798 // Slice the rendered output into header and footer.
799 $cutpos = strpos($rendered, $this->unique_main_content_token);
800 if ($cutpos === false) {
801 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
802 $token = self::MAIN_CONTENT_TOKEN;
803 } else {
804 $token = $this->unique_main_content_token;
807 if ($cutpos === false) {
808 throw new coding_exception('page layout file ' . $layoutfile . ' does not contain the main content placeholder, please include "<?php echo $OUTPUT->main_content() ?>" in theme layout file.');
810 $header = substr($rendered, 0, $cutpos);
811 $footer = substr($rendered, $cutpos + strlen($token));
813 if (empty($this->contenttype)) {
814 debugging('The page layout file did not call $OUTPUT->doctype()');
815 $header = $this->doctype() . $header;
818 // If this theme version is below 2.4 release and this is a course view page
819 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
820 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
821 // check if course content header/footer have not been output during render of theme layout
822 $coursecontentheader = $this->course_content_header(true);
823 $coursecontentfooter = $this->course_content_footer(true);
824 if (!empty($coursecontentheader)) {
825 // display debug message and add header and footer right above and below main content
826 // Please note that course header and footer (to be displayed above and below the whole page)
827 // are not displayed in this case at all.
828 // Besides the content header and footer are not displayed on any other course page
829 debugging('The current theme is not optimised for 2.4, the course-specific header and footer defined in course format will not be output', DEBUG_DEVELOPER);
830 $header .= $coursecontentheader;
831 $footer = $coursecontentfooter. $footer;
835 send_headers($this->contenttype, $this->page->cacheable);
837 $this->opencontainers->push('header/footer', $footer);
838 $this->page->set_state(moodle_page::STATE_IN_BODY);
840 return $header . $this->skip_link_target('maincontent');
844 * Renders and outputs the page layout file.
846 * This is done by preparing the normal globals available to a script, and
847 * then including the layout file provided by the current theme for the
848 * requested layout.
850 * @param string $layoutfile The name of the layout file
851 * @return string HTML code
853 protected function render_page_layout($layoutfile) {
854 global $CFG, $SITE, $USER;
855 // The next lines are a bit tricky. The point is, here we are in a method
856 // of a renderer class, and this object may, or may not, be the same as
857 // the global $OUTPUT object. When rendering the page layout file, we want to use
858 // this object. However, people writing Moodle code expect the current
859 // renderer to be called $OUTPUT, not $this, so define a variable called
860 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
861 $OUTPUT = $this;
862 $PAGE = $this->page;
863 $COURSE = $this->page->course;
865 ob_start();
866 include($layoutfile);
867 $rendered = ob_get_contents();
868 ob_end_clean();
869 return $rendered;
873 * Outputs the page's footer
875 * @return string HTML fragment
877 public function footer() {
878 global $CFG, $DB;
880 $output = $this->container_end_all(true);
882 $footer = $this->opencontainers->pop('header/footer');
884 if (debugging() and $DB and $DB->is_transaction_started()) {
885 // TODO: MDL-20625 print warning - transaction will be rolled back
888 // Provide some performance info if required
889 $performanceinfo = '';
890 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
891 $perf = get_performance_info();
892 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
893 $performanceinfo = $perf['html'];
897 // We always want performance data when running a performance test, even if the user is redirected to another page.
898 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
899 $footer = $this->unique_performance_info_token . $footer;
901 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
903 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
905 $this->page->set_state(moodle_page::STATE_DONE);
907 return $output . $footer;
911 * Close all but the last open container. This is useful in places like error
912 * handling, where you want to close all the open containers (apart from <body>)
913 * before outputting the error message.
915 * @param bool $shouldbenone assert that the stack should be empty now - causes a
916 * developer debug warning if it isn't.
917 * @return string the HTML required to close any open containers inside <body>.
919 public function container_end_all($shouldbenone = false) {
920 return $this->opencontainers->pop_all_but_last($shouldbenone);
924 * Returns course-specific information to be output immediately above content on any course page
925 * (for the current course)
927 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
928 * @return string
930 public function course_content_header($onlyifnotcalledbefore = false) {
931 global $CFG;
932 if ($this->page->course->id == SITEID) {
933 // return immediately and do not include /course/lib.php if not necessary
934 return '';
936 static $functioncalled = false;
937 if ($functioncalled && $onlyifnotcalledbefore) {
938 // we have already output the content header
939 return '';
941 require_once($CFG->dirroot.'/course/lib.php');
942 $functioncalled = true;
943 $courseformat = course_get_format($this->page->course);
944 if (($obj = $courseformat->course_content_header()) !== null) {
945 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
947 return '';
951 * Returns course-specific information to be output immediately below content on any course page
952 * (for the current course)
954 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
955 * @return string
957 public function course_content_footer($onlyifnotcalledbefore = false) {
958 global $CFG;
959 if ($this->page->course->id == SITEID) {
960 // return immediately and do not include /course/lib.php if not necessary
961 return '';
963 static $functioncalled = false;
964 if ($functioncalled && $onlyifnotcalledbefore) {
965 // we have already output the content footer
966 return '';
968 $functioncalled = true;
969 require_once($CFG->dirroot.'/course/lib.php');
970 $courseformat = course_get_format($this->page->course);
971 if (($obj = $courseformat->course_content_footer()) !== null) {
972 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
974 return '';
978 * Returns course-specific information to be output on any course page in the header area
979 * (for the current course)
981 * @return string
983 public function course_header() {
984 global $CFG;
985 if ($this->page->course->id == SITEID) {
986 // return immediately and do not include /course/lib.php if not necessary
987 return '';
989 require_once($CFG->dirroot.'/course/lib.php');
990 $courseformat = course_get_format($this->page->course);
991 if (($obj = $courseformat->course_header()) !== null) {
992 return $courseformat->get_renderer($this->page)->render($obj);
994 return '';
998 * Returns course-specific information to be output on any course page in the footer area
999 * (for the current course)
1001 * @return string
1003 public function course_footer() {
1004 global $CFG;
1005 if ($this->page->course->id == SITEID) {
1006 // return immediately and do not include /course/lib.php if not necessary
1007 return '';
1009 require_once($CFG->dirroot.'/course/lib.php');
1010 $courseformat = course_get_format($this->page->course);
1011 if (($obj = $courseformat->course_footer()) !== null) {
1012 return $courseformat->get_renderer($this->page)->render($obj);
1014 return '';
1018 * Returns lang menu or '', this method also checks forcing of languages in courses.
1020 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1022 * @return string The lang menu HTML or empty string
1024 public function lang_menu() {
1025 global $CFG;
1027 if (empty($CFG->langmenu)) {
1028 return '';
1031 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1032 // do not show lang menu if language forced
1033 return '';
1036 $currlang = current_language();
1037 $langs = get_string_manager()->get_list_of_translations();
1039 if (count($langs) < 2) {
1040 return '';
1043 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1044 $s->label = get_accesshide(get_string('language'));
1045 $s->class = 'langmenu';
1046 return $this->render($s);
1050 * Output the row of editing icons for a block, as defined by the controls array.
1052 * @param array $controls an array like {@link block_contents::$controls}.
1053 * @param string $blockid The ID given to the block.
1054 * @return string HTML fragment.
1056 public function block_controls($actions, $blockid = null) {
1057 global $CFG;
1058 if (empty($actions)) {
1059 return '';
1061 $menu = new action_menu($actions);
1062 if ($blockid !== null) {
1063 $menu->set_owner_selector('#'.$blockid);
1065 $menu->set_constraint('.block-region');
1066 $menu->attributes['class'] .= ' block-control-actions commands';
1067 if (isset($CFG->blockeditingmenu) && !$CFG->blockeditingmenu) {
1068 $menu->do_not_enhance();
1070 return $this->render($menu);
1074 * Renders an action menu component.
1076 * ARIA references:
1077 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1078 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1080 * @param action_menu $menu
1081 * @return string HTML
1083 public function render_action_menu(action_menu $menu) {
1084 $menu->initialise_js($this->page);
1086 $output = html_writer::start_tag('div', $menu->attributes);
1087 $output .= html_writer::start_tag('ul', $menu->attributesprimary);
1088 foreach ($menu->get_primary_actions($this) as $action) {
1089 if ($action instanceof renderable) {
1090 $content = $this->render($action);
1091 } else {
1092 $content = $action;
1094 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1096 $output .= html_writer::end_tag('ul');
1097 $output .= html_writer::start_tag('ul', $menu->attributessecondary);
1098 foreach ($menu->get_secondary_actions() as $action) {
1099 if ($action instanceof renderable) {
1100 $content = $this->render($action);
1101 } else {
1102 $content = $action;
1104 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1106 $output .= html_writer::end_tag('ul');
1107 $output .= html_writer::end_tag('div');
1108 return $output;
1112 * Renders an action_menu_link item.
1114 * @param action_menu_link $action
1115 * @return string HTML fragment
1117 protected function render_action_menu_link(action_menu_link $action) {
1118 static $actioncount = 0;
1119 $actioncount++;
1121 $comparetoalt = '';
1122 $text = '';
1123 if (!$action->icon || $action->primary === false) {
1124 $text .= html_writer::start_tag('span', array('class'=>'menu-action-text', 'id' => 'actionmenuaction-'.$actioncount));
1125 if ($action->text instanceof renderable) {
1126 $text .= $this->render($action->text);
1127 } else {
1128 $text .= $action->text;
1129 $comparetoalt = (string)$action->text;
1131 $text .= html_writer::end_tag('span');
1134 $icon = '';
1135 if ($action->icon) {
1136 $icon = $action->icon;
1137 if ($action->primary || !$action->actionmenu->will_be_enhanced()) {
1138 $action->attributes['title'] = $action->text;
1140 if (!$action->primary && $action->actionmenu->will_be_enhanced()) {
1141 if ((string)$icon->attributes['alt'] === $comparetoalt) {
1142 $icon->attributes['alt'] = '';
1144 if (isset($icon->attributes['title']) && (string)$icon->attributes['title'] === $comparetoalt) {
1145 unset($icon->attributes['title']);
1148 $icon = $this->render($icon);
1151 // A disabled link is rendered as formatted text.
1152 if (!empty($action->attributes['disabled'])) {
1153 // Do not use div here due to nesting restriction in xhtml strict.
1154 return html_writer::tag('span', $icon.$text, array('class'=>'currentlink', 'role' => 'menuitem'));
1157 $attributes = $action->attributes;
1158 unset($action->attributes['disabled']);
1159 $attributes['href'] = $action->url;
1160 if ($text !== '') {
1161 $attributes['aria-labelledby'] = 'actionmenuaction-'.$actioncount;
1164 return html_writer::tag('a', $icon.$text, $attributes);
1168 * Renders a primary action_menu_filler item.
1170 * @param action_menu_link_filler $action
1171 * @return string HTML fragment
1173 protected function render_action_menu_filler(action_menu_filler $action) {
1174 return html_writer::span('&nbsp;', 'filler');
1178 * Renders a primary action_menu_link item.
1180 * @param action_menu_link_primary $action
1181 * @return string HTML fragment
1183 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1184 return $this->render_action_menu_link($action);
1188 * Renders a secondary action_menu_link item.
1190 * @param action_menu_link_secondary $action
1191 * @return string HTML fragment
1193 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1194 return $this->render_action_menu_link($action);
1198 * Prints a nice side block with an optional header.
1200 * The content is described
1201 * by a {@link core_renderer::block_contents} object.
1203 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1204 * <div class="header"></div>
1205 * <div class="content">
1206 * ...CONTENT...
1207 * <div class="footer">
1208 * </div>
1209 * </div>
1210 * <div class="annotation">
1211 * </div>
1212 * </div>
1214 * @param block_contents $bc HTML for the content
1215 * @param string $region the region the block is appearing in.
1216 * @return string the HTML to be output.
1218 public function block(block_contents $bc, $region) {
1219 $bc = clone($bc); // Avoid messing up the object passed in.
1220 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1221 $bc->collapsible = block_contents::NOT_HIDEABLE;
1223 if (!empty($bc->blockinstanceid)) {
1224 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1226 $skiptitle = strip_tags($bc->title);
1227 if ($bc->blockinstanceid && !empty($skiptitle)) {
1228 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1229 } else if (!empty($bc->arialabel)) {
1230 $bc->attributes['aria-label'] = $bc->arialabel;
1232 if ($bc->dockable) {
1233 $bc->attributes['data-dockable'] = 1;
1235 if ($bc->collapsible == block_contents::HIDDEN) {
1236 $bc->add_class('hidden');
1238 if (!empty($bc->controls)) {
1239 $bc->add_class('block_with_controls');
1243 if (empty($skiptitle)) {
1244 $output = '';
1245 $skipdest = '';
1246 } else {
1247 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
1248 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
1251 $output .= html_writer::start_tag('div', $bc->attributes);
1253 $output .= $this->block_header($bc);
1254 $output .= $this->block_content($bc);
1256 $output .= html_writer::end_tag('div');
1258 $output .= $this->block_annotation($bc);
1260 $output .= $skipdest;
1262 $this->init_block_hider_js($bc);
1263 return $output;
1267 * Produces a header for a block
1269 * @param block_contents $bc
1270 * @return string
1272 protected function block_header(block_contents $bc) {
1274 $title = '';
1275 if ($bc->title) {
1276 $attributes = array();
1277 if ($bc->blockinstanceid) {
1278 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1280 $title = html_writer::tag('h2', $bc->title, $attributes);
1283 $blockid = null;
1284 if (isset($bc->attributes['id'])) {
1285 $blockid = $bc->attributes['id'];
1287 $controlshtml = $this->block_controls($bc->controls, $blockid);
1289 $output = '';
1290 if ($title || $controlshtml) {
1291 $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'));
1293 return $output;
1297 * Produces the content area for a block
1299 * @param block_contents $bc
1300 * @return string
1302 protected function block_content(block_contents $bc) {
1303 $output = html_writer::start_tag('div', array('class' => 'content'));
1304 if (!$bc->title && !$this->block_controls($bc->controls)) {
1305 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1307 $output .= $bc->content;
1308 $output .= $this->block_footer($bc);
1309 $output .= html_writer::end_tag('div');
1311 return $output;
1315 * Produces the footer for a block
1317 * @param block_contents $bc
1318 * @return string
1320 protected function block_footer(block_contents $bc) {
1321 $output = '';
1322 if ($bc->footer) {
1323 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1325 return $output;
1329 * Produces the annotation for a block
1331 * @param block_contents $bc
1332 * @return string
1334 protected function block_annotation(block_contents $bc) {
1335 $output = '';
1336 if ($bc->annotation) {
1337 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1339 return $output;
1343 * Calls the JS require function to hide a block.
1345 * @param block_contents $bc A block_contents object
1347 protected function init_block_hider_js(block_contents $bc) {
1348 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1349 $config = new stdClass;
1350 $config->id = $bc->attributes['id'];
1351 $config->title = strip_tags($bc->title);
1352 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1353 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1354 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1356 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1357 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1362 * Render the contents of a block_list.
1364 * @param array $icons the icon for each item.
1365 * @param array $items the content of each item.
1366 * @return string HTML
1368 public function list_block_contents($icons, $items) {
1369 $row = 0;
1370 $lis = array();
1371 foreach ($items as $key => $string) {
1372 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1373 if (!empty($icons[$key])) { //test if the content has an assigned icon
1374 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1376 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1377 $item .= html_writer::end_tag('li');
1378 $lis[] = $item;
1379 $row = 1 - $row; // Flip even/odd.
1381 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1385 * Output all the blocks in a particular region.
1387 * @param string $region the name of a region on this page.
1388 * @return string the HTML to be output.
1390 public function blocks_for_region($region) {
1391 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1392 $blocks = $this->page->blocks->get_blocks_for_region($region);
1393 $lastblock = null;
1394 $zones = array();
1395 foreach ($blocks as $block) {
1396 $zones[] = $block->title;
1398 $output = '';
1400 foreach ($blockcontents as $bc) {
1401 if ($bc instanceof block_contents) {
1402 $output .= $this->block($bc, $region);
1403 $lastblock = $bc->title;
1404 } else if ($bc instanceof block_move_target) {
1405 $output .= $this->block_move_target($bc, $zones, $lastblock);
1406 } else {
1407 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1410 return $output;
1414 * Output a place where the block that is currently being moved can be dropped.
1416 * @param block_move_target $target with the necessary details.
1417 * @param array $zones array of areas where the block can be moved to
1418 * @param string $previous the block located before the area currently being rendered.
1419 * @return string the HTML to be output.
1421 public function block_move_target($target, $zones, $previous) {
1422 if ($previous == null) {
1423 $position = get_string('moveblockbefore', 'block', $zones[0]);
1424 } else {
1425 $position = get_string('moveblockafter', 'block', $previous);
1427 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1431 * Renders a special html link with attached action
1433 * Theme developers: DO NOT OVERRIDE! Please override function
1434 * {@link core_renderer::render_action_link()} instead.
1436 * @param string|moodle_url $url
1437 * @param string $text HTML fragment
1438 * @param component_action $action
1439 * @param array $attributes associative array of html link attributes + disabled
1440 * @param pix_icon optional pix icon to render with the link
1441 * @return string HTML fragment
1443 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1444 if (!($url instanceof moodle_url)) {
1445 $url = new moodle_url($url);
1447 $link = new action_link($url, $text, $action, $attributes, $icon);
1449 return $this->render($link);
1453 * Renders an action_link object.
1455 * The provided link is renderer and the HTML returned. At the same time the
1456 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1458 * @param action_link $link
1459 * @return string HTML fragment
1461 protected function render_action_link(action_link $link) {
1462 global $CFG;
1464 $text = '';
1465 if ($link->icon) {
1466 $text .= $this->render($link->icon);
1469 if ($link->text instanceof renderable) {
1470 $text .= $this->render($link->text);
1471 } else {
1472 $text .= $link->text;
1475 // A disabled link is rendered as formatted text
1476 if (!empty($link->attributes['disabled'])) {
1477 // do not use div here due to nesting restriction in xhtml strict
1478 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1481 $attributes = $link->attributes;
1482 unset($link->attributes['disabled']);
1483 $attributes['href'] = $link->url;
1485 if ($link->actions) {
1486 if (empty($attributes['id'])) {
1487 $id = html_writer::random_id('action_link');
1488 $attributes['id'] = $id;
1489 } else {
1490 $id = $attributes['id'];
1492 foreach ($link->actions as $action) {
1493 $this->add_action_handler($action, $id);
1497 return html_writer::tag('a', $text, $attributes);
1502 * Renders an action_icon.
1504 * This function uses the {@link core_renderer::action_link()} method for the
1505 * most part. What it does different is prepare the icon as HTML and use it
1506 * as the link text.
1508 * Theme developers: If you want to change how action links and/or icons are rendered,
1509 * consider overriding function {@link core_renderer::render_action_link()} and
1510 * {@link core_renderer::render_pix_icon()}.
1512 * @param string|moodle_url $url A string URL or moodel_url
1513 * @param pix_icon $pixicon
1514 * @param component_action $action
1515 * @param array $attributes associative array of html link attributes + disabled
1516 * @param bool $linktext show title next to image in link
1517 * @return string HTML fragment
1519 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1520 if (!($url instanceof moodle_url)) {
1521 $url = new moodle_url($url);
1523 $attributes = (array)$attributes;
1525 if (empty($attributes['class'])) {
1526 // let ppl override the class via $options
1527 $attributes['class'] = 'action-icon';
1530 $icon = $this->render($pixicon);
1532 if ($linktext) {
1533 $text = $pixicon->attributes['alt'];
1534 } else {
1535 $text = '';
1538 return $this->action_link($url, $text.$icon, $action, $attributes);
1542 * Print a message along with button choices for Continue/Cancel
1544 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1546 * @param string $message The question to ask the user
1547 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1548 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1549 * @return string HTML fragment
1551 public function confirm($message, $continue, $cancel) {
1552 if ($continue instanceof single_button) {
1553 // ok
1554 } else if (is_string($continue)) {
1555 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1556 } else if ($continue instanceof moodle_url) {
1557 $continue = new single_button($continue, get_string('continue'), 'post');
1558 } else {
1559 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1562 if ($cancel instanceof single_button) {
1563 // ok
1564 } else if (is_string($cancel)) {
1565 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1566 } else if ($cancel instanceof moodle_url) {
1567 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1568 } else {
1569 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1572 $output = $this->box_start('generalbox', 'notice');
1573 $output .= html_writer::tag('p', $message);
1574 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1575 $output .= $this->box_end();
1576 return $output;
1580 * Returns a form with a single button.
1582 * Theme developers: DO NOT OVERRIDE! Please override function
1583 * {@link core_renderer::render_single_button()} instead.
1585 * @param string|moodle_url $url
1586 * @param string $label button text
1587 * @param string $method get or post submit method
1588 * @param array $options associative array {disabled, title, etc.}
1589 * @return string HTML fragment
1591 public function single_button($url, $label, $method='post', array $options=null) {
1592 if (!($url instanceof moodle_url)) {
1593 $url = new moodle_url($url);
1595 $button = new single_button($url, $label, $method);
1597 foreach ((array)$options as $key=>$value) {
1598 if (array_key_exists($key, $button)) {
1599 $button->$key = $value;
1603 return $this->render($button);
1607 * Renders a single button widget.
1609 * This will return HTML to display a form containing a single button.
1611 * @param single_button $button
1612 * @return string HTML fragment
1614 protected function render_single_button(single_button $button) {
1615 $attributes = array('type' => 'submit',
1616 'value' => $button->label,
1617 'disabled' => $button->disabled ? 'disabled' : null,
1618 'title' => $button->tooltip);
1620 if ($button->actions) {
1621 $id = html_writer::random_id('single_button');
1622 $attributes['id'] = $id;
1623 foreach ($button->actions as $action) {
1624 $this->add_action_handler($action, $id);
1628 // first the input element
1629 $output = html_writer::empty_tag('input', $attributes);
1631 // then hidden fields
1632 $params = $button->url->params();
1633 if ($button->method === 'post') {
1634 $params['sesskey'] = sesskey();
1636 foreach ($params as $var => $val) {
1637 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1640 // then div wrapper for xhtml strictness
1641 $output = html_writer::tag('div', $output);
1643 // now the form itself around it
1644 if ($button->method === 'get') {
1645 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1646 } else {
1647 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1649 if ($url === '') {
1650 $url = '#'; // there has to be always some action
1652 $attributes = array('method' => $button->method,
1653 'action' => $url,
1654 'id' => $button->formid);
1655 $output = html_writer::tag('form', $output, $attributes);
1657 // and finally one more wrapper with class
1658 return html_writer::tag('div', $output, array('class' => $button->class));
1662 * Returns a form with a single select widget.
1664 * Theme developers: DO NOT OVERRIDE! Please override function
1665 * {@link core_renderer::render_single_select()} instead.
1667 * @param moodle_url $url form action target, includes hidden fields
1668 * @param string $name name of selection field - the changing parameter in url
1669 * @param array $options list of options
1670 * @param string $selected selected element
1671 * @param array $nothing
1672 * @param string $formid
1673 * @return string HTML fragment
1675 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1676 if (!($url instanceof moodle_url)) {
1677 $url = new moodle_url($url);
1679 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1681 return $this->render($select);
1685 * Internal implementation of single_select rendering
1687 * @param single_select $select
1688 * @return string HTML fragment
1690 protected function render_single_select(single_select $select) {
1691 $select = clone($select);
1692 if (empty($select->formid)) {
1693 $select->formid = html_writer::random_id('single_select_f');
1696 $output = '';
1697 $params = $select->url->params();
1698 if ($select->method === 'post') {
1699 $params['sesskey'] = sesskey();
1701 foreach ($params as $name=>$value) {
1702 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1705 if (empty($select->attributes['id'])) {
1706 $select->attributes['id'] = html_writer::random_id('single_select');
1709 if ($select->disabled) {
1710 $select->attributes['disabled'] = 'disabled';
1713 if ($select->tooltip) {
1714 $select->attributes['title'] = $select->tooltip;
1717 $select->attributes['class'] = 'autosubmit';
1718 if ($select->class) {
1719 $select->attributes['class'] .= ' ' . $select->class;
1722 if ($select->label) {
1723 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1726 if ($select->helpicon instanceof help_icon) {
1727 $output .= $this->render($select->helpicon);
1729 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1731 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1732 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1734 $nothing = empty($select->nothing) ? false : key($select->nothing);
1735 $this->page->requires->yui_module('moodle-core-formautosubmit',
1736 'M.core.init_formautosubmit',
1737 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1740 // then div wrapper for xhtml strictness
1741 $output = html_writer::tag('div', $output);
1743 // now the form itself around it
1744 if ($select->method === 'get') {
1745 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1746 } else {
1747 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1749 $formattributes = array('method' => $select->method,
1750 'action' => $url,
1751 'id' => $select->formid);
1752 $output = html_writer::tag('form', $output, $formattributes);
1754 // and finally one more wrapper with class
1755 return html_writer::tag('div', $output, array('class' => $select->class));
1759 * Returns a form with a url select widget.
1761 * Theme developers: DO NOT OVERRIDE! Please override function
1762 * {@link core_renderer::render_url_select()} instead.
1764 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1765 * @param string $selected selected element
1766 * @param array $nothing
1767 * @param string $formid
1768 * @return string HTML fragment
1770 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1771 $select = new url_select($urls, $selected, $nothing, $formid);
1772 return $this->render($select);
1776 * Internal implementation of url_select rendering
1778 * @param url_select $select
1779 * @return string HTML fragment
1781 protected function render_url_select(url_select $select) {
1782 global $CFG;
1784 $select = clone($select);
1785 if (empty($select->formid)) {
1786 $select->formid = html_writer::random_id('url_select_f');
1789 if (empty($select->attributes['id'])) {
1790 $select->attributes['id'] = html_writer::random_id('url_select');
1793 if ($select->disabled) {
1794 $select->attributes['disabled'] = 'disabled';
1797 if ($select->tooltip) {
1798 $select->attributes['title'] = $select->tooltip;
1801 $output = '';
1803 if ($select->label) {
1804 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1807 $classes = array();
1808 if (!$select->showbutton) {
1809 $classes[] = 'autosubmit';
1811 if ($select->class) {
1812 $classes[] = $select->class;
1814 if (count($classes)) {
1815 $select->attributes['class'] = implode(' ', $classes);
1818 if ($select->helpicon instanceof help_icon) {
1819 $output .= $this->render($select->helpicon);
1822 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1823 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1824 $urls = array();
1825 foreach ($select->urls as $k=>$v) {
1826 if (is_array($v)) {
1827 // optgroup structure
1828 foreach ($v as $optgrouptitle => $optgroupoptions) {
1829 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1830 if (empty($optionurl)) {
1831 $safeoptionurl = '';
1832 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1833 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1834 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1835 } else if (strpos($optionurl, '/') !== 0) {
1836 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1837 continue;
1838 } else {
1839 $safeoptionurl = $optionurl;
1841 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1844 } else {
1845 // plain list structure
1846 if (empty($k)) {
1847 // nothing selected option
1848 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1849 $k = str_replace($CFG->wwwroot, '', $k);
1850 } else if (strpos($k, '/') !== 0) {
1851 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1852 continue;
1854 $urls[$k] = $v;
1857 $selected = $select->selected;
1858 if (!empty($selected)) {
1859 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1860 $selected = str_replace($CFG->wwwroot, '', $selected);
1861 } else if (strpos($selected, '/') !== 0) {
1862 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1866 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1867 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1869 if (!$select->showbutton) {
1870 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1871 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1872 $nothing = empty($select->nothing) ? false : key($select->nothing);
1873 $this->page->requires->yui_module('moodle-core-formautosubmit',
1874 'M.core.init_formautosubmit',
1875 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1877 } else {
1878 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1881 // then div wrapper for xhtml strictness
1882 $output = html_writer::tag('div', $output);
1884 // now the form itself around it
1885 $formattributes = array('method' => 'post',
1886 'action' => new moodle_url('/course/jumpto.php'),
1887 'id' => $select->formid);
1888 $output = html_writer::tag('form', $output, $formattributes);
1890 // and finally one more wrapper with class
1891 return html_writer::tag('div', $output, array('class' => $select->class));
1895 * Returns a string containing a link to the user documentation.
1896 * Also contains an icon by default. Shown to teachers and admin only.
1898 * @param string $path The page link after doc root and language, no leading slash.
1899 * @param string $text The text to be displayed for the link
1900 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
1901 * @return string
1903 public function doc_link($path, $text = '', $forcepopup = false) {
1904 global $CFG;
1906 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp icon-pre'));
1908 $url = new moodle_url(get_docs_url($path));
1910 $attributes = array('href'=>$url);
1911 if (!empty($CFG->doctonewwindow) || $forcepopup) {
1912 $attributes['class'] = 'helplinkpopup';
1915 return html_writer::tag('a', $icon.$text, $attributes);
1919 * Return HTML for a pix_icon.
1921 * Theme developers: DO NOT OVERRIDE! Please override function
1922 * {@link core_renderer::render_pix_icon()} instead.
1924 * @param string $pix short pix name
1925 * @param string $alt mandatory alt attribute
1926 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1927 * @param array $attributes htm lattributes
1928 * @return string HTML fragment
1930 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1931 $icon = new pix_icon($pix, $alt, $component, $attributes);
1932 return $this->render($icon);
1936 * Renders a pix_icon widget and returns the HTML to display it.
1938 * @param pix_icon $icon
1939 * @return string HTML fragment
1941 protected function render_pix_icon(pix_icon $icon) {
1942 $attributes = $icon->attributes;
1943 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1944 return html_writer::empty_tag('img', $attributes);
1948 * Return HTML to display an emoticon icon.
1950 * @param pix_emoticon $emoticon
1951 * @return string HTML fragment
1953 protected function render_pix_emoticon(pix_emoticon $emoticon) {
1954 $attributes = $emoticon->attributes;
1955 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
1956 return html_writer::empty_tag('img', $attributes);
1960 * Produces the html that represents this rating in the UI
1962 * @param rating $rating the page object on which this rating will appear
1963 * @return string
1965 function render_rating(rating $rating) {
1966 global $CFG, $USER;
1968 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
1969 return null;//ratings are turned off
1972 $ratingmanager = new rating_manager();
1973 // Initialise the JavaScript so ratings can be done by AJAX.
1974 $ratingmanager->initialise_rating_javascript($this->page);
1976 $strrate = get_string("rate", "rating");
1977 $ratinghtml = ''; //the string we'll return
1979 // permissions check - can they view the aggregate?
1980 if ($rating->user_can_view_aggregate()) {
1982 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
1983 $aggregatestr = $rating->get_aggregate_string();
1985 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
1986 if ($rating->count > 0) {
1987 $countstr = "({$rating->count})";
1988 } else {
1989 $countstr = '-';
1991 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
1993 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
1994 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
1996 $nonpopuplink = $rating->get_view_ratings_url();
1997 $popuplink = $rating->get_view_ratings_url(true);
1999 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2000 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2001 } else {
2002 $ratinghtml .= $aggregatehtml;
2006 $formstart = null;
2007 // if the item doesn't belong to the current user, the user has permission to rate
2008 // and we're within the assessable period
2009 if ($rating->user_can_rate()) {
2011 $rateurl = $rating->get_rate_url();
2012 $inputs = $rateurl->params();
2014 //start the rating form
2015 $formattrs = array(
2016 'id' => "postrating{$rating->itemid}",
2017 'class' => 'postratingform',
2018 'method' => 'post',
2019 'action' => $rateurl->out_omit_querystring()
2021 $formstart = html_writer::start_tag('form', $formattrs);
2022 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2024 // add the hidden inputs
2025 foreach ($inputs as $name => $value) {
2026 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2027 $formstart .= html_writer::empty_tag('input', $attributes);
2030 if (empty($ratinghtml)) {
2031 $ratinghtml .= $strrate.': ';
2033 $ratinghtml = $formstart.$ratinghtml;
2035 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2036 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2037 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2038 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2040 //output submit button
2041 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2043 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2044 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2046 if (!$rating->settings->scale->isnumeric) {
2047 // If a global scale, try to find current course ID from the context
2048 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2049 $courseid = $coursecontext->instanceid;
2050 } else {
2051 $courseid = $rating->settings->scale->courseid;
2053 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2055 $ratinghtml .= html_writer::end_tag('span');
2056 $ratinghtml .= html_writer::end_tag('div');
2057 $ratinghtml .= html_writer::end_tag('form');
2060 return $ratinghtml;
2064 * Centered heading with attached help button (same title text)
2065 * and optional icon attached.
2067 * @param string $text A heading text
2068 * @param string $helpidentifier The keyword that defines a help page
2069 * @param string $component component name
2070 * @param string|moodle_url $icon
2071 * @param string $iconalt icon alt text
2072 * @param int $level The level of importance of the heading. Defaulting to 2
2073 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2074 * @return string HTML fragment
2076 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2077 $image = '';
2078 if ($icon) {
2079 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2082 $help = '';
2083 if ($helpidentifier) {
2084 $help = $this->help_icon($helpidentifier, $component);
2087 return $this->heading($image.$text.$help, $level, $classnames);
2091 * Returns HTML to display a help icon.
2093 * @deprecated since Moodle 2.0
2095 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2096 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2100 * Returns HTML to display a help icon.
2102 * Theme developers: DO NOT OVERRIDE! Please override function
2103 * {@link core_renderer::render_help_icon()} instead.
2105 * @param string $identifier The keyword that defines a help page
2106 * @param string $component component name
2107 * @param string|bool $linktext true means use $title as link text, string means link text value
2108 * @return string HTML fragment
2110 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2111 $icon = new help_icon($identifier, $component);
2112 $icon->diag_strings();
2113 if ($linktext === true) {
2114 $icon->linktext = get_string($icon->identifier, $icon->component);
2115 } else if (!empty($linktext)) {
2116 $icon->linktext = $linktext;
2118 return $this->render($icon);
2122 * Implementation of user image rendering.
2124 * @param help_icon $helpicon A help icon instance
2125 * @return string HTML fragment
2127 protected function render_help_icon(help_icon $helpicon) {
2128 global $CFG;
2130 // first get the help image icon
2131 $src = $this->pix_url('help');
2133 $title = get_string($helpicon->identifier, $helpicon->component);
2135 if (empty($helpicon->linktext)) {
2136 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
2137 } else {
2138 $alt = get_string('helpwiththis');
2141 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
2142 $output = html_writer::empty_tag('img', $attributes);
2144 // add the link text if given
2145 if (!empty($helpicon->linktext)) {
2146 // the spacing has to be done through CSS
2147 $output .= $helpicon->linktext;
2150 // now create the link around it - we need https on loginhttps pages
2151 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
2153 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
2154 $title = get_string('helpprefix2', '', trim($title, ". \t"));
2156 $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true', 'target'=>'_blank');
2157 $output = html_writer::tag('a', $output, $attributes);
2159 // and finally span
2160 return html_writer::tag('span', $output, array('class' => 'helptooltip'));
2164 * Returns HTML to display a scale help icon.
2166 * @param int $courseid
2167 * @param stdClass $scale instance
2168 * @return string HTML fragment
2170 public function help_icon_scale($courseid, stdClass $scale) {
2171 global $CFG;
2173 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2175 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2177 $scaleid = abs($scale->id);
2179 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2180 $action = new popup_action('click', $link, 'ratingscale');
2182 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2186 * Creates and returns a spacer image with optional line break.
2188 * @param array $attributes Any HTML attributes to add to the spaced.
2189 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2190 * laxy do it with CSS which is a much better solution.
2191 * @return string HTML fragment
2193 public function spacer(array $attributes = null, $br = false) {
2194 $attributes = (array)$attributes;
2195 if (empty($attributes['width'])) {
2196 $attributes['width'] = 1;
2198 if (empty($attributes['height'])) {
2199 $attributes['height'] = 1;
2201 $attributes['class'] = 'spacer';
2203 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2205 if (!empty($br)) {
2206 $output .= '<br />';
2209 return $output;
2213 * Returns HTML to display the specified user's avatar.
2215 * User avatar may be obtained in two ways:
2216 * <pre>
2217 * // Option 1: (shortcut for simple cases, preferred way)
2218 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2219 * $OUTPUT->user_picture($user, array('popup'=>true));
2221 * // Option 2:
2222 * $userpic = new user_picture($user);
2223 * // Set properties of $userpic
2224 * $userpic->popup = true;
2225 * $OUTPUT->render($userpic);
2226 * </pre>
2228 * Theme developers: DO NOT OVERRIDE! Please override function
2229 * {@link core_renderer::render_user_picture()} instead.
2231 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2232 * If any of these are missing, the database is queried. Avoid this
2233 * if at all possible, particularly for reports. It is very bad for performance.
2234 * @param array $options associative array with user picture options, used only if not a user_picture object,
2235 * options are:
2236 * - courseid=$this->page->course->id (course id of user profile in link)
2237 * - size=35 (size of image)
2238 * - link=true (make image clickable - the link leads to user profile)
2239 * - popup=false (open in popup)
2240 * - alttext=true (add image alt attribute)
2241 * - class = image class attribute (default 'userpicture')
2242 * @return string HTML fragment
2244 public function user_picture(stdClass $user, array $options = null) {
2245 $userpicture = new user_picture($user);
2246 foreach ((array)$options as $key=>$value) {
2247 if (array_key_exists($key, $userpicture)) {
2248 $userpicture->$key = $value;
2251 return $this->render($userpicture);
2255 * Internal implementation of user image rendering.
2257 * @param user_picture $userpicture
2258 * @return string
2260 protected function render_user_picture(user_picture $userpicture) {
2261 global $CFG, $DB;
2263 $user = $userpicture->user;
2265 if ($userpicture->alttext) {
2266 if (!empty($user->imagealt)) {
2267 $alt = $user->imagealt;
2268 } else {
2269 $alt = get_string('pictureof', '', fullname($user));
2271 } else {
2272 $alt = '';
2275 if (empty($userpicture->size)) {
2276 $size = 35;
2277 } else if ($userpicture->size === true or $userpicture->size == 1) {
2278 $size = 100;
2279 } else {
2280 $size = $userpicture->size;
2283 $class = $userpicture->class;
2285 if ($user->picture == 0) {
2286 $class .= ' defaultuserpic';
2289 $src = $userpicture->get_url($this->page, $this);
2291 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2293 // get the image html output fisrt
2294 $output = html_writer::empty_tag('img', $attributes);
2296 // then wrap it in link if needed
2297 if (!$userpicture->link) {
2298 return $output;
2301 if (empty($userpicture->courseid)) {
2302 $courseid = $this->page->course->id;
2303 } else {
2304 $courseid = $userpicture->courseid;
2307 if ($courseid == SITEID) {
2308 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2309 } else {
2310 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2313 $attributes = array('href'=>$url);
2315 if ($userpicture->popup) {
2316 $id = html_writer::random_id('userpicture');
2317 $attributes['id'] = $id;
2318 $this->add_action_handler(new popup_action('click', $url), $id);
2321 return html_writer::tag('a', $output, $attributes);
2325 * Internal implementation of file tree viewer items rendering.
2327 * @param array $dir
2328 * @return string
2330 public function htmllize_file_tree($dir) {
2331 if (empty($dir['subdirs']) and empty($dir['files'])) {
2332 return '';
2334 $result = '<ul>';
2335 foreach ($dir['subdirs'] as $subdir) {
2336 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2338 foreach ($dir['files'] as $file) {
2339 $filename = $file->get_filename();
2340 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2342 $result .= '</ul>';
2344 return $result;
2348 * Returns HTML to display the file picker
2350 * <pre>
2351 * $OUTPUT->file_picker($options);
2352 * </pre>
2354 * Theme developers: DO NOT OVERRIDE! Please override function
2355 * {@link core_renderer::render_file_picker()} instead.
2357 * @param array $options associative array with file manager options
2358 * options are:
2359 * maxbytes=>-1,
2360 * itemid=>0,
2361 * client_id=>uniqid(),
2362 * acepted_types=>'*',
2363 * return_types=>FILE_INTERNAL,
2364 * context=>$PAGE->context
2365 * @return string HTML fragment
2367 public function file_picker($options) {
2368 $fp = new file_picker($options);
2369 return $this->render($fp);
2373 * Internal implementation of file picker rendering.
2375 * @param file_picker $fp
2376 * @return string
2378 public function render_file_picker(file_picker $fp) {
2379 global $CFG, $OUTPUT, $USER;
2380 $options = $fp->options;
2381 $client_id = $options->client_id;
2382 $strsaved = get_string('filesaved', 'repository');
2383 $straddfile = get_string('openpicker', 'repository');
2384 $strloading = get_string('loading', 'repository');
2385 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2386 $strdroptoupload = get_string('droptoupload', 'moodle');
2387 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2389 $currentfile = $options->currentfile;
2390 if (empty($currentfile)) {
2391 $currentfile = '';
2392 } else {
2393 $currentfile .= ' - ';
2395 if ($options->maxbytes) {
2396 $size = $options->maxbytes;
2397 } else {
2398 $size = get_max_upload_file_size();
2400 if ($size == -1) {
2401 $maxsize = '';
2402 } else {
2403 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2405 if ($options->buttonname) {
2406 $buttonname = ' name="' . $options->buttonname . '"';
2407 } else {
2408 $buttonname = '';
2410 $html = <<<EOD
2411 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2412 $icon_progress
2413 </div>
2414 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2415 <div>
2416 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2417 <span> $maxsize </span>
2418 </div>
2419 EOD;
2420 if ($options->env != 'url') {
2421 $html .= <<<EOD
2422 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2423 <div class="filepicker-filename">
2424 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2425 <div class="dndupload-progressbars"></div>
2426 </div>
2427 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2428 </div>
2429 EOD;
2431 $html .= '</div>';
2432 return $html;
2436 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2438 * @param string $cmid the course_module id.
2439 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2440 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2442 public function update_module_button($cmid, $modulename) {
2443 global $CFG;
2444 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2445 $modulename = get_string('modulename', $modulename);
2446 $string = get_string('updatethis', '', $modulename);
2447 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2448 return $this->single_button($url, $string);
2449 } else {
2450 return '';
2455 * Returns HTML to display a "Turn editing on/off" button in a form.
2457 * @param moodle_url $url The URL + params to send through when clicking the button
2458 * @return string HTML the button
2460 public function edit_button(moodle_url $url) {
2462 $url->param('sesskey', sesskey());
2463 if ($this->page->user_is_editing()) {
2464 $url->param('edit', 'off');
2465 $editstring = get_string('turneditingoff');
2466 } else {
2467 $url->param('edit', 'on');
2468 $editstring = get_string('turneditingon');
2471 return $this->single_button($url, $editstring);
2475 * Returns HTML to display a simple button to close a window
2477 * @param string $text The lang string for the button's label (already output from get_string())
2478 * @return string html fragment
2480 public function close_window_button($text='') {
2481 if (empty($text)) {
2482 $text = get_string('closewindow');
2484 $button = new single_button(new moodle_url('#'), $text, 'get');
2485 $button->add_action(new component_action('click', 'close_window'));
2487 return $this->container($this->render($button), 'closewindow');
2491 * Output an error message. By default wraps the error message in <span class="error">.
2492 * If the error message is blank, nothing is output.
2494 * @param string $message the error message.
2495 * @return string the HTML to output.
2497 public function error_text($message) {
2498 if (empty($message)) {
2499 return '';
2501 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2502 return html_writer::tag('span', $message, array('class' => 'error'));
2506 * Do not call this function directly.
2508 * To terminate the current script with a fatal error, call the {@link print_error}
2509 * function, or throw an exception. Doing either of those things will then call this
2510 * function to display the error, before terminating the execution.
2512 * @param string $message The message to output
2513 * @param string $moreinfourl URL where more info can be found about the error
2514 * @param string $link Link for the Continue button
2515 * @param array $backtrace The execution backtrace
2516 * @param string $debuginfo Debugging information
2517 * @return string the HTML to output.
2519 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2520 global $CFG;
2522 $output = '';
2523 $obbuffer = '';
2525 if ($this->has_started()) {
2526 // we can not always recover properly here, we have problems with output buffering,
2527 // html tables, etc.
2528 $output .= $this->opencontainers->pop_all_but_last();
2530 } else {
2531 // It is really bad if library code throws exception when output buffering is on,
2532 // because the buffered text would be printed before our start of page.
2533 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2534 error_reporting(0); // disable notices from gzip compression, etc.
2535 while (ob_get_level() > 0) {
2536 $buff = ob_get_clean();
2537 if ($buff === false) {
2538 break;
2540 $obbuffer .= $buff;
2542 error_reporting($CFG->debug);
2544 // Output not yet started.
2545 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2546 if (empty($_SERVER['HTTP_RANGE'])) {
2547 @header($protocol . ' 404 Not Found');
2548 } else {
2549 // Must stop byteserving attempts somehow,
2550 // this is weird but Chrome PDF viewer can be stopped only with 407!
2551 @header($protocol . ' 407 Proxy Authentication Required');
2554 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2555 $this->page->set_url('/'); // no url
2556 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2557 $this->page->set_title(get_string('error'));
2558 $this->page->set_heading($this->page->course->fullname);
2559 $output .= $this->header();
2562 $message = '<p class="errormessage">' . $message . '</p>'.
2563 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2564 get_string('moreinformation') . '</a></p>';
2565 if (empty($CFG->rolesactive)) {
2566 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2567 //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.
2569 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
2571 if ($CFG->debugdeveloper) {
2572 if (!empty($debuginfo)) {
2573 $debuginfo = s($debuginfo); // removes all nasty JS
2574 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2575 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2577 if (!empty($backtrace)) {
2578 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2580 if ($obbuffer !== '' ) {
2581 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2585 if (empty($CFG->rolesactive)) {
2586 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2587 } else if (!empty($link)) {
2588 $output .= $this->continue_button($link);
2591 $output .= $this->footer();
2593 // Padding to encourage IE to display our error page, rather than its own.
2594 $output .= str_repeat(' ', 512);
2596 return $output;
2600 * Output a notification (that is, a status message about something that has
2601 * just happened).
2603 * @param string $message the message to print out
2604 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2605 * @return string the HTML to output.
2607 public function notification($message, $classes = 'notifyproblem') {
2608 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2612 * Returns HTML to display a continue button that goes to a particular URL.
2614 * @param string|moodle_url $url The url the button goes to.
2615 * @return string the HTML to output.
2617 public function continue_button($url) {
2618 if (!($url instanceof moodle_url)) {
2619 $url = new moodle_url($url);
2621 $button = new single_button($url, get_string('continue'), 'get');
2622 $button->class = 'continuebutton';
2624 return $this->render($button);
2628 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2630 * Theme developers: DO NOT OVERRIDE! Please override function
2631 * {@link core_renderer::render_paging_bar()} instead.
2633 * @param int $totalcount The total number of entries available to be paged through
2634 * @param int $page The page you are currently viewing
2635 * @param int $perpage The number of entries that should be shown per page
2636 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2637 * @param string $pagevar name of page parameter that holds the page number
2638 * @return string the HTML to output.
2640 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2641 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2642 return $this->render($pb);
2646 * Internal implementation of paging bar rendering.
2648 * @param paging_bar $pagingbar
2649 * @return string
2651 protected function render_paging_bar(paging_bar $pagingbar) {
2652 $output = '';
2653 $pagingbar = clone($pagingbar);
2654 $pagingbar->prepare($this, $this->page, $this->target);
2656 if ($pagingbar->totalcount > $pagingbar->perpage) {
2657 $output .= get_string('page') . ':';
2659 if (!empty($pagingbar->previouslink)) {
2660 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
2663 if (!empty($pagingbar->firstlink)) {
2664 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
2667 foreach ($pagingbar->pagelinks as $link) {
2668 $output .= "&#160;&#160;$link";
2671 if (!empty($pagingbar->lastlink)) {
2672 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
2675 if (!empty($pagingbar->nextlink)) {
2676 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
2680 return html_writer::tag('div', $output, array('class' => 'paging'));
2684 * Output the place a skip link goes to.
2686 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2687 * @return string the HTML to output.
2689 public function skip_link_target($id = null) {
2690 return html_writer::tag('span', '', array('id' => $id));
2694 * Outputs a heading
2696 * @param string $text The text of the heading
2697 * @param int $level The level of importance of the heading. Defaulting to 2
2698 * @param string $classes A space-separated list of CSS classes. Defaulting to null
2699 * @param string $id An optional ID
2700 * @return string the HTML to output.
2702 public function heading($text, $level = 2, $classes = null, $id = null) {
2703 $level = (integer) $level;
2704 if ($level < 1 or $level > 6) {
2705 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2707 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2711 * Outputs a box.
2713 * @param string $contents The contents of the box
2714 * @param string $classes A space-separated list of CSS classes
2715 * @param string $id An optional ID
2716 * @param array $attributes An array of other attributes to give the box.
2717 * @return string the HTML to output.
2719 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
2720 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
2724 * Outputs the opening section of a box.
2726 * @param string $classes A space-separated list of CSS classes
2727 * @param string $id An optional ID
2728 * @param array $attributes An array of other attributes to give the box.
2729 * @return string the HTML to output.
2731 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
2732 $this->opencontainers->push('box', html_writer::end_tag('div'));
2733 $attributes['id'] = $id;
2734 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
2735 return html_writer::start_tag('div', $attributes);
2739 * Outputs the closing section of a box.
2741 * @return string the HTML to output.
2743 public function box_end() {
2744 return $this->opencontainers->pop('box');
2748 * Outputs a container.
2750 * @param string $contents The contents of the box
2751 * @param string $classes A space-separated list of CSS classes
2752 * @param string $id An optional ID
2753 * @return string the HTML to output.
2755 public function container($contents, $classes = null, $id = null) {
2756 return $this->container_start($classes, $id) . $contents . $this->container_end();
2760 * Outputs the opening section of a container.
2762 * @param string $classes A space-separated list of CSS classes
2763 * @param string $id An optional ID
2764 * @return string the HTML to output.
2766 public function container_start($classes = null, $id = null) {
2767 $this->opencontainers->push('container', html_writer::end_tag('div'));
2768 return html_writer::start_tag('div', array('id' => $id,
2769 'class' => renderer_base::prepare_classes($classes)));
2773 * Outputs the closing section of a container.
2775 * @return string the HTML to output.
2777 public function container_end() {
2778 return $this->opencontainers->pop('container');
2782 * Make nested HTML lists out of the items
2784 * The resulting list will look something like this:
2786 * <pre>
2787 * <<ul>>
2788 * <<li>><div class='tree_item parent'>(item contents)</div>
2789 * <<ul>
2790 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2791 * <</ul>>
2792 * <</li>>
2793 * <</ul>>
2794 * </pre>
2796 * @param array $items
2797 * @param array $attrs html attributes passed to the top ofs the list
2798 * @return string HTML
2800 public function tree_block_contents($items, $attrs = array()) {
2801 // exit if empty, we don't want an empty ul element
2802 if (empty($items)) {
2803 return '';
2805 // array of nested li elements
2806 $lis = array();
2807 foreach ($items as $item) {
2808 // this applies to the li item which contains all child lists too
2809 $content = $item->content($this);
2810 $liclasses = array($item->get_css_type());
2811 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2812 $liclasses[] = 'collapsed';
2814 if ($item->isactive === true) {
2815 $liclasses[] = 'current_branch';
2817 $liattr = array('class'=>join(' ',$liclasses));
2818 // class attribute on the div item which only contains the item content
2819 $divclasses = array('tree_item');
2820 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2821 $divclasses[] = 'branch';
2822 } else {
2823 $divclasses[] = 'leaf';
2825 if (!empty($item->classes) && count($item->classes)>0) {
2826 $divclasses[] = join(' ', $item->classes);
2828 $divattr = array('class'=>join(' ', $divclasses));
2829 if (!empty($item->id)) {
2830 $divattr['id'] = $item->id;
2832 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2833 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2834 $content = html_writer::empty_tag('hr') . $content;
2836 $content = html_writer::tag('li', $content, $liattr);
2837 $lis[] = $content;
2839 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2843 * Return the navbar content so that it can be echoed out by the layout
2845 * @return string XHTML navbar
2847 public function navbar() {
2848 $items = $this->page->navbar->get_items();
2849 $itemcount = count($items);
2850 if ($itemcount === 0) {
2851 return '';
2854 $htmlblocks = array();
2855 // Iterate the navarray and display each node
2856 $separator = get_separator();
2857 for ($i=0;$i < $itemcount;$i++) {
2858 $item = $items[$i];
2859 $item->hideicon = true;
2860 if ($i===0) {
2861 $content = html_writer::tag('li', $this->render($item));
2862 } else {
2863 $content = html_writer::tag('li', $separator.$this->render($item));
2865 $htmlblocks[] = $content;
2868 //accessibility: heading for navbar list (MDL-20446)
2869 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2870 $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks), array('role'=>'navigation'));
2871 // XHTML
2872 return $navbarcontent;
2876 * Renders a navigation node object.
2878 * @param navigation_node $item The navigation node to render.
2879 * @return string HTML fragment
2881 protected function render_navigation_node(navigation_node $item) {
2882 $content = $item->get_content();
2883 $title = $item->get_title();
2884 if ($item->icon instanceof renderable && !$item->hideicon) {
2885 $icon = $this->render($item->icon);
2886 $content = $icon.$content; // use CSS for spacing of icons
2888 if ($item->helpbutton !== null) {
2889 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2891 if ($content === '') {
2892 return '';
2894 if ($item->action instanceof action_link) {
2895 $link = $item->action;
2896 if ($item->hidden) {
2897 $link->add_class('dimmed');
2899 if (!empty($content)) {
2900 // Providing there is content we will use that for the link content.
2901 $link->text = $content;
2903 $content = $this->render($link);
2904 } else if ($item->action instanceof moodle_url) {
2905 $attributes = array();
2906 if ($title !== '') {
2907 $attributes['title'] = $title;
2909 if ($item->hidden) {
2910 $attributes['class'] = 'dimmed_text';
2912 $content = html_writer::link($item->action, $content, $attributes);
2914 } else if (is_string($item->action) || empty($item->action)) {
2915 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2916 if ($title !== '') {
2917 $attributes['title'] = $title;
2919 if ($item->hidden) {
2920 $attributes['class'] = 'dimmed_text';
2922 $content = html_writer::tag('span', $content, $attributes);
2924 return $content;
2928 * Accessibility: Right arrow-like character is
2929 * used in the breadcrumb trail, course navigation menu
2930 * (previous/next activity), calendar, and search forum block.
2931 * If the theme does not set characters, appropriate defaults
2932 * are set automatically. Please DO NOT
2933 * use &lt; &gt; &raquo; - these are confusing for blind users.
2935 * @return string
2937 public function rarrow() {
2938 return $this->page->theme->rarrow;
2942 * Accessibility: Right arrow-like character is
2943 * used in the breadcrumb trail, course navigation menu
2944 * (previous/next activity), calendar, and search forum block.
2945 * If the theme does not set characters, appropriate defaults
2946 * are set automatically. Please DO NOT
2947 * use &lt; &gt; &raquo; - these are confusing for blind users.
2949 * @return string
2951 public function larrow() {
2952 return $this->page->theme->larrow;
2956 * Returns the custom menu if one has been set
2958 * A custom menu can be configured by browsing to
2959 * Settings: Administration > Appearance > Themes > Theme settings
2960 * and then configuring the custommenu config setting as described.
2962 * Theme developers: DO NOT OVERRIDE! Please override function
2963 * {@link core_renderer::render_custom_menu()} instead.
2965 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
2966 * @return string
2968 public function custom_menu($custommenuitems = '') {
2969 global $CFG;
2970 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
2971 $custommenuitems = $CFG->custommenuitems;
2973 if (empty($custommenuitems)) {
2974 return '';
2976 $custommenu = new custom_menu($custommenuitems, current_language());
2977 return $this->render($custommenu);
2981 * Renders a custom menu object (located in outputcomponents.php)
2983 * The custom menu this method produces makes use of the YUI3 menunav widget
2984 * and requires very specific html elements and classes.
2986 * @staticvar int $menucount
2987 * @param custom_menu $menu
2988 * @return string
2990 protected function render_custom_menu(custom_menu $menu) {
2991 static $menucount = 0;
2992 // If the menu has no children return an empty string
2993 if (!$menu->has_children()) {
2994 return '';
2996 // Increment the menu count. This is used for ID's that get worked with
2997 // in JavaScript as is essential
2998 $menucount++;
2999 // Initialise this custom menu (the custom menu object is contained in javascript-static
3000 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
3001 $jscode = "(function(){{$jscode}})";
3002 $this->page->requires->yui_module('node-menunav', $jscode);
3003 // Build the root nodes as required by YUI
3004 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
3005 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3006 $content .= html_writer::start_tag('ul');
3007 // Render each child
3008 foreach ($menu->get_children() as $item) {
3009 $content .= $this->render_custom_menu_item($item);
3011 // Close the open tags
3012 $content .= html_writer::end_tag('ul');
3013 $content .= html_writer::end_tag('div');
3014 $content .= html_writer::end_tag('div');
3015 // Return the custom menu
3016 return $content;
3020 * Renders a custom menu node as part of a submenu
3022 * The custom menu this method produces makes use of the YUI3 menunav widget
3023 * and requires very specific html elements and classes.
3025 * @see core:renderer::render_custom_menu()
3027 * @staticvar int $submenucount
3028 * @param custom_menu_item $menunode
3029 * @return string
3031 protected function render_custom_menu_item(custom_menu_item $menunode) {
3032 // Required to ensure we get unique trackable id's
3033 static $submenucount = 0;
3034 if ($menunode->has_children()) {
3035 // If the child has menus render it as a sub menu
3036 $submenucount++;
3037 $content = html_writer::start_tag('li');
3038 if ($menunode->get_url() !== null) {
3039 $url = $menunode->get_url();
3040 } else {
3041 $url = '#cm_submenu_'.$submenucount;
3043 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3044 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3045 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3046 $content .= html_writer::start_tag('ul');
3047 foreach ($menunode->get_children() as $menunode) {
3048 $content .= $this->render_custom_menu_item($menunode);
3050 $content .= html_writer::end_tag('ul');
3051 $content .= html_writer::end_tag('div');
3052 $content .= html_writer::end_tag('div');
3053 $content .= html_writer::end_tag('li');
3054 } else {
3055 // The node doesn't have children so produce a final menuitem
3056 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
3057 if ($menunode->get_url() !== null) {
3058 $url = $menunode->get_url();
3059 } else {
3060 $url = '#';
3062 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
3063 $content .= html_writer::end_tag('li');
3065 // Return the sub menu
3066 return $content;
3070 * Renders theme links for switching between default and other themes.
3072 * @return string
3074 protected function theme_switch_links() {
3076 $actualdevice = core_useragent::get_device_type();
3077 $currentdevice = $this->page->devicetypeinuse;
3078 $switched = ($actualdevice != $currentdevice);
3080 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3081 // The user is using the a default device and hasn't switched so don't shown the switch
3082 // device links.
3083 return '';
3086 if ($switched) {
3087 $linktext = get_string('switchdevicerecommended');
3088 $devicetype = $actualdevice;
3089 } else {
3090 $linktext = get_string('switchdevicedefault');
3091 $devicetype = 'default';
3093 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3095 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3096 $content .= html_writer::link($linkurl, $linktext);
3097 $content .= html_writer::end_tag('div');
3099 return $content;
3103 * Renders tabs
3105 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3107 * Theme developers: In order to change how tabs are displayed please override functions
3108 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3110 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3111 * @param string|null $selected which tab to mark as selected, all parent tabs will
3112 * automatically be marked as activated
3113 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3114 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3115 * @return string
3117 public final function tabtree($tabs, $selected = null, $inactive = null) {
3118 return $this->render(new tabtree($tabs, $selected, $inactive));
3122 * Renders tabtree
3124 * @param tabtree $tabtree
3125 * @return string
3127 protected function render_tabtree(tabtree $tabtree) {
3128 if (empty($tabtree->subtree)) {
3129 return '';
3131 $str = '';
3132 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
3133 $str .= $this->render_tabobject($tabtree);
3134 $str .= html_writer::end_tag('div').
3135 html_writer::tag('div', ' ', array('class' => 'clearer'));
3136 return $str;
3140 * Renders tabobject (part of tabtree)
3142 * This function is called from {@link core_renderer::render_tabtree()}
3143 * and also it calls itself when printing the $tabobject subtree recursively.
3145 * Property $tabobject->level indicates the number of row of tabs.
3147 * @param tabobject $tabobject
3148 * @return string HTML fragment
3150 protected function render_tabobject(tabobject $tabobject) {
3151 $str = '';
3153 // Print name of the current tab.
3154 if ($tabobject instanceof tabtree) {
3155 // No name for tabtree root.
3156 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3157 // Tab name without a link. The <a> tag is used for styling.
3158 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3159 } else {
3160 // Tab name with a link.
3161 if (!($tabobject->link instanceof moodle_url)) {
3162 // backward compartibility when link was passed as quoted string
3163 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3164 } else {
3165 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3169 if (empty($tabobject->subtree)) {
3170 if ($tabobject->selected) {
3171 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3173 return $str;
3176 // Print subtree
3177 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3178 $cnt = 0;
3179 foreach ($tabobject->subtree as $tab) {
3180 $liclass = '';
3181 if (!$cnt) {
3182 $liclass .= ' first';
3184 if ($cnt == count($tabobject->subtree) - 1) {
3185 $liclass .= ' last';
3187 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3188 $liclass .= ' onerow';
3191 if ($tab->selected) {
3192 $liclass .= ' here selected';
3193 } else if ($tab->activated) {
3194 $liclass .= ' here active';
3197 // This will recursively call function render_tabobject() for each item in subtree
3198 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3199 $cnt++;
3201 $str .= html_writer::end_tag('ul');
3203 return $str;
3207 * Get the HTML for blocks in the given region.
3209 * @since 2.5.1 2.6
3210 * @param string $region The region to get HTML for.
3211 * @return string HTML.
3213 public function blocks($region, $classes = array(), $tag = 'aside') {
3214 $displayregion = $this->page->apply_theme_region_manipulations($region);
3215 $classes = (array)$classes;
3216 $classes[] = 'block-region';
3217 $attributes = array(
3218 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3219 'class' => join(' ', $classes),
3220 'data-blockregion' => $displayregion,
3221 'data-droptarget' => '1'
3223 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3224 $content = $this->blocks_for_region($displayregion);
3225 } else {
3226 $content = '';
3228 return html_writer::tag($tag, $content, $attributes);
3232 * Returns the CSS classes to apply to the body tag.
3234 * @since 2.5.1 2.6
3235 * @param array $additionalclasses Any additional classes to apply.
3236 * @return string
3238 public function body_css_classes(array $additionalclasses = array()) {
3239 // Add a class for each block region on the page.
3240 // We use the block manager here because the theme object makes get_string calls.
3241 foreach ($this->page->blocks->get_regions() as $region) {
3242 $additionalclasses[] = 'has-region-'.$region;
3243 if ($this->page->blocks->region_has_content($region, $this)) {
3244 $additionalclasses[] = 'used-region-'.$region;
3245 } else {
3246 $additionalclasses[] = 'empty-region-'.$region;
3249 foreach ($this->page->layout_options as $option => $value) {
3250 if ($value) {
3251 $additionalclasses[] = 'layout-option-'.$option;
3254 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
3255 return $css;
3259 * The ID attribute to apply to the body tag.
3261 * @since 2.5.1 2.6
3262 * @return string
3264 public function body_id() {
3265 return $this->page->bodyid;
3269 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
3271 * @since 2.5.1 2.6
3272 * @param string|array $additionalclasses Any additional classes to give the body tag,
3273 * @return string
3275 public function body_attributes($additionalclasses = array()) {
3276 if (!is_array($additionalclasses)) {
3277 $additionalclasses = explode(' ', $additionalclasses);
3279 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
3283 * Gets HTML for the page heading.
3285 * @since 2.5.1 2.6
3286 * @param string $tag The tag to encase the heading in. h1 by default.
3287 * @return string HTML.
3289 public function page_heading($tag = 'h1') {
3290 return html_writer::tag($tag, $this->page->heading);
3294 * Gets the HTML for the page heading button.
3296 * @since 2.5.1 2.6
3297 * @return string HTML.
3299 public function page_heading_button() {
3300 return $this->page->button;
3304 * Returns the Moodle docs link to use for this page.
3306 * @since 2.5.1 2.6
3307 * @param string $text
3308 * @return string
3310 public function page_doc_link($text = null) {
3311 if ($text === null) {
3312 $text = get_string('moodledocslink');
3314 $path = page_get_doc_link_path($this->page);
3315 if (!$path) {
3316 return '';
3318 return $this->doc_link($path, $text);
3322 * Returns the page heading menu.
3324 * @since 2.5.1 2.6
3325 * @return string HTML.
3327 public function page_heading_menu() {
3328 return $this->page->headingmenu;
3332 * Returns the title to use on the page.
3334 * @since 2.5.1 2.6
3335 * @return string
3337 public function page_title() {
3338 return $this->page->title;
3342 * Returns the URL for the favicon.
3344 * @since 2.5.1 2.6
3345 * @return string The favicon URL
3347 public function favicon() {
3348 return $this->pix_url('favicon', 'theme');
3353 * A renderer that generates output for command-line scripts.
3355 * The implementation of this renderer is probably incomplete.
3357 * @copyright 2009 Tim Hunt
3358 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3359 * @since Moodle 2.0
3360 * @package core
3361 * @category output
3363 class core_renderer_cli extends core_renderer {
3366 * Returns the page header.
3368 * @return string HTML fragment
3370 public function header() {
3371 return $this->page->heading . "\n";
3375 * Returns a template fragment representing a Heading.
3377 * @param string $text The text of the heading
3378 * @param int $level The level of importance of the heading
3379 * @param string $classes A space-separated list of CSS classes
3380 * @param string $id An optional ID
3381 * @return string A template fragment for a heading
3383 public function heading($text, $level = 2, $classes = 'main', $id = null) {
3384 $text .= "\n";
3385 switch ($level) {
3386 case 1:
3387 return '=>' . $text;
3388 case 2:
3389 return '-->' . $text;
3390 default:
3391 return $text;
3396 * Returns a template fragment representing a fatal error.
3398 * @param string $message The message to output
3399 * @param string $moreinfourl URL where more info can be found about the error
3400 * @param string $link Link for the Continue button
3401 * @param array $backtrace The execution backtrace
3402 * @param string $debuginfo Debugging information
3403 * @return string A template fragment for a fatal error
3405 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
3406 global $CFG;
3408 $output = "!!! $message !!!\n";
3410 if ($CFG->debugdeveloper) {
3411 if (!empty($debuginfo)) {
3412 $output .= $this->notification($debuginfo, 'notifytiny');
3414 if (!empty($backtrace)) {
3415 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
3419 return $output;
3423 * Returns a template fragment representing a notification.
3425 * @param string $message The message to include
3426 * @param string $classes A space-separated list of CSS classes
3427 * @return string A template fragment for a notification
3429 public function notification($message, $classes = 'notifyproblem') {
3430 $message = clean_text($message);
3431 if ($classes === 'notifysuccess') {
3432 return "++ $message ++\n";
3434 return "!! $message !!\n";
3440 * A renderer that generates output for ajax scripts.
3442 * This renderer prevents accidental sends back only json
3443 * encoded error messages, all other output is ignored.
3445 * @copyright 2010 Petr Skoda
3446 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3447 * @since Moodle 2.0
3448 * @package core
3449 * @category output
3451 class core_renderer_ajax extends core_renderer {
3454 * Returns a template fragment representing a fatal error.
3456 * @param string $message The message to output
3457 * @param string $moreinfourl URL where more info can be found about the error
3458 * @param string $link Link for the Continue button
3459 * @param array $backtrace The execution backtrace
3460 * @param string $debuginfo Debugging information
3461 * @return string A template fragment for a fatal error
3463 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
3464 global $CFG;
3466 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
3468 $e = new stdClass();
3469 $e->error = $message;
3470 $e->stacktrace = NULL;
3471 $e->debuginfo = NULL;
3472 $e->reproductionlink = NULL;
3473 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
3474 $e->reproductionlink = $link;
3475 if (!empty($debuginfo)) {
3476 $e->debuginfo = $debuginfo;
3478 if (!empty($backtrace)) {
3479 $e->stacktrace = format_backtrace($backtrace, true);
3482 $this->header();
3483 return json_encode($e);
3487 * Used to display a notification.
3488 * For the AJAX notifications are discarded.
3490 * @param string $message
3491 * @param string $classes
3493 public function notification($message, $classes = 'notifyproblem') {}
3496 * Used to display a redirection message.
3497 * AJAX redirections should not occur and as such redirection messages
3498 * are discarded.
3500 * @param moodle_url|string $encodedurl
3501 * @param string $message
3502 * @param int $delay
3503 * @param bool $debugdisableredirect
3505 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
3508 * Prepares the start of an AJAX output.
3510 public function header() {
3511 // unfortunately YUI iframe upload does not support application/json
3512 if (!empty($_FILES)) {
3513 @header('Content-type: text/plain; charset=utf-8');
3514 if (!core_useragent::supports_json_contenttype()) {
3515 @header('X-Content-Type-Options: nosniff');
3517 } else if (!core_useragent::supports_json_contenttype()) {
3518 @header('Content-type: text/plain; charset=utf-8');
3519 @header('X-Content-Type-Options: nosniff');
3520 } else {
3521 @header('Content-type: application/json; charset=utf-8');
3524 // Headers to make it not cacheable and json
3525 @header('Cache-Control: no-store, no-cache, must-revalidate');
3526 @header('Cache-Control: post-check=0, pre-check=0', false);
3527 @header('Pragma: no-cache');
3528 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
3529 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
3530 @header('Accept-Ranges: none');
3534 * There is no footer for an AJAX request, however we must override the
3535 * footer method to prevent the default footer.
3537 public function footer() {}
3540 * No need for headers in an AJAX request... this should never happen.
3541 * @param string $text
3542 * @param int $level
3543 * @param string $classes
3544 * @param string $id
3546 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
3551 * Renderer for media files.
3553 * Used in file resources, media filter, and any other places that need to
3554 * output embedded media.
3556 * @copyright 2011 The Open University
3557 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3559 class core_media_renderer extends plugin_renderer_base {
3560 /** @var array Array of available 'player' objects */
3561 private $players;
3562 /** @var string Regex pattern for links which may contain embeddable content */
3563 private $embeddablemarkers;
3566 * Constructor requires medialib.php.
3568 * This is needed in the constructor (not later) so that you can use the
3569 * constants and static functions that are defined in core_media class
3570 * before you call renderer functions.
3572 public function __construct() {
3573 global $CFG;
3574 require_once($CFG->libdir . '/medialib.php');
3578 * Obtains the list of core_media_player objects currently in use to render
3579 * items.
3581 * The list is in rank order (highest first) and does not include players
3582 * which are disabled.
3584 * @return array Array of core_media_player objects in rank order
3586 protected function get_players() {
3587 global $CFG;
3589 // Save time by only building the list once.
3590 if (!$this->players) {
3591 // Get raw list of players.
3592 $players = $this->get_players_raw();
3594 // Chuck all the ones that are disabled.
3595 foreach ($players as $key => $player) {
3596 if (!$player->is_enabled()) {
3597 unset($players[$key]);
3601 // Sort in rank order (highest first).
3602 usort($players, array('core_media_player', 'compare_by_rank'));
3603 $this->players = $players;
3605 return $this->players;
3609 * Obtains a raw list of player objects that includes objects regardless
3610 * of whether they are disabled or not, and without sorting.
3612 * You can override this in a subclass if you need to add additional
3613 * players.
3615 * The return array is be indexed by player name to make it easier to
3616 * remove players in a subclass.
3618 * @return array $players Array of core_media_player objects in any order
3620 protected function get_players_raw() {
3621 return array(
3622 'vimeo' => new core_media_player_vimeo(),
3623 'youtube' => new core_media_player_youtube(),
3624 'youtube_playlist' => new core_media_player_youtube_playlist(),
3625 'html5video' => new core_media_player_html5video(),
3626 'html5audio' => new core_media_player_html5audio(),
3627 'mp3' => new core_media_player_mp3(),
3628 'flv' => new core_media_player_flv(),
3629 'wmp' => new core_media_player_wmp(),
3630 'qt' => new core_media_player_qt(),
3631 'rm' => new core_media_player_rm(),
3632 'swf' => new core_media_player_swf(),
3633 'link' => new core_media_player_link(),
3638 * Renders a media file (audio or video) using suitable embedded player.
3640 * See embed_alternatives function for full description of parameters.
3641 * This function calls through to that one.
3643 * When using this function you can also specify width and height in the
3644 * URL by including ?d=100x100 at the end. If specified in the URL, this
3645 * will override the $width and $height parameters.
3647 * @param moodle_url $url Full URL of media file
3648 * @param string $name Optional user-readable name to display in download link
3649 * @param int $width Width in pixels (optional)
3650 * @param int $height Height in pixels (optional)
3651 * @param array $options Array of key/value pairs
3652 * @return string HTML content of embed
3654 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
3655 $options = array()) {
3657 // Get width and height from URL if specified (overrides parameters in
3658 // function call).
3659 $rawurl = $url->out(false);
3660 if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
3661 $width = $matches[1];
3662 $height = $matches[2];
3663 $url = new moodle_url(str_replace($matches[0], '', $rawurl));
3666 // Defer to array version of function.
3667 return $this->embed_alternatives(array($url), $name, $width, $height, $options);
3671 * Renders media files (audio or video) using suitable embedded player.
3672 * The list of URLs should be alternative versions of the same content in
3673 * multiple formats. If there is only one format it should have a single
3674 * entry.
3676 * If the media files are not in a supported format, this will give students
3677 * a download link to each format. The download link uses the filename
3678 * unless you supply the optional name parameter.
3680 * Width and height are optional. If specified, these are suggested sizes
3681 * and should be the exact values supplied by the user, if they come from
3682 * user input. These will be treated as relating to the size of the video
3683 * content, not including any player control bar.
3685 * For audio files, height will be ignored. For video files, a few formats
3686 * work if you specify only width, but in general if you specify width
3687 * you must specify height as well.
3689 * The $options array is passed through to the core_media_player classes
3690 * that render the object tag. The keys can contain values from
3691 * core_media::OPTION_xx.
3693 * @param array $alternatives Array of moodle_url to media files
3694 * @param string $name Optional user-readable name to display in download link
3695 * @param int $width Width in pixels (optional)
3696 * @param int $height Height in pixels (optional)
3697 * @param array $options Array of key/value pairs
3698 * @return string HTML content of embed
3700 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
3701 $options = array()) {
3703 // Get list of player plugins (will also require the library).
3704 $players = $this->get_players();
3706 // Set up initial text which will be replaced by first player that
3707 // supports any of the formats.
3708 $out = core_media_player::PLACEHOLDER;
3710 // Loop through all players that support any of these URLs.
3711 foreach ($players as $player) {
3712 // Option: When no other player matched, don't do the default link player.
3713 if (!empty($options[core_media::OPTION_FALLBACK_TO_BLANK]) &&
3714 $player->get_rank() === 0 && $out === core_media_player::PLACEHOLDER) {
3715 continue;
3718 $supported = $player->list_supported_urls($alternatives, $options);
3719 if ($supported) {
3720 // Embed.
3721 $text = $player->embed($supported, $name, $width, $height, $options);
3723 // Put this in place of the 'fallback' slot in the previous text.
3724 $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
3728 // Remove 'fallback' slot from final version and return it.
3729 $out = str_replace(core_media_player::PLACEHOLDER, '', $out);
3730 if (!empty($options[core_media::OPTION_BLOCK]) && $out !== '') {
3731 $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
3733 return $out;
3737 * Checks whether a file can be embedded. If this returns true you will get
3738 * an embedded player; if this returns false, you will just get a download
3739 * link.
3741 * This is a wrapper for can_embed_urls.
3743 * @param moodle_url $url URL of media file
3744 * @param array $options Options (same as when embedding)
3745 * @return bool True if file can be embedded
3747 public function can_embed_url(moodle_url $url, $options = array()) {
3748 return $this->can_embed_urls(array($url), $options);
3752 * Checks whether a file can be embedded. If this returns true you will get
3753 * an embedded player; if this returns false, you will just get a download
3754 * link.
3756 * @param array $urls URL of media file and any alternatives (moodle_url)
3757 * @param array $options Options (same as when embedding)
3758 * @return bool True if file can be embedded
3760 public function can_embed_urls(array $urls, $options = array()) {
3761 // Check all players to see if any of them support it.
3762 foreach ($this->get_players() as $player) {
3763 // Link player (always last on list) doesn't count!
3764 if ($player->get_rank() <= 0) {
3765 break;
3767 // First player that supports it, return true.
3768 if ($player->list_supported_urls($urls, $options)) {
3769 return true;
3772 return false;
3776 * Obtains a list of markers that can be used in a regular expression when
3777 * searching for URLs that can be embedded by any player type.
3779 * This string is used to improve peformance of regex matching by ensuring
3780 * that the (presumably C) regex code can do a quick keyword check on the
3781 * URL part of a link to see if it matches one of these, rather than having
3782 * to go into PHP code for every single link to see if it can be embedded.
3784 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
3786 public function get_embeddable_markers() {
3787 if (empty($this->embeddablemarkers)) {
3788 $markers = '';
3789 foreach ($this->get_players() as $player) {
3790 foreach ($player->get_embeddable_markers() as $marker) {
3791 if ($markers !== '') {
3792 $markers .= '|';
3794 $markers .= preg_quote($marker);
3797 $this->embeddablemarkers = $markers;
3799 return $this->embeddablemarkers;
3804 * The maintenance renderer.
3806 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
3807 * is running a maintenance related task.
3808 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
3810 * @since 2.6
3811 * @package core
3812 * @category output
3813 * @copyright 2013 Sam Hemelryk
3814 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3816 class core_renderer_maintenance extends core_renderer {
3819 * Initialises the renderer instance.
3820 * @param moodle_page $page
3821 * @param string $target
3822 * @throws coding_exception
3824 public function __construct(moodle_page $page, $target) {
3825 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
3826 throw new coding_exception('Invalid request for the maintenance renderer.');
3828 parent::__construct($page, $target);
3832 * Does nothing. The maintenance renderer cannot produce blocks.
3834 * @param block_contents $bc
3835 * @param string $region
3836 * @return string
3838 public function block(block_contents $bc, $region) {
3839 // Computer says no blocks.
3840 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3841 return '';
3845 * Does nothing. The maintenance renderer cannot produce blocks.
3847 * @param string $region
3848 * @param array $classes
3849 * @param string $tag
3850 * @return string
3852 public function blocks($region, $classes = array(), $tag = 'aside') {
3853 // Computer says no blocks.
3854 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3855 return '';
3859 * Does nothing. The maintenance renderer cannot produce blocks.
3861 * @param string $region
3862 * @return string
3864 public function blocks_for_region($region) {
3865 // Computer says no blocks for region.
3866 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3867 return '';
3871 * Does nothing. The maintenance renderer cannot produce a course content header.
3873 * @param bool $onlyifnotcalledbefore
3874 * @return string
3876 public function course_content_header($onlyifnotcalledbefore = false) {
3877 // Computer says no course content header.
3878 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3879 return '';
3883 * Does nothing. The maintenance renderer cannot produce a course content footer.
3885 * @param bool $onlyifnotcalledbefore
3886 * @return string
3888 public function course_content_footer($onlyifnotcalledbefore = false) {
3889 // Computer says no course content footer.
3890 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3891 return '';
3895 * Does nothing. The maintenance renderer cannot produce a course header.
3897 * @return string
3899 public function course_header() {
3900 // Computer says no course header.
3901 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3902 return '';
3906 * Does nothing. The maintenance renderer cannot produce a course footer.
3908 * @return string
3910 public function course_footer() {
3911 // Computer says no course footer.
3912 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3913 return '';
3917 * Does nothing. The maintenance renderer cannot produce a custom menu.
3919 * @param string $custommenuitems
3920 * @return string
3922 public function custom_menu($custommenuitems = '') {
3923 // Computer says no custom menu.
3924 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3925 return '';
3929 * Does nothing. The maintenance renderer cannot produce a file picker.
3931 * @param array $options
3932 * @return string
3934 public function file_picker($options) {
3935 // Computer says no file picker.
3936 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3937 return '';
3941 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
3943 * @param array $dir
3944 * @return string
3946 public function htmllize_file_tree($dir) {
3947 // Hell no we don't want no htmllized file tree.
3948 // Also why on earth is this function on the core renderer???
3949 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3950 return '';
3955 * Does nothing. The maintenance renderer does not support JS.
3957 * @param block_contents $bc
3959 public function init_block_hider_js(block_contents $bc) {
3960 // Computer says no JavaScript.
3961 // Do nothing, ridiculous method.
3965 * Does nothing. The maintenance renderer cannot produce language menus.
3967 * @return string
3969 public function lang_menu() {
3970 // Computer says no lang menu.
3971 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3972 return '';
3976 * Does nothing. The maintenance renderer has no need for login information.
3978 * @param null $withlinks
3979 * @return string
3981 public function login_info($withlinks = null) {
3982 // Computer says no login info.
3983 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3984 return '';
3988 * Does nothing. The maintenance renderer cannot produce user pictures.
3990 * @param stdClass $user
3991 * @param array $options
3992 * @return string
3994 public function user_picture(stdClass $user, array $options = null) {
3995 // Computer says no user pictures.
3996 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3997 return '';