Merge branch 'MDL-32903' of git://github.com/netspotau/moodle-mod_assign
[moodle.git] / lib / outputrenderers.php
blob95d3bb88356759f808a38c4f3d27823c3f96f942
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
21 * for an overview.
23 * Included in this file are the primary renderer classes:
24 * - renderer_base: The renderer outline class that all renderers
25 * should inherit from.
26 * - core_renderer: The standard HTML renderer.
27 * - core_renderer_cli: An adaption of the standard renderer for CLI scripts.
28 * - core_renderer_ajax: An adaption of the standard renderer for AJAX scripts.
29 * - plugin_renderer_base: A renderer class that should be extended by all
30 * plugin renderers.
32 * @package core
33 * @category output
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') || die();
40 /**
41 * Simple base class for Moodle renderers.
43 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
45 * Also has methods to facilitate generating HTML output.
47 * @copyright 2009 Tim Hunt
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 * @since Moodle 2.0
50 * @package core
51 * @category output
53 class renderer_base {
54 /**
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
59 /**
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
62 protected $page;
64 /**
65 * @var string The requested rendering target.
67 protected $target;
69 /**
70 * Constructor
72 * The constructor takes two arguments. The first is the page that the renderer
73 * has been created to assist with, and the second is the target.
74 * The target is an additional identifier that can be used to load different
75 * renderers for different options.
77 * @param moodle_page $page the page we are doing output for.
78 * @param string $target one of rendering target constants
80 public function __construct(moodle_page $page, $target) {
81 $this->opencontainers = $page->opencontainers;
82 $this->page = $page;
83 $this->target = $target;
86 /**
87 * Returns rendered widget.
89 * The provided widget needs to be an object that extends the renderable
90 * interface.
91 * If will then be rendered by a method based upon the classname for the widget.
92 * For instance a widget of class `crazywidget` will be rendered by a protected
93 * render_crazywidget method of this renderer.
95 * @param renderable $widget instance with renderable interface
96 * @return string
98 public function render(renderable $widget) {
99 $rendermethod = 'render_'.get_class($widget);
100 if (method_exists($this, $rendermethod)) {
101 return $this->$rendermethod($widget);
103 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
107 * Adds a JS action for the element with the provided id.
109 * This method adds a JS event for the provided component action to the page
110 * and then returns the id that the event has been attached to.
111 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
113 * @param component_action $action
114 * @param string $id
115 * @return string id of element, either original submitted or random new if not supplied
117 public function add_action_handler(component_action $action, $id = null) {
118 if (!$id) {
119 $id = html_writer::random_id($action->event);
121 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
122 return $id;
126 * Returns true is output has already started, and false if not.
128 * @return boolean true if the header has been printed.
130 public function has_started() {
131 return $this->page->state >= moodle_page::STATE_IN_BODY;
135 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
137 * @param mixed $classes Space-separated string or array of classes
138 * @return string HTML class attribute value
140 public static function prepare_classes($classes) {
141 if (is_array($classes)) {
142 return implode(' ', array_unique($classes));
144 return $classes;
148 * Return the moodle_url for an image.
150 * The exact image location and extension is determined
151 * automatically by searching for gif|png|jpg|jpeg, please
152 * note there can not be diferent images with the different
153 * extension. The imagename is for historical reasons
154 * a relative path name, it may be changed later for core
155 * images. It is recommended to not use subdirectories
156 * in plugin and theme pix directories.
158 * There are three types of images:
159 * 1/ theme images - stored in theme/mytheme/pix/,
160 * use component 'theme'
161 * 2/ core images - stored in /pix/,
162 * overridden via theme/mytheme/pix_core/
163 * 3/ plugin images - stored in mod/mymodule/pix,
164 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
165 * example: pix_url('comment', 'mod_glossary')
167 * @param string $imagename the pathname of the image
168 * @param string $component full plugin name (aka component) or 'theme'
169 * @return moodle_url
171 public function pix_url($imagename, $component = 'moodle') {
172 return $this->page->theme->pix_url($imagename, $component);
178 * Basis for all plugin renderers.
180 * @copyright Petr Skoda (skodak)
181 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
182 * @since Moodle 2.0
183 * @package core
184 * @category output
186 class plugin_renderer_base extends renderer_base {
189 * @var renderer_base|core_renderer A reference to the current renderer.
190 * The renderer provided here will be determined by the page but will in 90%
191 * of cases by the {@link core_renderer}
193 protected $output;
196 * Constructor method, calls the parent constructor
198 * @param moodle_page $page
199 * @param string $target one of rendering target constants
201 public function __construct(moodle_page $page, $target) {
202 $this->output = $page->get_renderer('core', null, $target);
203 parent::__construct($page, $target);
207 * Renders the provided widget and returns the HTML to display it.
209 * @param renderable $widget instance with renderable interface
210 * @return string
212 public function render(renderable $widget) {
213 $rendermethod = 'render_'.get_class($widget);
214 if (method_exists($this, $rendermethod)) {
215 return $this->$rendermethod($widget);
217 // pass to core renderer if method not found here
218 return $this->output->render($widget);
222 * Magic method used to pass calls otherwise meant for the standard renderer
223 * to it to ensure we don't go causing unnecessary grief.
225 * @param string $method
226 * @param array $arguments
227 * @return mixed
229 public function __call($method, $arguments) {
230 if (method_exists('renderer_base', $method)) {
231 throw new coding_exception('Protected method called against '.__CLASS__.' :: '.$method);
233 if (method_exists($this->output, $method)) {
234 return call_user_func_array(array($this->output, $method), $arguments);
235 } else {
236 throw new coding_exception('Unknown method called against '.__CLASS__.' :: '.$method);
243 * The standard implementation of the core_renderer interface.
245 * @copyright 2009 Tim Hunt
246 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
247 * @since Moodle 2.0
248 * @package core
249 * @category output
251 class core_renderer extends renderer_base {
253 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
254 * in layout files instead.
255 * @deprecated
256 * @var string used in {@link core_renderer::header()}.
258 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
261 * @var string Used to pass information from {@link core_renderer::doctype()} to
262 * {@link core_renderer::standard_head_html()}.
264 protected $contenttype;
267 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
268 * with {@link core_renderer::header()}.
270 protected $metarefreshtag = '';
273 * @var string Unique token for the closing HTML
275 protected $unique_end_html_token;
278 * @var string Unique token for performance information
280 protected $unique_performance_info_token;
283 * @var string Unique token for the main content.
285 protected $unique_main_content_token;
288 * Constructor
290 * @param moodle_page $page the page we are doing output for.
291 * @param string $target one of rendering target constants
293 public function __construct(moodle_page $page, $target) {
294 $this->opencontainers = $page->opencontainers;
295 $this->page = $page;
296 $this->target = $target;
298 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
299 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
300 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
304 * Get the DOCTYPE declaration that should be used with this page. Designed to
305 * be called in theme layout.php files.
307 * @return string the DOCTYPE declaration (and any XML prologue) that should be used.
309 public function doctype() {
310 global $CFG;
312 $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n";
313 $this->contenttype = 'text/html; charset=utf-8';
315 if (empty($CFG->xmlstrictheaders)) {
316 return $doctype;
319 // We want to serve the page with an XML content type, to force well-formedness errors to be reported.
320 $prolog = '<?xml version="1.0" encoding="utf-8"?>' . "\n";
321 if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml') !== false) {
322 // Firefox and other browsers that can cope natively with XHTML.
323 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
325 } else if (preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
326 // IE can't cope with application/xhtml+xml, but it will cope if we send application/xml with an XSL stylesheet.
327 $this->contenttype = 'application/xml; charset=utf-8';
328 $prolog .= '<?xml-stylesheet type="text/xsl" href="' . $CFG->httpswwwroot . '/lib/xhtml.xsl"?>' . "\n";
330 } else {
331 $prolog = '';
334 return $prolog . $doctype;
338 * The attributes that should be added to the <html> tag. Designed to
339 * be called in theme layout.php files.
341 * @return string HTML fragment.
343 public function htmlattributes() {
344 return get_html_lang(true) . ' xmlns="http://www.w3.org/1999/xhtml"';
348 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
349 * that should be included in the <head> tag. Designed to be called in theme
350 * layout.php files.
352 * @return string HTML fragment.
354 public function standard_head_html() {
355 global $CFG, $SESSION;
356 $output = '';
357 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
358 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
359 if (!$this->page->cacheable) {
360 $output .= '<meta http-equiv="pragma" content="no-cache" />' . "\n";
361 $output .= '<meta http-equiv="expires" content="0" />' . "\n";
363 // This is only set by the {@link redirect()} method
364 $output .= $this->metarefreshtag;
366 // Check if a periodic refresh delay has been set and make sure we arn't
367 // already meta refreshing
368 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
369 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
372 // flow player embedding support
373 $this->page->requires->js_function_call('M.util.load_flowplayer');
375 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
377 $focus = $this->page->focuscontrol;
378 if (!empty($focus)) {
379 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
380 // This is a horrifically bad way to handle focus but it is passed in
381 // through messy formslib::moodleform
382 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
383 } else if (strpos($focus, '.')!==false) {
384 // Old style of focus, bad way to do it
385 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);
386 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
387 } else {
388 // Focus element with given id
389 $this->page->requires->js_function_call('focuscontrol', array($focus));
393 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
394 // any other custom CSS can not be overridden via themes and is highly discouraged
395 $urls = $this->page->theme->css_urls($this->page);
396 foreach ($urls as $url) {
397 $this->page->requires->css_theme($url);
400 // Get the theme javascript head and footer
401 $jsurl = $this->page->theme->javascript_url(true);
402 $this->page->requires->js($jsurl, true);
403 $jsurl = $this->page->theme->javascript_url(false);
404 $this->page->requires->js($jsurl);
406 // Get any HTML from the page_requirements_manager.
407 $output .= $this->page->requires->get_head_code($this->page, $this);
409 // List alternate versions.
410 foreach ($this->page->alternateversions as $type => $alt) {
411 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
412 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
415 if (!empty($CFG->additionalhtmlhead)) {
416 $output .= "\n".$CFG->additionalhtmlhead;
419 return $output;
423 * The standard tags (typically skip links) that should be output just inside
424 * the start of the <body> tag. Designed to be called in theme layout.php files.
426 * @return string HTML fragment.
428 public function standard_top_of_body_html() {
429 global $CFG;
430 $output = $this->page->requires->get_top_of_body_code();
431 if (!empty($CFG->additionalhtmltopofbody)) {
432 $output .= "\n".$CFG->additionalhtmltopofbody;
434 return $output;
438 * The standard tags (typically performance information and validation links,
439 * if we are in developer debug mode) that should be output in the footer area
440 * of the page. Designed to be called in theme layout.php files.
442 * @return string HTML fragment.
444 public function standard_footer_html() {
445 global $CFG, $SCRIPT;
447 // This function is normally called from a layout.php file in {@link core_renderer::header()}
448 // but some of the content won't be known until later, so we return a placeholder
449 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
450 $output = $this->unique_performance_info_token;
451 if ($this->page->devicetypeinuse == 'legacy') {
452 // The legacy theme is in use print the notification
453 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
456 // Get links to switch device types (only shown for users not on a default device)
457 $output .= $this->theme_switch_links();
459 if (!empty($CFG->debugpageinfo)) {
460 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
462 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { // Only in developer mode
463 // Add link to profiling report if necessary
464 if (function_exists('profiling_is_running') && profiling_is_running()) {
465 $txt = get_string('profiledscript', 'admin');
466 $title = get_string('profiledscriptview', 'admin');
467 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
468 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
469 $output .= '<div class="profilingfooter">' . $link . '</div>';
471 $output .= '<div class="purgecaches"><a href="'.$CFG->wwwroot.'/admin/purgecaches.php?confirm=1&amp;sesskey='.sesskey().'">'.get_string('purgecaches', 'admin').'</a></div>';
473 if (!empty($CFG->debugvalidators)) {
474 // 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
475 $output .= '<div class="validators"><ul>
476 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
477 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
478 <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>
479 </ul></div>';
481 if (!empty($CFG->additionalhtmlfooter)) {
482 $output .= "\n".$CFG->additionalhtmlfooter;
484 return $output;
488 * Returns standard main content placeholder.
489 * Designed to be called in theme layout.php files.
491 * @return string HTML fragment.
493 public function main_content() {
494 return $this->unique_main_content_token;
498 * The standard tags (typically script tags that are not needed earlier) that
499 * should be output after everything else, . Designed to be called in theme layout.php files.
501 * @return string HTML fragment.
503 public function standard_end_of_body_html() {
504 // This function is normally called from a layout.php file in {@link core_renderer::header()}
505 // but some of the content won't be known until later, so we return a placeholder
506 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
507 return $this->unique_end_html_token;
511 * Return the standard string that says whether you are logged in (and switched
512 * roles/logged in as another user).
514 * @return string HTML fragment.
516 public function login_info() {
517 global $USER, $CFG, $DB, $SESSION;
519 if (during_initial_install()) {
520 return '';
523 $loginpage = ((string)$this->page->url === get_login_url());
524 $course = $this->page->course;
526 if (session_is_loggedinas()) {
527 $realuser = session_get_realuser();
528 $fullname = fullname($realuser, true);
529 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\">$fullname</a>] ";
530 } else {
531 $realuserinfo = '';
534 $loginurl = get_login_url();
536 if (empty($course->id)) {
537 // $course->id is not defined during installation
538 return '';
539 } else if (isloggedin()) {
540 $context = get_context_instance(CONTEXT_COURSE, $course->id);
542 $fullname = fullname($USER, true);
543 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
544 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\">$fullname</a>";
545 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
546 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
548 if (isguestuser()) {
549 $loggedinas = $realuserinfo.get_string('loggedinasguest');
550 if (!$loginpage) {
551 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
553 } else if (is_role_switched($course->id)) { // Has switched roles
554 $rolename = '';
555 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
556 $rolename = ': '.format_string($role->name);
558 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
559 " (<a href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
560 } else {
561 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
562 " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
564 } else {
565 $loggedinas = get_string('loggedinnot', 'moodle');
566 if (!$loginpage) {
567 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
571 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
573 if (isset($SESSION->justloggedin)) {
574 unset($SESSION->justloggedin);
575 if (!empty($CFG->displayloginfailures)) {
576 if (!isguestuser()) {
577 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
578 $loggedinas .= '&nbsp;<div class="loginfailures">';
579 if (empty($count->accounts)) {
580 $loggedinas .= get_string('failedloginattempts', '', $count);
581 } else {
582 $loggedinas .= get_string('failedloginattemptsall', '', $count);
584 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', get_context_instance(CONTEXT_SYSTEM))) {
585 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/report/log/index.php'.
586 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
588 $loggedinas .= '</div>';
594 return $loggedinas;
598 * Return the 'back' link that normally appears in the footer.
600 * @return string HTML fragment.
602 public function home_link() {
603 global $CFG, $SITE;
605 if ($this->page->pagetype == 'site-index') {
606 // Special case for site home page - please do not remove
607 return '<div class="sitelink">' .
608 '<a title="Moodle" href="http://moodle.org/">' .
609 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
611 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
612 // Special case for during install/upgrade.
613 return '<div class="sitelink">'.
614 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
615 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
617 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
618 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
619 get_string('home') . '</a></div>';
621 } else {
622 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
623 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
628 * Redirects the user by any means possible given the current state
630 * This function should not be called directly, it should always be called using
631 * the redirect function in lib/weblib.php
633 * The redirect function should really only be called before page output has started
634 * however it will allow itself to be called during the state STATE_IN_BODY
636 * @param string $encodedurl The URL to send to encoded if required
637 * @param string $message The message to display to the user if any
638 * @param int $delay The delay before redirecting a user, if $message has been
639 * set this is a requirement and defaults to 3, set to 0 no delay
640 * @param boolean $debugdisableredirect this redirect has been disabled for
641 * debugging purposes. Display a message that explains, and don't
642 * trigger the redirect.
643 * @return string The HTML to display to the user before dying, may contain
644 * meta refresh, javascript refresh, and may have set header redirects
646 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
647 global $CFG;
648 $url = str_replace('&amp;', '&', $encodedurl);
650 switch ($this->page->state) {
651 case moodle_page::STATE_BEFORE_HEADER :
652 // No output yet it is safe to delivery the full arsenal of redirect methods
653 if (!$debugdisableredirect) {
654 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
655 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
656 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
658 $output = $this->header();
659 break;
660 case moodle_page::STATE_PRINTING_HEADER :
661 // We should hopefully never get here
662 throw new coding_exception('You cannot redirect while printing the page header');
663 break;
664 case moodle_page::STATE_IN_BODY :
665 // We really shouldn't be here but we can deal with this
666 debugging("You should really redirect before you start page output");
667 if (!$debugdisableredirect) {
668 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
670 $output = $this->opencontainers->pop_all_but_last();
671 break;
672 case moodle_page::STATE_DONE :
673 // Too late to be calling redirect now
674 throw new coding_exception('You cannot redirect after the entire page has been generated');
675 break;
677 $output .= $this->notification($message, 'redirectmessage');
678 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
679 if ($debugdisableredirect) {
680 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
682 $output .= $this->footer();
683 return $output;
687 * Start output by sending the HTTP headers, and printing the HTML <head>
688 * and the start of the <body>.
690 * To control what is printed, you should set properties on $PAGE. If you
691 * are familiar with the old {@link print_header()} function from Moodle 1.9
692 * you will find that there are properties on $PAGE that correspond to most
693 * of the old parameters to could be passed to print_header.
695 * Not that, in due course, the remaining $navigation, $menu parameters here
696 * will be replaced by more properties of $PAGE, but that is still to do.
698 * @return string HTML that you must output this, preferably immediately.
700 public function header() {
701 global $USER, $CFG;
703 if (session_is_loggedinas()) {
704 $this->page->add_body_class('userloggedinas');
707 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
709 // Find the appropriate page layout file, based on $this->page->pagelayout.
710 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
711 // Render the layout using the layout file.
712 $rendered = $this->render_page_layout($layoutfile);
714 // Slice the rendered output into header and footer.
715 $cutpos = strpos($rendered, $this->unique_main_content_token);
716 if ($cutpos === false) {
717 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
718 $token = self::MAIN_CONTENT_TOKEN;
719 } else {
720 $token = $this->unique_main_content_token;
723 if ($cutpos === false) {
724 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.');
726 $header = substr($rendered, 0, $cutpos);
727 $footer = substr($rendered, $cutpos + strlen($token));
729 if (empty($this->contenttype)) {
730 debugging('The page layout file did not call $OUTPUT->doctype()');
731 $header = $this->doctype() . $header;
734 send_headers($this->contenttype, $this->page->cacheable);
736 $this->opencontainers->push('header/footer', $footer);
737 $this->page->set_state(moodle_page::STATE_IN_BODY);
739 return $header . $this->skip_link_target('maincontent');
743 * Renders and outputs the page layout file.
745 * This is done by preparing the normal globals available to a script, and
746 * then including the layout file provided by the current theme for the
747 * requested layout.
749 * @param string $layoutfile The name of the layout file
750 * @return string HTML code
752 protected function render_page_layout($layoutfile) {
753 global $CFG, $SITE, $USER;
754 // The next lines are a bit tricky. The point is, here we are in a method
755 // of a renderer class, and this object may, or may not, be the same as
756 // the global $OUTPUT object. When rendering the page layout file, we want to use
757 // this object. However, people writing Moodle code expect the current
758 // renderer to be called $OUTPUT, not $this, so define a variable called
759 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
760 $OUTPUT = $this;
761 $PAGE = $this->page;
762 $COURSE = $this->page->course;
764 ob_start();
765 include($layoutfile);
766 $rendered = ob_get_contents();
767 ob_end_clean();
768 return $rendered;
772 * Outputs the page's footer
774 * @return string HTML fragment
776 public function footer() {
777 global $CFG, $DB;
779 $output = $this->container_end_all(true);
781 $footer = $this->opencontainers->pop('header/footer');
783 if (debugging() and $DB and $DB->is_transaction_started()) {
784 // TODO: MDL-20625 print warning - transaction will be rolled back
787 // Provide some performance info if required
788 $performanceinfo = '';
789 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
790 $perf = get_performance_info();
791 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
792 error_log("PERF: " . $perf['txt']);
794 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
795 $performanceinfo = $perf['html'];
798 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
800 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
802 $this->page->set_state(moodle_page::STATE_DONE);
804 return $output . $footer;
808 * Close all but the last open container. This is useful in places like error
809 * handling, where you want to close all the open containers (apart from <body>)
810 * before outputting the error message.
812 * @param bool $shouldbenone assert that the stack should be empty now - causes a
813 * developer debug warning if it isn't.
814 * @return string the HTML required to close any open containers inside <body>.
816 public function container_end_all($shouldbenone = false) {
817 return $this->opencontainers->pop_all_but_last($shouldbenone);
821 * Returns lang menu or '', this method also checks forcing of languages in courses.
823 * @return string The lang menu HTML or empty string
825 public function lang_menu() {
826 global $CFG;
828 if (empty($CFG->langmenu)) {
829 return '';
832 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
833 // do not show lang menu if language forced
834 return '';
837 $currlang = current_language();
838 $langs = get_string_manager()->get_list_of_translations();
840 if (count($langs) < 2) {
841 return '';
844 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
845 $s->label = get_accesshide(get_string('language'));
846 $s->class = 'langmenu';
847 return $this->render($s);
851 * Output the row of editing icons for a block, as defined by the controls array.
853 * @param array $controls an array like {@link block_contents::$controls}.
854 * @return string HTML fragment.
856 public function block_controls($controls) {
857 if (empty($controls)) {
858 return '';
860 $controlshtml = array();
861 foreach ($controls as $control) {
862 $controlshtml[] = html_writer::tag('a',
863 html_writer::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
864 array('class' => 'icon ' . $control['class'],'title' => $control['caption'], 'href' => $control['url']));
866 return html_writer::tag('div', implode('', $controlshtml), array('class' => 'commands'));
870 * Prints a nice side block with an optional header.
872 * The content is described
873 * by a {@link core_renderer::block_contents} object.
875 * <div id="inst{$instanceid}" class="block_{$blockname} block">
876 * <div class="header"></div>
877 * <div class="content">
878 * ...CONTENT...
879 * <div class="footer">
880 * </div>
881 * </div>
882 * <div class="annotation">
883 * </div>
884 * </div>
886 * @param block_contents $bc HTML for the content
887 * @param string $region the region the block is appearing in.
888 * @return string the HTML to be output.
890 public function block(block_contents $bc, $region) {
891 $bc = clone($bc); // Avoid messing up the object passed in.
892 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
893 $bc->collapsible = block_contents::NOT_HIDEABLE;
895 if ($bc->collapsible == block_contents::HIDDEN) {
896 $bc->add_class('hidden');
898 if (!empty($bc->controls)) {
899 $bc->add_class('block_with_controls');
902 $skiptitle = strip_tags($bc->title);
903 if (empty($skiptitle)) {
904 $output = '';
905 $skipdest = '';
906 } else {
907 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
908 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
911 $output .= html_writer::start_tag('div', $bc->attributes);
913 $output .= $this->block_header($bc);
914 $output .= $this->block_content($bc);
916 $output .= html_writer::end_tag('div');
918 $output .= $this->block_annotation($bc);
920 $output .= $skipdest;
922 $this->init_block_hider_js($bc);
923 return $output;
927 * Produces a header for a block
929 * @param block_contents $bc
930 * @return string
932 protected function block_header(block_contents $bc) {
934 $title = '';
935 if ($bc->title) {
936 $title = html_writer::tag('h2', $bc->title, null);
939 $controlshtml = $this->block_controls($bc->controls);
941 $output = '';
942 if ($title || $controlshtml) {
943 $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'));
945 return $output;
949 * Produces the content area for a block
951 * @param block_contents $bc
952 * @return string
954 protected function block_content(block_contents $bc) {
955 $output = html_writer::start_tag('div', array('class' => 'content'));
956 if (!$bc->title && !$this->block_controls($bc->controls)) {
957 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
959 $output .= $bc->content;
960 $output .= $this->block_footer($bc);
961 $output .= html_writer::end_tag('div');
963 return $output;
967 * Produces the footer for a block
969 * @param block_contents $bc
970 * @return string
972 protected function block_footer(block_contents $bc) {
973 $output = '';
974 if ($bc->footer) {
975 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
977 return $output;
981 * Produces the annotation for a block
983 * @param block_contents $bc
984 * @return string
986 protected function block_annotation(block_contents $bc) {
987 $output = '';
988 if ($bc->annotation) {
989 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
991 return $output;
995 * Calls the JS require function to hide a block.
997 * @param block_contents $bc A block_contents object
999 protected function init_block_hider_js(block_contents $bc) {
1000 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1001 $config = new stdClass;
1002 $config->id = $bc->attributes['id'];
1003 $config->title = strip_tags($bc->title);
1004 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1005 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1006 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1008 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1009 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1014 * Render the contents of a block_list.
1016 * @param array $icons the icon for each item.
1017 * @param array $items the content of each item.
1018 * @return string HTML
1020 public function list_block_contents($icons, $items) {
1021 $row = 0;
1022 $lis = array();
1023 foreach ($items as $key => $string) {
1024 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1025 if (!empty($icons[$key])) { //test if the content has an assigned icon
1026 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1028 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1029 $item .= html_writer::end_tag('li');
1030 $lis[] = $item;
1031 $row = 1 - $row; // Flip even/odd.
1033 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1037 * Output all the blocks in a particular region.
1039 * @param string $region the name of a region on this page.
1040 * @return string the HTML to be output.
1042 public function blocks_for_region($region) {
1043 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1045 $output = '';
1046 foreach ($blockcontents as $bc) {
1047 if ($bc instanceof block_contents) {
1048 $output .= $this->block($bc, $region);
1049 } else if ($bc instanceof block_move_target) {
1050 $output .= $this->block_move_target($bc);
1051 } else {
1052 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1055 return $output;
1059 * Output a place where the block that is currently being moved can be dropped.
1061 * @param block_move_target $target with the necessary details.
1062 * @return string the HTML to be output.
1064 public function block_move_target($target) {
1065 return html_writer::tag('a', html_writer::tag('span', $target->text, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1069 * Renders a special html link with attached action
1071 * @param string|moodle_url $url
1072 * @param string $text HTML fragment
1073 * @param component_action $action
1074 * @param array $attributes associative array of html link attributes + disabled
1075 * @return string HTML fragment
1077 public function action_link($url, $text, component_action $action = null, array $attributes=null) {
1078 if (!($url instanceof moodle_url)) {
1079 $url = new moodle_url($url);
1081 $link = new action_link($url, $text, $action, $attributes);
1083 return $this->render($link);
1087 * Renders an action_link object.
1089 * The provided link is renderer and the HTML returned. At the same time the
1090 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1092 * @param action_link $link
1093 * @return string HTML fragment
1095 protected function render_action_link(action_link $link) {
1096 global $CFG;
1098 if ($link->text instanceof renderable) {
1099 $text = $this->render($link->text);
1100 } else {
1101 $text = $link->text;
1104 // A disabled link is rendered as formatted text
1105 if (!empty($link->attributes['disabled'])) {
1106 // do not use div here due to nesting restriction in xhtml strict
1107 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1110 $attributes = $link->attributes;
1111 unset($link->attributes['disabled']);
1112 $attributes['href'] = $link->url;
1114 if ($link->actions) {
1115 if (empty($attributes['id'])) {
1116 $id = html_writer::random_id('action_link');
1117 $attributes['id'] = $id;
1118 } else {
1119 $id = $attributes['id'];
1121 foreach ($link->actions as $action) {
1122 $this->add_action_handler($action, $id);
1126 return html_writer::tag('a', $text, $attributes);
1131 * Renders an action_icon.
1133 * This function uses the {@link core_renderer::action_link()} method for the
1134 * most part. What it does different is prepare the icon as HTML and use it
1135 * as the link text.
1137 * @param string|moodle_url $url A string URL or moodel_url
1138 * @param pix_icon $pixicon
1139 * @param component_action $action
1140 * @param array $attributes associative array of html link attributes + disabled
1141 * @param bool $linktext show title next to image in link
1142 * @return string HTML fragment
1144 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1145 if (!($url instanceof moodle_url)) {
1146 $url = new moodle_url($url);
1148 $attributes = (array)$attributes;
1150 if (empty($attributes['class'])) {
1151 // let ppl override the class via $options
1152 $attributes['class'] = 'action-icon';
1155 $icon = $this->render($pixicon);
1157 if ($linktext) {
1158 $text = $pixicon->attributes['alt'];
1159 } else {
1160 $text = '';
1163 return $this->action_link($url, $text.$icon, $action, $attributes);
1167 * Print a message along with button choices for Continue/Cancel
1169 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1171 * @param string $message The question to ask the user
1172 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1173 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1174 * @return string HTML fragment
1176 public function confirm($message, $continue, $cancel) {
1177 if ($continue instanceof single_button) {
1178 // ok
1179 } else if (is_string($continue)) {
1180 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1181 } else if ($continue instanceof moodle_url) {
1182 $continue = new single_button($continue, get_string('continue'), 'post');
1183 } else {
1184 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1187 if ($cancel instanceof single_button) {
1188 // ok
1189 } else if (is_string($cancel)) {
1190 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1191 } else if ($cancel instanceof moodle_url) {
1192 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1193 } else {
1194 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1197 $output = $this->box_start('generalbox', 'notice');
1198 $output .= html_writer::tag('p', $message);
1199 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1200 $output .= $this->box_end();
1201 return $output;
1205 * Returns a form with a single button.
1207 * @param string|moodle_url $url
1208 * @param string $label button text
1209 * @param string $method get or post submit method
1210 * @param array $options associative array {disabled, title, etc.}
1211 * @return string HTML fragment
1213 public function single_button($url, $label, $method='post', array $options=null) {
1214 if (!($url instanceof moodle_url)) {
1215 $url = new moodle_url($url);
1217 $button = new single_button($url, $label, $method);
1219 foreach ((array)$options as $key=>$value) {
1220 if (array_key_exists($key, $button)) {
1221 $button->$key = $value;
1225 return $this->render($button);
1229 * Renders a single button widget.
1231 * This will return HTML to display a form containing a single button.
1233 * @param single_button $button
1234 * @return string HTML fragment
1236 protected function render_single_button(single_button $button) {
1237 $attributes = array('type' => 'submit',
1238 'value' => $button->label,
1239 'disabled' => $button->disabled ? 'disabled' : null,
1240 'title' => $button->tooltip);
1242 if ($button->actions) {
1243 $id = html_writer::random_id('single_button');
1244 $attributes['id'] = $id;
1245 foreach ($button->actions as $action) {
1246 $this->add_action_handler($action, $id);
1250 // first the input element
1251 $output = html_writer::empty_tag('input', $attributes);
1253 // then hidden fields
1254 $params = $button->url->params();
1255 if ($button->method === 'post') {
1256 $params['sesskey'] = sesskey();
1258 foreach ($params as $var => $val) {
1259 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1262 // then div wrapper for xhtml strictness
1263 $output = html_writer::tag('div', $output);
1265 // now the form itself around it
1266 if ($button->method === 'get') {
1267 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1268 } else {
1269 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1271 if ($url === '') {
1272 $url = '#'; // there has to be always some action
1274 $attributes = array('method' => $button->method,
1275 'action' => $url,
1276 'id' => $button->formid);
1277 $output = html_writer::tag('form', $output, $attributes);
1279 // and finally one more wrapper with class
1280 return html_writer::tag('div', $output, array('class' => $button->class));
1284 * Returns a form with a single select widget.
1286 * @param moodle_url $url form action target, includes hidden fields
1287 * @param string $name name of selection field - the changing parameter in url
1288 * @param array $options list of options
1289 * @param string $selected selected element
1290 * @param array $nothing
1291 * @param string $formid
1292 * @return string HTML fragment
1294 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1295 if (!($url instanceof moodle_url)) {
1296 $url = new moodle_url($url);
1298 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1300 return $this->render($select);
1304 * Internal implementation of single_select rendering
1306 * @param single_select $select
1307 * @return string HTML fragment
1309 protected function render_single_select(single_select $select) {
1310 $select = clone($select);
1311 if (empty($select->formid)) {
1312 $select->formid = html_writer::random_id('single_select_f');
1315 $output = '';
1316 $params = $select->url->params();
1317 if ($select->method === 'post') {
1318 $params['sesskey'] = sesskey();
1320 foreach ($params as $name=>$value) {
1321 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1324 if (empty($select->attributes['id'])) {
1325 $select->attributes['id'] = html_writer::random_id('single_select');
1328 if ($select->disabled) {
1329 $select->attributes['disabled'] = 'disabled';
1332 if ($select->tooltip) {
1333 $select->attributes['title'] = $select->tooltip;
1336 if ($select->label) {
1337 $output .= html_writer::label($select->label, $select->attributes['id']);
1340 if ($select->helpicon instanceof help_icon) {
1341 $output .= $this->render($select->helpicon);
1342 } else if ($select->helpicon instanceof old_help_icon) {
1343 $output .= $this->render($select->helpicon);
1346 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1348 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1349 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('style'=>'inline'));
1351 $nothing = empty($select->nothing) ? false : key($select->nothing);
1352 $this->page->requires->js_init_call('M.util.init_select_autosubmit', array($select->formid, $select->attributes['id'], $nothing));
1354 // then div wrapper for xhtml strictness
1355 $output = html_writer::tag('div', $output);
1357 // now the form itself around it
1358 if ($select->method === 'get') {
1359 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1360 } else {
1361 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1363 $formattributes = array('method' => $select->method,
1364 'action' => $url,
1365 'id' => $select->formid);
1366 $output = html_writer::tag('form', $output, $formattributes);
1368 // and finally one more wrapper with class
1369 return html_writer::tag('div', $output, array('class' => $select->class));
1373 * Returns a form with a url select widget.
1375 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1376 * @param string $selected selected element
1377 * @param array $nothing
1378 * @param string $formid
1379 * @return string HTML fragment
1381 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1382 $select = new url_select($urls, $selected, $nothing, $formid);
1383 return $this->render($select);
1387 * Internal implementation of url_select rendering
1389 * @param url_select $select
1390 * @return string HTML fragment
1392 protected function render_url_select(url_select $select) {
1393 global $CFG;
1395 $select = clone($select);
1396 if (empty($select->formid)) {
1397 $select->formid = html_writer::random_id('url_select_f');
1400 if (empty($select->attributes['id'])) {
1401 $select->attributes['id'] = html_writer::random_id('url_select');
1404 if ($select->disabled) {
1405 $select->attributes['disabled'] = 'disabled';
1408 if ($select->tooltip) {
1409 $select->attributes['title'] = $select->tooltip;
1412 $output = '';
1414 if ($select->label) {
1415 $output .= html_writer::label($select->label, $select->attributes['id']);
1418 if ($select->helpicon instanceof help_icon) {
1419 $output .= $this->render($select->helpicon);
1420 } else if ($select->helpicon instanceof old_help_icon) {
1421 $output .= $this->render($select->helpicon);
1424 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1425 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1426 $urls = array();
1427 foreach ($select->urls as $k=>$v) {
1428 if (is_array($v)) {
1429 // optgroup structure
1430 foreach ($v as $optgrouptitle => $optgroupoptions) {
1431 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1432 if (empty($optionurl)) {
1433 $safeoptionurl = '';
1434 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1435 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1436 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1437 } else if (strpos($optionurl, '/') !== 0) {
1438 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1439 continue;
1440 } else {
1441 $safeoptionurl = $optionurl;
1443 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1446 } else {
1447 // plain list structure
1448 if (empty($k)) {
1449 // nothing selected option
1450 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1451 $k = str_replace($CFG->wwwroot, '', $k);
1452 } else if (strpos($k, '/') !== 0) {
1453 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1454 continue;
1456 $urls[$k] = $v;
1459 $selected = $select->selected;
1460 if (!empty($selected)) {
1461 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1462 $selected = str_replace($CFG->wwwroot, '', $selected);
1463 } else if (strpos($selected, '/') !== 0) {
1464 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1468 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1469 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1471 if (!$select->showbutton) {
1472 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1473 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('style'=>'inline'));
1474 $nothing = empty($select->nothing) ? false : key($select->nothing);
1475 $output .= $this->page->requires->js_init_call('M.util.init_url_select', array($select->formid, $select->attributes['id'], $nothing));
1476 } else {
1477 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1480 // then div wrapper for xhtml strictness
1481 $output = html_writer::tag('div', $output);
1483 // now the form itself around it
1484 $formattributes = array('method' => 'post',
1485 'action' => new moodle_url('/course/jumpto.php'),
1486 'id' => $select->formid);
1487 $output = html_writer::tag('form', $output, $formattributes);
1489 // and finally one more wrapper with class
1490 return html_writer::tag('div', $output, array('class' => $select->class));
1494 * Returns a string containing a link to the user documentation.
1495 * Also contains an icon by default. Shown to teachers and admin only.
1497 * @param string $path The page link after doc root and language, no leading slash.
1498 * @param string $text The text to be displayed for the link
1499 * @return string
1501 public function doc_link($path, $text = '') {
1502 global $CFG;
1504 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp'));
1506 $url = new moodle_url(get_docs_url($path));
1508 $attributes = array('href'=>$url);
1509 if (!empty($CFG->doctonewwindow)) {
1510 $attributes['id'] = $this->add_action_handler(new popup_action('click', $url));
1513 return html_writer::tag('a', $icon.$text, $attributes);
1517 * Return HTML for a pix_icon.
1519 * @param string $pix short pix name
1520 * @param string $alt mandatory alt attribute
1521 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1522 * @param array $attributes htm lattributes
1523 * @return string HTML fragment
1525 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1526 $icon = new pix_icon($pix, $alt, $component, $attributes);
1527 return $this->render($icon);
1531 * Renders a pix_icon widget and returns the HTML to display it.
1533 * @param pix_icon $icon
1534 * @return string HTML fragment
1536 protected function render_pix_icon(pix_icon $icon) {
1537 $attributes = $icon->attributes;
1538 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1539 return html_writer::empty_tag('img', $attributes);
1543 * Return HTML to display an emoticon icon.
1545 * @param pix_emoticon $emoticon
1546 * @return string HTML fragment
1548 protected function render_pix_emoticon(pix_emoticon $emoticon) {
1549 $attributes = $emoticon->attributes;
1550 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
1551 return html_writer::empty_tag('img', $attributes);
1555 * Produces the html that represents this rating in the UI
1557 * @param rating $rating the page object on which this rating will appear
1558 * @return string
1560 function render_rating(rating $rating) {
1561 global $CFG, $USER;
1563 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
1564 return null;//ratings are turned off
1567 $ratingmanager = new rating_manager();
1568 // Initialise the JavaScript so ratings can be done by AJAX.
1569 $ratingmanager->initialise_rating_javascript($this->page);
1571 $strrate = get_string("rate", "rating");
1572 $ratinghtml = ''; //the string we'll return
1574 // permissions check - can they view the aggregate?
1575 if ($rating->user_can_view_aggregate()) {
1577 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
1578 $aggregatestr = $rating->get_aggregate_string();
1580 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
1581 if ($rating->count > 0) {
1582 $countstr = "({$rating->count})";
1583 } else {
1584 $countstr = '-';
1586 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
1588 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
1589 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
1591 $nonpopuplink = $rating->get_view_ratings_url();
1592 $popuplink = $rating->get_view_ratings_url(true);
1594 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
1595 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
1596 } else {
1597 $ratinghtml .= $aggregatehtml;
1601 $formstart = null;
1602 // if the item doesn't belong to the current user, the user has permission to rate
1603 // and we're within the assessable period
1604 if ($rating->user_can_rate()) {
1606 $rateurl = $rating->get_rate_url();
1607 $inputs = $rateurl->params();
1609 //start the rating form
1610 $formattrs = array(
1611 'id' => "postrating{$rating->itemid}",
1612 'class' => 'postratingform',
1613 'method' => 'post',
1614 'action' => $rateurl->out_omit_querystring()
1616 $formstart = html_writer::start_tag('form', $formattrs);
1617 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
1619 // add the hidden inputs
1620 foreach ($inputs as $name => $value) {
1621 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
1622 $formstart .= html_writer::empty_tag('input', $attributes);
1625 if (empty($ratinghtml)) {
1626 $ratinghtml .= $strrate.': ';
1628 $ratinghtml = $formstart.$ratinghtml;
1630 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
1631 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
1632 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
1634 //output submit button
1635 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
1637 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
1638 $ratinghtml .= html_writer::empty_tag('input', $attributes);
1640 if (!$rating->settings->scale->isnumeric) {
1641 $ratinghtml .= $this->help_icon_scale($rating->settings->scale->courseid, $rating->settings->scale);
1643 $ratinghtml .= html_writer::end_tag('span');
1644 $ratinghtml .= html_writer::end_tag('div');
1645 $ratinghtml .= html_writer::end_tag('form');
1648 return $ratinghtml;
1652 * Centered heading with attached help button (same title text)
1653 * and optional icon attached.
1655 * @param string $text A heading text
1656 * @param string $helpidentifier The keyword that defines a help page
1657 * @param string $component component name
1658 * @param string|moodle_url $icon
1659 * @param string $iconalt icon alt text
1660 * @return string HTML fragment
1662 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '') {
1663 $image = '';
1664 if ($icon) {
1665 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
1668 $help = '';
1669 if ($helpidentifier) {
1670 $help = $this->help_icon($helpidentifier, $component);
1673 return $this->heading($image.$text.$help, 2, 'main help');
1677 * Returns HTML to display a help icon.
1679 * @deprecated since Moodle 2.0
1680 * @param string $helpidentifier The keyword that defines a help page
1681 * @param string $title A descriptive text for accessibility only
1682 * @param string $component component name
1683 * @param string|bool $linktext true means use $title as link text, string means link text value
1684 * @return string HTML fragment
1686 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
1687 debugging('The method old_help_icon() is deprecated, please fix the code and use help_icon() method instead', DEBUG_DEVELOPER);
1688 $icon = new old_help_icon($helpidentifier, $title, $component);
1689 if ($linktext === true) {
1690 $icon->linktext = $title;
1691 } else if (!empty($linktext)) {
1692 $icon->linktext = $linktext;
1694 return $this->render($icon);
1698 * Implementation of user image rendering.
1700 * @param old_help_icon $helpicon A help icon instance
1701 * @return string HTML fragment
1703 protected function render_old_help_icon(old_help_icon $helpicon) {
1704 global $CFG;
1706 // first get the help image icon
1707 $src = $this->pix_url('help');
1709 if (empty($helpicon->linktext)) {
1710 $alt = $helpicon->title;
1711 } else {
1712 $alt = get_string('helpwiththis');
1715 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1716 $output = html_writer::empty_tag('img', $attributes);
1718 // add the link text if given
1719 if (!empty($helpicon->linktext)) {
1720 // the spacing has to be done through CSS
1721 $output .= $helpicon->linktext;
1724 // now create the link around it - we need https on loginhttps pages
1725 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->helpidentifier, 'lang'=>current_language()));
1727 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1728 $title = get_string('helpprefix2', '', trim($helpicon->title, ". \t"));
1730 $attributes = array('href'=>$url, 'title'=>$title);
1731 $id = html_writer::random_id('helpicon');
1732 $attributes['id'] = $id;
1733 $output = html_writer::tag('a', $output, $attributes);
1735 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1737 // and finally span
1738 return html_writer::tag('span', $output, array('class' => 'helplink'));
1742 * Returns HTML to display a help icon.
1744 * @param string $identifier The keyword that defines a help page
1745 * @param string $component component name
1746 * @param string|bool $linktext true means use $title as link text, string means link text value
1747 * @return string HTML fragment
1749 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
1750 $icon = new help_icon($identifier, $component);
1751 $icon->diag_strings();
1752 if ($linktext === true) {
1753 $icon->linktext = get_string($icon->identifier, $icon->component);
1754 } else if (!empty($linktext)) {
1755 $icon->linktext = $linktext;
1757 return $this->render($icon);
1761 * Implementation of user image rendering.
1763 * @param help_icon $helpicon A help icon instance
1764 * @return string HTML fragment
1766 protected function render_help_icon(help_icon $helpicon) {
1767 global $CFG;
1769 // first get the help image icon
1770 $src = $this->pix_url('help');
1772 $title = get_string($helpicon->identifier, $helpicon->component);
1774 if (empty($helpicon->linktext)) {
1775 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
1776 } else {
1777 $alt = get_string('helpwiththis');
1780 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1781 $output = html_writer::empty_tag('img', $attributes);
1783 // add the link text if given
1784 if (!empty($helpicon->linktext)) {
1785 // the spacing has to be done through CSS
1786 $output .= $helpicon->linktext;
1789 // now create the link around it - we need https on loginhttps pages
1790 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
1792 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1793 $title = get_string('helpprefix2', '', trim($title, ". \t"));
1795 $attributes = array('href'=>$url, 'title'=>$title);
1796 $id = html_writer::random_id('helpicon');
1797 $attributes['id'] = $id;
1798 $output = html_writer::tag('a', $output, $attributes);
1800 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1802 // and finally span
1803 return html_writer::tag('span', $output, array('class' => 'helplink'));
1807 * Returns HTML to display a scale help icon.
1809 * @param int $courseid
1810 * @param stdClass $scale instance
1811 * @return string HTML fragment
1813 public function help_icon_scale($courseid, stdClass $scale) {
1814 global $CFG;
1816 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
1818 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
1820 $scaleid = abs($scale->id);
1822 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
1823 $action = new popup_action('click', $link, 'ratingscale');
1825 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
1829 * Creates and returns a spacer image with optional line break.
1831 * @param array $attributes Any HTML attributes to add to the spaced.
1832 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
1833 * laxy do it with CSS which is a much better solution.
1834 * @return string HTML fragment
1836 public function spacer(array $attributes = null, $br = false) {
1837 $attributes = (array)$attributes;
1838 if (empty($attributes['width'])) {
1839 $attributes['width'] = 1;
1841 if (empty($attributes['height'])) {
1842 $attributes['height'] = 1;
1844 $attributes['class'] = 'spacer';
1846 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
1848 if (!empty($br)) {
1849 $output .= '<br />';
1852 return $output;
1856 * Returns HTML to display the specified user's avatar.
1858 * User avatar may be obtained in two ways:
1859 * <pre>
1860 * // Option 1: (shortcut for simple cases, preferred way)
1861 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
1862 * $OUTPUT->user_picture($user, array('popup'=>true));
1864 * // Option 2:
1865 * $userpic = new user_picture($user);
1866 * // Set properties of $userpic
1867 * $userpic->popup = true;
1868 * $OUTPUT->render($userpic);
1869 * </pre>
1871 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
1872 * If any of these are missing, the database is queried. Avoid this
1873 * if at all possible, particularly for reports. It is very bad for performance.
1874 * @param array $options associative array with user picture options, used only if not a user_picture object,
1875 * options are:
1876 * - courseid=$this->page->course->id (course id of user profile in link)
1877 * - size=35 (size of image)
1878 * - link=true (make image clickable - the link leads to user profile)
1879 * - popup=false (open in popup)
1880 * - alttext=true (add image alt attribute)
1881 * - class = image class attribute (default 'userpicture')
1882 * @return string HTML fragment
1884 public function user_picture(stdClass $user, array $options = null) {
1885 $userpicture = new user_picture($user);
1886 foreach ((array)$options as $key=>$value) {
1887 if (array_key_exists($key, $userpicture)) {
1888 $userpicture->$key = $value;
1891 return $this->render($userpicture);
1895 * Internal implementation of user image rendering.
1897 * @param user_picture $userpicture
1898 * @return string
1900 protected function render_user_picture(user_picture $userpicture) {
1901 global $CFG, $DB;
1903 $user = $userpicture->user;
1905 if ($userpicture->alttext) {
1906 if (!empty($user->imagealt)) {
1907 $alt = $user->imagealt;
1908 } else {
1909 $alt = get_string('pictureof', '', fullname($user));
1911 } else {
1912 $alt = '';
1915 if (empty($userpicture->size)) {
1916 $size = 35;
1917 } else if ($userpicture->size === true or $userpicture->size == 1) {
1918 $size = 100;
1919 } else {
1920 $size = $userpicture->size;
1923 $class = $userpicture->class;
1925 if ($user->picture == 0) {
1926 $class .= ' defaultuserpic';
1929 $src = $userpicture->get_url($this->page, $this);
1931 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
1933 // get the image html output fisrt
1934 $output = html_writer::empty_tag('img', $attributes);;
1936 // then wrap it in link if needed
1937 if (!$userpicture->link) {
1938 return $output;
1941 if (empty($userpicture->courseid)) {
1942 $courseid = $this->page->course->id;
1943 } else {
1944 $courseid = $userpicture->courseid;
1947 if ($courseid == SITEID) {
1948 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
1949 } else {
1950 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
1953 $attributes = array('href'=>$url);
1955 if ($userpicture->popup) {
1956 $id = html_writer::random_id('userpicture');
1957 $attributes['id'] = $id;
1958 $this->add_action_handler(new popup_action('click', $url), $id);
1961 return html_writer::tag('a', $output, $attributes);
1965 * Internal implementation of file tree viewer items rendering.
1967 * @param array $dir
1968 * @return string
1970 public function htmllize_file_tree($dir) {
1971 if (empty($dir['subdirs']) and empty($dir['files'])) {
1972 return '';
1974 $result = '<ul>';
1975 foreach ($dir['subdirs'] as $subdir) {
1976 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
1978 foreach ($dir['files'] as $file) {
1979 $filename = $file->get_filename();
1980 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
1982 $result .= '</ul>';
1984 return $result;
1988 * Returns HTML to display the file picker
1990 * <pre>
1991 * $OUTPUT->file_picker($options);
1992 * </pre>
1994 * @param array $options associative array with file manager options
1995 * options are:
1996 * maxbytes=>-1,
1997 * itemid=>0,
1998 * client_id=>uniqid(),
1999 * acepted_types=>'*',
2000 * return_types=>FILE_INTERNAL,
2001 * context=>$PAGE->context
2002 * @return string HTML fragment
2004 public function file_picker($options) {
2005 $fp = new file_picker($options);
2006 return $this->render($fp);
2010 * Internal implementation of file picker rendering.
2012 * @param file_picker $fp
2013 * @return string
2015 public function render_file_picker(file_picker $fp) {
2016 global $CFG, $OUTPUT, $USER;
2017 $options = $fp->options;
2018 $client_id = $options->client_id;
2019 $strsaved = get_string('filesaved', 'repository');
2020 $straddfile = get_string('openpicker', 'repository');
2021 $strloading = get_string('loading', 'repository');
2022 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2023 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2025 $currentfile = $options->currentfile;
2026 if (empty($currentfile)) {
2027 $currentfile = get_string('nofilesattached', 'repository');
2029 if ($options->maxbytes) {
2030 $size = $options->maxbytes;
2031 } else {
2032 $size = get_max_upload_file_size();
2034 if ($size == -1) {
2035 $maxsize = '';
2036 } else {
2037 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2039 if ($options->buttonname) {
2040 $buttonname = ' name="' . $options->buttonname . '"';
2041 } else {
2042 $buttonname = '';
2044 $html = <<<EOD
2045 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2046 $icon_progress
2047 </div>
2048 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2049 <div>
2050 <input type="button" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2051 <span> $maxsize </span>
2052 </div>
2053 EOD;
2054 if ($options->env != 'url') {
2055 $html .= <<<EOD
2056 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist">
2057 $currentfile<span id="dndenabled-{$client_id}" style="display: none"> - $strdndenabled </span>
2058 </div>
2059 EOD;
2061 $html .= '</div>';
2062 return $html;
2066 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2068 * @param string $cmid the course_module id.
2069 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2070 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2072 public function update_module_button($cmid, $modulename) {
2073 global $CFG;
2074 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $cmid))) {
2075 $modulename = get_string('modulename', $modulename);
2076 $string = get_string('updatethis', '', $modulename);
2077 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2078 return $this->single_button($url, $string);
2079 } else {
2080 return '';
2085 * Returns HTML to display a "Turn editing on/off" button in a form.
2087 * @param moodle_url $url The URL + params to send through when clicking the button
2088 * @return string HTML the button
2090 public function edit_button(moodle_url $url) {
2092 $url->param('sesskey', sesskey());
2093 if ($this->page->user_is_editing()) {
2094 $url->param('edit', 'off');
2095 $editstring = get_string('turneditingoff');
2096 } else {
2097 $url->param('edit', 'on');
2098 $editstring = get_string('turneditingon');
2101 return $this->single_button($url, $editstring);
2105 * Returns HTML to display a simple button to close a window
2107 * @param string $text The lang string for the button's label (already output from get_string())
2108 * @return string html fragment
2110 public function close_window_button($text='') {
2111 if (empty($text)) {
2112 $text = get_string('closewindow');
2114 $button = new single_button(new moodle_url('#'), $text, 'get');
2115 $button->add_action(new component_action('click', 'close_window'));
2117 return $this->container($this->render($button), 'closewindow');
2121 * Output an error message. By default wraps the error message in <span class="error">.
2122 * If the error message is blank, nothing is output.
2124 * @param string $message the error message.
2125 * @return string the HTML to output.
2127 public function error_text($message) {
2128 if (empty($message)) {
2129 return '';
2131 return html_writer::tag('span', $message, array('class' => 'error'));
2135 * Do not call this function directly.
2137 * To terminate the current script with a fatal error, call the {@link print_error}
2138 * function, or throw an exception. Doing either of those things will then call this
2139 * function to display the error, before terminating the execution.
2141 * @param string $message The message to output
2142 * @param string $moreinfourl URL where more info can be found about the error
2143 * @param string $link Link for the Continue button
2144 * @param array $backtrace The execution backtrace
2145 * @param string $debuginfo Debugging information
2146 * @return string the HTML to output.
2148 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2149 global $CFG;
2151 $output = '';
2152 $obbuffer = '';
2154 if ($this->has_started()) {
2155 // we can not always recover properly here, we have problems with output buffering,
2156 // html tables, etc.
2157 $output .= $this->opencontainers->pop_all_but_last();
2159 } else {
2160 // It is really bad if library code throws exception when output buffering is on,
2161 // because the buffered text would be printed before our start of page.
2162 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2163 error_reporting(0); // disable notices from gzip compression, etc.
2164 while (ob_get_level() > 0) {
2165 $buff = ob_get_clean();
2166 if ($buff === false) {
2167 break;
2169 $obbuffer .= $buff;
2171 error_reporting($CFG->debug);
2173 // Header not yet printed
2174 if (isset($_SERVER['SERVER_PROTOCOL'])) {
2175 // server protocol should be always present, because this render
2176 // can not be used from command line or when outputting custom XML
2177 @header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
2179 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2180 $this->page->set_url('/'); // no url
2181 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2182 $this->page->set_title(get_string('error'));
2183 $this->page->set_heading($this->page->course->fullname);
2184 $output .= $this->header();
2187 $message = '<p class="errormessage">' . $message . '</p>'.
2188 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2189 get_string('moreinformation') . '</a></p>';
2190 if (empty($CFG->rolesactive)) {
2191 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2192 //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.
2194 $output .= $this->box($message, 'errorbox');
2196 if (debugging('', DEBUG_DEVELOPER)) {
2197 if (!empty($debuginfo)) {
2198 $debuginfo = s($debuginfo); // removes all nasty JS
2199 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2200 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2202 if (!empty($backtrace)) {
2203 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2205 if ($obbuffer !== '' ) {
2206 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2210 if (empty($CFG->rolesactive)) {
2211 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2212 } else if (!empty($link)) {
2213 $output .= $this->continue_button($link);
2216 $output .= $this->footer();
2218 // Padding to encourage IE to display our error page, rather than its own.
2219 $output .= str_repeat(' ', 512);
2221 return $output;
2225 * Output a notification (that is, a status message about something that has
2226 * just happened).
2228 * @param string $message the message to print out
2229 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2230 * @return string the HTML to output.
2232 public function notification($message, $classes = 'notifyproblem') {
2233 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2237 * Returns HTML to display a continue button that goes to a particular URL.
2239 * @param string|moodle_url $url The url the button goes to.
2240 * @return string the HTML to output.
2242 public function continue_button($url) {
2243 if (!($url instanceof moodle_url)) {
2244 $url = new moodle_url($url);
2246 $button = new single_button($url, get_string('continue'), 'get');
2247 $button->class = 'continuebutton';
2249 return $this->render($button);
2253 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2255 * @param int $totalcount The total number of entries available to be paged through
2256 * @param int $page The page you are currently viewing
2257 * @param int $perpage The number of entries that should be shown per page
2258 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2259 * @param string $pagevar name of page parameter that holds the page number
2260 * @return string the HTML to output.
2262 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2263 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2264 return $this->render($pb);
2268 * Internal implementation of paging bar rendering.
2270 * @param paging_bar $pagingbar
2271 * @return string
2273 protected function render_paging_bar(paging_bar $pagingbar) {
2274 $output = '';
2275 $pagingbar = clone($pagingbar);
2276 $pagingbar->prepare($this, $this->page, $this->target);
2278 if ($pagingbar->totalcount > $pagingbar->perpage) {
2279 $output .= get_string('page') . ':';
2281 if (!empty($pagingbar->previouslink)) {
2282 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
2285 if (!empty($pagingbar->firstlink)) {
2286 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
2289 foreach ($pagingbar->pagelinks as $link) {
2290 $output .= "&#160;&#160;$link";
2293 if (!empty($pagingbar->lastlink)) {
2294 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
2297 if (!empty($pagingbar->nextlink)) {
2298 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
2302 return html_writer::tag('div', $output, array('class' => 'paging'));
2306 * Output the place a skip link goes to.
2308 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2309 * @return string the HTML to output.
2311 public function skip_link_target($id = null) {
2312 return html_writer::tag('span', '', array('id' => $id));
2316 * Outputs a heading
2318 * @param string $text The text of the heading
2319 * @param int $level The level of importance of the heading. Defaulting to 2
2320 * @param string $classes A space-separated list of CSS classes
2321 * @param string $id An optional ID
2322 * @return string the HTML to output.
2324 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2325 $level = (integer) $level;
2326 if ($level < 1 or $level > 6) {
2327 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2329 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2333 * Outputs a box.
2335 * @param string $contents The contents of the box
2336 * @param string $classes A space-separated list of CSS classes
2337 * @param string $id An optional ID
2338 * @return string the HTML to output.
2340 public function box($contents, $classes = 'generalbox', $id = null) {
2341 return $this->box_start($classes, $id) . $contents . $this->box_end();
2345 * Outputs the opening section of a box.
2347 * @param string $classes A space-separated list of CSS classes
2348 * @param string $id An optional ID
2349 * @return string the HTML to output.
2351 public function box_start($classes = 'generalbox', $id = null) {
2352 $this->opencontainers->push('box', html_writer::end_tag('div'));
2353 return html_writer::start_tag('div', array('id' => $id,
2354 'class' => 'box ' . renderer_base::prepare_classes($classes)));
2358 * Outputs the closing section of a box.
2360 * @return string the HTML to output.
2362 public function box_end() {
2363 return $this->opencontainers->pop('box');
2367 * Outputs a container.
2369 * @param string $contents The contents of the box
2370 * @param string $classes A space-separated list of CSS classes
2371 * @param string $id An optional ID
2372 * @return string the HTML to output.
2374 public function container($contents, $classes = null, $id = null) {
2375 return $this->container_start($classes, $id) . $contents . $this->container_end();
2379 * Outputs the opening section of a container.
2381 * @param string $classes A space-separated list of CSS classes
2382 * @param string $id An optional ID
2383 * @return string the HTML to output.
2385 public function container_start($classes = null, $id = null) {
2386 $this->opencontainers->push('container', html_writer::end_tag('div'));
2387 return html_writer::start_tag('div', array('id' => $id,
2388 'class' => renderer_base::prepare_classes($classes)));
2392 * Outputs the closing section of a container.
2394 * @return string the HTML to output.
2396 public function container_end() {
2397 return $this->opencontainers->pop('container');
2401 * Make nested HTML lists out of the items
2403 * The resulting list will look something like this:
2405 * <pre>
2406 * <<ul>>
2407 * <<li>><div class='tree_item parent'>(item contents)</div>
2408 * <<ul>
2409 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2410 * <</ul>>
2411 * <</li>>
2412 * <</ul>>
2413 * </pre>
2415 * @param array $items
2416 * @param array $attrs html attributes passed to the top ofs the list
2417 * @return string HTML
2419 public function tree_block_contents($items, $attrs = array()) {
2420 // exit if empty, we don't want an empty ul element
2421 if (empty($items)) {
2422 return '';
2424 // array of nested li elements
2425 $lis = array();
2426 foreach ($items as $item) {
2427 // this applies to the li item which contains all child lists too
2428 $content = $item->content($this);
2429 $liclasses = array($item->get_css_type());
2430 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2431 $liclasses[] = 'collapsed';
2433 if ($item->isactive === true) {
2434 $liclasses[] = 'current_branch';
2436 $liattr = array('class'=>join(' ',$liclasses));
2437 // class attribute on the div item which only contains the item content
2438 $divclasses = array('tree_item');
2439 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2440 $divclasses[] = 'branch';
2441 } else {
2442 $divclasses[] = 'leaf';
2444 if (!empty($item->classes) && count($item->classes)>0) {
2445 $divclasses[] = join(' ', $item->classes);
2447 $divattr = array('class'=>join(' ', $divclasses));
2448 if (!empty($item->id)) {
2449 $divattr['id'] = $item->id;
2451 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2452 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2453 $content = html_writer::empty_tag('hr') . $content;
2455 $content = html_writer::tag('li', $content, $liattr);
2456 $lis[] = $content;
2458 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2462 * Return the navbar content so that it can be echoed out by the layout
2464 * @return string XHTML navbar
2466 public function navbar() {
2467 $items = $this->page->navbar->get_items();
2469 $htmlblocks = array();
2470 // Iterate the navarray and display each node
2471 $itemcount = count($items);
2472 $separator = get_separator();
2473 for ($i=0;$i < $itemcount;$i++) {
2474 $item = $items[$i];
2475 $item->hideicon = true;
2476 if ($i===0) {
2477 $content = html_writer::tag('li', $this->render($item));
2478 } else {
2479 $content = html_writer::tag('li', $separator.$this->render($item));
2481 $htmlblocks[] = $content;
2484 //accessibility: heading for navbar list (MDL-20446)
2485 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2486 $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks));
2487 // XHTML
2488 return $navbarcontent;
2492 * Renders a navigation node object.
2494 * @param navigation_node $item The navigation node to render.
2495 * @return string HTML fragment
2497 protected function render_navigation_node(navigation_node $item) {
2498 $content = $item->get_content();
2499 $title = $item->get_title();
2500 if ($item->icon instanceof renderable && !$item->hideicon) {
2501 $icon = $this->render($item->icon);
2502 $content = $icon.$content; // use CSS for spacing of icons
2504 if ($item->helpbutton !== null) {
2505 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2507 if ($content === '') {
2508 return '';
2510 if ($item->action instanceof action_link) {
2511 $link = $item->action;
2512 if ($item->hidden) {
2513 $link->add_class('dimmed');
2515 if (!empty($content)) {
2516 // Providing there is content we will use that for the link content.
2517 $link->text = $content;
2519 $content = $this->render($link);
2520 } else if ($item->action instanceof moodle_url) {
2521 $attributes = array();
2522 if ($title !== '') {
2523 $attributes['title'] = $title;
2525 if ($item->hidden) {
2526 $attributes['class'] = 'dimmed_text';
2528 $content = html_writer::link($item->action, $content, $attributes);
2530 } else if (is_string($item->action) || empty($item->action)) {
2531 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2532 if ($title !== '') {
2533 $attributes['title'] = $title;
2535 if ($item->hidden) {
2536 $attributes['class'] = 'dimmed_text';
2538 $content = html_writer::tag('span', $content, $attributes);
2540 return $content;
2544 * Accessibility: Right arrow-like character is
2545 * used in the breadcrumb trail, course navigation menu
2546 * (previous/next activity), calendar, and search forum block.
2547 * If the theme does not set characters, appropriate defaults
2548 * are set automatically. Please DO NOT
2549 * use &lt; &gt; &raquo; - these are confusing for blind users.
2551 * @return string
2553 public function rarrow() {
2554 return $this->page->theme->rarrow;
2558 * Accessibility: Right arrow-like character is
2559 * used in the breadcrumb trail, course navigation menu
2560 * (previous/next activity), calendar, and search forum block.
2561 * If the theme does not set characters, appropriate defaults
2562 * are set automatically. Please DO NOT
2563 * use &lt; &gt; &raquo; - these are confusing for blind users.
2565 * @return string
2567 public function larrow() {
2568 return $this->page->theme->larrow;
2572 * Returns the custom menu if one has been set
2574 * A custom menu can be configured by browsing to
2575 * Settings: Administration > Appearance > Themes > Theme settings
2576 * and then configuring the custommenu config setting as described.
2578 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
2579 * @return string
2581 public function custom_menu($custommenuitems = '') {
2582 global $CFG;
2583 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
2584 $custommenuitems = $CFG->custommenuitems;
2586 if (empty($custommenuitems)) {
2587 return '';
2589 $custommenu = new custom_menu($custommenuitems, current_language());
2590 return $this->render_custom_menu($custommenu);
2594 * Renders a custom menu object (located in outputcomponents.php)
2596 * The custom menu this method produces makes use of the YUI3 menunav widget
2597 * and requires very specific html elements and classes.
2599 * @staticvar int $menucount
2600 * @param custom_menu $menu
2601 * @return string
2603 protected function render_custom_menu(custom_menu $menu) {
2604 static $menucount = 0;
2605 // If the menu has no children return an empty string
2606 if (!$menu->has_children()) {
2607 return '';
2609 // Increment the menu count. This is used for ID's that get worked with
2610 // in JavaScript as is essential
2611 $menucount++;
2612 // Initialise this custom menu (the custom menu object is contained in javascript-static
2613 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
2614 $jscode = "(function(){{$jscode}})";
2615 $this->page->requires->yui_module('node-menunav', $jscode);
2616 // Build the root nodes as required by YUI
2617 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled'));
2618 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2619 $content .= html_writer::start_tag('ul');
2620 // Render each child
2621 foreach ($menu->get_children() as $item) {
2622 $content .= $this->render_custom_menu_item($item);
2624 // Close the open tags
2625 $content .= html_writer::end_tag('ul');
2626 $content .= html_writer::end_tag('div');
2627 $content .= html_writer::end_tag('div');
2628 // Return the custom menu
2629 return $content;
2633 * Renders a custom menu node as part of a submenu
2635 * The custom menu this method produces makes use of the YUI3 menunav widget
2636 * and requires very specific html elements and classes.
2638 * @see core:renderer::render_custom_menu()
2640 * @staticvar int $submenucount
2641 * @param custom_menu_item $menunode
2642 * @return string
2644 protected function render_custom_menu_item(custom_menu_item $menunode) {
2645 // Required to ensure we get unique trackable id's
2646 static $submenucount = 0;
2647 if ($menunode->has_children()) {
2648 // If the child has menus render it as a sub menu
2649 $submenucount++;
2650 $content = html_writer::start_tag('li');
2651 if ($menunode->get_url() !== null) {
2652 $url = $menunode->get_url();
2653 } else {
2654 $url = '#cm_submenu_'.$submenucount;
2656 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
2657 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
2658 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2659 $content .= html_writer::start_tag('ul');
2660 foreach ($menunode->get_children() as $menunode) {
2661 $content .= $this->render_custom_menu_item($menunode);
2663 $content .= html_writer::end_tag('ul');
2664 $content .= html_writer::end_tag('div');
2665 $content .= html_writer::end_tag('div');
2666 $content .= html_writer::end_tag('li');
2667 } else {
2668 // The node doesn't have children so produce a final menuitem
2669 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
2670 if ($menunode->get_url() !== null) {
2671 $url = $menunode->get_url();
2672 } else {
2673 $url = '#';
2675 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
2676 $content .= html_writer::end_tag('li');
2678 // Return the sub menu
2679 return $content;
2683 * Renders theme links for switching between default and other themes.
2685 * @return string
2687 protected function theme_switch_links() {
2689 $actualdevice = get_device_type();
2690 $currentdevice = $this->page->devicetypeinuse;
2691 $switched = ($actualdevice != $currentdevice);
2693 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
2694 // The user is using the a default device and hasn't switched so don't shown the switch
2695 // device links.
2696 return '';
2699 if ($switched) {
2700 $linktext = get_string('switchdevicerecommended');
2701 $devicetype = $actualdevice;
2702 } else {
2703 $linktext = get_string('switchdevicedefault');
2704 $devicetype = 'default';
2706 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
2708 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
2709 $content .= html_writer::link($linkurl, $linktext);
2710 $content .= html_writer::end_tag('div');
2712 return $content;
2717 * A renderer that generates output for command-line scripts.
2719 * The implementation of this renderer is probably incomplete.
2721 * @copyright 2009 Tim Hunt
2722 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2723 * @since Moodle 2.0
2724 * @package core
2725 * @category output
2727 class core_renderer_cli extends core_renderer {
2730 * Returns the page header.
2732 * @return string HTML fragment
2734 public function header() {
2735 return $this->page->heading . "\n";
2739 * Returns a template fragment representing a Heading.
2741 * @param string $text The text of the heading
2742 * @param int $level The level of importance of the heading
2743 * @param string $classes A space-separated list of CSS classes
2744 * @param string $id An optional ID
2745 * @return string A template fragment for a heading
2747 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2748 $text .= "\n";
2749 switch ($level) {
2750 case 1:
2751 return '=>' . $text;
2752 case 2:
2753 return '-->' . $text;
2754 default:
2755 return $text;
2760 * Returns a template fragment representing a fatal error.
2762 * @param string $message The message to output
2763 * @param string $moreinfourl URL where more info can be found about the error
2764 * @param string $link Link for the Continue button
2765 * @param array $backtrace The execution backtrace
2766 * @param string $debuginfo Debugging information
2767 * @return string A template fragment for a fatal error
2769 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2770 $output = "!!! $message !!!\n";
2772 if (debugging('', DEBUG_DEVELOPER)) {
2773 if (!empty($debuginfo)) {
2774 $output .= $this->notification($debuginfo, 'notifytiny');
2776 if (!empty($backtrace)) {
2777 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
2781 return $output;
2785 * Returns a template fragment representing a notification.
2787 * @param string $message The message to include
2788 * @param string $classes A space-separated list of CSS classes
2789 * @return string A template fragment for a notification
2791 public function notification($message, $classes = 'notifyproblem') {
2792 $message = clean_text($message);
2793 if ($classes === 'notifysuccess') {
2794 return "++ $message ++\n";
2796 return "!! $message !!\n";
2802 * A renderer that generates output for ajax scripts.
2804 * This renderer prevents accidental sends back only json
2805 * encoded error messages, all other output is ignored.
2807 * @copyright 2010 Petr Skoda
2808 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2809 * @since Moodle 2.0
2810 * @package core
2811 * @category output
2813 class core_renderer_ajax extends core_renderer {
2816 * Returns a template fragment representing a fatal error.
2818 * @param string $message The message to output
2819 * @param string $moreinfourl URL where more info can be found about the error
2820 * @param string $link Link for the Continue button
2821 * @param array $backtrace The execution backtrace
2822 * @param string $debuginfo Debugging information
2823 * @return string A template fragment for a fatal error
2825 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2826 global $CFG;
2828 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2830 $e = new stdClass();
2831 $e->error = $message;
2832 $e->stacktrace = NULL;
2833 $e->debuginfo = NULL;
2834 $e->reproductionlink = NULL;
2835 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
2836 $e->reproductionlink = $link;
2837 if (!empty($debuginfo)) {
2838 $e->debuginfo = $debuginfo;
2840 if (!empty($backtrace)) {
2841 $e->stacktrace = format_backtrace($backtrace, true);
2844 $this->header();
2845 return json_encode($e);
2849 * Used to display a notification.
2850 * For the AJAX notifications are discarded.
2852 * @param string $message
2853 * @param string $classes
2855 public function notification($message, $classes = 'notifyproblem') {}
2858 * Used to display a redirection message.
2859 * AJAX redirections should not occur and as such redirection messages
2860 * are discarded.
2862 * @param moodle_url|string $encodedurl
2863 * @param string $message
2864 * @param int $delay
2865 * @param bool $debugdisableredirect
2867 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
2870 * Prepares the start of an AJAX output.
2872 public function header() {
2873 // unfortunately YUI iframe upload does not support application/json
2874 if (!empty($_FILES)) {
2875 @header('Content-type: text/plain; charset=utf-8');
2876 } else {
2877 @header('Content-type: application/json; charset=utf-8');
2880 // Headers to make it not cacheable and json
2881 @header('Cache-Control: no-store, no-cache, must-revalidate');
2882 @header('Cache-Control: post-check=0, pre-check=0', false);
2883 @header('Pragma: no-cache');
2884 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2885 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2886 @header('Accept-Ranges: none');
2890 * There is no footer for an AJAX request, however we must override the
2891 * footer method to prevent the default footer.
2893 public function footer() {}
2896 * No need for headers in an AJAX request... this should never happen.
2897 * @param string $text
2898 * @param int $level
2899 * @param string $classes
2900 * @param string $id
2902 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
2907 * Renderer for media files.
2909 * Used in file resources, media filter, and any other places that need to
2910 * output embedded media.
2912 * @copyright 2011 The Open University
2913 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2915 class core_media_renderer extends plugin_renderer_base {
2916 /** @var array Array of available 'player' objects */
2917 private $players;
2918 /** @var string Regex pattern for links which may contain embeddable content */
2919 private $embeddablemarkers;
2922 * Constructor requires medialib.php.
2924 * This is needed in the constructor (not later) so that you can use the
2925 * constants and static functions that are defined in core_media class
2926 * before you call renderer functions.
2928 public function __construct() {
2929 global $CFG;
2930 require_once($CFG->libdir . '/medialib.php');
2934 * Obtains the list of core_media_player objects currently in use to render
2935 * items.
2937 * The list is in rank order (highest first) and does not include players
2938 * which are disabled.
2940 * @return array Array of core_media_player objects in rank order
2942 protected function get_players() {
2943 global $CFG;
2945 // Save time by only building the list once.
2946 if (!$this->players) {
2947 // Get raw list of players.
2948 $players = $this->get_players_raw();
2950 // Chuck all the ones that are disabled.
2951 foreach ($players as $key => $player) {
2952 if (!$player->is_enabled()) {
2953 unset($players[$key]);
2957 // Sort in rank order (highest first).
2958 usort($players, array('core_media_player', 'compare_by_rank'));
2959 $this->players = $players;
2961 return $this->players;
2965 * Obtains a raw list of player objects that includes objects regardless
2966 * of whether they are disabled or not, and without sorting.
2968 * You can override this in a subclass if you need to add additional
2969 * players.
2971 * The return array is be indexed by player name to make it easier to
2972 * remove players in a subclass.
2974 * @return array $players Array of core_media_player objects in any order
2976 protected function get_players_raw() {
2977 return array(
2978 'vimeo' => new core_media_player_vimeo(),
2979 'youtube' => new core_media_player_youtube(),
2980 'youtube_playlist' => new core_media_player_youtube_playlist(),
2981 'html5video' => new core_media_player_html5video(),
2982 'html5audio' => new core_media_player_html5audio(),
2983 'mp3' => new core_media_player_mp3(),
2984 'flv' => new core_media_player_flv(),
2985 'wmp' => new core_media_player_wmp(),
2986 'qt' => new core_media_player_qt(),
2987 'rm' => new core_media_player_rm(),
2988 'swf' => new core_media_player_swf(),
2989 'link' => new core_media_player_link(),
2994 * Renders a media file (audio or video) using suitable embedded player.
2996 * See embed_alternatives function for full description of parameters.
2997 * This function calls through to that one.
2999 * When using this function you can also specify width and height in the
3000 * URL by including ?d=100x100 at the end. If specified in the URL, this
3001 * will override the $width and $height parameters.
3003 * @param moodle_url $url Full URL of media file
3004 * @param string $name Optional user-readable name to display in download link
3005 * @param int $width Width in pixels (optional)
3006 * @param int $height Height in pixels (optional)
3007 * @param array $options Array of key/value pairs
3008 * @return string HTML content of embed
3010 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
3011 $options = array()) {
3013 // Get width and height from URL if specified (overrides parameters in
3014 // function call).
3015 $rawurl = $url->out(false);
3016 if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
3017 $width = $matches[1];
3018 $height = $matches[2];
3019 $url = new moodle_url(str_replace($matches[0], '', $rawurl));
3022 // Defer to array version of function.
3023 return $this->embed_alternatives(array($url), $name, $width, $height, $options);
3027 * Renders media files (audio or video) using suitable embedded player.
3028 * The list of URLs should be alternative versions of the same content in
3029 * multiple formats. If there is only one format it should have a single
3030 * entry.
3032 * If the media files are not in a supported format, this will give students
3033 * a download link to each format. The download link uses the filename
3034 * unless you supply the optional name parameter.
3036 * Width and height are optional. If specified, these are suggested sizes
3037 * and should be the exact values supplied by the user, if they come from
3038 * user input. These will be treated as relating to the size of the video
3039 * content, not including any player control bar.
3041 * For audio files, height will be ignored. For video files, a few formats
3042 * work if you specify only width, but in general if you specify width
3043 * you must specify height as well.
3045 * The $options array is passed through to the core_media_player classes
3046 * that render the object tag. The keys can contain values from
3047 * core_media::OPTION_xx.
3049 * @param array $alternatives Array of moodle_url to media files
3050 * @param string $name Optional user-readable name to display in download link
3051 * @param int $width Width in pixels (optional)
3052 * @param int $height Height in pixels (optional)
3053 * @param array $options Array of key/value pairs
3054 * @return string HTML content of embed
3056 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
3057 $options = array()) {
3059 // Get list of player plugins (will also require the library).
3060 $players = $this->get_players();
3062 // Set up initial text which will be replaced by first player that
3063 // supports any of the formats.
3064 $out = core_media_player::PLACEHOLDER;
3066 // Loop through all players that support any of these URLs.
3067 foreach ($players as $player) {
3068 // Option: When no other player matched, don't do the default link player.
3069 if (!empty($options[core_media::OPTION_FALLBACK_TO_BLANK]) &&
3070 $player->get_rank() === 0 && $out === core_media_player::PLACEHOLDER) {
3071 continue;
3074 $supported = $player->list_supported_urls($alternatives, $options);
3075 if ($supported) {
3076 // Embed.
3077 $text = $player->embed($supported, $name, $width, $height, $options);
3079 // Put this in place of the 'fallback' slot in the previous text.
3080 $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
3084 // Remove 'fallback' slot from final version and return it.
3085 $out = str_replace(core_media_player::PLACEHOLDER, '', $out);
3086 if (!empty($options[core_media::OPTION_BLOCK]) && $out !== '') {
3087 $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
3089 return $out;
3093 * Checks whether a file can be embedded. If this returns true you will get
3094 * an embedded player; if this returns false, you will just get a download
3095 * link.
3097 * This is a wrapper for can_embed_urls.
3099 * @param moodle_url $url URL of media file
3100 * @param array $options Options (same as when embedding)
3101 * @return bool True if file can be embedded
3103 public function can_embed_url(moodle_url $url, $options = array()) {
3104 return $this->can_embed_urls(array($url), $options);
3108 * Checks whether a file can be embedded. If this returns true you will get
3109 * an embedded player; if this returns false, you will just get a download
3110 * link.
3112 * @param array $urls URL of media file and any alternatives (moodle_url)
3113 * @param array $options Options (same as when embedding)
3114 * @return bool True if file can be embedded
3116 public function can_embed_urls(array $urls, $options = array()) {
3117 // Check all players to see if any of them support it.
3118 foreach ($this->get_players() as $player) {
3119 // Link player (always last on list) doesn't count!
3120 if ($player->get_rank() <= 0) {
3121 break;
3123 // First player that supports it, return true.
3124 if ($player->list_supported_urls($urls, $options)) {
3125 return true;
3128 return false;
3132 * Obtains a list of markers that can be used in a regular expression when
3133 * searching for URLs that can be embedded by any player type.
3135 * This string is used to improve peformance of regex matching by ensuring
3136 * that the (presumably C) regex code can do a quick keyword check on the
3137 * URL part of a link to see if it matches one of these, rather than having
3138 * to go into PHP code for every single link to see if it can be embedded.
3140 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
3142 public function get_embeddable_markers() {
3143 if (empty($this->embeddablemarkers)) {
3144 $markers = '';
3145 foreach ($this->get_players() as $player) {
3146 foreach ($player->get_embeddable_markers() as $marker) {
3147 if ($markers !== '') {
3148 $markers .= '|';
3150 $markers .= preg_quote($marker);
3153 $this->embeddablemarkers = $markers;
3155 return $this->embeddablemarkers;