MDL-48841 admin: Fixed changed string
[moodle.git] / lib / outputrenderers.php
blobe4667309e2de3b17a0d67ffb6cc8513fbe2daf66
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Classes for rendering HTML output for Moodle.
20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
21 * for an overview.
23 * Included in this file are the primary renderer classes:
24 * - renderer_base: The renderer outline class that all renderers
25 * should inherit from.
26 * - core_renderer: The standard HTML renderer.
27 * - core_renderer_cli: An adaption of the standard renderer for CLI scripts.
28 * - core_renderer_ajax: An adaption of the standard renderer for AJAX scripts.
29 * - plugin_renderer_base: A renderer class that should be extended by all
30 * plugin renderers.
32 * @package core
33 * @category output
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') || die();
40 /**
41 * Simple base class for Moodle renderers.
43 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
45 * Also has methods to facilitate generating HTML output.
47 * @copyright 2009 Tim Hunt
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 * @since Moodle 2.0
50 * @package core
51 * @category output
53 class renderer_base {
54 /**
55 * @var xhtml_container_stack The xhtml_container_stack to use.
57 protected $opencontainers;
59 /**
60 * @var moodle_page The Moodle page the renderer has been created to assist with.
62 protected $page;
64 /**
65 * @var string The requested rendering target.
67 protected $target;
69 /**
70 * Constructor
72 * The constructor takes two arguments. The first is the page that the renderer
73 * has been created to assist with, and the second is the target.
74 * The target is an additional identifier that can be used to load different
75 * renderers for different options.
77 * @param moodle_page $page the page we are doing output for.
78 * @param string $target one of rendering target constants
80 public function __construct(moodle_page $page, $target) {
81 $this->opencontainers = $page->opencontainers;
82 $this->page = $page;
83 $this->target = $target;
86 /**
87 * Returns rendered widget.
89 * The provided widget needs to be an object that extends the renderable
90 * interface.
91 * If will then be rendered by a method based upon the classname for the widget.
92 * For instance a widget of class `crazywidget` will be rendered by a protected
93 * render_crazywidget method of this renderer.
95 * @param renderable $widget instance with renderable interface
96 * @return string
98 public function render(renderable $widget) {
99 $rendermethod = 'render_'.get_class($widget);
100 if (method_exists($this, $rendermethod)) {
101 return $this->$rendermethod($widget);
103 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
107 * Adds a JS action for the element with the provided id.
109 * This method adds a JS event for the provided component action to the page
110 * and then returns the id that the event has been attached to.
111 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
113 * @param component_action $action
114 * @param string $id
115 * @return string id of element, either original submitted or random new if not supplied
117 public function add_action_handler(component_action $action, $id = null) {
118 if (!$id) {
119 $id = html_writer::random_id($action->event);
121 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
122 return $id;
126 * Returns true is output has already started, and false if not.
128 * @return boolean true if the header has been printed.
130 public function has_started() {
131 return $this->page->state >= moodle_page::STATE_IN_BODY;
135 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
137 * @param mixed $classes Space-separated string or array of classes
138 * @return string HTML class attribute value
140 public static function prepare_classes($classes) {
141 if (is_array($classes)) {
142 return implode(' ', array_unique($classes));
144 return $classes;
148 * Return the moodle_url for an image.
150 * The exact image location and extension is determined
151 * automatically by searching for gif|png|jpg|jpeg, please
152 * note there can not be diferent images with the different
153 * extension. The imagename is for historical reasons
154 * a relative path name, it may be changed later for core
155 * images. It is recommended to not use subdirectories
156 * in plugin and theme pix directories.
158 * There are three types of images:
159 * 1/ theme images - stored in theme/mytheme/pix/,
160 * use component 'theme'
161 * 2/ core images - stored in /pix/,
162 * overridden via theme/mytheme/pix_core/
163 * 3/ plugin images - stored in mod/mymodule/pix,
164 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
165 * example: pix_url('comment', 'mod_glossary')
167 * @param string $imagename the pathname of the image
168 * @param string $component full plugin name (aka component) or 'theme'
169 * @return moodle_url
171 public function pix_url($imagename, $component = 'moodle') {
172 return $this->page->theme->pix_url($imagename, $component);
178 * Basis for all plugin renderers.
180 * @copyright Petr Skoda (skodak)
181 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
182 * @since Moodle 2.0
183 * @package core
184 * @category output
186 class plugin_renderer_base extends renderer_base {
189 * @var renderer_base|core_renderer A reference to the current renderer.
190 * The renderer provided here will be determined by the page but will in 90%
191 * of cases by the {@link core_renderer}
193 protected $output;
196 * Constructor method, calls the parent constructor
198 * @param moodle_page $page
199 * @param string $target one of rendering target constants
201 public function __construct(moodle_page $page, $target) {
202 if (empty($target) && $page->pagelayout === 'maintenance') {
203 // If the page is using the maintenance layout then we're going to force the target to maintenance.
204 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
205 // unavailable for this page layout.
206 $target = RENDERER_TARGET_MAINTENANCE;
208 $this->output = $page->get_renderer('core', null, $target);
209 parent::__construct($page, $target);
213 * Renders the provided widget and returns the HTML to display it.
215 * @param renderable $widget instance with renderable interface
216 * @return string
218 public function render(renderable $widget) {
219 $rendermethod = 'render_'.get_class($widget);
220 if (method_exists($this, $rendermethod)) {
221 return $this->$rendermethod($widget);
223 // pass to core renderer if method not found here
224 return $this->output->render($widget);
228 * Magic method used to pass calls otherwise meant for the standard renderer
229 * to it to ensure we don't go causing unnecessary grief.
231 * @param string $method
232 * @param array $arguments
233 * @return mixed
235 public function __call($method, $arguments) {
236 if (method_exists('renderer_base', $method)) {
237 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
239 if (method_exists($this->output, $method)) {
240 return call_user_func_array(array($this->output, $method), $arguments);
241 } else {
242 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
249 * The standard implementation of the core_renderer interface.
251 * @copyright 2009 Tim Hunt
252 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
253 * @since Moodle 2.0
254 * @package core
255 * @category output
257 class core_renderer extends renderer_base {
259 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
260 * in layout files instead.
261 * @deprecated
262 * @var string used in {@link core_renderer::header()}.
264 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
267 * @var string Used to pass information from {@link core_renderer::doctype()} to
268 * {@link core_renderer::standard_head_html()}.
270 protected $contenttype;
273 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
274 * with {@link core_renderer::header()}.
276 protected $metarefreshtag = '';
279 * @var string Unique token for the closing HTML
281 protected $unique_end_html_token;
284 * @var string Unique token for performance information
286 protected $unique_performance_info_token;
289 * @var string Unique token for the main content.
291 protected $unique_main_content_token;
294 * Constructor
296 * @param moodle_page $page the page we are doing output for.
297 * @param string $target one of rendering target constants
299 public function __construct(moodle_page $page, $target) {
300 $this->opencontainers = $page->opencontainers;
301 $this->page = $page;
302 $this->target = $target;
304 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
305 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
306 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
310 * Get the DOCTYPE declaration that should be used with this page. Designed to
311 * be called in theme layout.php files.
313 * @return string the DOCTYPE declaration that should be used.
315 public function doctype() {
316 if ($this->page->theme->doctype === 'html5') {
317 $this->contenttype = 'text/html; charset=utf-8';
318 return "<!DOCTYPE html>\n";
320 } else if ($this->page->theme->doctype === 'xhtml5') {
321 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
322 return "<!DOCTYPE html>\n";
324 } else {
325 // legacy xhtml 1.0
326 $this->contenttype = 'text/html; charset=utf-8';
327 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
332 * The attributes that should be added to the <html> tag. Designed to
333 * be called in theme layout.php files.
335 * @return string HTML fragment.
337 public function htmlattributes() {
338 $return = get_html_lang(true);
339 if ($this->page->theme->doctype !== 'html5') {
340 $return .= ' xmlns="http://www.w3.org/1999/xhtml"';
342 return $return;
346 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
347 * that should be included in the <head> tag. Designed to be called in theme
348 * layout.php files.
350 * @return string HTML fragment.
352 public function standard_head_html() {
353 global $CFG, $SESSION;
355 // Before we output any content, we need to ensure that certain
356 // page components are set up.
358 // Blocks must be set up early as they may require javascript which
359 // has to be included in the page header before output is created.
360 foreach ($this->page->blocks->get_regions() as $region) {
361 $this->page->blocks->ensure_content_created($region, $this);
364 $output = '';
365 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
366 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
367 // This is only set by the {@link redirect()} method
368 $output .= $this->metarefreshtag;
370 // Check if a periodic refresh delay has been set and make sure we arn't
371 // already meta refreshing
372 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
373 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
376 // flow player embedding support
377 $this->page->requires->js_function_call('M.util.load_flowplayer');
379 // Set up help link popups for all links with the helptooltip class
380 $this->page->requires->js_init_call('M.util.help_popups.setup');
382 // Setup help icon overlays.
383 $this->page->requires->yui_module('moodle-core-popuphelp', 'M.core.init_popuphelp');
384 $this->page->requires->strings_for_js(array(
385 'morehelp',
386 'loadinghelp',
387 ), 'moodle');
389 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
391 $focus = $this->page->focuscontrol;
392 if (!empty($focus)) {
393 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
394 // This is a horrifically bad way to handle focus but it is passed in
395 // through messy formslib::moodleform
396 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
397 } else if (strpos($focus, '.')!==false) {
398 // Old style of focus, bad way to do it
399 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);
400 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
401 } else {
402 // Focus element with given id
403 $this->page->requires->js_function_call('focuscontrol', array($focus));
407 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
408 // any other custom CSS can not be overridden via themes and is highly discouraged
409 $urls = $this->page->theme->css_urls($this->page);
410 foreach ($urls as $url) {
411 $this->page->requires->css_theme($url);
414 // Get the theme javascript head and footer
415 if ($jsurl = $this->page->theme->javascript_url(true)) {
416 $this->page->requires->js($jsurl, true);
418 if ($jsurl = $this->page->theme->javascript_url(false)) {
419 $this->page->requires->js($jsurl);
422 // Get any HTML from the page_requirements_manager.
423 $output .= $this->page->requires->get_head_code($this->page, $this);
425 // List alternate versions.
426 foreach ($this->page->alternateversions as $type => $alt) {
427 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
428 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
431 if (!empty($CFG->additionalhtmlhead)) {
432 $output .= "\n".$CFG->additionalhtmlhead;
435 return $output;
439 * The standard tags (typically skip links) that should be output just inside
440 * the start of the <body> tag. Designed to be called in theme layout.php files.
442 * @return string HTML fragment.
444 public function standard_top_of_body_html() {
445 global $CFG;
446 $output = $this->page->requires->get_top_of_body_code();
447 if (!empty($CFG->additionalhtmltopofbody)) {
448 $output .= "\n".$CFG->additionalhtmltopofbody;
450 $output .= $this->maintenance_warning();
451 return $output;
455 * Scheduled maintenance warning message.
457 * Note: This is a nasty hack to display maintenance notice, this should be moved
458 * to some general notification area once we have it.
460 * @return string
462 public function maintenance_warning() {
463 global $CFG;
465 $output = '';
466 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
467 $timeleft = $CFG->maintenance_later - time();
468 // If timeleft less than 30 sec, set the class on block to error to highlight.
469 $errorclass = ($timeleft < 30) ? 'error' : 'warning';
470 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning');
471 $a = new stdClass();
472 $a->min = (int)($timeleft/60);
473 $a->sec = (int)($timeleft % 60);
474 $output .= get_string('maintenancemodeisscheduled', 'admin', $a) ;
475 $output .= $this->box_end();
476 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
477 array(array('timeleftinsec' => $timeleft)));
478 $this->page->requires->strings_for_js(
479 array('maintenancemodeisscheduled', 'sitemaintenance'),
480 'admin');
482 return $output;
486 * The standard tags (typically performance information and validation links,
487 * if we are in developer debug mode) that should be output in the footer area
488 * of the page. Designed to be called in theme layout.php files.
490 * @return string HTML fragment.
492 public function standard_footer_html() {
493 global $CFG, $SCRIPT;
495 if (during_initial_install()) {
496 // Debugging info can not work before install is finished,
497 // in any case we do not want any links during installation!
498 return '';
501 // This function is normally called from a layout.php file in {@link core_renderer::header()}
502 // but some of the content won't be known until later, so we return a placeholder
503 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
504 $output = $this->unique_performance_info_token;
505 if ($this->page->devicetypeinuse == 'legacy') {
506 // The legacy theme is in use print the notification
507 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
510 // Get links to switch device types (only shown for users not on a default device)
511 $output .= $this->theme_switch_links();
513 if (!empty($CFG->debugpageinfo)) {
514 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
516 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
517 // Add link to profiling report if necessary
518 if (function_exists('profiling_is_running') && profiling_is_running()) {
519 $txt = get_string('profiledscript', 'admin');
520 $title = get_string('profiledscriptview', 'admin');
521 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
522 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
523 $output .= '<div class="profilingfooter">' . $link . '</div>';
525 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
526 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
527 $output .= '<div class="purgecaches">' .
528 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
530 if (!empty($CFG->debugvalidators)) {
531 // 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
532 $output .= '<div class="validators"><ul>
533 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
534 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
535 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&amp;warnp2n3e=1&amp;url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
536 </ul></div>';
538 return $output;
542 * Returns standard main content placeholder.
543 * Designed to be called in theme layout.php files.
545 * @return string HTML fragment.
547 public function main_content() {
548 // This is here because it is the only place we can inject the "main" role over the entire main content area
549 // without requiring all theme's to manually do it, and without creating yet another thing people need to
550 // remember in the theme.
551 // This is an unfortunate hack. DO NO EVER add anything more here.
552 // DO NOT add classes.
553 // DO NOT add an id.
554 return '<div role="main">'.$this->unique_main_content_token.'</div>';
558 * The standard tags (typically script tags that are not needed earlier) that
559 * should be output after everything else. Designed to be called in theme layout.php files.
561 * @return string HTML fragment.
563 public function standard_end_of_body_html() {
564 global $CFG;
566 // This function is normally called from a layout.php file in {@link core_renderer::header()}
567 // but some of the content won't be known until later, so we return a placeholder
568 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
569 $output = '';
570 if (!empty($CFG->additionalhtmlfooter)) {
571 $output .= "\n".$CFG->additionalhtmlfooter;
573 $output .= $this->unique_end_html_token;
574 return $output;
578 * Return the standard string that says whether you are logged in (and switched
579 * roles/logged in as another user).
580 * @param bool $withlinks if false, then don't include any links in the HTML produced.
581 * If not set, the default is the nologinlinks option from the theme config.php file,
582 * and if that is not set, then links are included.
583 * @return string HTML fragment.
585 public function login_info($withlinks = null) {
586 global $USER, $CFG, $DB, $SESSION;
588 if (during_initial_install()) {
589 return '';
592 if (is_null($withlinks)) {
593 $withlinks = empty($this->page->layout_options['nologinlinks']);
596 $loginpage = ((string)$this->page->url === get_login_url());
597 $course = $this->page->course;
598 if (\core\session\manager::is_loggedinas()) {
599 $realuser = \core\session\manager::get_realuser();
600 $fullname = fullname($realuser, true);
601 if ($withlinks) {
602 $loginastitle = get_string('loginas');
603 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
604 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
605 } else {
606 $realuserinfo = " [$fullname] ";
608 } else {
609 $realuserinfo = '';
612 $loginurl = get_login_url();
614 if (empty($course->id)) {
615 // $course->id is not defined during installation
616 return '';
617 } else if (isloggedin()) {
618 $context = context_course::instance($course->id);
620 $fullname = fullname($USER, true);
621 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
622 if ($withlinks) {
623 $linktitle = get_string('viewprofile');
624 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
625 } else {
626 $username = $fullname;
628 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
629 if ($withlinks) {
630 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
631 } else {
632 $username .= " from {$idprovider->name}";
635 if (isguestuser()) {
636 $loggedinas = $realuserinfo.get_string('loggedinasguest');
637 if (!$loginpage && $withlinks) {
638 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
640 } else if (is_role_switched($course->id)) { // Has switched roles
641 $rolename = '';
642 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
643 $rolename = ': '.role_get_name($role, $context);
645 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
646 if ($withlinks) {
647 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
648 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
650 } else {
651 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
652 if ($withlinks) {
653 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
656 } else {
657 $loggedinas = get_string('loggedinnot', 'moodle');
658 if (!$loginpage && $withlinks) {
659 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
663 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
665 if (isset($SESSION->justloggedin)) {
666 unset($SESSION->justloggedin);
667 if (!empty($CFG->displayloginfailures)) {
668 if (!isguestuser()) {
669 // Include this file only when required.
670 require_once($CFG->dirroot . '/user/lib.php');
671 if ($count = user_count_login_failures($USER)) {
672 $loggedinas .= '<div class="loginfailures">';
673 $a = new stdClass();
674 $a->attempts = $count;
675 $loggedinas .= get_string('failedloginattempts', '', $a);
676 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
677 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
678 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
680 $loggedinas .= '</div>';
686 return $loggedinas;
690 * Return the 'back' link that normally appears in the footer.
692 * @return string HTML fragment.
694 public function home_link() {
695 global $CFG, $SITE;
697 if ($this->page->pagetype == 'site-index') {
698 // Special case for site home page - please do not remove
699 return '<div class="sitelink">' .
700 '<a title="Moodle" href="http://moodle.org/">' .
701 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
703 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
704 // Special case for during install/upgrade.
705 return '<div class="sitelink">'.
706 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
707 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
709 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
710 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
711 get_string('home') . '</a></div>';
713 } else {
714 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
715 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
720 * Redirects the user by any means possible given the current state
722 * This function should not be called directly, it should always be called using
723 * the redirect function in lib/weblib.php
725 * The redirect function should really only be called before page output has started
726 * however it will allow itself to be called during the state STATE_IN_BODY
728 * @param string $encodedurl The URL to send to encoded if required
729 * @param string $message The message to display to the user if any
730 * @param int $delay The delay before redirecting a user, if $message has been
731 * set this is a requirement and defaults to 3, set to 0 no delay
732 * @param boolean $debugdisableredirect this redirect has been disabled for
733 * debugging purposes. Display a message that explains, and don't
734 * trigger the redirect.
735 * @return string The HTML to display to the user before dying, may contain
736 * meta refresh, javascript refresh, and may have set header redirects
738 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
739 global $CFG;
740 $url = str_replace('&amp;', '&', $encodedurl);
742 switch ($this->page->state) {
743 case moodle_page::STATE_BEFORE_HEADER :
744 // No output yet it is safe to delivery the full arsenal of redirect methods
745 if (!$debugdisableredirect) {
746 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
747 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
748 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
750 $output = $this->header();
751 break;
752 case moodle_page::STATE_PRINTING_HEADER :
753 // We should hopefully never get here
754 throw new coding_exception('You cannot redirect while printing the page header');
755 break;
756 case moodle_page::STATE_IN_BODY :
757 // We really shouldn't be here but we can deal with this
758 debugging("You should really redirect before you start page output");
759 if (!$debugdisableredirect) {
760 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
762 $output = $this->opencontainers->pop_all_but_last();
763 break;
764 case moodle_page::STATE_DONE :
765 // Too late to be calling redirect now
766 throw new coding_exception('You cannot redirect after the entire page has been generated');
767 break;
769 $output .= $this->notification($message, 'redirectmessage');
770 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
771 if ($debugdisableredirect) {
772 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
774 $output .= $this->footer();
775 return $output;
779 * Start output by sending the HTTP headers, and printing the HTML <head>
780 * and the start of the <body>.
782 * To control what is printed, you should set properties on $PAGE. If you
783 * are familiar with the old {@link print_header()} function from Moodle 1.9
784 * you will find that there are properties on $PAGE that correspond to most
785 * of the old parameters to could be passed to print_header.
787 * Not that, in due course, the remaining $navigation, $menu parameters here
788 * will be replaced by more properties of $PAGE, but that is still to do.
790 * @return string HTML that you must output this, preferably immediately.
792 public function header() {
793 global $USER, $CFG;
795 if (\core\session\manager::is_loggedinas()) {
796 $this->page->add_body_class('userloggedinas');
799 // Give themes a chance to init/alter the page object.
800 $this->page->theme->init_page($this->page);
802 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
804 // Find the appropriate page layout file, based on $this->page->pagelayout.
805 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
806 // Render the layout using the layout file.
807 $rendered = $this->render_page_layout($layoutfile);
809 // Slice the rendered output into header and footer.
810 $cutpos = strpos($rendered, $this->unique_main_content_token);
811 if ($cutpos === false) {
812 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
813 $token = self::MAIN_CONTENT_TOKEN;
814 } else {
815 $token = $this->unique_main_content_token;
818 if ($cutpos === false) {
819 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.');
821 $header = substr($rendered, 0, $cutpos);
822 $footer = substr($rendered, $cutpos + strlen($token));
824 if (empty($this->contenttype)) {
825 debugging('The page layout file did not call $OUTPUT->doctype()');
826 $header = $this->doctype() . $header;
829 // If this theme version is below 2.4 release and this is a course view page
830 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
831 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
832 // check if course content header/footer have not been output during render of theme layout
833 $coursecontentheader = $this->course_content_header(true);
834 $coursecontentfooter = $this->course_content_footer(true);
835 if (!empty($coursecontentheader)) {
836 // display debug message and add header and footer right above and below main content
837 // Please note that course header and footer (to be displayed above and below the whole page)
838 // are not displayed in this case at all.
839 // Besides the content header and footer are not displayed on any other course page
840 debugging('The current theme is not optimised for 2.4, the course-specific header and footer defined in course format will not be output', DEBUG_DEVELOPER);
841 $header .= $coursecontentheader;
842 $footer = $coursecontentfooter. $footer;
846 send_headers($this->contenttype, $this->page->cacheable);
848 $this->opencontainers->push('header/footer', $footer);
849 $this->page->set_state(moodle_page::STATE_IN_BODY);
851 return $header . $this->skip_link_target('maincontent');
855 * Renders and outputs the page layout file.
857 * This is done by preparing the normal globals available to a script, and
858 * then including the layout file provided by the current theme for the
859 * requested layout.
861 * @param string $layoutfile The name of the layout file
862 * @return string HTML code
864 protected function render_page_layout($layoutfile) {
865 global $CFG, $SITE, $USER;
866 // The next lines are a bit tricky. The point is, here we are in a method
867 // of a renderer class, and this object may, or may not, be the same as
868 // the global $OUTPUT object. When rendering the page layout file, we want to use
869 // this object. However, people writing Moodle code expect the current
870 // renderer to be called $OUTPUT, not $this, so define a variable called
871 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
872 $OUTPUT = $this;
873 $PAGE = $this->page;
874 $COURSE = $this->page->course;
876 ob_start();
877 include($layoutfile);
878 $rendered = ob_get_contents();
879 ob_end_clean();
880 return $rendered;
884 * Outputs the page's footer
886 * @return string HTML fragment
888 public function footer() {
889 global $CFG, $DB;
891 $output = $this->container_end_all(true);
893 $footer = $this->opencontainers->pop('header/footer');
895 if (debugging() and $DB and $DB->is_transaction_started()) {
896 // TODO: MDL-20625 print warning - transaction will be rolled back
899 // Provide some performance info if required
900 $performanceinfo = '';
901 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
902 $perf = get_performance_info();
903 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
904 $performanceinfo = $perf['html'];
908 // We always want performance data when running a performance test, even if the user is redirected to another page.
909 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
910 $footer = $this->unique_performance_info_token . $footer;
912 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
914 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
916 $this->page->set_state(moodle_page::STATE_DONE);
918 return $output . $footer;
922 * Close all but the last open container. This is useful in places like error
923 * handling, where you want to close all the open containers (apart from <body>)
924 * before outputting the error message.
926 * @param bool $shouldbenone assert that the stack should be empty now - causes a
927 * developer debug warning if it isn't.
928 * @return string the HTML required to close any open containers inside <body>.
930 public function container_end_all($shouldbenone = false) {
931 return $this->opencontainers->pop_all_but_last($shouldbenone);
935 * Returns course-specific information to be output immediately above content on any course page
936 * (for the current course)
938 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
939 * @return string
941 public function course_content_header($onlyifnotcalledbefore = false) {
942 global $CFG;
943 if ($this->page->course->id == SITEID) {
944 // return immediately and do not include /course/lib.php if not necessary
945 return '';
947 static $functioncalled = false;
948 if ($functioncalled && $onlyifnotcalledbefore) {
949 // we have already output the content header
950 return '';
952 require_once($CFG->dirroot.'/course/lib.php');
953 $functioncalled = true;
954 $courseformat = course_get_format($this->page->course);
955 if (($obj = $courseformat->course_content_header()) !== null) {
956 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
958 return '';
962 * Returns course-specific information to be output immediately below content on any course page
963 * (for the current course)
965 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
966 * @return string
968 public function course_content_footer($onlyifnotcalledbefore = false) {
969 global $CFG;
970 if ($this->page->course->id == SITEID) {
971 // return immediately and do not include /course/lib.php if not necessary
972 return '';
974 static $functioncalled = false;
975 if ($functioncalled && $onlyifnotcalledbefore) {
976 // we have already output the content footer
977 return '';
979 $functioncalled = true;
980 require_once($CFG->dirroot.'/course/lib.php');
981 $courseformat = course_get_format($this->page->course);
982 if (($obj = $courseformat->course_content_footer()) !== null) {
983 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
985 return '';
989 * Returns course-specific information to be output on any course page in the header area
990 * (for the current course)
992 * @return string
994 public function course_header() {
995 global $CFG;
996 if ($this->page->course->id == SITEID) {
997 // return immediately and do not include /course/lib.php if not necessary
998 return '';
1000 require_once($CFG->dirroot.'/course/lib.php');
1001 $courseformat = course_get_format($this->page->course);
1002 if (($obj = $courseformat->course_header()) !== null) {
1003 return $courseformat->get_renderer($this->page)->render($obj);
1005 return '';
1009 * Returns course-specific information to be output on any course page in the footer area
1010 * (for the current course)
1012 * @return string
1014 public function course_footer() {
1015 global $CFG;
1016 if ($this->page->course->id == SITEID) {
1017 // return immediately and do not include /course/lib.php if not necessary
1018 return '';
1020 require_once($CFG->dirroot.'/course/lib.php');
1021 $courseformat = course_get_format($this->page->course);
1022 if (($obj = $courseformat->course_footer()) !== null) {
1023 return $courseformat->get_renderer($this->page)->render($obj);
1025 return '';
1029 * Returns lang menu or '', this method also checks forcing of languages in courses.
1031 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1033 * @return string The lang menu HTML or empty string
1035 public function lang_menu() {
1036 global $CFG;
1038 if (empty($CFG->langmenu)) {
1039 return '';
1042 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1043 // do not show lang menu if language forced
1044 return '';
1047 $currlang = current_language();
1048 $langs = get_string_manager()->get_list_of_translations();
1050 if (count($langs) < 2) {
1051 return '';
1054 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1055 $s->label = get_accesshide(get_string('language'));
1056 $s->class = 'langmenu';
1057 return $this->render($s);
1061 * Output the row of editing icons for a block, as defined by the controls array.
1063 * @param array $controls an array like {@link block_contents::$controls}.
1064 * @param string $blockid The ID given to the block.
1065 * @return string HTML fragment.
1067 public function block_controls($actions, $blockid = null) {
1068 global $CFG;
1069 if (empty($actions)) {
1070 return '';
1072 $menu = new action_menu($actions);
1073 if ($blockid !== null) {
1074 $menu->set_owner_selector('#'.$blockid);
1076 $menu->set_constraint('.block-region');
1077 $menu->attributes['class'] .= ' block-control-actions commands';
1078 if (isset($CFG->blockeditingmenu) && !$CFG->blockeditingmenu) {
1079 $menu->do_not_enhance();
1081 return $this->render($menu);
1085 * Renders an action menu component.
1087 * ARIA references:
1088 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1089 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1091 * @param action_menu $menu
1092 * @return string HTML
1094 public function render_action_menu(action_menu $menu) {
1095 $menu->initialise_js($this->page);
1097 $output = html_writer::start_tag('div', $menu->attributes);
1098 $output .= html_writer::start_tag('ul', $menu->attributesprimary);
1099 foreach ($menu->get_primary_actions($this) as $action) {
1100 if ($action instanceof renderable) {
1101 $content = $this->render($action);
1102 } else {
1103 $content = $action;
1105 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1107 $output .= html_writer::end_tag('ul');
1108 $output .= html_writer::start_tag('ul', $menu->attributessecondary);
1109 foreach ($menu->get_secondary_actions() as $action) {
1110 if ($action instanceof renderable) {
1111 $content = $this->render($action);
1112 } else {
1113 $content = $action;
1115 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1117 $output .= html_writer::end_tag('ul');
1118 $output .= html_writer::end_tag('div');
1119 return $output;
1123 * Renders an action_menu_link item.
1125 * @param action_menu_link $action
1126 * @return string HTML fragment
1128 protected function render_action_menu_link(action_menu_link $action) {
1129 static $actioncount = 0;
1130 $actioncount++;
1132 $comparetoalt = '';
1133 $text = '';
1134 if (!$action->icon || $action->primary === false) {
1135 $text .= html_writer::start_tag('span', array('class'=>'menu-action-text', 'id' => 'actionmenuaction-'.$actioncount));
1136 if ($action->text instanceof renderable) {
1137 $text .= $this->render($action->text);
1138 } else {
1139 $text .= $action->text;
1140 $comparetoalt = (string)$action->text;
1142 $text .= html_writer::end_tag('span');
1145 $icon = '';
1146 if ($action->icon) {
1147 $icon = $action->icon;
1148 if ($action->primary || !$action->actionmenu->will_be_enhanced()) {
1149 $action->attributes['title'] = $action->text;
1151 if (!$action->primary && $action->actionmenu->will_be_enhanced()) {
1152 if ((string)$icon->attributes['alt'] === $comparetoalt) {
1153 $icon->attributes['alt'] = '';
1155 if (isset($icon->attributes['title']) && (string)$icon->attributes['title'] === $comparetoalt) {
1156 unset($icon->attributes['title']);
1159 $icon = $this->render($icon);
1162 // A disabled link is rendered as formatted text.
1163 if (!empty($action->attributes['disabled'])) {
1164 // Do not use div here due to nesting restriction in xhtml strict.
1165 return html_writer::tag('span', $icon.$text, array('class'=>'currentlink', 'role' => 'menuitem'));
1168 $attributes = $action->attributes;
1169 unset($action->attributes['disabled']);
1170 $attributes['href'] = $action->url;
1171 if ($text !== '') {
1172 $attributes['aria-labelledby'] = 'actionmenuaction-'.$actioncount;
1175 return html_writer::tag('a', $icon.$text, $attributes);
1179 * Renders a primary action_menu_filler item.
1181 * @param action_menu_link_filler $action
1182 * @return string HTML fragment
1184 protected function render_action_menu_filler(action_menu_filler $action) {
1185 return html_writer::span('&nbsp;', 'filler');
1189 * Renders a primary action_menu_link item.
1191 * @param action_menu_link_primary $action
1192 * @return string HTML fragment
1194 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1195 return $this->render_action_menu_link($action);
1199 * Renders a secondary action_menu_link item.
1201 * @param action_menu_link_secondary $action
1202 * @return string HTML fragment
1204 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1205 return $this->render_action_menu_link($action);
1209 * Prints a nice side block with an optional header.
1211 * The content is described
1212 * by a {@link core_renderer::block_contents} object.
1214 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1215 * <div class="header"></div>
1216 * <div class="content">
1217 * ...CONTENT...
1218 * <div class="footer">
1219 * </div>
1220 * </div>
1221 * <div class="annotation">
1222 * </div>
1223 * </div>
1225 * @param block_contents $bc HTML for the content
1226 * @param string $region the region the block is appearing in.
1227 * @return string the HTML to be output.
1229 public function block(block_contents $bc, $region) {
1230 $bc = clone($bc); // Avoid messing up the object passed in.
1231 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1232 $bc->collapsible = block_contents::NOT_HIDEABLE;
1234 if (!empty($bc->blockinstanceid)) {
1235 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1237 $skiptitle = strip_tags($bc->title);
1238 if ($bc->blockinstanceid && !empty($skiptitle)) {
1239 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1240 } else if (!empty($bc->arialabel)) {
1241 $bc->attributes['aria-label'] = $bc->arialabel;
1243 if ($bc->dockable) {
1244 $bc->attributes['data-dockable'] = 1;
1246 if ($bc->collapsible == block_contents::HIDDEN) {
1247 $bc->add_class('hidden');
1249 if (!empty($bc->controls)) {
1250 $bc->add_class('block_with_controls');
1254 if (empty($skiptitle)) {
1255 $output = '';
1256 $skipdest = '';
1257 } else {
1258 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
1259 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
1262 $output .= html_writer::start_tag('div', $bc->attributes);
1264 $output .= $this->block_header($bc);
1265 $output .= $this->block_content($bc);
1267 $output .= html_writer::end_tag('div');
1269 $output .= $this->block_annotation($bc);
1271 $output .= $skipdest;
1273 $this->init_block_hider_js($bc);
1274 return $output;
1278 * Produces a header for a block
1280 * @param block_contents $bc
1281 * @return string
1283 protected function block_header(block_contents $bc) {
1285 $title = '';
1286 if ($bc->title) {
1287 $attributes = array();
1288 if ($bc->blockinstanceid) {
1289 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1291 $title = html_writer::tag('h2', $bc->title, $attributes);
1294 $blockid = null;
1295 if (isset($bc->attributes['id'])) {
1296 $blockid = $bc->attributes['id'];
1298 $controlshtml = $this->block_controls($bc->controls, $blockid);
1300 $output = '';
1301 if ($title || $controlshtml) {
1302 $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'));
1304 return $output;
1308 * Produces the content area for a block
1310 * @param block_contents $bc
1311 * @return string
1313 protected function block_content(block_contents $bc) {
1314 $output = html_writer::start_tag('div', array('class' => 'content'));
1315 if (!$bc->title && !$this->block_controls($bc->controls)) {
1316 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1318 $output .= $bc->content;
1319 $output .= $this->block_footer($bc);
1320 $output .= html_writer::end_tag('div');
1322 return $output;
1326 * Produces the footer for a block
1328 * @param block_contents $bc
1329 * @return string
1331 protected function block_footer(block_contents $bc) {
1332 $output = '';
1333 if ($bc->footer) {
1334 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1336 return $output;
1340 * Produces the annotation for a block
1342 * @param block_contents $bc
1343 * @return string
1345 protected function block_annotation(block_contents $bc) {
1346 $output = '';
1347 if ($bc->annotation) {
1348 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1350 return $output;
1354 * Calls the JS require function to hide a block.
1356 * @param block_contents $bc A block_contents object
1358 protected function init_block_hider_js(block_contents $bc) {
1359 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1360 $config = new stdClass;
1361 $config->id = $bc->attributes['id'];
1362 $config->title = strip_tags($bc->title);
1363 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1364 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1365 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1367 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1368 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1373 * Render the contents of a block_list.
1375 * @param array $icons the icon for each item.
1376 * @param array $items the content of each item.
1377 * @return string HTML
1379 public function list_block_contents($icons, $items) {
1380 $row = 0;
1381 $lis = array();
1382 foreach ($items as $key => $string) {
1383 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1384 if (!empty($icons[$key])) { //test if the content has an assigned icon
1385 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1387 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1388 $item .= html_writer::end_tag('li');
1389 $lis[] = $item;
1390 $row = 1 - $row; // Flip even/odd.
1392 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1396 * Output all the blocks in a particular region.
1398 * @param string $region the name of a region on this page.
1399 * @return string the HTML to be output.
1401 public function blocks_for_region($region) {
1402 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1403 $blocks = $this->page->blocks->get_blocks_for_region($region);
1404 $lastblock = null;
1405 $zones = array();
1406 foreach ($blocks as $block) {
1407 $zones[] = $block->title;
1409 $output = '';
1411 foreach ($blockcontents as $bc) {
1412 if ($bc instanceof block_contents) {
1413 $output .= $this->block($bc, $region);
1414 $lastblock = $bc->title;
1415 } else if ($bc instanceof block_move_target) {
1416 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1417 } else {
1418 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1421 return $output;
1425 * Output a place where the block that is currently being moved can be dropped.
1427 * @param block_move_target $target with the necessary details.
1428 * @param array $zones array of areas where the block can be moved to
1429 * @param string $previous the block located before the area currently being rendered.
1430 * @param string $region the name of the region
1431 * @return string the HTML to be output.
1433 public function block_move_target($target, $zones, $previous, $region) {
1434 if ($previous == null) {
1435 if (empty($zones)) {
1436 // There are no zones, probably because there are no blocks.
1437 $regions = $this->page->theme->get_all_block_regions();
1438 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1439 } else {
1440 $position = get_string('moveblockbefore', 'block', $zones[0]);
1442 } else {
1443 $position = get_string('moveblockafter', 'block', $previous);
1445 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1449 * Renders a special html link with attached action
1451 * Theme developers: DO NOT OVERRIDE! Please override function
1452 * {@link core_renderer::render_action_link()} instead.
1454 * @param string|moodle_url $url
1455 * @param string $text HTML fragment
1456 * @param component_action $action
1457 * @param array $attributes associative array of html link attributes + disabled
1458 * @param pix_icon optional pix icon to render with the link
1459 * @return string HTML fragment
1461 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1462 if (!($url instanceof moodle_url)) {
1463 $url = new moodle_url($url);
1465 $link = new action_link($url, $text, $action, $attributes, $icon);
1467 return $this->render($link);
1471 * Renders an action_link object.
1473 * The provided link is renderer and the HTML returned. At the same time the
1474 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1476 * @param action_link $link
1477 * @return string HTML fragment
1479 protected function render_action_link(action_link $link) {
1480 global $CFG;
1482 $text = '';
1483 if ($link->icon) {
1484 $text .= $this->render($link->icon);
1487 if ($link->text instanceof renderable) {
1488 $text .= $this->render($link->text);
1489 } else {
1490 $text .= $link->text;
1493 // A disabled link is rendered as formatted text
1494 if (!empty($link->attributes['disabled'])) {
1495 // do not use div here due to nesting restriction in xhtml strict
1496 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1499 $attributes = $link->attributes;
1500 unset($link->attributes['disabled']);
1501 $attributes['href'] = $link->url;
1503 if ($link->actions) {
1504 if (empty($attributes['id'])) {
1505 $id = html_writer::random_id('action_link');
1506 $attributes['id'] = $id;
1507 } else {
1508 $id = $attributes['id'];
1510 foreach ($link->actions as $action) {
1511 $this->add_action_handler($action, $id);
1515 return html_writer::tag('a', $text, $attributes);
1520 * Renders an action_icon.
1522 * This function uses the {@link core_renderer::action_link()} method for the
1523 * most part. What it does different is prepare the icon as HTML and use it
1524 * as the link text.
1526 * Theme developers: If you want to change how action links and/or icons are rendered,
1527 * consider overriding function {@link core_renderer::render_action_link()} and
1528 * {@link core_renderer::render_pix_icon()}.
1530 * @param string|moodle_url $url A string URL or moodel_url
1531 * @param pix_icon $pixicon
1532 * @param component_action $action
1533 * @param array $attributes associative array of html link attributes + disabled
1534 * @param bool $linktext show title next to image in link
1535 * @return string HTML fragment
1537 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1538 if (!($url instanceof moodle_url)) {
1539 $url = new moodle_url($url);
1541 $attributes = (array)$attributes;
1543 if (empty($attributes['class'])) {
1544 // let ppl override the class via $options
1545 $attributes['class'] = 'action-icon';
1548 $icon = $this->render($pixicon);
1550 if ($linktext) {
1551 $text = $pixicon->attributes['alt'];
1552 } else {
1553 $text = '';
1556 return $this->action_link($url, $text.$icon, $action, $attributes);
1560 * Print a message along with button choices for Continue/Cancel
1562 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1564 * @param string $message The question to ask the user
1565 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1566 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1567 * @return string HTML fragment
1569 public function confirm($message, $continue, $cancel) {
1570 if ($continue instanceof single_button) {
1571 // ok
1572 } else if (is_string($continue)) {
1573 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1574 } else if ($continue instanceof moodle_url) {
1575 $continue = new single_button($continue, get_string('continue'), 'post');
1576 } else {
1577 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1580 if ($cancel instanceof single_button) {
1581 // ok
1582 } else if (is_string($cancel)) {
1583 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1584 } else if ($cancel instanceof moodle_url) {
1585 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1586 } else {
1587 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1590 $output = $this->box_start('generalbox', 'notice');
1591 $output .= html_writer::tag('p', $message);
1592 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1593 $output .= $this->box_end();
1594 return $output;
1598 * Returns a form with a single button.
1600 * Theme developers: DO NOT OVERRIDE! Please override function
1601 * {@link core_renderer::render_single_button()} instead.
1603 * @param string|moodle_url $url
1604 * @param string $label button text
1605 * @param string $method get or post submit method
1606 * @param array $options associative array {disabled, title, etc.}
1607 * @return string HTML fragment
1609 public function single_button($url, $label, $method='post', array $options=null) {
1610 if (!($url instanceof moodle_url)) {
1611 $url = new moodle_url($url);
1613 $button = new single_button($url, $label, $method);
1615 foreach ((array)$options as $key=>$value) {
1616 if (array_key_exists($key, $button)) {
1617 $button->$key = $value;
1621 return $this->render($button);
1625 * Renders a single button widget.
1627 * This will return HTML to display a form containing a single button.
1629 * @param single_button $button
1630 * @return string HTML fragment
1632 protected function render_single_button(single_button $button) {
1633 $attributes = array('type' => 'submit',
1634 'value' => $button->label,
1635 'disabled' => $button->disabled ? 'disabled' : null,
1636 'title' => $button->tooltip);
1638 if ($button->actions) {
1639 $id = html_writer::random_id('single_button');
1640 $attributes['id'] = $id;
1641 foreach ($button->actions as $action) {
1642 $this->add_action_handler($action, $id);
1646 // first the input element
1647 $output = html_writer::empty_tag('input', $attributes);
1649 // then hidden fields
1650 $params = $button->url->params();
1651 if ($button->method === 'post') {
1652 $params['sesskey'] = sesskey();
1654 foreach ($params as $var => $val) {
1655 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1658 // then div wrapper for xhtml strictness
1659 $output = html_writer::tag('div', $output);
1661 // now the form itself around it
1662 if ($button->method === 'get') {
1663 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1664 } else {
1665 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1667 if ($url === '') {
1668 $url = '#'; // there has to be always some action
1670 $attributes = array('method' => $button->method,
1671 'action' => $url,
1672 'id' => $button->formid);
1673 $output = html_writer::tag('form', $output, $attributes);
1675 // and finally one more wrapper with class
1676 return html_writer::tag('div', $output, array('class' => $button->class));
1680 * Returns a form with a single select widget.
1682 * Theme developers: DO NOT OVERRIDE! Please override function
1683 * {@link core_renderer::render_single_select()} instead.
1685 * @param moodle_url $url form action target, includes hidden fields
1686 * @param string $name name of selection field - the changing parameter in url
1687 * @param array $options list of options
1688 * @param string $selected selected element
1689 * @param array $nothing
1690 * @param string $formid
1691 * @return string HTML fragment
1693 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1694 if (!($url instanceof moodle_url)) {
1695 $url = new moodle_url($url);
1697 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1699 return $this->render($select);
1703 * Internal implementation of single_select rendering
1705 * @param single_select $select
1706 * @return string HTML fragment
1708 protected function render_single_select(single_select $select) {
1709 $select = clone($select);
1710 if (empty($select->formid)) {
1711 $select->formid = html_writer::random_id('single_select_f');
1714 $output = '';
1715 $params = $select->url->params();
1716 if ($select->method === 'post') {
1717 $params['sesskey'] = sesskey();
1719 foreach ($params as $name=>$value) {
1720 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1723 if (empty($select->attributes['id'])) {
1724 $select->attributes['id'] = html_writer::random_id('single_select');
1727 if ($select->disabled) {
1728 $select->attributes['disabled'] = 'disabled';
1731 if ($select->tooltip) {
1732 $select->attributes['title'] = $select->tooltip;
1735 $select->attributes['class'] = 'autosubmit';
1736 if ($select->class) {
1737 $select->attributes['class'] .= ' ' . $select->class;
1740 if ($select->label) {
1741 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1744 if ($select->helpicon instanceof help_icon) {
1745 $output .= $this->render($select->helpicon);
1747 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1749 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1750 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1752 $nothing = empty($select->nothing) ? false : key($select->nothing);
1753 $this->page->requires->yui_module('moodle-core-formautosubmit',
1754 'M.core.init_formautosubmit',
1755 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1758 // then div wrapper for xhtml strictness
1759 $output = html_writer::tag('div', $output);
1761 // now the form itself around it
1762 if ($select->method === 'get') {
1763 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1764 } else {
1765 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1767 $formattributes = array('method' => $select->method,
1768 'action' => $url,
1769 'id' => $select->formid);
1770 $output = html_writer::tag('form', $output, $formattributes);
1772 // and finally one more wrapper with class
1773 return html_writer::tag('div', $output, array('class' => $select->class));
1777 * Returns a form with a url select widget.
1779 * Theme developers: DO NOT OVERRIDE! Please override function
1780 * {@link core_renderer::render_url_select()} instead.
1782 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1783 * @param string $selected selected element
1784 * @param array $nothing
1785 * @param string $formid
1786 * @return string HTML fragment
1788 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1789 $select = new url_select($urls, $selected, $nothing, $formid);
1790 return $this->render($select);
1794 * Internal implementation of url_select rendering
1796 * @param url_select $select
1797 * @return string HTML fragment
1799 protected function render_url_select(url_select $select) {
1800 global $CFG;
1802 $select = clone($select);
1803 if (empty($select->formid)) {
1804 $select->formid = html_writer::random_id('url_select_f');
1807 if (empty($select->attributes['id'])) {
1808 $select->attributes['id'] = html_writer::random_id('url_select');
1811 if ($select->disabled) {
1812 $select->attributes['disabled'] = 'disabled';
1815 if ($select->tooltip) {
1816 $select->attributes['title'] = $select->tooltip;
1819 $output = '';
1821 if ($select->label) {
1822 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1825 $classes = array();
1826 if (!$select->showbutton) {
1827 $classes[] = 'autosubmit';
1829 if ($select->class) {
1830 $classes[] = $select->class;
1832 if (count($classes)) {
1833 $select->attributes['class'] = implode(' ', $classes);
1836 if ($select->helpicon instanceof help_icon) {
1837 $output .= $this->render($select->helpicon);
1840 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1841 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1842 $urls = array();
1843 foreach ($select->urls as $k=>$v) {
1844 if (is_array($v)) {
1845 // optgroup structure
1846 foreach ($v as $optgrouptitle => $optgroupoptions) {
1847 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1848 if (empty($optionurl)) {
1849 $safeoptionurl = '';
1850 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1851 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1852 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1853 } else if (strpos($optionurl, '/') !== 0) {
1854 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1855 continue;
1856 } else {
1857 $safeoptionurl = $optionurl;
1859 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1862 } else {
1863 // plain list structure
1864 if (empty($k)) {
1865 // nothing selected option
1866 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1867 $k = str_replace($CFG->wwwroot, '', $k);
1868 } else if (strpos($k, '/') !== 0) {
1869 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1870 continue;
1872 $urls[$k] = $v;
1875 $selected = $select->selected;
1876 if (!empty($selected)) {
1877 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1878 $selected = str_replace($CFG->wwwroot, '', $selected);
1879 } else if (strpos($selected, '/') !== 0) {
1880 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1884 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1885 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1887 if (!$select->showbutton) {
1888 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1889 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1890 $nothing = empty($select->nothing) ? false : key($select->nothing);
1891 $this->page->requires->yui_module('moodle-core-formautosubmit',
1892 'M.core.init_formautosubmit',
1893 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1895 } else {
1896 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1899 // then div wrapper for xhtml strictness
1900 $output = html_writer::tag('div', $output);
1902 // now the form itself around it
1903 $formattributes = array('method' => 'post',
1904 'action' => new moodle_url('/course/jumpto.php'),
1905 'id' => $select->formid);
1906 $output = html_writer::tag('form', $output, $formattributes);
1908 // and finally one more wrapper with class
1909 return html_writer::tag('div', $output, array('class' => $select->class));
1913 * Returns a string containing a link to the user documentation.
1914 * Also contains an icon by default. Shown to teachers and admin only.
1916 * @param string $path The page link after doc root and language, no leading slash.
1917 * @param string $text The text to be displayed for the link
1918 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
1919 * @return string
1921 public function doc_link($path, $text = '', $forcepopup = false) {
1922 global $CFG;
1924 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
1926 $url = new moodle_url(get_docs_url($path));
1928 $attributes = array('href'=>$url);
1929 if (!empty($CFG->doctonewwindow) || $forcepopup) {
1930 $attributes['class'] = 'helplinkpopup';
1933 return html_writer::tag('a', $icon.$text, $attributes);
1937 * Return HTML for a pix_icon.
1939 * Theme developers: DO NOT OVERRIDE! Please override function
1940 * {@link core_renderer::render_pix_icon()} instead.
1942 * @param string $pix short pix name
1943 * @param string $alt mandatory alt attribute
1944 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1945 * @param array $attributes htm lattributes
1946 * @return string HTML fragment
1948 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1949 $icon = new pix_icon($pix, $alt, $component, $attributes);
1950 return $this->render($icon);
1954 * Renders a pix_icon widget and returns the HTML to display it.
1956 * @param pix_icon $icon
1957 * @return string HTML fragment
1959 protected function render_pix_icon(pix_icon $icon) {
1960 $attributes = $icon->attributes;
1961 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1962 return html_writer::empty_tag('img', $attributes);
1966 * Return HTML to display an emoticon icon.
1968 * @param pix_emoticon $emoticon
1969 * @return string HTML fragment
1971 protected function render_pix_emoticon(pix_emoticon $emoticon) {
1972 $attributes = $emoticon->attributes;
1973 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
1974 return html_writer::empty_tag('img', $attributes);
1978 * Produces the html that represents this rating in the UI
1980 * @param rating $rating the page object on which this rating will appear
1981 * @return string
1983 function render_rating(rating $rating) {
1984 global $CFG, $USER;
1986 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
1987 return null;//ratings are turned off
1990 $ratingmanager = new rating_manager();
1991 // Initialise the JavaScript so ratings can be done by AJAX.
1992 $ratingmanager->initialise_rating_javascript($this->page);
1994 $strrate = get_string("rate", "rating");
1995 $ratinghtml = ''; //the string we'll return
1997 // permissions check - can they view the aggregate?
1998 if ($rating->user_can_view_aggregate()) {
2000 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2001 $aggregatestr = $rating->get_aggregate_string();
2003 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2004 if ($rating->count > 0) {
2005 $countstr = "({$rating->count})";
2006 } else {
2007 $countstr = '-';
2009 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2011 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2012 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2014 $nonpopuplink = $rating->get_view_ratings_url();
2015 $popuplink = $rating->get_view_ratings_url(true);
2017 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2018 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2019 } else {
2020 $ratinghtml .= $aggregatehtml;
2024 $formstart = null;
2025 // if the item doesn't belong to the current user, the user has permission to rate
2026 // and we're within the assessable period
2027 if ($rating->user_can_rate()) {
2029 $rateurl = $rating->get_rate_url();
2030 $inputs = $rateurl->params();
2032 //start the rating form
2033 $formattrs = array(
2034 'id' => "postrating{$rating->itemid}",
2035 'class' => 'postratingform',
2036 'method' => 'post',
2037 'action' => $rateurl->out_omit_querystring()
2039 $formstart = html_writer::start_tag('form', $formattrs);
2040 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2042 // add the hidden inputs
2043 foreach ($inputs as $name => $value) {
2044 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2045 $formstart .= html_writer::empty_tag('input', $attributes);
2048 if (empty($ratinghtml)) {
2049 $ratinghtml .= $strrate.': ';
2051 $ratinghtml = $formstart.$ratinghtml;
2053 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2054 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2055 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2056 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2058 //output submit button
2059 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2061 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2062 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2064 if (!$rating->settings->scale->isnumeric) {
2065 // If a global scale, try to find current course ID from the context
2066 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2067 $courseid = $coursecontext->instanceid;
2068 } else {
2069 $courseid = $rating->settings->scale->courseid;
2071 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2073 $ratinghtml .= html_writer::end_tag('span');
2074 $ratinghtml .= html_writer::end_tag('div');
2075 $ratinghtml .= html_writer::end_tag('form');
2078 return $ratinghtml;
2082 * Centered heading with attached help button (same title text)
2083 * and optional icon attached.
2085 * @param string $text A heading text
2086 * @param string $helpidentifier The keyword that defines a help page
2087 * @param string $component component name
2088 * @param string|moodle_url $icon
2089 * @param string $iconalt icon alt text
2090 * @param int $level The level of importance of the heading. Defaulting to 2
2091 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2092 * @return string HTML fragment
2094 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2095 $image = '';
2096 if ($icon) {
2097 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2100 $help = '';
2101 if ($helpidentifier) {
2102 $help = $this->help_icon($helpidentifier, $component);
2105 return $this->heading($image.$text.$help, $level, $classnames);
2109 * Returns HTML to display a help icon.
2111 * @deprecated since Moodle 2.0
2113 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2114 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2118 * Returns HTML to display a help icon.
2120 * Theme developers: DO NOT OVERRIDE! Please override function
2121 * {@link core_renderer::render_help_icon()} instead.
2123 * @param string $identifier The keyword that defines a help page
2124 * @param string $component component name
2125 * @param string|bool $linktext true means use $title as link text, string means link text value
2126 * @return string HTML fragment
2128 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2129 $icon = new help_icon($identifier, $component);
2130 $icon->diag_strings();
2131 if ($linktext === true) {
2132 $icon->linktext = get_string($icon->identifier, $icon->component);
2133 } else if (!empty($linktext)) {
2134 $icon->linktext = $linktext;
2136 return $this->render($icon);
2140 * Implementation of user image rendering.
2142 * @param help_icon $helpicon A help icon instance
2143 * @return string HTML fragment
2145 protected function render_help_icon(help_icon $helpicon) {
2146 global $CFG;
2148 // first get the help image icon
2149 $src = $this->pix_url('help');
2151 $title = get_string($helpicon->identifier, $helpicon->component);
2153 if (empty($helpicon->linktext)) {
2154 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
2155 } else {
2156 $alt = get_string('helpwiththis');
2159 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
2160 $output = html_writer::empty_tag('img', $attributes);
2162 // add the link text if given
2163 if (!empty($helpicon->linktext)) {
2164 // the spacing has to be done through CSS
2165 $output .= $helpicon->linktext;
2168 // now create the link around it - we need https on loginhttps pages
2169 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
2171 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
2172 $title = get_string('helpprefix2', '', trim($title, ". \t"));
2174 $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true', 'target'=>'_blank');
2175 $output = html_writer::tag('a', $output, $attributes);
2177 // and finally span
2178 return html_writer::tag('span', $output, array('class' => 'helptooltip'));
2182 * Returns HTML to display a scale help icon.
2184 * @param int $courseid
2185 * @param stdClass $scale instance
2186 * @return string HTML fragment
2188 public function help_icon_scale($courseid, stdClass $scale) {
2189 global $CFG;
2191 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2193 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2195 $scaleid = abs($scale->id);
2197 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2198 $action = new popup_action('click', $link, 'ratingscale');
2200 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2204 * Creates and returns a spacer image with optional line break.
2206 * @param array $attributes Any HTML attributes to add to the spaced.
2207 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2208 * laxy do it with CSS which is a much better solution.
2209 * @return string HTML fragment
2211 public function spacer(array $attributes = null, $br = false) {
2212 $attributes = (array)$attributes;
2213 if (empty($attributes['width'])) {
2214 $attributes['width'] = 1;
2216 if (empty($attributes['height'])) {
2217 $attributes['height'] = 1;
2219 $attributes['class'] = 'spacer';
2221 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2223 if (!empty($br)) {
2224 $output .= '<br />';
2227 return $output;
2231 * Returns HTML to display the specified user's avatar.
2233 * User avatar may be obtained in two ways:
2234 * <pre>
2235 * // Option 1: (shortcut for simple cases, preferred way)
2236 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2237 * $OUTPUT->user_picture($user, array('popup'=>true));
2239 * // Option 2:
2240 * $userpic = new user_picture($user);
2241 * // Set properties of $userpic
2242 * $userpic->popup = true;
2243 * $OUTPUT->render($userpic);
2244 * </pre>
2246 * Theme developers: DO NOT OVERRIDE! Please override function
2247 * {@link core_renderer::render_user_picture()} instead.
2249 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2250 * If any of these are missing, the database is queried. Avoid this
2251 * if at all possible, particularly for reports. It is very bad for performance.
2252 * @param array $options associative array with user picture options, used only if not a user_picture object,
2253 * options are:
2254 * - courseid=$this->page->course->id (course id of user profile in link)
2255 * - size=35 (size of image)
2256 * - link=true (make image clickable - the link leads to user profile)
2257 * - popup=false (open in popup)
2258 * - alttext=true (add image alt attribute)
2259 * - class = image class attribute (default 'userpicture')
2260 * @return string HTML fragment
2262 public function user_picture(stdClass $user, array $options = null) {
2263 $userpicture = new user_picture($user);
2264 foreach ((array)$options as $key=>$value) {
2265 if (array_key_exists($key, $userpicture)) {
2266 $userpicture->$key = $value;
2269 return $this->render($userpicture);
2273 * Internal implementation of user image rendering.
2275 * @param user_picture $userpicture
2276 * @return string
2278 protected function render_user_picture(user_picture $userpicture) {
2279 global $CFG, $DB;
2281 $user = $userpicture->user;
2283 if ($userpicture->alttext) {
2284 if (!empty($user->imagealt)) {
2285 $alt = $user->imagealt;
2286 } else {
2287 $alt = get_string('pictureof', '', fullname($user));
2289 } else {
2290 $alt = '';
2293 if (empty($userpicture->size)) {
2294 $size = 35;
2295 } else if ($userpicture->size === true or $userpicture->size == 1) {
2296 $size = 100;
2297 } else {
2298 $size = $userpicture->size;
2301 $class = $userpicture->class;
2303 if ($user->picture == 0) {
2304 $class .= ' defaultuserpic';
2307 $src = $userpicture->get_url($this->page, $this);
2309 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2311 // get the image html output fisrt
2312 $output = html_writer::empty_tag('img', $attributes);
2314 // then wrap it in link if needed
2315 if (!$userpicture->link) {
2316 return $output;
2319 if (empty($userpicture->courseid)) {
2320 $courseid = $this->page->course->id;
2321 } else {
2322 $courseid = $userpicture->courseid;
2325 if ($courseid == SITEID) {
2326 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2327 } else {
2328 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2331 $attributes = array('href'=>$url);
2333 if ($userpicture->popup) {
2334 $id = html_writer::random_id('userpicture');
2335 $attributes['id'] = $id;
2336 $this->add_action_handler(new popup_action('click', $url), $id);
2339 return html_writer::tag('a', $output, $attributes);
2343 * Internal implementation of file tree viewer items rendering.
2345 * @param array $dir
2346 * @return string
2348 public function htmllize_file_tree($dir) {
2349 if (empty($dir['subdirs']) and empty($dir['files'])) {
2350 return '';
2352 $result = '<ul>';
2353 foreach ($dir['subdirs'] as $subdir) {
2354 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2356 foreach ($dir['files'] as $file) {
2357 $filename = $file->get_filename();
2358 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2360 $result .= '</ul>';
2362 return $result;
2366 * Returns HTML to display the file picker
2368 * <pre>
2369 * $OUTPUT->file_picker($options);
2370 * </pre>
2372 * Theme developers: DO NOT OVERRIDE! Please override function
2373 * {@link core_renderer::render_file_picker()} instead.
2375 * @param array $options associative array with file manager options
2376 * options are:
2377 * maxbytes=>-1,
2378 * itemid=>0,
2379 * client_id=>uniqid(),
2380 * acepted_types=>'*',
2381 * return_types=>FILE_INTERNAL,
2382 * context=>$PAGE->context
2383 * @return string HTML fragment
2385 public function file_picker($options) {
2386 $fp = new file_picker($options);
2387 return $this->render($fp);
2391 * Internal implementation of file picker rendering.
2393 * @param file_picker $fp
2394 * @return string
2396 public function render_file_picker(file_picker $fp) {
2397 global $CFG, $OUTPUT, $USER;
2398 $options = $fp->options;
2399 $client_id = $options->client_id;
2400 $strsaved = get_string('filesaved', 'repository');
2401 $straddfile = get_string('openpicker', 'repository');
2402 $strloading = get_string('loading', 'repository');
2403 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2404 $strdroptoupload = get_string('droptoupload', 'moodle');
2405 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2407 $currentfile = $options->currentfile;
2408 if (empty($currentfile)) {
2409 $currentfile = '';
2410 } else {
2411 $currentfile .= ' - ';
2413 if ($options->maxbytes) {
2414 $size = $options->maxbytes;
2415 } else {
2416 $size = get_max_upload_file_size();
2418 if ($size == -1) {
2419 $maxsize = '';
2420 } else {
2421 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2423 if ($options->buttonname) {
2424 $buttonname = ' name="' . $options->buttonname . '"';
2425 } else {
2426 $buttonname = '';
2428 $html = <<<EOD
2429 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2430 $icon_progress
2431 </div>
2432 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2433 <div>
2434 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2435 <span> $maxsize </span>
2436 </div>
2437 EOD;
2438 if ($options->env != 'url') {
2439 $html .= <<<EOD
2440 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2441 <div class="filepicker-filename">
2442 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2443 <div class="dndupload-progressbars"></div>
2444 </div>
2445 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2446 </div>
2447 EOD;
2449 $html .= '</div>';
2450 return $html;
2454 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2456 * @param string $cmid the course_module id.
2457 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2458 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2460 public function update_module_button($cmid, $modulename) {
2461 global $CFG;
2462 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2463 $modulename = get_string('modulename', $modulename);
2464 $string = get_string('updatethis', '', $modulename);
2465 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2466 return $this->single_button($url, $string);
2467 } else {
2468 return '';
2473 * Returns HTML to display a "Turn editing on/off" button in a form.
2475 * @param moodle_url $url The URL + params to send through when clicking the button
2476 * @return string HTML the button
2478 public function edit_button(moodle_url $url) {
2480 $url->param('sesskey', sesskey());
2481 if ($this->page->user_is_editing()) {
2482 $url->param('edit', 'off');
2483 $editstring = get_string('turneditingoff');
2484 } else {
2485 $url->param('edit', 'on');
2486 $editstring = get_string('turneditingon');
2489 return $this->single_button($url, $editstring);
2493 * Returns HTML to display a simple button to close a window
2495 * @param string $text The lang string for the button's label (already output from get_string())
2496 * @return string html fragment
2498 public function close_window_button($text='') {
2499 if (empty($text)) {
2500 $text = get_string('closewindow');
2502 $button = new single_button(new moodle_url('#'), $text, 'get');
2503 $button->add_action(new component_action('click', 'close_window'));
2505 return $this->container($this->render($button), 'closewindow');
2509 * Output an error message. By default wraps the error message in <span class="error">.
2510 * If the error message is blank, nothing is output.
2512 * @param string $message the error message.
2513 * @return string the HTML to output.
2515 public function error_text($message) {
2516 if (empty($message)) {
2517 return '';
2519 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2520 return html_writer::tag('span', $message, array('class' => 'error'));
2524 * Do not call this function directly.
2526 * To terminate the current script with a fatal error, call the {@link print_error}
2527 * function, or throw an exception. Doing either of those things will then call this
2528 * function to display the error, before terminating the execution.
2530 * @param string $message The message to output
2531 * @param string $moreinfourl URL where more info can be found about the error
2532 * @param string $link Link for the Continue button
2533 * @param array $backtrace The execution backtrace
2534 * @param string $debuginfo Debugging information
2535 * @return string the HTML to output.
2537 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2538 global $CFG;
2540 $output = '';
2541 $obbuffer = '';
2543 if ($this->has_started()) {
2544 // we can not always recover properly here, we have problems with output buffering,
2545 // html tables, etc.
2546 $output .= $this->opencontainers->pop_all_but_last();
2548 } else {
2549 // It is really bad if library code throws exception when output buffering is on,
2550 // because the buffered text would be printed before our start of page.
2551 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2552 error_reporting(0); // disable notices from gzip compression, etc.
2553 while (ob_get_level() > 0) {
2554 $buff = ob_get_clean();
2555 if ($buff === false) {
2556 break;
2558 $obbuffer .= $buff;
2560 error_reporting($CFG->debug);
2562 // Output not yet started.
2563 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2564 if (empty($_SERVER['HTTP_RANGE'])) {
2565 @header($protocol . ' 404 Not Found');
2566 } else {
2567 // Must stop byteserving attempts somehow,
2568 // this is weird but Chrome PDF viewer can be stopped only with 407!
2569 @header($protocol . ' 407 Proxy Authentication Required');
2572 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2573 $this->page->set_url('/'); // no url
2574 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2575 $this->page->set_title(get_string('error'));
2576 $this->page->set_heading($this->page->course->fullname);
2577 $output .= $this->header();
2580 $message = '<p class="errormessage">' . $message . '</p>'.
2581 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2582 get_string('moreinformation') . '</a></p>';
2583 if (empty($CFG->rolesactive)) {
2584 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2585 //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.
2587 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
2589 if ($CFG->debugdeveloper) {
2590 if (!empty($debuginfo)) {
2591 $debuginfo = s($debuginfo); // removes all nasty JS
2592 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2593 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2595 if (!empty($backtrace)) {
2596 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2598 if ($obbuffer !== '' ) {
2599 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2603 if (empty($CFG->rolesactive)) {
2604 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2605 } else if (!empty($link)) {
2606 $output .= $this->continue_button($link);
2609 $output .= $this->footer();
2611 // Padding to encourage IE to display our error page, rather than its own.
2612 $output .= str_repeat(' ', 512);
2614 return $output;
2618 * Output a notification (that is, a status message about something that has
2619 * just happened).
2621 * @param string $message the message to print out
2622 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2623 * @return string the HTML to output.
2625 public function notification($message, $classes = 'notifyproblem') {
2626 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2630 * Returns HTML to display a continue button that goes to a particular URL.
2632 * @param string|moodle_url $url The url the button goes to.
2633 * @return string the HTML to output.
2635 public function continue_button($url) {
2636 if (!($url instanceof moodle_url)) {
2637 $url = new moodle_url($url);
2639 $button = new single_button($url, get_string('continue'), 'get');
2640 $button->class = 'continuebutton';
2642 return $this->render($button);
2646 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2648 * Theme developers: DO NOT OVERRIDE! Please override function
2649 * {@link core_renderer::render_paging_bar()} instead.
2651 * @param int $totalcount The total number of entries available to be paged through
2652 * @param int $page The page you are currently viewing
2653 * @param int $perpage The number of entries that should be shown per page
2654 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2655 * @param string $pagevar name of page parameter that holds the page number
2656 * @return string the HTML to output.
2658 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2659 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2660 return $this->render($pb);
2664 * Internal implementation of paging bar rendering.
2666 * @param paging_bar $pagingbar
2667 * @return string
2669 protected function render_paging_bar(paging_bar $pagingbar) {
2670 $output = '';
2671 $pagingbar = clone($pagingbar);
2672 $pagingbar->prepare($this, $this->page, $this->target);
2674 if ($pagingbar->totalcount > $pagingbar->perpage) {
2675 $output .= get_string('page') . ':';
2677 if (!empty($pagingbar->previouslink)) {
2678 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
2681 if (!empty($pagingbar->firstlink)) {
2682 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
2685 foreach ($pagingbar->pagelinks as $link) {
2686 $output .= "&#160;&#160;$link";
2689 if (!empty($pagingbar->lastlink)) {
2690 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
2693 if (!empty($pagingbar->nextlink)) {
2694 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
2698 return html_writer::tag('div', $output, array('class' => 'paging'));
2702 * Output the place a skip link goes to.
2704 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2705 * @return string the HTML to output.
2707 public function skip_link_target($id = null) {
2708 return html_writer::tag('span', '', array('id' => $id));
2712 * Outputs a heading
2714 * @param string $text The text of the heading
2715 * @param int $level The level of importance of the heading. Defaulting to 2
2716 * @param string $classes A space-separated list of CSS classes. Defaulting to null
2717 * @param string $id An optional ID
2718 * @return string the HTML to output.
2720 public function heading($text, $level = 2, $classes = null, $id = null) {
2721 $level = (integer) $level;
2722 if ($level < 1 or $level > 6) {
2723 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2725 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2729 * Outputs a box.
2731 * @param string $contents The contents of the box
2732 * @param string $classes A space-separated list of CSS classes
2733 * @param string $id An optional ID
2734 * @param array $attributes An array of other attributes to give the box.
2735 * @return string the HTML to output.
2737 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
2738 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
2742 * Outputs the opening section of a box.
2744 * @param string $classes A space-separated list of CSS classes
2745 * @param string $id An optional ID
2746 * @param array $attributes An array of other attributes to give the box.
2747 * @return string the HTML to output.
2749 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
2750 $this->opencontainers->push('box', html_writer::end_tag('div'));
2751 $attributes['id'] = $id;
2752 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
2753 return html_writer::start_tag('div', $attributes);
2757 * Outputs the closing section of a box.
2759 * @return string the HTML to output.
2761 public function box_end() {
2762 return $this->opencontainers->pop('box');
2766 * Outputs a container.
2768 * @param string $contents The contents of the box
2769 * @param string $classes A space-separated list of CSS classes
2770 * @param string $id An optional ID
2771 * @return string the HTML to output.
2773 public function container($contents, $classes = null, $id = null) {
2774 return $this->container_start($classes, $id) . $contents . $this->container_end();
2778 * Outputs the opening section of a container.
2780 * @param string $classes A space-separated list of CSS classes
2781 * @param string $id An optional ID
2782 * @return string the HTML to output.
2784 public function container_start($classes = null, $id = null) {
2785 $this->opencontainers->push('container', html_writer::end_tag('div'));
2786 return html_writer::start_tag('div', array('id' => $id,
2787 'class' => renderer_base::prepare_classes($classes)));
2791 * Outputs the closing section of a container.
2793 * @return string the HTML to output.
2795 public function container_end() {
2796 return $this->opencontainers->pop('container');
2800 * Make nested HTML lists out of the items
2802 * The resulting list will look something like this:
2804 * <pre>
2805 * <<ul>>
2806 * <<li>><div class='tree_item parent'>(item contents)</div>
2807 * <<ul>
2808 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2809 * <</ul>>
2810 * <</li>>
2811 * <</ul>>
2812 * </pre>
2814 * @param array $items
2815 * @param array $attrs html attributes passed to the top ofs the list
2816 * @return string HTML
2818 public function tree_block_contents($items, $attrs = array()) {
2819 // exit if empty, we don't want an empty ul element
2820 if (empty($items)) {
2821 return '';
2823 // array of nested li elements
2824 $lis = array();
2825 foreach ($items as $item) {
2826 // this applies to the li item which contains all child lists too
2827 $content = $item->content($this);
2828 $liclasses = array($item->get_css_type());
2829 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2830 $liclasses[] = 'collapsed';
2832 if ($item->isactive === true) {
2833 $liclasses[] = 'current_branch';
2835 $liattr = array('class'=>join(' ',$liclasses));
2836 // class attribute on the div item which only contains the item content
2837 $divclasses = array('tree_item');
2838 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2839 $divclasses[] = 'branch';
2840 } else {
2841 $divclasses[] = 'leaf';
2843 if (!empty($item->classes) && count($item->classes)>0) {
2844 $divclasses[] = join(' ', $item->classes);
2846 $divattr = array('class'=>join(' ', $divclasses));
2847 if (!empty($item->id)) {
2848 $divattr['id'] = $item->id;
2850 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2851 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2852 $content = html_writer::empty_tag('hr') . $content;
2854 $content = html_writer::tag('li', $content, $liattr);
2855 $lis[] = $content;
2857 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2861 * Return the navbar content so that it can be echoed out by the layout
2863 * @return string XHTML navbar
2865 public function navbar() {
2866 $items = $this->page->navbar->get_items();
2867 $itemcount = count($items);
2868 if ($itemcount === 0) {
2869 return '';
2872 $htmlblocks = array();
2873 // Iterate the navarray and display each node
2874 $separator = get_separator();
2875 for ($i=0;$i < $itemcount;$i++) {
2876 $item = $items[$i];
2877 $item->hideicon = true;
2878 if ($i===0) {
2879 $content = html_writer::tag('li', $this->render($item));
2880 } else {
2881 $content = html_writer::tag('li', $separator.$this->render($item));
2883 $htmlblocks[] = $content;
2886 //accessibility: heading for navbar list (MDL-20446)
2887 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2888 $navbarcontent .= html_writer::tag('nav', html_writer::tag('ul', join('', $htmlblocks)));
2889 // XHTML
2890 return $navbarcontent;
2894 * Renders a navigation node object.
2896 * @param navigation_node $item The navigation node to render.
2897 * @return string HTML fragment
2899 protected function render_navigation_node(navigation_node $item) {
2900 $content = $item->get_content();
2901 $title = $item->get_title();
2902 if ($item->icon instanceof renderable && !$item->hideicon) {
2903 $icon = $this->render($item->icon);
2904 $content = $icon.$content; // use CSS for spacing of icons
2906 if ($item->helpbutton !== null) {
2907 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2909 if ($content === '') {
2910 return '';
2912 if ($item->action instanceof action_link) {
2913 $link = $item->action;
2914 if ($item->hidden) {
2915 $link->add_class('dimmed');
2917 if (!empty($content)) {
2918 // Providing there is content we will use that for the link content.
2919 $link->text = $content;
2921 $content = $this->render($link);
2922 } else if ($item->action instanceof moodle_url) {
2923 $attributes = array();
2924 if ($title !== '') {
2925 $attributes['title'] = $title;
2927 if ($item->hidden) {
2928 $attributes['class'] = 'dimmed_text';
2930 $content = html_writer::link($item->action, $content, $attributes);
2932 } else if (is_string($item->action) || empty($item->action)) {
2933 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2934 if ($title !== '') {
2935 $attributes['title'] = $title;
2937 if ($item->hidden) {
2938 $attributes['class'] = 'dimmed_text';
2940 $content = html_writer::tag('span', $content, $attributes);
2942 return $content;
2946 * Accessibility: Right arrow-like character is
2947 * used in the breadcrumb trail, course navigation menu
2948 * (previous/next activity), calendar, and search forum block.
2949 * If the theme does not set characters, appropriate defaults
2950 * are set automatically. Please DO NOT
2951 * use &lt; &gt; &raquo; - these are confusing for blind users.
2953 * @return string
2955 public function rarrow() {
2956 return $this->page->theme->rarrow;
2960 * Accessibility: Left arrow-like character is
2961 * used in the breadcrumb trail, course navigation menu
2962 * (previous/next activity), calendar, and search forum block.
2963 * If the theme does not set characters, appropriate defaults
2964 * are set automatically. Please DO NOT
2965 * use &lt; &gt; &raquo; - these are confusing for blind users.
2967 * @return string
2969 public function larrow() {
2970 return $this->page->theme->larrow;
2974 * Returns the custom menu if one has been set
2976 * A custom menu can be configured by browsing to
2977 * Settings: Administration > Appearance > Themes > Theme settings
2978 * and then configuring the custommenu config setting as described.
2980 * Theme developers: DO NOT OVERRIDE! Please override function
2981 * {@link core_renderer::render_custom_menu()} instead.
2983 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
2984 * @return string
2986 public function custom_menu($custommenuitems = '') {
2987 global $CFG;
2988 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
2989 $custommenuitems = $CFG->custommenuitems;
2991 if (empty($custommenuitems)) {
2992 return '';
2994 $custommenu = new custom_menu($custommenuitems, current_language());
2995 return $this->render($custommenu);
2999 * Renders a custom menu object (located in outputcomponents.php)
3001 * The custom menu this method produces makes use of the YUI3 menunav widget
3002 * and requires very specific html elements and classes.
3004 * @staticvar int $menucount
3005 * @param custom_menu $menu
3006 * @return string
3008 protected function render_custom_menu(custom_menu $menu) {
3009 static $menucount = 0;
3010 // If the menu has no children return an empty string
3011 if (!$menu->has_children()) {
3012 return '';
3014 // Increment the menu count. This is used for ID's that get worked with
3015 // in JavaScript as is essential
3016 $menucount++;
3017 // Initialise this custom menu (the custom menu object is contained in javascript-static
3018 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
3019 $jscode = "(function(){{$jscode}})";
3020 $this->page->requires->yui_module('node-menunav', $jscode);
3021 // Build the root nodes as required by YUI
3022 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
3023 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3024 $content .= html_writer::start_tag('ul');
3025 // Render each child
3026 foreach ($menu->get_children() as $item) {
3027 $content .= $this->render_custom_menu_item($item);
3029 // Close the open tags
3030 $content .= html_writer::end_tag('ul');
3031 $content .= html_writer::end_tag('div');
3032 $content .= html_writer::end_tag('div');
3033 // Return the custom menu
3034 return $content;
3038 * Renders a custom menu node as part of a submenu
3040 * The custom menu this method produces makes use of the YUI3 menunav widget
3041 * and requires very specific html elements and classes.
3043 * @see core:renderer::render_custom_menu()
3045 * @staticvar int $submenucount
3046 * @param custom_menu_item $menunode
3047 * @return string
3049 protected function render_custom_menu_item(custom_menu_item $menunode) {
3050 // Required to ensure we get unique trackable id's
3051 static $submenucount = 0;
3052 if ($menunode->has_children()) {
3053 // If the child has menus render it as a sub menu
3054 $submenucount++;
3055 $content = html_writer::start_tag('li');
3056 if ($menunode->get_url() !== null) {
3057 $url = $menunode->get_url();
3058 } else {
3059 $url = '#cm_submenu_'.$submenucount;
3061 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3062 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3063 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3064 $content .= html_writer::start_tag('ul');
3065 foreach ($menunode->get_children() as $menunode) {
3066 $content .= $this->render_custom_menu_item($menunode);
3068 $content .= html_writer::end_tag('ul');
3069 $content .= html_writer::end_tag('div');
3070 $content .= html_writer::end_tag('div');
3071 $content .= html_writer::end_tag('li');
3072 } else {
3073 // The node doesn't have children so produce a final menuitem
3074 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
3075 if ($menunode->get_url() !== null) {
3076 $url = $menunode->get_url();
3077 } else {
3078 $url = '#';
3080 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
3081 $content .= html_writer::end_tag('li');
3083 // Return the sub menu
3084 return $content;
3088 * Renders theme links for switching between default and other themes.
3090 * @return string
3092 protected function theme_switch_links() {
3094 $actualdevice = core_useragent::get_device_type();
3095 $currentdevice = $this->page->devicetypeinuse;
3096 $switched = ($actualdevice != $currentdevice);
3098 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3099 // The user is using the a default device and hasn't switched so don't shown the switch
3100 // device links.
3101 return '';
3104 if ($switched) {
3105 $linktext = get_string('switchdevicerecommended');
3106 $devicetype = $actualdevice;
3107 } else {
3108 $linktext = get_string('switchdevicedefault');
3109 $devicetype = 'default';
3111 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3113 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3114 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3115 $content .= html_writer::end_tag('div');
3117 return $content;
3121 * Renders tabs
3123 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3125 * Theme developers: In order to change how tabs are displayed please override functions
3126 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3128 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3129 * @param string|null $selected which tab to mark as selected, all parent tabs will
3130 * automatically be marked as activated
3131 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3132 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3133 * @return string
3135 public final function tabtree($tabs, $selected = null, $inactive = null) {
3136 return $this->render(new tabtree($tabs, $selected, $inactive));
3140 * Renders tabtree
3142 * @param tabtree $tabtree
3143 * @return string
3145 protected function render_tabtree(tabtree $tabtree) {
3146 if (empty($tabtree->subtree)) {
3147 return '';
3149 $str = '';
3150 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
3151 $str .= $this->render_tabobject($tabtree);
3152 $str .= html_writer::end_tag('div').
3153 html_writer::tag('div', ' ', array('class' => 'clearer'));
3154 return $str;
3158 * Renders tabobject (part of tabtree)
3160 * This function is called from {@link core_renderer::render_tabtree()}
3161 * and also it calls itself when printing the $tabobject subtree recursively.
3163 * Property $tabobject->level indicates the number of row of tabs.
3165 * @param tabobject $tabobject
3166 * @return string HTML fragment
3168 protected function render_tabobject(tabobject $tabobject) {
3169 $str = '';
3171 // Print name of the current tab.
3172 if ($tabobject instanceof tabtree) {
3173 // No name for tabtree root.
3174 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3175 // Tab name without a link. The <a> tag is used for styling.
3176 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3177 } else {
3178 // Tab name with a link.
3179 if (!($tabobject->link instanceof moodle_url)) {
3180 // backward compartibility when link was passed as quoted string
3181 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3182 } else {
3183 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3187 if (empty($tabobject->subtree)) {
3188 if ($tabobject->selected) {
3189 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3191 return $str;
3194 // Print subtree
3195 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3196 $cnt = 0;
3197 foreach ($tabobject->subtree as $tab) {
3198 $liclass = '';
3199 if (!$cnt) {
3200 $liclass .= ' first';
3202 if ($cnt == count($tabobject->subtree) - 1) {
3203 $liclass .= ' last';
3205 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3206 $liclass .= ' onerow';
3209 if ($tab->selected) {
3210 $liclass .= ' here selected';
3211 } else if ($tab->activated) {
3212 $liclass .= ' here active';
3215 // This will recursively call function render_tabobject() for each item in subtree
3216 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3217 $cnt++;
3219 $str .= html_writer::end_tag('ul');
3221 return $str;
3225 * Get the HTML for blocks in the given region.
3227 * @since Moodle 2.5.1 2.6
3228 * @param string $region The region to get HTML for.
3229 * @return string HTML.
3231 public function blocks($region, $classes = array(), $tag = 'aside') {
3232 $displayregion = $this->page->apply_theme_region_manipulations($region);
3233 $classes = (array)$classes;
3234 $classes[] = 'block-region';
3235 $attributes = array(
3236 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3237 'class' => join(' ', $classes),
3238 'data-blockregion' => $displayregion,
3239 'data-droptarget' => '1'
3241 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3242 $content = $this->blocks_for_region($displayregion);
3243 } else {
3244 $content = '';
3246 return html_writer::tag($tag, $content, $attributes);
3250 * Renders a custom block region.
3252 * Use this method if you want to add an additional block region to the content of the page.
3253 * Please note this should only be used in special situations.
3254 * We want to leave the theme is control where ever possible!
3256 * This method must use the same method that the theme uses within its layout file.
3257 * As such it asks the theme what method it is using.
3258 * It can be one of two values, blocks or blocks_for_region (deprecated).
3260 * @param string $regionname The name of the custom region to add.
3261 * @return string HTML for the block region.
3263 public function custom_block_region($regionname) {
3264 if ($this->page->theme->get_block_render_method() === 'blocks') {
3265 return $this->blocks($regionname);
3266 } else {
3267 return $this->blocks_for_region($regionname);
3272 * Returns the CSS classes to apply to the body tag.
3274 * @since Moodle 2.5.1 2.6
3275 * @param array $additionalclasses Any additional classes to apply.
3276 * @return string
3278 public function body_css_classes(array $additionalclasses = array()) {
3279 // Add a class for each block region on the page.
3280 // We use the block manager here because the theme object makes get_string calls.
3281 foreach ($this->page->blocks->get_regions() as $region) {
3282 $additionalclasses[] = 'has-region-'.$region;
3283 if ($this->page->blocks->region_has_content($region, $this)) {
3284 $additionalclasses[] = 'used-region-'.$region;
3285 } else {
3286 $additionalclasses[] = 'empty-region-'.$region;
3288 if ($this->page->blocks->region_completely_docked($region, $this)) {
3289 $additionalclasses[] = 'docked-region-'.$region;
3292 foreach ($this->page->layout_options as $option => $value) {
3293 if ($value) {
3294 $additionalclasses[] = 'layout-option-'.$option;
3297 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
3298 return $css;
3302 * The ID attribute to apply to the body tag.
3304 * @since Moodle 2.5.1 2.6
3305 * @return string
3307 public function body_id() {
3308 return $this->page->bodyid;
3312 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
3314 * @since Moodle 2.5.1 2.6
3315 * @param string|array $additionalclasses Any additional classes to give the body tag,
3316 * @return string
3318 public function body_attributes($additionalclasses = array()) {
3319 if (!is_array($additionalclasses)) {
3320 $additionalclasses = explode(' ', $additionalclasses);
3322 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
3326 * Gets HTML for the page heading.
3328 * @since Moodle 2.5.1 2.6
3329 * @param string $tag The tag to encase the heading in. h1 by default.
3330 * @return string HTML.
3332 public function page_heading($tag = 'h1') {
3333 return html_writer::tag($tag, $this->page->heading);
3337 * Gets the HTML for the page heading button.
3339 * @since Moodle 2.5.1 2.6
3340 * @return string HTML.
3342 public function page_heading_button() {
3343 return $this->page->button;
3347 * Returns the Moodle docs link to use for this page.
3349 * @since Moodle 2.5.1 2.6
3350 * @param string $text
3351 * @return string
3353 public function page_doc_link($text = null) {
3354 if ($text === null) {
3355 $text = get_string('moodledocslink');
3357 $path = page_get_doc_link_path($this->page);
3358 if (!$path) {
3359 return '';
3361 return $this->doc_link($path, $text);
3365 * Returns the page heading menu.
3367 * @since Moodle 2.5.1 2.6
3368 * @return string HTML.
3370 public function page_heading_menu() {
3371 return $this->page->headingmenu;
3375 * Returns the title to use on the page.
3377 * @since Moodle 2.5.1 2.6
3378 * @return string
3380 public function page_title() {
3381 return $this->page->title;
3385 * Returns the URL for the favicon.
3387 * @since Moodle 2.5.1 2.6
3388 * @return string The favicon URL
3390 public function favicon() {
3391 return $this->pix_url('favicon', 'theme');
3396 * A renderer that generates output for command-line scripts.
3398 * The implementation of this renderer is probably incomplete.
3400 * @copyright 2009 Tim Hunt
3401 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3402 * @since Moodle 2.0
3403 * @package core
3404 * @category output
3406 class core_renderer_cli extends core_renderer {
3409 * Returns the page header.
3411 * @return string HTML fragment
3413 public function header() {
3414 return $this->page->heading . "\n";
3418 * Returns a template fragment representing a Heading.
3420 * @param string $text The text of the heading
3421 * @param int $level The level of importance of the heading
3422 * @param string $classes A space-separated list of CSS classes
3423 * @param string $id An optional ID
3424 * @return string A template fragment for a heading
3426 public function heading($text, $level = 2, $classes = 'main', $id = null) {
3427 $text .= "\n";
3428 switch ($level) {
3429 case 1:
3430 return '=>' . $text;
3431 case 2:
3432 return '-->' . $text;
3433 default:
3434 return $text;
3439 * Returns a template fragment representing a fatal error.
3441 * @param string $message The message to output
3442 * @param string $moreinfourl URL where more info can be found about the error
3443 * @param string $link Link for the Continue button
3444 * @param array $backtrace The execution backtrace
3445 * @param string $debuginfo Debugging information
3446 * @return string A template fragment for a fatal error
3448 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
3449 global $CFG;
3451 $output = "!!! $message !!!\n";
3453 if ($CFG->debugdeveloper) {
3454 if (!empty($debuginfo)) {
3455 $output .= $this->notification($debuginfo, 'notifytiny');
3457 if (!empty($backtrace)) {
3458 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
3462 return $output;
3466 * Returns a template fragment representing a notification.
3468 * @param string $message The message to include
3469 * @param string $classes A space-separated list of CSS classes
3470 * @return string A template fragment for a notification
3472 public function notification($message, $classes = 'notifyproblem') {
3473 $message = clean_text($message);
3474 if ($classes === 'notifysuccess') {
3475 return "++ $message ++\n";
3477 return "!! $message !!\n";
3483 * A renderer that generates output for ajax scripts.
3485 * This renderer prevents accidental sends back only json
3486 * encoded error messages, all other output is ignored.
3488 * @copyright 2010 Petr Skoda
3489 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3490 * @since Moodle 2.0
3491 * @package core
3492 * @category output
3494 class core_renderer_ajax extends core_renderer {
3497 * Returns a template fragment representing a fatal error.
3499 * @param string $message The message to output
3500 * @param string $moreinfourl URL where more info can be found about the error
3501 * @param string $link Link for the Continue button
3502 * @param array $backtrace The execution backtrace
3503 * @param string $debuginfo Debugging information
3504 * @return string A template fragment for a fatal error
3506 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
3507 global $CFG;
3509 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
3511 $e = new stdClass();
3512 $e->error = $message;
3513 $e->stacktrace = NULL;
3514 $e->debuginfo = NULL;
3515 $e->reproductionlink = NULL;
3516 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
3517 $link = (string) $link;
3518 if ($link) {
3519 $e->reproductionlink = $link;
3521 if (!empty($debuginfo)) {
3522 $e->debuginfo = $debuginfo;
3524 if (!empty($backtrace)) {
3525 $e->stacktrace = format_backtrace($backtrace, true);
3528 $this->header();
3529 return json_encode($e);
3533 * Used to display a notification.
3534 * For the AJAX notifications are discarded.
3536 * @param string $message
3537 * @param string $classes
3539 public function notification($message, $classes = 'notifyproblem') {}
3542 * Used to display a redirection message.
3543 * AJAX redirections should not occur and as such redirection messages
3544 * are discarded.
3546 * @param moodle_url|string $encodedurl
3547 * @param string $message
3548 * @param int $delay
3549 * @param bool $debugdisableredirect
3551 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
3554 * Prepares the start of an AJAX output.
3556 public function header() {
3557 // unfortunately YUI iframe upload does not support application/json
3558 if (!empty($_FILES)) {
3559 @header('Content-type: text/plain; charset=utf-8');
3560 if (!core_useragent::supports_json_contenttype()) {
3561 @header('X-Content-Type-Options: nosniff');
3563 } else if (!core_useragent::supports_json_contenttype()) {
3564 @header('Content-type: text/plain; charset=utf-8');
3565 @header('X-Content-Type-Options: nosniff');
3566 } else {
3567 @header('Content-type: application/json; charset=utf-8');
3570 // Headers to make it not cacheable and json
3571 @header('Cache-Control: no-store, no-cache, must-revalidate');
3572 @header('Cache-Control: post-check=0, pre-check=0', false);
3573 @header('Pragma: no-cache');
3574 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
3575 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
3576 @header('Accept-Ranges: none');
3580 * There is no footer for an AJAX request, however we must override the
3581 * footer method to prevent the default footer.
3583 public function footer() {}
3586 * No need for headers in an AJAX request... this should never happen.
3587 * @param string $text
3588 * @param int $level
3589 * @param string $classes
3590 * @param string $id
3592 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
3597 * Renderer for media files.
3599 * Used in file resources, media filter, and any other places that need to
3600 * output embedded media.
3602 * @copyright 2011 The Open University
3603 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3605 class core_media_renderer extends plugin_renderer_base {
3606 /** @var array Array of available 'player' objects */
3607 private $players;
3608 /** @var string Regex pattern for links which may contain embeddable content */
3609 private $embeddablemarkers;
3612 * Constructor requires medialib.php.
3614 * This is needed in the constructor (not later) so that you can use the
3615 * constants and static functions that are defined in core_media class
3616 * before you call renderer functions.
3618 public function __construct() {
3619 global $CFG;
3620 require_once($CFG->libdir . '/medialib.php');
3624 * Obtains the list of core_media_player objects currently in use to render
3625 * items.
3627 * The list is in rank order (highest first) and does not include players
3628 * which are disabled.
3630 * @return array Array of core_media_player objects in rank order
3632 protected function get_players() {
3633 global $CFG;
3635 // Save time by only building the list once.
3636 if (!$this->players) {
3637 // Get raw list of players.
3638 $players = $this->get_players_raw();
3640 // Chuck all the ones that are disabled.
3641 foreach ($players as $key => $player) {
3642 if (!$player->is_enabled()) {
3643 unset($players[$key]);
3647 // Sort in rank order (highest first).
3648 usort($players, array('core_media_player', 'compare_by_rank'));
3649 $this->players = $players;
3651 return $this->players;
3655 * Obtains a raw list of player objects that includes objects regardless
3656 * of whether they are disabled or not, and without sorting.
3658 * You can override this in a subclass if you need to add additional
3659 * players.
3661 * The return array is be indexed by player name to make it easier to
3662 * remove players in a subclass.
3664 * @return array $players Array of core_media_player objects in any order
3666 protected function get_players_raw() {
3667 return array(
3668 'vimeo' => new core_media_player_vimeo(),
3669 'youtube' => new core_media_player_youtube(),
3670 'youtube_playlist' => new core_media_player_youtube_playlist(),
3671 'html5video' => new core_media_player_html5video(),
3672 'html5audio' => new core_media_player_html5audio(),
3673 'mp3' => new core_media_player_mp3(),
3674 'flv' => new core_media_player_flv(),
3675 'wmp' => new core_media_player_wmp(),
3676 'qt' => new core_media_player_qt(),
3677 'rm' => new core_media_player_rm(),
3678 'swf' => new core_media_player_swf(),
3679 'link' => new core_media_player_link(),
3684 * Renders a media file (audio or video) using suitable embedded player.
3686 * See embed_alternatives function for full description of parameters.
3687 * This function calls through to that one.
3689 * When using this function you can also specify width and height in the
3690 * URL by including ?d=100x100 at the end. If specified in the URL, this
3691 * will override the $width and $height parameters.
3693 * @param moodle_url $url Full URL of media file
3694 * @param string $name Optional user-readable name to display in download link
3695 * @param int $width Width in pixels (optional)
3696 * @param int $height Height in pixels (optional)
3697 * @param array $options Array of key/value pairs
3698 * @return string HTML content of embed
3700 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
3701 $options = array()) {
3703 // Get width and height from URL if specified (overrides parameters in
3704 // function call).
3705 $rawurl = $url->out(false);
3706 if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
3707 $width = $matches[1];
3708 $height = $matches[2];
3709 $url = new moodle_url(str_replace($matches[0], '', $rawurl));
3712 // Defer to array version of function.
3713 return $this->embed_alternatives(array($url), $name, $width, $height, $options);
3717 * Renders media files (audio or video) using suitable embedded player.
3718 * The list of URLs should be alternative versions of the same content in
3719 * multiple formats. If there is only one format it should have a single
3720 * entry.
3722 * If the media files are not in a supported format, this will give students
3723 * a download link to each format. The download link uses the filename
3724 * unless you supply the optional name parameter.
3726 * Width and height are optional. If specified, these are suggested sizes
3727 * and should be the exact values supplied by the user, if they come from
3728 * user input. These will be treated as relating to the size of the video
3729 * content, not including any player control bar.
3731 * For audio files, height will be ignored. For video files, a few formats
3732 * work if you specify only width, but in general if you specify width
3733 * you must specify height as well.
3735 * The $options array is passed through to the core_media_player classes
3736 * that render the object tag. The keys can contain values from
3737 * core_media::OPTION_xx.
3739 * @param array $alternatives Array of moodle_url to media files
3740 * @param string $name Optional user-readable name to display in download link
3741 * @param int $width Width in pixels (optional)
3742 * @param int $height Height in pixels (optional)
3743 * @param array $options Array of key/value pairs
3744 * @return string HTML content of embed
3746 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
3747 $options = array()) {
3749 // Get list of player plugins (will also require the library).
3750 $players = $this->get_players();
3752 // Set up initial text which will be replaced by first player that
3753 // supports any of the formats.
3754 $out = core_media_player::PLACEHOLDER;
3756 // Loop through all players that support any of these URLs.
3757 foreach ($players as $player) {
3758 // Option: When no other player matched, don't do the default link player.
3759 if (!empty($options[core_media::OPTION_FALLBACK_TO_BLANK]) &&
3760 $player->get_rank() === 0 && $out === core_media_player::PLACEHOLDER) {
3761 continue;
3764 $supported = $player->list_supported_urls($alternatives, $options);
3765 if ($supported) {
3766 // Embed.
3767 $text = $player->embed($supported, $name, $width, $height, $options);
3769 // Put this in place of the 'fallback' slot in the previous text.
3770 $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
3774 // Remove 'fallback' slot from final version and return it.
3775 $out = str_replace(core_media_player::PLACEHOLDER, '', $out);
3776 if (!empty($options[core_media::OPTION_BLOCK]) && $out !== '') {
3777 $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
3779 return $out;
3783 * Checks whether a file can be embedded. If this returns true you will get
3784 * an embedded player; if this returns false, you will just get a download
3785 * link.
3787 * This is a wrapper for can_embed_urls.
3789 * @param moodle_url $url URL of media file
3790 * @param array $options Options (same as when embedding)
3791 * @return bool True if file can be embedded
3793 public function can_embed_url(moodle_url $url, $options = array()) {
3794 return $this->can_embed_urls(array($url), $options);
3798 * Checks whether a file can be embedded. If this returns true you will get
3799 * an embedded player; if this returns false, you will just get a download
3800 * link.
3802 * @param array $urls URL of media file and any alternatives (moodle_url)
3803 * @param array $options Options (same as when embedding)
3804 * @return bool True if file can be embedded
3806 public function can_embed_urls(array $urls, $options = array()) {
3807 // Check all players to see if any of them support it.
3808 foreach ($this->get_players() as $player) {
3809 // Link player (always last on list) doesn't count!
3810 if ($player->get_rank() <= 0) {
3811 break;
3813 // First player that supports it, return true.
3814 if ($player->list_supported_urls($urls, $options)) {
3815 return true;
3818 return false;
3822 * Obtains a list of markers that can be used in a regular expression when
3823 * searching for URLs that can be embedded by any player type.
3825 * This string is used to improve peformance of regex matching by ensuring
3826 * that the (presumably C) regex code can do a quick keyword check on the
3827 * URL part of a link to see if it matches one of these, rather than having
3828 * to go into PHP code for every single link to see if it can be embedded.
3830 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
3832 public function get_embeddable_markers() {
3833 if (empty($this->embeddablemarkers)) {
3834 $markers = '';
3835 foreach ($this->get_players() as $player) {
3836 foreach ($player->get_embeddable_markers() as $marker) {
3837 if ($markers !== '') {
3838 $markers .= '|';
3840 $markers .= preg_quote($marker);
3843 $this->embeddablemarkers = $markers;
3845 return $this->embeddablemarkers;
3850 * The maintenance renderer.
3852 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
3853 * is running a maintenance related task.
3854 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
3856 * @since Moodle 2.6
3857 * @package core
3858 * @category output
3859 * @copyright 2013 Sam Hemelryk
3860 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3862 class core_renderer_maintenance extends core_renderer {
3865 * Initialises the renderer instance.
3866 * @param moodle_page $page
3867 * @param string $target
3868 * @throws coding_exception
3870 public function __construct(moodle_page $page, $target) {
3871 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
3872 throw new coding_exception('Invalid request for the maintenance renderer.');
3874 parent::__construct($page, $target);
3878 * Does nothing. The maintenance renderer cannot produce blocks.
3880 * @param block_contents $bc
3881 * @param string $region
3882 * @return string
3884 public function block(block_contents $bc, $region) {
3885 // Computer says no blocks.
3886 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3887 return '';
3891 * Does nothing. The maintenance renderer cannot produce blocks.
3893 * @param string $region
3894 * @param array $classes
3895 * @param string $tag
3896 * @return string
3898 public function blocks($region, $classes = array(), $tag = 'aside') {
3899 // Computer says no blocks.
3900 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3901 return '';
3905 * Does nothing. The maintenance renderer cannot produce blocks.
3907 * @param string $region
3908 * @return string
3910 public function blocks_for_region($region) {
3911 // Computer says no blocks for region.
3912 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3913 return '';
3917 * Does nothing. The maintenance renderer cannot produce a course content header.
3919 * @param bool $onlyifnotcalledbefore
3920 * @return string
3922 public function course_content_header($onlyifnotcalledbefore = false) {
3923 // Computer says no course content header.
3924 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3925 return '';
3929 * Does nothing. The maintenance renderer cannot produce a course content footer.
3931 * @param bool $onlyifnotcalledbefore
3932 * @return string
3934 public function course_content_footer($onlyifnotcalledbefore = false) {
3935 // Computer says no course content footer.
3936 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3937 return '';
3941 * Does nothing. The maintenance renderer cannot produce a course header.
3943 * @return string
3945 public function course_header() {
3946 // Computer says no course header.
3947 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3948 return '';
3952 * Does nothing. The maintenance renderer cannot produce a course footer.
3954 * @return string
3956 public function course_footer() {
3957 // Computer says no course footer.
3958 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3959 return '';
3963 * Does nothing. The maintenance renderer cannot produce a custom menu.
3965 * @param string $custommenuitems
3966 * @return string
3968 public function custom_menu($custommenuitems = '') {
3969 // Computer says no custom menu.
3970 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3971 return '';
3975 * Does nothing. The maintenance renderer cannot produce a file picker.
3977 * @param array $options
3978 * @return string
3980 public function file_picker($options) {
3981 // Computer says no file picker.
3982 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3983 return '';
3987 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
3989 * @param array $dir
3990 * @return string
3992 public function htmllize_file_tree($dir) {
3993 // Hell no we don't want no htmllized file tree.
3994 // Also why on earth is this function on the core renderer???
3995 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3996 return '';
4001 * Does nothing. The maintenance renderer does not support JS.
4003 * @param block_contents $bc
4005 public function init_block_hider_js(block_contents $bc) {
4006 // Computer says no JavaScript.
4007 // Do nothing, ridiculous method.
4011 * Does nothing. The maintenance renderer cannot produce language menus.
4013 * @return string
4015 public function lang_menu() {
4016 // Computer says no lang menu.
4017 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4018 return '';
4022 * Does nothing. The maintenance renderer has no need for login information.
4024 * @param null $withlinks
4025 * @return string
4027 public function login_info($withlinks = null) {
4028 // Computer says no login info.
4029 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4030 return '';
4034 * Does nothing. The maintenance renderer cannot produce user pictures.
4036 * @param stdClass $user
4037 * @param array $options
4038 * @return string
4040 public function user_picture(stdClass $user, array $options = null) {
4041 // Computer says no user pictures.
4042 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4043 return '';