Moodle release 2.7.12
[moodle.git] / lib / outputrenderers.php
blob3f72d1a3a75a69393924ecb57a862af086b039e3
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 $classname = get_class($widget);
100 // Strip namespaces.
101 $classname = preg_replace('/^.*\\\/', '', $classname);
103 $rendermethod = 'render_'.$classname;
104 if (method_exists($this, $rendermethod)) {
105 return $this->$rendermethod($widget);
107 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
111 * Adds a JS action for the element with the provided id.
113 * This method adds a JS event for the provided component action to the page
114 * and then returns the id that the event has been attached to.
115 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
117 * @param component_action $action
118 * @param string $id
119 * @return string id of element, either original submitted or random new if not supplied
121 public function add_action_handler(component_action $action, $id = null) {
122 if (!$id) {
123 $id = html_writer::random_id($action->event);
125 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
126 return $id;
130 * Returns true is output has already started, and false if not.
132 * @return boolean true if the header has been printed.
134 public function has_started() {
135 return $this->page->state >= moodle_page::STATE_IN_BODY;
139 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
141 * @param mixed $classes Space-separated string or array of classes
142 * @return string HTML class attribute value
144 public static function prepare_classes($classes) {
145 if (is_array($classes)) {
146 return implode(' ', array_unique($classes));
148 return $classes;
152 * Return the moodle_url for an image.
154 * The exact image location and extension is determined
155 * automatically by searching for gif|png|jpg|jpeg, please
156 * note there can not be diferent images with the different
157 * extension. The imagename is for historical reasons
158 * a relative path name, it may be changed later for core
159 * images. It is recommended to not use subdirectories
160 * in plugin and theme pix directories.
162 * There are three types of images:
163 * 1/ theme images - stored in theme/mytheme/pix/,
164 * use component 'theme'
165 * 2/ core images - stored in /pix/,
166 * overridden via theme/mytheme/pix_core/
167 * 3/ plugin images - stored in mod/mymodule/pix,
168 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
169 * example: pix_url('comment', 'mod_glossary')
171 * @param string $imagename the pathname of the image
172 * @param string $component full plugin name (aka component) or 'theme'
173 * @return moodle_url
175 public function pix_url($imagename, $component = 'moodle') {
176 return $this->page->theme->pix_url($imagename, $component);
182 * Basis for all plugin renderers.
184 * @copyright Petr Skoda (skodak)
185 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
186 * @since Moodle 2.0
187 * @package core
188 * @category output
190 class plugin_renderer_base extends renderer_base {
193 * @var renderer_base|core_renderer A reference to the current renderer.
194 * The renderer provided here will be determined by the page but will in 90%
195 * of cases by the {@link core_renderer}
197 protected $output;
200 * Constructor method, calls the parent constructor
202 * @param moodle_page $page
203 * @param string $target one of rendering target constants
205 public function __construct(moodle_page $page, $target) {
206 if (empty($target) && $page->pagelayout === 'maintenance') {
207 // If the page is using the maintenance layout then we're going to force the target to maintenance.
208 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
209 // unavailable for this page layout.
210 $target = RENDERER_TARGET_MAINTENANCE;
212 $this->output = $page->get_renderer('core', null, $target);
213 parent::__construct($page, $target);
217 * Renders the provided widget and returns the HTML to display it.
219 * @param renderable $widget instance with renderable interface
220 * @return string
222 public function render(renderable $widget) {
223 $classname = get_class($widget);
224 // Strip namespaces.
225 $classname = preg_replace('/^.*\\\/', '', $classname);
227 $rendermethod = 'render_'.$classname;
228 if (method_exists($this, $rendermethod)) {
229 return $this->$rendermethod($widget);
231 // pass to core renderer if method not found here
232 return $this->output->render($widget);
236 * Magic method used to pass calls otherwise meant for the standard renderer
237 * to it to ensure we don't go causing unnecessary grief.
239 * @param string $method
240 * @param array $arguments
241 * @return mixed
243 public function __call($method, $arguments) {
244 if (method_exists('renderer_base', $method)) {
245 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
247 if (method_exists($this->output, $method)) {
248 return call_user_func_array(array($this->output, $method), $arguments);
249 } else {
250 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
257 * The standard implementation of the core_renderer interface.
259 * @copyright 2009 Tim Hunt
260 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
261 * @since Moodle 2.0
262 * @package core
263 * @category output
265 class core_renderer extends renderer_base {
267 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
268 * in layout files instead.
269 * @deprecated
270 * @var string used in {@link core_renderer::header()}.
272 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
275 * @var string Used to pass information from {@link core_renderer::doctype()} to
276 * {@link core_renderer::standard_head_html()}.
278 protected $contenttype;
281 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
282 * with {@link core_renderer::header()}.
284 protected $metarefreshtag = '';
287 * @var string Unique token for the closing HTML
289 protected $unique_end_html_token;
292 * @var string Unique token for performance information
294 protected $unique_performance_info_token;
297 * @var string Unique token for the main content.
299 protected $unique_main_content_token;
302 * Constructor
304 * @param moodle_page $page the page we are doing output for.
305 * @param string $target one of rendering target constants
307 public function __construct(moodle_page $page, $target) {
308 $this->opencontainers = $page->opencontainers;
309 $this->page = $page;
310 $this->target = $target;
312 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
313 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
314 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
318 * Get the DOCTYPE declaration that should be used with this page. Designed to
319 * be called in theme layout.php files.
321 * @return string the DOCTYPE declaration that should be used.
323 public function doctype() {
324 if ($this->page->theme->doctype === 'html5') {
325 $this->contenttype = 'text/html; charset=utf-8';
326 return "<!DOCTYPE html>\n";
328 } else if ($this->page->theme->doctype === 'xhtml5') {
329 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
330 return "<!DOCTYPE html>\n";
332 } else {
333 // legacy xhtml 1.0
334 $this->contenttype = 'text/html; charset=utf-8';
335 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
340 * The attributes that should be added to the <html> tag. Designed to
341 * be called in theme layout.php files.
343 * @return string HTML fragment.
345 public function htmlattributes() {
346 $return = get_html_lang(true);
347 if ($this->page->theme->doctype !== 'html5') {
348 $return .= ' xmlns="http://www.w3.org/1999/xhtml"';
350 return $return;
354 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
355 * that should be included in the <head> tag. Designed to be called in theme
356 * layout.php files.
358 * @return string HTML fragment.
360 public function standard_head_html() {
361 global $CFG, $SESSION;
363 // Before we output any content, we need to ensure that certain
364 // page components are set up.
366 // Blocks must be set up early as they may require javascript which
367 // has to be included in the page header before output is created.
368 foreach ($this->page->blocks->get_regions() as $region) {
369 $this->page->blocks->ensure_content_created($region, $this);
372 $output = '';
373 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
374 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
375 // This is only set by the {@link redirect()} method
376 $output .= $this->metarefreshtag;
378 // Check if a periodic refresh delay has been set and make sure we arn't
379 // already meta refreshing
380 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
381 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
384 // flow player embedding support
385 $this->page->requires->js_function_call('M.util.load_flowplayer');
387 // Set up help link popups for all links with the helptooltip class
388 $this->page->requires->js_init_call('M.util.help_popups.setup');
390 // Setup help icon overlays.
391 $this->page->requires->yui_module('moodle-core-popuphelp', 'M.core.init_popuphelp');
392 $this->page->requires->strings_for_js(array(
393 'morehelp',
394 'loadinghelp',
395 ), 'moodle');
397 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
399 $focus = $this->page->focuscontrol;
400 if (!empty($focus)) {
401 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
402 // This is a horrifically bad way to handle focus but it is passed in
403 // through messy formslib::moodleform
404 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
405 } else if (strpos($focus, '.')!==false) {
406 // Old style of focus, bad way to do it
407 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);
408 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
409 } else {
410 // Focus element with given id
411 $this->page->requires->js_function_call('focuscontrol', array($focus));
415 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
416 // any other custom CSS can not be overridden via themes and is highly discouraged
417 $urls = $this->page->theme->css_urls($this->page);
418 foreach ($urls as $url) {
419 $this->page->requires->css_theme($url);
422 // Get the theme javascript head and footer
423 if ($jsurl = $this->page->theme->javascript_url(true)) {
424 $this->page->requires->js($jsurl, true);
426 if ($jsurl = $this->page->theme->javascript_url(false)) {
427 $this->page->requires->js($jsurl);
430 // Get any HTML from the page_requirements_manager.
431 $output .= $this->page->requires->get_head_code($this->page, $this);
433 // List alternate versions.
434 foreach ($this->page->alternateversions as $type => $alt) {
435 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
436 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
439 if (!empty($CFG->additionalhtmlhead)) {
440 $output .= "\n".$CFG->additionalhtmlhead;
443 return $output;
447 * The standard tags (typically skip links) that should be output just inside
448 * the start of the <body> tag. Designed to be called in theme layout.php files.
450 * @return string HTML fragment.
452 public function standard_top_of_body_html() {
453 global $CFG;
454 $output = $this->page->requires->get_top_of_body_code();
455 if (!empty($CFG->additionalhtmltopofbody)) {
456 $output .= "\n".$CFG->additionalhtmltopofbody;
458 $output .= $this->maintenance_warning();
459 return $output;
463 * Scheduled maintenance warning message.
465 * Note: This is a nasty hack to display maintenance notice, this should be moved
466 * to some general notification area once we have it.
468 * @return string
470 public function maintenance_warning() {
471 global $CFG;
473 $output = '';
474 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
475 $timeleft = $CFG->maintenance_later - time();
476 // If timeleft less than 30 sec, set the class on block to error to highlight.
477 $errorclass = ($timeleft < 30) ? 'error' : 'warning';
478 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning');
479 $a = new stdClass();
480 $a->min = (int)($timeleft/60);
481 $a->sec = (int)($timeleft % 60);
482 $output .= get_string('maintenancemodeisscheduled', 'admin', $a) ;
483 $output .= $this->box_end();
484 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
485 array(array('timeleftinsec' => $timeleft)));
486 $this->page->requires->strings_for_js(
487 array('maintenancemodeisscheduled', 'sitemaintenance'),
488 'admin');
490 return $output;
494 * The standard tags (typically performance information and validation links,
495 * if we are in developer debug mode) that should be output in the footer area
496 * of the page. Designed to be called in theme layout.php files.
498 * @return string HTML fragment.
500 public function standard_footer_html() {
501 global $CFG, $SCRIPT;
503 if (during_initial_install()) {
504 // Debugging info can not work before install is finished,
505 // in any case we do not want any links during installation!
506 return '';
509 // This function is normally called from a layout.php file in {@link core_renderer::header()}
510 // but some of the content won't be known until later, so we return a placeholder
511 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
512 $output = $this->unique_performance_info_token;
513 if ($this->page->devicetypeinuse == 'legacy') {
514 // The legacy theme is in use print the notification
515 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
518 // Get links to switch device types (only shown for users not on a default device)
519 $output .= $this->theme_switch_links();
521 if (!empty($CFG->debugpageinfo)) {
522 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
524 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
525 // Add link to profiling report if necessary
526 if (function_exists('profiling_is_running') && profiling_is_running()) {
527 $txt = get_string('profiledscript', 'admin');
528 $title = get_string('profiledscriptview', 'admin');
529 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
530 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
531 $output .= '<div class="profilingfooter">' . $link . '</div>';
533 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
534 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
535 $output .= '<div class="purgecaches">' .
536 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
538 if (!empty($CFG->debugvalidators)) {
539 // 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
540 $output .= '<div class="validators"><ul>
541 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
542 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
543 <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>
544 </ul></div>';
546 return $output;
550 * Returns standard main content placeholder.
551 * Designed to be called in theme layout.php files.
553 * @return string HTML fragment.
555 public function main_content() {
556 // This is here because it is the only place we can inject the "main" role over the entire main content area
557 // without requiring all theme's to manually do it, and without creating yet another thing people need to
558 // remember in the theme.
559 // This is an unfortunate hack. DO NO EVER add anything more here.
560 // DO NOT add classes.
561 // DO NOT add an id.
562 return '<div role="main">'.$this->unique_main_content_token.'</div>';
566 * The standard tags (typically script tags that are not needed earlier) that
567 * should be output after everything else. Designed to be called in theme layout.php files.
569 * @return string HTML fragment.
571 public function standard_end_of_body_html() {
572 global $CFG;
574 // This function is normally called from a layout.php file in {@link core_renderer::header()}
575 // but some of the content won't be known until later, so we return a placeholder
576 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
577 $output = '';
578 if (!empty($CFG->additionalhtmlfooter)) {
579 $output .= "\n".$CFG->additionalhtmlfooter;
581 $output .= $this->unique_end_html_token;
582 return $output;
586 * Return the standard string that says whether you are logged in (and switched
587 * roles/logged in as another user).
588 * @param bool $withlinks if false, then don't include any links in the HTML produced.
589 * If not set, the default is the nologinlinks option from the theme config.php file,
590 * and if that is not set, then links are included.
591 * @return string HTML fragment.
593 public function login_info($withlinks = null) {
594 global $USER, $CFG, $DB, $SESSION;
596 if (during_initial_install()) {
597 return '';
600 if (is_null($withlinks)) {
601 $withlinks = empty($this->page->layout_options['nologinlinks']);
604 $loginpage = ((string)$this->page->url === get_login_url());
605 $course = $this->page->course;
606 if (\core\session\manager::is_loggedinas()) {
607 $realuser = \core\session\manager::get_realuser();
608 $fullname = fullname($realuser, true);
609 if ($withlinks) {
610 $loginastitle = get_string('loginas');
611 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
612 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
613 } else {
614 $realuserinfo = " [$fullname] ";
616 } else {
617 $realuserinfo = '';
620 $loginurl = get_login_url();
622 if (empty($course->id)) {
623 // $course->id is not defined during installation
624 return '';
625 } else if (isloggedin()) {
626 $context = context_course::instance($course->id);
628 $fullname = fullname($USER, true);
629 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
630 if ($withlinks) {
631 $linktitle = get_string('viewprofile');
632 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
633 } else {
634 $username = $fullname;
636 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
637 if ($withlinks) {
638 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
639 } else {
640 $username .= " from {$idprovider->name}";
643 if (isguestuser()) {
644 $loggedinas = $realuserinfo.get_string('loggedinasguest');
645 if (!$loginpage && $withlinks) {
646 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
648 } else if (is_role_switched($course->id)) { // Has switched roles
649 $rolename = '';
650 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
651 $rolename = ': '.role_get_name($role, $context);
653 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
654 if ($withlinks) {
655 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
656 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
658 } else {
659 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
660 if ($withlinks) {
661 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
664 } else {
665 $loggedinas = get_string('loggedinnot', 'moodle');
666 if (!$loginpage && $withlinks) {
667 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
671 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
673 if (isset($SESSION->justloggedin)) {
674 unset($SESSION->justloggedin);
675 if (!empty($CFG->displayloginfailures)) {
676 if (!isguestuser()) {
677 // Include this file only when required.
678 require_once($CFG->dirroot . '/user/lib.php');
679 if ($count = user_count_login_failures($USER)) {
680 $loggedinas .= '<div class="loginfailures">';
681 $a = new stdClass();
682 $a->attempts = $count;
683 $loggedinas .= get_string('failedloginattempts', '', $a);
684 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
685 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
686 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
688 $loggedinas .= '</div>';
694 return $loggedinas;
698 * Return the 'back' link that normally appears in the footer.
700 * @return string HTML fragment.
702 public function home_link() {
703 global $CFG, $SITE;
705 if ($this->page->pagetype == 'site-index') {
706 // Special case for site home page - please do not remove
707 return '<div class="sitelink">' .
708 '<a title="Moodle" href="http://moodle.org/">' .
709 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
711 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
712 // Special case for during install/upgrade.
713 return '<div class="sitelink">'.
714 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
715 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
717 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
718 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
719 get_string('home') . '</a></div>';
721 } else {
722 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
723 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
728 * Redirects the user by any means possible given the current state
730 * This function should not be called directly, it should always be called using
731 * the redirect function in lib/weblib.php
733 * The redirect function should really only be called before page output has started
734 * however it will allow itself to be called during the state STATE_IN_BODY
736 * @param string $encodedurl The URL to send to encoded if required
737 * @param string $message The message to display to the user if any
738 * @param int $delay The delay before redirecting a user, if $message has been
739 * set this is a requirement and defaults to 3, set to 0 no delay
740 * @param boolean $debugdisableredirect this redirect has been disabled for
741 * debugging purposes. Display a message that explains, and don't
742 * trigger the redirect.
743 * @return string The HTML to display to the user before dying, may contain
744 * meta refresh, javascript refresh, and may have set header redirects
746 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
747 global $CFG;
748 $url = str_replace('&amp;', '&', $encodedurl);
750 switch ($this->page->state) {
751 case moodle_page::STATE_BEFORE_HEADER :
752 // No output yet it is safe to delivery the full arsenal of redirect methods
753 if (!$debugdisableredirect) {
754 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
755 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
756 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
758 $output = $this->header();
759 break;
760 case moodle_page::STATE_PRINTING_HEADER :
761 // We should hopefully never get here
762 throw new coding_exception('You cannot redirect while printing the page header');
763 break;
764 case moodle_page::STATE_IN_BODY :
765 // We really shouldn't be here but we can deal with this
766 debugging("You should really redirect before you start page output");
767 if (!$debugdisableredirect) {
768 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
770 $output = $this->opencontainers->pop_all_but_last();
771 break;
772 case moodle_page::STATE_DONE :
773 // Too late to be calling redirect now
774 throw new coding_exception('You cannot redirect after the entire page has been generated');
775 break;
777 $output .= $this->notification($message, 'redirectmessage');
778 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
779 if ($debugdisableredirect) {
780 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
782 $output .= $this->footer();
783 return $output;
787 * Start output by sending the HTTP headers, and printing the HTML <head>
788 * and the start of the <body>.
790 * To control what is printed, you should set properties on $PAGE. If you
791 * are familiar with the old {@link print_header()} function from Moodle 1.9
792 * you will find that there are properties on $PAGE that correspond to most
793 * of the old parameters to could be passed to print_header.
795 * Not that, in due course, the remaining $navigation, $menu parameters here
796 * will be replaced by more properties of $PAGE, but that is still to do.
798 * @return string HTML that you must output this, preferably immediately.
800 public function header() {
801 global $USER, $CFG;
803 if (\core\session\manager::is_loggedinas()) {
804 $this->page->add_body_class('userloggedinas');
807 // Give themes a chance to init/alter the page object.
808 $this->page->theme->init_page($this->page);
810 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
812 // Find the appropriate page layout file, based on $this->page->pagelayout.
813 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
814 // Render the layout using the layout file.
815 $rendered = $this->render_page_layout($layoutfile);
817 // Slice the rendered output into header and footer.
818 $cutpos = strpos($rendered, $this->unique_main_content_token);
819 if ($cutpos === false) {
820 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
821 $token = self::MAIN_CONTENT_TOKEN;
822 } else {
823 $token = $this->unique_main_content_token;
826 if ($cutpos === false) {
827 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.');
829 $header = substr($rendered, 0, $cutpos);
830 $footer = substr($rendered, $cutpos + strlen($token));
832 if (empty($this->contenttype)) {
833 debugging('The page layout file did not call $OUTPUT->doctype()');
834 $header = $this->doctype() . $header;
837 // If this theme version is below 2.4 release and this is a course view page
838 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
839 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
840 // check if course content header/footer have not been output during render of theme layout
841 $coursecontentheader = $this->course_content_header(true);
842 $coursecontentfooter = $this->course_content_footer(true);
843 if (!empty($coursecontentheader)) {
844 // display debug message and add header and footer right above and below main content
845 // Please note that course header and footer (to be displayed above and below the whole page)
846 // are not displayed in this case at all.
847 // Besides the content header and footer are not displayed on any other course page
848 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);
849 $header .= $coursecontentheader;
850 $footer = $coursecontentfooter. $footer;
854 send_headers($this->contenttype, $this->page->cacheable);
856 $this->opencontainers->push('header/footer', $footer);
857 $this->page->set_state(moodle_page::STATE_IN_BODY);
859 return $header . $this->skip_link_target('maincontent');
863 * Renders and outputs the page layout file.
865 * This is done by preparing the normal globals available to a script, and
866 * then including the layout file provided by the current theme for the
867 * requested layout.
869 * @param string $layoutfile The name of the layout file
870 * @return string HTML code
872 protected function render_page_layout($layoutfile) {
873 global $CFG, $SITE, $USER;
874 // The next lines are a bit tricky. The point is, here we are in a method
875 // of a renderer class, and this object may, or may not, be the same as
876 // the global $OUTPUT object. When rendering the page layout file, we want to use
877 // this object. However, people writing Moodle code expect the current
878 // renderer to be called $OUTPUT, not $this, so define a variable called
879 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
880 $OUTPUT = $this;
881 $PAGE = $this->page;
882 $COURSE = $this->page->course;
884 ob_start();
885 include($layoutfile);
886 $rendered = ob_get_contents();
887 ob_end_clean();
888 return $rendered;
892 * Outputs the page's footer
894 * @return string HTML fragment
896 public function footer() {
897 global $CFG, $DB;
899 $output = $this->container_end_all(true);
901 $footer = $this->opencontainers->pop('header/footer');
903 if (debugging() and $DB and $DB->is_transaction_started()) {
904 // TODO: MDL-20625 print warning - transaction will be rolled back
907 // Provide some performance info if required
908 $performanceinfo = '';
909 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
910 $perf = get_performance_info();
911 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
912 $performanceinfo = $perf['html'];
916 // We always want performance data when running a performance test, even if the user is redirected to another page.
917 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
918 $footer = $this->unique_performance_info_token . $footer;
920 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
922 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
924 $this->page->set_state(moodle_page::STATE_DONE);
926 return $output . $footer;
930 * Close all but the last open container. This is useful in places like error
931 * handling, where you want to close all the open containers (apart from <body>)
932 * before outputting the error message.
934 * @param bool $shouldbenone assert that the stack should be empty now - causes a
935 * developer debug warning if it isn't.
936 * @return string the HTML required to close any open containers inside <body>.
938 public function container_end_all($shouldbenone = false) {
939 return $this->opencontainers->pop_all_but_last($shouldbenone);
943 * Returns course-specific information to be output immediately above content on any course page
944 * (for the current course)
946 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
947 * @return string
949 public function course_content_header($onlyifnotcalledbefore = false) {
950 global $CFG;
951 if ($this->page->course->id == SITEID) {
952 // return immediately and do not include /course/lib.php if not necessary
953 return '';
955 static $functioncalled = false;
956 if ($functioncalled && $onlyifnotcalledbefore) {
957 // we have already output the content header
958 return '';
960 require_once($CFG->dirroot.'/course/lib.php');
961 $functioncalled = true;
962 $courseformat = course_get_format($this->page->course);
963 if (($obj = $courseformat->course_content_header()) !== null) {
964 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
966 return '';
970 * Returns course-specific information to be output immediately below content on any course page
971 * (for the current course)
973 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
974 * @return string
976 public function course_content_footer($onlyifnotcalledbefore = false) {
977 global $CFG;
978 if ($this->page->course->id == SITEID) {
979 // return immediately and do not include /course/lib.php if not necessary
980 return '';
982 static $functioncalled = false;
983 if ($functioncalled && $onlyifnotcalledbefore) {
984 // we have already output the content footer
985 return '';
987 $functioncalled = true;
988 require_once($CFG->dirroot.'/course/lib.php');
989 $courseformat = course_get_format($this->page->course);
990 if (($obj = $courseformat->course_content_footer()) !== null) {
991 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
993 return '';
997 * Returns course-specific information to be output on any course page in the header area
998 * (for the current course)
1000 * @return string
1002 public function course_header() {
1003 global $CFG;
1004 if ($this->page->course->id == SITEID) {
1005 // return immediately and do not include /course/lib.php if not necessary
1006 return '';
1008 require_once($CFG->dirroot.'/course/lib.php');
1009 $courseformat = course_get_format($this->page->course);
1010 if (($obj = $courseformat->course_header()) !== null) {
1011 return $courseformat->get_renderer($this->page)->render($obj);
1013 return '';
1017 * Returns course-specific information to be output on any course page in the footer area
1018 * (for the current course)
1020 * @return string
1022 public function course_footer() {
1023 global $CFG;
1024 if ($this->page->course->id == SITEID) {
1025 // return immediately and do not include /course/lib.php if not necessary
1026 return '';
1028 require_once($CFG->dirroot.'/course/lib.php');
1029 $courseformat = course_get_format($this->page->course);
1030 if (($obj = $courseformat->course_footer()) !== null) {
1031 return $courseformat->get_renderer($this->page)->render($obj);
1033 return '';
1037 * Returns lang menu or '', this method also checks forcing of languages in courses.
1039 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1041 * @return string The lang menu HTML or empty string
1043 public function lang_menu() {
1044 global $CFG;
1046 if (empty($CFG->langmenu)) {
1047 return '';
1050 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1051 // do not show lang menu if language forced
1052 return '';
1055 $currlang = current_language();
1056 $langs = get_string_manager()->get_list_of_translations();
1058 if (count($langs) < 2) {
1059 return '';
1062 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1063 $s->label = get_accesshide(get_string('language'));
1064 $s->class = 'langmenu';
1065 return $this->render($s);
1069 * Output the row of editing icons for a block, as defined by the controls array.
1071 * @param array $controls an array like {@link block_contents::$controls}.
1072 * @param string $blockid The ID given to the block.
1073 * @return string HTML fragment.
1075 public function block_controls($actions, $blockid = null) {
1076 global $CFG;
1077 if (empty($actions)) {
1078 return '';
1080 $menu = new action_menu($actions);
1081 if ($blockid !== null) {
1082 $menu->set_owner_selector('#'.$blockid);
1084 $menu->set_constraint('.block-region');
1085 $menu->attributes['class'] .= ' block-control-actions commands';
1086 if (isset($CFG->blockeditingmenu) && !$CFG->blockeditingmenu) {
1087 $menu->do_not_enhance();
1089 return $this->render($menu);
1093 * Renders an action menu component.
1095 * ARIA references:
1096 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1097 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1099 * @param action_menu $menu
1100 * @return string HTML
1102 public function render_action_menu(action_menu $menu) {
1103 $menu->initialise_js($this->page);
1105 $output = html_writer::start_tag('div', $menu->attributes);
1106 $output .= html_writer::start_tag('ul', $menu->attributesprimary);
1107 foreach ($menu->get_primary_actions($this) as $action) {
1108 if ($action instanceof renderable) {
1109 $content = $this->render($action);
1110 } else {
1111 $content = $action;
1113 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1115 $output .= html_writer::end_tag('ul');
1116 $output .= html_writer::start_tag('ul', $menu->attributessecondary);
1117 foreach ($menu->get_secondary_actions() as $action) {
1118 if ($action instanceof renderable) {
1119 $content = $this->render($action);
1120 } else {
1121 $content = $action;
1123 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1125 $output .= html_writer::end_tag('ul');
1126 $output .= html_writer::end_tag('div');
1127 return $output;
1131 * Renders an action_menu_link item.
1133 * @param action_menu_link $action
1134 * @return string HTML fragment
1136 protected function render_action_menu_link(action_menu_link $action) {
1137 static $actioncount = 0;
1138 $actioncount++;
1140 $comparetoalt = '';
1141 $text = '';
1142 if (!$action->icon || $action->primary === false) {
1143 $text .= html_writer::start_tag('span', array('class'=>'menu-action-text', 'id' => 'actionmenuaction-'.$actioncount));
1144 if ($action->text instanceof renderable) {
1145 $text .= $this->render($action->text);
1146 } else {
1147 $text .= $action->text;
1148 $comparetoalt = (string)$action->text;
1150 $text .= html_writer::end_tag('span');
1153 $icon = '';
1154 if ($action->icon) {
1155 $icon = $action->icon;
1156 if ($action->primary || !$action->actionmenu->will_be_enhanced()) {
1157 $action->attributes['title'] = $action->text;
1159 if (!$action->primary && $action->actionmenu->will_be_enhanced()) {
1160 if ((string)$icon->attributes['alt'] === $comparetoalt) {
1161 $icon->attributes['alt'] = '';
1163 if (isset($icon->attributes['title']) && (string)$icon->attributes['title'] === $comparetoalt) {
1164 unset($icon->attributes['title']);
1167 $icon = $this->render($icon);
1170 // A disabled link is rendered as formatted text.
1171 if (!empty($action->attributes['disabled'])) {
1172 // Do not use div here due to nesting restriction in xhtml strict.
1173 return html_writer::tag('span', $icon.$text, array('class'=>'currentlink', 'role' => 'menuitem'));
1176 $attributes = $action->attributes;
1177 unset($action->attributes['disabled']);
1178 $attributes['href'] = $action->url;
1179 if ($text !== '') {
1180 $attributes['aria-labelledby'] = 'actionmenuaction-'.$actioncount;
1183 return html_writer::tag('a', $icon.$text, $attributes);
1187 * Renders a primary action_menu_filler item.
1189 * @param action_menu_link_filler $action
1190 * @return string HTML fragment
1192 protected function render_action_menu_filler(action_menu_filler $action) {
1193 return html_writer::span('&nbsp;', 'filler');
1197 * Renders a primary action_menu_link item.
1199 * @param action_menu_link_primary $action
1200 * @return string HTML fragment
1202 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1203 return $this->render_action_menu_link($action);
1207 * Renders a secondary action_menu_link item.
1209 * @param action_menu_link_secondary $action
1210 * @return string HTML fragment
1212 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1213 return $this->render_action_menu_link($action);
1217 * Prints a nice side block with an optional header.
1219 * The content is described
1220 * by a {@link core_renderer::block_contents} object.
1222 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1223 * <div class="header"></div>
1224 * <div class="content">
1225 * ...CONTENT...
1226 * <div class="footer">
1227 * </div>
1228 * </div>
1229 * <div class="annotation">
1230 * </div>
1231 * </div>
1233 * @param block_contents $bc HTML for the content
1234 * @param string $region the region the block is appearing in.
1235 * @return string the HTML to be output.
1237 public function block(block_contents $bc, $region) {
1238 $bc = clone($bc); // Avoid messing up the object passed in.
1239 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1240 $bc->collapsible = block_contents::NOT_HIDEABLE;
1242 if (!empty($bc->blockinstanceid)) {
1243 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1245 $skiptitle = strip_tags($bc->title);
1246 if ($bc->blockinstanceid && !empty($skiptitle)) {
1247 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1248 } else if (!empty($bc->arialabel)) {
1249 $bc->attributes['aria-label'] = $bc->arialabel;
1251 if ($bc->dockable) {
1252 $bc->attributes['data-dockable'] = 1;
1254 if ($bc->collapsible == block_contents::HIDDEN) {
1255 $bc->add_class('hidden');
1257 if (!empty($bc->controls)) {
1258 $bc->add_class('block_with_controls');
1262 if (empty($skiptitle)) {
1263 $output = '';
1264 $skipdest = '';
1265 } else {
1266 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
1267 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
1270 $output .= html_writer::start_tag('div', $bc->attributes);
1272 $output .= $this->block_header($bc);
1273 $output .= $this->block_content($bc);
1275 $output .= html_writer::end_tag('div');
1277 $output .= $this->block_annotation($bc);
1279 $output .= $skipdest;
1281 $this->init_block_hider_js($bc);
1282 return $output;
1286 * Produces a header for a block
1288 * @param block_contents $bc
1289 * @return string
1291 protected function block_header(block_contents $bc) {
1293 $title = '';
1294 if ($bc->title) {
1295 $attributes = array();
1296 if ($bc->blockinstanceid) {
1297 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1299 $title = html_writer::tag('h2', $bc->title, $attributes);
1302 $blockid = null;
1303 if (isset($bc->attributes['id'])) {
1304 $blockid = $bc->attributes['id'];
1306 $controlshtml = $this->block_controls($bc->controls, $blockid);
1308 $output = '';
1309 if ($title || $controlshtml) {
1310 $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'));
1312 return $output;
1316 * Produces the content area for a block
1318 * @param block_contents $bc
1319 * @return string
1321 protected function block_content(block_contents $bc) {
1322 $output = html_writer::start_tag('div', array('class' => 'content'));
1323 if (!$bc->title && !$this->block_controls($bc->controls)) {
1324 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1326 $output .= $bc->content;
1327 $output .= $this->block_footer($bc);
1328 $output .= html_writer::end_tag('div');
1330 return $output;
1334 * Produces the footer for a block
1336 * @param block_contents $bc
1337 * @return string
1339 protected function block_footer(block_contents $bc) {
1340 $output = '';
1341 if ($bc->footer) {
1342 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1344 return $output;
1348 * Produces the annotation for a block
1350 * @param block_contents $bc
1351 * @return string
1353 protected function block_annotation(block_contents $bc) {
1354 $output = '';
1355 if ($bc->annotation) {
1356 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1358 return $output;
1362 * Calls the JS require function to hide a block.
1364 * @param block_contents $bc A block_contents object
1366 protected function init_block_hider_js(block_contents $bc) {
1367 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1368 $config = new stdClass;
1369 $config->id = $bc->attributes['id'];
1370 $config->title = strip_tags($bc->title);
1371 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1372 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1373 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1375 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1376 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1381 * Render the contents of a block_list.
1383 * @param array $icons the icon for each item.
1384 * @param array $items the content of each item.
1385 * @return string HTML
1387 public function list_block_contents($icons, $items) {
1388 $row = 0;
1389 $lis = array();
1390 foreach ($items as $key => $string) {
1391 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1392 if (!empty($icons[$key])) { //test if the content has an assigned icon
1393 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1395 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1396 $item .= html_writer::end_tag('li');
1397 $lis[] = $item;
1398 $row = 1 - $row; // Flip even/odd.
1400 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1404 * Output all the blocks in a particular region.
1406 * @param string $region the name of a region on this page.
1407 * @return string the HTML to be output.
1409 public function blocks_for_region($region) {
1410 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1411 $blocks = $this->page->blocks->get_blocks_for_region($region);
1412 $lastblock = null;
1413 $zones = array();
1414 foreach ($blocks as $block) {
1415 $zones[] = $block->title;
1417 $output = '';
1419 foreach ($blockcontents as $bc) {
1420 if ($bc instanceof block_contents) {
1421 $output .= $this->block($bc, $region);
1422 $lastblock = $bc->title;
1423 } else if ($bc instanceof block_move_target) {
1424 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1425 } else {
1426 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1429 return $output;
1433 * Output a place where the block that is currently being moved can be dropped.
1435 * @param block_move_target $target with the necessary details.
1436 * @param array $zones array of areas where the block can be moved to
1437 * @param string $previous the block located before the area currently being rendered.
1438 * @param string $region the name of the region
1439 * @return string the HTML to be output.
1441 public function block_move_target($target, $zones, $previous, $region) {
1442 if ($previous == null) {
1443 if (empty($zones)) {
1444 // There are no zones, probably because there are no blocks.
1445 $regions = $this->page->theme->get_all_block_regions();
1446 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1447 } else {
1448 $position = get_string('moveblockbefore', 'block', $zones[0]);
1450 } else {
1451 $position = get_string('moveblockafter', 'block', $previous);
1453 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1457 * Renders a special html link with attached action
1459 * Theme developers: DO NOT OVERRIDE! Please override function
1460 * {@link core_renderer::render_action_link()} instead.
1462 * @param string|moodle_url $url
1463 * @param string $text HTML fragment
1464 * @param component_action $action
1465 * @param array $attributes associative array of html link attributes + disabled
1466 * @param pix_icon optional pix icon to render with the link
1467 * @return string HTML fragment
1469 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1470 if (!($url instanceof moodle_url)) {
1471 $url = new moodle_url($url);
1473 $link = new action_link($url, $text, $action, $attributes, $icon);
1475 return $this->render($link);
1479 * Renders an action_link object.
1481 * The provided link is renderer and the HTML returned. At the same time the
1482 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1484 * @param action_link $link
1485 * @return string HTML fragment
1487 protected function render_action_link(action_link $link) {
1488 global $CFG;
1490 $text = '';
1491 if ($link->icon) {
1492 $text .= $this->render($link->icon);
1495 if ($link->text instanceof renderable) {
1496 $text .= $this->render($link->text);
1497 } else {
1498 $text .= $link->text;
1501 // A disabled link is rendered as formatted text
1502 if (!empty($link->attributes['disabled'])) {
1503 // do not use div here due to nesting restriction in xhtml strict
1504 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1507 $attributes = $link->attributes;
1508 unset($link->attributes['disabled']);
1509 $attributes['href'] = $link->url;
1511 if ($link->actions) {
1512 if (empty($attributes['id'])) {
1513 $id = html_writer::random_id('action_link');
1514 $attributes['id'] = $id;
1515 } else {
1516 $id = $attributes['id'];
1518 foreach ($link->actions as $action) {
1519 $this->add_action_handler($action, $id);
1523 return html_writer::tag('a', $text, $attributes);
1528 * Renders an action_icon.
1530 * This function uses the {@link core_renderer::action_link()} method for the
1531 * most part. What it does different is prepare the icon as HTML and use it
1532 * as the link text.
1534 * Theme developers: If you want to change how action links and/or icons are rendered,
1535 * consider overriding function {@link core_renderer::render_action_link()} and
1536 * {@link core_renderer::render_pix_icon()}.
1538 * @param string|moodle_url $url A string URL or moodel_url
1539 * @param pix_icon $pixicon
1540 * @param component_action $action
1541 * @param array $attributes associative array of html link attributes + disabled
1542 * @param bool $linktext show title next to image in link
1543 * @return string HTML fragment
1545 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1546 if (!($url instanceof moodle_url)) {
1547 $url = new moodle_url($url);
1549 $attributes = (array)$attributes;
1551 if (empty($attributes['class'])) {
1552 // let ppl override the class via $options
1553 $attributes['class'] = 'action-icon';
1556 $icon = $this->render($pixicon);
1558 if ($linktext) {
1559 $text = $pixicon->attributes['alt'];
1560 } else {
1561 $text = '';
1564 return $this->action_link($url, $text.$icon, $action, $attributes);
1568 * Print a message along with button choices for Continue/Cancel
1570 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1572 * @param string $message The question to ask the user
1573 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1574 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1575 * @return string HTML fragment
1577 public function confirm($message, $continue, $cancel) {
1578 if ($continue instanceof single_button) {
1579 // ok
1580 } else if (is_string($continue)) {
1581 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1582 } else if ($continue instanceof moodle_url) {
1583 $continue = new single_button($continue, get_string('continue'), 'post');
1584 } else {
1585 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1588 if ($cancel instanceof single_button) {
1589 // ok
1590 } else if (is_string($cancel)) {
1591 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1592 } else if ($cancel instanceof moodle_url) {
1593 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1594 } else {
1595 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1598 $output = $this->box_start('generalbox', 'notice');
1599 $output .= html_writer::tag('p', $message);
1600 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1601 $output .= $this->box_end();
1602 return $output;
1606 * Returns a form with a single button.
1608 * Theme developers: DO NOT OVERRIDE! Please override function
1609 * {@link core_renderer::render_single_button()} instead.
1611 * @param string|moodle_url $url
1612 * @param string $label button text
1613 * @param string $method get or post submit method
1614 * @param array $options associative array {disabled, title, etc.}
1615 * @return string HTML fragment
1617 public function single_button($url, $label, $method='post', array $options=null) {
1618 if (!($url instanceof moodle_url)) {
1619 $url = new moodle_url($url);
1621 $button = new single_button($url, $label, $method);
1623 foreach ((array)$options as $key=>$value) {
1624 if (array_key_exists($key, $button)) {
1625 $button->$key = $value;
1629 return $this->render($button);
1633 * Renders a single button widget.
1635 * This will return HTML to display a form containing a single button.
1637 * @param single_button $button
1638 * @return string HTML fragment
1640 protected function render_single_button(single_button $button) {
1641 $attributes = array('type' => 'submit',
1642 'value' => $button->label,
1643 'disabled' => $button->disabled ? 'disabled' : null,
1644 'title' => $button->tooltip);
1646 if ($button->actions) {
1647 $id = html_writer::random_id('single_button');
1648 $attributes['id'] = $id;
1649 foreach ($button->actions as $action) {
1650 $this->add_action_handler($action, $id);
1654 // first the input element
1655 $output = html_writer::empty_tag('input', $attributes);
1657 // then hidden fields
1658 $params = $button->url->params();
1659 if ($button->method === 'post') {
1660 $params['sesskey'] = sesskey();
1662 foreach ($params as $var => $val) {
1663 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1666 // then div wrapper for xhtml strictness
1667 $output = html_writer::tag('div', $output);
1669 // now the form itself around it
1670 if ($button->method === 'get') {
1671 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1672 } else {
1673 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1675 if ($url === '') {
1676 $url = '#'; // there has to be always some action
1678 $attributes = array('method' => $button->method,
1679 'action' => $url,
1680 'id' => $button->formid);
1681 $output = html_writer::tag('form', $output, $attributes);
1683 // and finally one more wrapper with class
1684 return html_writer::tag('div', $output, array('class' => $button->class));
1688 * Returns a form with a single select widget.
1690 * Theme developers: DO NOT OVERRIDE! Please override function
1691 * {@link core_renderer::render_single_select()} instead.
1693 * @param moodle_url $url form action target, includes hidden fields
1694 * @param string $name name of selection field - the changing parameter in url
1695 * @param array $options list of options
1696 * @param string $selected selected element
1697 * @param array $nothing
1698 * @param string $formid
1699 * @return string HTML fragment
1701 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1702 if (!($url instanceof moodle_url)) {
1703 $url = new moodle_url($url);
1705 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1707 return $this->render($select);
1711 * Internal implementation of single_select rendering
1713 * @param single_select $select
1714 * @return string HTML fragment
1716 protected function render_single_select(single_select $select) {
1717 $select = clone($select);
1718 if (empty($select->formid)) {
1719 $select->formid = html_writer::random_id('single_select_f');
1722 $output = '';
1723 $params = $select->url->params();
1724 if ($select->method === 'post') {
1725 $params['sesskey'] = sesskey();
1727 foreach ($params as $name=>$value) {
1728 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1731 if (empty($select->attributes['id'])) {
1732 $select->attributes['id'] = html_writer::random_id('single_select');
1735 if ($select->disabled) {
1736 $select->attributes['disabled'] = 'disabled';
1739 if ($select->tooltip) {
1740 $select->attributes['title'] = $select->tooltip;
1743 $select->attributes['class'] = 'autosubmit';
1744 if ($select->class) {
1745 $select->attributes['class'] .= ' ' . $select->class;
1748 if ($select->label) {
1749 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1752 if ($select->helpicon instanceof help_icon) {
1753 $output .= $this->render($select->helpicon);
1755 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1757 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1758 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1760 $nothing = empty($select->nothing) ? false : key($select->nothing);
1761 $this->page->requires->yui_module('moodle-core-formautosubmit',
1762 'M.core.init_formautosubmit',
1763 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1766 // then div wrapper for xhtml strictness
1767 $output = html_writer::tag('div', $output);
1769 // now the form itself around it
1770 if ($select->method === 'get') {
1771 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1772 } else {
1773 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1775 $formattributes = array('method' => $select->method,
1776 'action' => $url,
1777 'id' => $select->formid);
1778 $output = html_writer::tag('form', $output, $formattributes);
1780 // and finally one more wrapper with class
1781 return html_writer::tag('div', $output, array('class' => $select->class));
1785 * Returns a form with a url select widget.
1787 * Theme developers: DO NOT OVERRIDE! Please override function
1788 * {@link core_renderer::render_url_select()} instead.
1790 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1791 * @param string $selected selected element
1792 * @param array $nothing
1793 * @param string $formid
1794 * @return string HTML fragment
1796 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1797 $select = new url_select($urls, $selected, $nothing, $formid);
1798 return $this->render($select);
1802 * Internal implementation of url_select rendering
1804 * @param url_select $select
1805 * @return string HTML fragment
1807 protected function render_url_select(url_select $select) {
1808 global $CFG;
1810 $select = clone($select);
1811 if (empty($select->formid)) {
1812 $select->formid = html_writer::random_id('url_select_f');
1815 if (empty($select->attributes['id'])) {
1816 $select->attributes['id'] = html_writer::random_id('url_select');
1819 if ($select->disabled) {
1820 $select->attributes['disabled'] = 'disabled';
1823 if ($select->tooltip) {
1824 $select->attributes['title'] = $select->tooltip;
1827 $output = '';
1829 if ($select->label) {
1830 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1833 $classes = array();
1834 if (!$select->showbutton) {
1835 $classes[] = 'autosubmit';
1837 if ($select->class) {
1838 $classes[] = $select->class;
1840 if (count($classes)) {
1841 $select->attributes['class'] = implode(' ', $classes);
1844 if ($select->helpicon instanceof help_icon) {
1845 $output .= $this->render($select->helpicon);
1848 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1849 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1850 $urls = array();
1851 foreach ($select->urls as $k=>$v) {
1852 if (is_array($v)) {
1853 // optgroup structure
1854 foreach ($v as $optgrouptitle => $optgroupoptions) {
1855 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1856 if (empty($optionurl)) {
1857 $safeoptionurl = '';
1858 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1859 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1860 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1861 } else if (strpos($optionurl, '/') !== 0) {
1862 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1863 continue;
1864 } else {
1865 $safeoptionurl = $optionurl;
1867 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1870 } else {
1871 // plain list structure
1872 if (empty($k)) {
1873 // nothing selected option
1874 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1875 $k = str_replace($CFG->wwwroot, '', $k);
1876 } else if (strpos($k, '/') !== 0) {
1877 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1878 continue;
1880 $urls[$k] = $v;
1883 $selected = $select->selected;
1884 if (!empty($selected)) {
1885 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1886 $selected = str_replace($CFG->wwwroot, '', $selected);
1887 } else if (strpos($selected, '/') !== 0) {
1888 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1892 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1893 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1895 if (!$select->showbutton) {
1896 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1897 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1898 $nothing = empty($select->nothing) ? false : key($select->nothing);
1899 $this->page->requires->yui_module('moodle-core-formautosubmit',
1900 'M.core.init_formautosubmit',
1901 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1903 } else {
1904 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1907 // then div wrapper for xhtml strictness
1908 $output = html_writer::tag('div', $output);
1910 // now the form itself around it
1911 $formattributes = array('method' => 'post',
1912 'action' => new moodle_url('/course/jumpto.php'),
1913 'id' => $select->formid);
1914 $output = html_writer::tag('form', $output, $formattributes);
1916 // and finally one more wrapper with class
1917 return html_writer::tag('div', $output, array('class' => $select->class));
1921 * Returns a string containing a link to the user documentation.
1922 * Also contains an icon by default. Shown to teachers and admin only.
1924 * @param string $path The page link after doc root and language, no leading slash.
1925 * @param string $text The text to be displayed for the link
1926 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
1927 * @return string
1929 public function doc_link($path, $text = '', $forcepopup = false) {
1930 global $CFG;
1932 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
1934 $url = new moodle_url(get_docs_url($path));
1936 $attributes = array('href'=>$url);
1937 if (!empty($CFG->doctonewwindow) || $forcepopup) {
1938 $attributes['class'] = 'helplinkpopup';
1941 return html_writer::tag('a', $icon.$text, $attributes);
1945 * Return HTML for a pix_icon.
1947 * Theme developers: DO NOT OVERRIDE! Please override function
1948 * {@link core_renderer::render_pix_icon()} instead.
1950 * @param string $pix short pix name
1951 * @param string $alt mandatory alt attribute
1952 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1953 * @param array $attributes htm lattributes
1954 * @return string HTML fragment
1956 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1957 $icon = new pix_icon($pix, $alt, $component, $attributes);
1958 return $this->render($icon);
1962 * Renders a pix_icon widget and returns the HTML to display it.
1964 * @param pix_icon $icon
1965 * @return string HTML fragment
1967 protected function render_pix_icon(pix_icon $icon) {
1968 $attributes = $icon->attributes;
1969 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
1970 return html_writer::empty_tag('img', $attributes);
1974 * Return HTML to display an emoticon icon.
1976 * @param pix_emoticon $emoticon
1977 * @return string HTML fragment
1979 protected function render_pix_emoticon(pix_emoticon $emoticon) {
1980 $attributes = $emoticon->attributes;
1981 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
1982 return html_writer::empty_tag('img', $attributes);
1986 * Produces the html that represents this rating in the UI
1988 * @param rating $rating the page object on which this rating will appear
1989 * @return string
1991 function render_rating(rating $rating) {
1992 global $CFG, $USER;
1994 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
1995 return null;//ratings are turned off
1998 $ratingmanager = new rating_manager();
1999 // Initialise the JavaScript so ratings can be done by AJAX.
2000 $ratingmanager->initialise_rating_javascript($this->page);
2002 $strrate = get_string("rate", "rating");
2003 $ratinghtml = ''; //the string we'll return
2005 // permissions check - can they view the aggregate?
2006 if ($rating->user_can_view_aggregate()) {
2008 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2009 $aggregatestr = $rating->get_aggregate_string();
2011 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2012 if ($rating->count > 0) {
2013 $countstr = "({$rating->count})";
2014 } else {
2015 $countstr = '-';
2017 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2019 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2020 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2022 $nonpopuplink = $rating->get_view_ratings_url();
2023 $popuplink = $rating->get_view_ratings_url(true);
2025 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2026 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2027 } else {
2028 $ratinghtml .= $aggregatehtml;
2032 $formstart = null;
2033 // if the item doesn't belong to the current user, the user has permission to rate
2034 // and we're within the assessable period
2035 if ($rating->user_can_rate()) {
2037 $rateurl = $rating->get_rate_url();
2038 $inputs = $rateurl->params();
2040 //start the rating form
2041 $formattrs = array(
2042 'id' => "postrating{$rating->itemid}",
2043 'class' => 'postratingform',
2044 'method' => 'post',
2045 'action' => $rateurl->out_omit_querystring()
2047 $formstart = html_writer::start_tag('form', $formattrs);
2048 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2050 // add the hidden inputs
2051 foreach ($inputs as $name => $value) {
2052 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2053 $formstart .= html_writer::empty_tag('input', $attributes);
2056 if (empty($ratinghtml)) {
2057 $ratinghtml .= $strrate.': ';
2059 $ratinghtml = $formstart.$ratinghtml;
2061 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2062 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2063 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2064 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2066 //output submit button
2067 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2069 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2070 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2072 if (!$rating->settings->scale->isnumeric) {
2073 // If a global scale, try to find current course ID from the context
2074 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2075 $courseid = $coursecontext->instanceid;
2076 } else {
2077 $courseid = $rating->settings->scale->courseid;
2079 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2081 $ratinghtml .= html_writer::end_tag('span');
2082 $ratinghtml .= html_writer::end_tag('div');
2083 $ratinghtml .= html_writer::end_tag('form');
2086 return $ratinghtml;
2090 * Centered heading with attached help button (same title text)
2091 * and optional icon attached.
2093 * @param string $text A heading text
2094 * @param string $helpidentifier The keyword that defines a help page
2095 * @param string $component component name
2096 * @param string|moodle_url $icon
2097 * @param string $iconalt icon alt text
2098 * @param int $level The level of importance of the heading. Defaulting to 2
2099 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2100 * @return string HTML fragment
2102 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2103 $image = '';
2104 if ($icon) {
2105 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2108 $help = '';
2109 if ($helpidentifier) {
2110 $help = $this->help_icon($helpidentifier, $component);
2113 return $this->heading($image.$text.$help, $level, $classnames);
2117 * Returns HTML to display a help icon.
2119 * @deprecated since Moodle 2.0
2121 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2122 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2126 * Returns HTML to display a help icon.
2128 * Theme developers: DO NOT OVERRIDE! Please override function
2129 * {@link core_renderer::render_help_icon()} instead.
2131 * @param string $identifier The keyword that defines a help page
2132 * @param string $component component name
2133 * @param string|bool $linktext true means use $title as link text, string means link text value
2134 * @return string HTML fragment
2136 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2137 $icon = new help_icon($identifier, $component);
2138 $icon->diag_strings();
2139 if ($linktext === true) {
2140 $icon->linktext = get_string($icon->identifier, $icon->component);
2141 } else if (!empty($linktext)) {
2142 $icon->linktext = $linktext;
2144 return $this->render($icon);
2148 * Implementation of user image rendering.
2150 * @param help_icon $helpicon A help icon instance
2151 * @return string HTML fragment
2153 protected function render_help_icon(help_icon $helpicon) {
2154 global $CFG;
2156 // first get the help image icon
2157 $src = $this->pix_url('help');
2159 $title = get_string($helpicon->identifier, $helpicon->component);
2161 if (empty($helpicon->linktext)) {
2162 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
2163 } else {
2164 $alt = get_string('helpwiththis');
2167 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
2168 $output = html_writer::empty_tag('img', $attributes);
2170 // add the link text if given
2171 if (!empty($helpicon->linktext)) {
2172 // the spacing has to be done through CSS
2173 $output .= $helpicon->linktext;
2176 // now create the link around it - we need https on loginhttps pages
2177 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
2179 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
2180 $title = get_string('helpprefix2', '', trim($title, ". \t"));
2182 $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true', 'target'=>'_blank');
2183 $output = html_writer::tag('a', $output, $attributes);
2185 // and finally span
2186 return html_writer::tag('span', $output, array('class' => 'helptooltip'));
2190 * Returns HTML to display a scale help icon.
2192 * @param int $courseid
2193 * @param stdClass $scale instance
2194 * @return string HTML fragment
2196 public function help_icon_scale($courseid, stdClass $scale) {
2197 global $CFG;
2199 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2201 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2203 $scaleid = abs($scale->id);
2205 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2206 $action = new popup_action('click', $link, 'ratingscale');
2208 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2212 * Creates and returns a spacer image with optional line break.
2214 * @param array $attributes Any HTML attributes to add to the spaced.
2215 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2216 * laxy do it with CSS which is a much better solution.
2217 * @return string HTML fragment
2219 public function spacer(array $attributes = null, $br = false) {
2220 $attributes = (array)$attributes;
2221 if (empty($attributes['width'])) {
2222 $attributes['width'] = 1;
2224 if (empty($attributes['height'])) {
2225 $attributes['height'] = 1;
2227 $attributes['class'] = 'spacer';
2229 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2231 if (!empty($br)) {
2232 $output .= '<br />';
2235 return $output;
2239 * Returns HTML to display the specified user's avatar.
2241 * User avatar may be obtained in two ways:
2242 * <pre>
2243 * // Option 1: (shortcut for simple cases, preferred way)
2244 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2245 * $OUTPUT->user_picture($user, array('popup'=>true));
2247 * // Option 2:
2248 * $userpic = new user_picture($user);
2249 * // Set properties of $userpic
2250 * $userpic->popup = true;
2251 * $OUTPUT->render($userpic);
2252 * </pre>
2254 * Theme developers: DO NOT OVERRIDE! Please override function
2255 * {@link core_renderer::render_user_picture()} instead.
2257 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2258 * If any of these are missing, the database is queried. Avoid this
2259 * if at all possible, particularly for reports. It is very bad for performance.
2260 * @param array $options associative array with user picture options, used only if not a user_picture object,
2261 * options are:
2262 * - courseid=$this->page->course->id (course id of user profile in link)
2263 * - size=35 (size of image)
2264 * - link=true (make image clickable - the link leads to user profile)
2265 * - popup=false (open in popup)
2266 * - alttext=true (add image alt attribute)
2267 * - class = image class attribute (default 'userpicture')
2268 * @return string HTML fragment
2270 public function user_picture(stdClass $user, array $options = null) {
2271 $userpicture = new user_picture($user);
2272 foreach ((array)$options as $key=>$value) {
2273 if (array_key_exists($key, $userpicture)) {
2274 $userpicture->$key = $value;
2277 return $this->render($userpicture);
2281 * Internal implementation of user image rendering.
2283 * @param user_picture $userpicture
2284 * @return string
2286 protected function render_user_picture(user_picture $userpicture) {
2287 global $CFG, $DB;
2289 $user = $userpicture->user;
2291 if ($userpicture->alttext) {
2292 if (!empty($user->imagealt)) {
2293 $alt = $user->imagealt;
2294 } else {
2295 $alt = get_string('pictureof', '', fullname($user));
2297 } else {
2298 $alt = '';
2301 if (empty($userpicture->size)) {
2302 $size = 35;
2303 } else if ($userpicture->size === true or $userpicture->size == 1) {
2304 $size = 100;
2305 } else {
2306 $size = $userpicture->size;
2309 $class = $userpicture->class;
2311 if ($user->picture == 0) {
2312 $class .= ' defaultuserpic';
2315 $src = $userpicture->get_url($this->page, $this);
2317 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2319 // get the image html output fisrt
2320 $output = html_writer::empty_tag('img', $attributes);
2322 // then wrap it in link if needed
2323 if (!$userpicture->link) {
2324 return $output;
2327 if (empty($userpicture->courseid)) {
2328 $courseid = $this->page->course->id;
2329 } else {
2330 $courseid = $userpicture->courseid;
2333 if ($courseid == SITEID) {
2334 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2335 } else {
2336 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2339 $attributes = array('href'=>$url);
2341 if ($userpicture->popup) {
2342 $id = html_writer::random_id('userpicture');
2343 $attributes['id'] = $id;
2344 $this->add_action_handler(new popup_action('click', $url), $id);
2347 return html_writer::tag('a', $output, $attributes);
2351 * Internal implementation of file tree viewer items rendering.
2353 * @param array $dir
2354 * @return string
2356 public function htmllize_file_tree($dir) {
2357 if (empty($dir['subdirs']) and empty($dir['files'])) {
2358 return '';
2360 $result = '<ul>';
2361 foreach ($dir['subdirs'] as $subdir) {
2362 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2364 foreach ($dir['files'] as $file) {
2365 $filename = $file->get_filename();
2366 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2368 $result .= '</ul>';
2370 return $result;
2374 * Returns HTML to display the file picker
2376 * <pre>
2377 * $OUTPUT->file_picker($options);
2378 * </pre>
2380 * Theme developers: DO NOT OVERRIDE! Please override function
2381 * {@link core_renderer::render_file_picker()} instead.
2383 * @param array $options associative array with file manager options
2384 * options are:
2385 * maxbytes=>-1,
2386 * itemid=>0,
2387 * client_id=>uniqid(),
2388 * acepted_types=>'*',
2389 * return_types=>FILE_INTERNAL,
2390 * context=>$PAGE->context
2391 * @return string HTML fragment
2393 public function file_picker($options) {
2394 $fp = new file_picker($options);
2395 return $this->render($fp);
2399 * Internal implementation of file picker rendering.
2401 * @param file_picker $fp
2402 * @return string
2404 public function render_file_picker(file_picker $fp) {
2405 global $CFG, $OUTPUT, $USER;
2406 $options = $fp->options;
2407 $client_id = $options->client_id;
2408 $strsaved = get_string('filesaved', 'repository');
2409 $straddfile = get_string('openpicker', 'repository');
2410 $strloading = get_string('loading', 'repository');
2411 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2412 $strdroptoupload = get_string('droptoupload', 'moodle');
2413 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2415 $currentfile = $options->currentfile;
2416 if (empty($currentfile)) {
2417 $currentfile = '';
2418 } else {
2419 $currentfile .= ' - ';
2421 if ($options->maxbytes) {
2422 $size = $options->maxbytes;
2423 } else {
2424 $size = get_max_upload_file_size();
2426 if ($size == -1) {
2427 $maxsize = '';
2428 } else {
2429 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2431 if ($options->buttonname) {
2432 $buttonname = ' name="' . $options->buttonname . '"';
2433 } else {
2434 $buttonname = '';
2436 $html = <<<EOD
2437 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2438 $icon_progress
2439 </div>
2440 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2441 <div>
2442 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2443 <span> $maxsize </span>
2444 </div>
2445 EOD;
2446 if ($options->env != 'url') {
2447 $html .= <<<EOD
2448 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2449 <div class="filepicker-filename">
2450 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2451 <div class="dndupload-progressbars"></div>
2452 </div>
2453 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2454 </div>
2455 EOD;
2457 $html .= '</div>';
2458 return $html;
2462 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2464 * @param string $cmid the course_module id.
2465 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2466 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2468 public function update_module_button($cmid, $modulename) {
2469 global $CFG;
2470 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2471 $modulename = get_string('modulename', $modulename);
2472 $string = get_string('updatethis', '', $modulename);
2473 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2474 return $this->single_button($url, $string);
2475 } else {
2476 return '';
2481 * Returns HTML to display a "Turn editing on/off" button in a form.
2483 * @param moodle_url $url The URL + params to send through when clicking the button
2484 * @return string HTML the button
2486 public function edit_button(moodle_url $url) {
2488 $url->param('sesskey', sesskey());
2489 if ($this->page->user_is_editing()) {
2490 $url->param('edit', 'off');
2491 $editstring = get_string('turneditingoff');
2492 } else {
2493 $url->param('edit', 'on');
2494 $editstring = get_string('turneditingon');
2497 return $this->single_button($url, $editstring);
2501 * Returns HTML to display a simple button to close a window
2503 * @param string $text The lang string for the button's label (already output from get_string())
2504 * @return string html fragment
2506 public function close_window_button($text='') {
2507 if (empty($text)) {
2508 $text = get_string('closewindow');
2510 $button = new single_button(new moodle_url('#'), $text, 'get');
2511 $button->add_action(new component_action('click', 'close_window'));
2513 return $this->container($this->render($button), 'closewindow');
2517 * Output an error message. By default wraps the error message in <span class="error">.
2518 * If the error message is blank, nothing is output.
2520 * @param string $message the error message.
2521 * @return string the HTML to output.
2523 public function error_text($message) {
2524 if (empty($message)) {
2525 return '';
2527 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2528 return html_writer::tag('span', $message, array('class' => 'error'));
2532 * Do not call this function directly.
2534 * To terminate the current script with a fatal error, call the {@link print_error}
2535 * function, or throw an exception. Doing either of those things will then call this
2536 * function to display the error, before terminating the execution.
2538 * @param string $message The message to output
2539 * @param string $moreinfourl URL where more info can be found about the error
2540 * @param string $link Link for the Continue button
2541 * @param array $backtrace The execution backtrace
2542 * @param string $debuginfo Debugging information
2543 * @return string the HTML to output.
2545 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2546 global $CFG;
2548 $output = '';
2549 $obbuffer = '';
2551 if ($this->has_started()) {
2552 // we can not always recover properly here, we have problems with output buffering,
2553 // html tables, etc.
2554 $output .= $this->opencontainers->pop_all_but_last();
2556 } else {
2557 // It is really bad if library code throws exception when output buffering is on,
2558 // because the buffered text would be printed before our start of page.
2559 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2560 error_reporting(0); // disable notices from gzip compression, etc.
2561 while (ob_get_level() > 0) {
2562 $buff = ob_get_clean();
2563 if ($buff === false) {
2564 break;
2566 $obbuffer .= $buff;
2568 error_reporting($CFG->debug);
2570 // Output not yet started.
2571 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2572 if (empty($_SERVER['HTTP_RANGE'])) {
2573 @header($protocol . ' 404 Not Found');
2574 } else {
2575 // Must stop byteserving attempts somehow,
2576 // this is weird but Chrome PDF viewer can be stopped only with 407!
2577 @header($protocol . ' 407 Proxy Authentication Required');
2580 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2581 $this->page->set_url('/'); // no url
2582 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2583 $this->page->set_title(get_string('error'));
2584 $this->page->set_heading($this->page->course->fullname);
2585 $output .= $this->header();
2588 $message = '<p class="errormessage">' . $message . '</p>'.
2589 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2590 get_string('moreinformation') . '</a></p>';
2591 if (empty($CFG->rolesactive)) {
2592 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2593 //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.
2595 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
2597 if ($CFG->debugdeveloper) {
2598 if (!empty($debuginfo)) {
2599 $debuginfo = s($debuginfo); // removes all nasty JS
2600 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2601 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2603 if (!empty($backtrace)) {
2604 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2606 if ($obbuffer !== '' ) {
2607 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2611 if (empty($CFG->rolesactive)) {
2612 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2613 } else if (!empty($link)) {
2614 $output .= $this->continue_button($link);
2617 $output .= $this->footer();
2619 // Padding to encourage IE to display our error page, rather than its own.
2620 $output .= str_repeat(' ', 512);
2622 return $output;
2626 * Output a notification (that is, a status message about something that has
2627 * just happened).
2629 * @param string $message the message to print out
2630 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2631 * @return string the HTML to output.
2633 public function notification($message, $classes = 'notifyproblem') {
2634 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2638 * Returns HTML to display a continue button that goes to a particular URL.
2640 * @param string|moodle_url $url The url the button goes to.
2641 * @return string the HTML to output.
2643 public function continue_button($url) {
2644 if (!($url instanceof moodle_url)) {
2645 $url = new moodle_url($url);
2647 $button = new single_button($url, get_string('continue'), 'get');
2648 $button->class = 'continuebutton';
2650 return $this->render($button);
2654 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2656 * Theme developers: DO NOT OVERRIDE! Please override function
2657 * {@link core_renderer::render_paging_bar()} instead.
2659 * @param int $totalcount The total number of entries available to be paged through
2660 * @param int $page The page you are currently viewing
2661 * @param int $perpage The number of entries that should be shown per page
2662 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2663 * @param string $pagevar name of page parameter that holds the page number
2664 * @return string the HTML to output.
2666 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2667 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2668 return $this->render($pb);
2672 * Internal implementation of paging bar rendering.
2674 * @param paging_bar $pagingbar
2675 * @return string
2677 protected function render_paging_bar(paging_bar $pagingbar) {
2678 $output = '';
2679 $pagingbar = clone($pagingbar);
2680 $pagingbar->prepare($this, $this->page, $this->target);
2682 if ($pagingbar->totalcount > $pagingbar->perpage) {
2683 $output .= get_string('page') . ':';
2685 if (!empty($pagingbar->previouslink)) {
2686 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
2689 if (!empty($pagingbar->firstlink)) {
2690 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
2693 foreach ($pagingbar->pagelinks as $link) {
2694 $output .= "&#160;&#160;$link";
2697 if (!empty($pagingbar->lastlink)) {
2698 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
2701 if (!empty($pagingbar->nextlink)) {
2702 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
2706 return html_writer::tag('div', $output, array('class' => 'paging'));
2710 * Output the place a skip link goes to.
2712 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2713 * @return string the HTML to output.
2715 public function skip_link_target($id = null) {
2716 return html_writer::tag('span', '', array('id' => $id));
2720 * Outputs a heading
2722 * @param string $text The text of the heading
2723 * @param int $level The level of importance of the heading. Defaulting to 2
2724 * @param string $classes A space-separated list of CSS classes. Defaulting to null
2725 * @param string $id An optional ID
2726 * @return string the HTML to output.
2728 public function heading($text, $level = 2, $classes = null, $id = null) {
2729 $level = (integer) $level;
2730 if ($level < 1 or $level > 6) {
2731 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2733 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2737 * Outputs a box.
2739 * @param string $contents The contents of the box
2740 * @param string $classes A space-separated list of CSS classes
2741 * @param string $id An optional ID
2742 * @param array $attributes An array of other attributes to give the box.
2743 * @return string the HTML to output.
2745 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
2746 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
2750 * Outputs the opening section of a box.
2752 * @param string $classes A space-separated list of CSS classes
2753 * @param string $id An optional ID
2754 * @param array $attributes An array of other attributes to give the box.
2755 * @return string the HTML to output.
2757 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
2758 $this->opencontainers->push('box', html_writer::end_tag('div'));
2759 $attributes['id'] = $id;
2760 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
2761 return html_writer::start_tag('div', $attributes);
2765 * Outputs the closing section of a box.
2767 * @return string the HTML to output.
2769 public function box_end() {
2770 return $this->opencontainers->pop('box');
2774 * Outputs a container.
2776 * @param string $contents The contents of the box
2777 * @param string $classes A space-separated list of CSS classes
2778 * @param string $id An optional ID
2779 * @return string the HTML to output.
2781 public function container($contents, $classes = null, $id = null) {
2782 return $this->container_start($classes, $id) . $contents . $this->container_end();
2786 * Outputs the opening section of a container.
2788 * @param string $classes A space-separated list of CSS classes
2789 * @param string $id An optional ID
2790 * @return string the HTML to output.
2792 public function container_start($classes = null, $id = null) {
2793 $this->opencontainers->push('container', html_writer::end_tag('div'));
2794 return html_writer::start_tag('div', array('id' => $id,
2795 'class' => renderer_base::prepare_classes($classes)));
2799 * Outputs the closing section of a container.
2801 * @return string the HTML to output.
2803 public function container_end() {
2804 return $this->opencontainers->pop('container');
2808 * Make nested HTML lists out of the items
2810 * The resulting list will look something like this:
2812 * <pre>
2813 * <<ul>>
2814 * <<li>><div class='tree_item parent'>(item contents)</div>
2815 * <<ul>
2816 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2817 * <</ul>>
2818 * <</li>>
2819 * <</ul>>
2820 * </pre>
2822 * @param array $items
2823 * @param array $attrs html attributes passed to the top ofs the list
2824 * @return string HTML
2826 public function tree_block_contents($items, $attrs = array()) {
2827 // exit if empty, we don't want an empty ul element
2828 if (empty($items)) {
2829 return '';
2831 // array of nested li elements
2832 $lis = array();
2833 foreach ($items as $item) {
2834 // this applies to the li item which contains all child lists too
2835 $content = $item->content($this);
2836 $liclasses = array($item->get_css_type());
2837 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2838 $liclasses[] = 'collapsed';
2840 if ($item->isactive === true) {
2841 $liclasses[] = 'current_branch';
2843 $liattr = array('class'=>join(' ',$liclasses));
2844 // class attribute on the div item which only contains the item content
2845 $divclasses = array('tree_item');
2846 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2847 $divclasses[] = 'branch';
2848 } else {
2849 $divclasses[] = 'leaf';
2851 if (!empty($item->classes) && count($item->classes)>0) {
2852 $divclasses[] = join(' ', $item->classes);
2854 $divattr = array('class'=>join(' ', $divclasses));
2855 if (!empty($item->id)) {
2856 $divattr['id'] = $item->id;
2858 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2859 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2860 $content = html_writer::empty_tag('hr') . $content;
2862 $content = html_writer::tag('li', $content, $liattr);
2863 $lis[] = $content;
2865 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2869 * Return the navbar content so that it can be echoed out by the layout
2871 * @return string XHTML navbar
2873 public function navbar() {
2874 $items = $this->page->navbar->get_items();
2875 $itemcount = count($items);
2876 if ($itemcount === 0) {
2877 return '';
2880 $htmlblocks = array();
2881 // Iterate the navarray and display each node
2882 $separator = get_separator();
2883 for ($i=0;$i < $itemcount;$i++) {
2884 $item = $items[$i];
2885 $item->hideicon = true;
2886 if ($i===0) {
2887 $content = html_writer::tag('li', $this->render($item));
2888 } else {
2889 $content = html_writer::tag('li', $separator.$this->render($item));
2891 $htmlblocks[] = $content;
2894 //accessibility: heading for navbar list (MDL-20446)
2895 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
2896 $navbarcontent .= html_writer::tag('nav', html_writer::tag('ul', join('', $htmlblocks)));
2897 // XHTML
2898 return $navbarcontent;
2902 * Renders a navigation node object.
2904 * @param navigation_node $item The navigation node to render.
2905 * @return string HTML fragment
2907 protected function render_navigation_node(navigation_node $item) {
2908 $content = $item->get_content();
2909 $title = $item->get_title();
2910 if ($item->icon instanceof renderable && !$item->hideicon) {
2911 $icon = $this->render($item->icon);
2912 $content = $icon.$content; // use CSS for spacing of icons
2914 if ($item->helpbutton !== null) {
2915 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
2917 if ($content === '') {
2918 return '';
2920 if ($item->action instanceof action_link) {
2921 $link = $item->action;
2922 if ($item->hidden) {
2923 $link->add_class('dimmed');
2925 if (!empty($content)) {
2926 // Providing there is content we will use that for the link content.
2927 $link->text = $content;
2929 $content = $this->render($link);
2930 } else if ($item->action instanceof moodle_url) {
2931 $attributes = array();
2932 if ($title !== '') {
2933 $attributes['title'] = $title;
2935 if ($item->hidden) {
2936 $attributes['class'] = 'dimmed_text';
2938 $content = html_writer::link($item->action, $content, $attributes);
2940 } else if (is_string($item->action) || empty($item->action)) {
2941 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
2942 if ($title !== '') {
2943 $attributes['title'] = $title;
2945 if ($item->hidden) {
2946 $attributes['class'] = 'dimmed_text';
2948 $content = html_writer::tag('span', $content, $attributes);
2950 return $content;
2954 * Accessibility: Right arrow-like character is
2955 * used in the breadcrumb trail, course navigation menu
2956 * (previous/next activity), calendar, and search forum block.
2957 * If the theme does not set characters, appropriate defaults
2958 * are set automatically. Please DO NOT
2959 * use &lt; &gt; &raquo; - these are confusing for blind users.
2961 * @return string
2963 public function rarrow() {
2964 return $this->page->theme->rarrow;
2968 * Accessibility: Left arrow-like character is
2969 * used in the breadcrumb trail, course navigation menu
2970 * (previous/next activity), calendar, and search forum block.
2971 * If the theme does not set characters, appropriate defaults
2972 * are set automatically. Please DO NOT
2973 * use &lt; &gt; &raquo; - these are confusing for blind users.
2975 * @return string
2977 public function larrow() {
2978 return $this->page->theme->larrow;
2982 * Returns the custom menu if one has been set
2984 * A custom menu can be configured by browsing to
2985 * Settings: Administration > Appearance > Themes > Theme settings
2986 * and then configuring the custommenu config setting as described.
2988 * Theme developers: DO NOT OVERRIDE! Please override function
2989 * {@link core_renderer::render_custom_menu()} instead.
2991 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
2992 * @return string
2994 public function custom_menu($custommenuitems = '') {
2995 global $CFG;
2996 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
2997 $custommenuitems = $CFG->custommenuitems;
2999 if (empty($custommenuitems)) {
3000 return '';
3002 $custommenu = new custom_menu($custommenuitems, current_language());
3003 return $this->render($custommenu);
3007 * Renders a custom menu object (located in outputcomponents.php)
3009 * The custom menu this method produces makes use of the YUI3 menunav widget
3010 * and requires very specific html elements and classes.
3012 * @staticvar int $menucount
3013 * @param custom_menu $menu
3014 * @return string
3016 protected function render_custom_menu(custom_menu $menu) {
3017 static $menucount = 0;
3018 // If the menu has no children return an empty string
3019 if (!$menu->has_children()) {
3020 return '';
3022 // Increment the menu count. This is used for ID's that get worked with
3023 // in JavaScript as is essential
3024 $menucount++;
3025 // Initialise this custom menu (the custom menu object is contained in javascript-static
3026 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
3027 $jscode = "(function(){{$jscode}})";
3028 $this->page->requires->yui_module('node-menunav', $jscode);
3029 // Build the root nodes as required by YUI
3030 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
3031 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3032 $content .= html_writer::start_tag('ul');
3033 // Render each child
3034 foreach ($menu->get_children() as $item) {
3035 $content .= $this->render_custom_menu_item($item);
3037 // Close the open tags
3038 $content .= html_writer::end_tag('ul');
3039 $content .= html_writer::end_tag('div');
3040 $content .= html_writer::end_tag('div');
3041 // Return the custom menu
3042 return $content;
3046 * Renders a custom menu node as part of a submenu
3048 * The custom menu this method produces makes use of the YUI3 menunav widget
3049 * and requires very specific html elements and classes.
3051 * @see core:renderer::render_custom_menu()
3053 * @staticvar int $submenucount
3054 * @param custom_menu_item $menunode
3055 * @return string
3057 protected function render_custom_menu_item(custom_menu_item $menunode) {
3058 // Required to ensure we get unique trackable id's
3059 static $submenucount = 0;
3060 if ($menunode->has_children()) {
3061 // If the child has menus render it as a sub menu
3062 $submenucount++;
3063 $content = html_writer::start_tag('li');
3064 if ($menunode->get_url() !== null) {
3065 $url = $menunode->get_url();
3066 } else {
3067 $url = '#cm_submenu_'.$submenucount;
3069 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3070 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3071 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3072 $content .= html_writer::start_tag('ul');
3073 foreach ($menunode->get_children() as $menunode) {
3074 $content .= $this->render_custom_menu_item($menunode);
3076 $content .= html_writer::end_tag('ul');
3077 $content .= html_writer::end_tag('div');
3078 $content .= html_writer::end_tag('div');
3079 $content .= html_writer::end_tag('li');
3080 } else {
3081 // The node doesn't have children so produce a final menuitem
3082 $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
3083 if ($menunode->get_url() !== null) {
3084 $url = $menunode->get_url();
3085 } else {
3086 $url = '#';
3088 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
3089 $content .= html_writer::end_tag('li');
3091 // Return the sub menu
3092 return $content;
3096 * Renders theme links for switching between default and other themes.
3098 * @return string
3100 protected function theme_switch_links() {
3102 $actualdevice = core_useragent::get_device_type();
3103 $currentdevice = $this->page->devicetypeinuse;
3104 $switched = ($actualdevice != $currentdevice);
3106 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3107 // The user is using the a default device and hasn't switched so don't shown the switch
3108 // device links.
3109 return '';
3112 if ($switched) {
3113 $linktext = get_string('switchdevicerecommended');
3114 $devicetype = $actualdevice;
3115 } else {
3116 $linktext = get_string('switchdevicedefault');
3117 $devicetype = 'default';
3119 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3121 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3122 $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3123 $content .= html_writer::end_tag('div');
3125 return $content;
3129 * Renders tabs
3131 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3133 * Theme developers: In order to change how tabs are displayed please override functions
3134 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3136 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3137 * @param string|null $selected which tab to mark as selected, all parent tabs will
3138 * automatically be marked as activated
3139 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3140 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3141 * @return string
3143 public final function tabtree($tabs, $selected = null, $inactive = null) {
3144 return $this->render(new tabtree($tabs, $selected, $inactive));
3148 * Renders tabtree
3150 * @param tabtree $tabtree
3151 * @return string
3153 protected function render_tabtree(tabtree $tabtree) {
3154 if (empty($tabtree->subtree)) {
3155 return '';
3157 $str = '';
3158 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
3159 $str .= $this->render_tabobject($tabtree);
3160 $str .= html_writer::end_tag('div').
3161 html_writer::tag('div', ' ', array('class' => 'clearer'));
3162 return $str;
3166 * Renders tabobject (part of tabtree)
3168 * This function is called from {@link core_renderer::render_tabtree()}
3169 * and also it calls itself when printing the $tabobject subtree recursively.
3171 * Property $tabobject->level indicates the number of row of tabs.
3173 * @param tabobject $tabobject
3174 * @return string HTML fragment
3176 protected function render_tabobject(tabobject $tabobject) {
3177 $str = '';
3179 // Print name of the current tab.
3180 if ($tabobject instanceof tabtree) {
3181 // No name for tabtree root.
3182 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3183 // Tab name without a link. The <a> tag is used for styling.
3184 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3185 } else {
3186 // Tab name with a link.
3187 if (!($tabobject->link instanceof moodle_url)) {
3188 // backward compartibility when link was passed as quoted string
3189 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3190 } else {
3191 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3195 if (empty($tabobject->subtree)) {
3196 if ($tabobject->selected) {
3197 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3199 return $str;
3202 // Print subtree
3203 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3204 $cnt = 0;
3205 foreach ($tabobject->subtree as $tab) {
3206 $liclass = '';
3207 if (!$cnt) {
3208 $liclass .= ' first';
3210 if ($cnt == count($tabobject->subtree) - 1) {
3211 $liclass .= ' last';
3213 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3214 $liclass .= ' onerow';
3217 if ($tab->selected) {
3218 $liclass .= ' here selected';
3219 } else if ($tab->activated) {
3220 $liclass .= ' here active';
3223 // This will recursively call function render_tabobject() for each item in subtree
3224 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3225 $cnt++;
3227 $str .= html_writer::end_tag('ul');
3229 return $str;
3233 * Get the HTML for blocks in the given region.
3235 * @since Moodle 2.5.1 2.6
3236 * @param string $region The region to get HTML for.
3237 * @return string HTML.
3239 public function blocks($region, $classes = array(), $tag = 'aside') {
3240 $displayregion = $this->page->apply_theme_region_manipulations($region);
3241 $classes = (array)$classes;
3242 $classes[] = 'block-region';
3243 $attributes = array(
3244 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3245 'class' => join(' ', $classes),
3246 'data-blockregion' => $displayregion,
3247 'data-droptarget' => '1'
3249 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3250 $content = $this->blocks_for_region($displayregion);
3251 } else {
3252 $content = '';
3254 return html_writer::tag($tag, $content, $attributes);
3258 * Renders a custom block region.
3260 * Use this method if you want to add an additional block region to the content of the page.
3261 * Please note this should only be used in special situations.
3262 * We want to leave the theme is control where ever possible!
3264 * This method must use the same method that the theme uses within its layout file.
3265 * As such it asks the theme what method it is using.
3266 * It can be one of two values, blocks or blocks_for_region (deprecated).
3268 * @param string $regionname The name of the custom region to add.
3269 * @return string HTML for the block region.
3271 public function custom_block_region($regionname) {
3272 if ($this->page->theme->get_block_render_method() === 'blocks') {
3273 return $this->blocks($regionname);
3274 } else {
3275 return $this->blocks_for_region($regionname);
3280 * Returns the CSS classes to apply to the body tag.
3282 * @since Moodle 2.5.1 2.6
3283 * @param array $additionalclasses Any additional classes to apply.
3284 * @return string
3286 public function body_css_classes(array $additionalclasses = array()) {
3287 // Add a class for each block region on the page.
3288 // We use the block manager here because the theme object makes get_string calls.
3289 foreach ($this->page->blocks->get_regions() as $region) {
3290 $additionalclasses[] = 'has-region-'.$region;
3291 if ($this->page->blocks->region_has_content($region, $this)) {
3292 $additionalclasses[] = 'used-region-'.$region;
3293 } else {
3294 $additionalclasses[] = 'empty-region-'.$region;
3296 if ($this->page->blocks->region_completely_docked($region, $this)) {
3297 $additionalclasses[] = 'docked-region-'.$region;
3300 foreach ($this->page->layout_options as $option => $value) {
3301 if ($value) {
3302 $additionalclasses[] = 'layout-option-'.$option;
3305 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
3306 return $css;
3310 * The ID attribute to apply to the body tag.
3312 * @since Moodle 2.5.1 2.6
3313 * @return string
3315 public function body_id() {
3316 return $this->page->bodyid;
3320 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
3322 * @since Moodle 2.5.1 2.6
3323 * @param string|array $additionalclasses Any additional classes to give the body tag,
3324 * @return string
3326 public function body_attributes($additionalclasses = array()) {
3327 if (!is_array($additionalclasses)) {
3328 $additionalclasses = explode(' ', $additionalclasses);
3330 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
3334 * Gets HTML for the page heading.
3336 * @since Moodle 2.5.1 2.6
3337 * @param string $tag The tag to encase the heading in. h1 by default.
3338 * @return string HTML.
3340 public function page_heading($tag = 'h1') {
3341 return html_writer::tag($tag, $this->page->heading);
3345 * Gets the HTML for the page heading button.
3347 * @since Moodle 2.5.1 2.6
3348 * @return string HTML.
3350 public function page_heading_button() {
3351 return $this->page->button;
3355 * Returns the Moodle docs link to use for this page.
3357 * @since Moodle 2.5.1 2.6
3358 * @param string $text
3359 * @return string
3361 public function page_doc_link($text = null) {
3362 if ($text === null) {
3363 $text = get_string('moodledocslink');
3365 $path = page_get_doc_link_path($this->page);
3366 if (!$path) {
3367 return '';
3369 return $this->doc_link($path, $text);
3373 * Returns the page heading menu.
3375 * @since Moodle 2.5.1 2.6
3376 * @return string HTML.
3378 public function page_heading_menu() {
3379 return $this->page->headingmenu;
3383 * Returns the title to use on the page.
3385 * @since Moodle 2.5.1 2.6
3386 * @return string
3388 public function page_title() {
3389 return $this->page->title;
3393 * Returns the URL for the favicon.
3395 * @since Moodle 2.5.1 2.6
3396 * @return string The favicon URL
3398 public function favicon() {
3399 return $this->pix_url('favicon', 'theme');
3404 * A renderer that generates output for command-line scripts.
3406 * The implementation of this renderer is probably incomplete.
3408 * @copyright 2009 Tim Hunt
3409 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3410 * @since Moodle 2.0
3411 * @package core
3412 * @category output
3414 class core_renderer_cli extends core_renderer {
3417 * Returns the page header.
3419 * @return string HTML fragment
3421 public function header() {
3422 return $this->page->heading . "\n";
3426 * Returns a template fragment representing a Heading.
3428 * @param string $text The text of the heading
3429 * @param int $level The level of importance of the heading
3430 * @param string $classes A space-separated list of CSS classes
3431 * @param string $id An optional ID
3432 * @return string A template fragment for a heading
3434 public function heading($text, $level = 2, $classes = 'main', $id = null) {
3435 $text .= "\n";
3436 switch ($level) {
3437 case 1:
3438 return '=>' . $text;
3439 case 2:
3440 return '-->' . $text;
3441 default:
3442 return $text;
3447 * Returns a template fragment representing a fatal error.
3449 * @param string $message The message to output
3450 * @param string $moreinfourl URL where more info can be found about the error
3451 * @param string $link Link for the Continue button
3452 * @param array $backtrace The execution backtrace
3453 * @param string $debuginfo Debugging information
3454 * @return string A template fragment for a fatal error
3456 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
3457 global $CFG;
3459 $output = "!!! $message !!!\n";
3461 if ($CFG->debugdeveloper) {
3462 if (!empty($debuginfo)) {
3463 $output .= $this->notification($debuginfo, 'notifytiny');
3465 if (!empty($backtrace)) {
3466 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
3470 return $output;
3474 * Returns a template fragment representing a notification.
3476 * @param string $message The message to include
3477 * @param string $classes A space-separated list of CSS classes
3478 * @return string A template fragment for a notification
3480 public function notification($message, $classes = 'notifyproblem') {
3481 $message = clean_text($message);
3482 if ($classes === 'notifysuccess') {
3483 return "++ $message ++\n";
3485 return "!! $message !!\n";
3491 * A renderer that generates output for ajax scripts.
3493 * This renderer prevents accidental sends back only json
3494 * encoded error messages, all other output is ignored.
3496 * @copyright 2010 Petr Skoda
3497 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3498 * @since Moodle 2.0
3499 * @package core
3500 * @category output
3502 class core_renderer_ajax extends core_renderer {
3505 * Returns a template fragment representing a fatal error.
3507 * @param string $message The message to output
3508 * @param string $moreinfourl URL where more info can be found about the error
3509 * @param string $link Link for the Continue button
3510 * @param array $backtrace The execution backtrace
3511 * @param string $debuginfo Debugging information
3512 * @return string A template fragment for a fatal error
3514 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
3515 global $CFG;
3517 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
3519 $e = new stdClass();
3520 $e->error = $message;
3521 $e->stacktrace = NULL;
3522 $e->debuginfo = NULL;
3523 $e->reproductionlink = NULL;
3524 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
3525 $link = (string) $link;
3526 if ($link) {
3527 $e->reproductionlink = $link;
3529 if (!empty($debuginfo)) {
3530 $e->debuginfo = $debuginfo;
3532 if (!empty($backtrace)) {
3533 $e->stacktrace = format_backtrace($backtrace, true);
3536 $this->header();
3537 return json_encode($e);
3541 * Used to display a notification.
3542 * For the AJAX notifications are discarded.
3544 * @param string $message
3545 * @param string $classes
3547 public function notification($message, $classes = 'notifyproblem') {}
3550 * Used to display a redirection message.
3551 * AJAX redirections should not occur and as such redirection messages
3552 * are discarded.
3554 * @param moodle_url|string $encodedurl
3555 * @param string $message
3556 * @param int $delay
3557 * @param bool $debugdisableredirect
3559 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
3562 * Prepares the start of an AJAX output.
3564 public function header() {
3565 // unfortunately YUI iframe upload does not support application/json
3566 if (!empty($_FILES)) {
3567 @header('Content-type: text/plain; charset=utf-8');
3568 if (!core_useragent::supports_json_contenttype()) {
3569 @header('X-Content-Type-Options: nosniff');
3571 } else if (!core_useragent::supports_json_contenttype()) {
3572 @header('Content-type: text/plain; charset=utf-8');
3573 @header('X-Content-Type-Options: nosniff');
3574 } else {
3575 @header('Content-type: application/json; charset=utf-8');
3578 // Headers to make it not cacheable and json
3579 @header('Cache-Control: no-store, no-cache, must-revalidate');
3580 @header('Cache-Control: post-check=0, pre-check=0', false);
3581 @header('Pragma: no-cache');
3582 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
3583 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
3584 @header('Accept-Ranges: none');
3588 * There is no footer for an AJAX request, however we must override the
3589 * footer method to prevent the default footer.
3591 public function footer() {}
3594 * No need for headers in an AJAX request... this should never happen.
3595 * @param string $text
3596 * @param int $level
3597 * @param string $classes
3598 * @param string $id
3600 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
3605 * Renderer for media files.
3607 * Used in file resources, media filter, and any other places that need to
3608 * output embedded media.
3610 * @copyright 2011 The Open University
3611 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3613 class core_media_renderer extends plugin_renderer_base {
3614 /** @var array Array of available 'player' objects */
3615 private $players;
3616 /** @var string Regex pattern for links which may contain embeddable content */
3617 private $embeddablemarkers;
3620 * Constructor requires medialib.php.
3622 * This is needed in the constructor (not later) so that you can use the
3623 * constants and static functions that are defined in core_media class
3624 * before you call renderer functions.
3626 public function __construct() {
3627 global $CFG;
3628 require_once($CFG->libdir . '/medialib.php');
3632 * Obtains the list of core_media_player objects currently in use to render
3633 * items.
3635 * The list is in rank order (highest first) and does not include players
3636 * which are disabled.
3638 * @return array Array of core_media_player objects in rank order
3640 protected function get_players() {
3641 global $CFG;
3643 // Save time by only building the list once.
3644 if (!$this->players) {
3645 // Get raw list of players.
3646 $players = $this->get_players_raw();
3648 // Chuck all the ones that are disabled.
3649 foreach ($players as $key => $player) {
3650 if (!$player->is_enabled()) {
3651 unset($players[$key]);
3655 // Sort in rank order (highest first).
3656 usort($players, array('core_media_player', 'compare_by_rank'));
3657 $this->players = $players;
3659 return $this->players;
3663 * Obtains a raw list of player objects that includes objects regardless
3664 * of whether they are disabled or not, and without sorting.
3666 * You can override this in a subclass if you need to add additional
3667 * players.
3669 * The return array is be indexed by player name to make it easier to
3670 * remove players in a subclass.
3672 * @return array $players Array of core_media_player objects in any order
3674 protected function get_players_raw() {
3675 return array(
3676 'vimeo' => new core_media_player_vimeo(),
3677 'youtube' => new core_media_player_youtube(),
3678 'youtube_playlist' => new core_media_player_youtube_playlist(),
3679 'html5video' => new core_media_player_html5video(),
3680 'html5audio' => new core_media_player_html5audio(),
3681 'mp3' => new core_media_player_mp3(),
3682 'flv' => new core_media_player_flv(),
3683 'wmp' => new core_media_player_wmp(),
3684 'qt' => new core_media_player_qt(),
3685 'rm' => new core_media_player_rm(),
3686 'swf' => new core_media_player_swf(),
3687 'link' => new core_media_player_link(),
3692 * Renders a media file (audio or video) using suitable embedded player.
3694 * See embed_alternatives function for full description of parameters.
3695 * This function calls through to that one.
3697 * When using this function you can also specify width and height in the
3698 * URL by including ?d=100x100 at the end. If specified in the URL, this
3699 * will override the $width and $height parameters.
3701 * @param moodle_url $url Full URL of media file
3702 * @param string $name Optional user-readable name to display in download link
3703 * @param int $width Width in pixels (optional)
3704 * @param int $height Height in pixels (optional)
3705 * @param array $options Array of key/value pairs
3706 * @return string HTML content of embed
3708 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
3709 $options = array()) {
3711 // Get width and height from URL if specified (overrides parameters in
3712 // function call).
3713 $rawurl = $url->out(false);
3714 if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
3715 $width = $matches[1];
3716 $height = $matches[2];
3717 $url = new moodle_url(str_replace($matches[0], '', $rawurl));
3720 // Defer to array version of function.
3721 return $this->embed_alternatives(array($url), $name, $width, $height, $options);
3725 * Renders media files (audio or video) using suitable embedded player.
3726 * The list of URLs should be alternative versions of the same content in
3727 * multiple formats. If there is only one format it should have a single
3728 * entry.
3730 * If the media files are not in a supported format, this will give students
3731 * a download link to each format. The download link uses the filename
3732 * unless you supply the optional name parameter.
3734 * Width and height are optional. If specified, these are suggested sizes
3735 * and should be the exact values supplied by the user, if they come from
3736 * user input. These will be treated as relating to the size of the video
3737 * content, not including any player control bar.
3739 * For audio files, height will be ignored. For video files, a few formats
3740 * work if you specify only width, but in general if you specify width
3741 * you must specify height as well.
3743 * The $options array is passed through to the core_media_player classes
3744 * that render the object tag. The keys can contain values from
3745 * core_media::OPTION_xx.
3747 * @param array $alternatives Array of moodle_url to media files
3748 * @param string $name Optional user-readable name to display in download link
3749 * @param int $width Width in pixels (optional)
3750 * @param int $height Height in pixels (optional)
3751 * @param array $options Array of key/value pairs
3752 * @return string HTML content of embed
3754 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
3755 $options = array()) {
3757 // Get list of player plugins (will also require the library).
3758 $players = $this->get_players();
3760 // Set up initial text which will be replaced by first player that
3761 // supports any of the formats.
3762 $out = core_media_player::PLACEHOLDER;
3764 // Loop through all players that support any of these URLs.
3765 foreach ($players as $player) {
3766 // Option: When no other player matched, don't do the default link player.
3767 if (!empty($options[core_media::OPTION_FALLBACK_TO_BLANK]) &&
3768 $player->get_rank() === 0 && $out === core_media_player::PLACEHOLDER) {
3769 continue;
3772 $supported = $player->list_supported_urls($alternatives, $options);
3773 if ($supported) {
3774 // Embed.
3775 $text = $player->embed($supported, $name, $width, $height, $options);
3777 // Put this in place of the 'fallback' slot in the previous text.
3778 $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
3782 // Remove 'fallback' slot from final version and return it.
3783 $out = str_replace(core_media_player::PLACEHOLDER, '', $out);
3784 if (!empty($options[core_media::OPTION_BLOCK]) && $out !== '') {
3785 $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
3787 return $out;
3791 * Checks whether a file can be embedded. If this returns true you will get
3792 * an embedded player; if this returns false, you will just get a download
3793 * link.
3795 * This is a wrapper for can_embed_urls.
3797 * @param moodle_url $url URL of media file
3798 * @param array $options Options (same as when embedding)
3799 * @return bool True if file can be embedded
3801 public function can_embed_url(moodle_url $url, $options = array()) {
3802 return $this->can_embed_urls(array($url), $options);
3806 * Checks whether a file can be embedded. If this returns true you will get
3807 * an embedded player; if this returns false, you will just get a download
3808 * link.
3810 * @param array $urls URL of media file and any alternatives (moodle_url)
3811 * @param array $options Options (same as when embedding)
3812 * @return bool True if file can be embedded
3814 public function can_embed_urls(array $urls, $options = array()) {
3815 // Check all players to see if any of them support it.
3816 foreach ($this->get_players() as $player) {
3817 // Link player (always last on list) doesn't count!
3818 if ($player->get_rank() <= 0) {
3819 break;
3821 // First player that supports it, return true.
3822 if ($player->list_supported_urls($urls, $options)) {
3823 return true;
3826 return false;
3830 * Obtains a list of markers that can be used in a regular expression when
3831 * searching for URLs that can be embedded by any player type.
3833 * This string is used to improve peformance of regex matching by ensuring
3834 * that the (presumably C) regex code can do a quick keyword check on the
3835 * URL part of a link to see if it matches one of these, rather than having
3836 * to go into PHP code for every single link to see if it can be embedded.
3838 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
3840 public function get_embeddable_markers() {
3841 if (empty($this->embeddablemarkers)) {
3842 $markers = '';
3843 foreach ($this->get_players() as $player) {
3844 foreach ($player->get_embeddable_markers() as $marker) {
3845 if ($markers !== '') {
3846 $markers .= '|';
3848 $markers .= preg_quote($marker);
3851 $this->embeddablemarkers = $markers;
3853 return $this->embeddablemarkers;
3858 * The maintenance renderer.
3860 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
3861 * is running a maintenance related task.
3862 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
3864 * @since Moodle 2.6
3865 * @package core
3866 * @category output
3867 * @copyright 2013 Sam Hemelryk
3868 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3870 class core_renderer_maintenance extends core_renderer {
3873 * Initialises the renderer instance.
3874 * @param moodle_page $page
3875 * @param string $target
3876 * @throws coding_exception
3878 public function __construct(moodle_page $page, $target) {
3879 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
3880 throw new coding_exception('Invalid request for the maintenance renderer.');
3882 parent::__construct($page, $target);
3886 * Does nothing. The maintenance renderer cannot produce blocks.
3888 * @param block_contents $bc
3889 * @param string $region
3890 * @return string
3892 public function block(block_contents $bc, $region) {
3893 // Computer says no blocks.
3894 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3895 return '';
3899 * Does nothing. The maintenance renderer cannot produce blocks.
3901 * @param string $region
3902 * @param array $classes
3903 * @param string $tag
3904 * @return string
3906 public function blocks($region, $classes = array(), $tag = 'aside') {
3907 // Computer says no blocks.
3908 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3909 return '';
3913 * Does nothing. The maintenance renderer cannot produce blocks.
3915 * @param string $region
3916 * @return string
3918 public function blocks_for_region($region) {
3919 // Computer says no blocks for region.
3920 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3921 return '';
3925 * Does nothing. The maintenance renderer cannot produce a course content header.
3927 * @param bool $onlyifnotcalledbefore
3928 * @return string
3930 public function course_content_header($onlyifnotcalledbefore = false) {
3931 // Computer says no course content header.
3932 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3933 return '';
3937 * Does nothing. The maintenance renderer cannot produce a course content footer.
3939 * @param bool $onlyifnotcalledbefore
3940 * @return string
3942 public function course_content_footer($onlyifnotcalledbefore = false) {
3943 // Computer says no course content footer.
3944 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3945 return '';
3949 * Does nothing. The maintenance renderer cannot produce a course header.
3951 * @return string
3953 public function course_header() {
3954 // Computer says no course header.
3955 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3956 return '';
3960 * Does nothing. The maintenance renderer cannot produce a course footer.
3962 * @return string
3964 public function course_footer() {
3965 // Computer says no course footer.
3966 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3967 return '';
3971 * Does nothing. The maintenance renderer cannot produce a custom menu.
3973 * @param string $custommenuitems
3974 * @return string
3976 public function custom_menu($custommenuitems = '') {
3977 // Computer says no custom menu.
3978 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3979 return '';
3983 * Does nothing. The maintenance renderer cannot produce a file picker.
3985 * @param array $options
3986 * @return string
3988 public function file_picker($options) {
3989 // Computer says no file picker.
3990 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
3991 return '';
3995 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
3997 * @param array $dir
3998 * @return string
4000 public function htmllize_file_tree($dir) {
4001 // Hell no we don't want no htmllized file tree.
4002 // Also why on earth is this function on the core renderer???
4003 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4004 return '';
4009 * Does nothing. The maintenance renderer does not support JS.
4011 * @param block_contents $bc
4013 public function init_block_hider_js(block_contents $bc) {
4014 // Computer says no JavaScript.
4015 // Do nothing, ridiculous method.
4019 * Does nothing. The maintenance renderer cannot produce language menus.
4021 * @return string
4023 public function lang_menu() {
4024 // Computer says no lang menu.
4025 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4026 return '';
4030 * Does nothing. The maintenance renderer has no need for login information.
4032 * @param null $withlinks
4033 * @return string
4035 public function login_info($withlinks = null) {
4036 // Computer says no login info.
4037 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4038 return '';
4042 * Does nothing. The maintenance renderer cannot produce user pictures.
4044 * @param stdClass $user
4045 * @param array $options
4046 * @return string
4048 public function user_picture(stdClass $user, array $options = null) {
4049 // Computer says no user pictures.
4050 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4051 return '';