MDL-49163 Webservices, AJAX: Add support for a new ajax webservice handler.
[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
244a32c6 627 $course = $this->page->course;
d79d5ac2
PS
628 if (\core\session\manager::is_loggedinas()) {
629 $realuser = \core\session\manager::get_realuser();
244a32c6 630 $fullname = fullname($realuser, true);
2d0e682d 631 if ($withlinks) {
fa84b901
RT
632 $loginastitle = get_string('loginas');
633 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
634 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
2d0e682d
MV
635 } else {
636 $realuserinfo = " [$fullname] ";
637 }
244a32c6
PS
638 } else {
639 $realuserinfo = '';
640 }
4bcc5118 641
0e61dba3 642 $loginpage = $this->is_login_page();
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
0e61dba3
AN
720 /**
721 * Check whether the current page is a login page.
722 *
723 * @since Moodle 2.9
724 * @return bool
725 */
726 protected function is_login_page() {
727 // This is a real bit of a hack, but its a rarety that we need to do something like this.
728 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
729 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
730 return in_array(
731 $this->page->url->out_as_local_url(false, array()),
732 array(
733 '/login/index.php',
734 '/login/forgot_password.php',
735 )
736 );
737 }
738
d9c8f425 739 /**
740 * Return the 'back' link that normally appears in the footer.
7a3c215b 741 *
d9c8f425 742 * @return string HTML fragment.
743 */
744 public function home_link() {
745 global $CFG, $SITE;
746
747 if ($this->page->pagetype == 'site-index') {
748 // Special case for site home page - please do not remove
749 return '<div class="sitelink">' .
34dff6aa 750 '<a title="Moodle" href="http://moodle.org/">' .
970c4419 751 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
d9c8f425 752
753 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
754 // Special case for during install/upgrade.
755 return '<div class="sitelink">'.
34dff6aa 756 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
970c4419 757 '<img src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
d9c8f425 758
759 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
760 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
761 get_string('home') . '</a></div>';
762
763 } else {
764 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
8ebbb06a 765 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
d9c8f425 766 }
767 }
768
769 /**
770 * Redirects the user by any means possible given the current state
771 *
772 * This function should not be called directly, it should always be called using
773 * the redirect function in lib/weblib.php
774 *
775 * The redirect function should really only be called before page output has started
776 * however it will allow itself to be called during the state STATE_IN_BODY
777 *
778 * @param string $encodedurl The URL to send to encoded if required
779 * @param string $message The message to display to the user if any
780 * @param int $delay The delay before redirecting a user, if $message has been
781 * set this is a requirement and defaults to 3, set to 0 no delay
782 * @param boolean $debugdisableredirect this redirect has been disabled for
783 * debugging purposes. Display a message that explains, and don't
784 * trigger the redirect.
785 * @return string The HTML to display to the user before dying, may contain
786 * meta refresh, javascript refresh, and may have set header redirects
787 */
788 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
789 global $CFG;
790 $url = str_replace('&amp;', '&', $encodedurl);
791
792 switch ($this->page->state) {
793 case moodle_page::STATE_BEFORE_HEADER :
794 // No output yet it is safe to delivery the full arsenal of redirect methods
795 if (!$debugdisableredirect) {
796 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
797 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
593f9b87 798 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
d9c8f425 799 }
800 $output = $this->header();
801 break;
802 case moodle_page::STATE_PRINTING_HEADER :
803 // We should hopefully never get here
804 throw new coding_exception('You cannot redirect while printing the page header');
805 break;
806 case moodle_page::STATE_IN_BODY :
807 // We really shouldn't be here but we can deal with this
808 debugging("You should really redirect before you start page output");
809 if (!$debugdisableredirect) {
593f9b87 810 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
d9c8f425 811 }
812 $output = $this->opencontainers->pop_all_but_last();
813 break;
814 case moodle_page::STATE_DONE :
815 // Too late to be calling redirect now
816 throw new coding_exception('You cannot redirect after the entire page has been generated');
817 break;
818 }
819 $output .= $this->notification($message, 'redirectmessage');
3ab2e357 820 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
d9c8f425 821 if ($debugdisableredirect) {
05da2850 822 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
d9c8f425 823 }
824 $output .= $this->footer();
825 return $output;
826 }
827
828 /**
829 * Start output by sending the HTTP headers, and printing the HTML <head>
830 * and the start of the <body>.
831 *
832 * To control what is printed, you should set properties on $PAGE. If you
f8129210 833 * are familiar with the old {@link print_header()} function from Moodle 1.9
d9c8f425 834 * you will find that there are properties on $PAGE that correspond to most
835 * of the old parameters to could be passed to print_header.
836 *
837 * Not that, in due course, the remaining $navigation, $menu parameters here
838 * will be replaced by more properties of $PAGE, but that is still to do.
839 *
d9c8f425 840 * @return string HTML that you must output this, preferably immediately.
841 */
e120c61d 842 public function header() {
d9c8f425 843 global $USER, $CFG;
844
d79d5ac2 845 if (\core\session\manager::is_loggedinas()) {
e884f63a
PS
846 $this->page->add_body_class('userloggedinas');
847 }
848
46629116
JC
849 // If the user is logged in, and we're not in initial install,
850 // check to see if the user is role-switched and add the appropriate
851 // CSS class to the body element.
852 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
853 $this->page->add_body_class('userswitchedrole');
854 }
855
63c88397
PS
856 // Give themes a chance to init/alter the page object.
857 $this->page->theme->init_page($this->page);
858
d9c8f425 859 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
860
78946b9b
PS
861 // Find the appropriate page layout file, based on $this->page->pagelayout.
862 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
863 // Render the layout using the layout file.
864 $rendered = $this->render_page_layout($layoutfile);
67e84a7f 865
78946b9b 866 // Slice the rendered output into header and footer.
72009b87
PS
867 $cutpos = strpos($rendered, $this->unique_main_content_token);
868 if ($cutpos === false) {
869 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
870 $token = self::MAIN_CONTENT_TOKEN;
871 } else {
872 $token = $this->unique_main_content_token;
873 }
874
d9c8f425 875 if ($cutpos === false) {
72009b87 876 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 877 }
78946b9b 878 $header = substr($rendered, 0, $cutpos);
72009b87 879 $footer = substr($rendered, $cutpos + strlen($token));
d9c8f425 880
881 if (empty($this->contenttype)) {
78946b9b 882 debugging('The page layout file did not call $OUTPUT->doctype()');
67e84a7f 883 $header = $this->doctype() . $header;
d9c8f425 884 }
885
fdd4b9a5
MG
886 // If this theme version is below 2.4 release and this is a course view page
887 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
888 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
889 // check if course content header/footer have not been output during render of theme layout
890 $coursecontentheader = $this->course_content_header(true);
891 $coursecontentfooter = $this->course_content_footer(true);
892 if (!empty($coursecontentheader)) {
893 // display debug message and add header and footer right above and below main content
894 // Please note that course header and footer (to be displayed above and below the whole page)
895 // are not displayed in this case at all.
896 // Besides the content header and footer are not displayed on any other course page
897 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);
898 $header .= $coursecontentheader;
899 $footer = $coursecontentfooter. $footer;
900 }
901 }
902
d9c8f425 903 send_headers($this->contenttype, $this->page->cacheable);
67e84a7f 904
d9c8f425 905 $this->opencontainers->push('header/footer', $footer);
906 $this->page->set_state(moodle_page::STATE_IN_BODY);
67e84a7f 907
29ba64e5 908 return $header . $this->skip_link_target('maincontent');
d9c8f425 909 }
910
911 /**
78946b9b 912 * Renders and outputs the page layout file.
7a3c215b
SH
913 *
914 * This is done by preparing the normal globals available to a script, and
915 * then including the layout file provided by the current theme for the
916 * requested layout.
917 *
78946b9b 918 * @param string $layoutfile The name of the layout file
d9c8f425 919 * @return string HTML code
920 */
78946b9b 921 protected function render_page_layout($layoutfile) {
92e01ab7 922 global $CFG, $SITE, $USER;
d9c8f425 923 // The next lines are a bit tricky. The point is, here we are in a method
924 // of a renderer class, and this object may, or may not, be the same as
78946b9b 925 // the global $OUTPUT object. When rendering the page layout file, we want to use
d9c8f425 926 // this object. However, people writing Moodle code expect the current
927 // renderer to be called $OUTPUT, not $this, so define a variable called
928 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
929 $OUTPUT = $this;
930 $PAGE = $this->page;
931 $COURSE = $this->page->course;
932
d9c8f425 933 ob_start();
78946b9b
PS
934 include($layoutfile);
935 $rendered = ob_get_contents();
d9c8f425 936 ob_end_clean();
78946b9b 937 return $rendered;
d9c8f425 938 }
939
940 /**
941 * Outputs the page's footer
7a3c215b 942 *
d9c8f425 943 * @return string HTML fragment
944 */
945 public function footer() {
d5a8d9aa 946 global $CFG, $DB;
0f0801f4 947
f6794ace 948 $output = $this->container_end_all(true);
4d2ee4c2 949
d9c8f425 950 $footer = $this->opencontainers->pop('header/footer');
951
d5a8d9aa 952 if (debugging() and $DB and $DB->is_transaction_started()) {
03221650 953 // TODO: MDL-20625 print warning - transaction will be rolled back
d5a8d9aa
PS
954 }
955
d9c8f425 956 // Provide some performance info if required
957 $performanceinfo = '';
958 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
959 $perf = get_performance_info();
d9c8f425 960 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
961 $performanceinfo = $perf['html'];
962 }
963 }
58a3a34e
DM
964
965 // We always want performance data when running a performance test, even if the user is redirected to another page.
966 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
967 $footer = $this->unique_performance_info_token . $footer;
968 }
72009b87 969 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
d9c8f425 970
72009b87 971 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
d9c8f425 972
973 $this->page->set_state(moodle_page::STATE_DONE);
d9c8f425 974
975 return $output . $footer;
976 }
977
f6794ace
PS
978 /**
979 * Close all but the last open container. This is useful in places like error
980 * handling, where you want to close all the open containers (apart from <body>)
981 * before outputting the error message.
7a3c215b 982 *
f6794ace
PS
983 * @param bool $shouldbenone assert that the stack should be empty now - causes a
984 * developer debug warning if it isn't.
985 * @return string the HTML required to close any open containers inside <body>.
986 */
987 public function container_end_all($shouldbenone = false) {
988 return $this->opencontainers->pop_all_but_last($shouldbenone);
989 }
990
fdd4b9a5
MG
991 /**
992 * Returns course-specific information to be output immediately above content on any course page
993 * (for the current course)
994 *
995 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
996 * @return string
997 */
998 public function course_content_header($onlyifnotcalledbefore = false) {
999 global $CFG;
1000 if ($this->page->course->id == SITEID) {
1001 // return immediately and do not include /course/lib.php if not necessary
1002 return '';
1003 }
1004 static $functioncalled = false;
1005 if ($functioncalled && $onlyifnotcalledbefore) {
1006 // we have already output the content header
1007 return '';
1008 }
1009 require_once($CFG->dirroot.'/course/lib.php');
1010 $functioncalled = true;
1011 $courseformat = course_get_format($this->page->course);
1012 if (($obj = $courseformat->course_content_header()) !== null) {
06a72e01 1013 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
fdd4b9a5
MG
1014 }
1015 return '';
1016 }
1017
1018 /**
1019 * Returns course-specific information to be output immediately below content on any course page
1020 * (for the current course)
1021 *
1022 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1023 * @return string
1024 */
1025 public function course_content_footer($onlyifnotcalledbefore = false) {
1026 global $CFG;
1027 if ($this->page->course->id == SITEID) {
1028 // return immediately and do not include /course/lib.php if not necessary
1029 return '';
1030 }
1031 static $functioncalled = false;
1032 if ($functioncalled && $onlyifnotcalledbefore) {
1033 // we have already output the content footer
1034 return '';
1035 }
1036 $functioncalled = true;
1037 require_once($CFG->dirroot.'/course/lib.php');
1038 $courseformat = course_get_format($this->page->course);
1039 if (($obj = $courseformat->course_content_footer()) !== null) {
06a72e01 1040 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
fdd4b9a5
MG
1041 }
1042 return '';
1043 }
1044
1045 /**
1046 * Returns course-specific information to be output on any course page in the header area
1047 * (for the current course)
1048 *
1049 * @return string
1050 */
1051 public function course_header() {
1052 global $CFG;
1053 if ($this->page->course->id == SITEID) {
1054 // return immediately and do not include /course/lib.php if not necessary
1055 return '';
1056 }
1057 require_once($CFG->dirroot.'/course/lib.php');
1058 $courseformat = course_get_format($this->page->course);
1059 if (($obj = $courseformat->course_header()) !== null) {
1060 return $courseformat->get_renderer($this->page)->render($obj);
1061 }
1062 return '';
1063 }
1064
1065 /**
1066 * Returns course-specific information to be output on any course page in the footer area
1067 * (for the current course)
1068 *
1069 * @return string
1070 */
1071 public function course_footer() {
1072 global $CFG;
1073 if ($this->page->course->id == SITEID) {
1074 // return immediately and do not include /course/lib.php if not necessary
1075 return '';
1076 }
1077 require_once($CFG->dirroot.'/course/lib.php');
1078 $courseformat = course_get_format($this->page->course);
1079 if (($obj = $courseformat->course_footer()) !== null) {
1080 return $courseformat->get_renderer($this->page)->render($obj);
1081 }
1082 return '';
1083 }
1084
244a32c6
PS
1085 /**
1086 * Returns lang menu or '', this method also checks forcing of languages in courses.
7a3c215b 1087 *
2fada290
MG
1088 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1089 *
7a3c215b 1090 * @return string The lang menu HTML or empty string
244a32c6
PS
1091 */
1092 public function lang_menu() {
1093 global $CFG;
1094
1095 if (empty($CFG->langmenu)) {
1096 return '';
1097 }
1098
1099 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1100 // do not show lang menu if language forced
1101 return '';
1102 }
1103
1104 $currlang = current_language();
1f96e907 1105 $langs = get_string_manager()->get_list_of_translations();
4bcc5118 1106
244a32c6
PS
1107 if (count($langs) < 2) {
1108 return '';
1109 }
1110
a9967cf5
PS
1111 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1112 $s->label = get_accesshide(get_string('language'));
1113 $s->class = 'langmenu';
1114 return $this->render($s);
244a32c6
PS
1115 }
1116
d9c8f425 1117 /**
1118 * Output the row of editing icons for a block, as defined by the controls array.
7a3c215b 1119 *
f8129210 1120 * @param array $controls an array like {@link block_contents::$controls}.
b59f2e3b 1121 * @param string $blockid The ID given to the block.
7a3c215b 1122 * @return string HTML fragment.
d9c8f425 1123 */
b59f2e3b 1124 public function block_controls($actions, $blockid = null) {
10fc1569 1125 global $CFG;
b59f2e3b
SH
1126 if (empty($actions)) {
1127 return '';
1128 }
cf69a00a 1129 $menu = new action_menu($actions);
b59f2e3b
SH
1130 if ($blockid !== null) {
1131 $menu->set_owner_selector('#'.$blockid);
1132 }
ae3fd8eb 1133 $menu->set_constraint('.block-region');
b59f2e3b 1134 $menu->attributes['class'] .= ' block-control-actions commands';
10fc1569
SH
1135 if (isset($CFG->blockeditingmenu) && !$CFG->blockeditingmenu) {
1136 $menu->do_not_enhance();
1137 }
b59f2e3b
SH
1138 return $this->render($menu);
1139 }
1140
1141 /**
1142 * Renders an action menu component.
1143 *
3665af78
SH
1144 * ARIA references:
1145 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1146 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1147 *
b59f2e3b
SH
1148 * @param action_menu $menu
1149 * @return string HTML
1150 */
1151 public function render_action_menu(action_menu $menu) {
1152 $menu->initialise_js($this->page);
1153
1154 $output = html_writer::start_tag('div', $menu->attributes);
3665af78 1155 $output .= html_writer::start_tag('ul', $menu->attributesprimary);
b59f2e3b
SH
1156 foreach ($menu->get_primary_actions($this) as $action) {
1157 if ($action instanceof renderable) {
3665af78 1158 $content = $this->render($action);
b59f2e3b 1159 } else {
3665af78 1160 $content = $action;
e282c679 1161 }
11dd4dad 1162 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
d9c8f425 1163 }
3665af78
SH
1164 $output .= html_writer::end_tag('ul');
1165 $output .= html_writer::start_tag('ul', $menu->attributessecondary);
b59f2e3b 1166 foreach ($menu->get_secondary_actions() as $action) {
3665af78
SH
1167 if ($action instanceof renderable) {
1168 $content = $this->render($action);
3665af78
SH
1169 } else {
1170 $content = $action;
3665af78 1171 }
11dd4dad 1172 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
b59f2e3b 1173 }
3665af78 1174 $output .= html_writer::end_tag('ul');
b59f2e3b 1175 $output .= html_writer::end_tag('div');
e282c679 1176 return $output;
d9c8f425 1177 }
1178
cf69a00a 1179 /**
3665af78 1180 * Renders an action_menu_link item.
cf69a00a 1181 *
3665af78 1182 * @param action_menu_link $action
cf69a00a
SH
1183 * @return string HTML fragment
1184 */
3665af78 1185 protected function render_action_menu_link(action_menu_link $action) {
d0647301
SH
1186 static $actioncount = 0;
1187 $actioncount++;
cf69a00a 1188
ea5a01fb 1189 $comparetoalt = '';
cf69a00a 1190 $text = '';
ea5a01fb 1191 if (!$action->icon || $action->primary === false) {
d0647301 1192 $text .= html_writer::start_tag('span', array('class'=>'menu-action-text', 'id' => 'actionmenuaction-'.$actioncount));
cf69a00a
SH
1193 if ($action->text instanceof renderable) {
1194 $text .= $this->render($action->text);
1195 } else {
1196 $text .= $action->text;
cfd1e08a 1197 $comparetoalt = (string)$action->text;
cf69a00a
SH
1198 }
1199 $text .= html_writer::end_tag('span');
1200 }
1201
ea5a01fb
SH
1202 $icon = '';
1203 if ($action->icon) {
1204 $icon = $action->icon;
f803ce26 1205 if ($action->primary || !$action->actionmenu->will_be_enhanced()) {
ea5a01fb
SH
1206 $action->attributes['title'] = $action->text;
1207 }
cfd1e08a
SH
1208 if (!$action->primary && $action->actionmenu->will_be_enhanced()) {
1209 if ((string)$icon->attributes['alt'] === $comparetoalt) {
d0647301 1210 $icon->attributes['alt'] = '';
cfd1e08a 1211 }
c7a2291f 1212 if (isset($icon->attributes['title']) && (string)$icon->attributes['title'] === $comparetoalt) {
cfd1e08a
SH
1213 unset($icon->attributes['title']);
1214 }
1215 }
ea5a01fb
SH
1216 $icon = $this->render($icon);
1217 }
1218
3665af78 1219 // A disabled link is rendered as formatted text.
cf69a00a 1220 if (!empty($action->attributes['disabled'])) {
3665af78 1221 // Do not use div here due to nesting restriction in xhtml strict.
ea5a01fb 1222 return html_writer::tag('span', $icon.$text, array('class'=>'currentlink', 'role' => 'menuitem'));
cf69a00a
SH
1223 }
1224
1225 $attributes = $action->attributes;
1226 unset($action->attributes['disabled']);
1227 $attributes['href'] = $action->url;
d0647301
SH
1228 if ($text !== '') {
1229 $attributes['aria-labelledby'] = 'actionmenuaction-'.$actioncount;
1230 }
cf69a00a 1231
ea5a01fb 1232 return html_writer::tag('a', $icon.$text, $attributes);
cf69a00a
SH
1233 }
1234
9ac099a1
AN
1235 /**
1236 * Renders a primary action_menu_filler item.
1237 *
1238 * @param action_menu_link_filler $action
1239 * @return string HTML fragment
1240 */
1241 protected function render_action_menu_filler(action_menu_filler $action) {
1242 return html_writer::span('&nbsp;', 'filler');
1243 }
1244
cf69a00a 1245 /**
3665af78 1246 * Renders a primary action_menu_link item.
cf69a00a 1247 *
3665af78 1248 * @param action_menu_link_primary $action
cf69a00a
SH
1249 * @return string HTML fragment
1250 */
3665af78
SH
1251 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1252 return $this->render_action_menu_link($action);
cf69a00a
SH
1253 }
1254
1255 /**
3665af78 1256 * Renders a secondary action_menu_link item.
cf69a00a 1257 *
3665af78 1258 * @param action_menu_link_secondary $action
cf69a00a
SH
1259 * @return string HTML fragment
1260 */
3665af78
SH
1261 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1262 return $this->render_action_menu_link($action);
cf69a00a
SH
1263 }
1264
d9c8f425 1265 /**
1266 * Prints a nice side block with an optional header.
1267 *
1268 * The content is described
f8129210 1269 * by a {@link core_renderer::block_contents} object.
d9c8f425 1270 *
cbb54cce
SH
1271 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1272 * <div class="header"></div>
1273 * <div class="content">
1274 * ...CONTENT...
1275 * <div class="footer">
1276 * </div>
1277 * </div>
1278 * <div class="annotation">
1279 * </div>
1280 * </div>
1281 *
d9c8f425 1282 * @param block_contents $bc HTML for the content
1283 * @param string $region the region the block is appearing in.
1284 * @return string the HTML to be output.
1285 */
7a3c215b 1286 public function block(block_contents $bc, $region) {
d9c8f425 1287 $bc = clone($bc); // Avoid messing up the object passed in.
dd72b308
PS
1288 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1289 $bc->collapsible = block_contents::NOT_HIDEABLE;
1290 }
84192d78
SH
1291 if (!empty($bc->blockinstanceid)) {
1292 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1293 }
91d941c3
SH
1294 $skiptitle = strip_tags($bc->title);
1295 if ($bc->blockinstanceid && !empty($skiptitle)) {
1296 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1297 } else if (!empty($bc->arialabel)) {
1298 $bc->attributes['aria-label'] = $bc->arialabel;
1299 }
84192d78
SH
1300 if ($bc->dockable) {
1301 $bc->attributes['data-dockable'] = 1;
1302 }
dd72b308
PS
1303 if ($bc->collapsible == block_contents::HIDDEN) {
1304 $bc->add_class('hidden');
1305 }
1306 if (!empty($bc->controls)) {
1307 $bc->add_class('block_with_controls');
1308 }
d9c8f425 1309
91d941c3 1310
d9c8f425 1311 if (empty($skiptitle)) {
1312 $output = '';
1313 $skipdest = '';
1314 } else {
26acc814
PS
1315 $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
1316 $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
d9c8f425 1317 }
4d2ee4c2 1318
5d0c95a5 1319 $output .= html_writer::start_tag('div', $bc->attributes);
d9c8f425 1320
9f5c39b5
SH
1321 $output .= $this->block_header($bc);
1322 $output .= $this->block_content($bc);
1323
1324 $output .= html_writer::end_tag('div');
1325
1326 $output .= $this->block_annotation($bc);
1327
1328 $output .= $skipdest;
1329
1330 $this->init_block_hider_js($bc);
1331 return $output;
1332 }
1333
1334 /**
1335 * Produces a header for a block
fa7f2a45 1336 *
9f5c39b5
SH
1337 * @param block_contents $bc
1338 * @return string
1339 */
1340 protected function block_header(block_contents $bc) {
d9c8f425 1341
1342 $title = '';
1343 if ($bc->title) {
91d941c3
SH
1344 $attributes = array();
1345 if ($bc->blockinstanceid) {
1346 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1347 }
1348 $title = html_writer::tag('h2', $bc->title, $attributes);
d9c8f425 1349 }
1350
b59f2e3b
SH
1351 $blockid = null;
1352 if (isset($bc->attributes['id'])) {
1353 $blockid = $bc->attributes['id'];
1354 }
1355 $controlshtml = $this->block_controls($bc->controls, $blockid);
9f5c39b5
SH
1356
1357 $output = '';
d9c8f425 1358 if ($title || $controlshtml) {
46de77b6 1359 $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 1360 }
9f5c39b5
SH
1361 return $output;
1362 }
d9c8f425 1363
9f5c39b5
SH
1364 /**
1365 * Produces the content area for a block
1366 *
1367 * @param block_contents $bc
1368 * @return string
1369 */
1370 protected function block_content(block_contents $bc) {
1371 $output = html_writer::start_tag('div', array('class' => 'content'));
1372 if (!$bc->title && !$this->block_controls($bc->controls)) {
46de77b6
SH
1373 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1374 }
d9c8f425 1375 $output .= $bc->content;
9f5c39b5
SH
1376 $output .= $this->block_footer($bc);
1377 $output .= html_writer::end_tag('div');
fa7f2a45 1378
9f5c39b5
SH
1379 return $output;
1380 }
d9c8f425 1381
9f5c39b5
SH
1382 /**
1383 * Produces the footer for a block
1384 *
1385 * @param block_contents $bc
1386 * @return string
1387 */
1388 protected function block_footer(block_contents $bc) {
1389 $output = '';
d9c8f425 1390 if ($bc->footer) {
26acc814 1391 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
d9c8f425 1392 }
9f5c39b5
SH
1393 return $output;
1394 }
d9c8f425 1395
9f5c39b5
SH
1396 /**
1397 * Produces the annotation for a block
1398 *
1399 * @param block_contents $bc
1400 * @return string
1401 */
1402 protected function block_annotation(block_contents $bc) {
1403 $output = '';
d9c8f425 1404 if ($bc->annotation) {
26acc814 1405 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
d9c8f425 1406 }
d9c8f425 1407 return $output;
1408 }
1409
1410 /**
1411 * Calls the JS require function to hide a block.
7a3c215b 1412 *
d9c8f425 1413 * @param block_contents $bc A block_contents object
d9c8f425 1414 */
dd72b308
PS
1415 protected function init_block_hider_js(block_contents $bc) {
1416 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
cbb54cce
SH
1417 $config = new stdClass;
1418 $config->id = $bc->attributes['id'];
1419 $config->title = strip_tags($bc->title);
1420 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1421 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1422 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1423
1424 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1425 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
d9c8f425 1426 }
1427 }
1428
1429 /**
1430 * Render the contents of a block_list.
7a3c215b 1431 *
d9c8f425 1432 * @param array $icons the icon for each item.
1433 * @param array $items the content of each item.
1434 * @return string HTML
1435 */
1436 public function list_block_contents($icons, $items) {
1437 $row = 0;
1438 $lis = array();
1439 foreach ($items as $key => $string) {
5d0c95a5 1440 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
2c5ec833 1441 if (!empty($icons[$key])) { //test if the content has an assigned icon
26acc814 1442 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
d9c8f425 1443 }
26acc814 1444 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
5d0c95a5 1445 $item .= html_writer::end_tag('li');
d9c8f425 1446 $lis[] = $item;
1447 $row = 1 - $row; // Flip even/odd.
1448 }
f2a04fc1 1449 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
d9c8f425 1450 }
1451
1452 /**
1453 * Output all the blocks in a particular region.
7a3c215b 1454 *
d9c8f425 1455 * @param string $region the name of a region on this page.
1456 * @return string the HTML to be output.
1457 */
1458 public function blocks_for_region($region) {
1459 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
6671fa73
JF
1460 $blocks = $this->page->blocks->get_blocks_for_region($region);
1461 $lastblock = null;
1462 $zones = array();
1463 foreach ($blocks as $block) {
1464 $zones[] = $block->title;
1465 }
d9c8f425 1466 $output = '';
6671fa73 1467
d9c8f425 1468 foreach ($blockcontents as $bc) {
1469 if ($bc instanceof block_contents) {
1470 $output .= $this->block($bc, $region);
6671fa73 1471 $lastblock = $bc->title;
d9c8f425 1472 } else if ($bc instanceof block_move_target) {
686e3b3a 1473 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
d9c8f425 1474 } else {
1475 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1476 }
1477 }
1478 return $output;
1479 }
1480
1481 /**
1482 * Output a place where the block that is currently being moved can be dropped.
7a3c215b 1483 *
d9c8f425 1484 * @param block_move_target $target with the necessary details.
6671fa73
JF
1485 * @param array $zones array of areas where the block can be moved to
1486 * @param string $previous the block located before the area currently being rendered.
686e3b3a 1487 * @param string $region the name of the region
d9c8f425 1488 * @return string the HTML to be output.
1489 */
686e3b3a 1490 public function block_move_target($target, $zones, $previous, $region) {
0e2ca62e 1491 if ($previous == null) {
686e3b3a
FM
1492 if (empty($zones)) {
1493 // There are no zones, probably because there are no blocks.
1494 $regions = $this->page->theme->get_all_block_regions();
1495 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1496 } else {
1497 $position = get_string('moveblockbefore', 'block', $zones[0]);
1498 }
6671fa73
JF
1499 } else {
1500 $position = get_string('moveblockafter', 'block', $previous);
1501 }
1502 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
d9c8f425 1503 }
1504
574fbea4 1505 /**
996b1e0c 1506 * Renders a special html link with attached action
574fbea4 1507 *
2fada290
MG
1508 * Theme developers: DO NOT OVERRIDE! Please override function
1509 * {@link core_renderer::render_action_link()} instead.
1510 *
574fbea4
PS
1511 * @param string|moodle_url $url
1512 * @param string $text HTML fragment
1513 * @param component_action $action
11820bac 1514 * @param array $attributes associative array of html link attributes + disabled
e282c679 1515 * @param pix_icon optional pix icon to render with the link
7a3c215b 1516 * @return string HTML fragment
574fbea4 1517 */
e282c679 1518 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
574fbea4
PS
1519 if (!($url instanceof moodle_url)) {
1520 $url = new moodle_url($url);
1521 }
e282c679 1522 $link = new action_link($url, $text, $action, $attributes, $icon);
574fbea4 1523
f14b641b 1524 return $this->render($link);
574fbea4
PS
1525 }
1526
1527 /**
7a3c215b
SH
1528 * Renders an action_link object.
1529 *
1530 * The provided link is renderer and the HTML returned. At the same time the
f8129210 1531 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
7a3c215b 1532 *
574fbea4
PS
1533 * @param action_link $link
1534 * @return string HTML fragment
1535 */
1536 protected function render_action_link(action_link $link) {
1537 global $CFG;
1538
e282c679
SH
1539 $text = '';
1540 if ($link->icon) {
1541 $text .= $this->render($link->icon);
1542 }
1543
7749e187 1544 if ($link->text instanceof renderable) {
e282c679 1545 $text .= $this->render($link->text);
7749e187 1546 } else {
e282c679 1547 $text .= $link->text;
7749e187
SH
1548 }
1549
574fbea4
PS
1550 // A disabled link is rendered as formatted text
1551 if (!empty($link->attributes['disabled'])) {
1552 // do not use div here due to nesting restriction in xhtml strict
7749e187 1553 return html_writer::tag('span', $text, array('class'=>'currentlink'));
574fbea4 1554 }
11820bac 1555
574fbea4
PS
1556 $attributes = $link->attributes;
1557 unset($link->attributes['disabled']);
1558 $attributes['href'] = $link->url;
1559
1560 if ($link->actions) {
f14b641b 1561 if (empty($attributes['id'])) {
574fbea4
PS
1562 $id = html_writer::random_id('action_link');
1563 $attributes['id'] = $id;
1564 } else {
1565 $id = $attributes['id'];
1566 }
1567 foreach ($link->actions as $action) {
c80877aa 1568 $this->add_action_handler($action, $id);
574fbea4
PS
1569 }
1570 }
1571
7749e187 1572 return html_writer::tag('a', $text, $attributes);
574fbea4
PS
1573 }
1574
c63923bd
PS
1575
1576 /**
7a3c215b
SH
1577 * Renders an action_icon.
1578 *
f8129210 1579 * This function uses the {@link core_renderer::action_link()} method for the
7a3c215b
SH
1580 * most part. What it does different is prepare the icon as HTML and use it
1581 * as the link text.
c63923bd 1582 *
2fada290
MG
1583 * Theme developers: If you want to change how action links and/or icons are rendered,
1584 * consider overriding function {@link core_renderer::render_action_link()} and
1585 * {@link core_renderer::render_pix_icon()}.
1586 *
c63923bd
PS
1587 * @param string|moodle_url $url A string URL or moodel_url
1588 * @param pix_icon $pixicon
1589 * @param component_action $action
1590 * @param array $attributes associative array of html link attributes + disabled
1591 * @param bool $linktext show title next to image in link
1592 * @return string HTML fragment
1593 */
1594 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1595 if (!($url instanceof moodle_url)) {
1596 $url = new moodle_url($url);
1597 }
1598 $attributes = (array)$attributes;
1599
524645e7 1600 if (empty($attributes['class'])) {
c63923bd
PS
1601 // let ppl override the class via $options
1602 $attributes['class'] = 'action-icon';
1603 }
1604
1605 $icon = $this->render($pixicon);
1606
1607 if ($linktext) {
1608 $text = $pixicon->attributes['alt'];
1609 } else {
1610 $text = '';
1611 }
1612
1613 return $this->action_link($url, $text.$icon, $action, $attributes);
1614 }
1615
d9c8f425 1616 /**
0b634d75 1617 * Print a message along with button choices for Continue/Cancel
1618 *
4ed85790 1619 * If a string or moodle_url is given instead of a single_button, method defaults to post.
0b634d75 1620 *
d9c8f425 1621 * @param string $message The question to ask the user
3ba60ee1
PS
1622 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1623 * @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 1624 * @return string HTML fragment
1625 */
1626 public function confirm($message, $continue, $cancel) {
4871a238 1627 if ($continue instanceof single_button) {
11820bac 1628 // ok
4871a238
PS
1629 } else if (is_string($continue)) {
1630 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1631 } else if ($continue instanceof moodle_url) {
26eab8d4 1632 $continue = new single_button($continue, get_string('continue'), 'post');
d9c8f425 1633 } else {
4ed85790 1634 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
d9c8f425 1635 }
1636
4871a238 1637 if ($cancel instanceof single_button) {
11820bac 1638 // ok
4871a238
PS
1639 } else if (is_string($cancel)) {
1640 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1641 } else if ($cancel instanceof moodle_url) {
26eab8d4 1642 $cancel = new single_button($cancel, get_string('cancel'), 'get');
d9c8f425 1643 } else {
4ed85790 1644 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
d9c8f425 1645 }
1646
d9c8f425 1647 $output = $this->box_start('generalbox', 'notice');
26acc814
PS
1648 $output .= html_writer::tag('p', $message);
1649 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
d9c8f425 1650 $output .= $this->box_end();
1651 return $output;
1652 }
1653
3cd5305f 1654 /**
3ba60ee1 1655 * Returns a form with a single button.
3cd5305f 1656 *
2fada290
MG
1657 * Theme developers: DO NOT OVERRIDE! Please override function
1658 * {@link core_renderer::render_single_button()} instead.
1659 *
3ba60ee1 1660 * @param string|moodle_url $url
3cd5305f
PS
1661 * @param string $label button text
1662 * @param string $method get or post submit method
3ba60ee1 1663 * @param array $options associative array {disabled, title, etc.}
3cd5305f
PS
1664 * @return string HTML fragment
1665 */
3ba60ee1 1666 public function single_button($url, $label, $method='post', array $options=null) {
574fbea4
PS
1667 if (!($url instanceof moodle_url)) {
1668 $url = new moodle_url($url);
3ba60ee1 1669 }
574fbea4
PS
1670 $button = new single_button($url, $label, $method);
1671
3ba60ee1
PS
1672 foreach ((array)$options as $key=>$value) {
1673 if (array_key_exists($key, $button)) {
1674 $button->$key = $value;
1675 }
3cd5305f
PS
1676 }
1677
3ba60ee1 1678 return $this->render($button);
3cd5305f
PS
1679 }
1680
d9c8f425 1681 /**
7a3c215b
SH
1682 * Renders a single button widget.
1683 *
1684 * This will return HTML to display a form containing a single button.
1685 *
3ba60ee1 1686 * @param single_button $button
d9c8f425 1687 * @return string HTML fragment
1688 */
3ba60ee1
PS
1689 protected function render_single_button(single_button $button) {
1690 $attributes = array('type' => 'submit',
1691 'value' => $button->label,
db09524d 1692 'disabled' => $button->disabled ? 'disabled' : null,
3ba60ee1
PS
1693 'title' => $button->tooltip);
1694
1695 if ($button->actions) {
1696 $id = html_writer::random_id('single_button');
1697 $attributes['id'] = $id;
1698 foreach ($button->actions as $action) {
c80877aa 1699 $this->add_action_handler($action, $id);
3ba60ee1 1700 }
d9c8f425 1701 }
d9c8f425 1702
3ba60ee1
PS
1703 // first the input element
1704 $output = html_writer::empty_tag('input', $attributes);
d9c8f425 1705
3ba60ee1
PS
1706 // then hidden fields
1707 $params = $button->url->params();
1708 if ($button->method === 'post') {
1709 $params['sesskey'] = sesskey();
1710 }
1711 foreach ($params as $var => $val) {
1712 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1713 }
d9c8f425 1714
3ba60ee1 1715 // then div wrapper for xhtml strictness
26acc814 1716 $output = html_writer::tag('div', $output);
d9c8f425 1717
3ba60ee1 1718 // now the form itself around it
a12cd69c
DM
1719 if ($button->method === 'get') {
1720 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1721 } else {
1722 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1723 }
a6855934
PS
1724 if ($url === '') {
1725 $url = '#'; // there has to be always some action
1726 }
3ba60ee1 1727 $attributes = array('method' => $button->method,
a6855934 1728 'action' => $url,
3ba60ee1 1729 'id' => $button->formid);
26acc814 1730 $output = html_writer::tag('form', $output, $attributes);
d9c8f425 1731
3ba60ee1 1732 // and finally one more wrapper with class
26acc814 1733 return html_writer::tag('div', $output, array('class' => $button->class));
d9c8f425 1734 }
1735
a9967cf5 1736 /**
ab08be98 1737 * Returns a form with a single select widget.
7a3c215b 1738 *
2fada290
MG
1739 * Theme developers: DO NOT OVERRIDE! Please override function
1740 * {@link core_renderer::render_single_select()} instead.
1741 *
a9967cf5
PS
1742 * @param moodle_url $url form action target, includes hidden fields
1743 * @param string $name name of selection field - the changing parameter in url
1744 * @param array $options list of options
1745 * @param string $selected selected element
1746 * @param array $nothing
f8dab966 1747 * @param string $formid
a9967cf5
PS
1748 * @return string HTML fragment
1749 */
7a3c215b 1750 public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
a9967cf5
PS
1751 if (!($url instanceof moodle_url)) {
1752 $url = new moodle_url($url);
1753 }
f8dab966 1754 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
a9967cf5
PS
1755
1756 return $this->render($select);
1757 }
1758
1759 /**
1760 * Internal implementation of single_select rendering
7a3c215b 1761 *
a9967cf5
PS
1762 * @param single_select $select
1763 * @return string HTML fragment
1764 */
1765 protected function render_single_select(single_select $select) {
1766 $select = clone($select);
1767 if (empty($select->formid)) {
1768 $select->formid = html_writer::random_id('single_select_f');
1769 }
1770
1771 $output = '';
1772 $params = $select->url->params();
1773 if ($select->method === 'post') {
1774 $params['sesskey'] = sesskey();
1775 }
1776 foreach ($params as $name=>$value) {
1777 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1778 }
1779
1780 if (empty($select->attributes['id'])) {
1781 $select->attributes['id'] = html_writer::random_id('single_select');
1782 }
1783
0b2cb132
PS
1784 if ($select->disabled) {
1785 $select->attributes['disabled'] = 'disabled';
1786 }
4d10e579 1787
a9967cf5
PS
1788 if ($select->tooltip) {
1789 $select->attributes['title'] = $select->tooltip;
1790 }
1791
7266bd3e
ARN
1792 $select->attributes['class'] = 'autosubmit';
1793 if ($select->class) {
1794 $select->attributes['class'] .= ' ' . $select->class;
1795 }
1796
a9967cf5 1797 if ($select->label) {
ecc5cc31 1798 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
a9967cf5
PS
1799 }
1800
1801 if ($select->helpicon instanceof help_icon) {
1802 $output .= $this->render($select->helpicon);
1803 }
a9967cf5
PS
1804 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1805
1806 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
ebc583e4 1807 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
a9967cf5
PS
1808
1809 $nothing = empty($select->nothing) ? false : key($select->nothing);
7266bd3e
ARN
1810 $this->page->requires->yui_module('moodle-core-formautosubmit',
1811 'M.core.init_formautosubmit',
1812 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1813 );
a9967cf5
PS
1814
1815 // then div wrapper for xhtml strictness
26acc814 1816 $output = html_writer::tag('div', $output);
a9967cf5
PS
1817
1818 // now the form itself around it
a12cd69c
DM
1819 if ($select->method === 'get') {
1820 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1821 } else {
1822 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1823 }
a9967cf5 1824 $formattributes = array('method' => $select->method,
a12cd69c 1825 'action' => $url,
a9967cf5 1826 'id' => $select->formid);
26acc814 1827 $output = html_writer::tag('form', $output, $formattributes);
4d10e579
PS
1828
1829 // and finally one more wrapper with class
26acc814 1830 return html_writer::tag('div', $output, array('class' => $select->class));
4d10e579
PS
1831 }
1832
1833 /**
ab08be98 1834 * Returns a form with a url select widget.
7a3c215b 1835 *
2fada290
MG
1836 * Theme developers: DO NOT OVERRIDE! Please override function
1837 * {@link core_renderer::render_url_select()} instead.
1838 *
4d10e579
PS
1839 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1840 * @param string $selected selected element
1841 * @param array $nothing
1842 * @param string $formid
1843 * @return string HTML fragment
1844 */
7a3c215b 1845 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
4d10e579
PS
1846 $select = new url_select($urls, $selected, $nothing, $formid);
1847 return $this->render($select);
1848 }
1849
1850 /**
ab08be98 1851 * Internal implementation of url_select rendering
7a3c215b
SH
1852 *
1853 * @param url_select $select
4d10e579
PS
1854 * @return string HTML fragment
1855 */
1856 protected function render_url_select(url_select $select) {
c422efcf
PS
1857 global $CFG;
1858
4d10e579
PS
1859 $select = clone($select);
1860 if (empty($select->formid)) {
1861 $select->formid = html_writer::random_id('url_select_f');
1862 }
1863
1864 if (empty($select->attributes['id'])) {
1865 $select->attributes['id'] = html_writer::random_id('url_select');
1866 }
1867
1868 if ($select->disabled) {
1869 $select->attributes['disabled'] = 'disabled';
1870 }
1871
1872 if ($select->tooltip) {
1873 $select->attributes['title'] = $select->tooltip;
1874 }
1875
1876 $output = '';
1877
1878 if ($select->label) {
ecc5cc31 1879 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
4d10e579
PS
1880 }
1881
50d6ad84
ARN
1882 $classes = array();
1883 if (!$select->showbutton) {
1884 $classes[] = 'autosubmit';
1885 }
7266bd3e 1886 if ($select->class) {
50d6ad84
ARN
1887 $classes[] = $select->class;
1888 }
1889 if (count($classes)) {
1890 $select->attributes['class'] = implode(' ', $classes);
7266bd3e
ARN
1891 }
1892
4d10e579
PS
1893 if ($select->helpicon instanceof help_icon) {
1894 $output .= $this->render($select->helpicon);
1895 }
1896
d4dcfc6b
DM
1897 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
1898 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
c422efcf
PS
1899 $urls = array();
1900 foreach ($select->urls as $k=>$v) {
d4dcfc6b
DM
1901 if (is_array($v)) {
1902 // optgroup structure
1903 foreach ($v as $optgrouptitle => $optgroupoptions) {
1904 foreach ($optgroupoptions as $optionurl => $optiontitle) {
1905 if (empty($optionurl)) {
1906 $safeoptionurl = '';
1907 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
1908 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
1909 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
1910 } else if (strpos($optionurl, '/') !== 0) {
1911 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
1912 continue;
1913 } else {
1914 $safeoptionurl = $optionurl;
1915 }
1916 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
1917 }
1918 }
1919 } else {
1920 // plain list structure
1921 if (empty($k)) {
1922 // nothing selected option
1923 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
1924 $k = str_replace($CFG->wwwroot, '', $k);
1925 } else if (strpos($k, '/') !== 0) {
1926 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
1927 continue;
1928 }
1929 $urls[$k] = $v;
1930 }
1931 }
1932 $selected = $select->selected;
1933 if (!empty($selected)) {
1934 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
1935 $selected = str_replace($CFG->wwwroot, '', $selected);
1936 } else if (strpos($selected, '/') !== 0) {
1937 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
c422efcf 1938 }
c422efcf
PS
1939 }
1940
4d10e579 1941 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
d4dcfc6b 1942 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
4d10e579 1943
15e48a1a
SM
1944 if (!$select->showbutton) {
1945 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
ebc583e4 1946 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
15e48a1a 1947 $nothing = empty($select->nothing) ? false : key($select->nothing);
7266bd3e
ARN
1948 $this->page->requires->yui_module('moodle-core-formautosubmit',
1949 'M.core.init_formautosubmit',
1950 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1951 );
15e48a1a
SM
1952 } else {
1953 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
1954 }
4d10e579
PS
1955
1956 // then div wrapper for xhtml strictness
26acc814 1957 $output = html_writer::tag('div', $output);
4d10e579
PS
1958
1959 // now the form itself around it
1960 $formattributes = array('method' => 'post',
1961 'action' => new moodle_url('/course/jumpto.php'),
1962 'id' => $select->formid);
26acc814 1963 $output = html_writer::tag('form', $output, $formattributes);
a9967cf5
PS
1964
1965 // and finally one more wrapper with class
26acc814 1966 return html_writer::tag('div', $output, array('class' => $select->class));
a9967cf5
PS
1967 }
1968
d9c8f425 1969 /**
1970 * Returns a string containing a link to the user documentation.
1971 * Also contains an icon by default. Shown to teachers and admin only.
7a3c215b 1972 *
d9c8f425 1973 * @param string $path The page link after doc root and language, no leading slash.
1974 * @param string $text The text to be displayed for the link
afe3566c 1975 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
996b1e0c 1976 * @return string
d9c8f425 1977 */
afe3566c 1978 public function doc_link($path, $text = '', $forcepopup = false) {
8ae8bf8a
PS
1979 global $CFG;
1980
ae4086bd 1981 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
8ae8bf8a 1982
000c278c 1983 $url = new moodle_url(get_docs_url($path));
8ae8bf8a 1984
c80877aa 1985 $attributes = array('href'=>$url);
afe3566c
ARN
1986 if (!empty($CFG->doctonewwindow) || $forcepopup) {
1987 $attributes['class'] = 'helplinkpopup';
d9c8f425 1988 }
1adaa404 1989
26acc814 1990 return html_writer::tag('a', $icon.$text, $attributes);
d9c8f425 1991 }
1992
000c278c 1993 /**
7a3c215b
SH
1994 * Return HTML for a pix_icon.
1995 *
2fada290
MG
1996 * Theme developers: DO NOT OVERRIDE! Please override function
1997 * {@link core_renderer::render_pix_icon()} instead.
1998 *
000c278c
PS
1999 * @param string $pix short pix name
2000 * @param string $alt mandatory alt attribute
eb557002 2001 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
000c278c
PS
2002 * @param array $attributes htm lattributes
2003 * @return string HTML fragment
2004 */
2005 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2006 $icon = new pix_icon($pix, $alt, $component, $attributes);
2007 return $this->render($icon);
2008 }
2009
2010 /**
7a3c215b
SH
2011 * Renders a pix_icon widget and returns the HTML to display it.
2012 *
000c278c
PS
2013 * @param pix_icon $icon
2014 * @return string HTML fragment
2015 */
ce0110bf 2016 protected function render_pix_icon(pix_icon $icon) {
000c278c
PS
2017 $attributes = $icon->attributes;
2018 $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
c80877aa 2019 return html_writer::empty_tag('img', $attributes);
000c278c
PS
2020 }
2021
d63c5073 2022 /**
7a3c215b
SH
2023 * Return HTML to display an emoticon icon.
2024 *
d63c5073
DM
2025 * @param pix_emoticon $emoticon
2026 * @return string HTML fragment
2027 */
2028 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2029 $attributes = $emoticon->attributes;
2030 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
2031 return html_writer::empty_tag('img', $attributes);
2032 }
2033
a09aeee4 2034 /**
7a3c215b
SH
2035 * Produces the html that represents this rating in the UI
2036 *
2037 * @param rating $rating the page object on which this rating will appear
2038 * @return string
2039 */
a09aeee4 2040 function render_rating(rating $rating) {
7ac928a7 2041 global $CFG, $USER;
a09aeee4 2042
2b04c41c 2043 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
63e87951
AD
2044 return null;//ratings are turned off
2045 }
2046
2b04c41c
SH
2047 $ratingmanager = new rating_manager();
2048 // Initialise the JavaScript so ratings can be done by AJAX.
2049 $ratingmanager->initialise_rating_javascript($this->page);
a09aeee4 2050
63e87951
AD
2051 $strrate = get_string("rate", "rating");
2052 $ratinghtml = ''; //the string we'll return
2053
2b04c41c
SH
2054 // permissions check - can they view the aggregate?
2055 if ($rating->user_can_view_aggregate()) {
a09aeee4 2056
2b04c41c
SH
2057 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2058 $aggregatestr = $rating->get_aggregate_string();
a09aeee4 2059
6278ce45 2060 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2b04c41c 2061 if ($rating->count > 0) {
6278ce45 2062 $countstr = "({$rating->count})";
d251b259 2063 } else {
6278ce45 2064 $countstr = '-';
d251b259 2065 }
6278ce45 2066 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
63e87951 2067
c6de9cef 2068 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
d251b259 2069 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2b04c41c
SH
2070
2071 $nonpopuplink = $rating->get_view_ratings_url();
2072 $popuplink = $rating->get_view_ratings_url(true);
a09aeee4 2073
d251b259 2074 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
c6de9cef 2075 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
d251b259 2076 } else {
c6de9cef 2077 $ratinghtml .= $aggregatehtml;
a09aeee4 2078 }
d251b259 2079 }
a09aeee4 2080
d251b259 2081 $formstart = null;
2b04c41c
SH
2082 // if the item doesn't belong to the current user, the user has permission to rate
2083 // and we're within the assessable period
2084 if ($rating->user_can_rate()) {
771b3fbe 2085
2b04c41c
SH
2086 $rateurl = $rating->get_rate_url();
2087 $inputs = $rateurl->params();
771b3fbe 2088
2b04c41c
SH
2089 //start the rating form
2090 $formattrs = array(
2091 'id' => "postrating{$rating->itemid}",
2092 'class' => 'postratingform',
2093 'method' => 'post',
2094 'action' => $rateurl->out_omit_querystring()
2095 );
2096 $formstart = html_writer::start_tag('form', $formattrs);
2097 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2098
2099 // add the hidden inputs
2100 foreach ($inputs as $name => $value) {
2101 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2102 $formstart .= html_writer::empty_tag('input', $attributes);
2103 }
3180bc2c 2104
d251b259
AD
2105 if (empty($ratinghtml)) {
2106 $ratinghtml .= $strrate.': ';
2107 }
d251b259 2108 $ratinghtml = $formstart.$ratinghtml;
63e87951 2109
2b04c41c
SH
2110 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2111 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
ecc5cc31 2112 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2b04c41c 2113 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
a09aeee4 2114
d251b259 2115 //output submit button
771b3fbe
AD
2116 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2117
2b04c41c 2118 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
771b3fbe 2119 $ratinghtml .= html_writer::empty_tag('input', $attributes);
a09aeee4 2120
2b04c41c 2121 if (!$rating->settings->scale->isnumeric) {
eaf52ff0
MN
2122 // If a global scale, try to find current course ID from the context
2123 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2124 $courseid = $coursecontext->instanceid;
2125 } else {
2126 $courseid = $rating->settings->scale->courseid;
2127 }
2128 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
a09aeee4 2129 }
771b3fbe
AD
2130 $ratinghtml .= html_writer::end_tag('span');
2131 $ratinghtml .= html_writer::end_tag('div');
2132 $ratinghtml .= html_writer::end_tag('form');
a09aeee4
AD
2133 }
2134
63e87951 2135 return $ratinghtml;
a09aeee4
AD
2136 }
2137
7a3c215b 2138 /**
d9c8f425 2139 * Centered heading with attached help button (same title text)
7a3c215b
SH
2140 * and optional icon attached.
2141 *
4bcc5118 2142 * @param string $text A heading text
53a78cef 2143 * @param string $helpidentifier The keyword that defines a help page
4bcc5118
PS
2144 * @param string $component component name
2145 * @param string|moodle_url $icon
2146 * @param string $iconalt icon alt text
699e2fd0
RW
2147 * @param int $level The level of importance of the heading. Defaulting to 2
2148 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
d9c8f425 2149 * @return string HTML fragment
2150 */
699e2fd0 2151 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
4bcc5118
PS
2152 $image = '';
2153 if ($icon) {
8ef1aa40 2154 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
d9c8f425 2155 }
4bcc5118 2156
259c165d
PS
2157 $help = '';
2158 if ($helpidentifier) {
2159 $help = $this->help_icon($helpidentifier, $component);
2160 }
4bcc5118 2161
699e2fd0 2162 return $this->heading($image.$text.$help, $level, $classnames);
d9c8f425 2163 }
2164
2165 /**
7a3c215b 2166 * Returns HTML to display a help icon.
d9c8f425 2167 *
cb616be8 2168 * @deprecated since Moodle 2.0
bf11293a 2169 */
596509e4 2170 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
a6d81a73 2171 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
d9c8f425 2172 }
2173
259c165d 2174 /**
7a3c215b 2175 * Returns HTML to display a help icon.
259c165d 2176 *
2fada290
MG
2177 * Theme developers: DO NOT OVERRIDE! Please override function
2178 * {@link core_renderer::render_help_icon()} instead.
2179 *
259c165d
PS
2180 * @param string $identifier The keyword that defines a help page
2181 * @param string $component component name
2182 * @param string|bool $linktext true means use $title as link text, string means link text value
2183 * @return string HTML fragment
2184 */
2185 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2cf81209 2186 $icon = new help_icon($identifier, $component);
259c165d
PS
2187 $icon->diag_strings();
2188 if ($linktext === true) {
2189 $icon->linktext = get_string($icon->identifier, $icon->component);
2190 } else if (!empty($linktext)) {
2191 $icon->linktext = $linktext;
2192 }
2193 return $this->render($icon);
2194 }
2195
2196 /**
2197 * Implementation of user image rendering.
7a3c215b 2198 *
3d3fae72 2199 * @param help_icon $helpicon A help icon instance
259c165d
PS
2200 * @return string HTML fragment
2201 */
2202 protected function render_help_icon(help_icon $helpicon) {
2203 global $CFG;
2204
2205 // first get the help image icon
2206 $src = $this->pix_url('help');
2207
2208 $title = get_string($helpicon->identifier, $helpicon->component);
2209
2210 if (empty($helpicon->linktext)) {
cab2c7ea 2211 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
259c165d
PS
2212 } else {
2213 $alt = get_string('helpwiththis');
2214 }
2215
2216 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
2217 $output = html_writer::empty_tag('img', $attributes);
2218
2219 // add the link text if given
2220 if (!empty($helpicon->linktext)) {
2221 // the spacing has to be done through CSS
2222 $output .= $helpicon->linktext;
2223 }
2224
69542fb3
PS
2225 // now create the link around it - we need https on loginhttps pages
2226 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
259c165d
PS
2227
2228 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
2229 $title = get_string('helpprefix2', '', trim($title, ". \t"));
2230
e88419a2 2231 $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true', 'target'=>'_blank');
259c165d
PS
2232 $output = html_writer::tag('a', $output, $attributes);
2233
2234 // and finally span
238b8bc9 2235 return html_writer::tag('span', $output, array('class' => 'helptooltip'));
259c165d
PS
2236 }
2237
d9c8f425 2238 /**
7a3c215b 2239 * Returns HTML to display a scale help icon.
d9c8f425 2240 *
4bcc5118 2241 * @param int $courseid
7a3c215b
SH
2242 * @param stdClass $scale instance
2243 * @return string HTML fragment
d9c8f425 2244 */
4bcc5118
PS
2245 public function help_icon_scale($courseid, stdClass $scale) {
2246 global $CFG;
02f64f97 2247
4bcc5118 2248 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
02f64f97 2249
0029a917 2250 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
02f64f97 2251
68bf577b
AD
2252 $scaleid = abs($scale->id);
2253
2254 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
230ec401 2255 $action = new popup_action('click', $link, 'ratingscale');
02f64f97 2256
26acc814 2257 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
d9c8f425 2258 }
2259
2260 /**
2261 * Creates and returns a spacer image with optional line break.
2262 *
3d3fae72
SH
2263 * @param array $attributes Any HTML attributes to add to the spaced.
2264 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2265 * laxy do it with CSS which is a much better solution.
d9c8f425 2266 * @return string HTML fragment
2267 */
0029a917
PS
2268 public function spacer(array $attributes = null, $br = false) {
2269 $attributes = (array)$attributes;
2270 if (empty($attributes['width'])) {
2271 $attributes['width'] = 1;
1ba862ec 2272 }
e1a5a9cc 2273 if (empty($attributes['height'])) {
0029a917 2274 $attributes['height'] = 1;
d9c8f425 2275 }
0029a917 2276 $attributes['class'] = 'spacer';
d9c8f425 2277
0029a917 2278 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
b65bfc3e 2279
0029a917 2280 if (!empty($br)) {
1ba862ec
PS
2281 $output .= '<br />';
2282 }
d9c8f425 2283
2284 return $output;
2285 }
2286
d9c8f425 2287 /**
7a3c215b 2288 * Returns HTML to display the specified user's avatar.
d9c8f425 2289 *
5d0c95a5 2290 * User avatar may be obtained in two ways:
d9c8f425 2291 * <pre>
812dbaf7
PS
2292 * // Option 1: (shortcut for simple cases, preferred way)
2293 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2294 * $OUTPUT->user_picture($user, array('popup'=>true));
2295 *
5d0c95a5
PS
2296 * // Option 2:
2297 * $userpic = new user_picture($user);
d9c8f425 2298 * // Set properties of $userpic
812dbaf7 2299 * $userpic->popup = true;
5d0c95a5 2300 * $OUTPUT->render($userpic);
d9c8f425 2301 * </pre>
2302 *
2fada290
MG
2303 * Theme developers: DO NOT OVERRIDE! Please override function
2304 * {@link core_renderer::render_user_picture()} instead.
2305 *
7a3c215b 2306 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
812dbaf7 2307 * If any of these are missing, the database is queried. Avoid this
d9c8f425 2308 * if at all possible, particularly for reports. It is very bad for performance.
812dbaf7
PS
2309 * @param array $options associative array with user picture options, used only if not a user_picture object,
2310 * options are:
2311 * - courseid=$this->page->course->id (course id of user profile in link)
2312 * - size=35 (size of image)
2313 * - link=true (make image clickable - the link leads to user profile)
2314 * - popup=false (open in popup)
2315 * - alttext=true (add image alt attribute)
5d0c95a5 2316 * - class = image class attribute (default 'userpicture')
e4a1efcb 2317 * - visibletoscreenreaders=true (whether to be visible to screen readers)
d9c8f425 2318 * @return string HTML fragment
2319 */
5d0c95a5
PS
2320 public function user_picture(stdClass $user, array $options = null) {
2321 $userpicture = new user_picture($user);
2322 foreach ((array)$options as $key=>$value) {
2323 if (array_key_exists($key, $userpicture)) {
2324 $userpicture->$key = $value;
2325 }
2326 }
2327 return $this->render($userpicture);
2328 }
2329
2330 /**
2331 * Internal implementation of user image rendering.
7a3c215b 2332 *
5d0c95a5
PS
2333 * @param user_picture $userpicture
2334 * @return string
2335 */
2336 protected function render_user_picture(user_picture $userpicture) {
2337 global $CFG, $DB;
812dbaf7 2338
5d0c95a5
PS
2339 $user = $userpicture->user;
2340
2341 if ($userpicture->alttext) {
2342 if (!empty($user->imagealt)) {
2343 $alt = $user->imagealt;
2344 } else {
2345 $alt = get_string('pictureof', '', fullname($user));
2346 }
d9c8f425 2347 } else {
97c10099 2348 $alt = '';
5d0c95a5
PS
2349 }
2350
2351 if (empty($userpicture->size)) {
5d0c95a5
PS
2352 $size = 35;
2353 } else if ($userpicture->size === true or $userpicture->size == 1) {
5d0c95a5 2354 $size = 100;
5d0c95a5 2355 } else {
5d0c95a5 2356 $size = $userpicture->size;
d9c8f425 2357 }
2358
5d0c95a5 2359 $class = $userpicture->class;
d9c8f425 2360
4d254790 2361 if ($user->picture == 0) {
5d0c95a5 2362 $class .= ' defaultuserpic';
5d0c95a5 2363 }
d9c8f425 2364
871a3ec5
SH
2365 $src = $userpicture->get_url($this->page, $this);
2366
29cf6631 2367 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
e4a1efcb
JC
2368 if (!$userpicture->visibletoscreenreaders) {
2369 $attributes['role'] = 'presentation';
2370 }
2371
5d0c95a5 2372 // get the image html output fisrt
0e35ba6f 2373 $output = html_writer::empty_tag('img', $attributes);
5d0c95a5
PS
2374
2375 // then wrap it in link if needed
2376 if (!$userpicture->link) {
2377 return $output;
d9c8f425 2378 }
2379
5d0c95a5
PS
2380 if (empty($userpicture->courseid)) {
2381 $courseid = $this->page->course->id;
2382 } else {
2383 $courseid = $userpicture->courseid;
2384 }
2385
03d9401e
MD
2386 if ($courseid == SITEID) {
2387 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2388 } else {
2389 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2390 }
5d0c95a5
PS
2391
2392 $attributes = array('href'=>$url);
e4a1efcb 2393 if (!$userpicture->visibletoscreenreaders) {
e4a1efcb
JC
2394 $attributes['tabindex'] = '-1';
2395 $attributes['aria-hidden'] = 'true';
2396 }
5d0c95a5
PS
2397
2398 if ($userpicture->popup) {
2399 $id = html_writer::random_id('userpicture');
2400 $attributes['id'] = $id;
c80877aa 2401 $this->add_action_handler(new popup_action('click', $url), $id);
5d0c95a5
PS
2402 }
2403
26acc814 2404 return html_writer::tag('a', $output, $attributes);
d9c8f425 2405 }
b80ef420 2406
b80ef420
DC
2407 /**
2408 * Internal implementation of file tree viewer items rendering.
7a3c215b 2409 *
b80ef420
DC
2410 * @param array $dir
2411 * @return string
2412 */
2413 public function htmllize_file_tree($dir) {
2414 if (empty($dir['subdirs']) and empty($dir['files'])) {
2415 return '';
2416 }
2417 $result = '<ul>';
2418 foreach ($dir['subdirs'] as $subdir) {
2419 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2420 }
2421 foreach ($dir['files'] as $file) {
2422 $filename = $file->get_filename();
2423 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2424 }
2425 $result .= '</ul>';
2426
2427 return $result;
2428 }
7a3c215b 2429
bb496de7 2430 /**
7a3c215b 2431 * Returns HTML to display the file picker
bb496de7
DC
2432 *
2433 * <pre>
2434 * $OUTPUT->file_picker($options);
2435 * </pre>
2436 *
2fada290
MG
2437 * Theme developers: DO NOT OVERRIDE! Please override function
2438 * {@link core_renderer::render_file_picker()} instead.
2439 *
bb496de7
DC
2440 * @param array $options associative array with file manager options
2441 * options are:
2442 * maxbytes=>-1,
2443 * itemid=>0,
2444 * client_id=>uniqid(),
2445 * acepted_types=>'*',
2446 * return_types=>FILE_INTERNAL,
2447 * context=>$PAGE->context
2448 * @return string HTML fragment
2449 */
2450 public function file_picker($options) {
2451 $fp = new file_picker($options);
2452 return $this->render($fp);
2453 }
7a3c215b 2454
b80ef420
DC
2455 /**
2456 * Internal implementation of file picker rendering.
7a3c215b 2457 *
b80ef420
DC
2458 * @param file_picker $fp
2459 * @return string
2460 */
bb496de7
DC
2461 public function render_file_picker(file_picker $fp) {
2462 global $CFG, $OUTPUT, $USER;
2463 $options = $fp->options;
2464 $client_id = $options->client_id;
2465 $strsaved = get_string('filesaved', 'repository');
2466 $straddfile = get_string('openpicker', 'repository');
2467 $strloading = get_string('loading', 'repository');
adce0230 2468 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
906e7d89 2469 $strdroptoupload = get_string('droptoupload', 'moodle');
bb496de7
DC
2470 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2471
2472 $currentfile = $options->currentfile;
2473 if (empty($currentfile)) {
322945e9
FM
2474 $currentfile = '';
2475 } else {
2476 $currentfile .= ' - ';
bb496de7 2477 }
b817205b
DC
2478 if ($options->maxbytes) {
2479 $size = $options->maxbytes;
2480 } else {
2481 $size = get_max_upload_file_size();
2482 }
513aed3c 2483 if ($size == -1) {
831399c4 2484 $maxsize = '';
513aed3c
DC
2485 } else {
2486 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2487 }
f50a61fb 2488 if ($options->buttonname) {
4b72f9eb
AW
2489 $buttonname = ' name="' . $options->buttonname . '"';
2490 } else {
2491 $buttonname = '';
2492 }
bb496de7
DC
2493 $html = <<<EOD
2494<div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2495$icon_progress
2496</div>
2497<div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2498 <div>
c81f3328 2499 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
fa7f2a45 2500 <span> $maxsize </span>
bb496de7
DC
2501 </div>
2502EOD;
2503 if ($options->env != 'url') {
2504 $html .= <<<EOD
50597880 2505 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
a9352f1f 2506 <div class="filepicker-filename">
08a6a19d 2507 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
0f94289c 2508 <div class="dndupload-progressbars"></div>
a9352f1f 2509 </div>
08a6a19d 2510 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
f08fac7c 2511 </div>
bb496de7
DC
2512EOD;
2513 }
2514 $html .= '</div>';
2515 return $html;
2516 }
d9c8f425 2517
2518 /**
7a3c215b 2519 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
d9c8f425 2520 *
2521 * @param string $cmid the course_module id.
2522 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2523 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2524 */
2525 public function update_module_button($cmid, $modulename) {
2526 global $CFG;
b0c6dc1c 2527 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
d9c8f425 2528 $modulename = get_string('modulename', $modulename);
2529 $string = get_string('updatethis', '', $modulename);
3ba60ee1
PS
2530 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2531 return $this->single_button($url, $string);
d9c8f425 2532 } else {
2533 return '';
2534 }
2535 }
2536
2537 /**
7a3c215b
SH
2538 * Returns HTML to display a "Turn editing on/off" button in a form.
2539 *
d9c8f425 2540 * @param moodle_url $url The URL + params to send through when clicking the button
2541 * @return string HTML the button
2542 */
2543 public function edit_button(moodle_url $url) {
3362dfdc
EL
2544
2545 $url->param('sesskey', sesskey());
2546 if ($this->page->user_is_editing()) {
2547 $url->param('edit', 'off');
2548 $editstring = get_string('turneditingoff');
d9c8f425 2549 } else {
3362dfdc
EL
2550 $url->param('edit', 'on');
2551 $editstring = get_string('turneditingon');
d9c8f425 2552 }
2553
3362dfdc 2554 return $this->single_button($url, $editstring);
d9c8f425 2555 }
2556
d9c8f425 2557 /**
7a3c215b 2558 * Returns HTML to display a simple button to close a window
d9c8f425 2559 *
d9c8f425 2560 * @param string $text The lang string for the button's label (already output from get_string())
3ba60ee1 2561 * @return string html fragment
d9c8f425 2562 */
7a5c78e0 2563 public function close_window_button($text='') {
d9c8f425 2564 if (empty($text)) {
2565 $text = get_string('closewindow');
2566 }
a6855934
PS
2567 $button = new single_button(new moodle_url('#'), $text, 'get');
2568 $button->add_action(new component_action('click', 'close_window'));
3ba60ee1
PS
2569
2570 return $this->container($this->render($button), 'closewindow');
d9c8f425 2571 }
2572
d9c8f425 2573 /**
2574 * Output an error message. By default wraps the error message in <span class="error">.
2575 * If the error message is blank, nothing is output.
7a3c215b 2576 *
d9c8f425 2577 * @param string $message the error message.
2578 * @return string the HTML to output.
2579 */
2580 public function error_text($message) {
2581 if (empty($message)) {
2582 return '';
2583 }
3246648b 2584 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
26acc814 2585 return html_writer::tag('span', $message, array('class' => 'error'));
d9c8f425 2586 }
2587
2588 /**
2589 * Do not call this function directly.
2590 *
f8129210 2591 * To terminate the current script with a fatal error, call the {@link print_error}
d9c8f425 2592 * function, or throw an exception. Doing either of those things will then call this
2593 * function to display the error, before terminating the execution.
2594 *
2595 * @param string $message The message to output
2596 * @param string $moreinfourl URL where more info can be found about the error
2597 * @param string $link Link for the Continue button
2598 * @param array $backtrace The execution backtrace
2599 * @param string $debuginfo Debugging information
d9c8f425 2600 * @return string the HTML to output.
2601 */
83267ec0 2602 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
6bd8d7e7 2603 global $CFG;
d9c8f425 2604
2605 $output = '';
6f8f4d83 2606 $obbuffer = '';
e57c283d 2607
d9c8f425 2608 if ($this->has_started()) {
50764d37
PS
2609 // we can not always recover properly here, we have problems with output buffering,
2610 // html tables, etc.
d9c8f425 2611 $output .= $this->opencontainers->pop_all_but_last();
50764d37 2612
d9c8f425 2613 } else {
50764d37
PS
2614 // It is really bad if library code throws exception when output buffering is on,
2615 // because the buffered text would be printed before our start of page.
2616 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
6bd8d7e7 2617 error_reporting(0); // disable notices from gzip compression, etc.
50764d37 2618 while (ob_get_level() > 0) {
2cadd443
PS
2619 $buff = ob_get_clean();
2620 if ($buff === false) {
2621 break;
2622 }
2623 $obbuffer .= $buff;
50764d37 2624 }
6bd8d7e7 2625 error_reporting($CFG->debug);
6f8f4d83 2626
f22f1caf
PS
2627 // Output not yet started.
2628 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2629 if (empty($_SERVER['HTTP_RANGE'])) {
2630 @header($protocol . ' 404 Not Found');
2631 } else {
2632 // Must stop byteserving attempts somehow,
2633 // this is weird but Chrome PDF viewer can be stopped only with 407!
2634 @header($protocol . ' 407 Proxy Authentication Required');
85309744 2635 }
f22f1caf 2636
eb5bdb35 2637 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
7fde1e4b 2638 $this->page->set_url('/'); // no url
191b267b 2639 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
dcfb9b78 2640 $this->page->set_title(get_string('error'));
8093188f 2641 $this->page->set_heading($this->page->course->fullname);
d9c8f425 2642 $output .= $this->header();
2643 }
2644
2645 $message = '<p class="errormessage">' . $message . '</p>'.
2646 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2647 get_string('moreinformation') . '</a></p>';
1ad8143a
PS
2648 if (empty($CFG->rolesactive)) {
2649 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2650 //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.
2651 }
4c2892c6 2652 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
d9c8f425 2653
96f81ea3 2654 if ($CFG->debugdeveloper) {
6f8f4d83 2655 if (!empty($debuginfo)) {
c5d18164
PS
2656 $debuginfo = s($debuginfo); // removes all nasty JS
2657 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2658 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
6f8f4d83
PS
2659 }
2660 if (!empty($backtrace)) {
2661 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2662 }
2663 if ($obbuffer !== '' ) {
2664 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2665 }
d9c8f425 2666 }
2667
3efe6bbb
PS
2668 if (empty($CFG->rolesactive)) {
2669 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2670 } else if (!empty($link)) {
d9c8f425 2671 $output .= $this->continue_button($link);
2672 }
2673
2674 $output .= $this->footer();
2675
2676 // Padding to encourage IE to display our error page, rather than its own.
2677 $output .= str_repeat(' ', 512);
2678
2679 return $output;
2680 }
2681
2682 /**
2683 * Output a notification (that is, a status message about something that has
2684 * just happened).
2685 *
2686 * @param string $message the message to print out
2687 * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
2688 * @return string the HTML to output.
2689 */
2690 public function notification($message, $classes = 'notifyproblem') {
26acc814 2691 return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
d9c8f425 2692 }
2693
2694 /**
7a3c215b 2695 * Returns HTML to display a continue button that goes to a particular URL.
d9c8f425 2696 *
3ba60ee1 2697 * @param string|moodle_url $url The url the button goes to.
d9c8f425 2698 * @return string the HTML to output.
2699 */
3ba60ee1
PS
2700 public function continue_button($url) {
2701 if (!($url instanceof moodle_url)) {
2702 $url = new moodle_url($url);
d9c8f425 2703 }
3ba60ee1
PS
2704 $button = new single_button($url, get_string('continue'), 'get');
2705 $button->class = 'continuebutton';
d9c8f425 2706
3ba60ee1 2707 return $this->render($button);
d9c8f425 2708 }
2709
2710 /**
7a3c215b 2711 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
d9c8f425 2712 *
2fada290
MG
2713 * Theme developers: DO NOT OVERRIDE! Please override function
2714 * {@link core_renderer::render_paging_bar()} instead.
2715 *
71c03ac1 2716 * @param int $totalcount The total number of entries available to be paged through
929d7a83
PS
2717 * @param int $page The page you are currently viewing
2718 * @param int $perpage The number of entries that should be shown per page
2719 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2720 * @param string $pagevar name of page parameter that holds the page number
d9c8f425 2721 * @return string the HTML to output.
2722 */
929d7a83
PS
2723 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2724 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2725 return $this->render($pb);
2726 }
2727
2728 /**
2729 * Internal implementation of paging bar rendering.
7a3c215b 2730 *
929d7a83
PS
2731 * @param paging_bar $pagingbar
2732 * @return string
2733 */
2734 protected function render_paging_bar(paging_bar $pagingbar) {
d9c8f425 2735 $output = '';
2736 $pagingbar = clone($pagingbar);
34059565 2737 $pagingbar->prepare($this, $this->page, $this->target);
d9c8f425 2738
2739 if ($pagingbar->totalcount > $pagingbar->perpage) {
2740 $output .= get_string('page') . ':';
2741
2742 if (!empty($pagingbar->previouslink)) {
56ddb719 2743 $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
d9c8f425 2744 }
2745
2746 if (!empty($pagingbar->firstlink)) {
56ddb719 2747 $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
d9c8f425 2748 }
2749
2750 foreach ($pagingbar->pagelinks as $link) {
56ddb719 2751 $output .= "&#160;&#160;$link";
d9c8f425 2752 }
2753
2754 if (!empty($pagingbar->lastlink)) {
56ddb719 2755 $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
d9c8f425 2756 }
2757
2758 if (!empty($pagingbar->nextlink)) {
56ddb719 2759 $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
d9c8f425 2760 }
2761 }
2762
26acc814 2763 return html_writer::tag('div', $output, array('class' => 'paging'));
d9c8f425 2764 }
2765
d9c8f425 2766 /**
2767 * Output the place a skip link goes to.
7a3c215b 2768 *
d9c8f425 2769 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
2770 * @return string the HTML to output.
2771 */
fe213365 2772 public function skip_link_target($id = null) {
26acc814 2773 return html_writer::tag('span', '', array('id' => $id));
d9c8f425 2774 }
2775
2776 /**
2777 * Outputs a heading
7a3c215b 2778 *
d9c8f425 2779 * @param string $text The text of the heading
2780 * @param int $level The level of importance of the heading. Defaulting to 2
699e2fd0 2781 * @param string $classes A space-separated list of CSS classes. Defaulting to null
d9c8f425 2782 * @param string $id An optional ID
2783 * @return string the HTML to output.
2784 */
699e2fd0 2785 public function heading($text, $level = 2, $classes = null, $id = null) {
d9c8f425 2786 $level = (integer) $level;
2787 if ($level < 1 or $level > 6) {
2788 throw new coding_exception('Heading level must be an integer between 1 and 6.');
2789 }
26acc814 2790 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
d9c8f425 2791 }
2792
2793 /**
2794 * Outputs a box.
7a3c215b 2795 *
d9c8f425 2796 * @param string $contents The contents of the box
2797 * @param string $classes A space-separated list of CSS classes
2798 * @param string $id An optional ID
3e76c7fa 2799 * @param array $attributes An array of other attributes to give the box.
d9c8f425 2800 * @return string the HTML to output.
2801 */
3e76c7fa
SH
2802 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
2803 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
d9c8f425 2804 }
2805
2806 /**
3d3fae72 2807 * Outputs the opening section of a box.
7a3c215b 2808 *
d9c8f425 2809 * @param string $classes A space-separated list of CSS classes
2810 * @param string $id An optional ID
3e76c7fa 2811 * @param array $attributes An array of other attributes to give the box.
d9c8f425 2812 * @return string the HTML to output.
2813 */
3e76c7fa 2814 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
5d0c95a5 2815 $this->opencontainers->push('box', html_writer::end_tag('div'));
3e76c7fa
SH
2816 $attributes['id'] = $id;
2817 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
2818 return html_writer::start_tag('div', $attributes);
d9c8f425 2819 }
2820
2821 /**
2822 * Outputs the closing section of a box.
7a3c215b 2823 *
d9c8f425 2824 * @return string the HTML to output.
2825 */
2826 public function box_end() {
2827 return $this->opencontainers->pop('box');
2828 }
2829
2830 /**
2831 * Outputs a container.
7a3c215b 2832 *
d9c8f425 2833 * @param string $contents The contents of the box
2834 * @param string $classes A space-separated list of CSS classes
2835 * @param string $id An optional ID
2836 * @return string the HTML to output.
2837 */
fe213365 2838 public function container($contents, $classes = null, $id = null) {
d9c8f425 2839 return $this->container_start($classes, $id) . $contents . $this->container_end();
2840 }
2841
2842 /**
2843 * Outputs the opening section of a container.
7a3c215b 2844 *
d9c8f425 2845 * @param string $classes A space-separated list of CSS classes
2846 * @param string $id An optional ID
2847 * @return string the HTML to output.
2848 */
fe213365 2849 public function container_start($classes = null, $id = null) {
5d0c95a5
PS
2850 $this->opencontainers->push('container', html_writer::end_tag('div'));
2851 return html_writer::start_tag('div', array('id' => $id,
78946b9b 2852 'class' => renderer_base::prepare_classes($classes)));
d9c8f425 2853 }
2854
2855 /**
2856 * Outputs the closing section of a container.
7a3c215b 2857 *
d9c8f425 2858 * @return string the HTML to output.
2859 */
2860 public function container_end() {
2861 return $this->opencontainers->pop('container');
2862 }
7d2a0492 2863
3406acde 2864 /**
7d2a0492 2865 * Make nested HTML lists out of the items
2866 *
2867 * The resulting list will look something like this:
2868 *
2869 * <pre>
2870 * <<ul>>
2871 * <<li>><div class='tree_item parent'>(item contents)</div>
2872 * <<ul>
2873 * <<li>><div class='tree_item'>(item contents)</div><</li>>
2874 * <</ul>>
2875 * <</li>>
2876 * <</ul>>
2877 * </pre>
2878 *
7a3c215b
SH
2879 * @param array $items
2880 * @param array $attrs html attributes passed to the top ofs the list
7d2a0492 2881 * @return string HTML
2882 */
7a3c215b 2883 public function tree_block_contents($items, $attrs = array()) {
7d2a0492 2884 // exit if empty, we don't want an empty ul element
2885 if (empty($items)) {
2886 return '';
2887 }
2888 // array of nested li elements
2889 $lis = array();
2890 foreach ($items as $item) {
2891 // this applies to the li item which contains all child lists too
2892 $content = $item->content($this);
2893 $liclasses = array($item->get_css_type());
3406acde 2894 if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
7d2a0492 2895 $liclasses[] = 'collapsed';
2896 }
2897 if ($item->isactive === true) {
2898 $liclasses[] = 'current_branch';
2899 }
2900 $liattr = array('class'=>join(' ',$liclasses));
2901 // class attribute on the div item which only contains the item content
2902 $divclasses = array('tree_item');
3406acde 2903 if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
7d2a0492 2904 $divclasses[] = 'branch';
2905 } else {
2906 $divclasses[] = 'leaf';
2907 }
2908 if (!empty($item->classes) && count($item->classes)>0) {
2909 $divclasses[] = join(' ', $item->classes);
2910 }
2911 $divattr = array('class'=>join(' ', $divclasses));
2912 if (!empty($item->id)) {
2913 $divattr['id'] = $item->id;
2914 }
26acc814 2915 $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
7d2a0492 2916 if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
26acc814 2917 $content = html_writer::empty_tag('hr') . $content;
7d2a0492 2918 }
26acc814 2919 $content = html_writer::tag('li', $content, $liattr);
7d2a0492 2920 $lis[] = $content;
2921 }
26acc814 2922 return html_writer::tag('ul', implode("\n", $lis), $attrs);
7d2a0492 2923 }
2924
6da0e4cf
JC
2925 /**
2926 * Construct a user menu, returning HTML that can be echoed out by a
2927 * layout file.
2928 *
2929 * @param stdClass $user A user object, usually $USER.
2930 * @param bool $withlinks true if a dropdown should be built.
2931 * @return string HTML fragment.
2932 */
854a647e 2933 public function user_menu($user = null, $withlinks = null) {
6da0e4cf 2934 global $USER, $CFG;
854a647e 2935 require_once($CFG->dirroot . '/user/lib.php');
6da0e4cf
JC
2936
2937 if (is_null($user)) {
2938 $user = $USER;
2939 }
2940
2941 // Note: this behaviour is intended to match that of core_renderer::login_info,
2942 // but should not be considered to be good practice; layout options are
2943 // intended to be theme-specific. Please don't copy this snippet anywhere else.
2944 if (is_null($withlinks)) {
2945 $withlinks = empty($this->page->layout_options['nologinlinks']);
2946 }
2947
854a647e
JC
2948 // Add a class for when $withlinks is false.
2949 $usermenuclasses = 'usermenu';
2950 if (!$withlinks) {
2951 $usermenuclasses .= ' withoutlinks';
2952 }
2953
6da0e4cf
JC
2954 $returnstr = "";
2955
2956 // If during initial install, return the empty return string.
2957 if (during_initial_install()) {
2958 return $returnstr;
2959 }
2960
0e61dba3 2961 $loginpage = $this->is_login_page();
6da0e4cf
JC
2962 $loginurl = get_login_url();
2963 // If not logged in, show the typical not-logged-in string.
2964 if (!isloggedin()) {
2965 $returnstr = get_string('loggedinnot', 'moodle');
2966 if (!$loginpage) {
2967 $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
2968 }
854a647e
JC
2969 return html_writer::div(
2970 html_writer::span(
2971 $returnstr,
2972 'login'
2973 ),
2974 $usermenuclasses
6da0e4cf 2975 );
854a647e 2976
6da0e4cf
JC
2977 }
2978
2979 // If logged in as a guest user, show a string to that effect.
2980 if (isguestuser()) {
2981 $returnstr = get_string('loggedinasguest');
2982 if (!$loginpage && $withlinks) {
2983 $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
2984 }
854a647e
JC
2985
2986 return html_writer::div(
2987 html_writer::span(
2988 $returnstr,
2989 'login'
2990 ),
2991 $usermenuclasses
6da0e4cf
JC
2992 );
2993 }
2994
2995 // Get some navigation opts.
6da0e4cf
JC
2996 $opts = user_get_user_navigation_info($user, $this->page, $this->page->course);
2997
2998 $avatarclasses = "avatars";
2999 $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3000 $usertextcontents = $opts->metadata['userfullname'];
3001
3002 // Other user.
3003 if (!empty($opts->metadata['asotheruser'])) {
3004 $avatarcontents .= html_writer::span(
3005 $opts->metadata['realuseravatar'],
3006 'avatar realuser'
3007 );
3008 $usertextcontents = $opts->metadata['realuserfullname'];
3009 $usertextcontents .= html_writer::tag(
3010 'span',
3011 get_string(
3012 'loggedinas',
3013 'moodle',
3014 html_writer::span(
3015 $opts->metadata['userfullname'],
3016 'value'
3017 )
3018 ),
3019 array('class' => 'meta viewingas')
3020 );
3021 }
3022
3023 // Role.
3024 if (!empty($opts->metadata['asotherrole'])) {
3025 $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3026 $usertextcontents .= html_writer::span(
3027 $opts->metadata['rolename'],
3028 'meta role role-' . $role
3029 );
3030 }
3031
3032 // User login failures.
3033 if (!empty($opts->metadata['userloginfail'])) {
3034 $usertextcontents .= html_writer::span(
3035 $opts->metadata['userloginfail'],
3036 'meta loginfailures'
3037 );
3038 }
3039
3040 // MNet.
3041 if (!empty($opts->metadata['asmnetuser'])) {
3042 $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3043 $usertextcontents .= html_writer::span(
3044 $opts->metadata['mnetidprovidername'],
3045 'meta mnet mnet-' . $mnet
3046 );
3047 }
3048
3049 $returnstr .= html_writer::span(
854a647e
JC
3050 html_writer::span($usertextcontents, 'usertext') .
3051 html_writer::span($avatarcontents, $avatarclasses),
6da0e4cf
JC
3052 'userbutton'
3053 );
3054
6da0e4cf
JC
3055 // Create a divider (well, a filler).
3056 $divider = new action_menu_filler();
3057 $divider->primary = false;
3058
3059 $am = new action_menu();
3060 $am->initialise_js($this->page);
f89a85f8
JC
3061 $am->set_menu_trigger(
3062 $returnstr
3063 );
6da0e4cf 3064 $am->set_alignment(action_menu::TR, action_menu::BR);
84d5a89c 3065 $am->set_nowrap_on_items();
6da0e4cf
JC
3066 if ($withlinks) {
3067 $navitemcount = count($opts->navitems);
3068 $idx = 0;
3069 foreach ($opts->navitems as $key => $value) {
22893d6f
JC
3070
3071 switch ($value->itemtype) {
3072 case 'divider':
3073 // If the nav item is a divider, add one and skip link processing.