2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
23 * Included in this file are the primary renderer classes:
24 * - renderer_base: The renderer outline class that all renderers
25 * should inherit from.
26 * - core_renderer: The standard HTML renderer.
27 * - core_renderer_cli: An adaption of the standard renderer for CLI scripts.
28 * - core_renderer_ajax: An adaption of the standard renderer for AJAX scripts.
29 * - plugin_renderer_base: A renderer class that should be extended by all
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') ||
die();
41 * Simple base class for Moodle renderers.
43 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
45 * Also has methods to facilitate generating HTML output.
47 * @copyright 2009 Tim Hunt
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
65 * @var string The requested rendering target.
72 * The constructor takes two arguments. The first is the page that the renderer
73 * has been created to assist with, and the second is the target.
74 * The target is an additional identifier that can be used to load different
75 * renderers for different options.
77 * @param moodle_page $page the page we are doing output for.
78 * @param string $target one of rendering target constants
80 public function __construct(moodle_page
$page, $target) {
81 $this->opencontainers
= $page->opencontainers
;
83 $this->target
= $target;
87 * Returns rendered widget.
89 * The provided widget needs to be an object that extends the renderable
91 * If will then be rendered by a method based upon the classname for the widget.
92 * For instance a widget of class `crazywidget` will be rendered by a protected
93 * render_crazywidget method of this renderer.
95 * @param renderable $widget instance with renderable interface
98 public function render(renderable
$widget) {
99 $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
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) {
119 $id = html_writer
::random_id($action->event
);
121 $this->page
->requires
->event_handler("#$id", $action->event
, $action->jsfunction
, $action->jsfunctionargs
);
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));
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'
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
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}
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
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
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);
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
251 class core_renderer
extends renderer_base
{
253 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
254 * in layout files instead.
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;
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
;
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() {
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
)) {
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";
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
352 * @return string HTML fragment.
354 public function standard_head_html() {
355 global $CFG, $SESSION;
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));
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
;
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() {
433 $output = $this->page
->requires
->get_top_of_body_code();
434 if (!empty($CFG->additionalhtmltopofbody
)) {
435 $output .= "\n".$CFG->additionalhtmltopofbody
;
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&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&ss=1&uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
480 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
481 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&warnp2n3e=1&url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
484 if (!empty($CFG->additionalhtmlfooter
)) {
485 $output .= "\n".$CFG->additionalhtmlfooter
;
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()) {
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 $loginastitle = get_string('loginas');
533 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&sesskey=".sesskey()."\"";
534 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
539 $loginurl = get_login_url();
541 if (empty($course->id
)) {
542 // $course->id is not defined during installation
544 } else if (isloggedin()) {
545 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
547 $fullname = fullname($USER, true);
548 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
549 $linktitle = get_string('viewprofile');
550 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
551 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid
))) {
552 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
555 $loggedinas = $realuserinfo.get_string('loggedinasguest');
557 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
559 } else if (is_role_switched($course->id
)) { // Has switched roles
561 if ($role = $DB->get_record('role', array('id'=>$USER->access
['rsw'][$context->path
]))) {
562 $rolename = ': '.format_string($role->name
);
564 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
565 " (<a href=\"$CFG->wwwroot/course/view.php?id=$course->id&switchrole=0&sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
567 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
568 " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
571 $loggedinas = get_string('loggedinnot', 'moodle');
573 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
577 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
579 if (isset($SESSION->justloggedin
)) {
580 unset($SESSION->justloggedin
);
581 if (!empty($CFG->displayloginfailures
)) {
582 if (!isguestuser()) {
583 if ($count = count_login_failures($CFG->displayloginfailures
, $USER->username
, $USER->lastlogin
)) {
584 $loggedinas .= ' <div class="loginfailures">';
585 if (empty($count->accounts
)) {
586 $loggedinas .= get_string('failedloginattempts', '', $count);
588 $loggedinas .= get_string('failedloginattemptsall', '', $count);
590 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', get_context_instance(CONTEXT_SYSTEM
))) {
591 $loggedinas .= ' (<a href="'.$CFG->wwwroot
.'/report/log/index.php'.
592 '?chooselog=1&id=1&modid=site_errors">'.get_string('logs').'</a>)';
594 $loggedinas .= '</div>';
604 * Return the 'back' link that normally appears in the footer.
606 * @return string HTML fragment.
608 public function home_link() {
611 if ($this->page
->pagetype
== 'site-index') {
612 // Special case for site home page - please do not remove
613 return '<div class="sitelink">' .
614 '<a title="Moodle" href="http://moodle.org/">' .
615 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
617 } else if (!empty($CFG->target_release
) && $CFG->target_release
!= $CFG->release
) {
618 // Special case for during install/upgrade.
619 return '<div class="sitelink">'.
620 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
621 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
623 } else if ($this->page
->course
->id
== $SITE->id ||
strpos($this->page
->pagetype
, 'course-view') === 0) {
624 return '<div class="homelink"><a href="' . $CFG->wwwroot
. '/">' .
625 get_string('home') . '</a></div>';
628 return '<div class="homelink"><a href="' . $CFG->wwwroot
. '/course/view.php?id=' . $this->page
->course
->id
. '">' .
629 format_string($this->page
->course
->shortname
, true, array('context' => $this->page
->context
)) . '</a></div>';
634 * Redirects the user by any means possible given the current state
636 * This function should not be called directly, it should always be called using
637 * the redirect function in lib/weblib.php
639 * The redirect function should really only be called before page output has started
640 * however it will allow itself to be called during the state STATE_IN_BODY
642 * @param string $encodedurl The URL to send to encoded if required
643 * @param string $message The message to display to the user if any
644 * @param int $delay The delay before redirecting a user, if $message has been
645 * set this is a requirement and defaults to 3, set to 0 no delay
646 * @param boolean $debugdisableredirect this redirect has been disabled for
647 * debugging purposes. Display a message that explains, and don't
648 * trigger the redirect.
649 * @return string The HTML to display to the user before dying, may contain
650 * meta refresh, javascript refresh, and may have set header redirects
652 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
654 $url = str_replace('&', '&', $encodedurl);
656 switch ($this->page
->state
) {
657 case moodle_page
::STATE_BEFORE_HEADER
:
658 // No output yet it is safe to delivery the full arsenal of redirect methods
659 if (!$debugdisableredirect) {
660 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
661 $this->metarefreshtag
= '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
662 $this->page
->requires
->js_function_call('document.location.replace', array($url), false, ($delay +
3));
664 $output = $this->header();
666 case moodle_page
::STATE_PRINTING_HEADER
:
667 // We should hopefully never get here
668 throw new coding_exception('You cannot redirect while printing the page header');
670 case moodle_page
::STATE_IN_BODY
:
671 // We really shouldn't be here but we can deal with this
672 debugging("You should really redirect before you start page output");
673 if (!$debugdisableredirect) {
674 $this->page
->requires
->js_function_call('document.location.replace', array($url), false, $delay);
676 $output = $this->opencontainers
->pop_all_but_last();
678 case moodle_page
::STATE_DONE
:
679 // Too late to be calling redirect now
680 throw new coding_exception('You cannot redirect after the entire page has been generated');
683 $output .= $this->notification($message, 'redirectmessage');
684 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
685 if ($debugdisableredirect) {
686 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
688 $output .= $this->footer();
693 * Start output by sending the HTTP headers, and printing the HTML <head>
694 * and the start of the <body>.
696 * To control what is printed, you should set properties on $PAGE. If you
697 * are familiar with the old {@link print_header()} function from Moodle 1.9
698 * you will find that there are properties on $PAGE that correspond to most
699 * of the old parameters to could be passed to print_header.
701 * Not that, in due course, the remaining $navigation, $menu parameters here
702 * will be replaced by more properties of $PAGE, but that is still to do.
704 * @return string HTML that you must output this, preferably immediately.
706 public function header() {
709 if (session_is_loggedinas()) {
710 $this->page
->add_body_class('userloggedinas');
713 $this->page
->set_state(moodle_page
::STATE_PRINTING_HEADER
);
715 // Find the appropriate page layout file, based on $this->page->pagelayout.
716 $layoutfile = $this->page
->theme
->layout_file($this->page
->pagelayout
);
717 // Render the layout using the layout file.
718 $rendered = $this->render_page_layout($layoutfile);
720 // Slice the rendered output into header and footer.
721 $cutpos = strpos($rendered, $this->unique_main_content_token
);
722 if ($cutpos === false) {
723 $cutpos = strpos($rendered, self
::MAIN_CONTENT_TOKEN
);
724 $token = self
::MAIN_CONTENT_TOKEN
;
726 $token = $this->unique_main_content_token
;
729 if ($cutpos === false) {
730 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.');
732 $header = substr($rendered, 0, $cutpos);
733 $footer = substr($rendered, $cutpos +
strlen($token));
735 if (empty($this->contenttype
)) {
736 debugging('The page layout file did not call $OUTPUT->doctype()');
737 $header = $this->doctype() . $header;
740 send_headers($this->contenttype
, $this->page
->cacheable
);
742 $this->opencontainers
->push('header/footer', $footer);
743 $this->page
->set_state(moodle_page
::STATE_IN_BODY
);
745 return $header . $this->skip_link_target('maincontent');
749 * Renders and outputs the page layout file.
751 * This is done by preparing the normal globals available to a script, and
752 * then including the layout file provided by the current theme for the
755 * @param string $layoutfile The name of the layout file
756 * @return string HTML code
758 protected function render_page_layout($layoutfile) {
759 global $CFG, $SITE, $USER;
760 // The next lines are a bit tricky. The point is, here we are in a method
761 // of a renderer class, and this object may, or may not, be the same as
762 // the global $OUTPUT object. When rendering the page layout file, we want to use
763 // this object. However, people writing Moodle code expect the current
764 // renderer to be called $OUTPUT, not $this, so define a variable called
765 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
768 $COURSE = $this->page
->course
;
771 include($layoutfile);
772 $rendered = ob_get_contents();
778 * Outputs the page's footer
780 * @return string HTML fragment
782 public function footer() {
785 $output = $this->container_end_all(true);
787 $footer = $this->opencontainers
->pop('header/footer');
789 if (debugging() and $DB and $DB->is_transaction_started()) {
790 // TODO: MDL-20625 print warning - transaction will be rolled back
793 // Provide some performance info if required
794 $performanceinfo = '';
795 if (defined('MDL_PERF') ||
(!empty($CFG->perfdebug
) and $CFG->perfdebug
> 7)) {
796 $perf = get_performance_info();
797 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
798 error_log("PERF: " . $perf['txt']);
800 if (defined('MDL_PERFTOFOOT') ||
debugging() ||
$CFG->perfdebug
> 7) {
801 $performanceinfo = $perf['html'];
804 $footer = str_replace($this->unique_performance_info_token
, $performanceinfo, $footer);
806 $footer = str_replace($this->unique_end_html_token
, $this->page
->requires
->get_end_code(), $footer);
808 $this->page
->set_state(moodle_page
::STATE_DONE
);
810 return $output . $footer;
814 * Close all but the last open container. This is useful in places like error
815 * handling, where you want to close all the open containers (apart from <body>)
816 * before outputting the error message.
818 * @param bool $shouldbenone assert that the stack should be empty now - causes a
819 * developer debug warning if it isn't.
820 * @return string the HTML required to close any open containers inside <body>.
822 public function container_end_all($shouldbenone = false) {
823 return $this->opencontainers
->pop_all_but_last($shouldbenone);
827 * Returns lang menu or '', this method also checks forcing of languages in courses.
829 * @return string The lang menu HTML or empty string
831 public function lang_menu() {
834 if (empty($CFG->langmenu
)) {
838 if ($this->page
->course
!= SITEID
and !empty($this->page
->course
->lang
)) {
839 // do not show lang menu if language forced
843 $currlang = current_language();
844 $langs = get_string_manager()->get_list_of_translations();
846 if (count($langs) < 2) {
850 $s = new single_select($this->page
->url
, 'lang', $langs, $currlang, null);
851 $s->label
= get_accesshide(get_string('language'));
852 $s->class = 'langmenu';
853 return $this->render($s);
857 * Output the row of editing icons for a block, as defined by the controls array.
859 * @param array $controls an array like {@link block_contents::$controls}.
860 * @return string HTML fragment.
862 public function block_controls($controls) {
863 if (empty($controls)) {
866 $controlshtml = array();
867 foreach ($controls as $control) {
868 $controlshtml[] = html_writer
::tag('a',
869 html_writer
::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
870 array('class' => 'icon ' . $control['class'],'title' => $control['caption'], 'href' => $control['url']));
872 return html_writer
::tag('div', implode('', $controlshtml), array('class' => 'commands'));
876 * Prints a nice side block with an optional header.
878 * The content is described
879 * by a {@link core_renderer::block_contents} object.
881 * <div id="inst{$instanceid}" class="block_{$blockname} block">
882 * <div class="header"></div>
883 * <div class="content">
885 * <div class="footer">
888 * <div class="annotation">
892 * @param block_contents $bc HTML for the content
893 * @param string $region the region the block is appearing in.
894 * @return string the HTML to be output.
896 public function block(block_contents
$bc, $region) {
897 $bc = clone($bc); // Avoid messing up the object passed in.
898 if (empty($bc->blockinstanceid
) ||
!strip_tags($bc->title
)) {
899 $bc->collapsible
= block_contents
::NOT_HIDEABLE
;
901 if ($bc->collapsible
== block_contents
::HIDDEN
) {
902 $bc->add_class('hidden');
904 if (!empty($bc->controls
)) {
905 $bc->add_class('block_with_controls');
908 $skiptitle = strip_tags($bc->title
);
909 if (empty($skiptitle)) {
913 $output = html_writer
::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid
, 'class' => 'skip-block'));
914 $skipdest = html_writer
::tag('span', '', array('id' => 'sb-' . $bc->skipid
, 'class' => 'skip-block-to'));
917 $output .= html_writer
::start_tag('div', $bc->attributes
);
919 $output .= $this->block_header($bc);
920 $output .= $this->block_content($bc);
922 $output .= html_writer
::end_tag('div');
924 $output .= $this->block_annotation($bc);
926 $output .= $skipdest;
928 $this->init_block_hider_js($bc);
933 * Produces a header for a block
935 * @param block_contents $bc
938 protected function block_header(block_contents
$bc) {
942 $title = html_writer
::tag('h2', $bc->title
, null);
945 $controlshtml = $this->block_controls($bc->controls
);
948 if ($title ||
$controlshtml) {
949 $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'));
955 * Produces the content area for a block
957 * @param block_contents $bc
960 protected function block_content(block_contents
$bc) {
961 $output = html_writer
::start_tag('div', array('class' => 'content'));
962 if (!$bc->title
&& !$this->block_controls($bc->controls
)) {
963 $output .= html_writer
::tag('div', '', array('class'=>'block_action notitle'));
965 $output .= $bc->content
;
966 $output .= $this->block_footer($bc);
967 $output .= html_writer
::end_tag('div');
973 * Produces the footer for a block
975 * @param block_contents $bc
978 protected function block_footer(block_contents
$bc) {
981 $output .= html_writer
::tag('div', $bc->footer
, array('class' => 'footer'));
987 * Produces the annotation for a block
989 * @param block_contents $bc
992 protected function block_annotation(block_contents
$bc) {
994 if ($bc->annotation
) {
995 $output .= html_writer
::tag('div', $bc->annotation
, array('class' => 'blockannotation'));
1001 * Calls the JS require function to hide a block.
1003 * @param block_contents $bc A block_contents object
1005 protected function init_block_hider_js(block_contents
$bc) {
1006 if (!empty($bc->attributes
['id']) and $bc->collapsible
!= block_contents
::NOT_HIDEABLE
) {
1007 $config = new stdClass
;
1008 $config->id
= $bc->attributes
['id'];
1009 $config->title
= strip_tags($bc->title
);
1010 $config->preference
= 'block' . $bc->blockinstanceid
. 'hidden';
1011 $config->tooltipVisible
= get_string('hideblocka', 'access', $config->title
);
1012 $config->tooltipHidden
= get_string('showblocka', 'access', $config->title
);
1014 $this->page
->requires
->js_init_call('M.util.init_block_hider', array($config));
1015 user_preference_allow_ajax_update($config->preference
, PARAM_BOOL
);
1020 * Render the contents of a block_list.
1022 * @param array $icons the icon for each item.
1023 * @param array $items the content of each item.
1024 * @return string HTML
1026 public function list_block_contents($icons, $items) {
1029 foreach ($items as $key => $string) {
1030 $item = html_writer
::start_tag('li', array('class' => 'r' . $row));
1031 if (!empty($icons[$key])) { //test if the content has an assigned icon
1032 $item .= html_writer
::tag('div', $icons[$key], array('class' => 'icon column c0'));
1034 $item .= html_writer
::tag('div', $string, array('class' => 'column c1'));
1035 $item .= html_writer
::end_tag('li');
1037 $row = 1 - $row; // Flip even/odd.
1039 return html_writer
::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1043 * Output all the blocks in a particular region.
1045 * @param string $region the name of a region on this page.
1046 * @return string the HTML to be output.
1048 public function blocks_for_region($region) {
1049 $blockcontents = $this->page
->blocks
->get_content_for_region($region, $this);
1052 foreach ($blockcontents as $bc) {
1053 if ($bc instanceof block_contents
) {
1054 $output .= $this->block($bc, $region);
1055 } else if ($bc instanceof block_move_target
) {
1056 $output .= $this->block_move_target($bc);
1058 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1065 * Output a place where the block that is currently being moved can be dropped.
1067 * @param block_move_target $target with the necessary details.
1068 * @return string the HTML to be output.
1070 public function block_move_target($target) {
1071 return html_writer
::tag('a', html_writer
::tag('span', $target->text
, array('class' => 'accesshide')), array('href' => $target->url
, 'class' => 'blockmovetarget'));
1075 * Renders a special html link with attached action
1077 * @param string|moodle_url $url
1078 * @param string $text HTML fragment
1079 * @param component_action $action
1080 * @param array $attributes associative array of html link attributes + disabled
1081 * @return string HTML fragment
1083 public function action_link($url, $text, component_action
$action = null, array $attributes=null) {
1084 if (!($url instanceof moodle_url
)) {
1085 $url = new moodle_url($url);
1087 $link = new action_link($url, $text, $action, $attributes);
1089 return $this->render($link);
1093 * Renders an action_link object.
1095 * The provided link is renderer and the HTML returned. At the same time the
1096 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1098 * @param action_link $link
1099 * @return string HTML fragment
1101 protected function render_action_link(action_link
$link) {
1104 if ($link->text
instanceof renderable
) {
1105 $text = $this->render($link->text
);
1107 $text = $link->text
;
1110 // A disabled link is rendered as formatted text
1111 if (!empty($link->attributes
['disabled'])) {
1112 // do not use div here due to nesting restriction in xhtml strict
1113 return html_writer
::tag('span', $text, array('class'=>'currentlink'));
1116 $attributes = $link->attributes
;
1117 unset($link->attributes
['disabled']);
1118 $attributes['href'] = $link->url
;
1120 if ($link->actions
) {
1121 if (empty($attributes['id'])) {
1122 $id = html_writer
::random_id('action_link');
1123 $attributes['id'] = $id;
1125 $id = $attributes['id'];
1127 foreach ($link->actions
as $action) {
1128 $this->add_action_handler($action, $id);
1132 return html_writer
::tag('a', $text, $attributes);
1137 * Renders an action_icon.
1139 * This function uses the {@link core_renderer::action_link()} method for the
1140 * most part. What it does different is prepare the icon as HTML and use it
1143 * @param string|moodle_url $url A string URL or moodel_url
1144 * @param pix_icon $pixicon
1145 * @param component_action $action
1146 * @param array $attributes associative array of html link attributes + disabled
1147 * @param bool $linktext show title next to image in link
1148 * @return string HTML fragment
1150 public function action_icon($url, pix_icon
$pixicon, component_action
$action = null, array $attributes = null, $linktext=false) {
1151 if (!($url instanceof moodle_url
)) {
1152 $url = new moodle_url($url);
1154 $attributes = (array)$attributes;
1156 if (empty($attributes['class'])) {
1157 // let ppl override the class via $options
1158 $attributes['class'] = 'action-icon';
1161 $icon = $this->render($pixicon);
1164 $text = $pixicon->attributes
['alt'];
1169 return $this->action_link($url, $text.$icon, $action, $attributes);
1173 * Print a message along with button choices for Continue/Cancel
1175 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1177 * @param string $message The question to ask the user
1178 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1179 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1180 * @return string HTML fragment
1182 public function confirm($message, $continue, $cancel) {
1183 if ($continue instanceof single_button
) {
1185 } else if (is_string($continue)) {
1186 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1187 } else if ($continue instanceof moodle_url
) {
1188 $continue = new single_button($continue, get_string('continue'), 'post');
1190 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1193 if ($cancel instanceof single_button
) {
1195 } else if (is_string($cancel)) {
1196 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1197 } else if ($cancel instanceof moodle_url
) {
1198 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1200 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1203 $output = $this->box_start('generalbox', 'notice');
1204 $output .= html_writer
::tag('p', $message);
1205 $output .= html_writer
::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1206 $output .= $this->box_end();
1211 * Returns a form with a single button.
1213 * @param string|moodle_url $url
1214 * @param string $label button text
1215 * @param string $method get or post submit method
1216 * @param array $options associative array {disabled, title, etc.}
1217 * @return string HTML fragment
1219 public function single_button($url, $label, $method='post', array $options=null) {
1220 if (!($url instanceof moodle_url
)) {
1221 $url = new moodle_url($url);
1223 $button = new single_button($url, $label, $method);
1225 foreach ((array)$options as $key=>$value) {
1226 if (array_key_exists($key, $button)) {
1227 $button->$key = $value;
1231 return $this->render($button);
1235 * Renders a single button widget.
1237 * This will return HTML to display a form containing a single button.
1239 * @param single_button $button
1240 * @return string HTML fragment
1242 protected function render_single_button(single_button
$button) {
1243 $attributes = array('type' => 'submit',
1244 'value' => $button->label
,
1245 'disabled' => $button->disabled ?
'disabled' : null,
1246 'title' => $button->tooltip
);
1248 if ($button->actions
) {
1249 $id = html_writer
::random_id('single_button');
1250 $attributes['id'] = $id;
1251 foreach ($button->actions
as $action) {
1252 $this->add_action_handler($action, $id);
1256 // first the input element
1257 $output = html_writer
::empty_tag('input', $attributes);
1259 // then hidden fields
1260 $params = $button->url
->params();
1261 if ($button->method
=== 'post') {
1262 $params['sesskey'] = sesskey();
1264 foreach ($params as $var => $val) {
1265 $output .= html_writer
::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1268 // then div wrapper for xhtml strictness
1269 $output = html_writer
::tag('div', $output);
1271 // now the form itself around it
1272 if ($button->method
=== 'get') {
1273 $url = $button->url
->out_omit_querystring(true); // url without params, the anchor part allowed
1275 $url = $button->url
->out_omit_querystring(); // url without params, the anchor part not allowed
1278 $url = '#'; // there has to be always some action
1280 $attributes = array('method' => $button->method
,
1282 'id' => $button->formid
);
1283 $output = html_writer
::tag('form', $output, $attributes);
1285 // and finally one more wrapper with class
1286 return html_writer
::tag('div', $output, array('class' => $button->class));
1290 * Returns a form with a single select widget.
1292 * @param moodle_url $url form action target, includes hidden fields
1293 * @param string $name name of selection field - the changing parameter in url
1294 * @param array $options list of options
1295 * @param string $selected selected element
1296 * @param array $nothing
1297 * @param string $formid
1298 * @return string HTML fragment
1300 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1301 if (!($url instanceof moodle_url
)) {
1302 $url = new moodle_url($url);
1304 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1306 return $this->render($select);
1310 * Internal implementation of single_select rendering
1312 * @param single_select $select
1313 * @return string HTML fragment
1315 protected function render_single_select(single_select
$select) {
1316 $select = clone($select);
1317 if (empty($select->formid
)) {
1318 $select->formid
= html_writer
::random_id('single_select_f');
1322 $params = $select->url
->params();
1323 if ($select->method
=== 'post') {
1324 $params['sesskey'] = sesskey();
1326 foreach ($params as $name=>$value) {
1327 $output .= html_writer
::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1330 if (empty($select->attributes
['id'])) {
1331 $select->attributes
['id'] = html_writer
::random_id('single_select');
1334 if ($select->disabled
) {
1335 $select->attributes
['disabled'] = 'disabled';
1338 if ($select->tooltip
) {
1339 $select->attributes
['title'] = $select->tooltip
;
1342 $select->attributes
['class'] = 'autosubmit';
1343 if ($select->class) {
1344 $select->attributes
['class'] .= ' ' . $select->class;
1347 if ($select->label
) {
1348 $output .= html_writer
::label($select->label
, $select->attributes
['id'], false, $select->labelattributes
);
1351 if ($select->helpicon
instanceof help_icon
) {
1352 $output .= $this->render($select->helpicon
);
1353 } else if ($select->helpicon
instanceof old_help_icon
) {
1354 $output .= $this->render($select->helpicon
);
1356 $output .= html_writer
::select($select->options
, $select->name
, $select->selected
, $select->nothing
, $select->attributes
);
1358 $go = html_writer
::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1359 $output .= html_writer
::tag('noscript', html_writer
::tag('div', $go), array('style'=>'inline'));
1361 $nothing = empty($select->nothing
) ?
false : key($select->nothing
);
1362 $this->page
->requires
->yui_module('moodle-core-formautosubmit',
1363 'M.core.init_formautosubmit',
1364 array(array('selectid' => $select->attributes
['id'], 'nothing' => $nothing))
1367 // then div wrapper for xhtml strictness
1368 $output = html_writer
::tag('div', $output);
1370 // now the form itself around it
1371 if ($select->method
=== 'get') {
1372 $url = $select->url
->out_omit_querystring(true); // url without params, the anchor part allowed
1374 $url = $select->url
->out_omit_querystring(); // url without params, the anchor part not allowed
1376 $formattributes = array('method' => $select->method
,
1378 'id' => $select->formid
);
1379 $output = html_writer
::tag('form', $output, $formattributes);
1381 // and finally one more wrapper with class
1382 return html_writer
::tag('div', $output, array('class' => $select->class));
1386 * Returns a form with a url select widget.
1388 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1389 * @param string $selected selected element
1390 * @param array $nothing
1391 * @param string $formid
1392 * @return string HTML fragment
1394 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1395 $select = new url_select($urls, $selected, $nothing, $formid);
1396 return $this->render($select);
1400 * Internal implementation of url_select rendering
1402 * @param url_select $select
1403 * @return string HTML fragment
1405 protected function render_url_select(url_select
$select) {
1408 $select = clone($select);
1409 if (empty($select->formid
)) {
1410 $select->formid
= html_writer
::random_id('url_select_f');
1413 if (empty($select->attributes
['id'])) {
1414 $select->attributes
['id'] = html_writer
::random_id('url_select');
1417 if ($select->disabled
) {
1418 $select->attributes
['disabled'] = 'disabled';
1421 if ($select->tooltip
) {
1422 $select->attributes
['title'] = $select->tooltip
;
1427 if ($select->label
) {
1428 $output .= html_writer
::label($select->label
, $select->attributes
['id'], false, $select->labelattributes
);
1432 if (!$select->showbutton
) {
1433 $classes[] = 'autosubmit';
1435 if ($select->class) {
1436 $classes[] = $select->class;
1438 if (count($classes)) {
1439 $select->attributes
['class'] = implode(' ', $classes);
1442 if ($select->helpicon
instanceof help_icon
) {
1443 $output .= $this->render($select->helpicon
);
1444 } else if ($select->helpicon
instanceof old_help_icon
) {
1445 $output .= $this->render($select->helpicon
);
1448 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1449 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1451 foreach ($select->urls
as $k=>$v) {
1453 // optgroup structure
1454 foreach ($v as $optgrouptitle => $optgroupoptions) {
1455 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1456 if (empty($optionurl)) {
1457 $safeoptionurl = '';
1458 } else if (strpos($optionurl, $CFG->wwwroot
.'/') === 0) {
1459 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1460 $safeoptionurl = str_replace($CFG->wwwroot
, '', $optionurl);
1461 } else if (strpos($optionurl, '/') !== 0) {
1462 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1465 $safeoptionurl = $optionurl;
1467 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1471 // plain list structure
1473 // nothing selected option
1474 } else if (strpos($k, $CFG->wwwroot
.'/') === 0) {
1475 $k = str_replace($CFG->wwwroot
, '', $k);
1476 } else if (strpos($k, '/') !== 0) {
1477 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1483 $selected = $select->selected
;
1484 if (!empty($selected)) {
1485 if (strpos($select->selected
, $CFG->wwwroot
.'/') === 0) {
1486 $selected = str_replace($CFG->wwwroot
, '', $selected);
1487 } else if (strpos($selected, '/') !== 0) {
1488 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1492 $output .= html_writer
::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1493 $output .= html_writer
::select($urls, 'jump', $selected, $select->nothing
, $select->attributes
);
1495 if (!$select->showbutton
) {
1496 $go = html_writer
::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1497 $output .= html_writer
::tag('noscript', html_writer
::tag('div', $go), array('style'=>'inline'));
1498 $nothing = empty($select->nothing
) ?
false : key($select->nothing
);
1499 $this->page
->requires
->yui_module('moodle-core-formautosubmit',
1500 'M.core.init_formautosubmit',
1501 array(array('selectid' => $select->attributes
['id'], 'nothing' => $nothing))
1504 $output .= html_writer
::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton
));
1507 // then div wrapper for xhtml strictness
1508 $output = html_writer
::tag('div', $output);
1510 // now the form itself around it
1511 $formattributes = array('method' => 'post',
1512 'action' => new moodle_url('/course/jumpto.php'),
1513 'id' => $select->formid
);
1514 $output = html_writer
::tag('form', $output, $formattributes);
1516 // and finally one more wrapper with class
1517 return html_writer
::tag('div', $output, array('class' => $select->class));
1521 * Returns a string containing a link to the user documentation.
1522 * Also contains an icon by default. Shown to teachers and admin only.
1524 * @param string $path The page link after doc root and language, no leading slash.
1525 * @param string $text The text to be displayed for the link
1526 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
1529 public function doc_link($path, $text = '', $forcepopup = false) {
1532 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp'));
1534 $url = new moodle_url(get_docs_url($path));
1536 $attributes = array('href'=>$url);
1537 if (!empty($CFG->doctonewwindow
) ||
$forcepopup) {
1538 $attributes['class'] = 'helplinkpopup';
1541 return html_writer
::tag('a', $icon.$text, $attributes);
1545 * Return HTML for a pix_icon.
1547 * @param string $pix short pix name
1548 * @param string $alt mandatory alt attribute
1549 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1550 * @param array $attributes htm lattributes
1551 * @return string HTML fragment
1553 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1554 $icon = new pix_icon($pix, $alt, $component, $attributes);
1555 return $this->render($icon);
1559 * Renders a pix_icon widget and returns the HTML to display it.
1561 * @param pix_icon $icon
1562 * @return string HTML fragment
1564 protected function render_pix_icon(pix_icon
$icon) {
1565 $attributes = $icon->attributes
;
1566 $attributes['src'] = $this->pix_url($icon->pix
, $icon->component
);
1567 return html_writer
::empty_tag('img', $attributes);
1571 * Return HTML to display an emoticon icon.
1573 * @param pix_emoticon $emoticon
1574 * @return string HTML fragment
1576 protected function render_pix_emoticon(pix_emoticon
$emoticon) {
1577 $attributes = $emoticon->attributes
;
1578 $attributes['src'] = $this->pix_url($emoticon->pix
, $emoticon->component
);
1579 return html_writer
::empty_tag('img', $attributes);
1583 * Produces the html that represents this rating in the UI
1585 * @param rating $rating the page object on which this rating will appear
1588 function render_rating(rating
$rating) {
1591 if ($rating->settings
->aggregationmethod
== RATING_AGGREGATE_NONE
) {
1592 return null;//ratings are turned off
1595 $ratingmanager = new rating_manager();
1596 // Initialise the JavaScript so ratings can be done by AJAX.
1597 $ratingmanager->initialise_rating_javascript($this->page
);
1599 $strrate = get_string("rate", "rating");
1600 $ratinghtml = ''; //the string we'll return
1602 // permissions check - can they view the aggregate?
1603 if ($rating->user_can_view_aggregate()) {
1605 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings
->aggregationmethod
);
1606 $aggregatestr = $rating->get_aggregate_string();
1608 $aggregatehtml = html_writer
::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid
, 'class' => 'ratingaggregate')).' ';
1609 if ($rating->count
> 0) {
1610 $countstr = "({$rating->count})";
1614 $aggregatehtml .= html_writer
::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
1616 $ratinghtml .= html_writer
::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
1617 if ($rating->settings
->permissions
->viewall
&& $rating->settings
->pluginpermissions
->viewall
) {
1619 $nonpopuplink = $rating->get_view_ratings_url();
1620 $popuplink = $rating->get_view_ratings_url(true);
1622 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
1623 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
1625 $ratinghtml .= $aggregatehtml;
1630 // if the item doesn't belong to the current user, the user has permission to rate
1631 // and we're within the assessable period
1632 if ($rating->user_can_rate()) {
1634 $rateurl = $rating->get_rate_url();
1635 $inputs = $rateurl->params();
1637 //start the rating form
1639 'id' => "postrating{$rating->itemid}",
1640 'class' => 'postratingform',
1642 'action' => $rateurl->out_omit_querystring()
1644 $formstart = html_writer
::start_tag('form', $formattrs);
1645 $formstart .= html_writer
::start_tag('div', array('class' => 'ratingform'));
1647 // add the hidden inputs
1648 foreach ($inputs as $name => $value) {
1649 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
1650 $formstart .= html_writer
::empty_tag('input', $attributes);
1653 if (empty($ratinghtml)) {
1654 $ratinghtml .= $strrate.': ';
1656 $ratinghtml = $formstart.$ratinghtml;
1658 $scalearray = array(RATING_UNSET_RATING
=> $strrate.'...') +
$rating->settings
->scale
->scaleitems
;
1659 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid
);
1660 $ratinghtml .= html_writer
::label($rating->rating
, 'menurating'.$rating->itemid
, false, array('class' => 'accesshide'));
1661 $ratinghtml .= html_writer
::select($scalearray, 'rating', $rating->rating
, false, $scaleattrs);
1663 //output submit button
1664 $ratinghtml .= html_writer
::start_tag('span', array('class'=>"ratingsubmit"));
1666 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid
, 'value' => s(get_string('rate', 'rating')));
1667 $ratinghtml .= html_writer
::empty_tag('input', $attributes);
1669 if (!$rating->settings
->scale
->isnumeric
) {
1670 // If a global scale, try to find current course ID from the context
1671 if (empty($rating->settings
->scale
->courseid
) and $coursecontext = $rating->context
->get_course_context(false)) {
1672 $courseid = $coursecontext->instanceid
;
1674 $courseid = $rating->settings
->scale
->courseid
;
1676 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings
->scale
);
1678 $ratinghtml .= html_writer
::end_tag('span');
1679 $ratinghtml .= html_writer
::end_tag('div');
1680 $ratinghtml .= html_writer
::end_tag('form');
1687 * Centered heading with attached help button (same title text)
1688 * and optional icon attached.
1690 * @param string $text A heading text
1691 * @param string $helpidentifier The keyword that defines a help page
1692 * @param string $component component name
1693 * @param string|moodle_url $icon
1694 * @param string $iconalt icon alt text
1695 * @return string HTML fragment
1697 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '') {
1700 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
1704 if ($helpidentifier) {
1705 $help = $this->help_icon($helpidentifier, $component);
1708 return $this->heading($image.$text.$help, 2, 'main help');
1712 * Returns HTML to display a help icon.
1714 * @deprecated since Moodle 2.0
1715 * @param string $helpidentifier The keyword that defines a help page
1716 * @param string $title A descriptive text for accessibility only
1717 * @param string $component component name
1718 * @param string|bool $linktext true means use $title as link text, string means link text value
1719 * @return string HTML fragment
1721 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
1722 debugging('The method old_help_icon() is deprecated, please fix the code and use help_icon() method instead', DEBUG_DEVELOPER
);
1723 $icon = new old_help_icon($helpidentifier, $title, $component);
1724 if ($linktext === true) {
1725 $icon->linktext
= $title;
1726 } else if (!empty($linktext)) {
1727 $icon->linktext
= $linktext;
1729 return $this->render($icon);
1733 * Implementation of user image rendering.
1735 * @param old_help_icon $helpicon A help icon instance
1736 * @return string HTML fragment
1738 protected function render_old_help_icon(old_help_icon
$helpicon) {
1741 // first get the help image icon
1742 $src = $this->pix_url('help');
1744 if (empty($helpicon->linktext
)) {
1745 $alt = $helpicon->title
;
1747 $alt = get_string('helpwiththis');
1750 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1751 $output = html_writer
::empty_tag('img', $attributes);
1753 // add the link text if given
1754 if (!empty($helpicon->linktext
)) {
1755 // the spacing has to be done through CSS
1756 $output .= $helpicon->linktext
;
1759 // now create the link around it - we need https on loginhttps pages
1760 $url = new moodle_url($CFG->httpswwwroot
.'/help.php', array('component' => $helpicon->component
, 'identifier' => $helpicon->helpidentifier
, 'lang'=>current_language()));
1762 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1763 $title = get_string('helpprefix2', '', trim($helpicon->title
, ". \t"));
1765 $attributes = array('href'=>$url, 'title'=>$title, 'aria-haspopup' => 'true');
1766 $id = html_writer
::random_id('helpicon');
1767 $attributes['id'] = $id;
1768 $output = html_writer
::tag('a', $output, $attributes);
1770 $this->page
->requires
->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1771 $this->page
->requires
->string_for_js('close', 'form');
1774 return html_writer
::tag('span', $output, array('class' => 'helplink'));
1778 * Returns HTML to display a help icon.
1780 * @param string $identifier The keyword that defines a help page
1781 * @param string $component component name
1782 * @param string|bool $linktext true means use $title as link text, string means link text value
1783 * @return string HTML fragment
1785 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
1786 $icon = new help_icon($identifier, $component);
1787 $icon->diag_strings();
1788 if ($linktext === true) {
1789 $icon->linktext
= get_string($icon->identifier
, $icon->component
);
1790 } else if (!empty($linktext)) {
1791 $icon->linktext
= $linktext;
1793 return $this->render($icon);
1797 * Implementation of user image rendering.
1799 * @param help_icon $helpicon A help icon instance
1800 * @return string HTML fragment
1802 protected function render_help_icon(help_icon
$helpicon) {
1805 // first get the help image icon
1806 $src = $this->pix_url('help');
1808 $title = get_string($helpicon->identifier
, $helpicon->component
);
1810 if (empty($helpicon->linktext
)) {
1811 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
1813 $alt = get_string('helpwiththis');
1816 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1817 $output = html_writer
::empty_tag('img', $attributes);
1819 // add the link text if given
1820 if (!empty($helpicon->linktext
)) {
1821 // the spacing has to be done through CSS
1822 $output .= $helpicon->linktext
;
1825 // now create the link around it - we need https on loginhttps pages
1826 $url = new moodle_url($CFG->httpswwwroot
.'/help.php', array('component' => $helpicon->component
, 'identifier' => $helpicon->identifier
, 'lang'=>current_language()));
1828 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1829 $title = get_string('helpprefix2', '', trim($title, ". \t"));
1831 $attributes = array('href'=>$url, 'title'=>$title, 'aria-haspopup' => 'true', 'class' => 'tooltip');
1832 $output = html_writer
::tag('a', $output, $attributes);
1834 $this->page
->requires
->js_init_call('M.util.help_icon.setup');
1835 $this->page
->requires
->string_for_js('close', 'form');
1838 return html_writer
::tag('span', $output, array('class' => 'helplink'));
1842 * Returns HTML to display a scale help icon.
1844 * @param int $courseid
1845 * @param stdClass $scale instance
1846 * @return string HTML fragment
1848 public function help_icon_scale($courseid, stdClass
$scale) {
1851 $title = get_string('helpprefix2', '', $scale->name
) .' ('.get_string('newwindow').')';
1853 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
1855 $scaleid = abs($scale->id
);
1857 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
1858 $action = new popup_action('click', $link, 'ratingscale');
1860 return html_writer
::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
1864 * Creates and returns a spacer image with optional line break.
1866 * @param array $attributes Any HTML attributes to add to the spaced.
1867 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
1868 * laxy do it with CSS which is a much better solution.
1869 * @return string HTML fragment
1871 public function spacer(array $attributes = null, $br = false) {
1872 $attributes = (array)$attributes;
1873 if (empty($attributes['width'])) {
1874 $attributes['width'] = 1;
1876 if (empty($attributes['height'])) {
1877 $attributes['height'] = 1;
1879 $attributes['class'] = 'spacer';
1881 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
1884 $output .= '<br />';
1891 * Returns HTML to display the specified user's avatar.
1893 * User avatar may be obtained in two ways:
1895 * // Option 1: (shortcut for simple cases, preferred way)
1896 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
1897 * $OUTPUT->user_picture($user, array('popup'=>true));
1900 * $userpic = new user_picture($user);
1901 * // Set properties of $userpic
1902 * $userpic->popup = true;
1903 * $OUTPUT->render($userpic);
1906 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
1907 * If any of these are missing, the database is queried. Avoid this
1908 * if at all possible, particularly for reports. It is very bad for performance.
1909 * @param array $options associative array with user picture options, used only if not a user_picture object,
1911 * - courseid=$this->page->course->id (course id of user profile in link)
1912 * - size=35 (size of image)
1913 * - link=true (make image clickable - the link leads to user profile)
1914 * - popup=false (open in popup)
1915 * - alttext=true (add image alt attribute)
1916 * - class = image class attribute (default 'userpicture')
1917 * @return string HTML fragment
1919 public function user_picture(stdClass
$user, array $options = null) {
1920 $userpicture = new user_picture($user);
1921 foreach ((array)$options as $key=>$value) {
1922 if (array_key_exists($key, $userpicture)) {
1923 $userpicture->$key = $value;
1926 return $this->render($userpicture);
1930 * Internal implementation of user image rendering.
1932 * @param user_picture $userpicture
1935 protected function render_user_picture(user_picture
$userpicture) {
1938 $user = $userpicture->user
;
1940 if ($userpicture->alttext
) {
1941 if (!empty($user->imagealt
)) {
1942 $alt = $user->imagealt
;
1944 $alt = get_string('pictureof', '', fullname($user));
1950 if (empty($userpicture->size
)) {
1952 } else if ($userpicture->size
=== true or $userpicture->size
== 1) {
1955 $size = $userpicture->size
;
1958 $class = $userpicture->class;
1960 if ($user->picture
== 0) {
1961 $class .= ' defaultuserpic';
1964 $src = $userpicture->get_url($this->page
, $this);
1966 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
1968 // get the image html output fisrt
1969 $output = html_writer
::empty_tag('img', $attributes);;
1971 // then wrap it in link if needed
1972 if (!$userpicture->link
) {
1976 if (empty($userpicture->courseid
)) {
1977 $courseid = $this->page
->course
->id
;
1979 $courseid = $userpicture->courseid
;
1982 if ($courseid == SITEID
) {
1983 $url = new moodle_url('/user/profile.php', array('id' => $user->id
));
1985 $url = new moodle_url('/user/view.php', array('id' => $user->id
, 'course' => $courseid));
1988 $attributes = array('href'=>$url);
1990 if ($userpicture->popup
) {
1991 $id = html_writer
::random_id('userpicture');
1992 $attributes['id'] = $id;
1993 $this->add_action_handler(new popup_action('click', $url), $id);
1996 return html_writer
::tag('a', $output, $attributes);
2000 * Internal implementation of file tree viewer items rendering.
2005 public function htmllize_file_tree($dir) {
2006 if (empty($dir['subdirs']) and empty($dir['files'])) {
2010 foreach ($dir['subdirs'] as $subdir) {
2011 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2013 foreach ($dir['files'] as $file) {
2014 $filename = $file->get_filename();
2015 $result .= '<li><span>'.html_writer
::link($file->fileurl
, $filename).'</span></li>';
2023 * Returns HTML to display the file picker
2026 * $OUTPUT->file_picker($options);
2029 * @param array $options associative array with file manager options
2033 * client_id=>uniqid(),
2034 * acepted_types=>'*',
2035 * return_types=>FILE_INTERNAL,
2036 * context=>$PAGE->context
2037 * @return string HTML fragment
2039 public function file_picker($options) {
2040 $fp = new file_picker($options);
2041 return $this->render($fp);
2045 * Internal implementation of file picker rendering.
2047 * @param file_picker $fp
2050 public function render_file_picker(file_picker
$fp) {
2051 global $CFG, $OUTPUT, $USER;
2052 $options = $fp->options
;
2053 $client_id = $options->client_id
;
2054 $strsaved = get_string('filesaved', 'repository');
2055 $straddfile = get_string('openpicker', 'repository');
2056 $strloading = get_string('loading', 'repository');
2057 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2058 $strdroptoupload = get_string('droptoupload', 'moodle');
2059 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2061 $currentfile = $options->currentfile
;
2062 if (empty($currentfile)) {
2065 $currentfile .= ' - ';
2067 if ($options->maxbytes
) {
2068 $size = $options->maxbytes
;
2070 $size = get_max_upload_file_size();
2075 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2077 if ($options->buttonname
) {
2078 $buttonname = ' name="' . $options->buttonname
. '"';
2083 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2086 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2088 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2089 <span> $maxsize </span>
2092 if ($options->env
!= 'url') {
2094 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2095 <div class="filepicker-filename">
2096 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2098 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2107 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2109 * @param string $cmid the course_module id.
2110 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2111 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2113 public function update_module_button($cmid, $modulename) {
2115 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE
, $cmid))) {
2116 $modulename = get_string('modulename', $modulename);
2117 $string = get_string('updatethis', '', $modulename);
2118 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2119 return $this->single_button($url, $string);
2126 * Returns HTML to display a "Turn editing on/off" button in a form.
2128 * @param moodle_url $url The URL + params to send through when clicking the button
2129 * @return string HTML the button
2131 public function edit_button(moodle_url
$url) {
2133 $url->param('sesskey', sesskey());
2134 if ($this->page
->user_is_editing()) {
2135 $url->param('edit', 'off');
2136 $editstring = get_string('turneditingoff');
2138 $url->param('edit', 'on');
2139 $editstring = get_string('turneditingon');
2142 return $this->single_button($url, $editstring);
2146 * Returns HTML to display a simple button to close a window
2148 * @param string $text The lang string for the button's label (already output from get_string())
2149 * @return string html fragment
2151 public function close_window_button($text='') {
2153 $text = get_string('closewindow');
2155 $button = new single_button(new moodle_url('#'), $text, 'get');
2156 $button->add_action(new component_action('click', 'close_window'));
2158 return $this->container($this->render($button), 'closewindow');
2162 * Output an error message. By default wraps the error message in <span class="error">.
2163 * If the error message is blank, nothing is output.
2165 * @param string $message the error message.
2166 * @return string the HTML to output.
2168 public function error_text($message) {
2169 if (empty($message)) {
2172 return html_writer
::tag('span', $message, array('class' => 'error'));
2176 * Do not call this function directly.
2178 * To terminate the current script with a fatal error, call the {@link print_error}
2179 * function, or throw an exception. Doing either of those things will then call this
2180 * function to display the error, before terminating the execution.
2182 * @param string $message The message to output
2183 * @param string $moreinfourl URL where more info can be found about the error
2184 * @param string $link Link for the Continue button
2185 * @param array $backtrace The execution backtrace
2186 * @param string $debuginfo Debugging information
2187 * @return string the HTML to output.
2189 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2195 if ($this->has_started()) {
2196 // we can not always recover properly here, we have problems with output buffering,
2197 // html tables, etc.
2198 $output .= $this->opencontainers
->pop_all_but_last();
2201 // It is really bad if library code throws exception when output buffering is on,
2202 // because the buffered text would be printed before our start of page.
2203 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2204 error_reporting(0); // disable notices from gzip compression, etc.
2205 while (ob_get_level() > 0) {
2206 $buff = ob_get_clean();
2207 if ($buff === false) {
2212 error_reporting($CFG->debug
);
2214 // Header not yet printed
2215 if (isset($_SERVER['SERVER_PROTOCOL'])) {
2216 // server protocol should be always present, because this render
2217 // can not be used from command line or when outputting custom XML
2218 @header
($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
2220 $this->page
->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2221 $this->page
->set_url('/'); // no url
2222 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2223 $this->page
->set_title(get_string('error'));
2224 $this->page
->set_heading($this->page
->course
->fullname
);
2225 $output .= $this->header();
2228 $message = '<p class="errormessage">' . $message . '</p>'.
2229 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2230 get_string('moreinformation') . '</a></p>';
2231 if (empty($CFG->rolesactive
)) {
2232 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2233 //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.
2235 $output .= $this->box($message, 'errorbox');
2237 if (debugging('', DEBUG_DEVELOPER
)) {
2238 if (!empty($debuginfo)) {
2239 $debuginfo = s($debuginfo); // removes all nasty JS
2240 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2241 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2243 if (!empty($backtrace)) {
2244 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2246 if ($obbuffer !== '' ) {
2247 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2251 if (empty($CFG->rolesactive
)) {
2252 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2253 } else if (!empty($link)) {
2254 $output .= $this->continue_button($link);
2257 $output .= $this->footer();
2259 // Padding to encourage IE to display our error page, rather than its own.
2260 $output .= str_repeat(' ', 512);
2266 * Output a notification (that is, a status message about something that has
2269 * @param string $message the message to print out
2270 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2271 * @return string the HTML to output.
2273 public function notification($message, $classes = 'notifyproblem') {
2274 return html_writer
::tag('div', clean_text($message), array('class' => renderer_base
::prepare_classes($classes)));
2278 * Returns HTML to display a continue button that goes to a particular URL.
2280 * @param string|moodle_url $url The url the button goes to.
2281 * @return string the HTML to output.
2283 public function continue_button($url) {
2284 if (!($url instanceof moodle_url
)) {
2285 $url = new moodle_url($url);
2287 $button = new single_button($url, get_string('continue'), 'get');
2288 $button->class = 'continuebutton';
2290 return $this->render($button);
2294 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2296 * @param int $totalcount The total number of entries available to be paged through
2297 * @param int $page The page you are currently viewing
2298 * @param int $perpage The number of entries that should be shown per page
2299 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2300 * @param string $pagevar name of page parameter that holds the page number
2301 * @return string the HTML to output.
2303 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2304 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2305 return $this->render($pb);
2309 * Internal implementation of paging bar rendering.
2311 * @param paging_bar $pagingbar
2314 protected function render_paging_bar(paging_bar
$pagingbar) {
2316 $pagingbar = clone($pagingbar);
2317 $pagingbar->prepare($this, $this->page
, $this->target
);
2319 if ($pagingbar->totalcount
> $pagingbar->perpage
) {
2320 $output .= get_string('page') . ':';
2322 if (!empty($pagingbar->previouslink
)) {
2323 $output .= ' (' . $pagingbar->previouslink
. ') ';
2326 if (!empty($pagingbar->firstlink
)) {
2327 $output .= ' ' . $pagingbar->firstlink
. ' ...';
2330 foreach ($pagingbar->pagelinks
as $link) {
2331 $output .= "  $link";
2334 if (!empty($pagingbar->lastlink
)) {
2335 $output .= ' ...' . $pagingbar->lastlink
. ' ';
2338 if (!empty($pagingbar->nextlink
)) {
2339 $output .= '  (' . $pagingbar->nextlink
. ')';
2343 return html_writer
::tag('div', $output, array('class' => 'paging'));
2347 * Output the place a skip link goes to.
2349 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2350 * @return string the HTML to output.
2352 public function skip_link_target($id = null) {
2353 return html_writer
::tag('span', '', array('id' => $id));
2359 * @param string $text The text of the heading
2360 * @param int $level The level of importance of the heading. Defaulting to 2
2361 * @param string $classes A space-separated list of CSS classes
2362 * @param string $id An optional ID
2363 * @return string the HTML to output.
2365 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2366 $level = (integer) $level;
2367 if ($level < 1 or $level > 6) {
2368 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2370 return html_writer
::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base
::prepare_classes($classes)));
2376 * @param string $contents The contents of the box
2377 * @param string $classes A space-separated list of CSS classes
2378 * @param string $id An optional ID
2379 * @return string the HTML to output.
2381 public function box($contents, $classes = 'generalbox', $id = null) {
2382 return $this->box_start($classes, $id) . $contents . $this->box_end();
2386 * Outputs the opening section of a box.
2388 * @param string $classes A space-separated list of CSS classes
2389 * @param string $id An optional ID
2390 * @return string the HTML to output.
2392 public function box_start($classes = 'generalbox', $id = null) {
2393 $this->opencontainers
->push('box', html_writer
::end_tag('div'));
2394 return html_writer
::start_tag('div', array('id' => $id,
2395 'class' => 'box ' . renderer_base
::prepare_classes($classes)));
2399 * Outputs the closing section of a box.
2401 * @return string the HTML to output.
2403 public function box_end() {
2404 return $this->opencontainers
->pop('box');
2408 * Outputs a container.
2410 * @param string $contents The contents of the box
2411 * @param string $classes A space-separated list of CSS classes
2412 * @param string $id An optional ID
2413 * @return string the HTML to output.
2415 public function container($contents, $classes = null, $id = null) {
2416 return $this->container_start($classes, $id) . $contents . $this->container_end();
2420 * Outputs the opening section of a container.
2422 * @param string $classes A space-separated list of CSS classes
2423 * @param string $id An optional ID
2424 * @return string the HTML to output.
2426 public function container_start($classes = null, $id = null) {
2427 $this->opencontainers
->push('container', html_writer
::end_tag('div'));
2428 return html_writer
::start_tag('div', array('id' => $id,
2429 'class' => renderer_base
::prepare_classes($classes)));
2433 * Outputs the closing section of a container.
2435 * @return string the HTML to output.
2437 public function container_end() {
2438 return $this->opencontainers
->pop('container');
2442 * Make nested HTML lists out of the items
2444 * The resulting list will look something like this:
2448 * <<li>><div class='tree_item parent'>(item contents)</div>
2450 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2456 * @param array $items
2457 * @param array $attrs html attributes passed to the top ofs the list
2458 * @return string HTML
2460 public function tree_block_contents($items, $attrs = array()) {
2461 // exit if empty, we don't want an empty ul element
2462 if (empty($items)) {
2465 // array of nested li elements
2467 foreach ($items as $item) {
2468 // this applies to the li item which contains all child lists too
2469 $content = $item->content($this);
2470 $liclasses = array($item->get_css_type());
2471 if (!$item->forceopen ||
(!$item->forceopen
&& $item->collapse
) ||
($item->children
->count()==0 && $item->nodetype
==navigation_node
::NODETYPE_BRANCH
)) {
2472 $liclasses[] = 'collapsed';
2474 if ($item->isactive
=== true) {
2475 $liclasses[] = 'current_branch';
2477 $liattr = array('class'=>join(' ',$liclasses));
2478 // class attribute on the div item which only contains the item content
2479 $divclasses = array('tree_item');
2480 if ($item->children
->count()>0 ||
$item->nodetype
==navigation_node
::NODETYPE_BRANCH
) {
2481 $divclasses[] = 'branch';
2483 $divclasses[] = 'leaf';
2485 if (!empty($item->classes
) && count($item->classes
)>0) {
2486 $divclasses[] = join(' ', $item->classes
);
2488 $divattr = array('class'=>join(' ', $divclasses));
2489 if (!empty($item->id
)) {
2490 $divattr['id'] = $item->id
;
2492 $content = html_writer
::tag('p', $content, $divattr) . $this->tree_block_contents($item->children
);
2493 if (!empty($item->preceedwithhr
) && $item->preceedwithhr
===true) {
2494 $content = html_writer
::empty_tag('hr') . $content;
2496 $content = html_writer
::tag('li', $content, $liattr);
2499 return html_writer
::tag('ul', implode("\n", $lis), $attrs);
2503 * Return the navbar content so that it can be echoed out by the layout
2505 * @return string XHTML navbar
2507 public function navbar() {
2508 $items = $this->page
->navbar
->get_items();
2510 $htmlblocks = array();
2511 // Iterate the navarray and display each node
2512 $itemcount = count($items);
2513 $separator = get_separator();
2514 for ($i=0;$i < $itemcount;$i++
) {
2516 $item->hideicon
= true;
2518 $content = html_writer
::tag('li', $this->render($item));
2520 $content = html_writer
::tag('li', $separator.$this->render($item));
2522 $htmlblocks[] = $content;
2525 //accessibility: heading for navbar list (MDL-20446)
2526 $navbarcontent = html_writer
::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2527 $navbarcontent .= html_writer
::tag('ul', join('', $htmlblocks));
2529 return $navbarcontent;
2533 * Renders a navigation node object.
2535 * @param navigation_node $item The navigation node to render.
2536 * @return string HTML fragment
2538 protected function render_navigation_node(navigation_node
$item) {
2539 $content = $item->get_content();
2540 $title = $item->get_title();
2541 if ($item->icon
instanceof renderable
&& !$item->hideicon
) {
2542 $icon = $this->render($item->icon
);
2543 $content = $icon.$content; // use CSS for spacing of icons
2545 if ($item->helpbutton
!== null) {
2546 $content = trim($item->helpbutton
).html_writer
::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2548 if ($content === '') {
2551 if ($item->action
instanceof action_link
) {
2552 $link = $item->action
;
2553 if ($item->hidden
) {
2554 $link->add_class('dimmed');
2556 if (!empty($content)) {
2557 // Providing there is content we will use that for the link content.
2558 $link->text
= $content;
2560 $content = $this->render($link);
2561 } else if ($item->action
instanceof moodle_url
) {
2562 $attributes = array();
2563 if ($title !== '') {
2564 $attributes['title'] = $title;
2566 if ($item->hidden
) {
2567 $attributes['class'] = 'dimmed_text';
2569 $content = html_writer
::link($item->action
, $content, $attributes);
2571 } else if (is_string($item->action
) ||
empty($item->action
)) {
2572 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2573 if ($title !== '') {
2574 $attributes['title'] = $title;
2576 if ($item->hidden
) {
2577 $attributes['class'] = 'dimmed_text';
2579 $content = html_writer
::tag('span', $content, $attributes);
2585 * Accessibility: Right arrow-like character is
2586 * used in the breadcrumb trail, course navigation menu
2587 * (previous/next activity), calendar, and search forum block.
2588 * If the theme does not set characters, appropriate defaults
2589 * are set automatically. Please DO NOT
2590 * use < > » - these are confusing for blind users.
2594 public function rarrow() {
2595 return $this->page
->theme
->rarrow
;
2599 * Accessibility: Right arrow-like character is
2600 * used in the breadcrumb trail, course navigation menu
2601 * (previous/next activity), calendar, and search forum block.
2602 * If the theme does not set characters, appropriate defaults
2603 * are set automatically. Please DO NOT
2604 * use < > » - these are confusing for blind users.
2608 public function larrow() {
2609 return $this->page
->theme
->larrow
;
2613 * Returns the custom menu if one has been set
2615 * A custom menu can be configured by browsing to
2616 * Settings: Administration > Appearance > Themes > Theme settings
2617 * and then configuring the custommenu config setting as described.
2619 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
2622 public function custom_menu($custommenuitems = '') {
2624 if (empty($custommenuitems) && !empty($CFG->custommenuitems
)) {
2625 $custommenuitems = $CFG->custommenuitems
;
2627 if (empty($custommenuitems)) {
2630 $custommenu = new custom_menu($custommenuitems, current_language());
2631 return $this->render_custom_menu($custommenu);
2635 * Renders a custom menu object (located in outputcomponents.php)
2637 * The custom menu this method produces makes use of the YUI3 menunav widget
2638 * and requires very specific html elements and classes.
2640 * @staticvar int $menucount
2641 * @param custom_menu $menu
2644 protected function render_custom_menu(custom_menu
$menu) {
2645 static $menucount = 0;
2646 // If the menu has no children return an empty string
2647 if (!$menu->has_children()) {
2650 // Increment the menu count. This is used for ID's that get worked with
2651 // in JavaScript as is essential
2653 // Initialise this custom menu (the custom menu object is contained in javascript-static
2654 $jscode = js_writer
::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
2655 $jscode = "(function(){{$jscode}})";
2656 $this->page
->requires
->yui_module('node-menunav', $jscode);
2657 // Build the root nodes as required by YUI
2658 $content = html_writer
::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled'));
2659 $content .= html_writer
::start_tag('div', array('class'=>'yui3-menu-content'));
2660 $content .= html_writer
::start_tag('ul');
2661 // Render each child
2662 foreach ($menu->get_children() as $item) {
2663 $content .= $this->render_custom_menu_item($item);
2665 // Close the open tags
2666 $content .= html_writer
::end_tag('ul');
2667 $content .= html_writer
::end_tag('div');
2668 $content .= html_writer
::end_tag('div');
2669 // Return the custom menu
2674 * Renders a custom menu node as part of a submenu
2676 * The custom menu this method produces makes use of the YUI3 menunav widget
2677 * and requires very specific html elements and classes.
2679 * @see core:renderer::render_custom_menu()
2681 * @staticvar int $submenucount
2682 * @param custom_menu_item $menunode
2685 protected function render_custom_menu_item(custom_menu_item
$menunode) {
2686 // Required to ensure we get unique trackable id's
2687 static $submenucount = 0;
2688 if ($menunode->has_children()) {
2689 // If the child has menus render it as a sub menu
2691 $content = html_writer
::start_tag('li');
2692 if ($menunode->get_url() !== null) {
2693 $url = $menunode->get_url();
2695 $url = '#cm_submenu_'.$submenucount;
2697 $content .= html_writer
::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
2698 $content .= html_writer
::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
2699 $content .= html_writer
::start_tag('div', array('class'=>'yui3-menu-content'));
2700 $content .= html_writer
::start_tag('ul');
2701 foreach ($menunode->get_children() as $menunode) {
2702 $content .= $this->render_custom_menu_item($menunode);
2704 $content .= html_writer
::end_tag('ul');
2705 $content .= html_writer
::end_tag('div');
2706 $content .= html_writer
::end_tag('div');
2707 $content .= html_writer
::end_tag('li');
2709 // The node doesn't have children so produce a final menuitem
2710 $content = html_writer
::start_tag('li', array('class'=>'yui3-menuitem'));
2711 if ($menunode->get_url() !== null) {
2712 $url = $menunode->get_url();
2716 $content .= html_writer
::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
2717 $content .= html_writer
::end_tag('li');
2719 // Return the sub menu
2724 * Renders theme links for switching between default and other themes.
2728 protected function theme_switch_links() {
2730 $actualdevice = get_device_type();
2731 $currentdevice = $this->page
->devicetypeinuse
;
2732 $switched = ($actualdevice != $currentdevice);
2734 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
2735 // The user is using the a default device and hasn't switched so don't shown the switch
2741 $linktext = get_string('switchdevicerecommended');
2742 $devicetype = $actualdevice;
2744 $linktext = get_string('switchdevicedefault');
2745 $devicetype = 'default';
2747 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page
->url
, 'device' => $devicetype, 'sesskey' => sesskey()));
2749 $content = html_writer
::start_tag('div', array('id' => 'theme_switch_link'));
2750 $content .= html_writer
::link($linkurl, $linktext);
2751 $content .= html_writer
::end_tag('div');
2758 * A renderer that generates output for command-line scripts.
2760 * The implementation of this renderer is probably incomplete.
2762 * @copyright 2009 Tim Hunt
2763 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2768 class core_renderer_cli
extends core_renderer
{
2771 * Returns the page header.
2773 * @return string HTML fragment
2775 public function header() {
2776 return $this->page
->heading
. "\n";
2780 * Returns a template fragment representing a Heading.
2782 * @param string $text The text of the heading
2783 * @param int $level The level of importance of the heading
2784 * @param string $classes A space-separated list of CSS classes
2785 * @param string $id An optional ID
2786 * @return string A template fragment for a heading
2788 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2792 return '=>' . $text;
2794 return '-->' . $text;
2801 * Returns a template fragment representing a fatal error.
2803 * @param string $message The message to output
2804 * @param string $moreinfourl URL where more info can be found about the error
2805 * @param string $link Link for the Continue button
2806 * @param array $backtrace The execution backtrace
2807 * @param string $debuginfo Debugging information
2808 * @return string A template fragment for a fatal error
2810 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2811 $output = "!!! $message !!!\n";
2813 if (debugging('', DEBUG_DEVELOPER
)) {
2814 if (!empty($debuginfo)) {
2815 $output .= $this->notification($debuginfo, 'notifytiny');
2817 if (!empty($backtrace)) {
2818 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
2826 * Returns a template fragment representing a notification.
2828 * @param string $message The message to include
2829 * @param string $classes A space-separated list of CSS classes
2830 * @return string A template fragment for a notification
2832 public function notification($message, $classes = 'notifyproblem') {
2833 $message = clean_text($message);
2834 if ($classes === 'notifysuccess') {
2835 return "++ $message ++\n";
2837 return "!! $message !!\n";
2843 * A renderer that generates output for ajax scripts.
2845 * This renderer prevents accidental sends back only json
2846 * encoded error messages, all other output is ignored.
2848 * @copyright 2010 Petr Skoda
2849 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2854 class core_renderer_ajax
extends core_renderer
{
2857 * Returns a template fragment representing a fatal error.
2859 * @param string $message The message to output
2860 * @param string $moreinfourl URL where more info can be found about the error
2861 * @param string $link Link for the Continue button
2862 * @param array $backtrace The execution backtrace
2863 * @param string $debuginfo Debugging information
2864 * @return string A template fragment for a fatal error
2866 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2869 $this->page
->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2871 $e = new stdClass();
2872 $e->error
= $message;
2873 $e->stacktrace
= NULL;
2874 $e->debuginfo
= NULL;
2875 $e->reproductionlink
= NULL;
2876 if (!empty($CFG->debug
) and $CFG->debug
>= DEBUG_DEVELOPER
) {
2877 $e->reproductionlink
= $link;
2878 if (!empty($debuginfo)) {
2879 $e->debuginfo
= $debuginfo;
2881 if (!empty($backtrace)) {
2882 $e->stacktrace
= format_backtrace($backtrace, true);
2886 return json_encode($e);
2890 * Used to display a notification.
2891 * For the AJAX notifications are discarded.
2893 * @param string $message
2894 * @param string $classes
2896 public function notification($message, $classes = 'notifyproblem') {}
2899 * Used to display a redirection message.
2900 * AJAX redirections should not occur and as such redirection messages
2903 * @param moodle_url|string $encodedurl
2904 * @param string $message
2906 * @param bool $debugdisableredirect
2908 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
2911 * Prepares the start of an AJAX output.
2913 public function header() {
2914 // unfortunately YUI iframe upload does not support application/json
2915 if (!empty($_FILES)) {
2916 @header
('Content-type: text/plain; charset=utf-8');
2918 @header
('Content-type: application/json; charset=utf-8');
2921 // Headers to make it not cacheable and json
2922 @header
('Cache-Control: no-store, no-cache, must-revalidate');
2923 @header
('Cache-Control: post-check=0, pre-check=0', false);
2924 @header
('Pragma: no-cache');
2925 @header
('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2926 @header
('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2927 @header
('Accept-Ranges: none');
2931 * There is no footer for an AJAX request, however we must override the
2932 * footer method to prevent the default footer.
2934 public function footer() {}
2937 * No need for headers in an AJAX request... this should never happen.
2938 * @param string $text
2940 * @param string $classes
2943 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
2948 * Renderer for media files.
2950 * Used in file resources, media filter, and any other places that need to
2951 * output embedded media.
2953 * @copyright 2011 The Open University
2954 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2956 class core_media_renderer
extends plugin_renderer_base
{
2957 /** @var array Array of available 'player' objects */
2959 /** @var string Regex pattern for links which may contain embeddable content */
2960 private $embeddablemarkers;
2963 * Constructor requires medialib.php.
2965 * This is needed in the constructor (not later) so that you can use the
2966 * constants and static functions that are defined in core_media class
2967 * before you call renderer functions.
2969 public function __construct() {
2971 require_once($CFG->libdir
. '/medialib.php');
2975 * Obtains the list of core_media_player objects currently in use to render
2978 * The list is in rank order (highest first) and does not include players
2979 * which are disabled.
2981 * @return array Array of core_media_player objects in rank order
2983 protected function get_players() {
2986 // Save time by only building the list once.
2987 if (!$this->players
) {
2988 // Get raw list of players.
2989 $players = $this->get_players_raw();
2991 // Chuck all the ones that are disabled.
2992 foreach ($players as $key => $player) {
2993 if (!$player->is_enabled()) {
2994 unset($players[$key]);
2998 // Sort in rank order (highest first).
2999 usort($players, array('core_media_player', 'compare_by_rank'));
3000 $this->players
= $players;
3002 return $this->players
;
3006 * Obtains a raw list of player objects that includes objects regardless
3007 * of whether they are disabled or not, and without sorting.
3009 * You can override this in a subclass if you need to add additional
3012 * The return array is be indexed by player name to make it easier to
3013 * remove players in a subclass.
3015 * @return array $players Array of core_media_player objects in any order
3017 protected function get_players_raw() {
3019 'vimeo' => new core_media_player_vimeo(),
3020 'youtube' => new core_media_player_youtube(),
3021 'youtube_playlist' => new core_media_player_youtube_playlist(),
3022 'html5video' => new core_media_player_html5video(),
3023 'html5audio' => new core_media_player_html5audio(),
3024 'mp3' => new core_media_player_mp3(),
3025 'flv' => new core_media_player_flv(),
3026 'wmp' => new core_media_player_wmp(),
3027 'qt' => new core_media_player_qt(),
3028 'rm' => new core_media_player_rm(),
3029 'swf' => new core_media_player_swf(),
3030 'link' => new core_media_player_link(),
3035 * Renders a media file (audio or video) using suitable embedded player.
3037 * See embed_alternatives function for full description of parameters.
3038 * This function calls through to that one.
3040 * When using this function you can also specify width and height in the
3041 * URL by including ?d=100x100 at the end. If specified in the URL, this
3042 * will override the $width and $height parameters.
3044 * @param moodle_url $url Full URL of media file
3045 * @param string $name Optional user-readable name to display in download link
3046 * @param int $width Width in pixels (optional)
3047 * @param int $height Height in pixels (optional)
3048 * @param array $options Array of key/value pairs
3049 * @return string HTML content of embed
3051 public function embed_url(moodle_url
$url, $name = '', $width = 0, $height = 0,
3052 $options = array()) {
3054 // Get width and height from URL if specified (overrides parameters in
3056 $rawurl = $url->out(false);
3057 if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
3058 $width = $matches[1];
3059 $height = $matches[2];
3060 $url = new moodle_url(str_replace($matches[0], '', $rawurl));
3063 // Defer to array version of function.
3064 return $this->embed_alternatives(array($url), $name, $width, $height, $options);
3068 * Renders media files (audio or video) using suitable embedded player.
3069 * The list of URLs should be alternative versions of the same content in
3070 * multiple formats. If there is only one format it should have a single
3073 * If the media files are not in a supported format, this will give students
3074 * a download link to each format. The download link uses the filename
3075 * unless you supply the optional name parameter.
3077 * Width and height are optional. If specified, these are suggested sizes
3078 * and should be the exact values supplied by the user, if they come from
3079 * user input. These will be treated as relating to the size of the video
3080 * content, not including any player control bar.
3082 * For audio files, height will be ignored. For video files, a few formats
3083 * work if you specify only width, but in general if you specify width
3084 * you must specify height as well.
3086 * The $options array is passed through to the core_media_player classes
3087 * that render the object tag. The keys can contain values from
3088 * core_media::OPTION_xx.
3090 * @param array $alternatives Array of moodle_url to media files
3091 * @param string $name Optional user-readable name to display in download link
3092 * @param int $width Width in pixels (optional)
3093 * @param int $height Height in pixels (optional)
3094 * @param array $options Array of key/value pairs
3095 * @return string HTML content of embed
3097 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
3098 $options = array()) {
3100 // Get list of player plugins (will also require the library).
3101 $players = $this->get_players();
3103 // Set up initial text which will be replaced by first player that
3104 // supports any of the formats.
3105 $out = core_media_player
::PLACEHOLDER
;
3107 // Loop through all players that support any of these URLs.
3108 foreach ($players as $player) {
3109 // Option: When no other player matched, don't do the default link player.
3110 if (!empty($options[core_media
::OPTION_FALLBACK_TO_BLANK
]) &&
3111 $player->get_rank() === 0 && $out === core_media_player
::PLACEHOLDER
) {
3115 $supported = $player->list_supported_urls($alternatives, $options);
3118 $text = $player->embed($supported, $name, $width, $height, $options);
3120 // Put this in place of the 'fallback' slot in the previous text.
3121 $out = str_replace(core_media_player
::PLACEHOLDER
, $text, $out);
3125 // Remove 'fallback' slot from final version and return it.
3126 $out = str_replace(core_media_player
::PLACEHOLDER
, '', $out);
3127 if (!empty($options[core_media
::OPTION_BLOCK
]) && $out !== '') {
3128 $out = html_writer
::tag('div', $out, array('class' => 'resourcecontent'));
3134 * Checks whether a file can be embedded. If this returns true you will get
3135 * an embedded player; if this returns false, you will just get a download
3138 * This is a wrapper for can_embed_urls.
3140 * @param moodle_url $url URL of media file
3141 * @param array $options Options (same as when embedding)
3142 * @return bool True if file can be embedded
3144 public function can_embed_url(moodle_url
$url, $options = array()) {
3145 return $this->can_embed_urls(array($url), $options);
3149 * Checks whether a file can be embedded. If this returns true you will get
3150 * an embedded player; if this returns false, you will just get a download
3153 * @param array $urls URL of media file and any alternatives (moodle_url)
3154 * @param array $options Options (same as when embedding)
3155 * @return bool True if file can be embedded
3157 public function can_embed_urls(array $urls, $options = array()) {
3158 // Check all players to see if any of them support it.
3159 foreach ($this->get_players() as $player) {
3160 // Link player (always last on list) doesn't count!
3161 if ($player->get_rank() <= 0) {
3164 // First player that supports it, return true.
3165 if ($player->list_supported_urls($urls, $options)) {
3173 * Obtains a list of markers that can be used in a regular expression when
3174 * searching for URLs that can be embedded by any player type.
3176 * This string is used to improve peformance of regex matching by ensuring
3177 * that the (presumably C) regex code can do a quick keyword check on the
3178 * URL part of a link to see if it matches one of these, rather than having
3179 * to go into PHP code for every single link to see if it can be embedded.
3181 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
3183 public function get_embeddable_markers() {
3184 if (empty($this->embeddablemarkers
)) {
3186 foreach ($this->get_players() as $player) {
3187 foreach ($player->get_embeddable_markers() as $marker) {
3188 if ($markers !== '') {
3191 $markers .= preg_quote($marker);
3194 $this->embeddablemarkers
= $markers;
3196 return $this->embeddablemarkers
;