MDL-27930 Lesson: the count-down timer does not work
[moodle.git] / lib / outputrenderers.php
blobb1461629d79804c4f2e0f8f80a0ee41b9717958e
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);
102 // Remove _renderable suffixes
103 $classname = preg_replace('/_renderable$/', '', $classname);
105 $rendermethod = 'render_'.$classname;
106 if (method_exists($this, $rendermethod)) {
107 return $this->$rendermethod($widget);
109 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
113 * Adds a JS action for the element with the provided id.
115 * This method adds a JS event for the provided component action to the page
116 * and then returns the id that the event has been attached to.
117 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
119 * @param component_action $action
120 * @param string $id
121 * @return string id of element, either original submitted or random new if not supplied
123 public function add_action_handler(component_action $action, $id = null) {
124 if (!$id) {
125 $id = html_writer::random_id($action->event);
127 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
128 return $id;
132 * Returns true is output has already started, and false if not.
134 * @return boolean true if the header has been printed.
136 public function has_started() {
137 return $this->page->state >= moodle_page::STATE_IN_BODY;
141 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
143 * @param mixed $classes Space-separated string or array of classes
144 * @return string HTML class attribute value
146 public static function prepare_classes($classes) {
147 if (is_array($classes)) {
148 return implode(' ', array_unique($classes));
150 return $classes;
154 * Return the moodle_url for an image.
156 * The exact image location and extension is determined
157 * automatically by searching for gif|png|jpg|jpeg, please
158 * note there can not be diferent images with the different
159 * extension. The imagename is for historical reasons
160 * a relative path name, it may be changed later for core
161 * images. It is recommended to not use subdirectories
162 * in plugin and theme pix directories.
164 * There are three types of images:
165 * 1/ theme images - stored in theme/mytheme/pix/,
166 * use component 'theme'
167 * 2/ core images - stored in /pix/,
168 * overridden via theme/mytheme/pix_core/
169 * 3/ plugin images - stored in mod/mymodule/pix,
170 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
171 * example: pix_url('comment', 'mod_glossary')
173 * @param string $imagename the pathname of the image
174 * @param string $component full plugin name (aka component) or 'theme'
175 * @return moodle_url
177 public function pix_url($imagename, $component = 'moodle') {
178 return $this->page->theme->pix_url($imagename, $component);
184 * Basis for all plugin renderers.
186 * @copyright Petr Skoda (skodak)
187 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
188 * @since Moodle 2.0
189 * @package core
190 * @category output
192 class plugin_renderer_base extends renderer_base {
195 * @var renderer_base|core_renderer A reference to the current renderer.
196 * The renderer provided here will be determined by the page but will in 90%
197 * of cases by the {@link core_renderer}
199 protected $output;
202 * Constructor method, calls the parent constructor
204 * @param moodle_page $page
205 * @param string $target one of rendering target constants
207 public function __construct(moodle_page $page, $target) {
208 if (empty($target) && $page->pagelayout === 'maintenance') {
209 // If the page is using the maintenance layout then we're going to force the target to maintenance.
210 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
211 // unavailable for this page layout.
212 $target = RENDERER_TARGET_MAINTENANCE;
214 $this->output = $page->get_renderer('core', null, $target);
215 parent::__construct($page, $target);
219 * Renders the provided widget and returns the HTML to display it.
221 * @param renderable $widget instance with renderable interface
222 * @return string
224 public function render(renderable $widget) {
225 $classname = get_class($widget);
226 // Strip namespaces.
227 $classname = preg_replace('/^.*\\\/', '', $classname);
228 // Keep a copy at this point, we may need to look for a deprecated method.
229 $deprecatedmethod = 'render_'.$classname;
230 // Remove _renderable suffixes
231 $classname = preg_replace('/_renderable$/', '', $classname);
233 $rendermethod = 'render_'.$classname;
234 if (method_exists($this, $rendermethod)) {
235 return $this->$rendermethod($widget);
237 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
238 // This is exactly where we don't want to be.
239 // If you have arrived here you have a renderable component within your plugin that has the name
240 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
241 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
242 // and the _renderable suffix now gets removed when looking for a render method.
243 // You need to change your renderers render_blah_renderable to render_blah.
244 // Until you do this it will not be possible for a theme to override the renderer to override your method.
245 // Please do it ASAP.
246 static $debugged = array();
247 if (!isset($debugged[$deprecatedmethod])) {
248 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
249 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
250 $debugged[$deprecatedmethod] = true;
252 return $this->$deprecatedmethod($widget);
254 // pass to core renderer if method not found here
255 return $this->output->render($widget);
259 * Magic method used to pass calls otherwise meant for the standard renderer
260 * to it to ensure we don't go causing unnecessary grief.
262 * @param string $method
263 * @param array $arguments
264 * @return mixed
266 public function __call($method, $arguments) {
267 if (method_exists('renderer_base', $method)) {
268 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
270 if (method_exists($this->output, $method)) {
271 return call_user_func_array(array($this->output, $method), $arguments);
272 } else {
273 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
280 * The standard implementation of the core_renderer interface.
282 * @copyright 2009 Tim Hunt
283 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
284 * @since Moodle 2.0
285 * @package core
286 * @category output
288 class core_renderer extends renderer_base {
290 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
291 * in layout files instead.
292 * @deprecated
293 * @var string used in {@link core_renderer::header()}.
295 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
298 * @var string Used to pass information from {@link core_renderer::doctype()} to
299 * {@link core_renderer::standard_head_html()}.
301 protected $contenttype;
304 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
305 * with {@link core_renderer::header()}.
307 protected $metarefreshtag = '';
310 * @var string Unique token for the closing HTML
312 protected $unique_end_html_token;
315 * @var string Unique token for performance information
317 protected $unique_performance_info_token;
320 * @var string Unique token for the main content.
322 protected $unique_main_content_token;
325 * Constructor
327 * @param moodle_page $page the page we are doing output for.
328 * @param string $target one of rendering target constants
330 public function __construct(moodle_page $page, $target) {
331 $this->opencontainers = $page->opencontainers;
332 $this->page = $page;
333 $this->target = $target;
335 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
336 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
337 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
341 * Get the DOCTYPE declaration that should be used with this page. Designed to
342 * be called in theme layout.php files.
344 * @return string the DOCTYPE declaration that should be used.
346 public function doctype() {
347 if ($this->page->theme->doctype === 'html5') {
348 $this->contenttype = 'text/html; charset=utf-8';
349 return "<!DOCTYPE html>\n";
351 } else if ($this->page->theme->doctype === 'xhtml5') {
352 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
353 return "<!DOCTYPE html>\n";
355 } else {
356 // legacy xhtml 1.0
357 $this->contenttype = 'text/html; charset=utf-8';
358 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
363 * The attributes that should be added to the <html> tag. Designed to
364 * be called in theme layout.php files.
366 * @return string HTML fragment.
368 public function htmlattributes() {
369 $return = get_html_lang(true);
370 if ($this->page->theme->doctype !== 'html5') {
371 $return .= ' xmlns="http://www.w3.org/1999/xhtml"';
373 return $return;
377 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
378 * that should be included in the <head> tag. Designed to be called in theme
379 * layout.php files.
381 * @return string HTML fragment.
383 public function standard_head_html() {
384 global $CFG, $SESSION;
386 // Before we output any content, we need to ensure that certain
387 // page components are set up.
389 // Blocks must be set up early as they may require javascript which
390 // has to be included in the page header before output is created.
391 foreach ($this->page->blocks->get_regions() as $region) {
392 $this->page->blocks->ensure_content_created($region, $this);
395 $output = '';
396 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
397 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
398 // This is only set by the {@link redirect()} method
399 $output .= $this->metarefreshtag;
401 // Check if a periodic refresh delay has been set and make sure we arn't
402 // already meta refreshing
403 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
404 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
407 // flow player embedding support
408 $this->page->requires->js_function_call('M.util.load_flowplayer');
410 // Set up help link popups for all links with the helptooltip class
411 $this->page->requires->js_init_call('M.util.help_popups.setup');
413 // Setup help icon overlays.
414 $this->page->requires->yui_module('moodle-core-popuphelp', 'M.core.init_popuphelp');
415 $this->page->requires->strings_for_js(array(
416 'morehelp',
417 'loadinghelp',
418 ), 'moodle');
420 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
422 $focus = $this->page->focuscontrol;
423 if (!empty($focus)) {
424 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
425 // This is a horrifically bad way to handle focus but it is passed in
426 // through messy formslib::moodleform
427 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
428 } else if (strpos($focus, '.')!==false) {
429 // Old style of focus, bad way to do it
430 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);
431 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
432 } else {
433 // Focus element with given id
434 $this->page->requires->js_function_call('focuscontrol', array($focus));
438 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
439 // any other custom CSS can not be overridden via themes and is highly discouraged
440 $urls = $this->page->theme->css_urls($this->page);
441 foreach ($urls as $url) {
442 $this->page->requires->css_theme($url);
445 // Get the theme javascript head and footer
446 if ($jsurl = $this->page->theme->javascript_url(true)) {
447 $this->page->requires->js($jsurl, true);
449 if ($jsurl = $this->page->theme->javascript_url(false)) {
450 $this->page->requires->js($jsurl);
453 // Get any HTML from the page_requirements_manager.
454 $output .= $this->page->requires->get_head_code($this->page, $this);
456 // List alternate versions.
457 foreach ($this->page->alternateversions as $type => $alt) {
458 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
459 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
462 if (!empty($CFG->additionalhtmlhead)) {
463 $output .= "\n".$CFG->additionalhtmlhead;
466 return $output;
470 * The standard tags (typically skip links) that should be output just inside
471 * the start of the <body> tag. Designed to be called in theme layout.php files.
473 * @return string HTML fragment.
475 public function standard_top_of_body_html() {
476 global $CFG;
477 $output = $this->page->requires->get_top_of_body_code();
478 if (!empty($CFG->additionalhtmltopofbody)) {
479 $output .= "\n".$CFG->additionalhtmltopofbody;
481 $output .= $this->maintenance_warning();
482 return $output;
486 * Scheduled maintenance warning message.
488 * Note: This is a nasty hack to display maintenance notice, this should be moved
489 * to some general notification area once we have it.
491 * @return string
493 public function maintenance_warning() {
494 global $CFG;
496 $output = '';
497 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
498 $timeleft = $CFG->maintenance_later - time();
499 // If timeleft less than 30 sec, set the class on block to error to highlight.
500 $errorclass = ($timeleft < 30) ? 'error' : 'warning';
501 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning');
502 $a = new stdClass();
503 $a->min = (int)($timeleft/60);
504 $a->sec = (int)($timeleft % 60);
505 $output .= get_string('maintenancemodeisscheduled', 'admin', $a) ;
506 $output .= $this->box_end();
507 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
508 array(array('timeleftinsec' => $timeleft)));
509 $this->page->requires->strings_for_js(
510 array('maintenancemodeisscheduled', 'sitemaintenance'),
511 'admin');
513 return $output;
517 * The standard tags (typically performance information and validation links,
518 * if we are in developer debug mode) that should be output in the footer area
519 * of the page. Designed to be called in theme layout.php files.
521 * @return string HTML fragment.
523 public function standard_footer_html() {
524 global $CFG, $SCRIPT;
526 if (during_initial_install()) {
527 // Debugging info can not work before install is finished,
528 // in any case we do not want any links during installation!
529 return '';
532 // This function is normally called from a layout.php file in {@link core_renderer::header()}
533 // but some of the content won't be known until later, so we return a placeholder
534 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
535 $output = $this->unique_performance_info_token;
536 if ($this->page->devicetypeinuse == 'legacy') {
537 // The legacy theme is in use print the notification
538 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
541 // Get links to switch device types (only shown for users not on a default device)
542 $output .= $this->theme_switch_links();
544 if (!empty($CFG->debugpageinfo)) {
545 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
547 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
548 // Add link to profiling report if necessary
549 if (function_exists('profiling_is_running') && profiling_is_running()) {
550 $txt = get_string('profiledscript', 'admin');
551 $title = get_string('profiledscriptview', 'admin');
552 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
553 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
554 $output .= '<div class="profilingfooter">' . $link . '</div>';
556 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
557 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
558 $output .= '<div class="purgecaches">' .
559 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
561 if (!empty($CFG->debugvalidators)) {
562 // 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
563 $output .= '<div class="validators"><ul>
564 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
565 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
566 <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>
567 </ul></div>';
569 return $output;
573 * Returns standard main content placeholder.
574 * Designed to be called in theme layout.php files.
576 * @return string HTML fragment.
578 public function main_content() {
579 // This is here because it is the only place we can inject the "main" role over the entire main content area
580 // without requiring all theme's to manually do it, and without creating yet another thing people need to
581 // remember in the theme.
582 // This is an unfortunate hack. DO NO EVER add anything more here.
583 // DO NOT add classes.
584 // DO NOT add an id.
585 return '<div role="main">'.$this->unique_main_content_token.'</div>';
589 * The standard tags (typically script tags that are not needed earlier) that
590 * should be output after everything else. Designed to be called in theme layout.php files.
592 * @return string HTML fragment.
594 public function standard_end_of_body_html() {
595 global $CFG;
597 // This function is normally called from a layout.php file in {@link core_renderer::header()}
598 // but some of the content won't be known until later, so we return a placeholder
599 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
600 $output = '';
601 if (!empty($CFG->additionalhtmlfooter)) {
602 $output .= "\n".$CFG->additionalhtmlfooter;
604 $output .= $this->unique_end_html_token;
605 return $output;
609 * Return the standard string that says whether you are logged in (and switched
610 * roles/logged in as another user).
611 * @param bool $withlinks if false, then don't include any links in the HTML produced.
612 * If not set, the default is the nologinlinks option from the theme config.php file,
613 * and if that is not set, then links are included.
614 * @return string HTML fragment.
616 public function login_info($withlinks = null) {
617 global $USER, $CFG, $DB, $SESSION;
619 if (during_initial_install()) {
620 return '';
623 if (is_null($withlinks)) {
624 $withlinks = empty($this->page->layout_options['nologinlinks']);
627 $loginpage = ((string)$this->page->url === get_login_url());
628 $course = $this->page->course;
629 if (\core\session\manager::is_loggedinas()) {
630 $realuser = \core\session\manager::get_realuser();
631 $fullname = fullname($realuser, true);
632 if ($withlinks) {
633 $loginastitle = get_string('loginas');
634 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
635 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
636 } else {
637 $realuserinfo = " [$fullname] ";
639 } else {
640 $realuserinfo = '';
643 $loginurl = get_login_url();
645 if (empty($course->id)) {
646 // $course->id is not defined during installation
647 return '';
648 } else if (isloggedin()) {
649 $context = context_course::instance($course->id);
651 $fullname = fullname($USER, true);
652 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
653 if ($withlinks) {
654 $linktitle = get_string('viewprofile');
655 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
656 } else {
657 $username = $fullname;
659 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
660 if ($withlinks) {
661 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
662 } else {
663 $username .= " from {$idprovider->name}";
666 if (isguestuser()) {
667 $loggedinas = $realuserinfo.get_string('loggedinasguest');
668 if (!$loginpage && $withlinks) {
669 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
671 } else if (is_role_switched($course->id)) { // Has switched roles
672 $rolename = '';
673 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
674 $rolename = ': '.role_get_name($role, $context);
676 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
677 if ($withlinks) {
678 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
679 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
681 } else {
682 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
683 if ($withlinks) {
684 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
687 } else {
688 $loggedinas = get_string('loggedinnot', 'moodle');
689 if (!$loginpage && $withlinks) {
690 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
694 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
696 if (isset($SESSION->justloggedin)) {
697 unset($SESSION->justloggedin);
698 if (!empty($CFG->displayloginfailures)) {
699 if (!isguestuser()) {
700 // Include this file only when required.
701 require_once($CFG->dirroot . '/user/lib.php');
702 if ($count = user_count_login_failures($USER)) {
703 $loggedinas .= '<div class="loginfailures">';
704 $a = new stdClass();
705 $a->attempts = $count;
706 $loggedinas .= get_string('failedloginattempts', '', $a);
707 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
708 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
709 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
711 $loggedinas .= '</div>';
717 return $loggedinas;
721 * Return the 'back' link that normally appears in the footer.
723 * @return string HTML fragment.
725 public function home_link() {
726 global $CFG, $SITE;
728 if ($this->page->pagetype == 'site-index') {
729 // Special case for site home page - please do not remove
730 return '<div class="sitelink">' .
731 '<a title="Moodle" href="http://moodle.org/">' .
732 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
734 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
735 // Special case for during install/upgrade.
736 return '<div class="sitelink">'.
737 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
738 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
740 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
741 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
742 get_string('home') . '</a></div>';
744 } else {
745 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
746 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
751 * Redirects the user by any means possible given the current state
753 * This function should not be called directly, it should always be called using
754 * the redirect function in lib/weblib.php
756 * The redirect function should really only be called before page output has started
757 * however it will allow itself to be called during the state STATE_IN_BODY
759 * @param string $encodedurl The URL to send to encoded if required
760 * @param string $message The message to display to the user if any
761 * @param int $delay The delay before redirecting a user, if $message has been
762 * set this is a requirement and defaults to 3, set to 0 no delay
763 * @param boolean $debugdisableredirect this redirect has been disabled for
764 * debugging purposes. Display a message that explains, and don't
765 * trigger the redirect.
766 * @return string The HTML to display to the user before dying, may contain
767 * meta refresh, javascript refresh, and may have set header redirects
769 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
770 global $CFG;
771 $url = str_replace('&amp;', '&', $encodedurl);
773 switch ($this->page->state) {
774 case moodle_page::STATE_BEFORE_HEADER :
775 // No output yet it is safe to delivery the full arsenal of redirect methods
776 if (!$debugdisableredirect) {
777 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
778 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
779 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
781 $output = $this->header();
782 break;
783 case moodle_page::STATE_PRINTING_HEADER :
784 // We should hopefully never get here
785 throw new coding_exception('You cannot redirect while printing the page header');
786 break;
787 case moodle_page::STATE_IN_BODY :
788 // We really shouldn't be here but we can deal with this
789 debugging("You should really redirect before you start page output");
790 if (!$debugdisableredirect) {
791 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
793 $output = $this->opencontainers->pop_all_but_last();
794 break;
795 case moodle_page::STATE_DONE :
796 // Too late to be calling redirect now
797 throw new coding_exception('You cannot redirect after the entire page has been generated');
798 break;
800 $output .= $this->notification($message, 'redirectmessage');
801 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
802 if ($debugdisableredirect) {
803 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
805 $output .= $this->footer();
806 return $output;
810 * Start output by sending the HTTP headers, and printing the HTML <head>
811 * and the start of the <body>.
813 * To control what is printed, you should set properties on $PAGE. If you
814 * are familiar with the old {@link print_header()} function from Moodle 1.9
815 * you will find that there are properties on $PAGE that correspond to most
816 * of the old parameters to could be passed to print_header.
818 * Not that, in due course, the remaining $navigation, $menu parameters here
819 * will be replaced by more properties of $PAGE, but that is still to do.
821 * @return string HTML that you must output this, preferably immediately.
823 public function header() {
824 global $USER, $CFG;
826 if (\core\session\manager::is_loggedinas()) {
827 $this->page->add_body_class('userloggedinas');
830 // If the user is logged in, and we're not in initial install,
831 // check to see if the user is role-switched and add the appropriate
832 // CSS class to the body element.
833 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
834 $this->page->add_body_class('userswitchedrole');
837 // Give themes a chance to init/alter the page object.
838 $this->page->theme->init_page($this->page);
840 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
842 // Find the appropriate page layout file, based on $this->page->pagelayout.
843 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
844 // Render the layout using the layout file.
845 $rendered = $this->render_page_layout($layoutfile);
847 // Slice the rendered output into header and footer.
848 $cutpos = strpos($rendered, $this->unique_main_content_token);
849 if ($cutpos === false) {
850 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
851 $token = self::MAIN_CONTENT_TOKEN;
852 } else {
853 $token = $this->unique_main_content_token;
856 if ($cutpos === false) {
857 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.');
859 $header = substr($rendered, 0, $cutpos);
860 $footer = substr($rendered, $cutpos + strlen($token));
862 if (empty($this->contenttype)) {
863 debugging('The page layout file did not call $OUTPUT->doctype()');
864 $header = $this->doctype() . $header;
867 // If this theme version is below 2.4 release and this is a course view page
868 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
869 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
870 // check if course content header/footer have not been output during render of theme layout
871 $coursecontentheader = $this->course_content_header(true);
872 $coursecontentfooter = $this->course_content_footer(true);
873 if (!empty($coursecontentheader)) {
874 // display debug message and add header and footer right above and below main content
875 // Please note that course header and footer (to be displayed above and below the whole page)
876 // are not displayed in this case at all.
877 // Besides the content header and footer are not displayed on any other course page
878 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);
879 $header .= $coursecontentheader;
880 $footer = $coursecontentfooter. $footer;
884 send_headers($this->contenttype, $this->page->cacheable);
886 $this->opencontainers->push('header/footer', $footer);
887 $this->page->set_state(moodle_page::STATE_IN_BODY);
889 return $header . $this->skip_link_target('maincontent');
893 * Renders and outputs the page layout file.
895 * This is done by preparing the normal globals available to a script, and
896 * then including the layout file provided by the current theme for the
897 * requested layout.
899 * @param string $layoutfile The name of the layout file
900 * @return string HTML code
902 protected function render_page_layout($layoutfile) {
903 global $CFG, $SITE, $USER;
904 // The next lines are a bit tricky. The point is, here we are in a method
905 // of a renderer class, and this object may, or may not, be the same as
906 // the global $OUTPUT object. When rendering the page layout file, we want to use
907 // this object. However, people writing Moodle code expect the current
908 // renderer to be called $OUTPUT, not $this, so define a variable called
909 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
910 $OUTPUT = $this;
911 $PAGE = $this->page;
912 $COURSE = $this->page->course;
914 ob_start();
915 include($layoutfile);
916 $rendered = ob_get_contents();
917 ob_end_clean();
918 return $rendered;
922 * Outputs the page's footer
924 * @return string HTML fragment
926 public function footer() {
927 global $CFG, $DB;
929 $output = $this->container_end_all(true);
931 $footer = $this->opencontainers->pop('header/footer');
933 if (debugging() and $DB and $DB->is_transaction_started()) {
934 // TODO: MDL-20625 print warning - transaction will be rolled back
937 // Provide some performance info if required
938 $performanceinfo = '';
939 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
940 $perf = get_performance_info();
941 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
942 $performanceinfo = $perf['html'];
946 // We always want performance data when running a performance test, even if the user is redirected to another page.
947 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
948 $footer = $this->unique_performance_info_token . $footer;
950 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
952 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
954 $this->page->set_state(moodle_page::STATE_DONE);
956 return $output . $footer;
960 * Close all but the last open container. This is useful in places like error
961 * handling, where you want to close all the open containers (apart from <body>)
962 * before outputting the error message.
964 * @param bool $shouldbenone assert that the stack should be empty now - causes a
965 * developer debug warning if it isn't.
966 * @return string the HTML required to close any open containers inside <body>.
968 public function container_end_all($shouldbenone = false) {
969 return $this->opencontainers->pop_all_but_last($shouldbenone);
973 * Returns course-specific information to be output immediately above content on any course page
974 * (for the current course)
976 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
977 * @return string
979 public function course_content_header($onlyifnotcalledbefore = false) {
980 global $CFG;
981 if ($this->page->course->id == SITEID) {
982 // return immediately and do not include /course/lib.php if not necessary
983 return '';
985 static $functioncalled = false;
986 if ($functioncalled && $onlyifnotcalledbefore) {
987 // we have already output the content header
988 return '';
990 require_once($CFG->dirroot.'/course/lib.php');
991 $functioncalled = true;
992 $courseformat = course_get_format($this->page->course);
993 if (($obj = $courseformat->course_content_header()) !== null) {
994 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
996 return '';
1000 * Returns course-specific information to be output immediately below content on any course page
1001 * (for the current course)
1003 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1004 * @return string
1006 public function course_content_footer($onlyifnotcalledbefore = false) {
1007 global $CFG;
1008 if ($this->page->course->id == SITEID) {
1009 // return immediately and do not include /course/lib.php if not necessary
1010 return '';
1012 static $functioncalled = false;
1013 if ($functioncalled && $onlyifnotcalledbefore) {
1014 // we have already output the content footer
1015 return '';
1017 $functioncalled = true;
1018 require_once($CFG->dirroot.'/course/lib.php');
1019 $courseformat = course_get_format($this->page->course);
1020 if (($obj = $courseformat->course_content_footer()) !== null) {
1021 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1023 return '';
1027 * Returns course-specific information to be output on any course page in the header area
1028 * (for the current course)
1030 * @return string
1032 public function course_header() {
1033 global $CFG;
1034 if ($this->page->course->id == SITEID) {
1035 // return immediately and do not include /course/lib.php if not necessary
1036 return '';
1038 require_once($CFG->dirroot.'/course/lib.php');
1039 $courseformat = course_get_format($this->page->course);
1040 if (($obj = $courseformat->course_header()) !== null) {
1041 return $courseformat->get_renderer($this->page)->render($obj);
1043 return '';
1047 * Returns course-specific information to be output on any course page in the footer area
1048 * (for the current course)
1050 * @return string
1052 public function course_footer() {
1053 global $CFG;
1054 if ($this->page->course->id == SITEID) {
1055 // return immediately and do not include /course/lib.php if not necessary
1056 return '';
1058 require_once($CFG->dirroot.'/course/lib.php');
1059 $courseformat = course_get_format($this->page->course);
1060 if (($obj = $courseformat->course_footer()) !== null) {
1061 return $courseformat->get_renderer($this->page)->render($obj);
1063 return '';
1067 * Returns lang menu or '', this method also checks forcing of languages in courses.
1069 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1071 * @return string The lang menu HTML or empty string
1073 public function lang_menu() {
1074 global $CFG;
1076 if (empty($CFG->langmenu)) {
1077 return '';
1080 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1081 // do not show lang menu if language forced
1082 return '';
1085 $currlang = current_language();
1086 $langs = get_string_manager()->get_list_of_translations();
1088 if (count($langs) < 2) {
1089 return '';
1092 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1093 $s->label = get_accesshide(get_string('language'));
1094 $s->class = 'langmenu';
1095 return $this->render($s);
1099 * Output the row of editing icons for a block, as defined by the controls array.
1101 * @param array $controls an array like {@link block_contents::$controls}.
1102 * @param string $blockid The ID given to the block.
1103 * @return string HTML fragment.
1105 public function block_controls($actions, $blockid = null) {
1106 global $CFG;
1107 if (empty($actions)) {
1108 return '';
1110 $menu = new action_menu($actions);
1111 if ($blockid !== null) {
1112 $menu->set_owner_selector('#'.$blockid);
1114 $menu->set_constraint('.block-region');
1115 $menu->attributes['class'] .= ' block-control-actions commands';
1116 if (isset($CFG->blockeditingmenu) && !$CFG->blockeditingmenu) {
1117 $menu->do_not_enhance();
1119 return $this->render($menu);
1123 * Renders an action menu component.
1125 * ARIA references:
1126 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1127 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1129 * @param action_menu $menu
1130 * @return string HTML
1132 public function render_action_menu(action_menu $menu) {
1133 $menu->initialise_js($this->page);
1135 $output = html_writer::start_tag('div', $menu->attributes);
1136 $output .= html_writer::start_tag('ul', $menu->attributesprimary);
1137 foreach ($menu->get_primary_actions($this) as $action) {
1138 if ($action instanceof renderable) {
1139 $content = $this->render($action);
1140 } else {
1141 $content = $action;
1143 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1145 $output .= html_writer::end_tag('ul');
1146 $output .= html_writer::start_tag('ul', $menu->attributessecondary);
1147 foreach ($menu->get_secondary_actions() as $action) {
1148 if ($action instanceof renderable) {
1149 $content = $this->render($action);
1150 } else {
1151 $content = $action;
1153 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
1155 $output .= html_writer::end_tag('ul');
1156 $output .= html_writer::end_tag('div');
1157 return $output;
1161 * Renders an action_menu_link item.
1163 * @param action_menu_link $action
1164 * @return string HTML fragment
1166 protected function render_action_menu_link(action_menu_link $action) {
1167 static $actioncount = 0;
1168 $actioncount++;
1170 $comparetoalt = '';
1171 $text = '';
1172 if (!$action->icon || $action->primary === false) {
1173 $text .= html_writer::start_tag('span', array('class'=>'menu-action-text', 'id' => 'actionmenuaction-'.$actioncount));
1174 if ($action->text instanceof renderable) {
1175 $text .= $this->render($action->text);
1176 } else {
1177 $text .= $action->text;
1178 $comparetoalt = (string)$action->text;
1180 $text .= html_writer::end_tag('span');
1183 $icon = '';
1184 if ($action->icon) {
1185 $icon = $action->icon;
1186 if ($action->primary || !$action->actionmenu->will_be_enhanced()) {
1187 $action->attributes['title'] = $action->text;
1189 if (!$action->primary && $action->actionmenu->will_be_enhanced()) {
1190 if ((string)$icon->attributes['alt'] === $comparetoalt) {
1191 $icon->attributes['alt'] = '';
1193 if (isset($icon->attributes['title']) && (string)$icon->attributes['title'] === $comparetoalt) {
1194 unset($icon->attributes['title']);
1197 $icon = $this->render($icon);
1200 // A disabled link is rendered as formatted text.
1201 if (!empty($action->attributes['disabled'])) {
1202 // Do not use div here due to nesting restriction in xhtml strict.
1203 return html_writer::tag('span', $icon.$text, array('class'=>'currentlink', 'role' => 'menuitem'));
1206 $attributes = $action->attributes;
1207 unset($action->attributes['disabled']);
1208 $attributes['href'] = $action->url;
1209 if ($text !== '') {
1210 $attributes['aria-labelledby'] = 'actionmenuaction-'.$actioncount;
1213 return html_writer::tag('a', $icon.$text, $attributes);
1217 * Renders a primary action_menu_filler item.
1219 * @param action_menu_link_filler $action
1220 * @return string HTML fragment
1222 protected function render_action_menu_filler(action_menu_filler $action) {
1223 return html_writer::span('&nbsp;', 'filler');
1227 * Renders a primary action_menu_link item.
1229 * @param action_menu_link_primary $action
1230 * @return string HTML fragment
1232 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1233 return $this->render_action_menu_link($action);
1237 * Renders a secondary action_menu_link item.
1239 * @param action_menu_link_secondary $action
1240 * @return string HTML fragment
1242 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1243 return $this->render_action_menu_link($action);
1247 * Prints a nice side block with an optional header.
1249 * The content is described
1250 * by a {@link core_renderer::block_contents} object.
1252 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1253 * <div class="header"></div>
1254 * <div class="content">
1255 * ...CONTENT...
1256 * <div class="footer">
1257 * </div>
1258 * </div>
1259 * <div class="annotation">
1260 * </div>
1261 * </div>
1263 * @param block_contents $bc HTML for the content
1264 * @param string $region the region the block is appearing in.
1265 * @return string the HTML to be output.
1267 public function block(block_contents $bc, $region) {
1268 $bc = clone($bc); // Avoid messing up the object passed in.
1269 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1270 $bc->collapsible = block_contents::NOT_HIDEABLE;
1272 if (!empty($bc->blockinstanceid)) {
1273 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1275 $skiptitle = strip_tags($bc->title);
1276 if ($bc->blockinstanceid && !empty($skiptitle)) {
1277 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1278 } else if (!empty($bc->arialabel)) {
1279 $bc->attributes['aria-label'] = $bc->arialabel;
1281 if ($bc->dockable) {
1282 $bc->attributes['data-dockable'] = 1;
1284 if ($bc->collapsible == block_contents::HIDDEN) {
1285 $bc->add_class('hidden');
1287 if (!empty($bc->controls)) {
1288 $bc->add_class('block_with_controls');
1292 if (empty($skiptitle)) {
1293 $output = '';
1294 $skipdest = '';
1295 } else {
1296 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
1297 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
1300 $output .= html_writer::start_tag('div', $bc->attributes);
1302 $output .= $this->block_header($bc);
1303 $output .= $this->block_content($bc);
1305 $output .= html_writer::end_tag('div');
1307 $output .= $this->block_annotation($bc);
1309 $output .= $skipdest;
1311 $this->init_block_hider_js($bc);
1312 return $output;
1316 * Produces a header for a block
1318 * @param block_contents $bc
1319 * @return string
1321 protected function block_header(block_contents $bc) {
1323 $title = '';
1324 if ($bc->title) {
1325 $attributes = array();
1326 if ($bc->blockinstanceid) {
1327 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1329 $title = html_writer::tag('h2', $bc->title, $attributes);
1332 $blockid = null;
1333 if (isset($bc->attributes['id'])) {
1334 $blockid = $bc->attributes['id'];
1336 $controlshtml = $this->block_controls($bc->controls, $blockid);
1338 $output = '';
1339 if ($title || $controlshtml) {
1340 $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'));
1342 return $output;
1346 * Produces the content area for a block
1348 * @param block_contents $bc
1349 * @return string
1351 protected function block_content(block_contents $bc) {
1352 $output = html_writer::start_tag('div', array('class' => 'content'));
1353 if (!$bc->title && !$this->block_controls($bc->controls)) {
1354 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1356 $output .= $bc->content;
1357 $output .= $this->block_footer($bc);
1358 $output .= html_writer::end_tag('div');
1360 return $output;
1364 * Produces the footer for a block
1366 * @param block_contents $bc
1367 * @return string
1369 protected function block_footer(block_contents $bc) {
1370 $output = '';
1371 if ($bc->footer) {
1372 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
1374 return $output;
1378 * Produces the annotation for a block
1380 * @param block_contents $bc
1381 * @return string
1383 protected function block_annotation(block_contents $bc) {
1384 $output = '';
1385 if ($bc->annotation) {
1386 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
1388 return $output;
1392 * Calls the JS require function to hide a block.
1394 * @param block_contents $bc A block_contents object
1396 protected function init_block_hider_js(block_contents $bc) {
1397 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
1398 $config = new stdClass;
1399 $config->id = $bc->attributes['id'];
1400 $config->title = strip_tags($bc->title);
1401 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1402 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1403 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1405 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1406 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
1411 * Render the contents of a block_list.
1413 * @param array $icons the icon for each item.
1414 * @param array $items the content of each item.
1415 * @return string HTML
1417 public function list_block_contents($icons, $items) {
1418 $row = 0;
1419 $lis = array();
1420 foreach ($items as $key => $string) {
1421 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1422 if (!empty($icons[$key])) { //test if the content has an assigned icon
1423 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1425 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1426 $item .= html_writer::end_tag('li');
1427 $lis[] = $item;
1428 $row = 1 - $row; // Flip even/odd.
1430 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1434 * Output all the blocks in a particular region.
1436 * @param string $region the name of a region on this page.
1437 * @return string the HTML to be output.
1439 public function blocks_for_region($region) {
1440 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1441 $blocks = $this->page->blocks->get_blocks_for_region($region);
1442 $lastblock = null;
1443 $zones = array();
1444 foreach ($blocks as $block) {
1445 $zones[] = $block->title;
1447 $output = '';
1449 foreach ($blockcontents as $bc) {
1450 if ($bc instanceof block_contents) {
1451 $output .= $this->block($bc, $region);
1452 $lastblock = $bc->title;
1453 } else if ($bc instanceof block_move_target) {
1454 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1455 } else {
1456 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1459 return $output;
1463 * Output a place where the block that is currently being moved can be dropped.
1465 * @param block_move_target $target with the necessary details.
1466 * @param array $zones array of areas where the block can be moved to
1467 * @param string $previous the block located before the area currently being rendered.
1468 * @param string $region the name of the region
1469 * @return string the HTML to be output.
1471 public function block_move_target($target, $zones, $previous, $region) {
1472 if ($previous == null) {
1473 if (empty($zones)) {
1474 // There are no zones, probably because there are no blocks.
1475 $regions = $this->page->theme->get_all_block_regions();
1476 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1477 } else {
1478 $position = get_string('moveblockbefore', 'block', $zones[0]);
1480 } else {
1481 $position = get_string('moveblockafter', 'block', $previous);
1483 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1487 * Renders a special html link with attached action
1489 * Theme developers: DO NOT OVERRIDE! Please override function
1490 * {@link core_renderer::render_action_link()} instead.
1492 * @param string|moodle_url $url
1493 * @param string $text HTML fragment
1494 * @param component_action $action
1495 * @param array $attributes associative array of html link attributes + disabled
1496 * @param pix_icon optional pix icon to render with the link
1497 * @return string HTML fragment
1499 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1500 if (!($url instanceof moodle_url)) {
1501 $url = new moodle_url($url);
1503 $link = new action_link($url, $text, $action, $attributes, $icon);
1505 return $this->render($link);
1509 * Renders an action_link object.
1511 * The provided link is renderer and the HTML returned. At the same time the
1512 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1514 * @param action_link $link
1515 * @return string HTML fragment
1517 protected function render_action_link(action_link $link) {
1518 global $CFG;
1520 $text = '';
1521 if ($link->icon) {
1522 $text .= $this->render($link->icon);
1525 if ($link->text instanceof renderable) {
1526 $text .= $this->render($link->text);
1527 } else {
1528 $text .= $link->text;
1531 // A disabled link is rendered as formatted text
1532 if (!empty($link->attributes['disabled'])) {
1533 // do not use div here due to nesting restriction in xhtml strict
1534 return html_writer::tag('span', $text, array('class'=>'currentlink'));
1537 $attributes = $link->attributes;
1538 unset($link->attributes['disabled']);
1539 $attributes['href'] = $link->url;
1541 if ($link->actions) {
1542 if (empty($attributes['id'])) {
1543 $id = html_writer::random_id('action_link');
1544 $attributes['id'] = $id;
1545 } else {
1546 $id = $attributes['id'];
1548 foreach ($link->actions as $action) {
1549 $this->add_action_handler($action, $id);
1553 return html_writer::tag('a', $text, $attributes);
1558 * Renders an action_icon.
1560 * This function uses the {@link core_renderer::action_link()} method for the
1561 * most part. What it does different is prepare the icon as HTML and use it
1562 * as the link text.
1564 * Theme developers: If you want to change how action links and/or icons are rendered,
1565 * consider overriding function {@link core_renderer::render_action_link()} and
1566 * {@link core_renderer::render_pix_icon()}.
1568 * @param string|moodle_url $url A string URL or moodel_url
1569 * @param pix_icon $pixicon
1570 * @param component_action $action
1571 * @param array $attributes associative array of html link attributes + disabled
1572 * @param bool $linktext show title next to image in link
1573 * @return string HTML fragment
1575 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1576 if (!($url instanceof moodle_url)) {
1577 $url = new moodle_url($url);
1579 $attributes = (array)$attributes;
1581 if (empty($attributes['class'])) {
1582 // let ppl override the class via $options
1583 $attributes['class'] = 'action-icon';
1586 $icon = $this->render($pixicon);
1588 if ($linktext) {
1589 $text = $pixicon->attributes['alt'];
1590 } else {
1591 $text = '';
1594 return $this->action_link($url, $text.$icon, $action, $attributes);
1598 * Print a message along with button choices for Continue/Cancel
1600 * If a string or moodle_url is given instead of a single_button, method defaults to post.
1602 * @param string $message The question to ask the user
1603 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1604 * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
1605 * @return string HTML fragment
1607 public function confirm($message, $continue, $cancel) {
1608 if ($continue instanceof single_button) {
1609 // ok
1610 } else if (is_string($continue)) {
1611 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1612 } else if ($continue instanceof moodle_url) {
1613 $continue = new single_button($continue, get_string('continue'), 'post');
1614 } else {
1615 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1618 if ($cancel instanceof single_button) {
1619 // ok
1620 } else if (is_string($cancel)) {
1621 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1622 } else if ($cancel instanceof moodle_url) {
1623 $cancel = new single_button($cancel, get_string('cancel'), 'get');
1624 } else {
1625 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
1628 $output = $this->box_start('generalbox', 'notice');
1629 $output .= html_writer::tag('p', $message);
1630 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
1631 $output .= $this->box_end();
1632 return $output;
1636 * Returns a form with a single button.
1638 * Theme developers: DO NOT OVERRIDE! Please override function
1639 * {@link core_renderer::render_single_button()} instead.
1641 * @param string|moodle_url $url
1642 * @param string $label button text
1643 * @param string $method get or post submit method
1644 * @param array $options associative array {disabled, title, etc.}
1645 * @return string HTML fragment
1647 public function single_button($url, $label, $method='post', array $options=null) {
1648 if (!($url instanceof moodle_url)) {
1649 $url = new moodle_url($url);
1651 $button = new single_button($url, $label, $method);
1653 foreach ((array)$options as $key=>$value) {
1654 if (array_key_exists($key, $button)) {
1655 $button->$key = $value;
1659 return $this->render($button);
1663 * Renders a single button widget.
1665 * This will return HTML to display a form containing a single button.
1667 * @param single_button $button
1668 * @return string HTML fragment
1670 protected function render_single_button(single_button $button) {
1671 $attributes = array('type' => 'submit',
1672 'value' => $button->label,
1673 'disabled' => $button->disabled ? 'disabled' : null,
1674 'title' => $button->tooltip);
1676 if ($button->actions) {
1677 $id = html_writer::random_id('single_button');
1678 $attributes['id'] = $id;
1679 foreach ($button->actions as $action) {
1680 $this->add_action_handler($action, $id);
1684 // first the input element
1685 $output = html_writer::empty_tag('input', $attributes);
1687 // then hidden fields
1688 $params = $button->url->params();
1689 if ($button->method === 'post') {
1690 $params['sesskey'] = sesskey();
1692 foreach ($params as $var => $val) {
1693 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1696 // then div wrapper for xhtml strictness
1697 $output = html_writer::tag('div', $output);
1699 // now the form itself around it
1700 if ($button->method === 'get') {
1701 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1702 } else {
1703 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1705 if ($url === '') {
1706 $url = '#'; // there has to be always some action
1708 $attributes = array('method' => $button->method,
1709 'action' => $url,
1710 'id' => $button->formid);
1711 $output = html_writer::tag('form', $output, $attributes);
1713 // and finally one more wrapper with class
1714 return html_writer::tag('div', $output, array('class' => $button->class));
1718 * Returns a form with a single select widget.
1720 * Theme developers: DO NOT OVERRIDE! Please override function
1721 * {@link core_renderer::render_single_select()} instead.
1723 * @param moodle_url $url form action target, includes hidden fields
1724 * @param string $name name of selection field - the changing parameter in url
1725 * @param array $options list of options
1726 * @param string $selected selected element
1727 * @param array $nothing
1728 * @param string $formid
1729 * @return string HTML fragment
1731 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1732 if (!($url instanceof moodle_url)) {
1733 $url = new moodle_url($url);
1735 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
1737 return $this->render($select);
1741 * Internal implementation of single_select rendering
1743 * @param single_select $select
1744 * @return string HTML fragment
1746 protected function render_single_select(single_select $select) {
1747 $select = clone($select);
1748 if (empty($select->formid)) {
1749 $select->formid = html_writer::random_id('single_select_f');
1752 $output = '';
1753 $params = $select->url->params();
1754 if ($select->method === 'post') {
1755 $params['sesskey'] = sesskey();
1757 foreach ($params as $name=>$value) {
1758 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1761 if (empty($select->attributes['id'])) {
1762 $select->attributes['id'] = html_writer::random_id('single_select');
1765 if ($select->disabled) {
1766 $select->attributes['disabled'] = 'disabled';
1769 if ($select->tooltip) {
1770 $select->attributes['title'] = $select->tooltip;
1773 $select->attributes['class'] = 'autosubmit';
1774 if ($select->class) {
1775 $select->attributes['class'] .= ' ' . $select->class;
1778 if ($select->label) {
1779 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1782 if ($select->helpicon instanceof help_icon) {
1783 $output .= $this->render($select->helpicon);
1785 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1787 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1788 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1790 $nothing = empty($select->nothing) ? false : key($select->nothing);
1791 $this->page->requires->yui_module('moodle-core-formautosubmit',
1792 'M.core.init_formautosubmit',
1793 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1796 // then div wrapper for xhtml strictness
1797 $output = html_writer::tag('div', $output);
1799 // now the form itself around it
1800 if ($select->method === 'get') {
1801 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1802 } else {
1803 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1805 $formattributes = array('method' => $select->method,
1806 'action' => $url,
1807 'id' => $select->formid);
1808 $output = html_writer::tag('form', $output, $formattributes);
1810 // and finally one more wrapper with class
1811 return html_writer::tag('div', $output, array('class' => $select->class));
1815 * Returns a form with a url select widget.
1817 * Theme developers: DO NOT OVERRIDE! Please override function
1818 * {@link core_renderer::render_url_select()} instead.
1820 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1821 * @param string $selected selected element
1822 * @param array $nothing
1823 * @param string $formid
1824 * @return string HTML fragment
1826 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
1827 $select = new url_select($urls, $selected, $nothing, $formid);
1828 return $this->render($select);
1832 * Internal implementation of url_select rendering
1834 * @param url_select $select
1835 * @return string HTML fragment
1837 protected function render_url_select(url_select $select) {
1838 global $CFG;
1840 $select = clone($select);
1841 if (empty($select->formid)) {
1842 $select->formid = html_writer::random_id('url_select_f');
1845 if (empty($select->attributes['id'])) {
1846 $select->attributes['id'] = html_writer::random_id('url_select');
1849 if ($select->disabled) {
1850 $select->attributes['disabled'] = 'disabled';
1853 if ($select->tooltip) {
1854 $select->attributes['title'] = $select->tooltip;
1857 $output = '';
1859 if ($select->label) {
1860 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
1863 $classes = array();
1864 if (!$select->showbutton) {
1865 $classes[] = 'autosubmit';
1867 if ($select->class) {
1868 $classes[] = $select->class;
1870 if (count($classes)) {
1871 $select->attributes['class'] = implode(' ', $classes);
1874 if ($select->helpicon instanceof help_icon) {
1875 $output .= $this->render($select->helpicon);
1878 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1879 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
1880 $urls = array();
1881 foreach ($select->urls as $k=>$v) {
1882 if (is_array($v)) {
1883 // optgroup structure
1884 foreach ($v as $optgrouptitle => $optgroupoptions) {
1885 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1886 if (empty($optionurl)) {
1887 $safeoptionurl = '';
1888 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1889 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1890 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1891 } else if (strpos($optionurl, '/') !== 0) {
1892 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1893 continue;
1894 } else {
1895 $safeoptionurl = $optionurl;
1897 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1900 } else {
1901 // plain list structure
1902 if (empty($k)) {
1903 // nothing selected option
1904 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1905 $k = str_replace($CFG->wwwroot, '', $k);
1906 } else if (strpos($k, '/') !== 0) {
1907 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1908 continue;
1910 $urls[$k] = $v;
1913 $selected = $select->selected;
1914 if (!empty($selected)) {
1915 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1916 $selected = str_replace($CFG->wwwroot, '', $selected);
1917 } else if (strpos($selected, '/') !== 0) {
1918 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
1922 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
1923 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
1925 if (!$select->showbutton) {
1926 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
1927 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
1928 $nothing = empty($select->nothing) ? false : key($select->nothing);
1929 $this->page->requires->yui_module('moodle-core-formautosubmit',
1930 'M.core.init_formautosubmit',
1931 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1933 } else {
1934 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1937 // then div wrapper for xhtml strictness
1938 $output = html_writer::tag('div', $output);
1940 // now the form itself around it
1941 $formattributes = array('method' => 'post',
1942 'action' => new moodle_url('/course/jumpto.php'),
1943 'id' => $select->formid);
1944 $output = html_writer::tag('form', $output, $formattributes);
1946 // and finally one more wrapper with class
1947 return html_writer::tag('div', $output, array('class' => $select->class));
1951 * Returns a string containing a link to the user documentation.
1952 * Also contains an icon by default. Shown to teachers and admin only.
1954 * @param string $path The page link after doc root and language, no leading slash.
1955 * @param string $text The text to be displayed for the link
1956 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
1957 * @return string
1959 public function doc_link($path, $text = '', $forcepopup = false) {
1960 global $CFG;
1962 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
1964 $url = new moodle_url(get_docs_url($path));
1966 $attributes = array('href'=>$url);
1967 if (!empty($CFG->doctonewwindow) || $forcepopup) {
1968 $attributes['class'] = 'helplinkpopup';
1971 return html_writer::tag('a', $icon.$text, $attributes);
1975 * Return HTML for a pix_icon.
1977 * Theme developers: DO NOT OVERRIDE! Please override function
1978 * {@link core_renderer::render_pix_icon()} instead.
1980 * @param string $pix short pix name
1981 * @param string $alt mandatory alt attribute
1982 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
1983 * @param array $attributes htm lattributes
1984 * @return string HTML fragment
1986 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
1987 $icon = new pix_icon($pix, $alt, $component, $attributes);
1988 return $this->render($icon);
1992 * Renders a pix_icon widget and returns the HTML to display it.
1994 * @param pix_icon $icon
1995 * @return string HTML fragment
1997 protected function render_pix_icon(pix_icon $icon) {
1998 $attributes = $icon->attributes;
1999 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
2000 return html_writer::empty_tag('img', $attributes);
2004 * Return HTML to display an emoticon icon.
2006 * @param pix_emoticon $emoticon
2007 * @return string HTML fragment
2009 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2010 $attributes = $emoticon->attributes;
2011 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
2012 return html_writer::empty_tag('img', $attributes);
2016 * Produces the html that represents this rating in the UI
2018 * @param rating $rating the page object on which this rating will appear
2019 * @return string
2021 function render_rating(rating $rating) {
2022 global $CFG, $USER;
2024 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2025 return null;//ratings are turned off
2028 $ratingmanager = new rating_manager();
2029 // Initialise the JavaScript so ratings can be done by AJAX.
2030 $ratingmanager->initialise_rating_javascript($this->page);
2032 $strrate = get_string("rate", "rating");
2033 $ratinghtml = ''; //the string we'll return
2035 // permissions check - can they view the aggregate?
2036 if ($rating->user_can_view_aggregate()) {
2038 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2039 $aggregatestr = $rating->get_aggregate_string();
2041 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2042 if ($rating->count > 0) {
2043 $countstr = "({$rating->count})";
2044 } else {
2045 $countstr = '-';
2047 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2049 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2050 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2052 $nonpopuplink = $rating->get_view_ratings_url();
2053 $popuplink = $rating->get_view_ratings_url(true);
2055 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2056 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
2057 } else {
2058 $ratinghtml .= $aggregatehtml;
2062 $formstart = null;
2063 // if the item doesn't belong to the current user, the user has permission to rate
2064 // and we're within the assessable period
2065 if ($rating->user_can_rate()) {
2067 $rateurl = $rating->get_rate_url();
2068 $inputs = $rateurl->params();
2070 //start the rating form
2071 $formattrs = array(
2072 'id' => "postrating{$rating->itemid}",
2073 'class' => 'postratingform',
2074 'method' => 'post',
2075 'action' => $rateurl->out_omit_querystring()
2077 $formstart = html_writer::start_tag('form', $formattrs);
2078 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2080 // add the hidden inputs
2081 foreach ($inputs as $name => $value) {
2082 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2083 $formstart .= html_writer::empty_tag('input', $attributes);
2086 if (empty($ratinghtml)) {
2087 $ratinghtml .= $strrate.': ';
2089 $ratinghtml = $formstart.$ratinghtml;
2091 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2092 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2093 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2094 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2096 //output submit button
2097 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2099 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2100 $ratinghtml .= html_writer::empty_tag('input', $attributes);
2102 if (!$rating->settings->scale->isnumeric) {
2103 // If a global scale, try to find current course ID from the context
2104 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2105 $courseid = $coursecontext->instanceid;
2106 } else {
2107 $courseid = $rating->settings->scale->courseid;
2109 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2111 $ratinghtml .= html_writer::end_tag('span');
2112 $ratinghtml .= html_writer::end_tag('div');
2113 $ratinghtml .= html_writer::end_tag('form');
2116 return $ratinghtml;
2120 * Centered heading with attached help button (same title text)
2121 * and optional icon attached.
2123 * @param string $text A heading text
2124 * @param string $helpidentifier The keyword that defines a help page
2125 * @param string $component component name
2126 * @param string|moodle_url $icon
2127 * @param string $iconalt icon alt text
2128 * @param int $level The level of importance of the heading. Defaulting to 2
2129 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2130 * @return string HTML fragment
2132 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2133 $image = '';
2134 if ($icon) {
2135 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2138 $help = '';
2139 if ($helpidentifier) {
2140 $help = $this->help_icon($helpidentifier, $component);
2143 return $this->heading($image.$text.$help, $level, $classnames);
2147 * Returns HTML to display a help icon.
2149 * @deprecated since Moodle 2.0
2151 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2152 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2156 * Returns HTML to display a help icon.
2158 * Theme developers: DO NOT OVERRIDE! Please override function
2159 * {@link core_renderer::render_help_icon()} instead.
2161 * @param string $identifier The keyword that defines a help page
2162 * @param string $component component name
2163 * @param string|bool $linktext true means use $title as link text, string means link text value
2164 * @return string HTML fragment
2166 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2167 $icon = new help_icon($identifier, $component);
2168 $icon->diag_strings();
2169 if ($linktext === true) {
2170 $icon->linktext = get_string($icon->identifier, $icon->component);
2171 } else if (!empty($linktext)) {
2172 $icon->linktext = $linktext;
2174 return $this->render($icon);
2178 * Implementation of user image rendering.
2180 * @param help_icon $helpicon A help icon instance
2181 * @return string HTML fragment
2183 protected function render_help_icon(help_icon $helpicon) {
2184 global $CFG;
2186 // first get the help image icon
2187 $src = $this->pix_url('help');
2189 $title = get_string($helpicon->identifier, $helpicon->component);
2191 if (empty($helpicon->linktext)) {
2192 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
2193 } else {
2194 $alt = get_string('helpwiththis');
2197 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
2198 $output = html_writer::empty_tag('img', $attributes);
2200 // add the link text if given
2201 if (!empty($helpicon->linktext)) {
2202 // the spacing has to be done through CSS
2203 $output .= $helpicon->linktext;
2206 // now create the link around it - we need https on loginhttps pages
2207 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
2209 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
2210 $title = get_string('helpprefix2', '', trim($title, ". \t"));
2212 $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true', 'target'=>'_blank');
2213 $output = html_writer::tag('a', $output, $attributes);
2215 // and finally span
2216 return html_writer::tag('span', $output, array('class' => 'helptooltip'));
2220 * Returns HTML to display a scale help icon.
2222 * @param int $courseid
2223 * @param stdClass $scale instance
2224 * @return string HTML fragment
2226 public function help_icon_scale($courseid, stdClass $scale) {
2227 global $CFG;
2229 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2231 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2233 $scaleid = abs($scale->id);
2235 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2236 $action = new popup_action('click', $link, 'ratingscale');
2238 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2242 * Creates and returns a spacer image with optional line break.
2244 * @param array $attributes Any HTML attributes to add to the spaced.
2245 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2246 * laxy do it with CSS which is a much better solution.
2247 * @return string HTML fragment
2249 public function spacer(array $attributes = null, $br = false) {
2250 $attributes = (array)$attributes;
2251 if (empty($attributes['width'])) {
2252 $attributes['width'] = 1;
2254 if (empty($attributes['height'])) {
2255 $attributes['height'] = 1;
2257 $attributes['class'] = 'spacer';
2259 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2261 if (!empty($br)) {
2262 $output .= '<br />';
2265 return $output;
2269 * Returns HTML to display the specified user's avatar.
2271 * User avatar may be obtained in two ways:
2272 * <pre>
2273 * // Option 1: (shortcut for simple cases, preferred way)
2274 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2275 * $OUTPUT->user_picture($user, array('popup'=>true));
2277 * // Option 2:
2278 * $userpic = new user_picture($user);
2279 * // Set properties of $userpic
2280 * $userpic->popup = true;
2281 * $OUTPUT->render($userpic);
2282 * </pre>
2284 * Theme developers: DO NOT OVERRIDE! Please override function
2285 * {@link core_renderer::render_user_picture()} instead.
2287 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2288 * If any of these are missing, the database is queried. Avoid this
2289 * if at all possible, particularly for reports. It is very bad for performance.
2290 * @param array $options associative array with user picture options, used only if not a user_picture object,
2291 * options are:
2292 * - courseid=$this->page->course->id (course id of user profile in link)
2293 * - size=35 (size of image)
2294 * - link=true (make image clickable - the link leads to user profile)
2295 * - popup=false (open in popup)
2296 * - alttext=true (add image alt attribute)
2297 * - class = image class attribute (default 'userpicture')
2298 * - visibletoscreenreaders=true (whether to be visible to screen readers)
2299 * @return string HTML fragment
2301 public function user_picture(stdClass $user, array $options = null) {
2302 $userpicture = new user_picture($user);
2303 foreach ((array)$options as $key=>$value) {
2304 if (array_key_exists($key, $userpicture)) {
2305 $userpicture->$key = $value;
2308 return $this->render($userpicture);
2312 * Internal implementation of user image rendering.
2314 * @param user_picture $userpicture
2315 * @return string
2317 protected function render_user_picture(user_picture $userpicture) {
2318 global $CFG, $DB;
2320 $user = $userpicture->user;
2322 if ($userpicture->alttext) {
2323 if (!empty($user->imagealt)) {
2324 $alt = $user->imagealt;
2325 } else {
2326 $alt = get_string('pictureof', '', fullname($user));
2328 } else {
2329 $alt = '';
2332 if (empty($userpicture->size)) {
2333 $size = 35;
2334 } else if ($userpicture->size === true or $userpicture->size == 1) {
2335 $size = 100;
2336 } else {
2337 $size = $userpicture->size;
2340 $class = $userpicture->class;
2342 if ($user->picture == 0) {
2343 $class .= ' defaultuserpic';
2346 $src = $userpicture->get_url($this->page, $this);
2348 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
2349 if (!$userpicture->visibletoscreenreaders) {
2350 $attributes['role'] = 'presentation';
2353 // get the image html output fisrt
2354 $output = html_writer::empty_tag('img', $attributes);
2356 // then wrap it in link if needed
2357 if (!$userpicture->link) {
2358 return $output;
2361 if (empty($userpicture->courseid)) {
2362 $courseid = $this->page->course->id;
2363 } else {
2364 $courseid = $userpicture->courseid;
2367 if ($courseid == SITEID) {
2368 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2369 } else {
2370 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2373 $attributes = array('href'=>$url);
2374 if (!$userpicture->visibletoscreenreaders) {
2375 $attributes['role'] = 'presentation';
2376 $attributes['tabindex'] = '-1';
2377 $attributes['aria-hidden'] = 'true';
2380 if ($userpicture->popup) {
2381 $id = html_writer::random_id('userpicture');
2382 $attributes['id'] = $id;
2383 $this->add_action_handler(new popup_action('click', $url), $id);
2386 return html_writer::tag('a', $output, $attributes);
2390 * Internal implementation of file tree viewer items rendering.
2392 * @param array $dir
2393 * @return string
2395 public function htmllize_file_tree($dir) {
2396 if (empty($dir['subdirs']) and empty($dir['files'])) {
2397 return '';
2399 $result = '<ul>';
2400 foreach ($dir['subdirs'] as $subdir) {
2401 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2403 foreach ($dir['files'] as $file) {
2404 $filename = $file->get_filename();
2405 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2407 $result .= '</ul>';
2409 return $result;
2413 * Returns HTML to display the file picker
2415 * <pre>
2416 * $OUTPUT->file_picker($options);
2417 * </pre>
2419 * Theme developers: DO NOT OVERRIDE! Please override function
2420 * {@link core_renderer::render_file_picker()} instead.
2422 * @param array $options associative array with file manager options
2423 * options are:
2424 * maxbytes=>-1,
2425 * itemid=>0,
2426 * client_id=>uniqid(),
2427 * acepted_types=>'*',
2428 * return_types=>FILE_INTERNAL,
2429 * context=>$PAGE->context
2430 * @return string HTML fragment
2432 public function file_picker($options) {
2433 $fp = new file_picker($options);
2434 return $this->render($fp);
2438 * Internal implementation of file picker rendering.
2440 * @param file_picker $fp
2441 * @return string
2443 public function render_file_picker(file_picker $fp) {
2444 global $CFG, $OUTPUT, $USER;
2445 $options = $fp->options;
2446 $client_id = $options->client_id;
2447 $strsaved = get_string('filesaved', 'repository');
2448 $straddfile = get_string('openpicker', 'repository');
2449 $strloading = get_string('loading', 'repository');
2450 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2451 $strdroptoupload = get_string('droptoupload', 'moodle');
2452 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2454 $currentfile = $options->currentfile;
2455 if (empty($currentfile)) {
2456 $currentfile = '';
2457 } else {
2458 $currentfile .= ' - ';
2460 if ($options->maxbytes) {
2461 $size = $options->maxbytes;
2462 } else {
2463 $size = get_max_upload_file_size();
2465 if ($size == -1) {
2466 $maxsize = '';
2467 } else {
2468 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2470 if ($options->buttonname) {
2471 $buttonname = ' name="' . $options->buttonname . '"';
2472 } else {
2473 $buttonname = '';
2475 $html = <<<EOD
2476 <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2477 $icon_progress
2478 </div>
2479 <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2480 <div>
2481 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2482 <span> $maxsize </span>
2483 </div>
2484 EOD;
2485 if ($options->env != 'url') {
2486 $html .= <<<EOD
2487 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2488 <div class="filepicker-filename">
2489 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
2490 <div class="dndupload-progressbars"></div>
2491 </div>
2492 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
2493 </div>
2494 EOD;
2496 $html .= '</div>';
2497 return $html;
2501 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
2503 * @param string $cmid the course_module id.
2504 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2505 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2507 public function update_module_button($cmid, $modulename) {
2508 global $CFG;
2509 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2510 $modulename = get_string('modulename', $modulename);
2511 $string = get_string('updatethis', '', $modulename);
2512 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2513 return $this->single_button($url, $string);
2514 } else {
2515 return '';
2520 * Returns HTML to display a "Turn editing on/off" button in a form.
2522 * @param moodle_url $url The URL + params to send through when clicking the button
2523 * @return string HTML the button
2525 public function edit_button(moodle_url $url) {
2527 $url->param('sesskey', sesskey());
2528 if ($this->page->user_is_editing()) {
2529 $url->param('edit', 'off');
2530 $editstring = get_string('turneditingoff');
2531 } else {
2532 $url->param('edit', 'on');
2533 $editstring = get_string('turneditingon');
2536 return $this->single_button($url, $editstring);
2540 * Returns HTML to display a simple button to close a window
2542 * @param string $text The lang string for the button's label (already output from get_string())
2543 * @return string html fragment
2545 public function close_window_button($text='') {
2546 if (empty($text)) {
2547 $text = get_string('closewindow');
2549 $button = new single_button(new moodle_url('#'), $text, 'get');
2550 $button->add_action(new component_action('click', 'close_window'));
2552 return $this->container($this->render($button), 'closewindow');
2556 * Output an error message. By default wraps the error message in <span class="error">.
2557 * If the error message is blank, nothing is output.
2559 * @param string $message the error message.
2560 * @return string the HTML to output.
2562 public function error_text($message) {
2563 if (empty($message)) {
2564 return '';
2566 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2567 return html_writer::tag('span', $message, array('class' => 'error'));
2571 * Do not call this function directly.
2573 * To terminate the current script with a fatal error, call the {@link print_error}
2574 * function, or throw an exception. Doing either of those things will then call this
2575 * function to display the error, before terminating the execution.
2577 * @param string $message The message to output
2578 * @param string $moreinfourl URL where more info can be found about the error
2579 * @param string $link Link for the Continue button
2580 * @param array $backtrace The execution backtrace
2581 * @param string $debuginfo Debugging information
2582 * @return string the HTML to output.
2584 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2585 global $CFG;
2587 $output = '';
2588 $obbuffer = '';
2590 if ($this->has_started()) {
2591 // we can not always recover properly here, we have problems with output buffering,
2592 // html tables, etc.
2593 $output .= $this->opencontainers->pop_all_but_last();
2595 } else {
2596 // It is really bad if library code throws exception when output buffering is on,
2597 // because the buffered text would be printed before our start of page.
2598 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2599 error_reporting(0); // disable notices from gzip compression, etc.
2600 while (ob_get_level() > 0) {
2601 $buff = ob_get_clean();
2602 if ($buff === false) {
2603 break;
2605 $obbuffer .= $buff;
2607 error_reporting($CFG->debug);
2609 // Output not yet started.
2610 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2611 if (empty($_SERVER['HTTP_RANGE'])) {
2612 @header($protocol . ' 404 Not Found');
2613 } else {
2614 // Must stop byteserving attempts somehow,
2615 // this is weird but Chrome PDF viewer can be stopped only with 407!
2616 @header($protocol . ' 407 Proxy Authentication Required');
2619 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2620 $this->page->set_url('/'); // no url
2621 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2622 $this->page->set_title(get_string('error'));
2623 $this->page->set_heading($this->page->course->fullname);
2624 $output .= $this->header();
2627 $message = '<p class="errormessage">' . $message . '</p>'.
2628 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2629 get_string('moreinformation') . '</a></p>';
2630 if (empty($CFG->rolesactive)) {
2631 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2632 //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.
2634 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
2636 if ($CFG->debugdeveloper) {
2637 if (!empty($debuginfo)) {
2638 $debuginfo = s($debuginfo); // removes all nasty JS
2639 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2640 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
2642 if (!empty($backtrace)) {
2643 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2645 if ($obbuffer !== '' ) {
2646 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2650 if (empty($CFG->rolesactive)) {
2651 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2652 } else if (!empty($link)) {
2653 $output .= $this->continue_button($link);
2656 $output .= $this->footer();
2658 // Padding to encourage IE to display our error page, rather than its own.
2659 $output .= str_repeat(' ', 512);
2661 return $output;
2665 * Output a notification (that is, a status message about something that has
2666 * just happened).
2668 * @param string $message the message to print out
2669 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2670 * @return string the HTML to output.
2672 public function notification($message, $classes = 'notifyproblem') {
2673 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
2677 * Returns HTML to display a continue button that goes to a particular URL.
2679 * @param string|moodle_url $url The url the button goes to.
2680 * @return string the HTML to output.
2682 public function continue_button($url) {
2683 if (!($url instanceof moodle_url)) {
2684 $url = new moodle_url($url);
2686 $button = new single_button($url, get_string('continue'), 'get');
2687 $button->class = 'continuebutton';
2689 return $this->render($button);
2693 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
2695 * Theme developers: DO NOT OVERRIDE! Please override function
2696 * {@link core_renderer::render_paging_bar()} instead.
2698 * @param int $totalcount The total number of entries available to be paged through
2699 * @param int $page The page you are currently viewing
2700 * @param int $perpage The number of entries that should be shown per page
2701 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2702 * @param string $pagevar name of page parameter that holds the page number
2703 * @return string the HTML to output.
2705 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2706 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2707 return $this->render($pb);
2711 * Internal implementation of paging bar rendering.
2713 * @param paging_bar $pagingbar
2714 * @return string
2716 protected function render_paging_bar(paging_bar $pagingbar) {
2717 $output = '';
2718 $pagingbar = clone($pagingbar);
2719 $pagingbar->prepare($this, $this->page, $this->target);
2721 if ($pagingbar->totalcount > $pagingbar->perpage) {
2722 $output .= get_string('page') . ':';
2724 if (!empty($pagingbar->previouslink)) {
2725 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
2728 if (!empty($pagingbar->firstlink)) {
2729 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
2732 foreach ($pagingbar->pagelinks as $link) {
2733 $output .= "&#160;&#160;$link";
2736 if (!empty($pagingbar->lastlink)) {
2737 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
2740 if (!empty($pagingbar->nextlink)) {
2741 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
2745 return html_writer::tag('div', $output, array('class' => 'paging'));
2749 * Output the place a skip link goes to.
2751 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2752 * @return string the HTML to output.
2754 public function skip_link_target($id = null) {
2755 return html_writer::tag('span', '', array('id' => $id));
2759 * Outputs a heading
2761 * @param string $text The text of the heading
2762 * @param int $level The level of importance of the heading. Defaulting to 2
2763 * @param string $classes A space-separated list of CSS classes. Defaulting to null
2764 * @param string $id An optional ID
2765 * @return string the HTML to output.
2767 public function heading($text, $level = 2, $classes = null, $id = null) {
2768 $level = (integer) $level;
2769 if ($level < 1 or $level > 6) {
2770 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2772 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
2776 * Outputs a box.
2778 * @param string $contents The contents of the box
2779 * @param string $classes A space-separated list of CSS classes
2780 * @param string $id An optional ID
2781 * @param array $attributes An array of other attributes to give the box.
2782 * @return string the HTML to output.
2784 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
2785 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
2789 * Outputs the opening section of a box.
2791 * @param string $classes A space-separated list of CSS classes
2792 * @param string $id An optional ID
2793 * @param array $attributes An array of other attributes to give the box.
2794 * @return string the HTML to output.
2796 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
2797 $this->opencontainers->push('box', html_writer::end_tag('div'));
2798 $attributes['id'] = $id;
2799 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
2800 return html_writer::start_tag('div', $attributes);
2804 * Outputs the closing section of a box.
2806 * @return string the HTML to output.
2808 public function box_end() {
2809 return $this->opencontainers->pop('box');
2813 * Outputs a container.
2815 * @param string $contents The contents of the box
2816 * @param string $classes A space-separated list of CSS classes
2817 * @param string $id An optional ID
2818 * @return string the HTML to output.
2820 public function container($contents, $classes = null, $id = null) {
2821 return $this->container_start($classes, $id) . $contents . $this->container_end();
2825 * Outputs the opening section of a container.
2827 * @param string $classes A space-separated list of CSS classes
2828 * @param string $id An optional ID
2829 * @return string the HTML to output.
2831 public function container_start($classes = null, $id = null) {
2832 $this->opencontainers->push('container', html_writer::end_tag('div'));
2833 return html_writer::start_tag('div', array('id' => $id,
2834 'class' => renderer_base::prepare_classes($classes)));
2838 * Outputs the closing section of a container.
2840 * @return string the HTML to output.
2842 public function container_end() {
2843 return $this->opencontainers->pop('container');
2847 * Make nested HTML lists out of the items
2849 * The resulting list will look something like this:
2851 * <pre>
2852 * <<ul>>
2853 * <<li>><div class='tree_item parent'>(item contents)</div>
2854 * <<ul>
2855 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2856 * <</ul>>
2857 * <</li>>
2858 * <</ul>>
2859 * </pre>
2861 * @param array $items
2862 * @param array $attrs html attributes passed to the top ofs the list
2863 * @return string HTML
2865 public function tree_block_contents($items, $attrs = array()) {
2866 // exit if empty, we don't want an empty ul element
2867 if (empty($items)) {
2868 return '';
2870 // array of nested li elements
2871 $lis = array();
2872 foreach ($items as $item) {
2873 // this applies to the li item which contains all child lists too
2874 $content = $item->content($this);
2875 $liclasses = array($item->get_css_type());
2876 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
2877 $liclasses[] = 'collapsed';
2879 if ($item->isactive === true) {
2880 $liclasses[] = 'current_branch';
2882 $liattr = array('class'=>join(' ',$liclasses));
2883 // class attribute on the div item which only contains the item content
2884 $divclasses = array('tree_item');
2885 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
2886 $divclasses[] = 'branch';
2887 } else {
2888 $divclasses[] = 'leaf';
2890 if (!empty($item->classes) && count($item->classes)>0) {
2891 $divclasses[] = join(' ', $item->classes);
2893 $divattr = array('class'=>join(' ', $divclasses));
2894 if (!empty($item->id)) {
2895 $divattr['id'] = $item->id;
2897 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
2898 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
2899 $content = html_writer::empty_tag('hr') . $content;
2901 $content = html_writer::tag('li', $content, $liattr);
2902 $lis[] = $content;
2904 return html_writer::tag('ul', implode("\n", $lis), $attrs);
2908 * Construct a user menu, returning HTML that can be echoed out by a
2909 * layout file.
2911 * @param stdClass $user A user object, usually $USER.
2912 * @param bool $withlinks true if a dropdown should be built.
2913 * @return string HTML fragment.
2915 public function user_menu($user = null, $withlinks = null) {
2916 global $USER, $CFG;
2917 require_once($CFG->dirroot . '/user/lib.php');
2919 if (is_null($user)) {
2920 $user = $USER;
2923 // Note: this behaviour is intended to match that of core_renderer::login_info,
2924 // but should not be considered to be good practice; layout options are
2925 // intended to be theme-specific. Please don't copy this snippet anywhere else.
2926 if (is_null($withlinks)) {
2927 $withlinks = empty($this->page->layout_options['nologinlinks']);
2930 // Add a class for when $withlinks is false.
2931 $usermenuclasses = 'usermenu';
2932 if (!$withlinks) {
2933 $usermenuclasses .= ' withoutlinks';
2936 $returnstr = "";
2938 // If during initial install, return the empty return string.
2939 if (during_initial_install()) {
2940 return $returnstr;
2943 $loginpage = ((string)$this->page->url === get_login_url());
2944 $loginurl = get_login_url();
2945 // If not logged in, show the typical not-logged-in string.
2946 if (!isloggedin()) {
2947 $returnstr = get_string('loggedinnot', 'moodle');
2948 if (!$loginpage) {
2949 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
2951 return html_writer::div(
2952 html_writer::span(
2953 $returnstr,
2954 'login'
2956 $usermenuclasses
2961 // If logged in as a guest user, show a string to that effect.
2962 if (isguestuser()) {
2963 $returnstr = get_string('loggedinasguest');
2964 if (!$loginpage && $withlinks) {
2965 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
2968 return html_writer::div(
2969 html_writer::span(
2970 $returnstr,
2971 'login'
2973 $usermenuclasses
2977 // Get some navigation opts.
2978 $opts = user_get_user_navigation_info($user, $this->page, $this->page->course);
2980 $avatarclasses = "avatars";
2981 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
2982 $usertextcontents = $opts->metadata['userfullname'];
2984 // Other user.
2985 if (!empty($opts->metadata['asotheruser'])) {
2986 $avatarcontents .= html_writer::span(
2987 $opts->metadata['realuseravatar'],
2988 'avatar realuser'
2990 $usertextcontents = $opts->metadata['realuserfullname'];
2991 $usertextcontents .= html_writer::tag(
2992 'span',
2993 get_string(
2994 'loggedinas',
2995 'moodle',
2996 html_writer::span(
2997 $opts->metadata['userfullname'],
2998 'value'
3001 array('class' => 'meta viewingas')
3005 // Role.
3006 if (!empty($opts->metadata['asotherrole'])) {
3007 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3008 $usertextcontents .= html_writer::span(
3009 $opts->metadata['rolename'],
3010 'meta role role-' . $role
3014 // User login failures.
3015 if (!empty($opts->metadata['userloginfail'])) {
3016 $usertextcontents .= html_writer::span(
3017 $opts->metadata['userloginfail'],
3018 'meta loginfailures'
3022 // MNet.
3023 if (!empty($opts->metadata['asmnetuser'])) {
3024 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3025 $usertextcontents .= html_writer::span(
3026 $opts->metadata['mnetidprovidername'],
3027 'meta mnet mnet-' . $mnet
3031 $returnstr .= html_writer::span(
3032 html_writer::span($usertextcontents, 'usertext') .
3033 html_writer::span($avatarcontents, $avatarclasses),
3034 'userbutton'
3037 // Create a divider (well, a filler).
3038 $divider = new action_menu_filler();
3039 $divider->primary = false;
3041 $am = new action_menu();
3042 $am->initialise_js($this->page);
3043 $am->set_menu_trigger(
3044 $returnstr
3046 $am->set_alignment(action_menu::TR, action_menu::BR);
3047 if ($withlinks) {
3048 $navitemcount = count($opts->navitems);
3049 $idx = 0;
3050 foreach ($opts->navitems as $key => $value) {
3051 $pix = null;
3052 if (isset($value->pix) && !empty($value->pix)) {
3053 $pix = new pix_icon($value->pix, $value->title, null, array('class' => 'iconsmall'));
3054 } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3055 $value->title = html_writer::img(
3056 $value->imgsrc,
3057 $value->title,
3058 array('class' => 'iconsmall')
3059 ) . $value->title;
3061 $al = new action_menu_link_secondary(
3062 $value->url,
3063 $pix,
3064 $value->title,
3065 array('class' => 'icon')
3067 $am->add($al);
3069 // Add dividers after the first item and before the
3070 // last item.
3071 if ($idx == 0 || $idx == $navitemcount - 2) {
3072 $am->add($divider);
3075 $idx++;
3079 return html_writer::div(
3080 $this->render($am),
3081 $usermenuclasses
3086 * Return the navbar content so that it can be echoed out by the layout
3088 * @return string XHTML navbar
3090 public function navbar() {
3091 $items = $this->page->navbar->get_items();
3092 $itemcount = count($items);
3093 if ($itemcount === 0) {
3094 return '';
3097 $htmlblocks = array();
3098 // Iterate the navarray and display each node
3099 $separator = get_separator();
3100 for ($i=0;$i < $itemcount;$i++) {
3101 $item = $items[$i];
3102 $item->hideicon = true;
3103 if ($i===0) {
3104 $content = html_writer::tag('li', $this->render($item));
3105 } else {
3106 $content = html_writer::tag('li', $separator.$this->render($item));
3108 $htmlblocks[] = $content;
3111 //accessibility: heading for navbar list (MDL-20446)
3112 $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
3113 $navbarcontent .= html_writer::tag('nav', html_writer::tag('ul', join('', $htmlblocks)));
3114 // XHTML
3115 return $navbarcontent;
3119 * Renders a navigation node object.
3121 * @param navigation_node $item The navigation node to render.
3122 * @return string HTML fragment
3124 protected function render_navigation_node(navigation_node $item) {
3125 $content = $item->get_content();
3126 $title = $item->get_title();
3127 if ($item->icon instanceof renderable && !$item->hideicon) {
3128 $icon = $this->render($item->icon);
3129 $content = $icon.$content; // use CSS for spacing of icons
3131 if ($item->helpbutton !== null) {
3132 $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3134 if ($content === '') {
3135 return '';
3137 if ($item->action instanceof action_link) {
3138 $link = $item->action;
3139 if ($item->hidden) {
3140 $link->add_class('dimmed');
3142 if (!empty($content)) {
3143 // Providing there is content we will use that for the link content.
3144 $link->text = $content;
3146 $content = $this->render($link);
3147 } else if ($item->action instanceof moodle_url) {
3148 $attributes = array();
3149 if ($title !== '') {
3150 $attributes['title'] = $title;
3152 if ($item->hidden) {
3153 $attributes['class'] = 'dimmed_text';
3155 $content = html_writer::link($item->action, $content, $attributes);
3157 } else if (is_string($item->action) || empty($item->action)) {
3158 $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3159 if ($title !== '') {
3160 $attributes['title'] = $title;
3162 if ($item->hidden) {
3163 $attributes['class'] = 'dimmed_text';
3165 $content = html_writer::tag('span', $content, $attributes);
3167 return $content;
3171 * Accessibility: Right arrow-like character is
3172 * used in the breadcrumb trail, course navigation menu
3173 * (previous/next activity), calendar, and search forum block.
3174 * If the theme does not set characters, appropriate defaults
3175 * are set automatically. Please DO NOT
3176 * use &lt; &gt; &raquo; - these are confusing for blind users.
3178 * @return string
3180 public function rarrow() {
3181 return $this->page->theme->rarrow;
3185 * Accessibility: Right arrow-like character is
3186 * used in the breadcrumb trail, course navigation menu
3187 * (previous/next activity), calendar, and search forum block.
3188 * If the theme does not set characters, appropriate defaults
3189 * are set automatically. Please DO NOT
3190 * use &lt; &gt; &raquo; - these are confusing for blind users.
3192 * @return string
3194 public function larrow() {
3195 return $this->page->theme->larrow;
3199 * Returns the custom menu if one has been set
3201 * A custom menu can be configured by browsing to
3202 * Settings: Administration > Appearance > Themes > Theme settings
3203 * and then configuring the custommenu config setting as described.
3205 * Theme developers: DO NOT OVERRIDE! Please override function
3206 * {@link core_renderer::render_custom_menu()} instead.
3208 * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3209 * @return string
3211 public function custom_menu($custommenuitems = '') {
3212 global $CFG;
3213 if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3214 $custommenuitems = $CFG->custommenuitems;
3216 if (empty($custommenuitems)) {
3217 return '';
3219 $custommenu = new custom_menu($custommenuitems, current_language());
3220 return $this->render($custommenu);
3224 * Renders a custom menu object (located in outputcomponents.php)
3226 * The custom menu this method produces makes use of the YUI3 menunav widget
3227 * and requires very specific html elements and classes.
3229 * @staticvar int $menucount
3230 * @param custom_menu $menu
3231 * @return string
3233 protected function render_custom_menu(custom_menu $menu) {
3234 static $menucount = 0;
3235 // If the menu has no children return an empty string
3236 if (!$menu->has_children()) {
3237 return '';
3239 // Increment the menu count. This is used for ID's that get worked with
3240 // in JavaScript as is essential
3241 $menucount++;
3242 // Initialise this custom menu (the custom menu object is contained in javascript-static
3243 $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
3244 $jscode = "(function(){{$jscode}})";
3245 $this->page->requires->yui_module('node-menunav', $jscode);
3246 // Build the root nodes as required by YUI
3247 $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
3248 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3249 $content .= html_writer::start_tag('ul');
3250 // Render each child
3251 foreach ($menu->get_children() as $item) {
3252 $content .= $this->render_custom_menu_item($item);
3254 // Close the open tags
3255 $content .= html_writer::end_tag('ul');
3256 $content .= html_writer::end_tag('div');
3257 $content .= html_writer::end_tag('div');
3258 // Return the custom menu
3259 return $content;
3263 * Renders a custom menu node as part of a submenu
3265 * The custom menu this method produces makes use of the YUI3 menunav widget
3266 * and requires very specific html elements and classes.
3268 * @see core:renderer::render_custom_menu()
3270 * @staticvar int $submenucount
3271 * @param custom_menu_item $menunode
3272 * @return string
3274 protected function render_custom_menu_item(custom_menu_item $menunode) {
3275 // Required to ensure we get unique trackable id's
3276 static $submenucount = 0;
3277 if ($menunode->has_children()) {
3278 // If the child has menus render it as a sub menu
3279 $submenucount++;
3280 $content = html_writer::start_tag('li');
3281 if ($menunode->get_url() !== null) {
3282 $url = $menunode->get_url();
3283 } else {
3284 $url = '#cm_submenu_'.$submenucount;
3286 $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3287 $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3288 $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3289 $content .= html_writer::start_tag('ul');
3290 foreach ($menunode->get_children() as $menunode) {
3291 $content .= $this->render_custom_menu_item($menunode);
3293 $content .= html_writer::end_tag('ul');
3294 $content .= html_writer::end_tag('div');
3295 $content .= html_writer::end_tag('div');
3296 $content .= html_writer::end_tag('li');
3297 } else {
3298 // The node doesn't have children so produce a final menuitem.
3299 // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3300 $content = '';
3301 if (preg_match("/^#+$/", $menunode->get_text())) {
3303 // This is a divider.
3304 $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3305 } else {
3306 $content = html_writer::start_tag(
3307 'li',
3308 array(
3309 'class' => 'yui3-menuitem'
3312 if ($menunode->get_url() !== null) {
3313 $url = $menunode->get_url();
3314 } else {
3315 $url = '#';
3317 $content .= html_writer::link(
3318 $url,
3319 $menunode->get_text(),
3320 array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3323 $content .= html_writer::end_tag('li');
3325 // Return the sub menu
3326 return $content;
3330 * Renders theme links for switching between default and other themes.
3332 * @return string
3334 protected function theme_switch_links() {
3336 $actualdevice = core_useragent::get_device_type();
3337 $currentdevice = $this->page->devicetypeinuse;
3338 $switched = ($actualdevice != $currentdevice);
3340 if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3341 // The user is using the a default device and hasn't switched so don't shown the switch
3342 // device links.
3343 return '';
3346 if ($switched) {
3347 $linktext = get_string('switchdevicerecommended');
3348 $devicetype = $actualdevice;
3349 } else {
3350 $linktext = get_string('switchdevicedefault');
3351 $devicetype = 'default';
3353 $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3355 $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3356 $content .= html_writer::link($linkurl, $linktext);
3357 $content .= html_writer::end_tag('div');
3359 return $content;
3363 * Renders tabs
3365 * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3367 * Theme developers: In order to change how tabs are displayed please override functions
3368 * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3370 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3371 * @param string|null $selected which tab to mark as selected, all parent tabs will
3372 * automatically be marked as activated
3373 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3374 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3375 * @return string
3377 public final function tabtree($tabs, $selected = null, $inactive = null) {
3378 return $this->render(new tabtree($tabs, $selected, $inactive));
3382 * Renders tabtree
3384 * @param tabtree $tabtree
3385 * @return string
3387 protected function render_tabtree(tabtree $tabtree) {
3388 if (empty($tabtree->subtree)) {
3389 return '';
3391 $str = '';
3392 $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
3393 $str .= $this->render_tabobject($tabtree);
3394 $str .= html_writer::end_tag('div').
3395 html_writer::tag('div', ' ', array('class' => 'clearer'));
3396 return $str;
3400 * Renders tabobject (part of tabtree)
3402 * This function is called from {@link core_renderer::render_tabtree()}
3403 * and also it calls itself when printing the $tabobject subtree recursively.
3405 * Property $tabobject->level indicates the number of row of tabs.
3407 * @param tabobject $tabobject
3408 * @return string HTML fragment
3410 protected function render_tabobject(tabobject $tabobject) {
3411 $str = '';
3413 // Print name of the current tab.
3414 if ($tabobject instanceof tabtree) {
3415 // No name for tabtree root.
3416 } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
3417 // Tab name without a link. The <a> tag is used for styling.
3418 $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
3419 } else {
3420 // Tab name with a link.
3421 if (!($tabobject->link instanceof moodle_url)) {
3422 // backward compartibility when link was passed as quoted string
3423 $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
3424 } else {
3425 $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
3429 if (empty($tabobject->subtree)) {
3430 if ($tabobject->selected) {
3431 $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
3433 return $str;
3436 // Print subtree
3437 $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
3438 $cnt = 0;
3439 foreach ($tabobject->subtree as $tab) {
3440 $liclass = '';
3441 if (!$cnt) {
3442 $liclass .= ' first';
3444 if ($cnt == count($tabobject->subtree) - 1) {
3445 $liclass .= ' last';
3447 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3448 $liclass .= ' onerow';
3451 if ($tab->selected) {
3452 $liclass .= ' here selected';
3453 } else if ($tab->activated) {
3454 $liclass .= ' here active';
3457 // This will recursively call function render_tabobject() for each item in subtree
3458 $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
3459 $cnt++;
3461 $str .= html_writer::end_tag('ul');
3463 return $str;
3467 * Get the HTML for blocks in the given region.
3469 * @since Moodle 2.5.1 2.6
3470 * @param string $region The region to get HTML for.
3471 * @return string HTML.
3473 public function blocks($region, $classes = array(), $tag = 'aside') {
3474 $displayregion = $this->page->apply_theme_region_manipulations($region);
3475 $classes = (array)$classes;
3476 $classes[] = 'block-region';
3477 $attributes = array(
3478 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
3479 'class' => join(' ', $classes),
3480 'data-blockregion' => $displayregion,
3481 'data-droptarget' => '1'
3483 if ($this->page->blocks->region_has_content($displayregion, $this)) {
3484 $content = $this->blocks_for_region($displayregion);
3485 } else {
3486 $content = '';
3488 return html_writer::tag($tag, $content, $attributes);
3492 * Renders a custom block region.
3494 * Use this method if you want to add an additional block region to the content of the page.
3495 * Please note this should only be used in special situations.
3496 * We want to leave the theme is control where ever possible!
3498 * This method must use the same method that the theme uses within its layout file.
3499 * As such it asks the theme what method it is using.
3500 * It can be one of two values, blocks or blocks_for_region (deprecated).
3502 * @param string $regionname The name of the custom region to add.
3503 * @return string HTML for the block region.
3505 public function custom_block_region($regionname) {
3506 if ($this->page->theme->get_block_render_method() === 'blocks') {
3507 return $this->blocks($regionname);
3508 } else {
3509 return $this->blocks_for_region($regionname);
3514 * Returns the CSS classes to apply to the body tag.
3516 * @since Moodle 2.5.1 2.6
3517 * @param array $additionalclasses Any additional classes to apply.
3518 * @return string
3520 public function body_css_classes(array $additionalclasses = array()) {
3521 // Add a class for each block region on the page.
3522 // We use the block manager here because the theme object makes get_string calls.
3523 foreach ($this->page->blocks->get_regions() as $region) {
3524 $additionalclasses[] = 'has-region-'.$region;
3525 if ($this->page->blocks->region_has_content($region, $this)) {
3526 $additionalclasses[] = 'used-region-'.$region;
3527 } else {
3528 $additionalclasses[] = 'empty-region-'.$region;
3530 if ($this->page->blocks->region_completely_docked($region, $this)) {
3531 $additionalclasses[] = 'docked-region-'.$region;
3534 foreach ($this->page->layout_options as $option => $value) {
3535 if ($value) {
3536 $additionalclasses[] = 'layout-option-'.$option;
3539 $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
3540 return $css;
3544 * The ID attribute to apply to the body tag.
3546 * @since Moodle 2.5.1 2.6
3547 * @return string
3549 public function body_id() {
3550 return $this->page->bodyid;
3554 * Returns HTML attributes to use within the body tag. This includes an ID and classes.
3556 * @since Moodle 2.5.1 2.6
3557 * @param string|array $additionalclasses Any additional classes to give the body tag,
3558 * @return string
3560 public function body_attributes($additionalclasses = array()) {
3561 if (!is_array($additionalclasses)) {
3562 $additionalclasses = explode(' ', $additionalclasses);
3564 return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
3568 * Gets HTML for the page heading.
3570 * @since Moodle 2.5.1 2.6
3571 * @param string $tag The tag to encase the heading in. h1 by default.
3572 * @return string HTML.
3574 public function page_heading($tag = 'h1') {
3575 return html_writer::tag($tag, $this->page->heading);
3579 * Gets the HTML for the page heading button.
3581 * @since Moodle 2.5.1 2.6
3582 * @return string HTML.
3584 public function page_heading_button() {
3585 return $this->page->button;
3589 * Returns the Moodle docs link to use for this page.
3591 * @since Moodle 2.5.1 2.6
3592 * @param string $text
3593 * @return string
3595 public function page_doc_link($text = null) {
3596 if ($text === null) {
3597 $text = get_string('moodledocslink');
3599 $path = page_get_doc_link_path($this->page);
3600 if (!$path) {
3601 return '';
3603 return $this->doc_link($path, $text);
3607 * Returns the page heading menu.
3609 * @since Moodle 2.5.1 2.6
3610 * @return string HTML.
3612 public function page_heading_menu() {
3613 return $this->page->headingmenu;
3617 * Returns the title to use on the page.
3619 * @since Moodle 2.5.1 2.6
3620 * @return string
3622 public function page_title() {
3623 return $this->page->title;
3627 * Returns the URL for the favicon.
3629 * @since Moodle 2.5.1 2.6
3630 * @return string The favicon URL
3632 public function favicon() {
3633 return $this->pix_url('favicon', 'theme');
3638 * A renderer that generates output for command-line scripts.
3640 * The implementation of this renderer is probably incomplete.
3642 * @copyright 2009 Tim Hunt
3643 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3644 * @since Moodle 2.0
3645 * @package core
3646 * @category output
3648 class core_renderer_cli extends core_renderer {
3651 * Returns the page header.
3653 * @return string HTML fragment
3655 public function header() {
3656 return $this->page->heading . "\n";
3660 * Returns a template fragment representing a Heading.
3662 * @param string $text The text of the heading
3663 * @param int $level The level of importance of the heading
3664 * @param string $classes A space-separated list of CSS classes
3665 * @param string $id An optional ID
3666 * @return string A template fragment for a heading
3668 public function heading($text, $level = 2, $classes = 'main', $id = null) {
3669 $text .= "\n";
3670 switch ($level) {
3671 case 1:
3672 return '=>' . $text;
3673 case 2:
3674 return '-->' . $text;
3675 default:
3676 return $text;
3681 * Returns a template fragment representing a fatal error.
3683 * @param string $message The message to output
3684 * @param string $moreinfourl URL where more info can be found about the error
3685 * @param string $link Link for the Continue button
3686 * @param array $backtrace The execution backtrace
3687 * @param string $debuginfo Debugging information
3688 * @return string A template fragment for a fatal error
3690 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
3691 global $CFG;
3693 $output = "!!! $message !!!\n";
3695 if ($CFG->debugdeveloper) {
3696 if (!empty($debuginfo)) {
3697 $output .= $this->notification($debuginfo, 'notifytiny');
3699 if (!empty($backtrace)) {
3700 $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
3704 return $output;
3708 * Returns a template fragment representing a notification.
3710 * @param string $message The message to include
3711 * @param string $classes A space-separated list of CSS classes
3712 * @return string A template fragment for a notification
3714 public function notification($message, $classes = 'notifyproblem') {
3715 $message = clean_text($message);
3716 if ($classes === 'notifysuccess') {
3717 return "++ $message ++\n";
3719 return "!! $message !!\n";
3723 * There is no footer for a cli request, however we must override the
3724 * footer method to prevent the default footer.
3726 public function footer() {}
3731 * A renderer that generates output for ajax scripts.
3733 * This renderer prevents accidental sends back only json
3734 * encoded error messages, all other output is ignored.
3736 * @copyright 2010 Petr Skoda
3737 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3738 * @since Moodle 2.0
3739 * @package core
3740 * @category output
3742 class core_renderer_ajax extends core_renderer {
3745 * Returns a template fragment representing a fatal error.
3747 * @param string $message The message to output
3748 * @param string $moreinfourl URL where more info can be found about the error
3749 * @param string $link Link for the Continue button
3750 * @param array $backtrace The execution backtrace
3751 * @param string $debuginfo Debugging information
3752 * @return string A template fragment for a fatal error
3754 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
3755 global $CFG;
3757 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
3759 $e = new stdClass();
3760 $e->error = $message;
3761 $e->stacktrace = NULL;
3762 $e->debuginfo = NULL;
3763 $e->reproductionlink = NULL;
3764 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
3765 $link = (string) $link;
3766 if ($link) {
3767 $e->reproductionlink = $link;
3769 if (!empty($debuginfo)) {
3770 $e->debuginfo = $debuginfo;
3772 if (!empty($backtrace)) {
3773 $e->stacktrace = format_backtrace($backtrace, true);
3776 $this->header();
3777 return json_encode($e);
3781 * Used to display a notification.
3782 * For the AJAX notifications are discarded.
3784 * @param string $message
3785 * @param string $classes
3787 public function notification($message, $classes = 'notifyproblem') {}
3790 * Used to display a redirection message.
3791 * AJAX redirections should not occur and as such redirection messages
3792 * are discarded.
3794 * @param moodle_url|string $encodedurl
3795 * @param string $message
3796 * @param int $delay
3797 * @param bool $debugdisableredirect
3799 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
3802 * Prepares the start of an AJAX output.
3804 public function header() {
3805 // unfortunately YUI iframe upload does not support application/json
3806 if (!empty($_FILES)) {
3807 @header('Content-type: text/plain; charset=utf-8');
3808 if (!core_useragent::supports_json_contenttype()) {
3809 @header('X-Content-Type-Options: nosniff');
3811 } else if (!core_useragent::supports_json_contenttype()) {
3812 @header('Content-type: text/plain; charset=utf-8');
3813 @header('X-Content-Type-Options: nosniff');
3814 } else {
3815 @header('Content-type: application/json; charset=utf-8');
3818 // Headers to make it not cacheable and json
3819 @header('Cache-Control: no-store, no-cache, must-revalidate');
3820 @header('Cache-Control: post-check=0, pre-check=0', false);
3821 @header('Pragma: no-cache');
3822 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
3823 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
3824 @header('Accept-Ranges: none');
3828 * There is no footer for an AJAX request, however we must override the
3829 * footer method to prevent the default footer.
3831 public function footer() {}
3834 * No need for headers in an AJAX request... this should never happen.
3835 * @param string $text
3836 * @param int $level
3837 * @param string $classes
3838 * @param string $id
3840 public function heading($text, $level = 2, $classes = 'main', $id = null) {}
3845 * Renderer for media files.
3847 * Used in file resources, media filter, and any other places that need to
3848 * output embedded media.
3850 * @copyright 2011 The Open University
3851 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3853 class core_media_renderer extends plugin_renderer_base {
3854 /** @var array Array of available 'player' objects */
3855 private $players;
3856 /** @var string Regex pattern for links which may contain embeddable content */
3857 private $embeddablemarkers;
3860 * Constructor requires medialib.php.
3862 * This is needed in the constructor (not later) so that you can use the
3863 * constants and static functions that are defined in core_media class
3864 * before you call renderer functions.
3866 public function __construct() {
3867 global $CFG;
3868 require_once($CFG->libdir . '/medialib.php');
3872 * Obtains the list of core_media_player objects currently in use to render
3873 * items.
3875 * The list is in rank order (highest first) and does not include players
3876 * which are disabled.
3878 * @return array Array of core_media_player objects in rank order
3880 protected function get_players() {
3881 global $CFG;
3883 // Save time by only building the list once.
3884 if (!$this->players) {
3885 // Get raw list of players.
3886 $players = $this->get_players_raw();
3888 // Chuck all the ones that are disabled.
3889 foreach ($players as $key => $player) {
3890 if (!$player->is_enabled()) {
3891 unset($players[$key]);
3895 // Sort in rank order (highest first).
3896 usort($players, array('core_media_player', 'compare_by_rank'));
3897 $this->players = $players;
3899 return $this->players;
3903 * Obtains a raw list of player objects that includes objects regardless
3904 * of whether they are disabled or not, and without sorting.
3906 * You can override this in a subclass if you need to add additional
3907 * players.
3909 * The return array is be indexed by player name to make it easier to
3910 * remove players in a subclass.
3912 * @return array $players Array of core_media_player objects in any order
3914 protected function get_players_raw() {
3915 return array(
3916 'vimeo' => new core_media_player_vimeo(),
3917 'youtube' => new core_media_player_youtube(),
3918 'youtube_playlist' => new core_media_player_youtube_playlist(),
3919 'html5video' => new core_media_player_html5video(),
3920 'html5audio' => new core_media_player_html5audio(),
3921 'mp3' => new core_media_player_mp3(),
3922 'flv' => new core_media_player_flv(),
3923 'wmp' => new core_media_player_wmp(),
3924 'qt' => new core_media_player_qt(),
3925 'rm' => new core_media_player_rm(),
3926 'swf' => new core_media_player_swf(),
3927 'link' => new core_media_player_link(),
3932 * Renders a media file (audio or video) using suitable embedded player.
3934 * See embed_alternatives function for full description of parameters.
3935 * This function calls through to that one.
3937 * When using this function you can also specify width and height in the
3938 * URL by including ?d=100x100 at the end. If specified in the URL, this
3939 * will override the $width and $height parameters.
3941 * @param moodle_url $url Full URL of media file
3942 * @param string $name Optional user-readable name to display in download link
3943 * @param int $width Width in pixels (optional)
3944 * @param int $height Height in pixels (optional)
3945 * @param array $options Array of key/value pairs
3946 * @return string HTML content of embed
3948 public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
3949 $options = array()) {
3951 // Get width and height from URL if specified (overrides parameters in
3952 // function call).
3953 $rawurl = $url->out(false);
3954 if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
3955 $width = $matches[1];
3956 $height = $matches[2];
3957 $url = new moodle_url(str_replace($matches[0], '', $rawurl));
3960 // Defer to array version of function.
3961 return $this->embed_alternatives(array($url), $name, $width, $height, $options);
3965 * Renders media files (audio or video) using suitable embedded player.
3966 * The list of URLs should be alternative versions of the same content in
3967 * multiple formats. If there is only one format it should have a single
3968 * entry.
3970 * If the media files are not in a supported format, this will give students
3971 * a download link to each format. The download link uses the filename
3972 * unless you supply the optional name parameter.
3974 * Width and height are optional. If specified, these are suggested sizes
3975 * and should be the exact values supplied by the user, if they come from
3976 * user input. These will be treated as relating to the size of the video
3977 * content, not including any player control bar.
3979 * For audio files, height will be ignored. For video files, a few formats
3980 * work if you specify only width, but in general if you specify width
3981 * you must specify height as well.
3983 * The $options array is passed through to the core_media_player classes
3984 * that render the object tag. The keys can contain values from
3985 * core_media::OPTION_xx.
3987 * @param array $alternatives Array of moodle_url to media files
3988 * @param string $name Optional user-readable name to display in download link
3989 * @param int $width Width in pixels (optional)
3990 * @param int $height Height in pixels (optional)
3991 * @param array $options Array of key/value pairs
3992 * @return string HTML content of embed
3994 public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
3995 $options = array()) {
3997 // Get list of player plugins (will also require the library).
3998 $players = $this->get_players();
4000 // Set up initial text which will be replaced by first player that
4001 // supports any of the formats.
4002 $out = core_media_player::PLACEHOLDER;
4004 // Loop through all players that support any of these URLs.
4005 foreach ($players as $player) {
4006 // Option: When no other player matched, don't do the default link player.
4007 if (!empty($options[core_media::OPTION_FALLBACK_TO_BLANK]) &&
4008 $player->get_rank() === 0 && $out === core_media_player::PLACEHOLDER) {
4009 continue;
4012 $supported = $player->list_supported_urls($alternatives, $options);
4013 if ($supported) {
4014 // Embed.
4015 $text = $player->embed($supported, $name, $width, $height, $options);
4017 // Put this in place of the 'fallback' slot in the previous text.
4018 $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
4022 // Remove 'fallback' slot from final version and return it.
4023 $out = str_replace(core_media_player::PLACEHOLDER, '', $out);
4024 if (!empty($options[core_media::OPTION_BLOCK]) && $out !== '') {
4025 $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
4027 return $out;
4031 * Checks whether a file can be embedded. If this returns true you will get
4032 * an embedded player; if this returns false, you will just get a download
4033 * link.
4035 * This is a wrapper for can_embed_urls.
4037 * @param moodle_url $url URL of media file
4038 * @param array $options Options (same as when embedding)
4039 * @return bool True if file can be embedded
4041 public function can_embed_url(moodle_url $url, $options = array()) {
4042 return $this->can_embed_urls(array($url), $options);
4046 * Checks whether a file can be embedded. If this returns true you will get
4047 * an embedded player; if this returns false, you will just get a download
4048 * link.
4050 * @param array $urls URL of media file and any alternatives (moodle_url)
4051 * @param array $options Options (same as when embedding)
4052 * @return bool True if file can be embedded
4054 public function can_embed_urls(array $urls, $options = array()) {
4055 // Check all players to see if any of them support it.
4056 foreach ($this->get_players() as $player) {
4057 // Link player (always last on list) doesn't count!
4058 if ($player->get_rank() <= 0) {
4059 break;
4061 // First player that supports it, return true.
4062 if ($player->list_supported_urls($urls, $options)) {
4063 return true;
4066 return false;
4070 * Obtains a list of markers that can be used in a regular expression when
4071 * searching for URLs that can be embedded by any player type.
4073 * This string is used to improve peformance of regex matching by ensuring
4074 * that the (presumably C) regex code can do a quick keyword check on the
4075 * URL part of a link to see if it matches one of these, rather than having
4076 * to go into PHP code for every single link to see if it can be embedded.
4078 * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
4080 public function get_embeddable_markers() {
4081 if (empty($this->embeddablemarkers)) {
4082 $markers = '';
4083 foreach ($this->get_players() as $player) {
4084 foreach ($player->get_embeddable_markers() as $marker) {
4085 if ($markers !== '') {
4086 $markers .= '|';
4088 $markers .= preg_quote($marker);
4091 $this->embeddablemarkers = $markers;
4093 return $this->embeddablemarkers;
4098 * The maintenance renderer.
4100 * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
4101 * is running a maintenance related task.
4102 * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
4104 * @since Moodle 2.6
4105 * @package core
4106 * @category output
4107 * @copyright 2013 Sam Hemelryk
4108 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4110 class core_renderer_maintenance extends core_renderer {
4113 * Initialises the renderer instance.
4114 * @param moodle_page $page
4115 * @param string $target
4116 * @throws coding_exception
4118 public function __construct(moodle_page $page, $target) {
4119 if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
4120 throw new coding_exception('Invalid request for the maintenance renderer.');
4122 parent::__construct($page, $target);
4126 * Does nothing. The maintenance renderer cannot produce blocks.
4128 * @param block_contents $bc
4129 * @param string $region
4130 * @return string
4132 public function block(block_contents $bc, $region) {
4133 // Computer says no blocks.
4134 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4135 return '';
4139 * Does nothing. The maintenance renderer cannot produce blocks.
4141 * @param string $region
4142 * @param array $classes
4143 * @param string $tag
4144 * @return string
4146 public function blocks($region, $classes = array(), $tag = 'aside') {
4147 // Computer says no blocks.
4148 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4149 return '';
4153 * Does nothing. The maintenance renderer cannot produce blocks.
4155 * @param string $region
4156 * @return string
4158 public function blocks_for_region($region) {
4159 // Computer says no blocks for region.
4160 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4161 return '';
4165 * Does nothing. The maintenance renderer cannot produce a course content header.
4167 * @param bool $onlyifnotcalledbefore
4168 * @return string
4170 public function course_content_header($onlyifnotcalledbefore = false) {
4171 // Computer says no course content header.
4172 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4173 return '';
4177 * Does nothing. The maintenance renderer cannot produce a course content footer.
4179 * @param bool $onlyifnotcalledbefore
4180 * @return string
4182 public function course_content_footer($onlyifnotcalledbefore = false) {
4183 // Computer says no course content footer.
4184 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4185 return '';
4189 * Does nothing. The maintenance renderer cannot produce a course header.
4191 * @return string
4193 public function course_header() {
4194 // Computer says no course header.
4195 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4196 return '';
4200 * Does nothing. The maintenance renderer cannot produce a course footer.
4202 * @return string
4204 public function course_footer() {
4205 // Computer says no course footer.
4206 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4207 return '';
4211 * Does nothing. The maintenance renderer cannot produce a custom menu.
4213 * @param string $custommenuitems
4214 * @return string
4216 public function custom_menu($custommenuitems = '') {
4217 // Computer says no custom menu.
4218 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4219 return '';
4223 * Does nothing. The maintenance renderer cannot produce a file picker.
4225 * @param array $options
4226 * @return string
4228 public function file_picker($options) {
4229 // Computer says no file picker.
4230 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4231 return '';
4235 * Does nothing. The maintenance renderer cannot produce and HTML file tree.
4237 * @param array $dir
4238 * @return string
4240 public function htmllize_file_tree($dir) {
4241 // Hell no we don't want no htmllized file tree.
4242 // Also why on earth is this function on the core renderer???
4243 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4244 return '';
4249 * Does nothing. The maintenance renderer does not support JS.
4251 * @param block_contents $bc
4253 public function init_block_hider_js(block_contents $bc) {
4254 // Computer says no JavaScript.
4255 // Do nothing, ridiculous method.
4259 * Does nothing. The maintenance renderer cannot produce language menus.
4261 * @return string
4263 public function lang_menu() {
4264 // Computer says no lang menu.
4265 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4266 return '';
4270 * Does nothing. The maintenance renderer has no need for login information.
4272 * @param null $withlinks
4273 * @return string
4275 public function login_info($withlinks = null) {
4276 // Computer says no login info.
4277 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4278 return '';
4282 * Does nothing. The maintenance renderer cannot produce user pictures.
4284 * @param stdClass $user
4285 * @param array $options
4286 * @return string
4288 public function user_picture(stdClass $user, array $options = null) {
4289 // Computer says no user pictures.
4290 // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
4291 return '';