Merge branch 'MDL-37781-workshop-schedule_23' of git://github.com/mudrd8mz/moodle...
[moodle.git] / lib / outputrenderers.php
blobbc89a754f8d7464f37efba460a8dd021ad868333
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
21 * for an overview.
23 * Included in this file are the primary renderer classes:
24 * - renderer_base: The renderer outline class that all renderers
25 * should inherit from.
26 * - core_renderer: The standard HTML renderer.
27 * - core_renderer_cli: An adaption of the standard renderer for CLI scripts.
28 * - core_renderer_ajax: An adaption of the standard renderer for AJAX scripts.
29 * - plugin_renderer_base: A renderer class that should be extended by all
30 * plugin renderers.
32 * @package core
33 * @category output
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') || die();
40 /**
41 * Simple base class for Moodle renderers.
43 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
45 * Also has methods to facilitate generating HTML output.
47 * @copyright 2009 Tim Hunt
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 * @since Moodle 2.0
50 * @package core
51 * @category output
53 class renderer_base {
54 /**
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
59 /**
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
62 protected $page;
64 /**
65 * @var string The requested rendering target.
67 protected $target;
69 /**
70 * Constructor
72 * The constructor takes two arguments. The first is the page that the renderer
73 * has been created to assist with, and the second is the target.
74 * The target is an additional identifier that can be used to load different
75 * renderers for different options.
77 * @param moodle_page $page the page we are doing output for.
78 * @param string $target one of rendering target constants
80 public function __construct(moodle_page $page, $target) {
81 $this->opencontainers = $page->opencontainers;
82 $this->page = $page;
83 $this->target = $target;
86 /**
87 * Returns rendered widget.
89 * The provided widget needs to be an object that extends the renderable
90 * interface.
91 * If will then be rendered by a method based upon the classname for the widget.
92 * For instance a widget of class `crazywidget` will be rendered by a protected
93 * render_crazywidget method of this renderer.
95 * @param renderable $widget instance with renderable interface
96 * @return string
98 public function render(renderable $widget) {
99 $rendermethod = 'render_'.get_class($widget);
100 if (method_exists($this, $rendermethod)) {
101 return $this->$rendermethod($widget);
103 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
107 * Adds a JS action for the element with the provided id.
109 * This method adds a JS event for the provided component action to the page
110 * and then returns the id that the event has been attached to.
111 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
113 * @param component_action $action
114 * @param string $id
115 * @return string id of element, either original submitted or random new if not supplied
117 public function add_action_handler(component_action $action, $id = null) {
118 if (!$id) {
119 $id = html_writer::random_id($action->event);
121 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
122 return $id;
126 * Returns true is output has already started, and false if not.
128 * @return boolean true if the header has been printed.
130 public function has_started() {
131 return $this->page->state >= moodle_page::STATE_IN_BODY;
135 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
137 * @param mixed $classes Space-separated string or array of classes
138 * @return string HTML class attribute value
140 public static function prepare_classes($classes) {
141 if (is_array($classes)) {
142 return implode(' ', array_unique($classes));
144 return $classes;
148 * Return the moodle_url for an image.
150 * The exact image location and extension is determined
151 * automatically by searching for gif|png|jpg|jpeg, please
152 * note there can not be diferent images with the different
153 * extension. The imagename is for historical reasons
154 * a relative path name, it may be changed later for core
155 * images. It is recommended to not use subdirectories
156 * in plugin and theme pix directories.
158 * There are three types of images:
159 * 1/ theme images - stored in theme/mytheme/pix/,
160 * use component 'theme'
161 * 2/ core images - stored in /pix/,
162 * overridden via theme/mytheme/pix_core/
163 * 3/ plugin images - stored in mod/mymodule/pix,
164 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
165 * example: pix_url('comment', 'mod_glossary')
167 * @param string $imagename the pathname of the image
168 * @param string $component full plugin name (aka component) or 'theme'
169 * @return moodle_url
171 public function pix_url($imagename, $component = 'moodle') {
172 return $this->page->theme->pix_url($imagename, $component);
178 * Basis for all plugin renderers.
180 * @copyright Petr Skoda (skodak)
181 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
182 * @since Moodle 2.0
183 * @package core
184 * @category output
186 class plugin_renderer_base extends renderer_base {
189 * @var renderer_base|core_renderer A reference to the current renderer.
190 * The renderer provided here will be determined by the page but will in 90%
191 * of cases by the {@link core_renderer}
193 protected $output;
196 * Constructor method, calls the parent constructor
198 * @param moodle_page $page
199 * @param string $target one of rendering target constants
201 public function __construct(moodle_page $page, $target) {
202 $this->output = $page->get_renderer('core', null, $target);
203 parent::__construct($page, $target);
207 * Renders the provided widget and returns the HTML to display it.
209 * @param renderable $widget instance with renderable interface
210 * @return string
212 public function render(renderable $widget) {
213 $rendermethod = 'render_'.get_class($widget);
214 if (method_exists($this, $rendermethod)) {
215 return $this->$rendermethod($widget);
217 // pass to core renderer if method not found here
218 return $this->output->render($widget);
222 * Magic method used to pass calls otherwise meant for the standard renderer
223 * to it to ensure we don't go causing unnecessary grief.
225 * @param string $method
226 * @param array $arguments
227 * @return mixed
229 public function __call($method, $arguments) {
230 if (method_exists('renderer_base', $method)) {
231 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
233 if (method_exists($this->output, $method)) {
234 return call_user_func_array(array($this->output, $method), $arguments);
235 } else {
236 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
243 * The standard implementation of the core_renderer interface.
245 * @copyright 2009 Tim Hunt
246 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
247 * @since Moodle 2.0
248 * @package core
249 * @category output
251 class core_renderer extends renderer_base {
253 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
254 * in layout files instead.
255 * @deprecated
256 * @var string used in {@link core_renderer::header()}.
258 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
261 * @var string Used to pass information from {@link core_renderer::doctype()} to
262 * {@link core_renderer::standard_head_html()}.
264 protected $contenttype;
267 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
268 * with {@link core_renderer::header()}.
270 protected $metarefreshtag = '';
273 * @var string Unique token for the closing HTML
275 protected $unique_end_html_token;
278 * @var string Unique token for performance information
280 protected $unique_performance_info_token;
283 * @var string Unique token for the main content.
285 protected $unique_main_content_token;
288 * Constructor
290 * @param moodle_page $page the page we are doing output for.
291 * @param string $target one of rendering target constants
293 public function __construct(moodle_page $page, $target) {
294 $this->opencontainers = $page->opencontainers;
295 $this->page = $page;
296 $this->target = $target;
298 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
299 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
300 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
304 * Get the DOCTYPE declaration that should be used with this page. Designed to
305 * be called in theme layout.php files.
307 * @return string the DOCTYPE declaration (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 // Set up help link popups for all links with the helplinkpopup class
376 $this->page->requires->js_init_call('M.util.help_popups.setup');
378 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
380 $focus = $this->page->focuscontrol;
381 if (!empty($focus)) {
382 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
383 // This is a horrifically bad way to handle focus but it is passed in
384 // through messy formslib::moodleform
385 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
386 } else if (strpos($focus, '.')!==false) {
387 // Old style of focus, bad way to do it
388 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);
389 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
390 } else {
391 // Focus element with given id
392 $this->page->requires->js_function_call('focuscontrol', array($focus));
396 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
397 // any other custom CSS can not be overridden via themes and is highly discouraged
398 $urls = $this->page->theme->css_urls($this->page);
399 foreach ($urls as $url) {
400 $this->page->requires->css_theme($url);
403 // Get the theme javascript head and footer
404 $jsurl = $this->page->theme->javascript_url(true);
405 $this->page->requires->js($jsurl, true);
406 $jsurl = $this->page->theme->javascript_url(false);
407 $this->page->requires->js($jsurl);
409 // Get any HTML from the page_requirements_manager.
410 $output .= $this->page->requires->get_head_code($this->page, $this);
412 // List alternate versions.
413 foreach ($this->page->alternateversions as $type => $alt) {
414 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
415 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
418 if (!empty($CFG->additionalhtmlhead)) {
419 $output .= "\n".$CFG->additionalhtmlhead;
422 return $output;
426 * The standard tags (typically skip links) that should be output just inside
427 * the start of the <body> tag. Designed to be called in theme layout.php files.
429 * @return string HTML fragment.
431 public function standard_top_of_body_html() {
432 global $CFG;
433 $output = $this->page->requires->get_top_of_body_code();
434 if (!empty($CFG->additionalhtmltopofbody)) {
435 $output .= "\n".$CFG->additionalhtmltopofbody;
437 return $output;
441 * The standard tags (typically performance information and validation links,
442 * if we are in developer debug mode) that should be output in the footer area
443 * of the page. Designed to be called in theme layout.php files.
445 * @return string HTML fragment.
447 public function standard_footer_html() {
448 global $CFG, $SCRIPT;
450 // This function is normally called from a layout.php file in {@link core_renderer::header()}
451 // but some of the content won't be known until later, so we return a placeholder
452 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
453 $output = $this->unique_performance_info_token;
454 if ($this->page->devicetypeinuse == 'legacy') {
455 // The legacy theme is in use print the notification
456 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
459 // Get links to switch device types (only shown for users not on a default device)
460 $output .= $this->theme_switch_links();
462 if (!empty($CFG->debugpageinfo)) {
463 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
465 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { // Only in developer mode
466 // Add link to profiling report if necessary
467 if (function_exists('profiling_is_running') && profiling_is_running()) {
468 $txt = get_string('profiledscript', 'admin');
469 $title = get_string('profiledscriptview', 'admin');
470 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
471 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
472 $output .= '<div class="profilingfooter">' . $link . '</div>';
474 $output .= '<div class="purgecaches"><a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/purgecaches.php?confirm=1&amp;sesskey='.sesskey().'">'.get_string('purgecaches', 'admin').'</a></div>';
476 if (!empty($CFG->debugvalidators)) {
477 // 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
478 $output .= '<div class="validators"><ul>
479 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
480 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
481 <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>
482 </ul></div>';
484 if (!empty($CFG->additionalhtmlfooter)) {
485 $output .= "\n".$CFG->additionalhtmlfooter;
487 return $output;
491 * Returns standard main content placeholder.
492 * Designed to be called in theme layout.php files.
494 * @return string HTML fragment.
496 public function main_content() {
497 return $this->unique_main_content_token;
501 * The standard tags (typically script tags that are not needed earlier) that
502 * should be output after everything else, . Designed to be called in theme layout.php files.
504 * @return string HTML fragment.
506 public function standard_end_of_body_html() {
507 // This function is normally called from a layout.php file in {@link core_renderer::header()}
508 // but some of the content won't be known until later, so we return a placeholder
509 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
510 return $this->unique_end_html_token;
514 * Return the standard string that says whether you are logged in (and switched
515 * roles/logged in as another user).
517 * @return string HTML fragment.
519 public function login_info() {
520 global $USER, $CFG, $DB, $SESSION;
522 if (during_initial_install()) {
523 return '';
526 $loginpage = ((string)$this->page->url === get_login_url());
527 $course = $this->page->course;
529 if (session_is_loggedinas()) {
530 $realuser = session_get_realuser();
531 $fullname = fullname($realuser, true);
532 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\">$fullname</a>] ";
533 } else {
534 $realuserinfo = '';
537 $loginurl = get_login_url();
539 if (empty($course->id)) {
540 // $course->id is not defined during installation
541 return '';
542 } else if (isloggedin()) {
543 $context = get_context_instance(CONTEXT_COURSE, $course->id);
545 $fullname = fullname($USER, true);
546 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
547 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\">$fullname</a>";
548 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
549 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
551 if (isguestuser()) {
552 $loggedinas = $realuserinfo.get_string('loggedinasguest');
553 if (!$loginpage) {
554 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
556 } else if (is_role_switched($course->id)) { // Has switched roles
557 $rolename = '';
558 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
559 $rolename = ': '.format_string($role->name);
561 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
562 " (<a href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
563 } else {
564 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
565 " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
567 } else {
568 $loggedinas = get_string('loggedinnot', 'moodle');
569 if (!$loginpage) {
570 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
574 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
576 if (isset($SESSION->justloggedin)) {
577 unset($SESSION->justloggedin);
578 if (!empty($CFG->displayloginfailures)) {
579 if (!isguestuser()) {
580 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
581 $loggedinas .= '&nbsp;<div class="loginfailures">';
582 if (empty($count->accounts)) {
583 $loggedinas .= get_string('failedloginattempts', '', $count);
584 } else {
585 $loggedinas .= get_string('failedloginattemptsall', '', $count);
587 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', get_context_instance(CONTEXT_SYSTEM))) {
588 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/report/log/index.php'.
589 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
591 $loggedinas .= '</div>';
597 return $loggedinas;
601 * Return the 'back' link that normally appears in the footer.
603 * @return string HTML fragment.
605 public function home_link() {
606 global $CFG, $SITE;
608 if ($this->page->pagetype == 'site-index') {
609 // Special case for site home page - please do not remove
610 return '<div class="sitelink">' .
611 '<a title="Moodle" href="http://moodle.org/">' .
612 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
614 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
615 // Special case for during install/upgrade.
616 return '<div class="sitelink">'.
617 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
618 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
620 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
621 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
622 get_string('home') . '</a></div>';
624 } else {
625 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
626 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
631 * Redirects the user by any means possible given the current state
633 * This function should not be called directly, it should always be called using
634 * the redirect function in lib/weblib.php
636 * The redirect function should really only be called before page output has started
637 * however it will allow itself to be called during the state STATE_IN_BODY
639 * @param string $encodedurl The URL to send to encoded if required
640 * @param string $message The message to display to the user if any
641 * @param int $delay The delay before redirecting a user, if $message has been
642 * set this is a requirement and defaults to 3, set to 0 no delay
643 * @param boolean $debugdisableredirect this redirect has been disabled for
644 * debugging purposes. Display a message that explains, and don't
645 * trigger the redirect.
646 * @return string The HTML to display to the user before dying, may contain
647 * meta refresh, javascript refresh, and may have set header redirects
649 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
650 global $CFG;
651 $url = str_replace('&amp;', '&', $encodedurl);
653 switch ($this->page->state) {
654 case moodle_page::STATE_BEFORE_HEADER :
655 // No output yet it is safe to delivery the full arsenal of redirect methods
656 if (!$debugdisableredirect) {
657 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
658 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
659 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
661 $output = $this->header();
662 break;
663 case moodle_page::STATE_PRINTING_HEADER :
664 // We should hopefully never get here
665 throw new coding_exception('You cannot redirect while printing the page header');
666 break;
667 case moodle_page::STATE_IN_BODY :
668 // We really shouldn't be here but we can deal with this
669 debugging("You should really redirect before you start page output");
670 if (!$debugdisableredirect) {
671 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
673 $output = $this->opencontainers->pop_all_but_last();
674 break;
675 case moodle_page::STATE_DONE :
676 // Too late to be calling redirect now
677 throw new coding_exception('You cannot redirect after the entire page has been generated');
678 break;
680 $output .= $this->notification($message, 'redirectmessage');
681 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
682 if ($debugdisableredirect) {
683 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
685 $output .= $this->footer();
686 return $output;
690 * Start output by sending the HTTP headers, and printing the HTML <head>
691 * and the start of the <body>.
693 * To control what is printed, you should set properties on $PAGE. If you
694 * are familiar with the old {@link print_header()} function from Moodle 1.9
695 * you will find that there are properties on $PAGE that correspond to most
696 * of the old parameters to could be passed to print_header.
698 * Not that, in due course, the remaining $navigation, $menu parameters here
699 * will be replaced by more properties of $PAGE, but that is still to do.
701 * @return string HTML that you must output this, preferably immediately.
703 public function header() {
704 global $USER, $CFG;
706 if (session_is_loggedinas()) {
707 $this->page->add_body_class('userloggedinas');
710 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
712 // Find the appropriate page layout file, based on $this->page->pagelayout.
713 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
714 // Render the layout using the layout file.
715 $rendered = $this->render_page_layout($layoutfile);
717 // Slice the rendered output into header and footer.
718 $cutpos = strpos($rendered, $this->unique_main_content_token);
719 if ($cutpos === false) {
720 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
721 $token = self::MAIN_CONTENT_TOKEN;
722 } else {
723 $token = $this->unique_main_content_token;
726 if ($cutpos === false) {
727 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.');
729 $header = substr($rendered, 0, $cutpos);
730 $footer = substr($rendered, $cutpos + strlen($token));
732 if (empty($this->contenttype)) {
733 debugging('The page layout file did not call $OUTPUT->doctype()');
734 $header = $this->doctype() . $header;
737 send_headers($this->contenttype, $this->page->cacheable);
739 $this->opencontainers->push('header/footer', $footer);
740 $this->page->set_state(moodle_page::STATE_IN_BODY);
742 return $header . $this->skip_link_target('maincontent');
746 * Renders and outputs the page layout file.
748 * This is done by preparing the normal globals available to a script, and
749 * then including the layout file provided by the current theme for the
750 * requested layout.
752 * @param string $layoutfile The name of the layout file
753 * @return string HTML code
755 protected function render_page_layout($layoutfile) {
756 global $CFG, $SITE, $USER;
757 // The next lines are a bit tricky. The point is, here we are in a method
758 // of a renderer class, and this object may, or may not, be the same as
759 // the global $OUTPUT object. When rendering the page layout file, we want to use
760 // this object. However, people writing Moodle code expect the current
761 // renderer to be called $OUTPUT, not $this, so define a variable called
762 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
763 $OUTPUT = $this;
764 $PAGE = $this->page;
765 $COURSE = $this->page->course;
767 ob_start();
768 include($layoutfile);
769 $rendered = ob_get_contents();
770 ob_end_clean();
771 return $rendered;
775 * Outputs the page's footer
777 * @return string HTML fragment
779 public function footer() {
780 global $CFG, $DB;
782 $output = $this->container_end_all(true);
784 $footer = $this->opencontainers->pop('header/footer');
786 if (debugging() and $DB and $DB->is_transaction_started()) {
787 // TODO: MDL-20625 print warning - transaction will be rolled back
790 // Provide some performance info if required
791 $performanceinfo = '';
792 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
793 $perf = get_performance_info();
794 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
795 error_log("PERF: " . $perf['txt']);
797 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
798 $performanceinfo = $perf['html'];
801 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
803 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
805 $this->page->set_state(moodle_page::STATE_DONE);
807 return $output . $footer;
811 * Close all but the last open container. This is useful in places like error
812 * handling, where you want to close all the open containers (apart from <body>)
813 * before outputting the error message.
815 * @param bool $shouldbenone assert that the stack should be empty now - causes a
816 * developer debug warning if it isn't.
817 * @return string the HTML required to close any open containers inside <body>.
819 public function container_end_all($shouldbenone = false) {
820 return $this->opencontainers->pop_all_but_last($shouldbenone);
824 * Returns lang menu or '', this method also checks forcing of languages in courses.
826 * @return string The lang menu HTML or empty string
828 public function lang_menu() {
829 global $CFG;
831 if (empty($CFG->langmenu)) {
832 return '';
835 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
836 // do not show lang menu if language forced
837 return '';
840 $currlang = current_language();
841 $langs = get_string_manager()->get_list_of_translations();
843 if (count($langs) < 2) {
844 return '';
847 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
848 $s->label = get_accesshide(get_string('language'));
849 $s->class = 'langmenu';
850 return $this->render($s);
854 * Output the row of editing icons for a block, as defined by the controls array.
856 * @param array $controls an array like {@link block_contents::$controls}.
857 * @return string HTML fragment.
859 public function block_controls($controls) {
860 if (empty($controls)) {
861 return '';
863 $controlshtml = array();
864 foreach ($controls as $control) {
865 $controlshtml[] = html_writer::tag('a',
866 html_writer::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
867 array('class' => 'icon ' . $control['class'],'title' => $control['caption'], 'href' => $control['url']));
869 return html_writer::tag('div', implode('', $controlshtml), array('class' => 'commands'));
873 * Prints a nice side block with an optional header.
875 * The content is described
876 * by a {@link core_renderer::block_contents} object.
878 * <div id="inst{$instanceid}" class="block_{$blockname} block">
879 * <div class="header"></div>
880 * <div class="content">
881 * ...CONTENT...
882 * <div class="footer">
883 * </div>
884 * </div>
885 * <div class="annotation">
886 * </div>
887 * </div>
889 * @param block_contents $bc HTML for the content
890 * @param string $region the region the block is appearing in.
891 * @return string the HTML to be output.
893 public function block(block_contents $bc, $region) {
894 $bc = clone($bc); // Avoid messing up the object passed in.
895 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
896 $bc->collapsible = block_contents::NOT_HIDEABLE;
898 if ($bc->collapsible == block_contents::HIDDEN) {
899 $bc->add_class('hidden');
901 if (!empty($bc->controls)) {
902 $bc->add_class('block_with_controls');
905 $skiptitle = strip_tags($bc->title);
906 if (empty($skiptitle)) {
907 $output = '';
908 $skipdest = '';
909 } else {
910 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
911 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
914 $output .= html_writer::start_tag('div', $bc->attributes);
916 $output .= $this->block_header($bc);
917 $output .= $this->block_content($bc);
919 $output .= html_writer::end_tag('div');
921 $output .= $this->block_annotation($bc);
923 $output .= $skipdest;
925 $this->init_block_hider_js($bc);
926 return $output;
930 * Produces a header for a block
932 * @param block_contents $bc
933 * @return string
935 protected function block_header(block_contents $bc) {
937 $title = '';
938 if ($bc->title) {
939 $title = html_writer::tag('h2', $bc->title, null);
942 $controlshtml = $this->block_controls($bc->controls);
944 $output = '';
945 if ($title || $controlshtml) {
946 $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'));
948 return $output;
952 * Produces the content area for a block
954 * @param block_contents $bc
955 * @return string
957 protected function block_content(block_contents $bc) {
958 $output = html_writer::start_tag('div', array('class' => 'content'));
959 if (!$bc->title && !$this->block_controls($bc->controls)) {
960 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
962 $output .= $bc->content;
963 $output .= $this->block_footer($bc);
964 $output .= html_writer::end_tag('div');
966 return $output;
970 * Produces the footer for a block
972 * @param block_contents $bc
973 * @return string
975 protected function block_footer(block_contents $bc) {
976 $output = '';
977 if ($bc->footer) {
978 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
980 return $output;
984 * Produces the annotation for a block
986 * @param block_contents $bc
987 * @return string
989 protected function block_annotation(block_contents $bc) {
990 $output = '';
991 if ($bc->annotation) {
992 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
994 return $output;
998 * Calls the JS require function to hide a block.
1000 * @param block_contents $bc A block_contents object
1002 protected function init_block_hider_js(block_contents $bc) {
1003 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1004 $config = new stdClass;
1005 $config->id = $bc->attributes['id'];
1006 $config->title = strip_tags($bc->title);
1007 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1008 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1009 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1011 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1012 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1017 * Render the contents of a block_list.
1019 * @param array $icons the icon for each item.
1020 * @param array $items the content of each item.
1021 * @return string HTML
1023 public function list_block_contents($icons, $items) {
1024 $row = 0;
1025 $lis = array();
1026 foreach ($items as $key => $string) {
1027 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1028 if (!empty($icons[$key])) { //test if the content has an assigned icon
1029 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1031 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1032 $item .= html_writer::end_tag('li');
1033 $lis[] = $item;
1034 $row = 1 - $row; // Flip even/odd.
1036 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1040 * Output all the blocks in a particular region.
1042 * @param string $region the name of a region on this page.
1043 * @return string the HTML to be output.
1045 public function blocks_for_region($region) {
1046 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1048 $output = '';
1049 foreach ($blockcontents as $bc) {
1050 if ($bc instanceof block_contents) {
1051 $output .= $this->block($bc, $region);
1052 } else if ($bc instanceof block_move_target) {
1053 $output .= $this->block_move_target($bc);
1054 } else {
1055 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1058 return $output;
1062 * Output a place where the block that is currently being moved can be dropped.
1064 * @param block_move_target $target with the necessary details.
1065 * @return string the HTML to be output.
1067 public function block_move_target($target) {
1068 return html_writer::tag('a', html_writer::tag('span', $target->text, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1072 * Renders a special html link with attached action
1074 * @param string|moodle_url $url
1075 * @param string $text HTML fragment
1076 * @param component_action $action
1077 * @param array $attributes associative array of html link attributes + disabled
1078 * @return string HTML fragment
1080 public function action_link($url, $text, component_action $action = null, array $attributes=null) {
1081 if (!($url instanceof moodle_url)) {
1082 $url = new moodle_url($url);
1084 $link = new action_link($url, $text, $action, $attributes);
1086 return $this->render($link);
1090 * Renders an action_link object.
1092 * The provided link is renderer and the HTML returned. At the same time the
1093 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1095 * @param action_link $link
1096 * @return string HTML fragment
1098 protected function render_action_link(action_link $link) {
1099 global $CFG;
1101 if ($link->text instanceof renderable) {
1102 $text = $this->render($link->text);
1103 } else {
1104 $text = $link->text;
1107 // A disabled link is rendered as formatted text
1108 if (!empty($link->attributes['disabled'])) {
1109 // do not use div here due to nesting restriction in xhtml strict
1110 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1113 $attributes = $link->attributes;
1114 unset($link->attributes['disabled']);
1115 $attributes['href'] = $link->url;
1117 if ($link->actions) {
1118 if (empty($attributes['id'])) {
1119 $id = html_writer::random_id('action_link');
1120 $attributes['id'] = $id;
1121 } else {
1122 $id = $attributes['id'];
1124 foreach ($link->actions as $action) {
1125 $this->add_action_handler($action, $id);
1129 return html_writer::tag('a', $text, $attributes);
1134 * Renders an action_icon.
1136 * This function uses the {@link core_renderer::action_link()} method for the
1137 * most part. What it does different is prepare the icon as HTML and use it
1138 * as the link text.
1140 * @param string|moodle_url $url A string URL or moodel_url
1141 * @param pix_icon $pixicon
1142 * @param component_action $action
1143 * @param array $attributes associative array of html link attributes + disabled
1144 * @param bool $linktext show title next to image in link
1145 * @return string HTML fragment
1147 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1148 if (!($url instanceof moodle_url)) {
1149 $url = new moodle_url($url);
1151 $attributes = (array)$attributes;
1153 if (empty($attributes['class'])) {
1154 // let ppl override the class via $options
1155 $attributes['class'] = 'action-icon';
1158 $icon = $this->render($pixicon);
1160 if ($linktext) {
1161 $text = $pixicon->attributes['alt'];
1162 } else {
1163 $text = '';
1166 return $this->action_link($url, $text.$icon, $action, $attributes);
1170 * Print a message along with button choices for Continue/Cancel
1172 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1174 * @param string $message The question to ask the user
1175 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1176 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1177 * @return string HTML fragment
1179 public function confirm($message, $continue, $cancel) {
1180 if ($continue instanceof single_button) {
1181 // ok
1182 } else if (is_string($continue)) {
1183 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1184 } else if ($continue instanceof moodle_url) {
1185 $continue = new single_button($continue, get_string('continue'), 'post');
1186 } else {
1187 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1190 if ($cancel instanceof single_button) {
1191 // ok
1192 } else if (is_string($cancel)) {
1193 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1194 } else if ($cancel instanceof moodle_url) {
1195 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1196 } else {
1197 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1200 $output = $this->box_start('generalbox', 'notice');
1201 $output .= html_writer::tag('p', $message);
1202 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1203 $output .= $this->box_end();
1204 return $output;
1208 * Returns a form with a single button.
1210 * @param string|moodle_url $url
1211 * @param string $label button text
1212 * @param string $method get or post submit method
1213 * @param array $options associative array {disabled, title, etc.}
1214 * @return string HTML fragment
1216 public function single_button($url, $label, $method='post', array $options=null) {
1217 if (!($url instanceof moodle_url)) {
1218 $url = new moodle_url($url);
1220 $button = new single_button($url, $label, $method);
1222 foreach ((array)$options as $key=>$value) {
1223 if (array_key_exists($key, $button)) {
1224 $button->$key = $value;
1228 return $this->render($button);
1232 * Renders a single button widget.
1234 * This will return HTML to display a form containing a single button.
1236 * @param single_button $button
1237 * @return string HTML fragment
1239 protected function render_single_button(single_button $button) {
1240 $attributes = array('type' => 'submit',
1241 'value' => $button->label,
1242 'disabled' => $button->disabled ? 'disabled' : null,
1243 'title' => $button->tooltip);
1245 if ($button->actions) {
1246 $id = html_writer::random_id('single_button');
1247 $attributes['id'] = $id;
1248 foreach ($button->actions as $action) {
1249 $this->add_action_handler($action, $id);
1253 // first the input element
1254 $output = html_writer::empty_tag('input', $attributes);
1256 // then hidden fields
1257 $params = $button->url->params();
1258 if ($button->method === 'post') {
1259 $params['sesskey'] = sesskey();
1261 foreach ($params as $var => $val) {
1262 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1265 // then div wrapper for xhtml strictness
1266 $output = html_writer::tag('div', $output);
1268 // now the form itself around it
1269 if ($button->method === 'get') {
1270 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1271 } else {
1272 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1274 if ($url === '') {
1275 $url = '#'; // there has to be always some action
1277 $attributes = array('method' => $button->method,
1278 'action' => $url,
1279 'id' => $button->formid);
1280 $output = html_writer::tag('form', $output, $attributes);
1282 // and finally one more wrapper with class
1283 return html_writer::tag('div', $output, array('class' => $button->class));
1287 * Returns a form with a single select widget.
1289 * @param moodle_url $url form action target, includes hidden fields
1290 * @param string $name name of selection field - the changing parameter in url
1291 * @param array $options list of options
1292 * @param string $selected selected element
1293 * @param array $nothing
1294 * @param string $formid
1295 * @return string HTML fragment
1297 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1298 if (!($url instanceof moodle_url)) {
1299 $url = new moodle_url($url);
1301 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1303 return $this->render($select);
1307 * Internal implementation of single_select rendering
1309 * @param single_select $select
1310 * @return string HTML fragment
1312 protected function render_single_select(single_select $select) {
1313 $select = clone($select);
1314 if (empty($select->formid)) {
1315 $select->formid = html_writer::random_id('single_select_f');
1318 $output = '';
1319 $params = $select->url->params();
1320 if ($select->method === 'post') {
1321 $params['sesskey'] = sesskey();
1323 foreach ($params as $name=>$value) {
1324 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1327 if (empty($select->attributes['id'])) {
1328 $select->attributes['id'] = html_writer::random_id('single_select');
1331 if ($select->disabled) {
1332 $select->attributes['disabled'] = 'disabled';
1335 if ($select->tooltip) {
1336 $select->attributes['title'] = $select->tooltip;
1339 $select->attributes['class'] = 'autosubmit';
1340 if ($select->class) {
1341 $select->attributes['class'] .= ' ' . $select->class;
1344 if ($select->label) {
1345 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1348 if ($select->helpicon instanceof help_icon) {
1349 $output .= $this->render($select->helpicon);
1350 } else if ($select->helpicon instanceof old_help_icon) {
1351 $output .= $this->render($select->helpicon);
1353 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1355 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1356 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('style'=>'inline'));
1358 $nothing = empty($select->nothing) ? false : key($select->nothing);
1359 $this->page->requires->yui_module('moodle-core-formautosubmit',
1360 'M.core.init_formautosubmit',
1361 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1364 // then div wrapper for xhtml strictness
1365 $output = html_writer::tag('div', $output);
1367 // now the form itself around it
1368 if ($select->method === 'get') {
1369 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1370 } else {
1371 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1373 $formattributes = array('method' => $select->method,
1374 'action' => $url,
1375 'id' => $select->formid);
1376 $output = html_writer::tag('form', $output, $formattributes);
1378 // and finally one more wrapper with class
1379 return html_writer::tag('div', $output, array('class' => $select->class));
1383 * Returns a form with a url select widget.
1385 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1386 * @param string $selected selected element
1387 * @param array $nothing
1388 * @param string $formid
1389 * @return string HTML fragment
1391 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1392 $select = new url_select($urls, $selected, $nothing, $formid);
1393 return $this->render($select);
1397 * Internal implementation of url_select rendering
1399 * @param url_select $select
1400 * @return string HTML fragment
1402 protected function render_url_select(url_select $select) {
1403 global $CFG;
1405 $select = clone($select);
1406 if (empty($select->formid)) {
1407 $select->formid = html_writer::random_id('url_select_f');
1410 if (empty($select->attributes['id'])) {
1411 $select->attributes['id'] = html_writer::random_id('url_select');
1414 if ($select->disabled) {
1415 $select->attributes['disabled'] = 'disabled';
1418 if ($select->tooltip) {
1419 $select->attributes['title'] = $select->tooltip;
1422 $output = '';
1424 if ($select->label) {
1425 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1428 $classes = array();
1429 if (!$select->showbutton) {
1430 $classes[] = 'autosubmit';
1432 if ($select->class) {
1433 $classes[] = $select->class;
1435 if (count($classes)) {
1436 $select->attributes['class'] = implode(' ', $classes);
1439 if ($select->helpicon instanceof help_icon) {
1440 $output .= $this->render($select->helpicon);
1441 } else if ($select->helpicon instanceof old_help_icon) {
1442 $output .= $this->render($select->helpicon);
1445 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1446 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1447 $urls = array();
1448 foreach ($select->urls as $k=>$v) {
1449 if (is_array($v)) {
1450 // optgroup structure
1451 foreach ($v as $optgrouptitle => $optgroupoptions) {
1452 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1453 if (empty($optionurl)) {
1454 $safeoptionurl = '';
1455 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1456 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1457 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1458 } else if (strpos($optionurl, '/') !== 0) {
1459 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1460 continue;
1461 } else {
1462 $safeoptionurl = $optionurl;
1464 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1467 } else {
1468 // plain list structure
1469 if (empty($k)) {
1470 // nothing selected option
1471 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1472 $k = str_replace($CFG->wwwroot, '', $k);
1473 } else if (strpos($k, '/') !== 0) {
1474 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1475 continue;
1477 $urls[$k] = $v;
1480 $selected = $select->selected;
1481 if (!empty($selected)) {
1482 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1483 $selected = str_replace($CFG->wwwroot, '', $selected);
1484 } else if (strpos($selected, '/') !== 0) {
1485 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1489 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1490 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1492 if (!$select->showbutton) {
1493 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1494 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('style'=>'inline'));
1495 $nothing = empty($select->nothing) ? false : key($select->nothing);
1496 $this->page->requires->yui_module('moodle-core-formautosubmit',
1497 'M.core.init_formautosubmit',
1498 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1500 } else {
1501 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1504 // then div wrapper for xhtml strictness
1505 $output = html_writer::tag('div', $output);
1507 // now the form itself around it
1508 $formattributes = array('method' => 'post',
1509 'action' => new moodle_url('/course/jumpto.php'),
1510 'id' => $select->formid);
1511 $output = html_writer::tag('form', $output, $formattributes);
1513 // and finally one more wrapper with class
1514 return html_writer::tag('div', $output, array('class' => $select->class));
1518 * Returns a string containing a link to the user documentation.
1519 * Also contains an icon by default. Shown to teachers and admin only.
1521 * @param string $path The page link after doc root and language, no leading slash.
1522 * @param string $text The text to be displayed for the link
1523 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
1524 * @return string
1526 public function doc_link($path, $text = '', $forcepopup = false) {
1527 global $CFG;
1529 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp'));
1531 $url = new moodle_url(get_docs_url($path));
1533 $attributes = array('href'=>$url);
1534 if (!empty($CFG->doctonewwindow) || $forcepopup) {
1535 $attributes['class'] = 'helplinkpopup';
1538 return html_writer::tag('a', $icon.$text, $attributes);
1542 * Return HTML for a pix_icon.
1544 * @param string $pix short pix name
1545 * @param string $alt mandatory alt attribute
1546 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1547 * @param array $attributes htm lattributes
1548 * @return string HTML fragment
1550 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1551 $icon = new pix_icon($pix, $alt, $component, $attributes);
1552 return $this->render($icon);
1556 * Renders a pix_icon widget and returns the HTML to display it.
1558 * @param pix_icon $icon
1559 * @return string HTML fragment
1561 protected function render_pix_icon(pix_icon $icon) {
1562 $attributes = $icon->attributes;
1563 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1564 return html_writer::empty_tag('img', $attributes);
1568 * Return HTML to display an emoticon icon.
1570 * @param pix_emoticon $emoticon
1571 * @return string HTML fragment
1573 protected function render_pix_emoticon(pix_emoticon $emoticon) {
1574 $attributes = $emoticon->attributes;
1575 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
1576 return html_writer::empty_tag('img', $attributes);
1580 * Produces the html that represents this rating in the UI
1582 * @param rating $rating the page object on which this rating will appear
1583 * @return string
1585 function render_rating(rating $rating) {
1586 global $CFG, $USER;
1588 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
1589 return null;//ratings are turned off
1592 $ratingmanager = new rating_manager();
1593 // Initialise the JavaScript so ratings can be done by AJAX.
1594 $ratingmanager->initialise_rating_javascript($this->page);
1596 $strrate = get_string("rate", "rating");
1597 $ratinghtml = ''; //the string we'll return
1599 // permissions check - can they view the aggregate?
1600 if ($rating->user_can_view_aggregate()) {
1602 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
1603 $aggregatestr = $rating->get_aggregate_string();
1605 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
1606 if ($rating->count > 0) {
1607 $countstr = "({$rating->count})";
1608 } else {
1609 $countstr = '-';
1611 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
1613 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
1614 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
1616 $nonpopuplink = $rating->get_view_ratings_url();
1617 $popuplink = $rating->get_view_ratings_url(true);
1619 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
1620 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
1621 } else {
1622 $ratinghtml .= $aggregatehtml;
1626 $formstart = null;
1627 // if the item doesn't belong to the current user, the user has permission to rate
1628 // and we're within the assessable period
1629 if ($rating->user_can_rate()) {
1631 $rateurl = $rating->get_rate_url();
1632 $inputs = $rateurl->params();
1634 //start the rating form
1635 $formattrs = array(
1636 'id' => "postrating{$rating->itemid}",
1637 'class' => 'postratingform',
1638 'method' => 'post',
1639 'action' => $rateurl->out_omit_querystring()
1641 $formstart = html_writer::start_tag('form', $formattrs);
1642 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
1644 // add the hidden inputs
1645 foreach ($inputs as $name => $value) {
1646 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
1647 $formstart .= html_writer::empty_tag('input', $attributes);
1650 if (empty($ratinghtml)) {
1651 $ratinghtml .= $strrate.': ';
1653 $ratinghtml = $formstart.$ratinghtml;
1655 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
1656 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
1657 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
1658 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
1660 //output submit button
1661 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
1663 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
1664 $ratinghtml .= html_writer::empty_tag('input', $attributes);
1666 if (!$rating->settings->scale->isnumeric) {
1667 // If a global scale, try to find current course ID from the context
1668 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
1669 $courseid = $coursecontext->instanceid;
1670 } else {
1671 $courseid = $rating->settings->scale->courseid;
1673 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
1675 $ratinghtml .= html_writer::end_tag('span');
1676 $ratinghtml .= html_writer::end_tag('div');
1677 $ratinghtml .= html_writer::end_tag('form');
1680 return $ratinghtml;
1684 * Centered heading with attached help button (same title text)
1685 * and optional icon attached.
1687 * @param string $text A heading text
1688 * @param string $helpidentifier The keyword that defines a help page
1689 * @param string $component component name
1690 * @param string|moodle_url $icon
1691 * @param string $iconalt icon alt text
1692 * @return string HTML fragment
1694 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '') {
1695 $image = '';
1696 if ($icon) {
1697 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
1700 $help = '';
1701 if ($helpidentifier) {
1702 $help = $this->help_icon($helpidentifier, $component);
1705 return $this->heading($image.$text.$help, 2, 'main help');
1709 * Returns HTML to display a help icon.
1711 * @deprecated since Moodle 2.0
1712 * @param string $helpidentifier The keyword that defines a help page
1713 * @param string $title A descriptive text for accessibility only
1714 * @param string $component component name
1715 * @param string|bool $linktext true means use $title as link text, string means link text value
1716 * @return string HTML fragment
1718 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
1719 debugging('The method old_help_icon() is deprecated, please fix the code and use help_icon() method instead', DEBUG_DEVELOPER);
1720 $icon = new old_help_icon($helpidentifier, $title, $component);
1721 if ($linktext === true) {
1722 $icon->linktext = $title;
1723 } else if (!empty($linktext)) {
1724 $icon->linktext = $linktext;
1726 return $this->render($icon);
1730 * Implementation of user image rendering.
1732 * @param old_help_icon $helpicon A help icon instance
1733 * @return string HTML fragment
1735 protected function render_old_help_icon(old_help_icon $helpicon) {
1736 global $CFG;
1738 // first get the help image icon
1739 $src = $this->pix_url('help');
1741 if (empty($helpicon->linktext)) {
1742 $alt = $helpicon->title;
1743 } else {
1744 $alt = get_string('helpwiththis');
1747 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1748 $output = html_writer::empty_tag('img', $attributes);
1750 // add the link text if given
1751 if (!empty($helpicon->linktext)) {
1752 // the spacing has to be done through CSS
1753 $output .= $helpicon->linktext;
1756 // now create the link around it - we need https on loginhttps pages
1757 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->helpidentifier, 'lang'=>current_language()));
1759 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1760 $title = get_string('helpprefix2', '', trim($helpicon->title, ". \t"));
1762 $attributes = array('href'=>$url, 'title'=>$title, 'aria-haspopup' => 'true');
1763 $id = html_writer::random_id('helpicon');
1764 $attributes['id'] = $id;
1765 $output = html_writer::tag('a', $output, $attributes);
1767 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1768 $this->page->requires->string_for_js('close', 'form');
1770 // and finally span
1771 return html_writer::tag('span', $output, array('class' => 'helplink'));
1775 * Returns HTML to display a help icon.
1777 * @param string $identifier The keyword that defines a help page
1778 * @param string $component component name
1779 * @param string|bool $linktext true means use $title as link text, string means link text value
1780 * @return string HTML fragment
1782 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
1783 $icon = new help_icon($identifier, $component);
1784 $icon->diag_strings();
1785 if ($linktext === true) {
1786 $icon->linktext = get_string($icon->identifier, $icon->component);
1787 } else if (!empty($linktext)) {
1788 $icon->linktext = $linktext;
1790 return $this->render($icon);
1794 * Implementation of user image rendering.
1796 * @param help_icon $helpicon A help icon instance
1797 * @return string HTML fragment
1799 protected function render_help_icon(help_icon $helpicon) {
1800 global $CFG;
1802 // first get the help image icon
1803 $src = $this->pix_url('help');
1805 $title = get_string($helpicon->identifier, $helpicon->component);
1807 if (empty($helpicon->linktext)) {
1808 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
1809 } else {
1810 $alt = get_string('helpwiththis');
1813 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1814 $output = html_writer::empty_tag('img', $attributes);
1816 // add the link text if given
1817 if (!empty($helpicon->linktext)) {
1818 // the spacing has to be done through CSS
1819 $output .= $helpicon->linktext;
1822 // now create the link around it - we need https on loginhttps pages
1823 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
1825 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1826 $title = get_string('helpprefix2', '', trim($title, ". \t"));
1828 $attributes = array('href'=>$url, 'title'=>$title, 'aria-haspopup' => 'true', 'class' => 'tooltip');
1829 $output = html_writer::tag('a', $output, $attributes);
1831 $this->page->requires->js_init_call('M.util.help_icon.setup');
1832 $this->page->requires->string_for_js('close', 'form');
1834 // and finally span
1835 return html_writer::tag('span', $output, array('class' => 'helplink'));
1839 * Returns HTML to display a scale help icon.
1841 * @param int $courseid
1842 * @param stdClass $scale instance
1843 * @return string HTML fragment
1845 public function help_icon_scale($courseid, stdClass $scale) {
1846 global $CFG;
1848 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
1850 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
1852 $scaleid = abs($scale->id);
1854 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
1855 $action = new popup_action('click', $link, 'ratingscale');
1857 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
1861 * Creates and returns a spacer image with optional line break.
1863 * @param array $attributes Any HTML attributes to add to the spaced.
1864 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
1865 * laxy do it with CSS which is a much better solution.
1866 * @return string HTML fragment
1868 public function spacer(array $attributes = null, $br = false) {
1869 $attributes = (array)$attributes;
1870 if (empty($attributes['width'])) {
1871 $attributes['width'] = 1;
1873 if (empty($attributes['height'])) {
1874 $attributes['height'] = 1;
1876 $attributes['class'] = 'spacer';
1878 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
1880 if (!empty($br)) {
1881 $output .= '<br />';
1884 return $output;
1888 * Returns HTML to display the specified user's avatar.
1890 * User avatar may be obtained in two ways:
1891 * <pre>
1892 * // Option 1: (shortcut for simple cases, preferred way)
1893 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
1894 * $OUTPUT->user_picture($user, array('popup'=>true));
1896 * // Option 2:
1897 * $userpic = new user_picture($user);
1898 * // Set properties of $userpic
1899 * $userpic->popup = true;
1900 * $OUTPUT->render($userpic);
1901 * </pre>
1903 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
1904 * If any of these are missing, the database is queried. Avoid this
1905 * if at all possible, particularly for reports. It is very bad for performance.
1906 * @param array $options associative array with user picture options, used only if not a user_picture object,
1907 * options are:
1908 * - courseid=$this->page->course->id (course id of user profile in link)
1909 * - size=35 (size of image)
1910 * - link=true (make image clickable - the link leads to user profile)
1911 * - popup=false (open in popup)
1912 * - alttext=true (add image alt attribute)
1913 * - class = image class attribute (default 'userpicture')
1914 * @return string HTML fragment
1916 public function user_picture(stdClass $user, array $options = null) {
1917 $userpicture = new user_picture($user);
1918 foreach ((array)$options as $key=>$value) {
1919 if (array_key_exists($key, $userpicture)) {
1920 $userpicture->$key = $value;
1923 return $this->render($userpicture);
1927 * Internal implementation of user image rendering.
1929 * @param user_picture $userpicture
1930 * @return string
1932 protected function render_user_picture(user_picture $userpicture) {
1933 global $CFG, $DB;
1935 $user = $userpicture->user;
1937 if ($userpicture->alttext) {
1938 if (!empty($user->imagealt)) {
1939 $alt = $user->imagealt;
1940 } else {
1941 $alt = get_string('pictureof', '', fullname($user));
1943 } else {
1944 $alt = '';
1947 if (empty($userpicture->size)) {
1948 $size = 35;
1949 } else if ($userpicture->size === true or $userpicture->size == 1) {
1950 $size = 100;
1951 } else {
1952 $size = $userpicture->size;
1955 $class = $userpicture->class;
1957 if ($user->picture == 0) {
1958 $class .= ' defaultuserpic';
1961 $src = $userpicture->get_url($this->page, $this);
1963 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
1965 // get the image html output fisrt
1966 $output = html_writer::empty_tag('img', $attributes);;
1968 // then wrap it in link if needed
1969 if (!$userpicture->link) {
1970 return $output;
1973 if (empty($userpicture->courseid)) {
1974 $courseid = $this->page->course->id;
1975 } else {
1976 $courseid = $userpicture->courseid;
1979 if ($courseid == SITEID) {
1980 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
1981 } else {
1982 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
1985 $attributes = array('href'=>$url);
1987 if ($userpicture->popup) {
1988 $id = html_writer::random_id('userpicture');
1989 $attributes['id'] = $id;
1990 $this->add_action_handler(new popup_action('click', $url), $id);
1993 return html_writer::tag('a', $output, $attributes);
1997 * Internal implementation of file tree viewer items rendering.
1999 * @param array $dir
2000 * @return string
2002 public function htmllize_file_tree($dir) {
2003 if (empty($dir['subdirs']) and empty($dir['files'])) {
2004 return '';
2006 $result = '<ul>';
2007 foreach ($dir['subdirs'] as $subdir) {
2008 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2010 foreach ($dir['files'] as $file) {
2011 $filename = $file->get_filename();
2012 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2014 $result .= '</ul>';
2016 return $result;
2020 * Returns HTML to display the file picker
2022 * <pre>
2023 * $OUTPUT->file_picker($options);
2024 * </pre>
2026 * @param array $options associative array with file manager options
2027 * options are:
2028 * maxbytes=>-1,
2029 * itemid=>0,
2030 * client_id=>uniqid(),
2031 * acepted_types=>'*',
2032 * return_types=>FILE_INTERNAL,
2033 * context=>$PAGE->context
2034 * @return string HTML fragment
2036 public function file_picker($options) {
2037 $fp = new file_picker($options);
2038 return $this->render($fp);
2042 * Internal implementation of file picker rendering.
2044 * @param file_picker $fp
2045 * @return string
2047 public function render_file_picker(file_picker $fp) {
2048 global $CFG, $OUTPUT, $USER;
2049 $options = $fp->options;
2050 $client_id = $options->client_id;
2051 $strsaved = get_string('filesaved', 'repository');
2052 $straddfile = get_string('openpicker', 'repository');
2053 $strloading = get_string('loading', 'repository');
2054 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2055 $strdroptoupload = get_string('droptoupload', 'moodle');
2056 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2058 $currentfile = $options->currentfile;
2059 if (empty($currentfile)) {
2060 $currentfile = '';
2061 } else {
2062 $currentfile .= ' - ';
2064 if ($options->maxbytes) {
2065 $size = $options->maxbytes;
2066 } else {
2067 $size = get_max_upload_file_size();
2069 if ($size == -1) {
2070 $maxsize = '';
2071 } else {
2072 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2074 if ($options->buttonname) {
2075 $buttonname = ' name="' . $options->buttonname . '"';
2076 } else {
2077 $buttonname = '';
2079 $html = <<<EOD
2080 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2081 $icon_progress
2082 </div>
2083 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2084 <div>
2085 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2086 <span> $maxsize </span>
2087 </div>
2088 EOD;
2089 if ($options->env != 'url') {
2090 $html .= <<<EOD
2091 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2092 <div class="filepicker-filename">
2093 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2094 </div>
2095 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2096 </div>
2097 EOD;
2099 $html .= '</div>';
2100 return $html;
2104 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2106 * @param string $cmid the course_module id.
2107 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2108 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2110 public function update_module_button($cmid, $modulename) {
2111 global $CFG;
2112 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $cmid))) {
2113 $modulename = get_string('modulename', $modulename);
2114 $string = get_string('updatethis', '', $modulename);
2115 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2116 return $this->single_button($url, $string);
2117 } else {
2118 return '';
2123 * Returns HTML to display a "Turn editing on/off" button in a form.
2125 * @param moodle_url $url The URL + params to send through when clicking the button
2126 * @return string HTML the button
2128 public function edit_button(moodle_url $url) {
2130 $url->param('sesskey', sesskey());
2131 if ($this->page->user_is_editing()) {
2132 $url->param('edit', 'off');
2133 $editstring = get_string('turneditingoff');
2134 } else {
2135 $url->param('edit', 'on');
2136 $editstring = get_string('turneditingon');
2139 return $this->single_button($url, $editstring);
2143 * Returns HTML to display a simple button to close a window
2145 * @param string $text The lang string for the button's label (already output from get_string())
2146 * @return string html fragment
2148 public function close_window_button($text='') {
2149 if (empty($text)) {
2150 $text = get_string('closewindow');
2152 $button = new single_button(new moodle_url('#'), $text, 'get');
2153 $button->add_action(new component_action('click', 'close_window'));
2155 return $this->container($this->render($button), 'closewindow');
2159 * Output an error message. By default wraps the error message in <span class="error">.
2160 * If the error message is blank, nothing is output.
2162 * @param string $message the error message.
2163 * @return string the HTML to output.
2165 public function error_text($message) {
2166 if (empty($message)) {
2167 return '';
2169 return html_writer::tag('span', $message, array('class' => 'error'));
2173 * Do not call this function directly.
2175 * To terminate the current script with a fatal error, call the {@link print_error}
2176 * function, or throw an exception. Doing either of those things will then call this
2177 * function to display the error, before terminating the execution.
2179 * @param string $message The message to output
2180 * @param string $moreinfourl URL where more info can be found about the error
2181 * @param string $link Link for the Continue button
2182 * @param array $backtrace The execution backtrace
2183 * @param string $debuginfo Debugging information
2184 * @return string the HTML to output.
2186 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2187 global $CFG;
2189 $output = '';
2190 $obbuffer = '';
2192 if ($this->has_started()) {
2193 // we can not always recover properly here, we have problems with output buffering,
2194 // html tables, etc.
2195 $output .= $this->opencontainers->pop_all_but_last();
2197 } else {
2198 // It is really bad if library code throws exception when output buffering is on,
2199 // because the buffered text would be printed before our start of page.
2200 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2201 error_reporting(0); // disable notices from gzip compression, etc.
2202 while (ob_get_level() > 0) {
2203 $buff = ob_get_clean();
2204 if ($buff === false) {
2205 break;
2207 $obbuffer .= $buff;
2209 error_reporting($CFG->debug);
2211 // Header not yet printed
2212 if (isset($_SERVER['SERVER_PROTOCOL'])) {
2213 // server protocol should be always present, because this render
2214 // can not be used from command line or when outputting custom XML
2215 @header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
2217 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2218 $this->page->set_url('/'); // no url
2219 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2220 $this->page->set_title(get_string('error'));
2221 $this->page->set_heading($this->page->course->fullname);
2222 $output .= $this->header();
2225 $message = '<p class="errormessage">' . $message . '</p>'.
2226 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2227 get_string('moreinformation') . '</a></p>';
2228 if (empty($CFG->rolesactive)) {
2229 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2230 //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.
2232 $output .= $this->box($message, 'errorbox');
2234 if (debugging('', DEBUG_DEVELOPER)) {
2235 if (!empty($debuginfo)) {
2236 $debuginfo = s($debuginfo); // removes all nasty JS
2237 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2238 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2240 if (!empty($backtrace)) {
2241 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2243 if ($obbuffer !== '' ) {
2244 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2248 if (empty($CFG->rolesactive)) {
2249 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2250 } else if (!empty($link)) {
2251 $output .= $this->continue_button($link);
2254 $output .= $this->footer();
2256 // Padding to encourage IE to display our error page, rather than its own.
2257 $output .= str_repeat(' ', 512);
2259 return $output;
2263 * Output a notification (that is, a status message about something that has
2264 * just happened).
2266 * @param string $message the message to print out
2267 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2268 * @return string the HTML to output.
2270 public function notification($message, $classes = 'notifyproblem') {
2271 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2275 * Returns HTML to display a continue button that goes to a particular URL.
2277 * @param string|moodle_url $url The url the button goes to.
2278 * @return string the HTML to output.
2280 public function continue_button($url) {
2281 if (!($url instanceof moodle_url)) {
2282 $url = new moodle_url($url);
2284 $button = new single_button($url, get_string('continue'), 'get');
2285 $button->class = 'continuebutton';
2287 return $this->render($button);
2291 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2293 * @param int $totalcount The total number of entries available to be paged through
2294 * @param int $page The page you are currently viewing
2295 * @param int $perpage The number of entries that should be shown per page
2296 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2297 * @param string $pagevar name of page parameter that holds the page number
2298 * @return string the HTML to output.
2300 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2301 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2302 return $this->render($pb);
2306 * Internal implementation of paging bar rendering.
2308 * @param paging_bar $pagingbar
2309 * @return string
2311 protected function render_paging_bar(paging_bar $pagingbar) {
2312 $output = '';
2313 $pagingbar = clone($pagingbar);
2314 $pagingbar->prepare($this, $this->page, $this->target);
2316 if ($pagingbar->totalcount > $pagingbar->perpage) {
2317 $output .= get_string('page') . ':';
2319 if (!empty($pagingbar->previouslink)) {
2320 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
2323 if (!empty($pagingbar->firstlink)) {
2324 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
2327 foreach ($pagingbar->pagelinks as $link) {
2328 $output .= "&#160;&#160;$link";
2331 if (!empty($pagingbar->lastlink)) {
2332 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
2335 if (!empty($pagingbar->nextlink)) {
2336 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
2340 return html_writer::tag('div', $output, array('class' => 'paging'));
2344 * Output the place a skip link goes to.
2346 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2347 * @return string the HTML to output.
2349 public function skip_link_target($id = null) {
2350 return html_writer::tag('span', '', array('id' => $id));
2354 * Outputs a heading
2356 * @param string $text The text of the heading
2357 * @param int $level The level of importance of the heading. Defaulting to 2
2358 * @param string $classes A space-separated list of CSS classes
2359 * @param string $id An optional ID
2360 * @return string the HTML to output.
2362 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2363 $level = (integer) $level;
2364 if ($level < 1 or $level > 6) {
2365 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2367 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2371 * Outputs a box.
2373 * @param string $contents The contents of the box
2374 * @param string $classes A space-separated list of CSS classes
2375 * @param string $id An optional ID
2376 * @return string the HTML to output.
2378 public function box($contents, $classes = 'generalbox', $id = null) {
2379 return $this->box_start($classes, $id) . $contents . $this->box_end();
2383 * Outputs the opening section of a box.
2385 * @param string $classes A space-separated list of CSS classes
2386 * @param string $id An optional ID
2387 * @return string the HTML to output.
2389 public function box_start($classes = 'generalbox', $id = null) {
2390 $this->opencontainers->push('box', html_writer::end_tag('div'));
2391 return html_writer::start_tag('div', array('id' => $id,
2392 'class' => 'box ' . renderer_base::prepare_classes($classes)));
2396 * Outputs the closing section of a box.
2398 * @return string the HTML to output.
2400 public function box_end() {
2401 return $this->opencontainers->pop('box');
2405 * Outputs a container.
2407 * @param string $contents The contents of the box
2408 * @param string $classes A space-separated list of CSS classes
2409 * @param string $id An optional ID
2410 * @return string the HTML to output.
2412 public function container($contents, $classes = null, $id = null) {
2413 return $this->container_start($classes, $id) . $contents . $this->container_end();
2417 * Outputs the opening section of a container.
2419 * @param string $classes A space-separated list of CSS classes
2420 * @param string $id An optional ID
2421 * @return string the HTML to output.
2423 public function container_start($classes = null, $id = null) {
2424 $this->opencontainers->push('container', html_writer::end_tag('div'));
2425 return html_writer::start_tag('div', array('id' => $id,
2426 'class' => renderer_base::prepare_classes($classes)));
2430 * Outputs the closing section of a container.
2432 * @return string the HTML to output.
2434 public function container_end() {
2435 return $this->opencontainers->pop('container');
2439 * Make nested HTML lists out of the items
2441 * The resulting list will look something like this:
2443 * <pre>
2444 * <<ul>>
2445 * <<li>><div class='tree_item parent'>(item contents)</div>
2446 * <<ul>
2447 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2448 * <</ul>>
2449 * <</li>>
2450 * <</ul>>
2451 * </pre>
2453 * @param array $items
2454 * @param array $attrs html attributes passed to the top ofs the list
2455 * @return string HTML
2457 public function tree_block_contents($items, $attrs = array()) {
2458 // exit if empty, we don't want an empty ul element
2459 if (empty($items)) {
2460 return '';
2462 // array of nested li elements
2463 $lis = array();
2464 foreach ($items as $item) {
2465 // this applies to the li item which contains all child lists too
2466 $content = $item->content($this);
2467 $liclasses = array($item->get_css_type());
2468 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2469 $liclasses[] = 'collapsed';
2471 if ($item->isactive === true) {
2472 $liclasses[] = 'current_branch';
2474 $liattr = array('class'=>join(' ',$liclasses));
2475 // class attribute on the div item which only contains the item content
2476 $divclasses = array('tree_item');
2477 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2478 $divclasses[] = 'branch';
2479 } else {
2480 $divclasses[] = 'leaf';
2482 if (!empty($item->classes) && count($item->classes)>0) {
2483 $divclasses[] = join(' ', $item->classes);
2485 $divattr = array('class'=>join(' ', $divclasses));
2486 if (!empty($item->id)) {
2487 $divattr['id'] = $item->id;
2489 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2490 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2491 $content = html_writer::empty_tag('hr') . $content;
2493 $content = html_writer::tag('li', $content, $liattr);
2494 $lis[] = $content;
2496 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2500 * Return the navbar content so that it can be echoed out by the layout
2502 * @return string XHTML navbar
2504 public function navbar() {
2505 $items = $this->page->navbar->get_items();
2507 $htmlblocks = array();
2508 // Iterate the navarray and display each node
2509 $itemcount = count($items);
2510 $separator = get_separator();
2511 for ($i=0;$i < $itemcount;$i++) {
2512 $item = $items[$i];
2513 $item->hideicon = true;
2514 if ($i===0) {
2515 $content = html_writer::tag('li', $this->render($item));
2516 } else {
2517 $content = html_writer::tag('li', $separator.$this->render($item));
2519 $htmlblocks[] = $content;
2522 //accessibility: heading for navbar list (MDL-20446)
2523 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2524 $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks));
2525 // XHTML
2526 return $navbarcontent;
2530 * Renders a navigation node object.
2532 * @param navigation_node $item The navigation node to render.
2533 * @return string HTML fragment
2535 protected function render_navigation_node(navigation_node $item) {
2536 $content = $item->get_content();
2537 $title = $item->get_title();
2538 if ($item->icon instanceof renderable && !$item->hideicon) {
2539 $icon = $this->render($item->icon);
2540 $content = $icon.$content; // use CSS for spacing of icons
2542 if ($item->helpbutton !== null) {
2543 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2545 if ($content === '') {
2546 return '';
2548 if ($item->action instanceof action_link) {
2549 $link = $item->action;
2550 if ($item->hidden) {
2551 $link->add_class('dimmed');
2553 if (!empty($content)) {
2554 // Providing there is content we will use that for the link content.
2555 $link->text = $content;
2557 $content = $this->render($link);
2558 } else if ($item->action instanceof moodle_url) {
2559 $attributes = array();
2560 if ($title !== '') {
2561 $attributes['title'] = $title;
2563 if ($item->hidden) {
2564 $attributes['class'] = 'dimmed_text';
2566 $content = html_writer::link($item->action, $content, $attributes);
2568 } else if (is_string($item->action) || empty($item->action)) {
2569 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2570 if ($title !== '') {
2571 $attributes['title'] = $title;
2573 if ($item->hidden) {
2574 $attributes['class'] = 'dimmed_text';
2576 $content = html_writer::tag('span', $content, $attributes);
2578 return $content;
2582 * Accessibility: Right arrow-like character is
2583 * used in the breadcrumb trail, course navigation menu
2584 * (previous/next activity), calendar, and search forum block.
2585 * If the theme does not set characters, appropriate defaults
2586 * are set automatically. Please DO NOT
2587 * use &lt; &gt; &raquo; - these are confusing for blind users.
2589 * @return string
2591 public function rarrow() {
2592 return $this->page->theme->rarrow;
2596 * Accessibility: Right arrow-like character is
2597 * used in the breadcrumb trail, course navigation menu
2598 * (previous/next activity), calendar, and search forum block.
2599 * If the theme does not set characters, appropriate defaults
2600 * are set automatically. Please DO NOT
2601 * use &lt; &gt; &raquo; - these are confusing for blind users.
2603 * @return string
2605 public function larrow() {
2606 return $this->page->theme->larrow;
2610 * Returns the custom menu if one has been set
2612 * A custom menu can be configured by browsing to
2613 * Settings: Administration > Appearance > Themes > Theme settings
2614 * and then configuring the custommenu config setting as described.
2616 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
2617 * @return string
2619 public function custom_menu($custommenuitems = '') {
2620 global $CFG;
2621 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
2622 $custommenuitems = $CFG->custommenuitems;
2624 if (empty($custommenuitems)) {
2625 return '';
2627 $custommenu = new custom_menu($custommenuitems, current_language());
2628 return $this->render_custom_menu($custommenu);
2632 * Renders a custom menu object (located in outputcomponents.php)
2634 * The custom menu this method produces makes use of the YUI3 menunav widget
2635 * and requires very specific html elements and classes.
2637 * @staticvar int $menucount
2638 * @param custom_menu $menu
2639 * @return string
2641 protected function render_custom_menu(custom_menu $menu) {
2642 static $menucount = 0;
2643 // If the menu has no children return an empty string
2644 if (!$menu->has_children()) {
2645 return '';
2647 // Increment the menu count. This is used for ID's that get worked with
2648 // in JavaScript as is essential
2649 $menucount++;
2650 // Initialise this custom menu (the custom menu object is contained in javascript-static
2651 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
2652 $jscode = "(function(){{$jscode}})";
2653 $this->page->requires->yui_module('node-menunav', $jscode);
2654 // Build the root nodes as required by YUI
2655 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled'));
2656 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2657 $content .= html_writer::start_tag('ul');
2658 // Render each child
2659 foreach ($menu->get_children() as $item) {
2660 $content .= $this->render_custom_menu_item($item);
2662 // Close the open tags
2663 $content .= html_writer::end_tag('ul');
2664 $content .= html_writer::end_tag('div');
2665 $content .= html_writer::end_tag('div');
2666 // Return the custom menu
2667 return $content;
2671 * Renders a custom menu node as part of a submenu
2673 * The custom menu this method produces makes use of the YUI3 menunav widget
2674 * and requires very specific html elements and classes.
2676 * @see core:renderer::render_custom_menu()
2678 * @staticvar int $submenucount
2679 * @param custom_menu_item $menunode
2680 * @return string
2682 protected function render_custom_menu_item(custom_menu_item $menunode) {
2683 // Required to ensure we get unique trackable id's
2684 static $submenucount = 0;
2685 if ($menunode->has_children()) {
2686 // If the child has menus render it as a sub menu
2687 $submenucount++;
2688 $content = html_writer::start_tag('li');
2689 if ($menunode->get_url() !== null) {
2690 $url = $menunode->get_url();
2691 } else {
2692 $url = '#cm_submenu_'.$submenucount;
2694 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
2695 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
2696 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2697 $content .= html_writer::start_tag('ul');
2698 foreach ($menunode->get_children() as $menunode) {
2699 $content .= $this->render_custom_menu_item($menunode);
2701 $content .= html_writer::end_tag('ul');
2702 $content .= html_writer::end_tag('div');
2703 $content .= html_writer::end_tag('div');
2704 $content .= html_writer::end_tag('li');
2705 } else {
2706 // The node doesn't have children so produce a final menuitem
2707 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
2708 if ($menunode->get_url() !== null) {
2709 $url = $menunode->get_url();
2710 } else {
2711 $url = '#';
2713 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
2714 $content .= html_writer::end_tag('li');
2716 // Return the sub menu
2717 return $content;
2721 * Renders theme links for switching between default and other themes.
2723 * @return string
2725 protected function theme_switch_links() {
2727 $actualdevice = get_device_type();
2728 $currentdevice = $this->page->devicetypeinuse;
2729 $switched = ($actualdevice != $currentdevice);
2731 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
2732 // The user is using the a default device and hasn't switched so don't shown the switch
2733 // device links.
2734 return '';
2737 if ($switched) {
2738 $linktext = get_string('switchdevicerecommended');
2739 $devicetype = $actualdevice;
2740 } else {
2741 $linktext = get_string('switchdevicedefault');
2742 $devicetype = 'default';
2744 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
2746 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
2747 $content .= html_writer::link($linkurl, $linktext);
2748 $content .= html_writer::end_tag('div');
2750 return $content;
2755 * A renderer that generates output for command-line scripts.
2757 * The implementation of this renderer is probably incomplete.
2759 * @copyright 2009 Tim Hunt
2760 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2761 * @since Moodle 2.0
2762 * @package core
2763 * @category output
2765 class core_renderer_cli extends core_renderer {
2768 * Returns the page header.
2770 * @return string HTML fragment
2772 public function header() {
2773 return $this->page->heading . "\n";
2777 * Returns a template fragment representing a Heading.
2779 * @param string $text The text of the heading
2780 * @param int $level The level of importance of the heading
2781 * @param string $classes A space-separated list of CSS classes
2782 * @param string $id An optional ID
2783 * @return string A template fragment for a heading
2785 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2786 $text .= "\n";
2787 switch ($level) {
2788 case 1:
2789 return '=>' . $text;
2790 case 2:
2791 return '-->' . $text;
2792 default:
2793 return $text;
2798 * Returns a template fragment representing a fatal error.
2800 * @param string $message The message to output
2801 * @param string $moreinfourl URL where more info can be found about the error
2802 * @param string $link Link for the Continue button
2803 * @param array $backtrace The execution backtrace
2804 * @param string $debuginfo Debugging information
2805 * @return string A template fragment for a fatal error
2807 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2808 $output = "!!! $message !!!\n";
2810 if (debugging('', DEBUG_DEVELOPER)) {
2811 if (!empty($debuginfo)) {
2812 $output .= $this->notification($debuginfo, 'notifytiny');
2814 if (!empty($backtrace)) {
2815 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
2819 return $output;
2823 * Returns a template fragment representing a notification.
2825 * @param string $message The message to include
2826 * @param string $classes A space-separated list of CSS classes
2827 * @return string A template fragment for a notification
2829 public function notification($message, $classes = 'notifyproblem') {
2830 $message = clean_text($message);
2831 if ($classes === 'notifysuccess') {
2832 return "++ $message ++\n";
2834 return "!! $message !!\n";
2840 * A renderer that generates output for ajax scripts.
2842 * This renderer prevents accidental sends back only json
2843 * encoded error messages, all other output is ignored.
2845 * @copyright 2010 Petr Skoda
2846 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2847 * @since Moodle 2.0
2848 * @package core
2849 * @category output
2851 class core_renderer_ajax extends core_renderer {
2854 * Returns a template fragment representing a fatal error.
2856 * @param string $message The message to output
2857 * @param string $moreinfourl URL where more info can be found about the error
2858 * @param string $link Link for the Continue button
2859 * @param array $backtrace The execution backtrace
2860 * @param string $debuginfo Debugging information
2861 * @return string A template fragment for a fatal error
2863 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2864 global $CFG;
2866 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2868 $e = new stdClass();
2869 $e->error = $message;
2870 $e->stacktrace = NULL;
2871 $e->debuginfo = NULL;
2872 $e->reproductionlink = NULL;
2873 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
2874 $e->reproductionlink = $link;
2875 if (!empty($debuginfo)) {
2876 $e->debuginfo = $debuginfo;
2878 if (!empty($backtrace)) {
2879 $e->stacktrace = format_backtrace($backtrace, true);
2882 $this->header();
2883 return json_encode($e);
2887 * Used to display a notification.
2888 * For the AJAX notifications are discarded.
2890 * @param string $message
2891 * @param string $classes
2893 public function notification($message, $classes = 'notifyproblem') {}
2896 * Used to display a redirection message.
2897 * AJAX redirections should not occur and as such redirection messages
2898 * are discarded.
2900 * @param moodle_url|string $encodedurl
2901 * @param string $message
2902 * @param int $delay
2903 * @param bool $debugdisableredirect
2905 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
2908 * Prepares the start of an AJAX output.
2910 public function header() {
2911 // unfortunately YUI iframe upload does not support application/json
2912 if (!empty($_FILES)) {
2913 @header('Content-type: text/plain; charset=utf-8');
2914 } else {
2915 @header('Content-type: application/json; charset=utf-8');
2918 // Headers to make it not cacheable and json
2919 @header('Cache-Control: no-store, no-cache, must-revalidate');
2920 @header('Cache-Control: post-check=0, pre-check=0', false);
2921 @header('Pragma: no-cache');
2922 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2923 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2924 @header('Accept-Ranges: none');
2928 * There is no footer for an AJAX request, however we must override the
2929 * footer method to prevent the default footer.
2931 public function footer() {}
2934 * No need for headers in an AJAX request... this should never happen.
2935 * @param string $text
2936 * @param int $level
2937 * @param string $classes
2938 * @param string $id
2940 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
2945 * Renderer for media files.
2947 * Used in file resources, media filter, and any other places that need to
2948 * output embedded media.
2950 * @copyright 2011 The Open University
2951 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2953 class core_media_renderer extends plugin_renderer_base {
2954 /** @var array Array of available 'player' objects */
2955 private $players;
2956 /** @var string Regex pattern for links which may contain embeddable content */
2957 private $embeddablemarkers;
2960 * Constructor requires medialib.php.
2962 * This is needed in the constructor (not later) so that you can use the
2963 * constants and static functions that are defined in core_media class
2964 * before you call renderer functions.
2966 public function __construct() {
2967 global $CFG;
2968 require_once($CFG->libdir . '/medialib.php');
2972 * Obtains the list of core_media_player objects currently in use to render
2973 * items.
2975 * The list is in rank order (highest first) and does not include players
2976 * which are disabled.
2978 * @return array Array of core_media_player objects in rank order
2980 protected function get_players() {
2981 global $CFG;
2983 // Save time by only building the list once.
2984 if (!$this->players) {
2985 // Get raw list of players.
2986 $players = $this->get_players_raw();
2988 // Chuck all the ones that are disabled.
2989 foreach ($players as $key => $player) {
2990 if (!$player->is_enabled()) {
2991 unset($players[$key]);
2995 // Sort in rank order (highest first).
2996 usort($players, array('core_media_player', 'compare_by_rank'));
2997 $this->players = $players;
2999 return $this->players;
3003 * Obtains a raw list of player objects that includes objects regardless
3004 * of whether they are disabled or not, and without sorting.
3006 * You can override this in a subclass if you need to add additional
3007 * players.
3009 * The return array is be indexed by player name to make it easier to
3010 * remove players in a subclass.
3012 * @return array $players Array of core_media_player objects in any order
3014 protected function get_players_raw() {
3015 return array(
3016 'vimeo' => new core_media_player_vimeo(),
3017 'youtube' => new core_media_player_youtube(),
3018 'youtube_playlist' => new core_media_player_youtube_playlist(),
3019 'html5video' => new core_media_player_html5video(),
3020 'html5audio' => new core_media_player_html5audio(),
3021 'mp3' => new core_media_player_mp3(),
3022 'flv' => new core_media_player_flv(),
3023 'wmp' => new core_media_player_wmp(),
3024 'qt' => new core_media_player_qt(),
3025 'rm' => new core_media_player_rm(),
3026 'swf' => new core_media_player_swf(),
3027 'link' => new core_media_player_link(),
3032 * Renders a media file (audio or video) using suitable embedded player.
3034 * See embed_alternatives function for full description of parameters.
3035 * This function calls through to that one.
3037 * When using this function you can also specify width and height in the
3038 * URL by including ?d=100x100 at the end. If specified in the URL, this
3039 * will override the $width and $height parameters.
3041 * @param moodle_url $url Full URL of media file
3042 * @param string $name Optional user-readable name to display in download link
3043 * @param int $width Width in pixels (optional)
3044 * @param int $height Height in pixels (optional)
3045 * @param array $options Array of key/value pairs
3046 * @return string HTML content of embed
3048 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
3049 $options = array()) {
3051 // Get width and height from URL if specified (overrides parameters in
3052 // function call).
3053 $rawurl = $url->out(false);
3054 if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
3055 $width = $matches[1];
3056 $height = $matches[2];
3057 $url = new moodle_url(str_replace($matches[0], '', $rawurl));
3060 // Defer to array version of function.
3061 return $this->embed_alternatives(array($url), $name, $width, $height, $options);
3065 * Renders media files (audio or video) using suitable embedded player.
3066 * The list of URLs should be alternative versions of the same content in
3067 * multiple formats. If there is only one format it should have a single
3068 * entry.
3070 * If the media files are not in a supported format, this will give students
3071 * a download link to each format. The download link uses the filename
3072 * unless you supply the optional name parameter.
3074 * Width and height are optional. If specified, these are suggested sizes
3075 * and should be the exact values supplied by the user, if they come from
3076 * user input. These will be treated as relating to the size of the video
3077 * content, not including any player control bar.
3079 * For audio files, height will be ignored. For video files, a few formats
3080 * work if you specify only width, but in general if you specify width
3081 * you must specify height as well.
3083 * The $options array is passed through to the core_media_player classes
3084 * that render the object tag. The keys can contain values from
3085 * core_media::OPTION_xx.
3087 * @param array $alternatives Array of moodle_url to media files
3088 * @param string $name Optional user-readable name to display in download link
3089 * @param int $width Width in pixels (optional)
3090 * @param int $height Height in pixels (optional)
3091 * @param array $options Array of key/value pairs
3092 * @return string HTML content of embed
3094 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
3095 $options = array()) {
3097 // Get list of player plugins (will also require the library).
3098 $players = $this->get_players();
3100 // Set up initial text which will be replaced by first player that
3101 // supports any of the formats.
3102 $out = core_media_player::PLACEHOLDER;
3104 // Loop through all players that support any of these URLs.
3105 foreach ($players as $player) {
3106 // Option: When no other player matched, don't do the default link player.
3107 if (!empty($options[core_media::OPTION_FALLBACK_TO_BLANK]) &&
3108 $player->get_rank() === 0 && $out === core_media_player::PLACEHOLDER) {
3109 continue;
3112 $supported = $player->list_supported_urls($alternatives, $options);
3113 if ($supported) {
3114 // Embed.
3115 $text = $player->embed($supported, $name, $width, $height, $options);
3117 // Put this in place of the 'fallback' slot in the previous text.
3118 $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
3122 // Remove 'fallback' slot from final version and return it.
3123 $out = str_replace(core_media_player::PLACEHOLDER, '', $out);
3124 if (!empty($options[core_media::OPTION_BLOCK]) && $out !== '') {
3125 $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
3127 return $out;
3131 * Checks whether a file can be embedded. If this returns true you will get
3132 * an embedded player; if this returns false, you will just get a download
3133 * link.
3135 * This is a wrapper for can_embed_urls.
3137 * @param moodle_url $url URL of media file
3138 * @param array $options Options (same as when embedding)
3139 * @return bool True if file can be embedded
3141 public function can_embed_url(moodle_url $url, $options = array()) {
3142 return $this->can_embed_urls(array($url), $options);
3146 * Checks whether a file can be embedded. If this returns true you will get
3147 * an embedded player; if this returns false, you will just get a download
3148 * link.
3150 * @param array $urls URL of media file and any alternatives (moodle_url)
3151 * @param array $options Options (same as when embedding)
3152 * @return bool True if file can be embedded
3154 public function can_embed_urls(array $urls, $options = array()) {
3155 // Check all players to see if any of them support it.
3156 foreach ($this->get_players() as $player) {
3157 // Link player (always last on list) doesn't count!
3158 if ($player->get_rank() <= 0) {
3159 break;
3161 // First player that supports it, return true.
3162 if ($player->list_supported_urls($urls, $options)) {
3163 return true;
3166 return false;
3170 * Obtains a list of markers that can be used in a regular expression when
3171 * searching for URLs that can be embedded by any player type.
3173 * This string is used to improve peformance of regex matching by ensuring
3174 * that the (presumably C) regex code can do a quick keyword check on the
3175 * URL part of a link to see if it matches one of these, rather than having
3176 * to go into PHP code for every single link to see if it can be embedded.
3178 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
3180 public function get_embeddable_markers() {
3181 if (empty($this->embeddablemarkers)) {
3182 $markers = '';
3183 foreach ($this->get_players() as $player) {
3184 foreach ($player->get_embeddable_markers() as $marker) {
3185 if ($markers !== '') {
3186 $markers .= '|';
3188 $markers .= preg_quote($marker);
3191 $this->embeddablemarkers = $markers;
3193 return $this->embeddablemarkers;