Merge branch 'MDL-47806' of github.com:mr-russ/moodle
[moodle.git] / lib / outputrenderers.php
CommitLineData
d9c8f425 1<?php
d9c8f425 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.
13//
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/>.
16
17/**
18 * Classes for rendering HTML output for Moodle.
19 *
7a3c215b 20 * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
d9c8f425 21 * for an overview.
22 *
7a3c215b
SH
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.
31 *
f8129210 32 * @package core
76be40cc 33 * @category output
78bfb562
PS
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d9c8f425 36 */
37
78bfb562
PS
38defined('MOODLE_INTERNAL') || die();
39
d9c8f425 40/**
41 * Simple base class for Moodle renderers.
42 *
43 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
44 *
45 * Also has methods to facilitate generating HTML output.
46 *
47 * @copyright 2009 Tim Hunt
7a3c215b
SH
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 * @since Moodle 2.0
f8129210 50 * @package core
76be40cc 51 * @category output
d9c8f425 52 */
78946b9b 53class renderer_base {
7a3c215b 54 /**
76be40cc 55 * @var xhtml_container_stack The xhtml_container_stack to use.
7a3c215b 56 */
d9c8f425 57 protected $opencontainers;
7a3c215b
SH
58
59 /**
76be40cc 60 * @var moodle_page The Moodle page the renderer has been created to assist with.
7a3c215b 61 */
d9c8f425 62 protected $page;
7a3c215b
SH
63
64 /**
76be40cc 65 * @var string The requested rendering target.
7a3c215b 66 */
c927e35c 67 protected $target;
d9c8f425 68
69 /**
70 * Constructor
7a3c215b 71 *
3d3fae72 72 * The constructor takes two arguments. The first is the page that the renderer
7a3c215b
SH
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.
76 *
d9c8f425 77 * @param moodle_page $page the page we are doing output for.
c927e35c 78 * @param string $target one of rendering target constants
d9c8f425 79 */
c927e35c 80 public function __construct(moodle_page $page, $target) {
d9c8f425 81 $this->opencontainers = $page->opencontainers;
82 $this->page = $page;
c927e35c 83 $this->target = $target;
d9c8f425 84 }
85
86 /**
5d0c95a5 87 * Returns rendered widget.
7a3c215b
SH
88 *
89 * The provided widget needs to be an object that extends the renderable
90 * interface.
3d3fae72 91 * If will then be rendered by a method based upon the classname for the widget.
7a3c215b
SH
92 * For instance a widget of class `crazywidget` will be rendered by a protected
93 * render_crazywidget method of this renderer.
94 *
996b1e0c 95 * @param renderable $widget instance with renderable interface
5d0c95a5 96 * @return string
d9c8f425 97 */
5d0c95a5 98 public function render(renderable $widget) {
d2bba1ee
DW
99 $classname = get_class($widget);
100 // Strip namespaces.
101 $classname = preg_replace('/^.*\\\/', '', $classname);
102 // Remove _renderable suffixes
103 $classname = preg_replace('/_renderable$/', '', $classname);
104
105 $rendermethod = 'render_'.$classname;
5d0c95a5
PS
106 if (method_exists($this, $rendermethod)) {
107 return $this->$rendermethod($widget);
108 }
109 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
d9c8f425 110 }
111
112 /**
7a3c215b
SH
113 * Adds a JS action for the element with the provided id.
114 *
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.
f8129210 117 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
7a3c215b 118 *
f8129210 119 * @param component_action $action
c80877aa
PS
120 * @param string $id
121 * @return string id of element, either original submitted or random new if not supplied
d9c8f425 122 */
7a3c215b 123 public function add_action_handler(component_action $action, $id = null) {
c80877aa
PS
124 if (!$id) {
125 $id = html_writer::random_id($action->event);
126 }
d96d8f03 127 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
c80877aa 128 return $id;
d9c8f425 129 }
130
131 /**
7a3c215b
SH
132 * Returns true is output has already started, and false if not.
133 *
5d0c95a5 134 * @return boolean true if the header has been printed.
d9c8f425 135 */
5d0c95a5
PS
136 public function has_started() {
137 return $this->page->state >= moodle_page::STATE_IN_BODY;
d9c8f425 138 }
139
140 /**
141 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
7a3c215b 142 *
d9c8f425 143 * @param mixed $classes Space-separated string or array of classes
144 * @return string HTML class attribute value
145 */
146 public static function prepare_classes($classes) {
147 if (is_array($classes)) {
148 return implode(' ', array_unique($classes));
149 }
150 return $classes;
151 }
152
d9c8f425 153 /**
897e902b 154 * Return the moodle_url for an image.
7a3c215b 155 *
897e902b
PS
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.
d9c8f425 163 *
897e902b
PS
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')
172 *
173 * @param string $imagename the pathname of the image
174 * @param string $component full plugin name (aka component) or 'theme'
78946b9b 175 * @return moodle_url
d9c8f425 176 */
c927e35c 177 public function pix_url($imagename, $component = 'moodle') {
c39e5ba2 178 return $this->page->theme->pix_url($imagename, $component);
d9c8f425 179 }
d9c8f425 180}
181
c927e35c 182
75590935
PS
183/**
184 * Basis for all plugin renderers.
185 *
f8129210
SH
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
76be40cc 190 * @category output
75590935
PS
191 */
192class plugin_renderer_base extends renderer_base {
7a3c215b 193
75590935 194 /**
3d3fae72
SH
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%
f8129210 197 * of cases by the {@link core_renderer}
75590935
PS
198 */
199 protected $output;
200
201 /**
996b1e0c 202 * Constructor method, calls the parent constructor
7a3c215b 203 *
75590935 204 * @param moodle_page $page
c927e35c 205 * @param string $target one of rendering target constants
75590935 206 */
c927e35c 207 public function __construct(moodle_page $page, $target) {
166ac0a3
SH
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;
213 }
c927e35c
PS
214 $this->output = $page->get_renderer('core', null, $target);
215 parent::__construct($page, $target);
75590935 216 }
ff5265c6 217
5d0c95a5 218 /**
7a3c215b
SH
219 * Renders the provided widget and returns the HTML to display it.
220 *
71c03ac1 221 * @param renderable $widget instance with renderable interface
5d0c95a5
PS
222 * @return string
223 */
224 public function render(renderable $widget) {
d2bba1ee
DW
225 $classname = get_class($widget);
226 // Strip namespaces.
227 $classname = preg_replace('/^.*\\\/', '', $classname);
ebdcb292
SH
228 // Keep a copy at this point, we may need to look for a deprecated method.
229 $deprecatedmethod = 'render_'.$classname;
d2bba1ee 230 // Remove _renderable suffixes
ebdcb292 231 $classname = preg_replace('/_renderable$/', '', $classname);
d2bba1ee
DW
232
233 $rendermethod = 'render_'.$classname;
5d0c95a5
PS
234 if (method_exists($this, $rendermethod)) {
235 return $this->$rendermethod($widget);
236 }
ebdcb292
SH
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;
251 }
252 return $this->$deprecatedmethod($widget);
253 }
5d0c95a5 254 // pass to core renderer if method not found here
469bf7a4 255 return $this->output->render($widget);
5d0c95a5
PS
256 }
257
ff5265c6
PS
258 /**
259 * Magic method used to pass calls otherwise meant for the standard renderer
996b1e0c 260 * to it to ensure we don't go causing unnecessary grief.
ff5265c6
PS
261 *
262 * @param string $method
263 * @param array $arguments
264 * @return mixed
265 */
266 public function __call($method, $arguments) {
37b5b18e 267 if (method_exists('renderer_base', $method)) {
fede0be5 268 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
37b5b18e 269 }
ff5265c6
PS
270 if (method_exists($this->output, $method)) {
271 return call_user_func_array(array($this->output, $method), $arguments);
272 } else {
fede0be5 273 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
ff5265c6
PS
274 }
275 }
75590935 276}
d9c8f425 277
c927e35c 278
d9c8f425 279/**
78946b9b 280 * The standard implementation of the core_renderer interface.
d9c8f425 281 *
282 * @copyright 2009 Tim Hunt
7a3c215b
SH
283 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
284 * @since Moodle 2.0
f8129210 285 * @package core
76be40cc 286 * @category output
d9c8f425 287 */
78946b9b 288class core_renderer extends renderer_base {
72009b87
PS
289 /**
290 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
291 * in layout files instead.
72009b87 292 * @deprecated
f8129210 293 * @var string used in {@link core_renderer::header()}.
72009b87 294 */
d9c8f425 295 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
7a3c215b
SH
296
297 /**
f8129210
SH
298 * @var string Used to pass information from {@link core_renderer::doctype()} to
299 * {@link core_renderer::standard_head_html()}.
7a3c215b 300 */
d9c8f425 301 protected $contenttype;
7a3c215b
SH
302
303 /**
f8129210
SH
304 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
305 * with {@link core_renderer::header()}.
7a3c215b 306 */
d9c8f425 307 protected $metarefreshtag = '';
7a3c215b
SH
308
309 /**
76be40cc 310 * @var string Unique token for the closing HTML
7a3c215b 311 */
72009b87 312 protected $unique_end_html_token;
7a3c215b
SH
313
314 /**
76be40cc 315 * @var string Unique token for performance information
7a3c215b 316 */
72009b87 317 protected $unique_performance_info_token;
7a3c215b
SH
318
319 /**
76be40cc 320 * @var string Unique token for the main content.
7a3c215b 321 */
72009b87
PS
322 protected $unique_main_content_token;
323
324 /**
325 * Constructor
7a3c215b 326 *
72009b87
PS
327 * @param moodle_page $page the page we are doing output for.
328 * @param string $target one of rendering target constants
329 */
330 public function __construct(moodle_page $page, $target) {
331 $this->opencontainers = $page->opencontainers;
332 $this->page = $page;
333 $this->target = $target;
334
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().']';
338 }
d9c8f425 339
340 /**
341 * Get the DOCTYPE declaration that should be used with this page. Designed to
342 * be called in theme layout.php files.
7a3c215b 343 *
13725b37 344 * @return string the DOCTYPE declaration that should be used.
d9c8f425 345 */
346 public function doctype() {
13725b37
PS
347 if ($this->page->theme->doctype === 'html5') {
348 $this->contenttype = 'text/html; charset=utf-8';
349 return "<!DOCTYPE html>\n";
d9c8f425 350
13725b37 351 } else if ($this->page->theme->doctype === 'xhtml5') {
d9c8f425 352 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
13725b37 353 return "<!DOCTYPE html>\n";
d9c8f425 354
355 } else {
13725b37
PS
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");
d9c8f425 359 }
d9c8f425 360 }
361
362 /**
363 * The attributes that should be added to the <html> tag. Designed to
364 * be called in theme layout.php files.
7a3c215b 365 *
d9c8f425 366 * @return string HTML fragment.
367 */
368 public function htmlattributes() {
13725b37
PS
369 $return = get_html_lang(true);
370 if ($this->page->theme->doctype !== 'html5') {
371 $return .= ' xmlns="http://www.w3.org/1999/xhtml"';
372 }
373 return $return;
d9c8f425 374 }
375
376 /**
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.
7a3c215b 380 *
d9c8f425 381 * @return string HTML fragment.
382 */
383 public function standard_head_html() {
b5bbeaf0 384 global $CFG, $SESSION;
59849f79
AN
385
386 // Before we output any content, we need to ensure that certain
387 // page components are set up.
388
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);
393 }
394
d9c8f425 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";
f8129210 398 // This is only set by the {@link redirect()} method
d9c8f425 399 $output .= $this->metarefreshtag;
400
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().'" />';
405 }
406
fcd2cbaf
PS
407 // flow player embedding support
408 $this->page->requires->js_function_call('M.util.load_flowplayer');
409
238b8bc9 410 // Set up help link popups for all links with the helptooltip class
afe3566c
ARN
411 $this->page->requires->js_init_call('M.util.help_popups.setup');
412
238b8bc9
ARN
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');
419
7d2a0492 420 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
d9c8f425 421
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
7d2a0492 427 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
d9c8f425 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
7d2a0492 434 $this->page->requires->js_function_call('focuscontrol', array($focus));
d9c8f425 435 }
436 }
437
78946b9b
PS
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
efaa4c08 440 $urls = $this->page->theme->css_urls($this->page);
78946b9b 441 foreach ($urls as $url) {
c0467479 442 $this->page->requires->css_theme($url);
78946b9b
PS
443 }
444
04c01408 445 // Get the theme javascript head and footer
d7656956
ARN
446 if ($jsurl = $this->page->theme->javascript_url(true)) {
447 $this->page->requires->js($jsurl, true);
448 }
449 if ($jsurl = $this->page->theme->javascript_url(false)) {
450 $this->page->requires->js($jsurl);
451 }
5d0c95a5 452
d9c8f425 453 // Get any HTML from the page_requirements_manager.
945f19f7 454 $output .= $this->page->requires->get_head_code($this->page, $this);
d9c8f425 455
456 // List alternate versions.
457 foreach ($this->page->alternateversions as $type => $alt) {
5d0c95a5 458 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
d9c8f425 459 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
460 }
8a7703ce 461
90e920c7
SH
462 if (!empty($CFG->additionalhtmlhead)) {
463 $output .= "\n".$CFG->additionalhtmlhead;
464 }
d9c8f425 465
466 return $output;
467 }
468
469 /**
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.
7a3c215b 472 *
d9c8f425 473 * @return string HTML fragment.
474 */
475 public function standard_top_of_body_html() {
90e920c7
SH
476 global $CFG;
477 $output = $this->page->requires->get_top_of_body_code();
478 if (!empty($CFG->additionalhtmltopofbody)) {
479 $output .= "\n".$CFG->additionalhtmltopofbody;
480 }
48e114a5
PS
481 $output .= $this->maintenance_warning();
482 return $output;
483 }
484
485 /**
486 * Scheduled maintenance warning message.
487 *
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.
490 *
491 * @return string
492 */
493 public function maintenance_warning() {
494 global $CFG;
495
496 $output = '';
497 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
f487a8f8
RT
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) ;
48e114a5 506 $output .= $this->box_end();
f487a8f8
RT
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');
48e114a5 512 }
90e920c7 513 return $output;
d9c8f425 514 }
515
516 /**
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.
7a3c215b 520 *
d9c8f425 521 * @return string HTML fragment.
522 */
523 public function standard_footer_html() {
6af80cae 524 global $CFG, $SCRIPT;
d9c8f425 525
ec3ce3a9
PS
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 '';
530 }
531
f8129210 532 // This function is normally called from a layout.php file in {@link core_renderer::header()}
d9c8f425 533 // but some of the content won't be known until later, so we return a placeholder
f8129210 534 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
72009b87 535 $output = $this->unique_performance_info_token;
e5824bb9 536 if ($this->page->devicetypeinuse == 'legacy') {
ee8df661
SH
537 // The legacy theme is in use print the notification
538 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
539 }
37959dd4 540
e5824bb9 541 // Get links to switch device types (only shown for users not on a default device)
37959dd4
AF
542 $output .= $this->theme_switch_links();
543
d9c8f425 544 if (!empty($CFG->debugpageinfo)) {
d4c3f025 545 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
d9c8f425 546 }
b0c6dc1c 547 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
6af80cae
EL
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');
4ac92d2a 552 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
6af80cae
EL
553 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
554 $output .= '<div class="profilingfooter">' . $link . '</div>';
555 }
2d22f3d9
TH
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>';
ba6c97ee 560 }
d9c8f425 561 if (!empty($CFG->debugvalidators)) {
f0202ae9 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
d9c8f425 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>';
568 }
569 return $output;
570 }
571
72009b87
PS
572 /**
573 * Returns standard main content placeholder.
574 * Designed to be called in theme layout.php files.
7a3c215b 575 *
72009b87
PS
576 * @return string HTML fragment.
577 */
578 public function main_content() {
537ba512
SH
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>';
72009b87
PS
586 }
587
d9c8f425 588 /**
589 * The standard tags (typically script tags that are not needed earlier) that
391edc51 590 * should be output after everything else. Designed to be called in theme layout.php files.
7a3c215b 591 *
d9c8f425 592 * @return string HTML fragment.
593 */
594 public function standard_end_of_body_html() {
391edc51
TH
595 global $CFG;
596
f8129210 597 // This function is normally called from a layout.php file in {@link core_renderer::header()}
d9c8f425 598 // but some of the content won't be known until later, so we return a placeholder
f8129210 599 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
391edc51
TH
600 $output = '';
601 if (!empty($CFG->additionalhtmlfooter)) {
602 $output .= "\n".$CFG->additionalhtmlfooter;
603 }
604 $output .= $this->unique_end_html_token;
605 return $output;
d9c8f425 606 }
607
608 /**
609 * Return the standard string that says whether you are logged in (and switched
610 * roles/logged in as another user).
2d0e682d
MV
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.
d9c8f425 614 * @return string HTML fragment.
615 */
2d0e682d 616 public function login_info($withlinks = null) {
8f0fe0b8 617 global $USER, $CFG, $DB, $SESSION;
4bcc5118 618
244a32c6
PS
619 if (during_initial_install()) {
620 return '';
621 }
4bcc5118 622
2d0e682d
MV
623 if (is_null($withlinks)) {
624 $withlinks = empty($this->page->layout_options['nologinlinks']);
625 }
626
1dedecf2 627 $loginpage = ((string)$this->page->url === get_login_url());
244a32c6 628 $course = $this->page->course;
d79d5ac2
PS
629 if (\core\session\manager::is_loggedinas()) {
630 $realuser = \core\session\manager::get_realuser();
244a32c6 631 $fullname = fullname($realuser, true);
2d0e682d 632 if ($withlinks) {
fa84b901
RT
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>] ";
2d0e682d
MV
636 } else {
637 $realuserinfo = " [$fullname] ";
638 }
244a32c6
PS
639 } else {
640 $realuserinfo = '';
641 }
4bcc5118 642
244a32c6 643 $loginurl = get_login_url();
4bcc5118 644
244a32c6
PS
645 if (empty($course->id)) {
646 // $course->id is not defined during installation
647 return '';
4f0c2d00 648 } else if (isloggedin()) {
b0c6dc1c 649 $context = context_course::instance($course->id);
4bcc5118 650
244a32c6 651 $fullname = fullname($USER, true);
03d9401e 652 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
2d0e682d 653 if ($withlinks) {
c7fe9f81
RT
654 $linktitle = get_string('viewprofile');
655 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
2d0e682d
MV
656 } else {
657 $username = $fullname;
658 }
244a32c6 659 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
2d0e682d
MV
660 if ($withlinks) {
661 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
662 } else {
663 $username .= " from {$idprovider->name}";
664 }
244a32c6 665 }
b3df1764 666 if (isguestuser()) {
2778744b 667 $loggedinas = $realuserinfo.get_string('loggedinasguest');
2d0e682d 668 if (!$loginpage && $withlinks) {
2778744b
PS
669 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
670 }
f5c1e621 671 } else if (is_role_switched($course->id)) { // Has switched roles
244a32c6
PS
672 $rolename = '';
673 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
f2cf0f84 674 $rolename = ': '.role_get_name($role, $context);
244a32c6 675 }
2d0e682d
MV
676 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
677 if ($withlinks) {
aae028d9 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)));
8bf91fb8 679 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
2d0e682d 680 }
244a32c6 681 } else {
2d0e682d
MV
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>)';
685 }
244a32c6
PS
686 }
687 } else {
2778744b 688 $loggedinas = get_string('loggedinnot', 'moodle');
2d0e682d 689 if (!$loginpage && $withlinks) {
2778744b
PS
690 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
691 }
244a32c6 692 }
4bcc5118 693
244a32c6 694 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
4bcc5118 695
244a32c6
PS
696 if (isset($SESSION->justloggedin)) {
697 unset($SESSION->justloggedin);
698 if (!empty($CFG->displayloginfailures)) {
b3df1764 699 if (!isguestuser()) {
52dc1de7
AA
700 // Include this file only when required.
701 require_once($CFG->dirroot . '/user/lib.php');
702 if ($count = user_count_login_failures($USER)) {
2b0c88e2 703 $loggedinas .= '<div class="loginfailures">';
52dc1de7
AA
704 $a = new stdClass();
705 $a->attempts = $count;
706 $loggedinas .= get_string('failedloginattempts', '', $a);
b0c6dc1c 707 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
46fa0628
DP
708 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
709 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
244a32c6
PS
710 }
711 $loggedinas .= '</div>';
712 }
713 }
714 }
715 }
4bcc5118 716
244a32c6 717 return $loggedinas;
d9c8f425 718 }
719
720 /**
721 * Return the 'back' link that normally appears in the footer.
7a3c215b 722 *
d9c8f425 723 * @return string HTML fragment.
724 */
725 public function home_link() {
726 global $CFG, $SITE;
727
728 if ($this->page->pagetype == 'site-index') {
729 // Special case for site home page - please do not remove
730 return '<div class="sitelink">' .
34dff6aa 731 '<a title="Moodle" href="http://moodle.org/">' .
970c4419 732 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
d9c8f425 733
734 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
735 // Special case for during install/upgrade.
736 return '<div class="sitelink">'.
34dff6aa 737 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
970c4419 738 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
d9c8f425 739
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>';
743
744 } else {
745 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
8ebbb06a 746 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
d9c8f425 747 }
748 }
749
750 /**
751 * Redirects the user by any means possible given the current state
752 *
753 * This function should not be called directly, it should always be called using
754 * the redirect function in lib/weblib.php
755 *
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
758 *
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
768 */
769 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
770 global $CFG;
771 $url = str_replace('&amp;', '&', $encodedurl);
772
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";
593f9b87 779 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
d9c8f425 780 }
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) {
593f9b87 791 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
d9c8f425 792 }
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;
799 }
800 $output .= $this->notification($message, 'redirectmessage');
3ab2e357 801 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
d9c8f425 802 if ($debugdisableredirect) {
803 $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
804 }
805 $output .= $this->footer();
806 return $output;
807 }
808
809 /**
810 * Start output by sending the HTTP headers, and printing the HTML <head>
811 * and the start of the <body>.
812 *
813 * To control what is printed, you should set properties on $PAGE. If you
f8129210 814 * are familiar with the old {@link print_header()} function from Moodle 1.9
d9c8f425 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.
817 *
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.
820 *
d9c8f425 821 * @return string HTML that you must output this, preferably immediately.
822 */
e120c61d 823 public function header() {
d9c8f425 824 global $USER, $CFG;
825
d79d5ac2 826 if (\core\session\manager::is_loggedinas()) {
e884f63a
PS
827 $this->page->add_body_class('userloggedinas');
828 }
829
46629116
JC
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');
835 }
836
63c88397
PS
837 // Give themes a chance to init/alter the page object.
838 $this->page->theme->init_page($this->page);
839
d9c8f425 840 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
841
78946b9b
PS
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);
67e84a7f 846
78946b9b 847 // Slice the rendered output into header and footer.
72009b87
PS
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;
854 }
855
d9c8f425 856 if ($cutpos === false) {
72009b87 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.');
d9c8f425 858 }
78946b9b 859 $header = substr($rendered, 0, $cutpos);
72009b87 860 $footer = substr($rendered, $cutpos + strlen($token));
d9c8f425 861
862 if (empty($this->contenttype)) {
78946b9b 863 debugging('The page layout file did not call $OUTPUT->doctype()');
67e84a7f 864 $header = $this->doctype() . $header;
d9c8f425 865 }
866
fdd4b9a5
MG
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;
881 }
882 }
883
d9c8f425 884 send_headers($this->contenttype, $this->page->cacheable);
67e84a7f 885
d9c8f425 886 $this->opencontainers->push('header/footer', $footer);
887 $this->page->set_state(moodle_page::STATE_IN_BODY);
67e84a7f 888
29ba64e5 889 return $header . $this->skip_link_target('maincontent');
d9c8f425 890 }
891
892 /**
78946b9b 893 * Renders and outputs the page layout file.
7a3c215b
SH
894 *
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.
898 *
78946b9b 899 * @param string $layoutfile The name of the layout file
d9c8f425 900 * @return string HTML code
901 */
78946b9b 902 protected function render_page_layout($layoutfile) {
92e01ab7 903 global $CFG, $SITE, $USER;
d9c8f425 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
78946b9b 906 // the global $OUTPUT object. When rendering the page layout file, we want to use
d9c8f425 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;
913
d9c8f425 914 ob_start();
78946b9b
PS
915 include($layoutfile);
916 $rendered = ob_get_contents();
d9c8f425 917 ob_end_clean();
78946b9b 918 return $rendered;
d9c8f425 919 }
920
921 /**
922 * Outputs the page's footer
7a3c215b 923 *
d9c8f425 924 * @return string HTML fragment
925 */
926 public function footer() {
d5a8d9aa 927 global $CFG, $DB;
0f0801f4 928
f6794ace 929 $output = $this->container_end_all(true);
4d2ee4c2 930
d9c8f425 931 $footer = $this->opencontainers->pop('header/footer');
932
d5a8d9aa 933 if (debugging() and $DB and $DB->is_transaction_started()) {
03221650 934 // TODO: MDL-20625 print warning - transaction will be rolled back
d5a8d9aa
PS
935 }
936
d9c8f425 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();
d9c8f425 941 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
942 $performanceinfo = $perf['html'];
943 }
944 }
58a3a34e
DM
945
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;
949 }
72009b87 950 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
d9c8f425 951
72009b87 952 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
d9c8f425 953
954 $this->page->set_state(moodle_page::STATE_DONE);
d9c8f425 955
956 return $output . $footer;
957 }
958
f6794ace
PS
959 /**
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.
7a3c215b 963 *
f6794ace
PS
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>.
967 */
968 public function container_end_all($shouldbenone = false) {
969 return $this->opencontainers->pop_all_but_last($shouldbenone);
970 }
971
fdd4b9a5
MG
972 /**
973 * Returns course-specific information to be output immediately above content on any course page
974 * (for the current course)
975 *
976 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
977 * @return string
978 */
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 '';
984 }
985 static $functioncalled = false;
986 if ($functioncalled && $onlyifnotcalledbefore) {
987 // we have already output the content header
988 return '';
989 }
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) {
06a72e01 994 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
fdd4b9a5
MG
995 }
996 return '';
997 }
998
999 /**
1000 * Returns course-specific information to be output immediately below content on any course page
1001 * (for the current course)
1002 *
1003 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1004 * @return string
1005 */
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 '';
1011 }
1012 static $functioncalled = false;
1013 if ($functioncalled && $onlyifnotcalledbefore) {
1014 // we have already output the content footer
1015 return '';
1016 }
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) {
06a72e01 1021 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
fdd4b9a5
MG
1022 }
1023 return '';
1024 }
1025
1026 /**
1027 * Returns course-specific information to be output on any course page in the header area
1028 * (for the current course)
1029 *
1030 * @return string
1031 */
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 '';
1037 }
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);
1042 }
1043 return '';
1044 }
1045
1046 /**
1047 * Returns course-specific information to be output on any course page in the footer area
1048 * (for the current course)
1049 *
1050 * @return string
1051 */
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 '';
1057 }
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);
1062 }
1063 return '';
1064 }
1065
244a32c6
PS
1066 /**
1067 * Returns lang menu or '', this method also checks forcing of languages in courses.
7a3c215b 1068 *
2fada290
MG
1069 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1070 *
7a3c215b 1071 * @return string The lang menu HTML or empty string
244a32c6
PS
1072 */
1073 public function lang_menu() {
1074 global $CFG;
1075
1076 if (empty($CFG->langmenu)) {
1077 return '';
1078 }
1079
1080 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1081 // do not show lang menu if language forced
1082 return '';
1083 }
1084
1085 $currlang = current_language();
1f96e907 1086 $langs = get_string_manager()->get_list_of_translations();
4bcc5118 1087
244a32c6
PS
1088 if (count($langs) < 2) {
1089 return '';
1090 }
1091
a9967cf5
PS
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);
244a32c6
PS
1096 }
1097
d9c8f425 1098 /**
1099 * Output the row of editing icons for a block, as defined by the controls array.
7a3c215b 1100 *
f8129210 1101 * @param array $controls an array like {@link block_contents::$controls}.
b59f2e3b 1102 * @param string $blockid The ID given to the block.
7a3c215b 1103 * @return string HTML fragment.
d9c8f425 1104 */
b59f2e3b 1105 public function block_controls($actions, $blockid = null) {
10fc1569 1106 global $CFG;
b59f2e3b
SH
1107 if (empty($actions)) {
1108 return '';
1109 }
cf69a00a 1110 $menu = new action_menu($actions);
b59f2e3b
SH
1111 if ($blockid !== null) {
1112 $menu->set_owner_selector('#'.$blockid);
1113 }
ae3fd8eb 1114 $menu->set_constraint('.block-region');
b59f2e3b 1115 $menu->attributes['class'] .= ' block-control-actions commands';
10fc1569
SH
1116 if (isset($CFG->blockeditingmenu) && !$CFG->blockeditingmenu) {
1117 $menu->do_not_enhance();
1118 }
b59f2e3b
SH
1119 return $this->render($menu);
1120 }
1121
1122 /**
1123 * Renders an action menu component.
1124 *
3665af78
SH
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
1128 *
b59f2e3b
SH
1129 * @param action_menu $menu
1130 * @return string HTML
1131 */
1132 public function render_action_menu(action_menu $menu) {
1133 $menu->initialise_js($this->page);
1134
1135 $output = html_writer::start_tag('div', $menu->attributes);
3665af78 1136 $output .= html_writer::start_tag('ul', $menu->attributesprimary);
b59f2e3b
SH
1137 foreach ($menu->get_primary_actions($this) as $action) {
1138 if ($action instanceof renderable) {
3665af78 1139 $content = $this->render($action);
b59f2e3b 1140 } else {
3665af78 1141 $content = $action;
e282c679 1142 }
11dd4dad 1143 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
d9c8f425 1144 }
3665af78
SH
1145 $output .= html_writer::end_tag('ul');
1146 $output .= html_writer::start_tag('ul', $menu->attributessecondary);
b59f2e3b 1147 foreach ($menu->get_secondary_actions() as $action) {
3665af78
SH
1148 if ($action instanceof renderable) {
1149 $content = $this->render($action);
3665af78
SH
1150 } else {
1151 $content = $action;
3665af78 1152 }
11dd4dad 1153 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
b59f2e3b 1154 }
3665af78 1155 $output .= html_writer::end_tag('ul');
b59f2e3b 1156 $output .= html_writer::end_tag('div');
e282c679 1157 return $output;
d9c8f425 1158 }
1159
cf69a00a 1160 /**
3665af78 1161 * Renders an action_menu_link item.
cf69a00a 1162 *
3665af78 1163 * @param action_menu_link $action
cf69a00a
SH
1164 * @return string HTML fragment
1165 */
3665af78 1166 protected function render_action_menu_link(action_menu_link $action) {
d0647301
SH
1167 static $actioncount = 0;
1168 $actioncount++;
cf69a00a 1169
ea5a01fb 1170 $comparetoalt = '';
cf69a00a 1171 $text = '';
ea5a01fb 1172 if (!$action->icon || $action->primary === false) {
d0647301 1173 $text .= html_writer::start_tag('span', array('class'=>'menu-action-text', 'id' => 'actionmenuaction-'.$actioncount));
cf69a00a
SH
1174 if ($action->text instanceof renderable) {
1175 $text .= $this->render($action->text);
1176 } else {
1177 $text .= $action->text;
cfd1e08a 1178 $comparetoalt = (string)$action->text;
cf69a00a
SH
1179 }
1180 $text .= html_writer::end_tag('span');
1181 }
1182
ea5a01fb
SH
1183 $icon = '';
1184 if ($action->icon) {
1185 $icon = $action->icon;
f803ce26 1186 if ($action->primary || !$action->actionmenu->will_be_enhanced()) {
ea5a01fb
SH
1187 $action->attributes['title'] = $action->text;
1188 }
cfd1e08a
SH
1189 if (!$action->primary && $action->actionmenu->will_be_enhanced()) {
1190 if ((string)$icon->attributes['alt'] === $comparetoalt) {
d0647301 1191 $icon->attributes['alt'] = '';
cfd1e08a 1192 }
c7a2291f 1193 if (isset($icon->attributes['title']) && (string)$icon->attributes['title'] === $comparetoalt) {
cfd1e08a
SH
1194 unset($icon->attributes['title']);
1195 }
1196 }
ea5a01fb
SH
1197 $icon = $this->render($icon);
1198 }
1199
3665af78 1200 // A disabled link is rendered as formatted text.
cf69a00a 1201 if (!empty($action->attributes['disabled'])) {
3665af78 1202 // Do not use div here due to nesting restriction in xhtml strict.
ea5a01fb 1203 return html_writer::tag('span', $icon.$text, array('class'=>'currentlink', 'role' => 'menuitem'));
cf69a00a
SH
1204 }
1205
1206 $attributes = $action->attributes;
1207 unset($action->attributes['disabled']);
1208 $attributes['href'] = $action->url;
d0647301
SH
1209 if ($text !== '') {
1210 $attributes['aria-labelledby'] = 'actionmenuaction-'.$actioncount;
1211 }
cf69a00a 1212
ea5a01fb 1213 return html_writer::tag('a', $icon.$text, $attributes);
cf69a00a
SH
1214 }
1215
9ac099a1
AN
1216 /**
1217 * Renders a primary action_menu_filler item.
1218 *
1219 * @param action_menu_link_filler $action
1220 * @return string HTML fragment
1221 */
1222 protected function render_action_menu_filler(action_menu_filler $action) {
1223 return html_writer::span('&nbsp;', 'filler');
1224 }
1225
cf69a00a 1226 /**
3665af78 1227 * Renders a primary action_menu_link item.
cf69a00a 1228 *
3665af78 1229 * @param action_menu_link_primary $action
cf69a00a
SH
1230 * @return string HTML fragment
1231 */
3665af78
SH
1232 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1233 return $this->render_action_menu_link($action);
cf69a00a
SH
1234 }
1235
1236 /**
3665af78 1237 * Renders a secondary action_menu_link item.
cf69a00a 1238 *
3665af78 1239 * @param action_menu_link_secondary $action
cf69a00a
SH
1240 * @return string HTML fragment
1241 */
3665af78
SH
1242 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1243 return $this->render_action_menu_link($action);
cf69a00a
SH
1244 }
1245
d9c8f425 1246 /**
1247 * Prints a nice side block with an optional header.
1248 *
1249 * The content is described
f8129210 1250 * by a {@link core_renderer::block_contents} object.
d9c8f425 1251 *
cbb54cce
SH
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>
1262 *
d9c8f425 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.
1266 */
7a3c215b 1267 public function block(block_contents $bc, $region) {
d9c8f425 1268 $bc = clone($bc); // Avoid messing up the object passed in.
dd72b308
PS
1269 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1270 $bc->collapsible = block_contents::NOT_HIDEABLE;
1271 }
84192d78
SH
1272 if (!empty($bc->blockinstanceid)) {
1273 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1274 }
91d941c3
SH
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;
1280 }
84192d78
SH
1281 if ($bc->dockable) {
1282 $bc->attributes['data-dockable'] = 1;
1283 }
dd72b308
PS
1284 if ($bc->collapsible == block_contents::HIDDEN) {
1285 $bc->add_class('hidden');
1286 }
1287 if (!empty($bc->controls)) {
1288 $bc->add_class('block_with_controls');
1289 }
d9c8f425 1290
91d941c3 1291
d9c8f425 1292 if (empty($skiptitle)) {
1293 $output = '';
1294 $skipdest = '';
1295 } else {
26acc814
PS
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'));
d9c8f425 1298 }
4d2ee4c2 1299
5d0c95a5 1300 $output .= html_writer::start_tag('div', $bc->attributes);
d9c8f425 1301
9f5c39b5
SH
1302 $output .= $this->block_header($bc);
1303 $output .= $this->block_content($bc);
1304
1305 $output .= html_writer::end_tag('div');
1306
1307 $output .= $this->block_annotation($bc);
1308
1309 $output .= $skipdest;
1310
1311 $this->init_block_hider_js($bc);
1312 return $output;
1313 }
1314
1315 /**
1316 * Produces a header for a block
fa7f2a45 1317 *
9f5c39b5
SH
1318 * @param block_contents $bc
1319 * @return string
1320 */
1321 protected function block_header(block_contents $bc) {
d9c8f425 1322
1323 $title = '';
1324 if ($bc->title) {
91d941c3
SH
1325 $attributes = array();
1326 if ($bc->blockinstanceid) {
1327 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1328 }
1329 $title = html_writer::tag('h2', $bc->title, $attributes);
d9c8f425 1330 }
1331
b59f2e3b
SH
1332 $blockid = null;
1333 if (isset($bc->attributes['id'])) {
1334 $blockid = $bc->attributes['id'];
1335 }
1336 $controlshtml = $this->block_controls($bc->controls, $blockid);
9f5c39b5
SH
1337
1338 $output = '';
d9c8f425 1339 if ($title || $controlshtml) {
46de77b6 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'));
d9c8f425 1341 }
9f5c39b5
SH
1342 return $output;
1343 }
d9c8f425 1344
9f5c39b5
SH
1345 /**
1346 * Produces the content area for a block
1347 *
1348 * @param block_contents $bc
1349 * @return string
1350 */
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)) {
46de77b6
SH
1354 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1355 }
d9c8f425 1356 $output .= $bc->content;
9f5c39b5
SH
1357 $output .= $this->block_footer($bc);
1358 $output .= html_writer::end_tag('div');
fa7f2a45 1359
9f5c39b5
SH
1360 return $output;
1361 }
d9c8f425 1362
9f5c39b5
SH
1363 /**
1364 * Produces the footer for a block
1365 *
1366 * @param block_contents $bc
1367 * @return string
1368 */
1369 protected function block_footer(block_contents $bc) {
1370 $output = '';
d9c8f425 1371 if ($bc->footer) {
26acc814 1372 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
d9c8f425 1373 }
9f5c39b5
SH
1374 return $output;
1375 }
d9c8f425 1376
9f5c39b5
SH
1377 /**
1378 * Produces the annotation for a block
1379 *
1380 * @param block_contents $bc
1381 * @return string
1382 */
1383 protected function block_annotation(block_contents $bc) {
1384 $output = '';
d9c8f425 1385 if ($bc->annotation) {
26acc814 1386 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
d9c8f425 1387 }
d9c8f425 1388 return $output;
1389 }
1390
1391 /**
1392 * Calls the JS require function to hide a block.
7a3c215b 1393 *
d9c8f425 1394 * @param block_contents $bc A block_contents object
d9c8f425 1395 */
dd72b308
PS
1396 protected function init_block_hider_js(block_contents $bc) {
1397 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
cbb54cce
SH
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);
1404
1405 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1406 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
d9c8f425 1407 }
1408 }
1409
1410 /**
1411 * Render the contents of a block_list.
7a3c215b 1412 *
d9c8f425 1413 * @param array $icons the icon for each item.
1414 * @param array $items the content of each item.
1415 * @return string HTML
1416 */
1417 public function list_block_contents($icons, $items) {
1418 $row = 0;
1419 $lis = array();
1420 foreach ($items as $key => $string) {
5d0c95a5 1421 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
2c5ec833 1422 if (!empty($icons[$key])) { //test if the content has an assigned icon
26acc814 1423 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
d9c8f425 1424 }
26acc814 1425 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
5d0c95a5 1426 $item .= html_writer::end_tag('li');
d9c8f425 1427 $lis[] = $item;
1428 $row = 1 - $row; // Flip even/odd.
1429 }
f2a04fc1 1430 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
d9c8f425 1431 }
1432
1433 /**
1434 * Output all the blocks in a particular region.
7a3c215b 1435 *
d9c8f425 1436 * @param string $region the name of a region on this page.
1437 * @return string the HTML to be output.
1438 */
1439 public function blocks_for_region($region) {
1440 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
6671fa73
JF
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;
1446 }
d9c8f425 1447 $output = '';
6671fa73 1448
d9c8f425 1449 foreach ($blockcontents as $bc) {
1450 if ($bc instanceof block_contents) {
1451 $output .= $this->block($bc, $region);
6671fa73 1452 $lastblock = $bc->title;
d9c8f425 1453 } else if ($bc instanceof block_move_target) {
686e3b3a 1454 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
d9c8f425 1455 } else {
1456 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1457 }
1458 }
1459 return $output;
1460 }
1461
1462 /**
1463 * Output a place where the block that is currently being moved can be dropped.
7a3c215b 1464 *
d9c8f425 1465 * @param block_move_target $target with the necessary details.
6671fa73
JF
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.
686e3b3a 1468 * @param string $region the name of the region
d9c8f425 1469 * @return string the HTML to be output.
1470 */
686e3b3a 1471 public function block_move_target($target, $zones, $previous, $region) {
0e2ca62e 1472 if ($previous == null) {
686e3b3a
FM
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]);
1479 }
6671fa73
JF
1480 } else {
1481 $position = get_string('moveblockafter', 'block', $previous);
1482 }
1483 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
d9c8f425 1484 }
1485
574fbea4 1486 /**
996b1e0c 1487 * Renders a special html link with attached action
574fbea4 1488 *
2fada290
MG
1489 * Theme developers: DO NOT OVERRIDE! Please override function
1490 * {@link core_renderer::render_action_link()} instead.
1491 *
574fbea4
PS
1492 * @param string|moodle_url $url
1493 * @param string $text HTML fragment
1494 * @param component_action $action
11820bac 1495 * @param array $attributes associative array of html link attributes + disabled
e282c679 1496 * @param pix_icon optional pix icon to render with the link
7a3c215b 1497 * @return string HTML fragment
574fbea4 1498 */
e282c679 1499 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
574fbea4
PS
1500 if (!($url instanceof moodle_url)) {
1501 $url = new moodle_url($url);
1502 }
e282c679 1503 $link = new action_link($url, $text, $action, $attributes, $icon);
574fbea4 1504
f14b641b 1505 return $this->render($link);
574fbea4
PS
1506 }
1507
1508 /**
7a3c215b
SH
1509 * Renders an action_link object.
1510 *
1511 * The provided link is renderer and the HTML returned. At the same time the
f8129210 1512 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
7a3c215b 1513 *
574fbea4
PS
1514 * @param action_link $link
1515 * @return string HTML fragment
1516 */
1517 protected function render_action_link(action_link $link) {
1518 global $CFG;
1519
e282c679
SH
1520 $text = '';
1521 if ($link->icon) {
1522 $text .= $this->render($link->icon);
1523 }
1524
7749e187 1525 if ($link->text instanceof renderable) {
e282c679 1526 $text .= $this->render($link->text);
7749e187 1527 } else {
e282c679 1528 $text .= $link->text;
7749e187
SH
1529 }
1530
574fbea4
PS
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
7749e187 1534 return html_writer::tag('span', $text, array('class'=>'currentlink'));
574fbea4 1535 }
11820bac 1536
574fbea4
PS
1537 $attributes = $link->attributes;
1538 unset($link->attributes['disabled']);
1539 $attributes['href'] = $link->url;
1540
1541 if ($link->actions) {
f14b641b 1542 if (empty($attributes['id'])) {
574fbea4
PS
1543 $id = html_writer::random_id('action_link');
1544 $attributes['id'] = $id;
1545 } else {
1546 $id = $attributes['id'];
1547 }
1548 foreach ($link->actions as $action) {
c80877aa 1549 $this->add_action_handler($action, $id);
574fbea4
PS
1550 }
1551 }
1552
7749e187 1553 return html_writer::tag('a', $text, $attributes);
574fbea4
PS
1554 }
1555
c63923bd
PS
1556
1557 /**
7a3c215b
SH
1558 * Renders an action_icon.
1559 *
f8129210 1560 * This function uses the {@link core_renderer::action_link()} method for the
7a3c215b
SH
1561 * most part. What it does different is prepare the icon as HTML and use it
1562 * as the link text.
c63923bd 1563 *
2fada290
MG
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()}.
1567 *
c63923bd
PS
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
1574 */
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);
1578 }
1579 $attributes = (array)$attributes;
1580
524645e7 1581 if (empty($attributes['class'])) {
c63923bd
PS
1582 // let ppl override the class via $options
1583 $attributes['class'] = 'action-icon';
1584 }
1585
1586 $icon = $this->render($pixicon);
1587
1588 if ($linktext) {
1589 $text = $pixicon->attributes['alt'];
1590 } else {
1591 $text = '';
1592 }
1593
1594 return $this->action_link($url, $text.$icon, $action, $attributes);
1595 }
1596
d9c8f425 1597 /**
0b634d75 1598 * Print a message along with button choices for Continue/Cancel
1599 *
4ed85790 1600 * If a string or moodle_url is given instead of a single_button, method defaults to post.
0b634d75 1601 *
d9c8f425 1602 * @param string $message The question to ask the user
3ba60ee1
PS
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
d9c8f425 1605 * @return string HTML fragment
1606 */
1607 public function confirm($message, $continue, $cancel) {
4871a238 1608 if ($continue instanceof single_button) {
11820bac 1609 // ok
4871a238
PS
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) {
26eab8d4 1613 $continue = new single_button($continue, get_string('continue'), 'post');
d9c8f425 1614 } else {
4ed85790 1615 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
d9c8f425 1616 }
1617
4871a238 1618 if ($cancel instanceof single_button) {
11820bac 1619 // ok
4871a238
PS
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) {
26eab8d4 1623 $cancel = new single_button($cancel, get_string('cancel'), 'get');
d9c8f425 1624 } else {
4ed85790 1625 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
d9c8f425 1626 }
1627
d9c8f425 1628 $output = $this->box_start('generalbox', 'notice');
26acc814
PS
1629 $output .= html_writer::tag('p', $message);
1630 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
d9c8f425 1631 $output .= $this->box_end();
1632 return $output;
1633 }
1634
3cd5305f 1635 /**
3ba60ee1 1636 * Returns a form with a single button.
3cd5305f 1637 *
2fada290
MG
1638 * Theme developers: DO NOT OVERRIDE! Please override function
1639 * {@link core_renderer::render_single_button()} instead.
1640 *
3ba60ee1 1641 * @param string|moodle_url $url
3cd5305f
PS
1642 * @param string $label button text
1643 * @param string $method get or post submit method
3ba60ee1 1644 * @param array $options associative array {disabled, title, etc.}
3cd5305f
PS
1645 * @return string HTML fragment
1646 */
3ba60ee1 1647 public function single_button($url, $label, $method='post', array $options=null) {
574fbea4
PS
1648 if (!($url instanceof moodle_url)) {
1649 $url = new moodle_url($url);
3ba60ee1 1650 }
574fbea4
PS
1651 $button = new single_button($url, $label, $method);
1652
3ba60ee1
PS
1653 foreach ((array)$options as $key=>$value) {
1654 if (array_key_exists($key, $button)) {
1655 $button->$key = $value;
1656 }
3cd5305f
PS
1657 }
1658
3ba60ee1 1659 return $this->render($button);
3cd5305f
PS
1660 }
1661
d9c8f425 1662 /**
7a3c215b
SH
1663 * Renders a single button widget.
1664 *
1665 * This will return HTML to display a form containing a single button.
1666 *
3ba60ee1 1667 * @param single_button $button
d9c8f425 1668 * @return string HTML fragment
1669 */
3ba60ee1
PS
1670 protected function render_single_button(single_button $button) {
1671 $attributes = array('type' => 'submit',
1672 'value' => $button->label,
db09524d 1673 'disabled' => $button->disabled ? 'disabled' : null,
3ba60ee1
PS
1674 'title' => $button->tooltip);
1675
1676 if ($button->actions) {
1677 $id = html_writer::random_id('single_button');
1678 $attributes['id'] = $id;
1679 foreach ($button->actions as $action) {
c80877aa 1680 $this->add_action_handler($action, $id);
3ba60ee1 1681 }
d9c8f425 1682 }
d9c8f425 1683
3ba60ee1
PS
1684 // first the input element
1685 $output = html_writer::empty_tag('input', $attributes);
d9c8f425 1686
3ba60ee1
PS
1687 // then hidden fields
1688 $params = $button->url->params();
1689 if ($button->method === 'post') {
1690 $params['sesskey'] = sesskey();
1691 }
1692 foreach ($params as $var => $val) {
1693 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1694 }
d9c8f425 1695
3ba60ee1 1696 // then div wrapper for xhtml strictness
26acc814 1697 $output = html_writer::tag('div', $output);
d9c8f425 1698
3ba60ee1 1699 // now the form itself around it
a12cd69c
DM
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
1704 }
a6855934
PS
1705 if ($url === '') {
1706 $url = '#'; // there has to be always some action
1707 }
3ba60ee1 1708 $attributes = array('method' => $button->method,
a6855934 1709 'action' => $url,
3ba60ee1 1710 'id' => $button->formid);
26acc814 1711 $output = html_writer::tag('form', $output, $attributes);
d9c8f425 1712
3ba60ee1 1713 // and finally one more wrapper with class
26acc814 1714 return html_writer::tag('div', $output, array('class' => $button->class));
d9c8f425 1715 }
1716
a9967cf5 1717 /**
ab08be98 1718 * Returns a form with a single select widget.
7a3c215b 1719 *
2fada290
MG
1720 * Theme developers: DO NOT OVERRIDE! Please override function
1721 * {@link core_renderer::render_single_select()} instead.
1722 *
a9967cf5
PS
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
f8dab966 1728 * @param string $formid
a9967cf5
PS
1729 * @return string HTML fragment
1730 */
7a3c215b 1731 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
a9967cf5
PS
1732 if (!($url instanceof moodle_url)) {
1733 $url = new moodle_url($url);
1734 }
f8dab966 1735 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
a9967cf5
PS
1736
1737 return $this->render($select);
1738 }
1739
1740 /**
1741 * Internal implementation of single_select rendering
7a3c215b 1742 *
a9967cf5
PS
1743 * @param single_select $select
1744 * @return string HTML fragment
1745 */
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');
1750 }
1751
1752 $output = '';
1753 $params = $select->url->params();
1754 if ($select->method === 'post') {
1755 $params['sesskey'] = sesskey();
1756 }
1757 foreach ($params as $name=>$value) {
1758 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1759 }
1760
1761 if (empty($select->attributes['id'])) {
1762 $select->attributes['id'] = html_writer::random_id('single_select');
1763 }
1764
0b2cb132
PS
1765 if ($select->disabled) {
1766 $select->attributes['disabled'] = 'disabled';
1767 }
4d10e579 1768
a9967cf5
PS
1769 if ($select->tooltip) {
1770 $select->attributes['title'] = $select->tooltip;
1771 }
1772
7266bd3e
ARN
1773 $select->attributes['class'] = 'autosubmit';
1774 if ($select->class) {
1775 $select->attributes['class'] .= ' ' . $select->class;
1776 }
1777
a9967cf5 1778 if ($select->label) {
ecc5cc31 1779 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
a9967cf5
PS
1780 }
1781
1782 if ($select->helpicon instanceof help_icon) {
1783 $output .= $this->render($select->helpicon);
1784 }
a9967cf5
PS
1785 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1786
1787 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
ebc583e4 1788 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
a9967cf5
PS
1789
1790 $nothing = empty($select->nothing) ? false : key($select->nothing);
7266bd3e
ARN
1791 $this->page->requires->yui_module('moodle-core-formautosubmit',
1792 'M.core.init_formautosubmit',
1793 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1794 );
a9967cf5
PS
1795
1796 // then div wrapper for xhtml strictness
26acc814 1797 $output = html_writer::tag('div', $output);
a9967cf5
PS
1798
1799 // now the form itself around it
a12cd69c
DM
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
1804 }
a9967cf5 1805 $formattributes = array('method' => $select->method,
a12cd69c 1806 'action' => $url,
a9967cf5 1807 'id' => $select->formid);
26acc814 1808 $output = html_writer::tag('form', $output, $formattributes);
4d10e579
PS
1809
1810 // and finally one more wrapper with class
26acc814 1811 return html_writer::tag('div', $output, array('class' => $select->class));
4d10e579
PS
1812 }
1813
1814 /**
ab08be98 1815 * Returns a form with a url select widget.
7a3c215b 1816 *
2fada290
MG
1817 * Theme developers: DO NOT OVERRIDE! Please override function
1818 * {@link core_renderer::render_url_select()} instead.
1819 *
4d10e579
PS
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
1825 */
7a3c215b 1826 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
4d10e579
PS
1827 $select = new url_select($urls, $selected, $nothing, $formid);
1828 return $this->render($select);
1829 }
1830
1831 /**
ab08be98 1832 * Internal implementation of url_select rendering
7a3c215b
SH
1833 *
1834 * @param url_select $select
4d10e579
PS
1835 * @return string HTML fragment
1836 */
1837 protected function render_url_select(url_select $select) {
c422efcf
PS
1838 global $CFG;
1839
4d10e579
PS
1840 $select = clone($select);
1841 if (empty($select->formid)) {
1842 $select->formid = html_writer::random_id('url_select_f');
1843 }
1844
1845 if (empty($select->attributes['id'])) {
1846 $select->attributes['id'] = html_writer::random_id('url_select');
1847 }
1848
1849 if ($select->disabled) {
1850 $select->attributes['disabled'] = 'disabled';
1851 }
1852
1853 if ($select->tooltip) {
1854 $select->attributes['title'] = $select->tooltip;
1855 }
1856
1857 $output = '';
1858
1859 if ($select->label) {
ecc5cc31 1860 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
4d10e579
PS
1861 }
1862
50d6ad84
ARN
1863 $classes = array();
1864 if (!$select->showbutton) {
1865 $classes[] = 'autosubmit';
1866 }
7266bd3e 1867 if ($select->class) {
50d6ad84
ARN
1868 $classes[] = $select->class;
1869 }
1870 if (count($classes)) {
1871 $select->attributes['class'] = implode(' ', $classes);
7266bd3e
ARN
1872 }
1873
4d10e579
PS
1874 if ($select->helpicon instanceof help_icon) {
1875 $output .= $this->render($select->helpicon);
1876 }
1877
d4dcfc6b
DM
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.
c422efcf
PS
1880 $urls = array();
1881 foreach ($select->urls as $k=>$v) {
d4dcfc6b
DM
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;
1896 }
1897 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1898 }
1899 }
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;
1909 }
1910 $urls[$k] = $v;
1911 }
1912 }
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!");
c422efcf 1919 }
c422efcf
PS
1920 }
1921
4d10e579 1922 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
d4dcfc6b 1923 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
4d10e579 1924
15e48a1a
SM
1925 if (!$select->showbutton) {
1926 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
ebc583e4 1927 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
15e48a1a 1928 $nothing = empty($select->nothing) ? false : key($select->nothing);
7266bd3e
ARN
1929 $this->page->requires->yui_module('moodle-core-formautosubmit',
1930 'M.core.init_formautosubmit',
1931 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1932 );
15e48a1a
SM
1933 } else {
1934 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1935 }
4d10e579
PS
1936
1937 // then div wrapper for xhtml strictness
26acc814 1938 $output = html_writer::tag('div', $output);
4d10e579
PS
1939
1940 // now the form itself around it
1941 $formattributes = array('method' => 'post',
1942 'action' => new moodle_url('/course/jumpto.php'),
1943 'id' => $select->formid);
26acc814 1944 $output = html_writer::tag('form', $output, $formattributes);
a9967cf5
PS
1945
1946 // and finally one more wrapper with class
26acc814 1947 return html_writer::tag('div', $output, array('class' => $select->class));
a9967cf5
PS
1948 }
1949
d9c8f425 1950 /**
1951 * Returns a string containing a link to the user documentation.
1952 * Also contains an icon by default. Shown to teachers and admin only.
7a3c215b 1953 *
d9c8f425 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
afe3566c 1956 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
996b1e0c 1957 * @return string
d9c8f425 1958 */
afe3566c 1959 public function doc_link($path, $text = '', $forcepopup = false) {
8ae8bf8a
PS
1960 global $CFG;
1961
ae4086bd 1962 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
8ae8bf8a 1963
000c278c 1964 $url = new moodle_url(get_docs_url($path));
8ae8bf8a 1965
c80877aa 1966 $attributes = array('href'=>$url);
afe3566c
ARN
1967 if (!empty($CFG->doctonewwindow) || $forcepopup) {
1968 $attributes['class'] = 'helplinkpopup';
d9c8f425 1969 }
1adaa404 1970
26acc814 1971 return html_writer::tag('a', $icon.$text, $attributes);
d9c8f425 1972 }
1973
000c278c 1974 /**
7a3c215b
SH
1975 * Return HTML for a pix_icon.
1976 *
2fada290
MG
1977 * Theme developers: DO NOT OVERRIDE! Please override function
1978 * {@link core_renderer::render_pix_icon()} instead.
1979 *
000c278c
PS
1980 * @param string $pix short pix name
1981 * @param string $alt mandatory alt attribute
eb557002 1982 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
000c278c
PS
1983 * @param array $attributes htm lattributes
1984 * @return string HTML fragment
1985 */
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);
1989 }
1990
1991 /**
7a3c215b
SH
1992 * Renders a pix_icon widget and returns the HTML to display it.
1993 *
000c278c
PS
1994 * @param pix_icon $icon
1995 * @return string HTML fragment
1996 */
ce0110bf 1997 protected function render_pix_icon(pix_icon $icon) {
000c278c
PS
1998 $attributes = $icon->attributes;
1999 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
c80877aa 2000 return html_writer::empty_tag('img', $attributes);
000c278c
PS
2001 }
2002
d63c5073 2003 /**
7a3c215b
SH
2004 * Return HTML to display an emoticon icon.
2005 *
d63c5073
DM
2006 * @param pix_emoticon $emoticon
2007 * @return string HTML fragment
2008 */
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);
2013 }
2014
a09aeee4 2015 /**
7a3c215b
SH
2016 * Produces the html that represents this rating in the UI
2017 *
2018 * @param rating $rating the page object on which this rating will appear
2019 * @return string
2020 */
a09aeee4 2021 function render_rating(rating $rating) {
7ac928a7 2022 global $CFG, $USER;
a09aeee4 2023
2b04c41c 2024 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
63e87951
AD
2025 return null;//ratings are turned off
2026 }
2027
2b04c41c
SH
2028 $ratingmanager = new rating_manager();
2029 // Initialise the JavaScript so ratings can be done by AJAX.
2030 $ratingmanager->initialise_rating_javascript($this->page);
a09aeee4 2031
63e87951
AD
2032 $strrate = get_string("rate", "rating");
2033 $ratinghtml = ''; //the string we'll return
2034
2b04c41c
SH
2035 // permissions check - can they view the aggregate?
2036 if ($rating->user_can_view_aggregate()) {
a09aeee4 2037
2b04c41c
SH
2038 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2039 $aggregatestr = $rating->get_aggregate_string();
a09aeee4 2040
6278ce45 2041 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2b04c41c 2042 if ($rating->count > 0) {
6278ce45 2043 $countstr = "({$rating->count})";
d251b259 2044 } else {
6278ce45 2045 $countstr = '-';
d251b259 2046 }
6278ce45 2047 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
63e87951 2048
c6de9cef 2049 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
d251b259 2050 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2b04c41c
SH
2051
2052 $nonpopuplink = $rating->get_view_ratings_url();
2053 $popuplink = $rating->get_view_ratings_url(true);
a09aeee4 2054
d251b259 2055 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
c6de9cef 2056 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
d251b259 2057 } else {
c6de9cef 2058 $ratinghtml .= $aggregatehtml;
a09aeee4 2059 }
d251b259 2060 }
a09aeee4 2061
d251b259 2062 $formstart = null;
2b04c41c
SH
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()) {
771b3fbe 2066
2b04c41c
SH
2067 $rateurl = $rating->get_rate_url();
2068 $inputs = $rateurl->params();
771b3fbe 2069
2b04c41c
SH
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()
2076 );
2077 $formstart = html_writer::start_tag('form', $formattrs);
2078 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2079
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);
2084 }
3180bc2c 2085
d251b259
AD
2086 if (empty($ratinghtml)) {
2087 $ratinghtml .= $strrate.': ';
2088 }
d251b259 2089 $ratinghtml = $formstart.$ratinghtml;
63e87951 2090
2b04c41c
SH
2091 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2092 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
ecc5cc31 2093 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2b04c41c 2094 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
a09aeee4 2095
d251b259 2096 //output submit button
771b3fbe
AD
2097 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2098
2b04c41c 2099 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
771b3fbe 2100 $ratinghtml .= html_writer::empty_tag('input', $attributes);
a09aeee4 2101
2b04c41c 2102 if (!$rating->settings->scale->isnumeric) {
eaf52ff0
MN
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;
2108 }
2109 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
a09aeee4 2110 }
771b3fbe
AD
2111 $ratinghtml .= html_writer::end_tag('span');
2112 $ratinghtml .= html_writer::end_tag('div');
2113 $ratinghtml .= html_writer::end_tag('form');
a09aeee4
AD
2114 }
2115
63e87951 2116 return $ratinghtml;
a09aeee4
AD
2117 }
2118
7a3c215b 2119 /**
d9c8f425 2120 * Centered heading with attached help button (same title text)
7a3c215b
SH
2121 * and optional icon attached.
2122 *
4bcc5118 2123 * @param string $text A heading text
53a78cef 2124 * @param string $helpidentifier The keyword that defines a help page
4bcc5118
PS
2125 * @param string $component component name
2126 * @param string|moodle_url $icon
2127 * @param string $iconalt icon alt text
699e2fd0
RW
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
d9c8f425 2130 * @return string HTML fragment
2131 */
699e2fd0 2132 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
4bcc5118
PS
2133 $image = '';
2134 if ($icon) {
8ef1aa40 2135 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
d9c8f425 2136 }
4bcc5118 2137
259c165d
PS
2138 $help = '';
2139 if ($helpidentifier) {
2140 $help = $this->help_icon($helpidentifier, $component);
2141 }
4bcc5118 2142
699e2fd0 2143 return $this->heading($image.$text.$help, $level, $classnames);
d9c8f425 2144 }
2145
2146 /**
7a3c215b 2147 * Returns HTML to display a help icon.
d9c8f425 2148 *
cb616be8 2149 * @deprecated since Moodle 2.0
bf11293a 2150 */
596509e4 2151 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
a6d81a73 2152 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
d9c8f425 2153 }
2154
259c165d 2155 /**
7a3c215b 2156 * Returns HTML to display a help icon.
259c165d 2157 *
2fada290
MG
2158 * Theme developers: DO NOT OVERRIDE! Please override function
2159 * {@link core_renderer::render_help_icon()} instead.
2160 *
259c165d
PS
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
2165 */
2166 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2cf81209 2167 $icon = new help_icon($identifier, $component);
259c165d
PS
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;
2173 }
2174 return $this->render($icon);
2175 }
2176
2177 /**
2178 * Implementation of user image rendering.
7a3c215b 2179 *
3d3fae72 2180 * @param help_icon $helpicon A help icon instance
259c165d
PS
2181 * @return string HTML fragment
2182 */
2183 protected function render_help_icon(help_icon $helpicon) {
2184 global $CFG;
2185
2186 // first get the help image icon
2187 $src = $this->pix_url('help');
2188
2189 $title = get_string($helpicon->identifier, $helpicon->component);
2190
2191 if (empty($helpicon->linktext)) {
cab2c7ea 2192 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
259c165d
PS
2193 } else {
2194 $alt = get_string('helpwiththis');
2195 }
2196
2197 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
2198 $output = html_writer::empty_tag('img', $attributes);
2199
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;
2204 }
2205
69542fb3
PS
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()));
259c165d
PS
2208
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"));
2211
e88419a2 2212 $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true', 'target'=>'_blank');
259c165d
PS
2213 $output = html_writer::tag('a', $output, $attributes);
2214
2215 // and finally span
238b8bc9 2216 return html_writer::tag('span', $output, array('class' => 'helptooltip'));
259c165d
PS
2217 }
2218
d9c8f425 2219 /**
7a3c215b 2220 * Returns HTML to display a scale help icon.
d9c8f425 2221 *
4bcc5118 2222 * @param int $courseid
7a3c215b
SH
2223 * @param stdClass $scale instance
2224 * @return string HTML fragment
d9c8f425 2225 */
4bcc5118
PS
2226 public function help_icon_scale($courseid, stdClass $scale) {
2227 global $CFG;
02f64f97 2228
4bcc5118 2229 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
02f64f97 2230
0029a917 2231 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
02f64f97 2232
68bf577b
AD
2233 $scaleid = abs($scale->id);
2234
2235 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
230ec401 2236 $action = new popup_action('click', $link, 'ratingscale');
02f64f97 2237
26acc814 2238 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
d9c8f425 2239 }
2240
2241 /**
2242 * Creates and returns a spacer image with optional line break.
2243 *
3d3fae72
SH
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.
d9c8f425 2247 * @return string HTML fragment
2248 */
0029a917
PS
2249 public function spacer(array $attributes = null, $br = false) {
2250 $attributes = (array)$attributes;
2251 if (empty($attributes['width'])) {
2252 $attributes['width'] = 1;
1ba862ec 2253 }
e1a5a9cc 2254 if (empty($attributes['height'])) {
0029a917 2255 $attributes['height'] = 1;
d9c8f425 2256 }
0029a917 2257 $attributes['class'] = 'spacer';
d9c8f425 2258
0029a917 2259 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
b65bfc3e 2260
0029a917 2261 if (!empty($br)) {
1ba862ec
PS
2262 $output .= '<br />';
2263 }
d9c8f425 2264
2265 return $output;
2266 }
2267
d9c8f425 2268 /**
7a3c215b 2269 * Returns HTML to display the specified user's avatar.
d9c8f425 2270 *
5d0c95a5 2271 * User avatar may be obtained in two ways:
d9c8f425 2272 * <pre>
812dbaf7
PS
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));
2276 *
5d0c95a5
PS
2277 * // Option 2:
2278 * $userpic = new user_picture($user);
d9c8f425 2279 * // Set properties of $userpic
812dbaf7 2280 * $userpic->popup = true;
5d0c95a5 2281 * $OUTPUT->render($userpic);
d9c8f425 2282 * </pre>
2283 *
2fada290
MG
2284 * Theme developers: DO NOT OVERRIDE! Please override function
2285 * {@link core_renderer::render_user_picture()} instead.
2286 *
7a3c215b 2287 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
812dbaf7 2288 * If any of these are missing, the database is queried. Avoid this
d9c8f425 2289 * if at all possible, particularly for reports. It is very bad for performance.
812dbaf7
PS
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)
5d0c95a5 2297 * - class = image class attribute (default 'userpicture')
e4a1efcb 2298 * - visibletoscreenreaders=true (whether to be visible to screen readers)
d9c8f425 2299 * @return string HTML fragment
2300 */
5d0c95a5
PS
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;
2306 }
2307 }
2308 return $this->render($userpicture);
2309 }
2310
2311 /**
2312 * Internal implementation of user image rendering.
7a3c215b 2313 *
5d0c95a5
PS
2314 * @param user_picture $userpicture
2315 * @return string
2316 */
2317 protected function render_user_picture(user_picture $userpicture) {
2318 global $CFG, $DB;
812dbaf7 2319
5d0c95a5
PS
2320 $user = $userpicture->user;
2321
2322 if ($userpicture->alttext) {
2323 if (!empty($user->imagealt)) {
2324 $alt = $user->imagealt;
2325 } else {
2326 $alt = get_string('pictureof', '', fullname($user));
2327 }
d9c8f425 2328 } else {
97c10099 2329 $alt = '';
5d0c95a5
PS
2330 }
2331
2332 if (empty($userpicture->size)) {
5d0c95a5
PS
2333 $size = 35;
2334 } else if ($userpicture->size === true or $userpicture->size == 1) {
5d0c95a5 2335 $size = 100;
5d0c95a5 2336 } else {
5d0c95a5 2337 $size = $userpicture->size;
d9c8f425 2338 }
2339
5d0c95a5 2340 $class = $userpicture->class;
d9c8f425 2341
4d254790 2342 if ($user->picture == 0) {
5d0c95a5 2343 $class .= ' defaultuserpic';
5d0c95a5 2344 }
d9c8f425 2345
871a3ec5
SH
2346 $src = $userpicture->get_url($this->page, $this);
2347
29cf6631 2348 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
e4a1efcb
JC
2349 if (!$userpicture->visibletoscreenreaders) {
2350 $attributes['role'] = 'presentation';
2351 }
2352
5d0c95a5 2353 // get the image html output fisrt
0e35ba6f 2354 $output = html_writer::empty_tag('img', $attributes);
5d0c95a5
PS
2355
2356 // then wrap it in link if needed
2357 if (!$userpicture->link) {
2358 return $output;
d9c8f425 2359 }
2360
5d0c95a5
PS
2361 if (empty($userpicture->courseid)) {
2362 $courseid = $this->page->course->id;
2363 } else {
2364 $courseid = $userpicture->courseid;
2365 }
2366
03d9401e
MD
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));
2371 }
5d0c95a5
PS
2372
2373 $attributes = array('href'=>$url);
e4a1efcb
JC
2374 if (!$userpicture->visibletoscreenreaders) {
2375 $attributes['role'] = 'presentation';
2376 $attributes['tabindex'] = '-1';
2377 $attributes['aria-hidden'] = 'true';
2378 }
5d0c95a5
PS
2379
2380 if ($userpicture->popup) {
2381 $id = html_writer::random_id('userpicture');
2382 $attributes['id'] = $id;
c80877aa 2383 $this->add_action_handler(new popup_action('click', $url), $id);
5d0c95a5
PS
2384 }
2385
26acc814 2386 return html_writer::tag('a', $output, $attributes);
d9c8f425 2387 }
b80ef420 2388
b80ef420
DC
2389 /**
2390 * Internal implementation of file tree viewer items rendering.
7a3c215b 2391 *
b80ef420
DC
2392 * @param array $dir
2393 * @return string
2394 */
2395 public function htmllize_file_tree($dir) {
2396 if (empty($dir['subdirs']) and empty($dir['files'])) {
2397 return '';
2398 }
2399 $result = '<ul>';
2400 foreach ($dir['subdirs'] as $subdir) {
2401 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2402 }
2403 foreach ($dir['files'] as $file) {
2404 $filename = $file->get_filename();
2405 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2406 }
2407 $result .= '</ul>';
2408
2409 return $result;
2410 }
7a3c215b 2411
bb496de7 2412 /**
7a3c215b 2413 * Returns HTML to display the file picker
bb496de7
DC
2414 *
2415 * <pre>
2416 * $OUTPUT->file_picker($options);
2417 * </pre>
2418 *
2fada290
MG
2419 * Theme developers: DO NOT OVERRIDE! Please override function
2420 * {@link core_renderer::render_file_picker()} instead.
2421 *
bb496de7
DC
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
2431 */
2432 public function file_picker($options) {
2433 $fp = new file_picker($options);
2434 return $this->render($fp);
2435 }
7a3c215b 2436
b80ef420
DC
2437 /**
2438 * Internal implementation of file picker rendering.
7a3c215b 2439 *
b80ef420
DC
2440 * @param file_picker $fp
2441 * @return string
2442 */
bb496de7
DC
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');
adce0230 2450 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
906e7d89 2451 $strdroptoupload = get_string('droptoupload', 'moodle');
bb496de7
DC
2452 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2453
2454 $currentfile = $options->currentfile;
2455 if (empty($currentfile)) {
322945e9
FM
2456 $currentfile = '';
2457 } else {
2458 $currentfile .= ' - ';
bb496de7 2459 }
b817205b
DC
2460 if ($options->maxbytes) {
2461 $size = $options->maxbytes;
2462 } else {
2463 $size = get_max_upload_file_size();
2464 }
513aed3c 2465 if ($size == -1) {
831399c4 2466 $maxsize = '';
513aed3c
DC
2467 } else {
2468 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2469 }
f50a61fb 2470 if ($options->buttonname) {
4b72f9eb
AW
2471 $buttonname = ' name="' . $options->buttonname . '"';
2472 } else {
2473 $buttonname = '';
2474 }
bb496de7
DC
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>
c81f3328 2481 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
fa7f2a45 2482 <span> $maxsize </span>
bb496de7
DC
2483 </div>
2484EOD;
2485 if ($options->env != 'url') {
2486 $html .= <<<EOD
50597880 2487 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
a9352f1f 2488 <div class="filepicker-filename">
08a6a19d 2489 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
0f94289c 2490 <div class="dndupload-progressbars"></div>
a9352f1f 2491 </div>
08a6a19d 2492 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
f08fac7c 2493 </div>
bb496de7
DC
2494EOD;
2495 }
2496 $html .= '</div>';
2497 return $html;
2498 }
d9c8f425 2499
2500 /**
7a3c215b 2501 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
d9c8f425 2502 *
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.
2506 */
2507 public function update_module_button($cmid, $modulename) {
2508 global $CFG;
b0c6dc1c 2509 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
d9c8f425 2510 $modulename = get_string('modulename', $modulename);
2511 $string = get_string('updatethis', '', $modulename);
3ba60ee1
PS
2512 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2513 return $this->single_button($url, $string);
d9c8f425 2514 } else {
2515 return '';
2516 }
2517 }
2518
2519 /**
7a3c215b
SH
2520 * Returns HTML to display a "Turn editing on/off" button in a form.
2521 *
d9c8f425 2522 * @param moodle_url $url The URL + params to send through when clicking the button
2523 * @return string HTML the button
2524 */
2525 public function edit_button(moodle_url $url) {
3362dfdc
EL
2526
2527 $url->param('sesskey', sesskey());
2528 if ($this->page->user_is_editing()) {
2529 $url->param('edit', 'off');
2530 $editstring = get_string('turneditingoff');
d9c8f425 2531 } else {
3362dfdc
EL
2532 $url->param('edit', 'on');
2533 $editstring = get_string('turneditingon');
d9c8f425 2534 }
2535
3362dfdc 2536 return $this->single_button($url, $editstring);
d9c8f425 2537 }
2538
d9c8f425 2539 /**
7a3c215b 2540 * Returns HTML to display a simple button to close a window
d9c8f425 2541 *
d9c8f425 2542 * @param string $text The lang string for the button's label (already output from get_string())
3ba60ee1 2543 * @return string html fragment
d9c8f425 2544 */
7a5c78e0 2545 public function close_window_button($text='') {
d9c8f425 2546 if (empty($text)) {
2547 $text = get_string('closewindow');
2548 }
a6855934
PS
2549 $button = new single_button(new moodle_url('#'), $text, 'get');
2550 $button->add_action(new component_action('click', 'close_window'));
3ba60ee1
PS
2551
2552 return $this->container($this->render($button), 'closewindow');
d9c8f425 2553 }
2554
d9c8f425 2555 /**
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.
7a3c215b 2558 *
d9c8f425 2559 * @param string $message the error message.
2560 * @return string the HTML to output.
2561 */
2562 public function error_text($message) {
2563 if (empty($message)) {
2564 return '';
2565 }
3246648b 2566 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
26acc814 2567 return html_writer::tag('span', $message, array('class' => 'error'));
d9c8f425 2568 }
2569
2570 /**
2571 * Do not call this function directly.
2572 *
f8129210 2573 * To terminate the current script with a fatal error, call the {@link print_error}
d9c8f425 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.
2576 *
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
d9c8f425 2582 * @return string the HTML to output.
2583 */
83267ec0 2584 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
6bd8d7e7 2585 global $CFG;
d9c8f425 2586
2587 $output = '';
6f8f4d83 2588 $obbuffer = '';
e57c283d 2589
d9c8f425 2590 if ($this->has_started()) {
50764d37
PS
2591 // we can not always recover properly here, we have problems with output buffering,
2592 // html tables, etc.
d9c8f425 2593 $output .= $this->opencontainers->pop_all_but_last();
50764d37 2594
d9c8f425 2595 } else {
50764d37
PS
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
6bd8d7e7 2599 error_reporting(0); // disable notices from gzip compression, etc.
50764d37 2600 while (ob_get_level() > 0) {
2cadd443
PS
2601 $buff = ob_get_clean();
2602 if ($buff === false) {
2603 break;
2604 }
2605 $obbuffer .= $buff;
50764d37 2606 }
6bd8d7e7 2607 error_reporting($CFG->debug);
6f8f4d83 2608
f22f1caf
PS
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');
85309744 2617 }
f22f1caf 2618
eb5bdb35 2619 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
7fde1e4b 2620 $this->page->set_url('/'); // no url
191b267b 2621 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
dcfb9b78 2622 $this->page->set_title(get_string('error'));
8093188f 2623 $this->page->set_heading($this->page->course->fullname);
d9c8f425 2624 $output .= $this->header();
2625 }
2626
2627 $message = '<p class="errormessage">' . $message . '</p>'.
2628 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2629 get_string('moreinformation') . '</a></p>';
1ad8143a
PS
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.
2633 }
4c2892c6 2634 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
d9c8f425 2635
96f81ea3 2636 if ($CFG->debugdeveloper) {
6f8f4d83 2637 if (!empty($debuginfo)) {
c5d18164
PS
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');
6f8f4d83
PS
2641 }
2642 if (!empty($backtrace)) {
2643 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2644 }
2645 if ($obbuffer !== '' ) {
2646 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2647 }
d9c8f425 2648 }
2649
3efe6bbb
PS
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)) {
d9c8f425 2653 $output .= $this->continue_button($link);
2654 }
2655
2656 $output .= $this->footer();
2657
2658 // Padding to encourage IE to display our error page, rather than its own.
2659 $output .= str_repeat(' ', 512);
2660
2661 return $output;
2662 }
2663
2664 /**
2665 * Output a notification (that is, a status message about something that has
2666 * just happened).
2667 *
2668 * @param string $message the message to print out
2669 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2670 * @return string the HTML to output.
2671 */
2672 public function notification($message, $classes = 'notifyproblem') {
26acc814 2673 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
d9c8f425 2674 }
2675
2676 /**
7a3c215b 2677 * Returns HTML to display a continue button that goes to a particular URL.
d9c8f425 2678 *
3ba60ee1 2679 * @param string|moodle_url $url The url the button goes to.
d9c8f425 2680 * @return string the HTML to output.
2681 */
3ba60ee1
PS
2682 public function continue_button($url) {
2683 if (!($url instanceof moodle_url)) {
2684 $url = new moodle_url($url);
d9c8f425 2685 }
3ba60ee1
PS
2686 $button = new single_button($url, get_string('continue'), 'get');
2687 $button->class = 'continuebutton';
d9c8f425 2688
3ba60ee1 2689 return $this->render($button);
d9c8f425 2690 }
2691
2692 /**
7a3c215b 2693 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
d9c8f425 2694 *
2fada290
MG
2695 * Theme developers: DO NOT OVERRIDE! Please override function
2696 * {@link core_renderer::render_paging_bar()} instead.
2697 *
71c03ac1 2698 * @param int $totalcount The total number of entries available to be paged through
929d7a83
PS
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
d9c8f425 2703 * @return string the HTML to output.
2704 */
929d7a83
PS
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);
2708 }
2709
2710 /**
2711 * Internal implementation of paging bar rendering.
7a3c215b 2712 *
929d7a83
PS
2713 * @param paging_bar $pagingbar
2714 * @return string
2715 */
2716 protected function render_paging_bar(paging_bar $pagingbar) {
d9c8f425 2717 $output = '';
2718 $pagingbar = clone($pagingbar);
34059565 2719 $pagingbar->prepare($this, $this->page, $this->target);
d9c8f425 2720
2721 if ($pagingbar->totalcount > $pagingbar->perpage) {
2722 $output .= get_string('page') . ':';
2723
2724 if (!empty($pagingbar->previouslink)) {
56ddb719 2725 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
d9c8f425 2726 }
2727
2728 if (!empty($pagingbar->firstlink)) {
56ddb719 2729 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
d9c8f425 2730 }
2731
2732 foreach ($pagingbar->pagelinks as $link) {
56ddb719 2733 $output .= "&#160;&#160;$link";
d9c8f425 2734 }
2735
2736 if (!empty($pagingbar->lastlink)) {
56ddb719 2737 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
d9c8f425 2738 }
2739
2740 if (!empty($pagingbar->nextlink)) {
56ddb719 2741 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
d9c8f425 2742 }
2743 }
2744
26acc814 2745 return html_writer::tag('div', $output, array('class' => 'paging'));
d9c8f425 2746 }
2747
d9c8f425 2748 /**
2749 * Output the place a skip link goes to.
7a3c215b 2750 *
d9c8f425 2751 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2752 * @return string the HTML to output.
2753 */
fe213365 2754 public function skip_link_target($id = null) {
26acc814 2755 return html_writer::tag('span', '', array('id' => $id));
d9c8f425 2756 }
2757
2758 /**
2759 * Outputs a heading
7a3c215b 2760 *
d9c8f425 2761 * @param string $text The text of the heading
2762 * @param int $level The level of importance of the heading. Defaulting to 2
699e2fd0 2763 * @param string $classes A space-separated list of CSS classes. Defaulting to null
d9c8f425 2764 * @param string $id An optional ID
2765 * @return string the HTML to output.
2766 */
699e2fd0 2767 public function heading($text, $level = 2, $classes = null, $id = null) {
d9c8f425 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.');
2771 }
26acc814 2772 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
d9c8f425 2773 }
2774
2775 /**
2776 * Outputs a box.
7a3c215b 2777 *
d9c8f425 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
3e76c7fa 2781 * @param array $attributes An array of other attributes to give the box.
d9c8f425 2782 * @return string the HTML to output.
2783 */
3e76c7fa
SH
2784 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
2785 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
d9c8f425 2786 }
2787
2788 /**
3d3fae72 2789 * Outputs the opening section of a box.
7a3c215b 2790 *
d9c8f425 2791 * @param string $classes A space-separated list of CSS classes
2792 * @param string $id An optional ID
3e76c7fa 2793 * @param array $attributes An array of other attributes to give the box.
d9c8f425 2794 * @return string the HTML to output.
2795 */
3e76c7fa 2796 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
5d0c95a5 2797 $this->opencontainers->push('box', html_writer::end_tag('div'));
3e76c7fa
SH
2798 $attributes['id'] = $id;
2799 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
2800 return html_writer::start_tag('div', $attributes);
d9c8f425 2801 }
2802
2803 /**
2804 * Outputs the closing section of a box.
7a3c215b 2805 *
d9c8f425 2806 * @return string the HTML to output.
2807 */
2808 public function box_end() {
2809 return $this->opencontainers->pop('box');
2810 }
2811
2812 /**
2813 * Outputs a container.
7a3c215b 2814 *
d9c8f425 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.
2819 */
fe213365 2820 public function container($contents, $classes = null, $id = null) {
d9c8f425 2821 return $this->container_start($classes, $id) . $contents . $this->container_end();
2822 }
2823
2824 /**
2825 * Outputs the opening section of a container.
7a3c215b 2826 *
d9c8f425 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.
2830 */
fe213365 2831 public function container_start($classes = null, $id = null) {
5d0c95a5
PS
2832 $this->opencontainers->push('container', html_writer::end_tag('div'));
2833 return html_writer::start_tag('div', array('id' => $id,
78946b9b 2834 'class' => renderer_base::prepare_classes($classes)));
d9c8f425 2835 }
2836
2837 /**
2838 * Outputs the closing section of a container.
7a3c215b 2839 *
d9c8f425 2840 * @return string the HTML to output.
2841 */
2842 public function container_end() {
2843 return $this->opencontainers->pop('container');
2844 }
7d2a0492 2845
3406acde 2846 /**
7d2a0492 2847 * Make nested HTML lists out of the items
2848 *
2849 * The resulting list will look something like this:
2850 *
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>
2860 *
7a3c215b
SH
2861 * @param array $items
2862 * @param array $attrs html attributes passed to the top ofs the list
7d2a0492 2863 * @return string HTML
2864 */
7a3c215b 2865 public function tree_block_contents($items, $attrs = array()) {
7d2a0492 2866 // exit if empty, we don't want an empty ul element
2867 if (empty($items)) {
2868 return '';
2869 }
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());
3406acde 2876 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
7d2a0492 2877 $liclasses[] = 'collapsed';
2878 }
2879 if ($item->isactive === true) {
2880 $liclasses[] = 'current_branch';
2881 }
2882 $liattr = array('class'=>join(' ',$liclasses));
2883 // class attribute on the div item which only contains the item content
2884 $divclasses = array('tree_item');
3406acde 2885 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
7d2a0492 2886 $divclasses[] = 'branch';
2887 } else {
2888 $divclasses[] = 'leaf';
2889 }
2890 if (!empty($item->classes) && count($item->classes)>0) {
2891 $divclasses[] = join(' ', $item->classes);
2892 }
2893 $divattr = array('class'=>join(' ', $divclasses));
2894 if (!empty($item->id)) {
2895 $divattr['id'] = $item->id;
2896 }
26acc814 2897 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
7d2a0492 2898 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
26acc814 2899 $content = html_writer::empty_tag('hr') . $content;
7d2a0492 2900 }
26acc814 2901 $content = html_writer::tag('li', $content, $liattr);
7d2a0492 2902 $lis[] = $content;
2903 }
26acc814 2904 return html_writer::tag('ul', implode("\n", $lis), $attrs);
7d2a0492 2905 }
2906
6da0e4cf
JC
2907 /**
2908 * Construct a user menu, returning HTML that can be echoed out by a
2909 * layout file.
2910 *
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.
2914 */
854a647e 2915 public function user_menu($user = null, $withlinks = null) {
6da0e4cf 2916 global $USER, $CFG;
854a647e 2917 require_once($CFG->dirroot . '/user/lib.php');
6da0e4cf
JC
2918
2919 if (is_null($user)) {
2920 $user = $USER;
2921 }
2922
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']);
2928 }
2929
854a647e
JC
2930 // Add a class for when $withlinks is false.
2931 $usermenuclasses = 'usermenu';
2932 if (!$withlinks) {
2933 $usermenuclasses .= ' withoutlinks';
2934 }
2935
6da0e4cf
JC
2936 $returnstr = "";
2937
2938 // If during initial install, return the empty return string.
2939 if (during_initial_install()) {
2940 return $returnstr;
2941 }
2942
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>)';
2950 }
854a647e
JC
2951 return html_writer::div(
2952 html_writer::span(
2953 $returnstr,
2954 'login'
2955 ),
2956 $usermenuclasses
6da0e4cf 2957 );
854a647e 2958
6da0e4cf
JC
2959 }
2960
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>)';
2966 }
854a647e
JC
2967
2968 return html_writer::div(
2969 html_writer::span(
2970 $returnstr,
2971 'login'
2972 ),
2973 $usermenuclasses
6da0e4cf
JC
2974 );
2975 }
2976
2977 // Get some navigation opts.
6da0e4cf
JC
2978 $opts = user_get_user_navigation_info($user, $this->page, $this->page->course);
2979
2980 $avatarclasses = "avatars";
2981 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
2982 $usertextcontents = $opts->metadata['userfullname'];
2983
2984 // Other user.
2985 if (!empty($opts->metadata['asotheruser'])) {
2986 $avatarcontents .= html_writer::span(
2987 $opts->metadata['realuseravatar'],
2988 'avatar realuser'
2989 );
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'
2999 )
3000 ),
3001 array('class' => 'meta viewingas')
3002 );
3003 }
3004
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
3011 );
3012 }
3013
3014 // User login failures.
3015 if (!empty($opts->metadata['userloginfail'])) {
3016 $usertextcontents .= html_writer::span(
3017 $opts->metadata['userloginfail'],
3018 'meta loginfailures'
3019 );
3020 }
3021
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
3028 );
3029 }
3030
3031 $returnstr .= html_writer::span(
854a647e
JC
3032 html_writer::span($usertextcontents, 'usertext') .
3033 html_writer::span($avatarcontents, $avatarclasses),
6da0e4cf
JC
3034 'userbutton'
3035 );
3036
6da0e4cf
JC
3037 // Create a divider (well, a filler).
3038 $divider = new action_menu_filler();
3039 $divider->primary = false;
3040
3041 $am = new action_menu();
3042 $am->initialise_js($this->page);
f89a85f8
JC
3043 $am->set_menu_trigger(
3044 $returnstr
3045 );
6da0e4cf
JC
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;
b865a3e2 3052 if (isset($value->pix) && !empty($value->pix)) {
854a647e 3053 $pix = new pix_icon($value->pix, $value->title, null, array('class' => 'iconsmall'));
b865a3e2
JC
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;
6da0e4cf
JC
3060 }
3061 $al = new action_menu_link_secondary(
3062 $value->url,
3063 $pix,
3064 $value->title,
3065 array('class' => 'icon')
3066 );
3067 $am->add($al);
3068
3069 // Add dividers after the first item and before the
3070 // last item.
3071 if ($idx == 0 || $idx == $navitemcount - 2) {
3072 $am->add($divider);
3073 }
3074
3075 $idx++;
3076 }
3077</