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 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
377 $focus = $this->page->focuscontrol;
378 if (!empty($focus)) {
379 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
380 // This is a horrifically bad way to handle focus but it is passed in
381 // through messy formslib::moodleform
382 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
383 } else if (strpos($focus, '.')!==false) {
384 // Old style of focus, bad way to do it
385 debugging('This code is using the old style focus event, Please update this code to focus on an element id or the moodleform focus method.', DEBUG_DEVELOPER);
386 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
388 // Focus element with given id
389 $this->page->requires->js_function_call('focuscontrol', array($focus));
393 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
394 // any other custom CSS can not be overridden via themes and is highly discouraged
395 $urls = $this->page->theme->css_urls($this->page);
396 foreach ($urls as $url) {
397 $this->page->requires->css_theme($url);
400 // Get the theme javascript head and footer
401 $jsurl = $this->page->theme->javascript_url(true);
402 $this->page->requires->js($jsurl, true);
403 $jsurl = $this->page->theme->javascript_url(false);
404 $this->page->requires->js($jsurl);
406 // Get any HTML from the page_requirements_manager.
407 $output .= $this->page->requires->get_head_code($this->page, $this);
409 // List alternate versions.
410 foreach ($this->page->alternateversions as $type => $alt) {
411 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
412 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
415 if (!empty($CFG->additionalhtmlhead)) {
416 $output .= "\n".$CFG->additionalhtmlhead;
423 * The standard tags (typically skip links) that should be output just inside
424 * the start of the <body> tag. Designed to be called in theme layout.php files.
426 * @return string HTML fragment.
428 public function standard_top_of_body_html() {
430 $output = $this->page->requires->get_top_of_body_code();
431 if (!empty($CFG->additionalhtmltopofbody)) {
432 $output .= "\n".$CFG->additionalhtmltopofbody;
438 * The standard tags (typically performance information and validation links,
439 * if we are in developer debug mode) that should be output in the footer area
440 * of the page. Designed to be called in theme layout.php files.
442 * @return string HTML fragment.
444 public function standard_footer_html() {
445 global $CFG, $SCRIPT;
447 // This function is normally called from a layout.php file in {@link core_renderer::header()}
448 // but some of the content won't be known until later, so we return a placeholder
449 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
450 $output = $this->unique_performance_info_token;
451 if ($this->page->devicetypeinuse == 'legacy') {
452 // The legacy theme is in use print the notification
453 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
456 // Get links to switch device types (only shown for users not on a default device)
457 $output .= $this->theme_switch_links();
459 if (!empty($CFG->debugpageinfo)) {
460 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
462 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { // Only in developer mode
463 // Add link to profiling report if necessary
464 if (function_exists('profiling_is_running') && profiling_is_running()) {
465 $txt = get_string('profiledscript', 'admin');
466 $title = get_string('profiledscriptview', 'admin');
467 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
468 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
469 $output .= '<div class="profilingfooter">' . $link . '</div>';
471 $output .= '<div class="purgecaches"><a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/purgecaches.php?confirm=1&sesskey='.sesskey().'">'.get_string('purgecaches', 'admin').'</a></div>';
473 if (!empty($CFG->debugvalidators)) {
474 // NOTE: this is not a nice hack, $PAGE->url is not always accurate and $FULLME neither, it is not a bug if it fails. --skodak
475 $output .= '<div class="validators"><ul>
476 <li><a href="http://validator.w3.org/check?verbose=1&ss=1&uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
477 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
478 <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>
481 if (!empty($CFG->additionalhtmlfooter)) {
482 $output .= "\n".$CFG->additionalhtmlfooter;
488 * Returns standard main content placeholder.
489 * Designed to be called in theme layout.php files.
491 * @return string HTML fragment.
493 public function main_content() {
494 return $this->unique_main_content_token;
498 * The standard tags (typically script tags that are not needed earlier) that
499 * should be output after everything else, . Designed to be called in theme layout.php files.
501 * @return string HTML fragment.
503 public function standard_end_of_body_html() {
504 // This function is normally called from a layout.php file in {@link core_renderer::header()}
505 // but some of the content won't be known until later, so we return a placeholder
506 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
507 return $this->unique_end_html_token;
511 * Return the standard string that says whether you are logged in (and switched
512 * roles/logged in as another user).
514 * @return string HTML fragment.
516 public function login_info() {
517 global $USER, $CFG, $DB, $SESSION;
519 if (during_initial_install()) {
523 $loginpage = ((string)$this->page->url === get_login_url());
524 $course = $this->page->course;
526 if (session_is_loggedinas()) {
527 $realuser = session_get_realuser();
528 $fullname = fullname($realuser, true);
529 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&sesskey=".sesskey()."\">$fullname</a>] ";
534 $loginurl = get_login_url();
536 if (empty($course->id)) {
537 // $course->id is not defined during installation
539 } else if (isloggedin()) {
540 $context = get_context_instance(CONTEXT_COURSE, $course->id);
542 $fullname = fullname($USER, true);
543 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
544 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\">$fullname</a>";
545 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
546 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
549 $loggedinas = $realuserinfo.get_string('loggedinasguest');
551 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
553 } else if (is_role_switched($course->id)) { // Has switched roles
555 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
556 $rolename = ': '.format_string($role->name);
558 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
559 " (<a href=\"$CFG->wwwroot/course/view.php?id=$course->id&switchrole=0&sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
561 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
562 " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
565 $loggedinas = get_string('loggedinnot', 'moodle');
567 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
571 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
573 if (isset($SESSION->justloggedin)) {
574 unset($SESSION->justloggedin);
575 if (!empty($CFG->displayloginfailures)) {
576 if (!isguestuser()) {
577 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
578 $loggedinas .= ' <div class="loginfailures">';
579 if (empty($count->accounts)) {
580 $loggedinas .= get_string('failedloginattempts', '', $count);
582 $loggedinas .= get_string('failedloginattemptsall', '', $count);
584 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', get_context_instance(CONTEXT_SYSTEM))) {
585 $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/report/log/index.php'.
586 '?chooselog=1&id=1&modid=site_errors">'.get_string('logs').'</a>)';
588 $loggedinas .= '</div>';
598 * Return the 'back' link that normally appears in the footer.
600 * @return string HTML fragment.
602 public function home_link() {
605 if ($this->page->pagetype == 'site-index') {
606 // Special case for site home page - please do not remove
607 return '<div class="sitelink">' .
608 '<a title="Moodle" href="http://moodle.org/">' .
609 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
611 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
612 // Special case for during install/upgrade.
613 return '<div class="sitelink">'.
614 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
615 '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
617 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
618 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
619 get_string('home') . '</a></div>';
622 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
623 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
628 * Redirects the user by any means possible given the current state
630 * This function should not be called directly, it should always be called using
631 * the redirect function in lib/weblib.php
633 * The redirect function should really only be called before page output has started
634 * however it will allow itself to be called during the state STATE_IN_BODY
636 * @param string $encodedurl The URL to send to encoded if required
637 * @param string $message The message to display to the user if any
638 * @param int $delay The delay before redirecting a user, if $message has been
639 * set this is a requirement and defaults to 3, set to 0 no delay
640 * @param boolean $debugdisableredirect this redirect has been disabled for
641 * debugging purposes. Display a message that explains, and don't
642 * trigger the redirect.
643 * @return string The HTML to display to the user before dying, may contain
644 * meta refresh, javascript refresh, and may have set header redirects
646 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
648 $url = str_replace('&', '&', $encodedurl);
650 switch ($this->page->state) {
651 case moodle_page::STATE_BEFORE_HEADER :
652 // No output yet it is safe to delivery the full arsenal of redirect methods
653 if (!$debugdisableredirect) {
654 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
655 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
656 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
658 $output = $this->header();
660 case moodle_page::STATE_PRINTING_HEADER :
661 // We should hopefully never get here
662 throw new coding_exception('You cannot redirect while printing the page header');
664 case moodle_page::STATE_IN_BODY :
665 // We really shouldn't be here but we can deal with this
666 debugging("You should really redirect before you start page output");
667 if (!$debugdisableredirect) {
668 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
670 $output = $this->opencontainers->pop_all_but_last();
672 case moodle_page::STATE_DONE :
673 // Too late to be calling redirect now
674 throw new coding_exception('You cannot redirect after the entire page has been generated');
677 $output .= $this->notification($message, 'redirectmessage');
678 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
679 if ($debugdisableredirect) {
680 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
682 $output .= $this->footer();
687 * Start output by sending the HTTP headers, and printing the HTML <head>
688 * and the start of the <body>.
690 * To control what is printed, you should set properties on $PAGE. If you
691 * are familiar with the old {@link print_header()} function from Moodle 1.9
692 * you will find that there are properties on $PAGE that correspond to most
693 * of the old parameters to could be passed to print_header.
695 * Not that, in due course, the remaining $navigation, $menu parameters here
696 * will be replaced by more properties of $PAGE, but that is still to do.
698 * @return string HTML that you must output this, preferably immediately.
700 public function header() {
703 if (session_is_loggedinas()) {
704 $this->page->add_body_class('userloggedinas');
707 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
709 // Find the appropriate page layout file, based on $this->page->pagelayout.
710 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
711 // Render the layout using the layout file.
712 $rendered = $this->render_page_layout($layoutfile);
714 // Slice the rendered output into header and footer.
715 $cutpos = strpos($rendered, $this->unique_main_content_token);
716 if ($cutpos === false) {
717 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
718 $token = self::MAIN_CONTENT_TOKEN;
720 $token = $this->unique_main_content_token;
723 if ($cutpos === false) {
724 throw new coding_exception('page layout file ' . $layoutfile . ' does not contain the main content placeholder, please include "<?php echo $OUTPUT->main_content() ?>" in theme layout file.');
726 $header = substr($rendered, 0, $cutpos);
727 $footer = substr($rendered, $cutpos + strlen($token));
729 if (empty($this->contenttype)) {
730 debugging('The page layout file did not call $OUTPUT->doctype()');
731 $header = $this->doctype() . $header;
734 send_headers($this->contenttype, $this->page->cacheable);
736 $this->opencontainers->push('header/footer', $footer);
737 $this->page->set_state(moodle_page::STATE_IN_BODY);
739 return $header . $this->skip_link_target('maincontent');
743 * Renders and outputs the page layout file.
745 * This is done by preparing the normal globals available to a script, and
746 * then including the layout file provided by the current theme for the
749 * @param string $layoutfile The name of the layout file
750 * @return string HTML code
752 protected function render_page_layout($layoutfile) {
753 global $CFG, $SITE, $USER;
754 // The next lines are a bit tricky. The point is, here we are in a method
755 // of a renderer class, and this object may, or may not, be the same as
756 // the global $OUTPUT object. When rendering the page layout file, we want to use
757 // this object. However, people writing Moodle code expect the current
758 // renderer to be called $OUTPUT, not $this, so define a variable called
759 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
762 $COURSE = $this->page->course;
765 include($layoutfile);
766 $rendered = ob_get_contents();
772 * Outputs the page's footer
774 * @return string HTML fragment
776 public function footer() {
779 $output = $this->container_end_all(true);
781 $footer = $this->opencontainers->pop('header/footer');
783 if (debugging() and $DB and $DB->is_transaction_started()) {
784 // TODO: MDL-20625 print warning - transaction will be rolled back
787 // Provide some performance info if required
788 $performanceinfo = '';
789 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
790 $perf = get_performance_info();
791 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
792 error_log("PERF: " . $perf['txt']);
794 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
795 $performanceinfo = $perf['html'];
798 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
800 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
802 $this->page->set_state(moodle_page::STATE_DONE);
804 return $output . $footer;
808 * Close all but the last open container. This is useful in places like error
809 * handling, where you want to close all the open containers (apart from <body>)
810 * before outputting the error message.
812 * @param bool $shouldbenone assert that the stack should be empty now - causes a
813 * developer debug warning if it isn't.
814 * @return string the HTML required to close any open containers inside <body>.
816 public function container_end_all($shouldbenone = false) {
817 return $this->opencontainers->pop_all_but_last($shouldbenone);
821 * Returns lang menu or '', this method also checks forcing of languages in courses.
823 * @return string The lang menu HTML or empty string
825 public function lang_menu() {
828 if (empty($CFG->langmenu)) {
832 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
833 // do not show lang menu if language forced
837 $currlang = current_language();
838 $langs = get_string_manager()->get_list_of_translations();
840 if (count($langs) < 2) {
844 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
845 $s->label = get_accesshide(get_string('language'));
846 $s->class = 'langmenu';
847 return $this->render($s);
851 * Output the row of editing icons for a block, as defined by the controls array.
853 * @param array $controls an array like {@link block_contents::$controls}.
854 * @return string HTML fragment.
856 public function block_controls($controls) {
857 if (empty($controls)) {
860 $controlshtml = array();
861 foreach ($controls as $control) {
862 $controlshtml[] = html_writer::tag('a',
863 html_writer::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
864 array('class' => 'icon ' . $control['class'],'title' => $control['caption'], 'href' => $control['url']));
866 return html_writer::tag('div', implode('', $controlshtml), array('class' => 'commands'));
870 * Prints a nice side block with an optional header.
872 * The content is described
873 * by a {@link core_renderer::block_contents} object.
875 * <div id="inst{$instanceid}" class="block_{$blockname} block">
876 * <div class="header"></div>
877 * <div class="content">
879 * <div class="footer">
882 * <div class="annotation">
886 * @param block_contents $bc HTML for the content
887 * @param string $region the region the block is appearing in.
888 * @return string the HTML to be output.
890 public function block(block_contents $bc, $region) {
891 $bc = clone($bc); // Avoid messing up the object passed in.
892 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
893 $bc->collapsible = block_contents::NOT_HIDEABLE;
895 if ($bc->collapsible == block_contents::HIDDEN) {
896 $bc->add_class('hidden');
898 if (!empty($bc->controls)) {
899 $bc->add_class('block_with_controls');
902 $skiptitle = strip_tags($bc->title);
903 if (empty($skiptitle)) {
907 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
908 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
911 $output .= html_writer::start_tag('div', $bc->attributes);
913 $output .= $this->block_header($bc);
914 $output .= $this->block_content($bc);
916 $output .= html_writer::end_tag('div');
918 $output .= $this->block_annotation($bc);
920 $output .= $skipdest;
922 $this->init_block_hider_js($bc);
927 * Produces a header for a block
929 * @param block_contents $bc
932 protected function block_header(block_contents $bc) {
936 $title = html_writer::tag('h2', $bc->title, null);
939 $controlshtml = $this->block_controls($bc->controls);
942 if ($title || $controlshtml) {
943 $output .= html_writer::tag('div', html_writer::tag('div', html_writer::tag('div', '', array('class'=>'block_action')). $title . $controlshtml, array('class' => 'title')), array('class' => 'header'));
949 * Produces the content area for a block
951 * @param block_contents $bc
954 protected function block_content(block_contents $bc) {
955 $output = html_writer::start_tag('div', array('class' => 'content'));
956 if (!$bc->title && !$this->block_controls($bc->controls)) {
957 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
959 $output .= $bc->content;
960 $output .= $this->block_footer($bc);
961 $output .= html_writer::end_tag('div');
967 * Produces the footer for a block
969 * @param block_contents $bc
972 protected function block_footer(block_contents $bc) {
975 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
981 * Produces the annotation for a block
983 * @param block_contents $bc
986 protected function block_annotation(block_contents $bc) {
988 if ($bc->annotation) {
989 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
995 * Calls the JS require function to hide a block.
997 * @param block_contents $bc A block_contents object
999 protected function init_block_hider_js(block_contents $bc) {
1000 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1001 $config = new stdClass;
1002 $config->id = $bc->attributes['id'];
1003 $config->title = strip_tags($bc->title);
1004 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1005 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1006 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1008 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1009 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1014 * Render the contents of a block_list.
1016 * @param array $icons the icon for each item.
1017 * @param array $items the content of each item.
1018 * @return string HTML
1020 public function list_block_contents($icons, $items) {
1023 foreach ($items as $key => $string) {
1024 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1025 if (!empty($icons[$key])) { //test if the content has an assigned icon
1026 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1028 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1029 $item .= html_writer::end_tag('li');
1031 $row = 1 - $row; // Flip even/odd.
1033 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1037 * Output all the blocks in a particular region.
1039 * @param string $region the name of a region on this page.
1040 * @return string the HTML to be output.
1042 public function blocks_for_region($region) {
1043 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1046 foreach ($blockcontents as $bc) {
1047 if ($bc instanceof block_contents) {
1048 $output .= $this->block($bc, $region);
1049 } else if ($bc instanceof block_move_target) {
1050 $output .= $this->block_move_target($bc);
1052 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1059 * Output a place where the block that is currently being moved can be dropped.
1061 * @param block_move_target $target with the necessary details.
1062 * @return string the HTML to be output.
1064 public function block_move_target($target) {
1065 return html_writer::tag('a', html_writer::tag('span', $target->text, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1069 * Renders a special html link with attached action
1071 * @param string|moodle_url $url
1072 * @param string $text HTML fragment
1073 * @param component_action $action
1074 * @param array $attributes associative array of html link attributes + disabled
1075 * @return string HTML fragment
1077 public function action_link($url, $text, component_action $action = null, array $attributes=null) {
1078 if (!($url instanceof moodle_url)) {
1079 $url = new moodle_url($url);
1081 $link = new action_link($url, $text, $action, $attributes);
1083 return $this->render($link);
1087 * Renders an action_link object.
1089 * The provided link is renderer and the HTML returned. At the same time the
1090 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1092 * @param action_link $link
1093 * @return string HTML fragment
1095 protected function render_action_link(action_link $link) {
1098 if ($link->text instanceof renderable) {
1099 $text = $this->render($link->text);
1101 $text = $link->text;
1104 // A disabled link is rendered as formatted text
1105 if (!empty($link->attributes['disabled'])) {
1106 // do not use div here due to nesting restriction in xhtml strict
1107 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1110 $attributes = $link->attributes;
1111 unset($link->attributes['disabled']);
1112 $attributes['href'] = $link->url;
1114 if ($link->actions) {
1115 if (empty($attributes['id'])) {
1116 $id = html_writer::random_id('action_link');
1117 $attributes['id'] = $id;
1119 $id = $attributes['id'];
1121 foreach ($link->actions as $action) {
1122 $this->add_action_handler($action, $id);
1126 return html_writer::tag('a', $text, $attributes);
1131 * Renders an action_icon.
1133 * This function uses the {@link core_renderer::action_link()} method for the
1134 * most part. What it does different is prepare the icon as HTML and use it
1137 * @param string|moodle_url $url A string URL or moodel_url
1138 * @param pix_icon $pixicon
1139 * @param component_action $action
1140 * @param array $attributes associative array of html link attributes + disabled
1141 * @param bool $linktext show title next to image in link
1142 * @return string HTML fragment
1144 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1145 if (!($url instanceof moodle_url)) {
1146 $url = new moodle_url($url);
1148 $attributes = (array)$attributes;
1150 if (empty($attributes['class'])) {
1151 // let ppl override the class via $options
1152 $attributes['class'] = 'action-icon';
1155 $icon = $this->render($pixicon);
1158 $text = $pixicon->attributes['alt'];
1163 return $this->action_link($url, $text.$icon, $action, $attributes);
1167 * Print a message along with button choices for Continue/Cancel
1169 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1171 * @param string $message The question to ask the user
1172 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1173 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1174 * @return string HTML fragment
1176 public function confirm($message, $continue, $cancel) {
1177 if ($continue instanceof single_button) {
1179 } else if (is_string($continue)) {
1180 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1181 } else if ($continue instanceof moodle_url) {
1182 $continue = new single_button($continue, get_string('continue'), 'post');
1184 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1187 if ($cancel instanceof single_button) {
1189 } else if (is_string($cancel)) {
1190 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1191 } else if ($cancel instanceof moodle_url) {
1192 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1194 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1197 $output = $this->box_start('generalbox', 'notice');
1198 $output .= html_writer::tag('p', $message);
1199 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1200 $output .= $this->box_end();
1205 * Returns a form with a single button.
1207 * @param string|moodle_url $url
1208 * @param string $label button text
1209 * @param string $method get or post submit method
1210 * @param array $options associative array {disabled, title, etc.}
1211 * @return string HTML fragment
1213 public function single_button($url, $label, $method='post', array $options=null) {
1214 if (!($url instanceof moodle_url)) {
1215 $url = new moodle_url($url);
1217 $button = new single_button($url, $label, $method);
1219 foreach ((array)$options as $key=>$value) {
1220 if (array_key_exists($key, $button)) {
1221 $button->$key = $value;
1225 return $this->render($button);
1229 * Renders a single button widget.
1231 * This will return HTML to display a form containing a single button.
1233 * @param single_button $button
1234 * @return string HTML fragment
1236 protected function render_single_button(single_button $button) {
1237 $attributes = array('type' => 'submit',
1238 'value' => $button->label,
1239 'disabled' => $button->disabled ? 'disabled' : null,
1240 'title' => $button->tooltip);
1242 if ($button->actions) {
1243 $id = html_writer::random_id('single_button');
1244 $attributes['id'] = $id;
1245 foreach ($button->actions as $action) {
1246 $this->add_action_handler($action, $id);
1250 // first the input element
1251 $output = html_writer::empty_tag('input', $attributes);
1253 // then hidden fields
1254 $params = $button->url->params();
1255 if ($button->method === 'post') {
1256 $params['sesskey'] = sesskey();
1258 foreach ($params as $var => $val) {
1259 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1262 // then div wrapper for xhtml strictness
1263 $output = html_writer::tag('div', $output);
1265 // now the form itself around it
1266 if ($button->method === 'get') {
1267 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1269 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1272 $url = '#'; // there has to be always some action
1274 $attributes = array('method' => $button->method,
1276 'id' => $button->formid);
1277 $output = html_writer::tag('form', $output, $attributes);
1279 // and finally one more wrapper with class
1280 return html_writer::tag('div', $output, array('class' => $button->class));
1284 * Returns a form with a single select widget.
1286 * @param moodle_url $url form action target, includes hidden fields
1287 * @param string $name name of selection field - the changing parameter in url
1288 * @param array $options list of options
1289 * @param string $selected selected element
1290 * @param array $nothing
1291 * @param string $formid
1292 * @return string HTML fragment
1294 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1295 if (!($url instanceof moodle_url)) {
1296 $url = new moodle_url($url);
1298 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1300 return $this->render($select);
1304 * Internal implementation of single_select rendering
1306 * @param single_select $select
1307 * @return string HTML fragment
1309 protected function render_single_select(single_select $select) {
1310 $select = clone($select);
1311 if (empty($select->formid)) {
1312 $select->formid = html_writer::random_id('single_select_f');
1316 $params = $select->url->params();
1317 if ($select->method === 'post') {
1318 $params['sesskey'] = sesskey();
1320 foreach ($params as $name=>$value) {
1321 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1324 if (empty($select->attributes['id'])) {
1325 $select->attributes['id'] = html_writer::random_id('single_select');
1328 if ($select->disabled) {
1329 $select->attributes['disabled'] = 'disabled';
1332 if ($select->tooltip) {
1333 $select->attributes['title'] = $select->tooltip;
1336 if ($select->label) {
1337 $output .= html_writer::label($select->label, $select->attributes['id']);
1340 if ($select->helpicon instanceof help_icon) {
1341 $output .= $this->render($select->helpicon);
1342 } else if ($select->helpicon instanceof old_help_icon) {
1343 $output .= $this->render($select->helpicon);
1346 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1348 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1349 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('style'=>'inline'));
1351 $nothing = empty($select->nothing) ? false : key($select->nothing);
1352 $this->page->requires->js_init_call('M.util.init_select_autosubmit', array($select->formid, $select->attributes['id'], $nothing));
1354 // then div wrapper for xhtml strictness
1355 $output = html_writer::tag('div', $output);
1357 // now the form itself around it
1358 if ($select->method === 'get') {
1359 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1361 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1363 $formattributes = array('method' => $select->method,
1365 'id' => $select->formid);
1366 $output = html_writer::tag('form', $output, $formattributes);
1368 // and finally one more wrapper with class
1369 return html_writer::tag('div', $output, array('class' => $select->class));
1373 * Returns a form with a url select widget.
1375 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1376 * @param string $selected selected element
1377 * @param array $nothing
1378 * @param string $formid
1379 * @return string HTML fragment
1381 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1382 $select = new url_select($urls, $selected, $nothing, $formid);
1383 return $this->render($select);
1387 * Internal implementation of url_select rendering
1389 * @param url_select $select
1390 * @return string HTML fragment
1392 protected function render_url_select(url_select $select) {
1395 $select = clone($select);
1396 if (empty($select->formid)) {
1397 $select->formid = html_writer::random_id('url_select_f');
1400 if (empty($select->attributes['id'])) {
1401 $select->attributes['id'] = html_writer::random_id('url_select');
1404 if ($select->disabled) {
1405 $select->attributes['disabled'] = 'disabled';
1408 if ($select->tooltip) {
1409 $select->attributes['title'] = $select->tooltip;
1414 if ($select->label) {
1415 $output .= html_writer::label($select->label, $select->attributes['id']);
1418 if ($select->helpicon instanceof help_icon) {
1419 $output .= $this->render($select->helpicon);
1420 } else if ($select->helpicon instanceof old_help_icon) {
1421 $output .= $this->render($select->helpicon);
1424 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1425 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1427 foreach ($select->urls as $k=>$v) {
1429 // optgroup structure
1430 foreach ($v as $optgrouptitle => $optgroupoptions) {
1431 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1432 if (empty($optionurl)) {
1433 $safeoptionurl = '';
1434 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1435 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1436 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1437 } else if (strpos($optionurl, '/') !== 0) {
1438 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1441 $safeoptionurl = $optionurl;
1443 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1447 // plain list structure
1449 // nothing selected option
1450 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1451 $k = str_replace($CFG->wwwroot, '', $k);
1452 } else if (strpos($k, '/') !== 0) {
1453 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1459 $selected = $select->selected;
1460 if (!empty($selected)) {
1461 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1462 $selected = str_replace($CFG->wwwroot, '', $selected);
1463 } else if (strpos($selected, '/') !== 0) {
1464 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1468 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1469 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1471 if (!$select->showbutton) {
1472 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1473 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('style'=>'inline'));
1474 $nothing = empty($select->nothing) ? false : key($select->nothing);
1475 $output .= $this->page->requires->js_init_call('M.util.init_url_select', array($select->formid, $select->attributes['id'], $nothing));
1477 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1480 // then div wrapper for xhtml strictness
1481 $output = html_writer::tag('div', $output);
1483 // now the form itself around it
1484 $formattributes = array('method' => 'post',
1485 'action' => new moodle_url('/course/jumpto.php'),
1486 'id' => $select->formid);
1487 $output = html_writer::tag('form', $output, $formattributes);
1489 // and finally one more wrapper with class
1490 return html_writer::tag('div', $output, array('class' => $select->class));
1494 * Returns a string containing a link to the user documentation.
1495 * Also contains an icon by default. Shown to teachers and admin only.
1497 * @param string $path The page link after doc root and language, no leading slash.
1498 * @param string $text The text to be displayed for the link
1501 public function doc_link($path, $text = '') {
1504 $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp'));
1506 $url = new moodle_url(get_docs_url($path));
1508 $attributes = array('href'=>$url);
1509 if (!empty($CFG->doctonewwindow)) {
1510 $attributes['id'] = $this->add_action_handler(new popup_action('click', $url));
1513 return html_writer::tag('a', $icon.$text, $attributes);
1517 * Return HTML for a pix_icon.
1519 * @param string $pix short pix name
1520 * @param string $alt mandatory alt attribute
1521 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1522 * @param array $attributes htm lattributes
1523 * @return string HTML fragment
1525 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1526 $icon = new pix_icon($pix, $alt, $component, $attributes);
1527 return $this->render($icon);
1531 * Renders a pix_icon widget and returns the HTML to display it.
1533 * @param pix_icon $icon
1534 * @return string HTML fragment
1536 protected function render_pix_icon(pix_icon $icon) {
1537 $attributes = $icon->attributes;
1538 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1539 return html_writer::empty_tag('img', $attributes);
1543 * Return HTML to display an emoticon icon.
1545 * @param pix_emoticon $emoticon
1546 * @return string HTML fragment
1548 protected function render_pix_emoticon(pix_emoticon $emoticon) {
1549 $attributes = $emoticon->attributes;
1550 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
1551 return html_writer::empty_tag('img', $attributes);
1555 * Produces the html that represents this rating in the UI
1557 * @param rating $rating the page object on which this rating will appear
1560 function render_rating(rating $rating) {
1563 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
1564 return null;//ratings are turned off
1567 $ratingmanager = new rating_manager();
1568 // Initialise the JavaScript so ratings can be done by AJAX.
1569 $ratingmanager->initialise_rating_javascript($this->page);
1571 $strrate = get_string("rate", "rating");
1572 $ratinghtml = ''; //the string we'll return
1574 // permissions check - can they view the aggregate?
1575 if ($rating->user_can_view_aggregate()) {
1577 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
1578 $aggregatestr = $rating->get_aggregate_string();
1580 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
1581 if ($rating->count > 0) {
1582 $countstr = "({$rating->count})";
1586 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
1588 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
1589 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
1591 $nonpopuplink = $rating->get_view_ratings_url();
1592 $popuplink = $rating->get_view_ratings_url(true);
1594 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
1595 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
1597 $ratinghtml .= $aggregatehtml;
1602 // if the item doesn't belong to the current user, the user has permission to rate
1603 // and we're within the assessable period
1604 if ($rating->user_can_rate()) {
1606 $rateurl = $rating->get_rate_url();
1607 $inputs = $rateurl->params();
1609 //start the rating form
1611 'id' => "postrating{$rating->itemid}",
1612 'class' => 'postratingform',
1614 'action' => $rateurl->out_omit_querystring()
1616 $formstart = html_writer::start_tag('form', $formattrs);
1617 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
1619 // add the hidden inputs
1620 foreach ($inputs as $name => $value) {
1621 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
1622 $formstart .= html_writer::empty_tag('input', $attributes);
1625 if (empty($ratinghtml)) {
1626 $ratinghtml .= $strrate.': ';
1628 $ratinghtml = $formstart.$ratinghtml;
1630 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
1631 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
1632 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
1634 //output submit button
1635 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
1637 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
1638 $ratinghtml .= html_writer::empty_tag('input', $attributes);
1640 if (!$rating->settings->scale->isnumeric) {
1641 $ratinghtml .= $this->help_icon_scale($rating->settings->scale->courseid, $rating->settings->scale);
1643 $ratinghtml .= html_writer::end_tag('span');
1644 $ratinghtml .= html_writer::end_tag('div');
1645 $ratinghtml .= html_writer::end_tag('form');
1652 * Centered heading with attached help button (same title text)
1653 * and optional icon attached.
1655 * @param string $text A heading text
1656 * @param string $helpidentifier The keyword that defines a help page
1657 * @param string $component component name
1658 * @param string|moodle_url $icon
1659 * @param string $iconalt icon alt text
1660 * @return string HTML fragment
1662 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '') {
1665 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon'));
1669 if ($helpidentifier) {
1670 $help = $this->help_icon($helpidentifier, $component);
1673 return $this->heading($image.$text.$help, 2, 'main help');
1677 * Returns HTML to display a help icon.
1679 * @deprecated since Moodle 2.0
1680 * @param string $helpidentifier The keyword that defines a help page
1681 * @param string $title A descriptive text for accessibility only
1682 * @param string $component component name
1683 * @param string|bool $linktext true means use $title as link text, string means link text value
1684 * @return string HTML fragment
1686 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
1687 debugging('The method old_help_icon() is deprecated, please fix the code and use help_icon() method instead', DEBUG_DEVELOPER);
1688 $icon = new old_help_icon($helpidentifier, $title, $component);
1689 if ($linktext === true) {
1690 $icon->linktext = $title;
1691 } else if (!empty($linktext)) {
1692 $icon->linktext = $linktext;
1694 return $this->render($icon);
1698 * Implementation of user image rendering.
1700 * @param old_help_icon $helpicon A help icon instance
1701 * @return string HTML fragment
1703 protected function render_old_help_icon(old_help_icon $helpicon) {
1706 // first get the help image icon
1707 $src = $this->pix_url('help');
1709 if (empty($helpicon->linktext)) {
1710 $alt = $helpicon->title;
1712 $alt = get_string('helpwiththis');
1715 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1716 $output = html_writer::empty_tag('img', $attributes);
1718 // add the link text if given
1719 if (!empty($helpicon->linktext)) {
1720 // the spacing has to be done through CSS
1721 $output .= $helpicon->linktext;
1724 // now create the link around it - we need https on loginhttps pages
1725 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->helpidentifier, 'lang'=>current_language()));
1727 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1728 $title = get_string('helpprefix2', '', trim($helpicon->title, ". \t"));
1730 $attributes = array('href'=>$url, 'title'=>$title);
1731 $id = html_writer::random_id('helpicon');
1732 $attributes['id'] = $id;
1733 $output = html_writer::tag('a', $output, $attributes);
1735 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1738 return html_writer::tag('span', $output, array('class' => 'helplink'));
1742 * Returns HTML to display a help icon.
1744 * @param string $identifier The keyword that defines a help page
1745 * @param string $component component name
1746 * @param string|bool $linktext true means use $title as link text, string means link text value
1747 * @return string HTML fragment
1749 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
1750 $icon = new help_icon($identifier, $component);
1751 $icon->diag_strings();
1752 if ($linktext === true) {
1753 $icon->linktext = get_string($icon->identifier, $icon->component);
1754 } else if (!empty($linktext)) {
1755 $icon->linktext = $linktext;
1757 return $this->render($icon);
1761 * Implementation of user image rendering.
1763 * @param help_icon $helpicon A help icon instance
1764 * @return string HTML fragment
1766 protected function render_help_icon(help_icon $helpicon) {
1769 // first get the help image icon
1770 $src = $this->pix_url('help');
1772 $title = get_string($helpicon->identifier, $helpicon->component);
1774 if (empty($helpicon->linktext)) {
1775 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
1777 $alt = get_string('helpwiththis');
1780 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
1781 $output = html_writer::empty_tag('img', $attributes);
1783 // add the link text if given
1784 if (!empty($helpicon->linktext)) {
1785 // the spacing has to be done through CSS
1786 $output .= $helpicon->linktext;
1789 // now create the link around it - we need https on loginhttps pages
1790 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
1792 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
1793 $title = get_string('helpprefix2', '', trim($title, ". \t"));
1795 $attributes = array('href'=>$url, 'title'=>$title);
1796 $id = html_writer::random_id('helpicon');
1797 $attributes['id'] = $id;
1798 $output = html_writer::tag('a', $output, $attributes);
1800 $this->page->requires->js_init_call('M.util.help_icon.add', array(array('id'=>$id, 'url'=>$url->out(false))));
1803 return html_writer::tag('span', $output, array('class' => 'helplink'));
1807 * Returns HTML to display a scale help icon.
1809 * @param int $courseid
1810 * @param stdClass $scale instance
1811 * @return string HTML fragment
1813 public function help_icon_scale($courseid, stdClass $scale) {
1816 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
1818 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
1820 $scaleid = abs($scale->id);
1822 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
1823 $action = new popup_action('click', $link, 'ratingscale');
1825 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
1829 * Creates and returns a spacer image with optional line break.
1831 * @param array $attributes Any HTML attributes to add to the spaced.
1832 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
1833 * laxy do it with CSS which is a much better solution.
1834 * @return string HTML fragment
1836 public function spacer(array $attributes = null, $br = false) {
1837 $attributes = (array)$attributes;
1838 if (empty($attributes['width'])) {
1839 $attributes['width'] = 1;
1841 if (empty($attributes['height'])) {
1842 $attributes['height'] = 1;
1844 $attributes['class'] = 'spacer';
1846 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
1849 $output .= '<br />';
1856 * Returns HTML to display the specified user's avatar.
1858 * User avatar may be obtained in two ways:
1860 * // Option 1: (shortcut for simple cases, preferred way)
1861 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
1862 * $OUTPUT->user_picture($user, array('popup'=>true));
1865 * $userpic = new user_picture($user);
1866 * // Set properties of $userpic
1867 * $userpic->popup = true;
1868 * $OUTPUT->render($userpic);
1871 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
1872 * If any of these are missing, the database is queried. Avoid this
1873 * if at all possible, particularly for reports. It is very bad for performance.
1874 * @param array $options associative array with user picture options, used only if not a user_picture object,
1876 * - courseid=$this->page->course->id (course id of user profile in link)
1877 * - size=35 (size of image)
1878 * - link=true (make image clickable - the link leads to user profile)
1879 * - popup=false (open in popup)
1880 * - alttext=true (add image alt attribute)
1881 * - class = image class attribute (default 'userpicture')
1882 * @return string HTML fragment
1884 public function user_picture(stdClass $user, array $options = null) {
1885 $userpicture = new user_picture($user);
1886 foreach ((array)$options as $key=>$value) {
1887 if (array_key_exists($key, $userpicture)) {
1888 $userpicture->$key = $value;
1891 return $this->render($userpicture);
1895 * Internal implementation of user image rendering.
1897 * @param user_picture $userpicture
1900 protected function render_user_picture(user_picture $userpicture) {
1903 $user = $userpicture->user;
1905 if ($userpicture->alttext) {
1906 if (!empty($user->imagealt)) {
1907 $alt = $user->imagealt;
1909 $alt = get_string('pictureof', '', fullname($user));
1915 if (empty($userpicture->size)) {
1917 } else if ($userpicture->size === true or $userpicture->size == 1) {
1920 $size = $userpicture->size;
1923 $class = $userpicture->class;
1925 if ($user->picture == 0) {
1926 $class .= ' defaultuserpic';
1929 $src = $userpicture->get_url($this->page, $this);
1931 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
1933 // get the image html output fisrt
1934 $output = html_writer::empty_tag('img', $attributes);;
1936 // then wrap it in link if needed
1937 if (!$userpicture->link) {
1941 if (empty($userpicture->courseid)) {
1942 $courseid = $this->page->course->id;
1944 $courseid = $userpicture->courseid;
1947 if ($courseid == SITEID) {
1948 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
1950 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
1953 $attributes = array('href'=>$url);
1955 if ($userpicture->popup) {
1956 $id = html_writer::random_id('userpicture');
1957 $attributes['id'] = $id;
1958 $this->add_action_handler(new popup_action('click', $url), $id);
1961 return html_writer::tag('a', $output, $attributes);
1965 * Internal implementation of file tree viewer items rendering.
1970 public function htmllize_file_tree($dir) {
1971 if (empty($dir['subdirs']) and empty($dir['files'])) {
1975 foreach ($dir['subdirs'] as $subdir) {
1976 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
1978 foreach ($dir['files'] as $file) {
1979 $filename = $file->get_filename();
1980 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
1988 * Returns HTML to display the file picker
1991 * $OUTPUT->file_picker($options);
1994 * @param array $options associative array with file manager options
1998 * client_id=>uniqid(),
1999 * acepted_types=>'*',
2000 * return_types=>FILE_INTERNAL,
2001 * context=>$PAGE->context
2002 * @return string HTML fragment
2004 public function file_picker($options) {
2005 $fp = new file_picker($options);
2006 return $this->render($fp);
2010 * Internal implementation of file picker rendering.
2012 * @param file_picker $fp
2015 public function render_file_picker(file_picker $fp) {
2016 global $CFG, $OUTPUT, $USER;
2017 $options = $fp->options;
2018 $client_id = $options->client_id;
2019 $strsaved = get_string('filesaved', 'repository');
2020 $straddfile = get_string('openpicker', 'repository');
2021 $strloading = get_string('loading', 'repository');
2022 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2023 $strdroptoupload = get_string('droptoupload', 'moodle');
2024 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2026 $currentfile = $options->currentfile;
2027 if (empty($currentfile)) {
2030 $currentfile .= ' - ';
2032 if ($options->maxbytes) {
2033 $size = $options->maxbytes;
2035 $size = get_max_upload_file_size();
2040 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2042 if ($options->buttonname) {
2043 $buttonname = ' name="' . $options->buttonname . '"';
2048 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2051 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2053 <input type="button" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2054 <span> $maxsize </span>
2057 if ($options->env != 'url') {
2059 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2060 <div class="filepicker-filename">
2061 <div class="filepicker-container">$currentfile<span class="dndupload-message">$strdndenabled <br/><span class="dndupload-arrow"></span></span></div>
2063 <div><div class="dndupload-target">{$strdroptoupload}<br/><span class="dndupload-arrow"></span></div></div>
2072 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2074 * @param string $cmid the course_module id.
2075 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2076 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2078 public function update_module_button($cmid, $modulename) {
2080 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $cmid))) {
2081 $modulename = get_string('modulename', $modulename);
2082 $string = get_string('updatethis', '', $modulename);
2083 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2084 return $this->single_button($url, $string);
2091 * Returns HTML to display a "Turn editing on/off" button in a form.
2093 * @param moodle_url $url The URL + params to send through when clicking the button
2094 * @return string HTML the button
2096 public function edit_button(moodle_url $url) {
2098 $url->param('sesskey', sesskey());
2099 if ($this->page->user_is_editing()) {
2100 $url->param('edit', 'off');
2101 $editstring = get_string('turneditingoff');
2103 $url->param('edit', 'on');
2104 $editstring = get_string('turneditingon');
2107 return $this->single_button($url, $editstring);
2111 * Returns HTML to display a simple button to close a window
2113 * @param string $text The lang string for the button's label (already output from get_string())
2114 * @return string html fragment
2116 public function close_window_button($text='') {
2118 $text = get_string('closewindow');
2120 $button = new single_button(new moodle_url('#'), $text, 'get');
2121 $button->add_action(new component_action('click', 'close_window'));
2123 return $this->container($this->render($button), 'closewindow');
2127 * Output an error message. By default wraps the error message in <span class="error">.
2128 * If the error message is blank, nothing is output.
2130 * @param string $message the error message.
2131 * @return string the HTML to output.
2133 public function error_text($message) {
2134 if (empty($message)) {
2137 return html_writer::tag('span', $message, array('class' => 'error'));
2141 * Do not call this function directly.
2143 * To terminate the current script with a fatal error, call the {@link print_error}
2144 * function, or throw an exception. Doing either of those things will then call this
2145 * function to display the error, before terminating the execution.
2147 * @param string $message The message to output
2148 * @param string $moreinfourl URL where more info can be found about the error
2149 * @param string $link Link for the Continue button
2150 * @param array $backtrace The execution backtrace
2151 * @param string $debuginfo Debugging information
2152 * @return string the HTML to output.
2154 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2160 if ($this->has_started()) {
2161 // we can not always recover properly here, we have problems with output buffering,
2162 // html tables, etc.
2163 $output .= $this->opencontainers->pop_all_but_last();
2166 // It is really bad if library code throws exception when output buffering is on,
2167 // because the buffered text would be printed before our start of page.
2168 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2169 error_reporting(0); // disable notices from gzip compression, etc.
2170 while (ob_get_level() > 0) {
2171 $buff = ob_get_clean();
2172 if ($buff === false) {
2177 error_reporting($CFG->debug);
2179 // Header not yet printed
2180 if (isset($_SERVER['SERVER_PROTOCOL'])) {
2181 // server protocol should be always present, because this render
2182 // can not be used from command line or when outputting custom XML
2183 @header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
2185 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2186 $this->page->set_url('/'); // no url
2187 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2188 $this->page->set_title(get_string('error'));
2189 $this->page->set_heading($this->page->course->fullname);
2190 $output .= $this->header();
2193 $message = '<p class="errormessage">' . $message . '</p>'.
2194 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2195 get_string('moreinformation') . '</a></p>';
2196 if (empty($CFG->rolesactive)) {
2197 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2198 //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.
2200 $output .= $this->box($message, 'errorbox');
2202 if (debugging('', DEBUG_DEVELOPER)) {
2203 if (!empty($debuginfo)) {
2204 $debuginfo = s($debuginfo); // removes all nasty JS
2205 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2206 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2208 if (!empty($backtrace)) {
2209 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2211 if ($obbuffer !== '' ) {
2212 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2216 if (empty($CFG->rolesactive)) {
2217 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2218 } else if (!empty($link)) {
2219 $output .= $this->continue_button($link);
2222 $output .= $this->footer();
2224 // Padding to encourage IE to display our error page, rather than its own.
2225 $output .= str_repeat(' ', 512);
2231 * Output a notification (that is, a status message about something that has
2234 * @param string $message the message to print out
2235 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2236 * @return string the HTML to output.
2238 public function notification($message, $classes = 'notifyproblem') {
2239 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2243 * Returns HTML to display a continue button that goes to a particular URL.
2245 * @param string|moodle_url $url The url the button goes to.
2246 * @return string the HTML to output.
2248 public function continue_button($url) {
2249 if (!($url instanceof moodle_url)) {
2250 $url = new moodle_url($url);
2252 $button = new single_button($url, get_string('continue'), 'get');
2253 $button->class = 'continuebutton';
2255 return $this->render($button);
2259 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2261 * @param int $totalcount The total number of entries available to be paged through
2262 * @param int $page The page you are currently viewing
2263 * @param int $perpage The number of entries that should be shown per page
2264 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2265 * @param string $pagevar name of page parameter that holds the page number
2266 * @return string the HTML to output.
2268 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2269 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2270 return $this->render($pb);
2274 * Internal implementation of paging bar rendering.
2276 * @param paging_bar $pagingbar
2279 protected function render_paging_bar(paging_bar $pagingbar) {
2281 $pagingbar = clone($pagingbar);
2282 $pagingbar->prepare($this, $this->page, $this->target);
2284 if ($pagingbar->totalcount > $pagingbar->perpage) {
2285 $output .= get_string('page') . ':';
2287 if (!empty($pagingbar->previouslink)) {
2288 $output .= ' (' . $pagingbar->previouslink . ') ';
2291 if (!empty($pagingbar->firstlink)) {
2292 $output .= ' ' . $pagingbar->firstlink . ' ...';
2295 foreach ($pagingbar->pagelinks as $link) {
2296 $output .= "  $link";
2299 if (!empty($pagingbar->lastlink)) {
2300 $output .= ' ...' . $pagingbar->lastlink . ' ';
2303 if (!empty($pagingbar->nextlink)) {
2304 $output .= '  (' . $pagingbar->nextlink . ')';
2308 return html_writer::tag('div', $output, array('class' => 'paging'));
2312 * Output the place a skip link goes to.
2314 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2315 * @return string the HTML to output.
2317 public function skip_link_target($id = null) {
2318 return html_writer::tag('span', '', array('id' => $id));
2324 * @param string $text The text of the heading
2325 * @param int $level The level of importance of the heading. Defaulting to 2
2326 * @param string $classes A space-separated list of CSS classes
2327 * @param string $id An optional ID
2328 * @return string the HTML to output.
2330 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2331 $level = (integer) $level;
2332 if ($level < 1 or $level > 6) {
2333 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2335 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2341 * @param string $contents The contents of the box
2342 * @param string $classes A space-separated list of CSS classes
2343 * @param string $id An optional ID
2344 * @return string the HTML to output.
2346 public function box($contents, $classes = 'generalbox', $id = null) {
2347 return $this->box_start($classes, $id) . $contents . $this->box_end();
2351 * Outputs the opening section of a box.
2353 * @param string $classes A space-separated list of CSS classes
2354 * @param string $id An optional ID
2355 * @return string the HTML to output.
2357 public function box_start($classes = 'generalbox', $id = null) {
2358 $this->opencontainers->push('box', html_writer::end_tag('div'));
2359 return html_writer::start_tag('div', array('id' => $id,
2360 'class' => 'box ' . renderer_base::prepare_classes($classes)));
2364 * Outputs the closing section of a box.
2366 * @return string the HTML to output.
2368 public function box_end() {
2369 return $this->opencontainers->pop('box');
2373 * Outputs a container.
2375 * @param string $contents The contents of the box
2376 * @param string $classes A space-separated list of CSS classes
2377 * @param string $id An optional ID
2378 * @return string the HTML to output.
2380 public function container($contents, $classes = null, $id = null) {
2381 return $this->container_start($classes, $id) . $contents . $this->container_end();
2385 * Outputs the opening section of a container.
2387 * @param string $classes A space-separated list of CSS classes
2388 * @param string $id An optional ID
2389 * @return string the HTML to output.
2391 public function container_start($classes = null, $id = null) {
2392 $this->opencontainers->push('container', html_writer::end_tag('div'));
2393 return html_writer::start_tag('div', array('id' => $id,
2394 'class' => renderer_base::prepare_classes($classes)));
2398 * Outputs the closing section of a container.
2400 * @return string the HTML to output.
2402 public function container_end() {
2403 return $this->opencontainers->pop('container');
2407 * Make nested HTML lists out of the items
2409 * The resulting list will look something like this:
2413 * <<li>><div class='tree_item parent'>(item contents)</div>
2415 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2421 * @param array $items
2422 * @param array $attrs html attributes passed to the top ofs the list
2423 * @return string HTML
2425 public function tree_block_contents($items, $attrs = array()) {
2426 // exit if empty, we don't want an empty ul element
2427 if (empty($items)) {
2430 // array of nested li elements
2432 foreach ($items as $item) {
2433 // this applies to the li item which contains all child lists too
2434 $content = $item->content($this);
2435 $liclasses = array($item->get_css_type());
2436 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2437 $liclasses[] = 'collapsed';
2439 if ($item->isactive === true) {
2440 $liclasses[] = 'current_branch';
2442 $liattr = array('class'=>join(' ',$liclasses));
2443 // class attribute on the div item which only contains the item content
2444 $divclasses = array('tree_item');
2445 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2446 $divclasses[] = 'branch';
2448 $divclasses[] = 'leaf';
2450 if (!empty($item->classes) && count($item->classes)>0) {
2451 $divclasses[] = join(' ', $item->classes);
2453 $divattr = array('class'=>join(' ', $divclasses));
2454 if (!empty($item->id)) {
2455 $divattr['id'] = $item->id;
2457 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2458 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2459 $content = html_writer::empty_tag('hr') . $content;
2461 $content = html_writer::tag('li', $content, $liattr);
2464 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2468 * Return the navbar content so that it can be echoed out by the layout
2470 * @return string XHTML navbar
2472 public function navbar() {
2473 $items = $this->page->navbar->get_items();
2475 $htmlblocks = array();
2476 // Iterate the navarray and display each node
2477 $itemcount = count($items);
2478 $separator = get_separator();
2479 for ($i=0;$i < $itemcount;$i++) {
2481 $item->hideicon = true;
2483 $content = html_writer::tag('li', $this->render($item));
2485 $content = html_writer::tag('li', $separator.$this->render($item));
2487 $htmlblocks[] = $content;
2490 //accessibility: heading for navbar list (MDL-20446)
2491 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2492 $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks));
2494 return $navbarcontent;
2498 * Renders a navigation node object.
2500 * @param navigation_node $item The navigation node to render.
2501 * @return string HTML fragment
2503 protected function render_navigation_node(navigation_node $item) {
2504 $content = $item->get_content();
2505 $title = $item->get_title();
2506 if ($item->icon instanceof renderable && !$item->hideicon) {
2507 $icon = $this->render($item->icon);
2508 $content = $icon.$content; // use CSS for spacing of icons
2510 if ($item->helpbutton !== null) {
2511 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2513 if ($content === '') {
2516 if ($item->action instanceof action_link) {
2517 $link = $item->action;
2518 if ($item->hidden) {
2519 $link->add_class('dimmed');
2521 if (!empty($content)) {
2522 // Providing there is content we will use that for the link content.
2523 $link->text = $content;
2525 $content = $this->render($link);
2526 } else if ($item->action instanceof moodle_url) {
2527 $attributes = array();
2528 if ($title !== '') {
2529 $attributes['title'] = $title;
2531 if ($item->hidden) {
2532 $attributes['class'] = 'dimmed_text';
2534 $content = html_writer::link($item->action, $content, $attributes);
2536 } else if (is_string($item->action) || empty($item->action)) {
2537 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2538 if ($title !== '') {
2539 $attributes['title'] = $title;
2541 if ($item->hidden) {
2542 $attributes['class'] = 'dimmed_text';
2544 $content = html_writer::tag('span', $content, $attributes);
2550 * Accessibility: Right arrow-like character is
2551 * used in the breadcrumb trail, course navigation menu
2552 * (previous/next activity), calendar, and search forum block.
2553 * If the theme does not set characters, appropriate defaults
2554 * are set automatically. Please DO NOT
2555 * use < > » - these are confusing for blind users.
2559 public function rarrow() {
2560 return $this->page->theme->rarrow;
2564 * Accessibility: Right arrow-like character is
2565 * used in the breadcrumb trail, course navigation menu
2566 * (previous/next activity), calendar, and search forum block.
2567 * If the theme does not set characters, appropriate defaults
2568 * are set automatically. Please DO NOT
2569 * use < > » - these are confusing for blind users.
2573 public function larrow() {
2574 return $this->page->theme->larrow;
2578 * Returns the custom menu if one has been set
2580 * A custom menu can be configured by browsing to
2581 * Settings: Administration > Appearance > Themes > Theme settings
2582 * and then configuring the custommenu config setting as described.
2584 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
2587 public function custom_menu($custommenuitems = '') {
2589 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
2590 $custommenuitems = $CFG->custommenuitems;
2592 if (empty($custommenuitems)) {
2595 $custommenu = new custom_menu($custommenuitems, current_language());
2596 return $this->render_custom_menu($custommenu);
2600 * Renders a custom menu object (located in outputcomponents.php)
2602 * The custom menu this method produces makes use of the YUI3 menunav widget
2603 * and requires very specific html elements and classes.
2605 * @staticvar int $menucount
2606 * @param custom_menu $menu
2609 protected function render_custom_menu(custom_menu $menu) {
2610 static $menucount = 0;
2611 // If the menu has no children return an empty string
2612 if (!$menu->has_children()) {
2615 // Increment the menu count. This is used for ID's that get worked with
2616 // in JavaScript as is essential
2618 // Initialise this custom menu (the custom menu object is contained in javascript-static
2619 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
2620 $jscode = "(function(){{$jscode}})";
2621 $this->page->requires->yui_module('node-menunav', $jscode);
2622 // Build the root nodes as required by YUI
2623 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled'));
2624 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2625 $content .= html_writer::start_tag('ul');
2626 // Render each child
2627 foreach ($menu->get_children() as $item) {
2628 $content .= $this->render_custom_menu_item($item);
2630 // Close the open tags
2631 $content .= html_writer::end_tag('ul');
2632 $content .= html_writer::end_tag('div');
2633 $content .= html_writer::end_tag('div');
2634 // Return the custom menu
2639 * Renders a custom menu node as part of a submenu
2641 * The custom menu this method produces makes use of the YUI3 menunav widget
2642 * and requires very specific html elements and classes.
2644 * @see core:renderer::render_custom_menu()
2646 * @staticvar int $submenucount
2647 * @param custom_menu_item $menunode
2650 protected function render_custom_menu_item(custom_menu_item $menunode) {
2651 // Required to ensure we get unique trackable id's
2652 static $submenucount = 0;
2653 if ($menunode->has_children()) {
2654 // If the child has menus render it as a sub menu
2656 $content = html_writer::start_tag('li');
2657 if ($menunode->get_url() !== null) {
2658 $url = $menunode->get_url();
2660 $url = '#cm_submenu_'.$submenucount;
2662 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
2663 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
2664 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
2665 $content .= html_writer::start_tag('ul');
2666 foreach ($menunode->get_children() as $menunode) {
2667 $content .= $this->render_custom_menu_item($menunode);
2669 $content .= html_writer::end_tag('ul');
2670 $content .= html_writer::end_tag('div');
2671 $content .= html_writer::end_tag('div');
2672 $content .= html_writer::end_tag('li');
2674 // The node doesn't have children so produce a final menuitem
2675 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
2676 if ($menunode->get_url() !== null) {
2677 $url = $menunode->get_url();
2681 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
2682 $content .= html_writer::end_tag('li');
2684 // Return the sub menu
2689 * Renders theme links for switching between default and other themes.
2693 protected function theme_switch_links() {
2695 $actualdevice = get_device_type();
2696 $currentdevice = $this->page->devicetypeinuse;
2697 $switched = ($actualdevice != $currentdevice);
2699 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
2700 // The user is using the a default device and hasn't switched so don't shown the switch
2706 $linktext = get_string('switchdevicerecommended');
2707 $devicetype = $actualdevice;
2709 $linktext = get_string('switchdevicedefault');
2710 $devicetype = 'default';
2712 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
2714 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
2715 $content .= html_writer::link($linkurl, $linktext);
2716 $content .= html_writer::end_tag('div');
2723 * A renderer that generates output for command-line scripts.
2725 * The implementation of this renderer is probably incomplete.
2727 * @copyright 2009 Tim Hunt
2728 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2733 class core_renderer_cli extends core_renderer {
2736 * Returns the page header.
2738 * @return string HTML fragment
2740 public function header() {
2741 return $this->page->heading . "\n";
2745 * Returns a template fragment representing a Heading.
2747 * @param string $text The text of the heading
2748 * @param int $level The level of importance of the heading
2749 * @param string $classes A space-separated list of CSS classes
2750 * @param string $id An optional ID
2751 * @return string A template fragment for a heading
2753 public function heading($text, $level = 2, $classes = 'main', $id = null) {
2757 return '=>' . $text;
2759 return '-->' . $text;
2766 * Returns a template fragment representing a fatal error.
2768 * @param string $message The message to output
2769 * @param string $moreinfourl URL where more info can be found about the error
2770 * @param string $link Link for the Continue button
2771 * @param array $backtrace The execution backtrace
2772 * @param string $debuginfo Debugging information
2773 * @return string A template fragment for a fatal error
2775 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2776 $output = "!!! $message !!!\n";
2778 if (debugging('', DEBUG_DEVELOPER)) {
2779 if (!empty($debuginfo)) {
2780 $output .= $this->notification($debuginfo, 'notifytiny');
2782 if (!empty($backtrace)) {
2783 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
2791 * Returns a template fragment representing a notification.
2793 * @param string $message The message to include
2794 * @param string $classes A space-separated list of CSS classes
2795 * @return string A template fragment for a notification
2797 public function notification($message, $classes = 'notifyproblem') {
2798 $message = clean_text($message);
2799 if ($classes === 'notifysuccess') {
2800 return "++ $message ++\n";
2802 return "!! $message !!\n";
2808 * A renderer that generates output for ajax scripts.
2810 * This renderer prevents accidental sends back only json
2811 * encoded error messages, all other output is ignored.
2813 * @copyright 2010 Petr Skoda
2814 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2819 class core_renderer_ajax extends core_renderer {
2822 * Returns a template fragment representing a fatal error.
2824 * @param string $message The message to output
2825 * @param string $moreinfourl URL where more info can be found about the error
2826 * @param string $link Link for the Continue button
2827 * @param array $backtrace The execution backtrace
2828 * @param string $debuginfo Debugging information
2829 * @return string A template fragment for a fatal error
2831 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2834 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2836 $e = new stdClass();
2837 $e->error = $message;
2838 $e->stacktrace = NULL;
2839 $e->debuginfo = NULL;
2840 $e->reproductionlink = NULL;
2841 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
2842 $e->reproductionlink = $link;
2843 if (!empty($debuginfo)) {
2844 $e->debuginfo = $debuginfo;
2846 if (!empty($backtrace)) {
2847 $e->stacktrace = format_backtrace($backtrace, true);
2851 return json_encode($e);
2855 * Used to display a notification.
2856 * For the AJAX notifications are discarded.
2858 * @param string $message
2859 * @param string $classes
2861 public function notification($message, $classes = 'notifyproblem') {}
2864 * Used to display a redirection message.
2865 * AJAX redirections should not occur and as such redirection messages
2868 * @param moodle_url|string $encodedurl
2869 * @param string $message
2871 * @param bool $debugdisableredirect
2873 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
2876 * Prepares the start of an AJAX output.
2878 public function header() {
2879 // unfortunately YUI iframe upload does not support application/json
2880 if (!empty($_FILES)) {
2881 @header('Content-type: text/plain; charset=utf-8');
2883 @header('Content-type: application/json; charset=utf-8');
2886 // Headers to make it not cacheable and json
2887 @header('Cache-Control: no-store, no-cache, must-revalidate');
2888 @header('Cache-Control: post-check=0, pre-check=0', false);
2889 @header('Pragma: no-cache');
2890 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2891 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2892 @header('Accept-Ranges: none');
2896 * There is no footer for an AJAX request, however we must override the
2897 * footer method to prevent the default footer.
2899 public function footer() {}
2902 * No need for headers in an AJAX request... this should never happen.
2903 * @param string $text
2905 * @param string $classes
2908 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
2913 * Renderer for media files.
2915 * Used in file resources, media filter, and any other places that need to
2916 * output embedded media.
2918 * @copyright 2011 The Open University
2919 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2921 class core_media_renderer extends plugin_renderer_base {
2922 /** @var array Array of available 'player' objects */
2924 /** @var string Regex pattern for links which may contain embeddable content */
2925 private $embeddablemarkers;
2928 * Constructor requires medialib.php.
2930 * This is needed in the constructor (not later) so that you can use the
2931 * constants and static functions that are defined in core_media class
2932 * before you call renderer functions.
2934 public function __construct() {
2936 require_once($CFG->libdir . '/medialib.php');
2940 * Obtains the list of core_media_player objects currently in use to render
2943 * The list is in rank order (highest first) and does not include players
2944 * which are disabled.
2946 * @return array Array of core_media_player objects in rank order
2948 protected function get_players() {
2951 // Save time by only building the list once.
2952 if (!$this->players) {
2953 // Get raw list of players.
2954 $players = $this->get_players_raw();
2956 // Chuck all the ones that are disabled.
2957 foreach ($players as $key => $player) {
2958 if (!$player->is_enabled()) {
2959 unset($players[$key]);
2963 // Sort in rank order (highest first).
2964 usort($players, array('core_media_player', 'compare_by_rank'));
2965 $this->players = $players;
2967 return $this->players;
2971 * Obtains a raw list of player objects that includes objects regardless
2972 * of whether they are disabled or not, and without sorting.
2974 * You can override this in a subclass if you need to add additional
2977 * The return array is be indexed by player name to make it easier to
2978 * remove players in a subclass.
2980 * @return array $players Array of core_media_player objects in any order
2982 protected function get_players_raw() {
2984 'vimeo' => new core_media_player_vimeo(),
2985 'youtube' => new core_media_player_youtube(),
2986 'youtube_playlist' => new core_media_player_youtube_playlist(),
2987 'html5video' => new core_media_player_html5video(),
2988 'html5audio' => new core_media_player_html5audio(),
2989 'mp3' => new core_media_player_mp3(),
2990 'flv' => new core_media_player_flv(),
2991 'wmp' => new core_media_player_wmp(),
2992 'qt' => new core_media_player_qt(),
2993 'rm' => new core_media_player_rm(),
2994 'swf' => new core_media_player_swf(),
2995 'link' => new core_media_player_link(),
3000 * Renders a media file (audio or video) using suitable embedded player.
3002 * See embed_alternatives function for full description of parameters.
3003 * This function calls through to that one.
3005 * When using this function you can also specify width and height in the
3006 * URL by including ?d=100x100 at the end. If specified in the URL, this
3007 * will override the $width and $height parameters.
3009 * @param moodle_url $url Full URL of media file
3010 * @param string $name Optional user-readable name to display in download link
3011 * @param int $width Width in pixels (optional)
3012 * @param int $height Height in pixels (optional)
3013 * @param array $options Array of key/value pairs
3014 * @return string HTML content of embed
3016 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
3017 $options = array()) {
3019 // Get width and height from URL if specified (overrides parameters in
3021 $rawurl = $url->out(false);
3022 if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
3023 $width = $matches[1];
3024 $height = $matches[2];
3025 $url = new moodle_url(str_replace($matches[0], '', $rawurl));
3028 // Defer to array version of function.
3029 return $this->embed_alternatives(array($url), $name, $width, $height, $options);
3033 * Renders media files (audio or video) using suitable embedded player.
3034 * The list of URLs should be alternative versions of the same content in
3035 * multiple formats. If there is only one format it should have a single
3038 * If the media files are not in a supported format, this will give students
3039 * a download link to each format. The download link uses the filename
3040 * unless you supply the optional name parameter.
3042 * Width and height are optional. If specified, these are suggested sizes
3043 * and should be the exact values supplied by the user, if they come from
3044 * user input. These will be treated as relating to the size of the video
3045 * content, not including any player control bar.
3047 * For audio files, height will be ignored. For video files, a few formats
3048 * work if you specify only width, but in general if you specify width
3049 * you must specify height as well.
3051 * The $options array is passed through to the core_media_player classes
3052 * that render the object tag. The keys can contain values from
3053 * core_media::OPTION_xx.
3055 * @param array $alternatives Array of moodle_url to media files
3056 * @param string $name Optional user-readable name to display in download link
3057 * @param int $width Width in pixels (optional)
3058 * @param int $height Height in pixels (optional)
3059 * @param array $options Array of key/value pairs
3060 * @return string HTML content of embed
3062 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
3063 $options = array()) {
3065 // Get list of player plugins (will also require the library).
3066 $players = $this->get_players();
3068 // Set up initial text which will be replaced by first player that
3069 // supports any of the formats.
3070 $out = core_media_player::PLACEHOLDER;
3072 // Loop through all players that support any of these URLs.
3073 foreach ($players as $player) {
3074 // Option: When no other player matched, don't do the default link player.
3075 if (!empty($options[core_media::OPTION_FALLBACK_TO_BLANK]) &&
3076 $player->get_rank() === 0 && $out === core_media_player::PLACEHOLDER) {
3080 $supported = $player->list_supported_urls($alternatives, $options);
3083 $text = $player->embed($supported, $name, $width, $height, $options);
3085 // Put this in place of the 'fallback' slot in the previous text.
3086 $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
3090 // Remove 'fallback' slot from final version and return it.
3091 $out = str_replace(core_media_player::PLACEHOLDER, '', $out);
3092 if (!empty($options[core_media::OPTION_BLOCK]) && $out !== '') {
3093 $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
3099 * Checks whether a file can be embedded. If this returns true you will get
3100 * an embedded player; if this returns false, you will just get a download
3103 * This is a wrapper for can_embed_urls.
3105 * @param moodle_url $url URL of media file
3106 * @param array $options Options (same as when embedding)
3107 * @return bool True if file can be embedded
3109 public function can_embed_url(moodle_url $url, $options = array()) {
3110 return $this->can_embed_urls(array($url), $options);
3114 * Checks whether a file can be embedded. If this returns true you will get
3115 * an embedded player; if this returns false, you will just get a download
3118 * @param array $urls URL of media file and any alternatives (moodle_url)
3119 * @param array $options Options (same as when embedding)
3120 * @return bool True if file can be embedded
3122 public function can_embed_urls(array $urls, $options = array()) {
3123 // Check all players to see if any of them support it.
3124 foreach ($this->get_players() as $player) {
3125 // Link player (always last on list) doesn't count!
3126 if ($player->get_rank() <= 0) {
3129 // First player that supports it, return true.
3130 if ($player->list_supported_urls($urls, $options)) {
3138 * Obtains a list of markers that can be used in a regular expression when
3139 * searching for URLs that can be embedded by any player type.
3141 * This string is used to improve peformance of regex matching by ensuring
3142 * that the (presumably C) regex code can do a quick keyword check on the
3143 * URL part of a link to see if it matches one of these, rather than having
3144 * to go into PHP code for every single link to see if it can be embedded.
3146 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
3148 public function get_embeddable_markers() {
3149 if (empty($this->embeddablemarkers)) {
3151 foreach ($this->get_players() as $player) {
3152 foreach ($player->get_embeddable_markers() as $marker) {
3153 if ($markers !== '') {
3156 $markers .= preg_quote($marker);
3159 $this->embeddablemarkers = $markers;
3161 return $this->embeddablemarkers;