MDL-51603 dataformat: Imported 3rd party lib spout
[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
9bdcf579
DW
69 /**
70 * @var Mustache_Engine $mustache The mustache template compiler
71 */
72 private $mustache;
73
9bdcf579
DW
74 /**
75 * Return an instance of the mustache class.
76 *
77 * @since 2.9
78 * @return Mustache_Engine
79 */
80 protected function get_mustache() {
81 global $CFG;
82
83 if ($this->mustache === null) {
84 require_once($CFG->dirroot . '/lib/mustache/src/Mustache/Autoloader.php');
85 Mustache_Autoloader::register();
86
87 $themename = $this->page->theme->name;
88 $themerev = theme_get_revision();
9bdcf579 89
fcc383db
DW
90 $cachedir = make_localcache_directory("mustache/$themerev/$themename");
91
92 $loader = new \core\output\mustache_filesystem_loader();
9bdcf579 93 $stringhelper = new \core\output\mustache_string_helper();
0b4bff8c 94 $quotehelper = new \core\output\mustache_quote_helper();
9bdcf579
DW
95 $jshelper = new \core\output\mustache_javascript_helper($this->page->requires);
96 $pixhelper = new \core\output\mustache_pix_helper($this);
97
98 // We only expose the variables that are exposed to JS templates.
99 $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
100
101 $helpers = array('config' => $safeconfig,
102 'str' => array($stringhelper, 'str'),
0b4bff8c 103 'quote' => array($quotehelper, 'quote'),
9bdcf579
DW
104 'js' => array($jshelper, 'help'),
105 'pix' => array($pixhelper, 'pix'));
106
107 $this->mustache = new Mustache_Engine(array(
108 'cache' => $cachedir,
109 'escape' => 's',
110 'loader' => $loader,
85fa6a93
DW
111 'helpers' => $helpers,
112 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS]));
9bdcf579
DW
113
114 }
115
116 return $this->mustache;
117 }
118
119
d9c8f425 120 /**
121 * Constructor
7a3c215b 122 *
3d3fae72 123 * The constructor takes two arguments. The first is the page that the renderer
7a3c215b
SH
124 * has been created to assist with, and the second is the target.
125 * The target is an additional identifier that can be used to load different
126 * renderers for different options.
127 *
d9c8f425 128 * @param moodle_page $page the page we are doing output for.
c927e35c 129 * @param string $target one of rendering target constants
d9c8f425 130 */
c927e35c 131 public function __construct(moodle_page $page, $target) {
d9c8f425 132 $this->opencontainers = $page->opencontainers;
133 $this->page = $page;
c927e35c 134 $this->target = $target;
d9c8f425 135 }
136
9bdcf579
DW
137 /**
138 * Renders a template by name with the given context.
139 *
140 * The provided data needs to be array/stdClass made up of only simple types.
141 * Simple types are array,stdClass,bool,int,float,string
142 *
143 * @since 2.9
144 * @param array|stdClass $context Context containing data for the template.
145 * @return string|boolean
146 */
147 public function render_from_template($templatename, $context) {
148 static $templatecache = array();
149 $mustache = $this->get_mustache();
150
151 // Provide 1 random value that will not change within a template
152 // but will be different from template to template. This is useful for
153 // e.g. aria attributes that only work with id attributes and must be
154 // unique in a page.
155 $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
156 if (isset($templatecache[$templatename])) {
157 $template = $templatecache[$templatename];
158 } else {
159 try {
160 $template = $mustache->loadTemplate($templatename);
161 $templatecache[$templatename] = $template;
162 } catch (Mustache_Exception_UnknownTemplateException $e) {
163 throw new moodle_exception('Unknown template: ' . $templatename);
164 }
165 }
166 return trim($template->render($context));
167 }
168
169
d9c8f425 170 /**
5d0c95a5 171 * Returns rendered widget.
7a3c215b
SH
172 *
173 * The provided widget needs to be an object that extends the renderable
174 * interface.
3d3fae72 175 * If will then be rendered by a method based upon the classname for the widget.
7a3c215b
SH
176 * For instance a widget of class `crazywidget` will be rendered by a protected
177 * render_crazywidget method of this renderer.
178 *
996b1e0c 179 * @param renderable $widget instance with renderable interface
5d0c95a5 180 * @return string
d9c8f425 181 */
5d0c95a5 182 public function render(renderable $widget) {
d2bba1ee
DW
183 $classname = get_class($widget);
184 // Strip namespaces.
185 $classname = preg_replace('/^.*\\\/', '', $classname);
186 // Remove _renderable suffixes
187 $classname = preg_replace('/_renderable$/', '', $classname);
188
189 $rendermethod = 'render_'.$classname;
5d0c95a5
PS
190 if (method_exists($this, $rendermethod)) {
191 return $this->$rendermethod($widget);
192 }
193 throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
d9c8f425 194 }
195
196 /**
7a3c215b
SH
197 * Adds a JS action for the element with the provided id.
198 *
199 * This method adds a JS event for the provided component action to the page
200 * and then returns the id that the event has been attached to.
f8129210 201 * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
7a3c215b 202 *
f8129210 203 * @param component_action $action
c80877aa
PS
204 * @param string $id
205 * @return string id of element, either original submitted or random new if not supplied
d9c8f425 206 */
7a3c215b 207 public function add_action_handler(component_action $action, $id = null) {
c80877aa
PS
208 if (!$id) {
209 $id = html_writer::random_id($action->event);
210 }
d96d8f03 211 $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
c80877aa 212 return $id;
d9c8f425 213 }
214
215 /**
7a3c215b
SH
216 * Returns true is output has already started, and false if not.
217 *
5d0c95a5 218 * @return boolean true if the header has been printed.
d9c8f425 219 */
5d0c95a5
PS
220 public function has_started() {
221 return $this->page->state >= moodle_page::STATE_IN_BODY;
d9c8f425 222 }
223
224 /**
225 * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
7a3c215b 226 *
d9c8f425 227 * @param mixed $classes Space-separated string or array of classes
228 * @return string HTML class attribute value
229 */
230 public static function prepare_classes($classes) {
231 if (is_array($classes)) {
232 return implode(' ', array_unique($classes));
233 }
234 return $classes;
235 }
236
d9c8f425 237 /**
897e902b 238 * Return the moodle_url for an image.
7a3c215b 239 *
897e902b
PS
240 * The exact image location and extension is determined
241 * automatically by searching for gif|png|jpg|jpeg, please
242 * note there can not be diferent images with the different
243 * extension. The imagename is for historical reasons
244 * a relative path name, it may be changed later for core
245 * images. It is recommended to not use subdirectories
246 * in plugin and theme pix directories.
d9c8f425 247 *
897e902b
PS
248 * There are three types of images:
249 * 1/ theme images - stored in theme/mytheme/pix/,
250 * use component 'theme'
251 * 2/ core images - stored in /pix/,
252 * overridden via theme/mytheme/pix_core/
253 * 3/ plugin images - stored in mod/mymodule/pix,
254 * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
255 * example: pix_url('comment', 'mod_glossary')
256 *
257 * @param string $imagename the pathname of the image
258 * @param string $component full plugin name (aka component) or 'theme'
78946b9b 259 * @return moodle_url
d9c8f425 260 */
c927e35c 261 public function pix_url($imagename, $component = 'moodle') {
c39e5ba2 262 return $this->page->theme->pix_url($imagename, $component);
d9c8f425 263 }
d9c8f425 264}
265
c927e35c 266
75590935
PS
267/**
268 * Basis for all plugin renderers.
269 *
f8129210
SH
270 * @copyright Petr Skoda (skodak)
271 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
272 * @since Moodle 2.0
273 * @package core
76be40cc 274 * @category output
75590935
PS
275 */
276class plugin_renderer_base extends renderer_base {
7a3c215b 277
75590935 278 /**
3d3fae72
SH
279 * @var renderer_base|core_renderer A reference to the current renderer.
280 * The renderer provided here will be determined by the page but will in 90%
f8129210 281 * of cases by the {@link core_renderer}
75590935
PS
282 */
283 protected $output;
284
285 /**
996b1e0c 286 * Constructor method, calls the parent constructor
7a3c215b 287 *
75590935 288 * @param moodle_page $page
c927e35c 289 * @param string $target one of rendering target constants
75590935 290 */
c927e35c 291 public function __construct(moodle_page $page, $target) {
166ac0a3
SH
292 if (empty($target) && $page->pagelayout === 'maintenance') {
293 // If the page is using the maintenance layout then we're going to force the target to maintenance.
294 // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
295 // unavailable for this page layout.
296 $target = RENDERER_TARGET_MAINTENANCE;
297 }
c927e35c
PS
298 $this->output = $page->get_renderer('core', null, $target);
299 parent::__construct($page, $target);
75590935 300 }
ff5265c6 301
5d0c95a5 302 /**
7a3c215b
SH
303 * Renders the provided widget and returns the HTML to display it.
304 *
71c03ac1 305 * @param renderable $widget instance with renderable interface
5d0c95a5
PS
306 * @return string
307 */
308 public function render(renderable $widget) {
d2bba1ee
DW
309 $classname = get_class($widget);
310 // Strip namespaces.
311 $classname = preg_replace('/^.*\\\/', '', $classname);
ebdcb292
SH
312 // Keep a copy at this point, we may need to look for a deprecated method.
313 $deprecatedmethod = 'render_'.$classname;
d2bba1ee 314 // Remove _renderable suffixes
ebdcb292 315 $classname = preg_replace('/_renderable$/', '', $classname);
d2bba1ee
DW
316
317 $rendermethod = 'render_'.$classname;
5d0c95a5
PS
318 if (method_exists($this, $rendermethod)) {
319 return $this->$rendermethod($widget);
320 }
ebdcb292
SH
321 if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
322 // This is exactly where we don't want to be.
323 // If you have arrived here you have a renderable component within your plugin that has the name
324 // blah_renderable, and you have a render method render_blah_renderable on your plugin.
325 // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
326 // and the _renderable suffix now gets removed when looking for a render method.
327 // You need to change your renderers render_blah_renderable to render_blah.
328 // Until you do this it will not be possible for a theme to override the renderer to override your method.
329 // Please do it ASAP.
330 static $debugged = array();
331 if (!isset($debugged[$deprecatedmethod])) {
332 debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
333 $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
334 $debugged[$deprecatedmethod] = true;
335 }
336 return $this->$deprecatedmethod($widget);
337 }
5d0c95a5 338 // pass to core renderer if method not found here
469bf7a4 339 return $this->output->render($widget);
5d0c95a5
PS
340 }
341
ff5265c6
PS
342 /**
343 * Magic method used to pass calls otherwise meant for the standard renderer
996b1e0c 344 * to it to ensure we don't go causing unnecessary grief.
ff5265c6
PS
345 *
346 * @param string $method
347 * @param array $arguments
348 * @return mixed
349 */
350 public function __call($method, $arguments) {
37b5b18e 351 if (method_exists('renderer_base', $method)) {
fede0be5 352 throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
37b5b18e 353 }
ff5265c6
PS
354 if (method_exists($this->output, $method)) {
355 return call_user_func_array(array($this->output, $method), $arguments);
356 } else {
fede0be5 357 throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
ff5265c6
PS
358 }
359 }
75590935 360}
d9c8f425 361
c927e35c 362
d9c8f425 363/**
78946b9b 364 * The standard implementation of the core_renderer interface.
d9c8f425 365 *
366 * @copyright 2009 Tim Hunt
7a3c215b
SH
367 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
368 * @since Moodle 2.0
f8129210 369 * @package core
76be40cc 370 * @category output
d9c8f425 371 */
78946b9b 372class core_renderer extends renderer_base {
72009b87
PS
373 /**
374 * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
375 * in layout files instead.
72009b87 376 * @deprecated
f8129210 377 * @var string used in {@link core_renderer::header()}.
72009b87 378 */
d9c8f425 379 const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
7a3c215b
SH
380
381 /**
f8129210
SH
382 * @var string Used to pass information from {@link core_renderer::doctype()} to
383 * {@link core_renderer::standard_head_html()}.
7a3c215b 384 */
d9c8f425 385 protected $contenttype;
7a3c215b
SH
386
387 /**
f8129210
SH
388 * @var string Used by {@link core_renderer::redirect_message()} method to communicate
389 * with {@link core_renderer::header()}.
7a3c215b 390 */
d9c8f425 391 protected $metarefreshtag = '';
7a3c215b
SH
392
393 /**
76be40cc 394 * @var string Unique token for the closing HTML
7a3c215b 395 */
72009b87 396 protected $unique_end_html_token;
7a3c215b
SH
397
398 /**
76be40cc 399 * @var string Unique token for performance information
7a3c215b 400 */
72009b87 401 protected $unique_performance_info_token;
7a3c215b
SH
402
403 /**
76be40cc 404 * @var string Unique token for the main content.
7a3c215b 405 */
72009b87
PS
406 protected $unique_main_content_token;
407
408 /**
409 * Constructor
7a3c215b 410 *
72009b87
PS
411 * @param moodle_page $page the page we are doing output for.
412 * @param string $target one of rendering target constants
413 */
414 public function __construct(moodle_page $page, $target) {
415 $this->opencontainers = $page->opencontainers;
416 $this->page = $page;
417 $this->target = $target;
418
419 $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
420 $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
421 $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
422 }
d9c8f425 423
424 /**
425 * Get the DOCTYPE declaration that should be used with this page. Designed to
426 * be called in theme layout.php files.
7a3c215b 427 *
13725b37 428 * @return string the DOCTYPE declaration that should be used.
d9c8f425 429 */
430 public function doctype() {
13725b37
PS
431 if ($this->page->theme->doctype === 'html5') {
432 $this->contenttype = 'text/html; charset=utf-8';
433 return "<!DOCTYPE html>\n";
d9c8f425 434
13725b37 435 } else if ($this->page->theme->doctype === 'xhtml5') {
d9c8f425 436 $this->contenttype = 'application/xhtml+xml; charset=utf-8';
13725b37 437 return "<!DOCTYPE html>\n";
d9c8f425 438
439 } else {
13725b37
PS
440 // legacy xhtml 1.0
441 $this->contenttype = 'text/html; charset=utf-8';
442 return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
d9c8f425 443 }
d9c8f425 444 }
445
446 /**
447 * The attributes that should be added to the <html> tag. Designed to
448 * be called in theme layout.php files.
7a3c215b 449 *
d9c8f425 450 * @return string HTML fragment.
451 */
452 public function htmlattributes() {
13725b37
PS
453 $return = get_html_lang(true);
454 if ($this->page->theme->doctype !== 'html5') {
455 $return .= ' xmlns="http://www.w3.org/1999/xhtml"';
456 }
457 return $return;
d9c8f425 458 }
459
460 /**
461 * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
462 * that should be included in the <head> tag. Designed to be called in theme
463 * layout.php files.
7a3c215b 464 *
d9c8f425 465 * @return string HTML fragment.
466 */
467 public function standard_head_html() {
b5bbeaf0 468 global $CFG, $SESSION;
59849f79
AN
469
470 // Before we output any content, we need to ensure that certain
471 // page components are set up.
472
473 // Blocks must be set up early as they may require javascript which
474 // has to be included in the page header before output is created.
475 foreach ($this->page->blocks->get_regions() as $region) {
476 $this->page->blocks->ensure_content_created($region, $this);
477 }
478
d9c8f425 479 $output = '';
2ab797c9
BH
480
481 // Allow a url_rewrite plugin to setup any dynamic head content.
482 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
483 $class = $CFG->urlrewriteclass;
484 $output .= $class::html_head_setup();
485 }
486
d9c8f425 487 $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
488 $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
f8129210 489 // This is only set by the {@link redirect()} method
d9c8f425 490 $output .= $this->metarefreshtag;
491
492 // Check if a periodic refresh delay has been set and make sure we arn't
493 // already meta refreshing
494 if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
495 $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
496 }
497
fcd2cbaf
PS
498 // flow player embedding support
499 $this->page->requires->js_function_call('M.util.load_flowplayer');
500
238b8bc9 501 // Set up help link popups for all links with the helptooltip class
afe3566c
ARN
502 $this->page->requires->js_init_call('M.util.help_popups.setup');
503
238b8bc9
ARN
504 // Setup help icon overlays.
505 $this->page->requires->yui_module('moodle-core-popuphelp', 'M.core.init_popuphelp');
506 $this->page->requires->strings_for_js(array(
507 'morehelp',
508 'loadinghelp',
509 ), 'moodle');
510
7d2a0492 511 $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
d9c8f425 512
513 $focus = $this->page->focuscontrol;
514 if (!empty($focus)) {
515 if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
516 // This is a horrifically bad way to handle focus but it is passed in
517 // through messy formslib::moodleform
7d2a0492 518 $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
d9c8f425 519 } else if (strpos($focus, '.')!==false) {
520 // Old style of focus, bad way to do it
521 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);
522 $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
523 } else {
524 // Focus element with given id
7d2a0492 525 $this->page->requires->js_function_call('focuscontrol', array($focus));
d9c8f425 526 }
527 }
528
78946b9b
PS
529 // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
530 // any other custom CSS can not be overridden via themes and is highly discouraged
efaa4c08 531 $urls = $this->page->theme->css_urls($this->page);
78946b9b 532 foreach ($urls as $url) {
c0467479 533 $this->page->requires->css_theme($url);
78946b9b
PS
534 }
535
04c01408 536 // Get the theme javascript head and footer
d7656956
ARN
537 if ($jsurl = $this->page->theme->javascript_url(true)) {
538 $this->page->requires->js($jsurl, true);
539 }
540 if ($jsurl = $this->page->theme->javascript_url(false)) {
541 $this->page->requires->js($jsurl);
542 }
5d0c95a5 543
d9c8f425 544 // Get any HTML from the page_requirements_manager.
945f19f7 545 $output .= $this->page->requires->get_head_code($this->page, $this);
d9c8f425 546
547 // List alternate versions.
548 foreach ($this->page->alternateversions as $type => $alt) {
5d0c95a5 549 $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
d9c8f425 550 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
551 }
8a7703ce 552
90e920c7
SH
553 if (!empty($CFG->additionalhtmlhead)) {
554 $output .= "\n".$CFG->additionalhtmlhead;
555 }
d9c8f425 556
557 return $output;
558 }
559
560 /**
561 * The standard tags (typically skip links) that should be output just inside
562 * the start of the <body> tag. Designed to be called in theme layout.php files.
7a3c215b 563 *
d9c8f425 564 * @return string HTML fragment.
565 */
566 public function standard_top_of_body_html() {
90e920c7
SH
567 global $CFG;
568 $output = $this->page->requires->get_top_of_body_code();
569 if (!empty($CFG->additionalhtmltopofbody)) {
570 $output .= "\n".$CFG->additionalhtmltopofbody;
571 }
48e114a5
PS
572 $output .= $this->maintenance_warning();
573 return $output;
574 }
575
576 /**
577 * Scheduled maintenance warning message.
578 *
579 * Note: This is a nasty hack to display maintenance notice, this should be moved
580 * to some general notification area once we have it.
581 *
582 * @return string
583 */
584 public function maintenance_warning() {
585 global $CFG;
586
587 $output = '';
588 if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
f487a8f8
RT
589 $timeleft = $CFG->maintenance_later - time();
590 // If timeleft less than 30 sec, set the class on block to error to highlight.
591 $errorclass = ($timeleft < 30) ? 'error' : 'warning';
592 $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning');
593 $a = new stdClass();
594 $a->min = (int)($timeleft/60);
595 $a->sec = (int)($timeleft % 60);
596 $output .= get_string('maintenancemodeisscheduled', 'admin', $a) ;
48e114a5 597 $output .= $this->box_end();
f487a8f8
RT
598 $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
599 array(array('timeleftinsec' => $timeleft)));
600 $this->page->requires->strings_for_js(
601 array('maintenancemodeisscheduled', 'sitemaintenance'),
602 'admin');
48e114a5 603 }
90e920c7 604 return $output;
d9c8f425 605 }
606
607 /**
608 * The standard tags (typically performance information and validation links,
609 * if we are in developer debug mode) that should be output in the footer area
610 * of the page. Designed to be called in theme layout.php files.
7a3c215b 611 *
d9c8f425 612 * @return string HTML fragment.
613 */
614 public function standard_footer_html() {
6af80cae 615 global $CFG, $SCRIPT;
d9c8f425 616
ec3ce3a9
PS
617 if (during_initial_install()) {
618 // Debugging info can not work before install is finished,
619 // in any case we do not want any links during installation!
620 return '';
621 }
622
f8129210 623 // This function is normally called from a layout.php file in {@link core_renderer::header()}
d9c8f425 624 // but some of the content won't be known until later, so we return a placeholder
f8129210 625 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
72009b87 626 $output = $this->unique_performance_info_token;
e5824bb9 627 if ($this->page->devicetypeinuse == 'legacy') {
ee8df661
SH
628 // The legacy theme is in use print the notification
629 $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
630 }
37959dd4 631
e5824bb9 632 // Get links to switch device types (only shown for users not on a default device)
37959dd4
AF
633 $output .= $this->theme_switch_links();
634
d9c8f425 635 if (!empty($CFG->debugpageinfo)) {
d4c3f025 636 $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
d9c8f425 637 }
b0c6dc1c 638 if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
6af80cae
EL
639 // Add link to profiling report if necessary
640 if (function_exists('profiling_is_running') && profiling_is_running()) {
641 $txt = get_string('profiledscript', 'admin');
642 $title = get_string('profiledscriptview', 'admin');
4ac92d2a 643 $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
6af80cae
EL
644 $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
645 $output .= '<div class="profilingfooter">' . $link . '</div>';
646 }
2d22f3d9
TH
647 $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
648 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
649 $output .= '<div class="purgecaches">' .
650 html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
ba6c97ee 651 }
d9c8f425 652 if (!empty($CFG->debugvalidators)) {
f0202ae9 653 // 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 654 $output .= '<div class="validators"><ul>
655 <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
656 <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
657 <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>
658 </ul></div>';
659 }
660 return $output;
661 }
662
72009b87
PS
663 /**
664 * Returns standard main content placeholder.
665 * Designed to be called in theme layout.php files.
7a3c215b 666 *
72009b87
PS
667 * @return string HTML fragment.
668 */
669 public function main_content() {
537ba512
SH
670 // This is here because it is the only place we can inject the "main" role over the entire main content area
671 // without requiring all theme's to manually do it, and without creating yet another thing people need to
672 // remember in the theme.
673 // This is an unfortunate hack. DO NO EVER add anything more here.
674 // DO NOT add classes.
675 // DO NOT add an id.
676 return '<div role="main">'.$this->unique_main_content_token.'</div>';
72009b87
PS
677 }
678
d9c8f425 679 /**
680 * The standard tags (typically script tags that are not needed earlier) that
391edc51 681 * should be output after everything else. Designed to be called in theme layout.php files.
7a3c215b 682 *
d9c8f425 683 * @return string HTML fragment.
684 */
685 public function standard_end_of_body_html() {
391edc51
TH
686 global $CFG;
687
f8129210 688 // This function is normally called from a layout.php file in {@link core_renderer::header()}
d9c8f425 689 // but some of the content won't be known until later, so we return a placeholder
f8129210 690 // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
391edc51
TH
691 $output = '';
692 if (!empty($CFG->additionalhtmlfooter)) {
693 $output .= "\n".$CFG->additionalhtmlfooter;
694 }
695 $output .= $this->unique_end_html_token;
696 return $output;
d9c8f425 697 }
698
699 /**
700 * Return the standard string that says whether you are logged in (and switched
701 * roles/logged in as another user).
2d0e682d
MV
702 * @param bool $withlinks if false, then don't include any links in the HTML produced.
703 * If not set, the default is the nologinlinks option from the theme config.php file,
704 * and if that is not set, then links are included.
d9c8f425 705 * @return string HTML fragment.
706 */
2d0e682d 707 public function login_info($withlinks = null) {
8f0fe0b8 708 global $USER, $CFG, $DB, $SESSION;
4bcc5118 709
244a32c6
PS
710 if (during_initial_install()) {
711 return '';
712 }
4bcc5118 713
2d0e682d
MV
714 if (is_null($withlinks)) {
715 $withlinks = empty($this->page->layout_options['nologinlinks']);
716 }
717
244a32c6 718 $course = $this->page->course;
d79d5ac2
PS
719 if (\core\session\manager::is_loggedinas()) {
720 $realuser = \core\session\manager::get_realuser();
244a32c6 721 $fullname = fullname($realuser, true);
2d0e682d 722 if ($withlinks) {
fa84b901
RT
723 $loginastitle = get_string('loginas');
724 $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
725 $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
2d0e682d
MV
726 } else {
727 $realuserinfo = " [$fullname] ";
728 }
244a32c6
PS
729 } else {
730 $realuserinfo = '';
731 }
4bcc5118 732
0e61dba3 733 $loginpage = $this->is_login_page();
244a32c6 734 $loginurl = get_login_url();
4bcc5118 735
244a32c6
PS
736 if (empty($course->id)) {
737 // $course->id is not defined during installation
738 return '';
4f0c2d00 739 } else if (isloggedin()) {
b0c6dc1c 740 $context = context_course::instance($course->id);
4bcc5118 741
244a32c6 742 $fullname = fullname($USER, true);
03d9401e 743 // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
2d0e682d 744 if ($withlinks) {
c7fe9f81
RT
745 $linktitle = get_string('viewprofile');
746 $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
2d0e682d
MV
747 } else {
748 $username = $fullname;
749 }
244a32c6 750 if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
2d0e682d
MV
751 if ($withlinks) {
752 $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
753 } else {
754 $username .= " from {$idprovider->name}";
755 }
244a32c6 756 }
b3df1764 757 if (isguestuser()) {
2778744b 758 $loggedinas = $realuserinfo.get_string('loggedinasguest');
2d0e682d 759 if (!$loginpage && $withlinks) {
2778744b
PS
760 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
761 }
f5c1e621 762 } else if (is_role_switched($course->id)) { // Has switched roles
244a32c6
PS
763 $rolename = '';
764 if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
f2cf0f84 765 $rolename = ': '.role_get_name($role, $context);
244a32c6 766 }
2d0e682d
MV
767 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
768 if ($withlinks) {
aae028d9 769 $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 770 $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
2d0e682d 771 }
244a32c6 772 } else {
2d0e682d
MV
773 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
774 if ($withlinks) {
775 $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
776 }
244a32c6
PS
777 }
778 } else {
2778744b 779 $loggedinas = get_string('loggedinnot', 'moodle');
2d0e682d 780 if (!$loginpage && $withlinks) {
2778744b
PS
781 $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
782 }
244a32c6 783 }
4bcc5118 784
244a32c6 785 $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
4bcc5118 786
244a32c6
PS
787 if (isset($SESSION->justloggedin)) {
788 unset($SESSION->justloggedin);
789 if (!empty($CFG->displayloginfailures)) {
b3df1764 790 if (!isguestuser()) {
52dc1de7
AA
791 // Include this file only when required.
792 require_once($CFG->dirroot . '/user/lib.php');
793 if ($count = user_count_login_failures($USER)) {
2b0c88e2 794 $loggedinas .= '<div class="loginfailures">';
52dc1de7
AA
795 $a = new stdClass();
796 $a->attempts = $count;
797 $loggedinas .= get_string('failedloginattempts', '', $a);
b0c6dc1c 798 if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
46fa0628
DP
799 $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
800 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
244a32c6
PS
801 }
802 $loggedinas .= '</div>';
803 }
804 }
805 }
806 }
4bcc5118 807
244a32c6 808 return $loggedinas;
d9c8f425 809 }
810
0e61dba3
AN
811 /**
812 * Check whether the current page is a login page.
813 *
814 * @since Moodle 2.9
815 * @return bool
816 */
817 protected function is_login_page() {
818 // This is a real bit of a hack, but its a rarety that we need to do something like this.
819 // In fact the login pages should be only these two pages and as exposing this as an option for all pages
820 // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
821 return in_array(
822 $this->page->url->out_as_local_url(false, array()),
823 array(
824 '/login/index.php',
825 '/login/forgot_password.php',
826 )
827 );
828 }
829
d9c8f425 830 /**
831 * Return the 'back' link that normally appears in the footer.
7a3c215b 832 *
d9c8f425 833 * @return string HTML fragment.
834 */
835 public function home_link() {
836 global $CFG, $SITE;
837
838 if ($this->page->pagetype == 'site-index') {
839 // Special case for site home page - please do not remove
840 return '<div class="sitelink">' .
34dff6aa 841 '<a title="Moodle" href="http://moodle.org/">' .
3a723033 842 '<img src="' . $this->pix_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
d9c8f425 843
844 } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
845 // Special case for during install/upgrade.
846 return '<div class="sitelink">'.
34dff6aa 847 '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
3a723033 848 '<img src="' . $this->pix_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
d9c8f425 849
850 } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
851 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
852 get_string('home') . '</a></div>';
853
854 } else {
855 return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
8ebbb06a 856 format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
d9c8f425 857 }
858 }
859
860 /**
861 * Redirects the user by any means possible given the current state
862 *
863 * This function should not be called directly, it should always be called using
864 * the redirect function in lib/weblib.php
865 *
866 * The redirect function should really only be called before page output has started
867 * however it will allow itself to be called during the state STATE_IN_BODY
868 *
869 * @param string $encodedurl The URL to send to encoded if required
870 * @param string $message The message to display to the user if any
871 * @param int $delay The delay before redirecting a user, if $message has been
872 * set this is a requirement and defaults to 3, set to 0 no delay
873 * @param boolean $debugdisableredirect this redirect has been disabled for
874 * debugging purposes. Display a message that explains, and don't
875 * trigger the redirect.
3ad96419
AN
876 * @param string $messagetype The type of notification to show the message in.
877 * See constants on \core\output\notification.
d9c8f425 878 * @return string The HTML to display to the user before dying, may contain
879 * meta refresh, javascript refresh, and may have set header redirects
880 */
3ad96419
AN
881 public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
882 $messagetype = \core\output\notification::NOTIFY_INFO) {
d9c8f425 883 global $CFG;
884 $url = str_replace('&amp;', '&', $encodedurl);
885
886 switch ($this->page->state) {
887 case moodle_page::STATE_BEFORE_HEADER :
888 // No output yet it is safe to delivery the full arsenal of redirect methods
889 if (!$debugdisableredirect) {
890 // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
891 $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
593f9b87 892 $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
d9c8f425 893 }
894 $output = $this->header();
895 break;
896 case moodle_page::STATE_PRINTING_HEADER :
897 // We should hopefully never get here
898 throw new coding_exception('You cannot redirect while printing the page header');
899 break;
900 case moodle_page::STATE_IN_BODY :
901 // We really shouldn't be here but we can deal with this
902 debugging("You should really redirect before you start page output");
903 if (!$debugdisableredirect) {
593f9b87 904 $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
d9c8f425 905 }
906 $output = $this->opencontainers->pop_all_but_last();
907 break;
908 case moodle_page::STATE_DONE :
909 // Too late to be calling redirect now
910 throw new coding_exception('You cannot redirect after the entire page has been generated');
911 break;
912 }
3ad96419 913 $output .= $this->notification($message, $messagetype);
3ab2e357 914 $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
d9c8f425 915 if ($debugdisableredirect) {
05da2850 916 $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
d9c8f425 917 }
918 $output .= $this->footer();
919 return $output;
920 }
921
922 /**
923 * Start output by sending the HTTP headers, and printing the HTML <head>
924 * and the start of the <body>.
925 *
926 * To control what is printed, you should set properties on $PAGE. If you
f8129210 927 * are familiar with the old {@link print_header()} function from Moodle 1.9
d9c8f425 928 * you will find that there are properties on $PAGE that correspond to most
929 * of the old parameters to could be passed to print_header.
930 *
931 * Not that, in due course, the remaining $navigation, $menu parameters here
932 * will be replaced by more properties of $PAGE, but that is still to do.
933 *
d9c8f425 934 * @return string HTML that you must output this, preferably immediately.
935 */
e120c61d 936 public function header() {
d9c8f425 937 global $USER, $CFG;
938
d79d5ac2 939 if (\core\session\manager::is_loggedinas()) {
e884f63a
PS
940 $this->page->add_body_class('userloggedinas');
941 }
942
46629116
JC
943 // If the user is logged in, and we're not in initial install,
944 // check to see if the user is role-switched and add the appropriate
945 // CSS class to the body element.
946 if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
947 $this->page->add_body_class('userswitchedrole');
948 }
949
63c88397
PS
950 // Give themes a chance to init/alter the page object.
951 $this->page->theme->init_page($this->page);
952
d9c8f425 953 $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
954
78946b9b
PS
955 // Find the appropriate page layout file, based on $this->page->pagelayout.
956 $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
957 // Render the layout using the layout file.
958 $rendered = $this->render_page_layout($layoutfile);
67e84a7f 959
78946b9b 960 // Slice the rendered output into header and footer.
72009b87
PS
961 $cutpos = strpos($rendered, $this->unique_main_content_token);
962 if ($cutpos === false) {
963 $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
964 $token = self::MAIN_CONTENT_TOKEN;
965 } else {
966 $token = $this->unique_main_content_token;
967 }
968
d9c8f425 969 if ($cutpos === false) {
72009b87 970 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 971 }
78946b9b 972 $header = substr($rendered, 0, $cutpos);
72009b87 973 $footer = substr($rendered, $cutpos + strlen($token));
d9c8f425 974
975 if (empty($this->contenttype)) {
78946b9b 976 debugging('The page layout file did not call $OUTPUT->doctype()');
67e84a7f 977 $header = $this->doctype() . $header;
d9c8f425 978 }
979
fdd4b9a5
MG
980 // If this theme version is below 2.4 release and this is a course view page
981 if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
982 $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
983 // check if course content header/footer have not been output during render of theme layout
984 $coursecontentheader = $this->course_content_header(true);
985 $coursecontentfooter = $this->course_content_footer(true);
986 if (!empty($coursecontentheader)) {
987 // display debug message and add header and footer right above and below main content
988 // Please note that course header and footer (to be displayed above and below the whole page)
989 // are not displayed in this case at all.
990 // Besides the content header and footer are not displayed on any other course page
991 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);
992 $header .= $coursecontentheader;
993 $footer = $coursecontentfooter. $footer;
994 }
995 }
996
d9c8f425 997 send_headers($this->contenttype, $this->page->cacheable);
67e84a7f 998
d9c8f425 999 $this->opencontainers->push('header/footer', $footer);
1000 $this->page->set_state(moodle_page::STATE_IN_BODY);
67e84a7f 1001
29ba64e5 1002 return $header . $this->skip_link_target('maincontent');
d9c8f425 1003 }
1004
1005 /**
78946b9b 1006 * Renders and outputs the page layout file.
7a3c215b
SH
1007 *
1008 * This is done by preparing the normal globals available to a script, and
1009 * then including the layout file provided by the current theme for the
1010 * requested layout.
1011 *
78946b9b 1012 * @param string $layoutfile The name of the layout file
d9c8f425 1013 * @return string HTML code
1014 */
78946b9b 1015 protected function render_page_layout($layoutfile) {
92e01ab7 1016 global $CFG, $SITE, $USER;
d9c8f425 1017 // The next lines are a bit tricky. The point is, here we are in a method
1018 // of a renderer class, and this object may, or may not, be the same as
78946b9b 1019 // the global $OUTPUT object. When rendering the page layout file, we want to use
d9c8f425 1020 // this object. However, people writing Moodle code expect the current
1021 // renderer to be called $OUTPUT, not $this, so define a variable called
1022 // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1023 $OUTPUT = $this;
1024 $PAGE = $this->page;
1025 $COURSE = $this->page->course;
1026
d9c8f425 1027 ob_start();
78946b9b
PS
1028 include($layoutfile);
1029 $rendered = ob_get_contents();
d9c8f425 1030 ob_end_clean();
78946b9b 1031 return $rendered;
d9c8f425 1032 }
1033
1034 /**
1035 * Outputs the page's footer
7a3c215b 1036 *
d9c8f425 1037 * @return string HTML fragment
1038 */
1039 public function footer() {
0346323c 1040 global $CFG, $DB, $PAGE;
0f0801f4 1041
f6794ace 1042 $output = $this->container_end_all(true);
4d2ee4c2 1043
d9c8f425 1044 $footer = $this->opencontainers->pop('header/footer');
1045
d5a8d9aa 1046 if (debugging() and $DB and $DB->is_transaction_started()) {
03221650 1047 // TODO: MDL-20625 print warning - transaction will be rolled back
d5a8d9aa
PS
1048 }
1049
d9c8f425 1050 // Provide some performance info if required
1051 $performanceinfo = '';
1052 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1053 $perf = get_performance_info();
d9c8f425 1054 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1055 $performanceinfo = $perf['html'];
1056 }
1057 }
58a3a34e
DM
1058
1059 // We always want performance data when running a performance test, even if the user is redirected to another page.
1060 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1061 $footer = $this->unique_performance_info_token . $footer;
1062 }
72009b87 1063 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
d9c8f425 1064
0346323c 1065 $this->page->requires->js_call_amd('core/notification', 'init', array($PAGE->context->id, \core\notification::fetch_as_array($this)));
72009b87 1066 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
d9c8f425 1067
1068 $this->page->set_state(moodle_page::STATE_DONE);
d9c8f425 1069
1070 return $output . $footer;
1071 }
1072
f6794ace
PS
1073 /**
1074 * Close all but the last open container. This is useful in places like error
1075 * handling, where you want to close all the open containers (apart from <body>)
1076 * before outputting the error message.
7a3c215b 1077 *
f6794ace
PS
1078 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1079 * developer debug warning if it isn't.
1080 * @return string the HTML required to close any open containers inside <body>.
1081 */
1082 public function container_end_all($shouldbenone = false) {
1083 return $this->opencontainers->pop_all_but_last($shouldbenone);
1084 }
1085
fdd4b9a5
MG
1086 /**
1087 * Returns course-specific information to be output immediately above content on any course page
1088 * (for the current course)
1089 *
1090 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1091 * @return string
1092 */
1093 public function course_content_header($onlyifnotcalledbefore = false) {
1094 global $CFG;
fdd4b9a5
MG
1095 static $functioncalled = false;
1096 if ($functioncalled && $onlyifnotcalledbefore) {
1097 // we have already output the content header
1098 return '';
1099 }
0346323c
AN
1100
1101 // Output any session notification.
1102 $notifications = \core\notification::fetch();
1103
1104 $bodynotifications = '';
1105 foreach ($notifications as $notification) {
1106 $bodynotifications .= $this->render_from_template(
1107 $notification->get_template_name(),
1108 $notification->export_for_template($this)
1109 );
1110 }
1111
1112 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1113
1114 if ($this->page->course->id == SITEID) {
1115 // return immediately and do not include /course/lib.php if not necessary
1116 return $output;
1117 }
1118
fdd4b9a5
MG
1119 require_once($CFG->dirroot.'/course/lib.php');
1120 $functioncalled = true;
1121 $courseformat = course_get_format($this->page->course);
1122 if (($obj = $courseformat->course_content_header()) !== null) {
0346323c 1123 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
fdd4b9a5 1124 }
0346323c 1125 return $output;
fdd4b9a5
MG
1126 }
1127
1128 /**
1129 * Returns course-specific information to be output immediately below content on any course page
1130 * (for the current course)
1131 *
1132 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1133 * @return string
1134 */
1135 public function course_content_footer($onlyifnotcalledbefore = false) {
1136 global $CFG;
1137 if ($this->page->course->id == SITEID) {
1138 // return immediately and do not include /course/lib.php if not necessary
1139 return '';
1140 }
1141 static $functioncalled = false;
1142 if ($functioncalled && $onlyifnotcalledbefore) {
1143 // we have already output the content footer
1144 return '';
1145 }
1146 $functioncalled = true;
1147 require_once($CFG->dirroot.'/course/lib.php');
1148 $courseformat = course_get_format($this->page->course);
1149 if (($obj = $courseformat->course_content_footer()) !== null) {
06a72e01 1150 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
fdd4b9a5
MG
1151 }
1152 return '';
1153 }
1154
1155 /**
1156 * Returns course-specific information to be output on any course page in the header area
1157 * (for the current course)
1158 *
1159 * @return string
1160 */
1161 public function course_header() {
1162 global $CFG;
1163 if ($this->page->course->id == SITEID) {
1164 // return immediately and do not include /course/lib.php if not necessary
1165 return '';
1166 }
1167 require_once($CFG->dirroot.'/course/lib.php');
1168 $courseformat = course_get_format($this->page->course);
1169 if (($obj = $courseformat->course_header()) !== null) {
1170 return $courseformat->get_renderer($this->page)->render($obj);
1171 }
1172 return '';
1173 }
1174
1175 /**
1176 * Returns course-specific information to be output on any course page in the footer area
1177 * (for the current course)
1178 *
1179 * @return string
1180 */
1181 public function course_footer() {
1182 global $CFG;
1183 if ($this->page->course->id == SITEID) {
1184 // return immediately and do not include /course/lib.php if not necessary
1185 return '';
1186 }
1187 require_once($CFG->dirroot.'/course/lib.php');
1188 $courseformat = course_get_format($this->page->course);
1189 if (($obj = $courseformat->course_footer()) !== null) {
1190 return $courseformat->get_renderer($this->page)->render($obj);
1191 }
1192 return '';
1193 }
1194
244a32c6
PS
1195 /**
1196 * Returns lang menu or '', this method also checks forcing of languages in courses.
7a3c215b 1197 *
2fada290
MG
1198 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1199 *
7a3c215b 1200 * @return string The lang menu HTML or empty string
244a32c6
PS
1201 */
1202 public function lang_menu() {
1203 global $CFG;
1204
1205 if (empty($CFG->langmenu)) {
1206 return '';
1207 }
1208
1209 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1210 // do not show lang menu if language forced
1211 return '';
1212 }
1213
1214 $currlang = current_language();
1f96e907 1215 $langs = get_string_manager()->get_list_of_translations();
4bcc5118 1216
244a32c6
PS
1217 if (count($langs) < 2) {
1218 return '';
1219 }
1220
a9967cf5
PS
1221 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1222 $s->label = get_accesshide(get_string('language'));
1223 $s->class = 'langmenu';
1224 return $this->render($s);
244a32c6
PS
1225 }
1226
d9c8f425 1227 /**
1228 * Output the row of editing icons for a block, as defined by the controls array.
7a3c215b 1229 *
f8129210 1230 * @param array $controls an array like {@link block_contents::$controls}.
b59f2e3b 1231 * @param string $blockid The ID given to the block.
7a3c215b 1232 * @return string HTML fragment.
d9c8f425 1233 */
b59f2e3b 1234 public function block_controls($actions, $blockid = null) {
10fc1569 1235 global $CFG;
b59f2e3b
SH
1236 if (empty($actions)) {
1237 return '';
1238 }
cf69a00a 1239 $menu = new action_menu($actions);
b59f2e3b
SH
1240 if ($blockid !== null) {
1241 $menu->set_owner_selector('#'.$blockid);
1242 }
ae3fd8eb 1243 $menu->set_constraint('.block-region');
b59f2e3b 1244 $menu->attributes['class'] .= ' block-control-actions commands';
10fc1569
SH
1245 if (isset($CFG->blockeditingmenu) && !$CFG->blockeditingmenu) {
1246 $menu->do_not_enhance();
1247 }
b59f2e3b
SH
1248 return $this->render($menu);
1249 }
1250
1251 /**
1252 * Renders an action menu component.
1253 *
3665af78
SH
1254 * ARIA references:
1255 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1256 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1257 *
b59f2e3b
SH
1258 * @param action_menu $menu
1259 * @return string HTML
1260 */
1261 public function render_action_menu(action_menu $menu) {
1262 $menu->initialise_js($this->page);
1263
1264 $output = html_writer::start_tag('div', $menu->attributes);
3665af78 1265 $output .= html_writer::start_tag('ul', $menu->attributesprimary);
b59f2e3b
SH
1266 foreach ($menu->get_primary_actions($this) as $action) {
1267 if ($action instanceof renderable) {
3665af78 1268 $content = $this->render($action);
b59f2e3b 1269 } else {
3665af78 1270 $content = $action;
e282c679 1271 }
11dd4dad 1272 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
d9c8f425 1273 }
3665af78
SH
1274 $output .= html_writer::end_tag('ul');
1275 $output .= html_writer::start_tag('ul', $menu->attributessecondary);
b59f2e3b 1276 foreach ($menu->get_secondary_actions() as $action) {
3665af78
SH
1277 if ($action instanceof renderable) {
1278 $content = $this->render($action);
3665af78
SH
1279 } else {
1280 $content = $action;
3665af78 1281 }
11dd4dad 1282 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
b59f2e3b 1283 }
3665af78 1284 $output .= html_writer::end_tag('ul');
b59f2e3b 1285 $output .= html_writer::end_tag('div');
e282c679 1286 return $output;
d9c8f425 1287 }
1288
cf69a00a 1289 /**
3665af78 1290 * Renders an action_menu_link item.
cf69a00a 1291 *
3665af78 1292 * @param action_menu_link $action
cf69a00a
SH
1293 * @return string HTML fragment
1294 */
3665af78 1295 protected function render_action_menu_link(action_menu_link $action) {
d0647301
SH
1296 static $actioncount = 0;
1297 $actioncount++;
cf69a00a 1298
ea5a01fb 1299 $comparetoalt = '';
cf69a00a 1300 $text = '';
ea5a01fb 1301 if (!$action->icon || $action->primary === false) {
d0647301 1302 $text .= html_writer::start_tag('span', array('class'=>'menu-action-text', 'id' => 'actionmenuaction-'.$actioncount));
cf69a00a
SH
1303 if ($action->text instanceof renderable) {
1304 $text .= $this->render($action->text);
1305 } else {
1306 $text .= $action->text;
cfd1e08a 1307 $comparetoalt = (string)$action->text;
cf69a00a
SH
1308 }
1309 $text .= html_writer::end_tag('span');
1310 }
1311
ea5a01fb
SH
1312 $icon = '';
1313 if ($action->icon) {
1314 $icon = $action->icon;
f803ce26 1315 if ($action->primary || !$action->actionmenu->will_be_enhanced()) {
ea5a01fb
SH
1316 $action->attributes['title'] = $action->text;
1317 }
cfd1e08a
SH
1318 if (!$action->primary && $action->actionmenu->will_be_enhanced()) {
1319 if ((string)$icon->attributes['alt'] === $comparetoalt) {
d0647301 1320 $icon->attributes['alt'] = '';
cfd1e08a 1321 }
c7a2291f 1322 if (isset($icon->attributes['title']) && (string)$icon->attributes['title'] === $comparetoalt) {
cfd1e08a
SH
1323 unset($icon->attributes['title']);
1324 }
1325 }
ea5a01fb
SH
1326 $icon = $this->render($icon);
1327 }
1328
3665af78 1329 // A disabled link is rendered as formatted text.
cf69a00a 1330 if (!empty($action->attributes['disabled'])) {
3665af78 1331 // Do not use div here due to nesting restriction in xhtml strict.
ea5a01fb 1332 return html_writer::tag('span', $icon.$text, array('class'=>'currentlink', 'role' => 'menuitem'));
cf69a00a
SH
1333 }
1334
1335 $attributes = $action->attributes;
1336 unset($action->attributes['disabled']);
1337 $attributes['href'] = $action->url;
d0647301
SH
1338 if ($text !== '') {
1339 $attributes['aria-labelledby'] = 'actionmenuaction-'.$actioncount;
1340 }
cf69a00a 1341
ea5a01fb 1342 return html_writer::tag('a', $icon.$text, $attributes);
cf69a00a
SH
1343 }
1344
9ac099a1
AN
1345 /**
1346 * Renders a primary action_menu_filler item.
1347 *
1348 * @param action_menu_link_filler $action
1349 * @return string HTML fragment
1350 */
1351 protected function render_action_menu_filler(action_menu_filler $action) {
1352 return html_writer::span('&nbsp;', 'filler');
1353 }
1354
cf69a00a 1355 /**
3665af78 1356 * Renders a primary action_menu_link item.
cf69a00a 1357 *
3665af78 1358 * @param action_menu_link_primary $action
cf69a00a
SH
1359 * @return string HTML fragment
1360 */
3665af78
SH
1361 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1362 return $this->render_action_menu_link($action);
cf69a00a
SH
1363 }
1364
1365 /**
3665af78 1366 * Renders a secondary action_menu_link item.
cf69a00a 1367 *
3665af78 1368 * @param action_menu_link_secondary $action
cf69a00a
SH
1369 * @return string HTML fragment
1370 */
3665af78
SH
1371 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1372 return $this->render_action_menu_link($action);
cf69a00a
SH
1373 }
1374
d9c8f425 1375 /**
1376 * Prints a nice side block with an optional header.
1377 *
1378 * The content is described
f8129210 1379 * by a {@link core_renderer::block_contents} object.
d9c8f425 1380 *
cbb54cce
SH
1381 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1382 * <div class="header"></div>
1383 * <div class="content">
1384 * ...CONTENT...
1385 * <div class="footer">
1386 * </div>
1387 * </div>
1388 * <div class="annotation">
1389 * </div>
1390 * </div>
1391 *
d9c8f425 1392 * @param block_contents $bc HTML for the content
1393 * @param string $region the region the block is appearing in.
1394 * @return string the HTML to be output.
1395 */
7a3c215b 1396 public function block(block_contents $bc, $region) {
d9c8f425 1397 $bc = clone($bc); // Avoid messing up the object passed in.
dd72b308
PS
1398 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1399 $bc->collapsible = block_contents::NOT_HIDEABLE;
1400 }
84192d78
SH
1401 if (!empty($bc->blockinstanceid)) {
1402 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1403 }
91d941c3
SH
1404 $skiptitle = strip_tags($bc->title);
1405 if ($bc->blockinstanceid && !empty($skiptitle)) {
1406 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1407 } else if (!empty($bc->arialabel)) {
1408 $bc->attributes['aria-label'] = $bc->arialabel;
1409 }
84192d78
SH
1410 if ($bc->dockable) {
1411 $bc->attributes['data-dockable'] = 1;
1412 }
dd72b308
PS
1413 if ($bc->collapsible == block_contents::HIDDEN) {
1414 $bc->add_class('hidden');
1415 }
1416 if (!empty($bc->controls)) {
1417 $bc->add_class('block_with_controls');
1418 }
d9c8f425 1419
91d941c3 1420
d9c8f425 1421 if (empty($skiptitle)) {
1422 $output = '';
1423 $skipdest = '';
1424 } else {
9e8d0842
AG
1425 $output = html_writer::link('#sb-'.$bc->skipid, get_string('skipa', 'access', $skiptitle),
1426 array('class' => 'skip skip-block', 'id' => 'fsb-' . $bc->skipid));
0b7856ef 1427 $skipdest = html_writer::span('', 'skip-block-to',
9e8d0842 1428 array('id' => 'sb-' . $bc->skipid));
d9c8f425 1429 }
4d2ee4c2 1430
5d0c95a5 1431 $output .= html_writer::start_tag('div', $bc->attributes);
d9c8f425 1432
9f5c39b5
SH
1433 $output .= $this->block_header($bc);
1434 $output .= $this->block_content($bc);
1435
1436 $output .= html_writer::end_tag('div');
1437
1438 $output .= $this->block_annotation($bc);
1439
1440 $output .= $skipdest;
1441
1442 $this->init_block_hider_js($bc);
1443 return $output;
1444 }
1445
1446 /**
1447 * Produces a header for a block
fa7f2a45 1448 *
9f5c39b5
SH
1449 * @param block_contents $bc
1450 * @return string
1451 */
1452 protected function block_header(block_contents $bc) {
d9c8f425 1453
1454 $title = '';
1455 if ($bc->title) {
91d941c3
SH
1456 $attributes = array();
1457 if ($bc->blockinstanceid) {
1458 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1459 }
1460 $title = html_writer::tag('h2', $bc->title, $attributes);
d9c8f425 1461 }
1462
b59f2e3b
SH
1463 $blockid = null;
1464 if (isset($bc->attributes['id'])) {
1465 $blockid = $bc->attributes['id'];
1466 }
1467 $controlshtml = $this->block_controls($bc->controls, $blockid);
9f5c39b5
SH
1468
1469 $output = '';
d9c8f425 1470 if ($title || $controlshtml) {
46de77b6 1471 $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 1472 }
9f5c39b5
SH
1473 return $output;
1474 }
d9c8f425 1475
9f5c39b5
SH
1476 /**
1477 * Produces the content area for a block
1478 *
1479 * @param block_contents $bc
1480 * @return string
1481 */
1482 protected function block_content(block_contents $bc) {
1483 $output = html_writer::start_tag('div', array('class' => 'content'));
1484 if (!$bc->title && !$this->block_controls($bc->controls)) {
46de77b6
SH
1485 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1486 }
d9c8f425 1487 $output .= $bc->content;
9f5c39b5
SH
1488 $output .= $this->block_footer($bc);
1489 $output .= html_writer::end_tag('div');
fa7f2a45 1490
9f5c39b5
SH
1491 return $output;
1492 }
d9c8f425 1493
9f5c39b5
SH
1494 /**
1495 * Produces the footer for a block
1496 *
1497 * @param block_contents $bc
1498 * @return string
1499 */
1500 protected function block_footer(block_contents $bc) {
1501 $output = '';
d9c8f425 1502 if ($bc->footer) {
26acc814 1503 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
d9c8f425 1504 }
9f5c39b5
SH
1505 return $output;
1506 }
d9c8f425 1507
9f5c39b5
SH
1508 /**
1509 * Produces the annotation for a block
1510 *
1511 * @param block_contents $bc
1512 * @return string
1513 */
1514 protected function block_annotation(block_contents $bc) {
1515 $output = '';
d9c8f425 1516 if ($bc->annotation) {
26acc814 1517 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
d9c8f425 1518 }
d9c8f425 1519 return $output;
1520 }
1521
1522 /**
1523 * Calls the JS require function to hide a block.
7a3c215b 1524 *
d9c8f425 1525 * @param block_contents $bc A block_contents object
d9c8f425 1526 */
dd72b308
PS
1527 protected function init_block_hider_js(block_contents $bc) {
1528 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
cbb54cce
SH
1529 $config = new stdClass;
1530 $config->id = $bc->attributes['id'];
1531 $config->title = strip_tags($bc->title);
1532 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1533 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1534 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1535
1536 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1537 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
d9c8f425 1538 }
1539 }
1540
1541 /**
1542 * Render the contents of a block_list.
7a3c215b 1543 *
d9c8f425 1544 * @param array $icons the icon for each item.
1545 * @param array $items the content of each item.
1546 * @return string HTML
1547 */
1548 public function list_block_contents($icons, $items) {
1549 $row = 0;
1550 $lis = array();
1551 foreach ($items as $key => $string) {
5d0c95a5 1552 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
2c5ec833 1553 if (!empty($icons[$key])) { //test if the content has an assigned icon
26acc814 1554 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
d9c8f425 1555 }
26acc814 1556 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
5d0c95a5 1557 $item .= html_writer::end_tag('li');
d9c8f425 1558 $lis[] = $item;
1559 $row = 1 - $row; // Flip even/odd.
1560 }
f2a04fc1 1561 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
d9c8f425 1562 }
1563
1564 /**
1565 * Output all the blocks in a particular region.
7a3c215b 1566 *
d9c8f425 1567 * @param string $region the name of a region on this page.
1568 * @return string the HTML to be output.
1569 */
1570 public function blocks_for_region($region) {
1571 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
6671fa73
JF
1572 $blocks = $this->page->blocks->get_blocks_for_region($region);
1573 $lastblock = null;
1574 $zones = array();
1575 foreach ($blocks as $block) {
1576 $zones[] = $block->title;
1577 }
d9c8f425 1578 $output = '';
6671fa73 1579
d9c8f425 1580 foreach ($blockcontents as $bc) {
1581 if ($bc instanceof block_contents) {
1582 $output .= $this->block($bc, $region);
6671fa73 1583 $lastblock = $bc->title;
d9c8f425 1584 } else if ($bc instanceof block_move_target) {
686e3b3a 1585 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
d9c8f425 1586 } else {
1587 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1588 }
1589 }
1590 return $output;
1591 }
1592
1593 /**
1594 * Output a place where the block that is currently being moved can be dropped.
7a3c215b 1595 *
d9c8f425 1596 * @param block_move_target $target with the necessary details.
6671fa73
JF
1597 * @param array $zones array of areas where the block can be moved to
1598 * @param string $previous the block located before the area currently being rendered.
686e3b3a 1599 * @param string $region the name of the region
d9c8f425 1600 * @return string the HTML to be output.
1601 */
686e3b3a 1602 public function block_move_target($target, $zones, $previous, $region) {
0e2ca62e 1603 if ($previous == null) {
686e3b3a
FM
1604 if (empty($zones)) {
1605 // There are no zones, probably because there are no blocks.
1606 $regions = $this->page->theme->get_all_block_regions();
1607 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1608 } else {
1609 $position = get_string('moveblockbefore', 'block', $zones[0]);
1610 }
6671fa73
JF
1611 } else {
1612 $position = get_string('moveblockafter', 'block', $previous);
1613 }
1614 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
d9c8f425 1615 }
1616
574fbea4 1617 /**
996b1e0c 1618 * Renders a special html link with attached action
574fbea4 1619 *
2fada290
MG
1620 * Theme developers: DO NOT OVERRIDE! Please override function
1621 * {@link core_renderer::render_action_link()} instead.
1622 *
574fbea4
PS
1623 * @param string|moodle_url $url
1624 * @param string $text HTML fragment
1625 * @param component_action $action
11820bac 1626 * @param array $attributes associative array of html link attributes + disabled
e282c679 1627 * @param pix_icon optional pix icon to render with the link
7a3c215b 1628 * @return string HTML fragment
574fbea4 1629 */
e282c679 1630 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
574fbea4
PS
1631 if (!($url instanceof moodle_url)) {
1632 $url = new moodle_url($url);
1633 }
e282c679 1634 $link = new action_link($url, $text, $action, $attributes, $icon);
574fbea4 1635
f14b641b 1636 return $this->render($link);
574fbea4
PS
1637 }
1638
1639 /**
7a3c215b
SH
1640 * Renders an action_link object.
1641 *
1642 * The provided link is renderer and the HTML returned. At the same time the
f8129210 1643 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
7a3c215b 1644 *
574fbea4
PS
1645 * @param action_link $link
1646 * @return string HTML fragment
1647 */
1648 protected function render_action_link(action_link $link) {
1649 global $CFG;
1650
e282c679
SH
1651 $text = '';
1652 if ($link->icon) {
1653 $text .= $this->render($link->icon);
1654 }
1655
7749e187 1656 if ($link->text instanceof renderable) {
e282c679 1657 $text .= $this->render($link->text);
7749e187 1658 } else {
e282c679 1659 $text .= $link->text;
7749e187
SH
1660 }
1661
574fbea4
PS
1662 // A disabled link is rendered as formatted text
1663 if (!empty($link->attributes['disabled'])) {
1664 // do not use div here due to nesting restriction in xhtml strict
7749e187 1665 return html_writer::tag('span', $text, array('class'=>'currentlink'));
574fbea4 1666 }
11820bac 1667
574fbea4
PS
1668 $attributes = $link->attributes;
1669 unset($link->attributes['disabled']);
1670 $attributes['href'] = $link->url;
1671
1672 if ($link->actions) {
f14b641b 1673 if (empty($attributes['id'])) {
574fbea4
PS
1674 $id = html_writer::random_id('action_link');
1675 $attributes['id'] = $id;
1676 } else {
1677 $id = $attributes['id'];
1678 }
1679 foreach ($link->actions as $action) {
c80877aa 1680 $this->add_action_handler($action, $id);
574fbea4
PS
1681 }
1682 }
1683
7749e187 1684 return html_writer::tag('a', $text, $attributes);
574fbea4
PS
1685 }
1686
c63923bd
PS
1687
1688 /**
7a3c215b
SH
1689 * Renders an action_icon.
1690 *
f8129210 1691 * This function uses the {@link core_renderer::action_link()} method for the
7a3c215b
SH
1692 * most part. What it does different is prepare the icon as HTML and use it
1693 * as the link text.
c63923bd 1694 *
2fada290
MG
1695 * Theme developers: If you want to change how action links and/or icons are rendered,
1696 * consider overriding function {@link core_renderer::render_action_link()} and
1697 * {@link core_renderer::render_pix_icon()}.
1698 *
c63923bd
PS
1699 * @param string|moodle_url $url A string URL or moodel_url
1700 * @param pix_icon $pixicon
1701 * @param component_action $action
1702 * @param array $attributes associative array of html link attributes + disabled
1703 * @param bool $linktext show title next to image in link
1704 * @return string HTML fragment
1705 */
1706 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1707 if (!($url instanceof moodle_url)) {
1708 $url = new moodle_url($url);
1709 }
1710 $attributes = (array)$attributes;
1711
524645e7 1712 if (empty($attributes['class'])) {
c63923bd
PS
1713 // let ppl override the class via $options
1714 $attributes['class'] = 'action-icon';
1715 }
1716
1717 $icon = $this->render($pixicon);
1718
1719 if ($linktext) {
1720 $text = $pixicon->attributes['alt'];
1721 } else {
1722 $text = '';
1723 }
1724
1725 return $this->action_link($url, $text.$icon, $action, $attributes);
1726 }
1727
d9c8f425 1728 /**
0b634d75 1729 * Print a message along with button choices for Continue/Cancel
1730 *
4ed85790 1731 * If a string or moodle_url is given instead of a single_button, method defaults to post.
0b634d75 1732 *
d9c8f425 1733 * @param string $message The question to ask the user
3ba60ee1
PS
1734 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1735 * @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 1736 * @return string HTML fragment
1737 */
1738 public function confirm($message, $continue, $cancel) {
4871a238 1739 if ($continue instanceof single_button) {
11820bac 1740 // ok
4871a238
PS
1741 } else if (is_string($continue)) {
1742 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1743 } else if ($continue instanceof moodle_url) {
26eab8d4 1744 $continue = new single_button($continue, get_string('continue'), 'post');
d9c8f425 1745 } else {
4ed85790 1746 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
d9c8f425 1747 }
1748
4871a238 1749 if ($cancel instanceof single_button) {
11820bac 1750 // ok
4871a238
PS
1751 } else if (is_string($cancel)) {
1752 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1753 } else if ($cancel instanceof moodle_url) {
26eab8d4 1754 $cancel = new single_button($cancel, get_string('cancel'), 'get');
d9c8f425 1755 } else {
4ed85790 1756 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
d9c8f425 1757 }
1758
d9c8f425 1759 $output = $this->box_start('generalbox', 'notice');
26acc814
PS
1760 $output .= html_writer::tag('p', $message);
1761 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
d9c8f425 1762 $output .= $this->box_end();
1763 return $output;
1764 }
1765
3cd5305f 1766 /**
3ba60ee1 1767 * Returns a form with a single button.
3cd5305f 1768 *
2fada290
MG
1769 * Theme developers: DO NOT OVERRIDE! Please override function
1770 * {@link core_renderer::render_single_button()} instead.
1771 *
3ba60ee1 1772 * @param string|moodle_url $url
3cd5305f
PS
1773 * @param string $label button text
1774 * @param string $method get or post submit method
3ba60ee1 1775 * @param array $options associative array {disabled, title, etc.}
3cd5305f
PS
1776 * @return string HTML fragment
1777 */
3ba60ee1 1778 public function single_button($url, $label, $method='post', array $options=null) {
574fbea4
PS
1779 if (!($url instanceof moodle_url)) {
1780 $url = new moodle_url($url);
3ba60ee1 1781 }
574fbea4
PS
1782 $button = new single_button($url, $label, $method);
1783
3ba60ee1
PS
1784 foreach ((array)$options as $key=>$value) {
1785 if (array_key_exists($key, $button)) {
1786 $button->$key = $value;
1787 }
3cd5305f
PS
1788 }
1789
3ba60ee1 1790 return $this->render($button);
3cd5305f
PS
1791 }
1792
d9c8f425 1793 /**
7a3c215b
SH
1794 * Renders a single button widget.
1795 *
1796 * This will return HTML to display a form containing a single button.
1797 *
3ba60ee1 1798 * @param single_button $button
d9c8f425 1799 * @return string HTML fragment
1800 */
3ba60ee1
PS
1801 protected function render_single_button(single_button $button) {
1802 $attributes = array('type' => 'submit',
1803 'value' => $button->label,
db09524d 1804 'disabled' => $button->disabled ? 'disabled' : null,
3ba60ee1
PS
1805 'title' => $button->tooltip);
1806
1807 if ($button->actions) {
1808 $id = html_writer::random_id('single_button');
1809 $attributes['id'] = $id;
1810 foreach ($button->actions as $action) {
c80877aa 1811 $this->add_action_handler($action, $id);
3ba60ee1 1812 }
d9c8f425 1813 }
d9c8f425 1814
3ba60ee1
PS
1815 // first the input element
1816 $output = html_writer::empty_tag('input', $attributes);
d9c8f425 1817
3ba60ee1
PS
1818 // then hidden fields
1819 $params = $button->url->params();
1820 if ($button->method === 'post') {
1821 $params['sesskey'] = sesskey();
1822 }
1823 foreach ($params as $var => $val) {
1824 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1825 }
d9c8f425 1826
3ba60ee1 1827 // then div wrapper for xhtml strictness
26acc814 1828 $output = html_writer::tag('div', $output);
d9c8f425 1829
3ba60ee1 1830 // now the form itself around it
a12cd69c
DM
1831 if ($button->method === 'get') {
1832 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1833 } else {
1834 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1835 }
a6855934
PS
1836 if ($url === '') {
1837 $url = '#'; // there has to be always some action
1838 }
3ba60ee1 1839 $attributes = array('method' => $button->method,
a6855934 1840 'action' => $url,
3ba60ee1 1841 'id' => $button->formid);
26acc814 1842 $output = html_writer::tag('form', $output, $attributes);
d9c8f425 1843
3ba60ee1 1844 // and finally one more wrapper with class
26acc814 1845 return html_writer::tag('div', $output, array('class' => $button->class));
d9c8f425 1846 }
1847
a9967cf5 1848 /**
ab08be98 1849 * Returns a form with a single select widget.
7a3c215b 1850 *
2fada290
MG
1851 * Theme developers: DO NOT OVERRIDE! Please override function
1852 * {@link core_renderer::render_single_select()} instead.
1853 *
a9967cf5
PS
1854 * @param moodle_url $url form action target, includes hidden fields
1855 * @param string $name name of selection field - the changing parameter in url
1856 * @param array $options list of options
1857 * @param string $selected selected element
1858 * @param array $nothing
f8dab966 1859 * @param string $formid
32bd11cb 1860 * @param array $attributes other attributes for the single select
a9967cf5
PS
1861 * @return string HTML fragment
1862 */
32bd11cb
BB
1863 public function single_select($url, $name, array $options, $selected = '',
1864 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
a9967cf5
PS
1865 if (!($url instanceof moodle_url)) {
1866 $url = new moodle_url($url);
1867 }
f8dab966 1868 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
a9967cf5 1869
32bd11cb
BB
1870 if (array_key_exists('label', $attributes)) {
1871 $select->set_label($attributes['label']);
1872 unset($attributes['label']);
1873 }
1874 $select->attributes = $attributes;
1875
a9967cf5
PS
1876 return $this->render($select);
1877 }
1878
1879 /**
1880 * Internal implementation of single_select rendering
7a3c215b 1881 *
a9967cf5
PS
1882 * @param single_select $select
1883 * @return string HTML fragment
1884 */
1885 protected function render_single_select(single_select $select) {
1886 $select = clone($select);
1887 if (empty($select->formid)) {
1888 $select->formid = html_writer::random_id('single_select_f');
1889 }
1890
1891 $output = '';
1892 $params = $select->url->params();
1893 if ($select->method === 'post') {
1894 $params['sesskey'] = sesskey();
1895 }
1896 foreach ($params as $name=>$value) {
1897 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1898 }
1899
1900 if (empty($select->attributes['id'])) {
1901 $select->attributes['id'] = html_writer::random_id('single_select');
1902 }
1903
0b2cb132
PS
1904 if ($select->disabled) {
1905 $select->attributes['disabled'] = 'disabled';
1906 }
4d10e579 1907
a9967cf5
PS
1908 if ($select->tooltip) {
1909 $select->attributes['title'] = $select->tooltip;
1910 }
1911
7266bd3e
ARN
1912 $select->attributes['class'] = 'autosubmit';
1913 if ($select->class) {
1914 $select->attributes['class'] .= ' ' . $select->class;
1915 }
1916
a9967cf5 1917 if ($select->label) {
ecc5cc31 1918 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
a9967cf5
PS
1919 }
1920
1921 if ($select->helpicon instanceof help_icon) {
1922 $output .= $this->render($select->helpicon);
1923 }
a9967cf5
PS
1924 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1925
1926 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
ebc583e4 1927 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
a9967cf5
PS
1928
1929 $nothing = empty($select->nothing) ? false : key($select->nothing);
7266bd3e
ARN
1930 $this->page->requires->yui_module('moodle-core-formautosubmit',
1931 'M.core.init_formautosubmit',
1932 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1933 );
a9967cf5
PS
1934
1935 // then div wrapper for xhtml strictness
26acc814 1936 $output = html_writer::tag('div', $output);
a9967cf5
PS
1937
1938 // now the form itself around it
a12cd69c
DM
1939 if ($select->method === 'get') {
1940 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1941 } else {
1942 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1943 }
a9967cf5 1944 $formattributes = array('method' => $select->method,
a12cd69c 1945 'action' => $url,
a9967cf5 1946 'id' => $select->formid);
26acc814 1947 $output = html_writer::tag('form', $output, $formattributes);
4d10e579
PS
1948
1949 // and finally one more wrapper with class
26acc814 1950 return html_writer::tag('div', $output, array('class' => $select->class));
4d10e579
PS
1951 }
1952
1953 /**
ab08be98 1954 * Returns a form with a url select widget.
7a3c215b 1955 *
2fada290
MG
1956 * Theme developers: DO NOT OVERRIDE! Please override function
1957 * {@link core_renderer::render_url_select()} instead.
1958 *
4d10e579
PS
1959 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1960 * @param string $selected selected element
1961 * @param array $nothing
1962 * @param string $formid
1963 * @return string HTML fragment
1964 */
7a3c215b 1965 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
4d10e579
PS
1966 $select = new url_select($urls, $selected, $nothing, $formid);
1967 return $this->render($select);
1968 }
1969
1970 /**
ab08be98 1971 * Internal implementation of url_select rendering
7a3c215b
SH
1972 *
1973 * @param url_select $select
4d10e579
PS
1974 * @return string HTML fragment
1975 */
1976 protected function render_url_select(url_select $select) {
c422efcf
PS
1977 global $CFG;
1978
4d10e579
PS
1979 $select = clone($select);
1980 if (empty($select->formid)) {
1981 $select->formid = html_writer::random_id('url_select_f');
1982 }
1983
1984 if (empty($select->attributes['id'])) {
1985 $select->attributes['id'] = html_writer::random_id('url_select');
1986 }
1987
1988 if ($select->disabled) {
1989 $select->attributes['disabled'] = 'disabled';
1990 }
1991
1992 if ($select->tooltip) {
1993 $select->attributes['title'] = $select->tooltip;
1994 }
1995
1996 $output = '';
1997
1998 if ($select->label) {
ecc5cc31 1999 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
4d10e579
PS
2000 }
2001
50d6ad84
ARN
2002 $classes = array();
2003 if (!$select->showbutton) {
2004 $classes[] = 'autosubmit';
2005 }
7266bd3e 2006 if ($select->class) {
50d6ad84
ARN
2007 $classes[] = $select->class;
2008 }
2009 if (count($classes)) {
2010 $select->attributes['class'] = implode(' ', $classes);
7266bd3e
ARN
2011 }
2012
4d10e579
PS
2013 if ($select->helpicon instanceof help_icon) {
2014 $output .= $this->render($select->helpicon);
2015 }
2016
d4dcfc6b
DM
2017 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
2018 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
c422efcf
PS
2019 $urls = array();
2020 foreach ($select->urls as $k=>$v) {
d4dcfc6b
DM
2021 if (is_array($v)) {
2022 // optgroup structure
2023 foreach ($v as $optgrouptitle => $optgroupoptions) {
2024 foreach ($optgroupoptions as $optionurl => $optiontitle) {
2025 if (empty($optionurl)) {
2026 $safeoptionurl = '';
2027 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
2028 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
2029 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
2030 } else if (strpos($optionurl, '/') !== 0) {
2031 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
2032 continue;
2033 } else {
2034 $safeoptionurl = $optionurl;
2035 }
2036 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
2037 }
2038 }
2039 } else {
2040 // plain list structure
2041 if (empty($k)) {
2042 // nothing selected option
2043 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
2044 $k = str_replace($CFG->wwwroot, '', $k);
2045 } else if (strpos($k, '/') !== 0) {
2046 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
2047 continue;
2048 }
2049 $urls[$k] = $v;
2050 }
2051 }
2052 $selected = $select->selected;
2053 if (!empty($selected)) {
2054 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
2055 $selected = str_replace($CFG->wwwroot, '', $selected);
2056 } else if (strpos($selected, '/') !== 0) {
2057 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
c422efcf 2058 }
c422efcf
PS
2059 }
2060
4d10e579 2061 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
d4dcfc6b 2062 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
4d10e579 2063
15e48a1a
SM
2064 if (!$select->showbutton) {
2065 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
ebc583e4 2066 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
15e48a1a 2067 $nothing = empty($select->nothing) ? false : key($select->nothing);
7266bd3e
ARN
2068 $this->page->requires->yui_module('moodle-core-formautosubmit',
2069 'M.core.init_formautosubmit',
2070 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
2071 );
15e48a1a
SM
2072 } else {
2073 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
2074 }
4d10e579
PS
2075
2076 // then div wrapper for xhtml strictness
26acc814 2077 $output = html_writer::tag('div', $output);
4d10e579
PS
2078
2079 // now the form itself around it
2080 $formattributes = array('method' => 'post',
2081 'action' => new moodle_url('/course/jumpto.php'),
2082 'id' => $select->formid);
26acc814 2083 $output = html_writer::tag('form', $output, $formattributes);
a9967cf5
PS
2084
2085 // and finally one more wrapper with class
26acc814 2086 return html_writer::tag('div', $output, array('class' => $select->class));
a9967cf5
PS
2087 }
2088
d9c8f425 2089 /**
2090 * Returns a string containing a link to the user documentation.
2091 * Also contains an icon by default. Shown to teachers and admin only.
7a3c215b 2092 *
d9c8f425 2093 * @param string $path The page link after doc root and language, no leading slash.
2094 * @param string $text The text to be displayed for the link
afe3566c 2095 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
996b1e0c 2096 * @return string
d9c8f425 2097 */
afe3566c 2098 public function doc_link($path, $text = '', $forcepopup = false) {
8ae8bf8a
PS
2099 global $CFG;
2100
ae4086bd 2101 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
8ae8bf8a 2102
000c278c 2103 $url = new moodle_url(get_docs_url($path));
8ae8bf8a 2104
c80877aa 2105 $attributes = array('href'=>$url);
afe3566c
ARN
2106 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2107 $attributes['class'] = 'helplinkpopup';
d9c8f425 2108 }
1adaa404 2109
26acc814 2110 return html_writer::tag('a', $icon.$text, $attributes);
d9c8f425 2111 }
2112
000c278c 2113 /**
7a3c215b
SH
2114 * Return HTML for a pix_icon.
2115 *
2fada290
MG
2116 * Theme developers: DO NOT OVERRIDE! Please override function
2117 * {@link core_renderer::render_pix_icon()} instead.
2118 *
000c278c
PS
2119 * @param string $pix short pix name
2120 * @param string $alt mandatory alt attribute
eb557002 2121 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
000c278c
PS
2122 * @param array $attributes htm lattributes
2123 * @return string HTML fragment
2124 */
2125 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2126 $icon = new pix_icon($pix, $alt, $component, $attributes);
2127 return $this->render($icon);
2128 }
2129
2130 /**
7a3c215b
SH
2131 * Renders a pix_icon widget and returns the HTML to display it.
2132 *
000c278c
PS
2133 * @param pix_icon $icon
2134 * @return string HTML fragment
2135 */
ce0110bf 2136 protected function render_pix_icon(pix_icon $icon) {
eb42bb7e
DC
2137 $data = $icon->export_for_template($this);
2138 return $this->render_from_template('core/pix_icon', $data);
000c278c
PS
2139 }
2140
d63c5073 2141 /**
7a3c215b
SH
2142 * Return HTML to display an emoticon icon.
2143 *
d63c5073
DM
2144 * @param pix_emoticon $emoticon
2145 * @return string HTML fragment
2146 */
2147 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2148 $attributes = $emoticon->attributes;
2149 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
2150 return html_writer::empty_tag('img', $attributes);
2151 }
2152
a09aeee4 2153 /**
7a3c215b
SH
2154 * Produces the html that represents this rating in the UI
2155 *
2156 * @param rating $rating the page object on which this rating will appear
2157 * @return string
2158 */
a09aeee4 2159 function render_rating(rating $rating) {
7ac928a7 2160 global $CFG, $USER;
a09aeee4 2161
2b04c41c 2162 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
63e87951
AD
2163 return null;//ratings are turned off
2164 }
2165
2b04c41c
SH
2166 $ratingmanager = new rating_manager();
2167 // Initialise the JavaScript so ratings can be done by AJAX.
2168 $ratingmanager->initialise_rating_javascript($this->page);
a09aeee4 2169
63e87951
AD
2170 $strrate = get_string("rate", "rating");
2171 $ratinghtml = ''; //the string we'll return
2172
2b04c41c
SH
2173 // permissions check - can they view the aggregate?
2174 if ($rating->user_can_view_aggregate()) {
a09aeee4 2175
2b04c41c
SH
2176 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2177 $aggregatestr = $rating->get_aggregate_string();
a09aeee4 2178
6278ce45 2179 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2b04c41c 2180 if ($rating->count > 0) {
6278ce45 2181 $countstr = "({$rating->count})";
d251b259 2182 } else {
6278ce45 2183 $countstr = '-';
d251b259 2184 }
6278ce45 2185 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
63e87951 2186
c6de9cef 2187 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
d251b259 2188 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2b04c41c
SH
2189
2190 $nonpopuplink = $rating->get_view_ratings_url();
2191 $popuplink = $rating->get_view_ratings_url(true);
a09aeee4 2192
d251b259 2193 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
c6de9cef 2194 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
d251b259 2195 } else {
c6de9cef 2196 $ratinghtml .= $aggregatehtml;
a09aeee4 2197 }
d251b259 2198 }
a09aeee4 2199
d251b259 2200 $formstart = null;
2b04c41c
SH
2201 // if the item doesn't belong to the current user, the user has permission to rate
2202 // and we're within the assessable period
2203 if ($rating->user_can_rate()) {
771b3fbe 2204
2b04c41c
SH
2205 $rateurl = $rating->get_rate_url();
2206 $inputs = $rateurl->params();
771b3fbe 2207
2b04c41c
SH
2208 //start the rating form
2209 $formattrs = array(
2210 'id' => "postrating{$rating->itemid}",
2211 'class' => 'postratingform',
2212 'method' => 'post',
2213 'action' => $rateurl->out_omit_querystring()
2214 );
2215 $formstart = html_writer::start_tag('form', $formattrs);
2216 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2217
2218 // add the hidden inputs
2219 foreach ($inputs as $name => $value) {
2220 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2221 $formstart .= html_writer::empty_tag('input', $attributes);
2222 }
3180bc2c 2223
d251b259
AD
2224 if (empty($ratinghtml)) {
2225 $ratinghtml .= $strrate.': ';
2226 }
d251b259 2227 $ratinghtml = $formstart.$ratinghtml;
63e87951 2228
2b04c41c
SH
2229 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2230 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
ecc5cc31 2231 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2b04c41c 2232 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
a09aeee4 2233
d251b259 2234 //output submit button
771b3fbe
AD
2235 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2236
2b04c41c 2237 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
771b3fbe 2238 $ratinghtml .= html_writer::empty_tag('input', $attributes);
a09aeee4 2239
2b04c41c 2240 if (!$rating->settings->scale->isnumeric) {
eaf52ff0
MN
2241 // If a global scale, try to find current course ID from the context
2242 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2243 $courseid = $coursecontext->instanceid;
2244 } else {
2245 $courseid = $rating->settings->scale->courseid;
2246 }
2247 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
a09aeee4 2248 }
771b3fbe
AD
2249 $ratinghtml .= html_writer::end_tag('span');
2250 $ratinghtml .= html_writer::end_tag('div');
2251 $ratinghtml .= html_writer::end_tag('form');
a09aeee4
AD
2252 }
2253
63e87951 2254 return $ratinghtml;
a09aeee4
AD
2255 }
2256
7a3c215b 2257 /**
d9c8f425 2258 * Centered heading with attached help button (same title text)
7a3c215b
SH
2259 * and optional icon attached.
2260 *
4bcc5118 2261 * @param string $text A heading text
53a78cef 2262 * @param string $helpidentifier The keyword that defines a help page
4bcc5118
PS
2263 * @param string $component component name
2264 * @param string|moodle_url $icon
2265 * @param string $iconalt icon alt text
699e2fd0
RW
2266 * @param int $level The level of importance of the heading. Defaulting to 2
2267 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
d9c8f425 2268 * @return string HTML fragment
2269 */
699e2fd0 2270 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
4bcc5118
PS
2271 $image = '';
2272 if ($icon) {
8ef1aa40 2273 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
d9c8f425 2274 }
4bcc5118 2275
259c165d
PS
2276 $help = '';
2277 if ($helpidentifier) {
2278 $help = $this->help_icon($helpidentifier, $component);
2279 }
4bcc5118 2280
699e2fd0 2281 return $this->heading($image.$text.$help, $level, $classnames);
d9c8f425 2282 }
2283
2284 /**
7a3c215b 2285 * Returns HTML to display a help icon.
d9c8f425 2286 *
cb616be8 2287 * @deprecated since Moodle 2.0
bf11293a 2288 */
596509e4 2289 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
a6d81a73 2290 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
d9c8f425 2291 }
2292
259c165d 2293 /**
7a3c215b 2294 * Returns HTML to display a help icon.
259c165d 2295 *
2fada290
MG
2296 * Theme developers: DO NOT OVERRIDE! Please override function
2297 * {@link core_renderer::render_help_icon()} instead.
2298 *
259c165d
PS
2299 * @param string $identifier The keyword that defines a help page
2300 * @param string $component component name
2301 * @param string|bool $linktext true means use $title as link text, string means link text value
2302 * @return string HTML fragment
2303 */
2304 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2cf81209 2305 $icon = new help_icon($identifier, $component);
259c165d
PS
2306 $icon->diag_strings();
2307 if ($linktext === true) {
2308 $icon->linktext = get_string($icon->identifier, $icon->component);
2309 } else if (!empty($linktext)) {
2310 $icon->linktext = $linktext;
2311 }
2312 return $this->render($icon);
2313 }
2314
2315 /**
2316 * Implementation of user image rendering.
7a3c215b 2317 *
3d3fae72 2318 * @param help_icon $helpicon A help icon instance
259c165d
PS
2319 * @return string HTML fragment
2320 */
2321 protected function render_help_icon(help_icon $helpicon) {
2322 global $CFG;
2323
2324 // first get the help image icon
2325 $src = $this->pix_url('help');
2326
2327 $title = get_string($helpicon->identifier, $helpicon->component);
2328
2329 if (empty($helpicon->linktext)) {
cab2c7ea 2330 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
259c165d
PS
2331 } else {
2332 $alt = get_string('helpwiththis');
2333 }
2334
2335 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
2336 $output = html_writer::empty_tag('img', $attributes);
2337
2338 // add the link text if given
2339 if (!empty($helpicon->linktext)) {
2340 // the spacing has to be done through CSS
2341 $output .= $helpicon->linktext;
2342 }
2343
69542fb3
PS
2344 // now create the link around it - we need https on loginhttps pages
2345 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
259c165d
PS
2346
2347 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
2348 $title = get_string('helpprefix2', '', trim($title, ". \t"));
2349
e88419a2 2350 $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true', 'target'=>'_blank');
259c165d
PS
2351 $output = html_writer::tag('a', $output, $attributes);
2352
2353 // and finally span
238b8bc9 2354 return html_writer::tag('span', $output, array('class' => 'helptooltip'));
259c165d
PS
2355 }
2356
d9c8f425 2357 /**
7a3c215b 2358 * Returns HTML to display a scale help icon.
d9c8f425 2359 *
4bcc5118 2360 * @param int $courseid
7a3c215b
SH
2361 * @param stdClass $scale instance
2362 * @return string HTML fragment
d9c8f425 2363 */
4bcc5118
PS
2364 public function help_icon_scale($courseid, stdClass $scale) {
2365 global $CFG;
02f64f97 2366
4bcc5118 2367 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
02f64f97 2368
0029a917 2369 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
02f64f97 2370
68bf577b
AD
2371 $scaleid = abs($scale->id);
2372
2373 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
230ec401 2374 $action = new popup_action('click', $link, 'ratingscale');
02f64f97 2375
26acc814 2376 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
d9c8f425 2377 }
2378
2379 /**
2380 * Creates and returns a spacer image with optional line break.
2381 *
3d3fae72
SH
2382 * @param array $attributes Any HTML attributes to add to the spaced.
2383 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2384 * laxy do it with CSS which is a much better solution.
d9c8f425 2385 * @return string HTML fragment
2386 */
0029a917
PS
2387 public function spacer(array $attributes = null, $br = false) {
2388 $attributes = (array)$attributes;
2389 if (empty($attributes['width'])) {
2390 $attributes['width'] = 1;
1ba862ec 2391 }
e1a5a9cc 2392 if (empty($attributes['height'])) {
0029a917 2393 $attributes['height'] = 1;
d9c8f425 2394 }
0029a917 2395 $attributes['class'] = 'spacer';
d9c8f425 2396
0029a917 2397 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
b65bfc3e 2398
0029a917 2399 if (!empty($br)) {
1ba862ec
PS
2400 $output .= '<br />';
2401 }
d9c8f425 2402
2403 return $output;
2404 }
2405
d9c8f425 2406 /**
7a3c215b 2407 * Returns HTML to display the specified user's avatar.
d9c8f425 2408 *
5d0c95a5 2409 * User avatar may be obtained in two ways:
d9c8f425 2410 * <pre>
812dbaf7
PS
2411 * // Option 1: (shortcut for simple cases, preferred way)
2412 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2413 * $OUTPUT->user_picture($user, array('popup'=>true));
2414 *
5d0c95a5
PS
2415 * // Option 2:
2416 * $userpic = new user_picture($user);
d9c8f425 2417 * // Set properties of $userpic
812dbaf7 2418 * $userpic->popup = true;
5d0c95a5 2419 * $OUTPUT->render($userpic);
d9c8f425 2420 * </pre>
2421 *
2fada290
MG
2422 * Theme developers: DO NOT OVERRIDE! Please override function
2423 * {@link core_renderer::render_user_picture()} instead.
2424 *
7a3c215b 2425 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
812dbaf7 2426 * If any of these are missing, the database is queried. Avoid this
d9c8f425 2427 * if at all possible, particularly for reports. It is very bad for performance.
812dbaf7
PS
2428 * @param array $options associative array with user picture options, used only if not a user_picture object,
2429 * options are:
2430 * - courseid=$this->page->course->id (course id of user profile in link)
2431 * - size=35 (size of image)
2432 * - link=true (make image clickable - the link leads to user profile)
2433 * - popup=false (open in popup)
2434 * - alttext=true (add image alt attribute)
5d0c95a5 2435 * - class = image class attribute (default 'userpicture')
e4a1efcb 2436 * - visibletoscreenreaders=true (whether to be visible to screen readers)
d9c8f425 2437 * @return string HTML fragment
2438 */
5d0c95a5
PS
2439 public function user_picture(stdClass $user, array $options = null) {
2440 $userpicture = new user_picture($user);
2441 foreach ((array)$options as $key=>$value) {
2442 if (array_key_exists($key, $userpicture)) {
2443 $userpicture->$key = $value;
2444 }
2445 }
2446 return $this->render($userpicture);
2447 }
2448
2449 /**
2450 * Internal implementation of user image rendering.
7a3c215b 2451 *
5d0c95a5
PS
2452 * @param user_picture $userpicture
2453 * @return string
2454 */
2455 protected function render_user_picture(user_picture $userpicture) {
2456 global $CFG, $DB;
812dbaf7 2457
5d0c95a5
PS
2458 $user = $userpicture->user;
2459
2460 if ($userpicture->alttext) {
2461 if (!empty($user->imagealt)) {
2462 $alt = $user->imagealt;
2463 } else {
2464 $alt = get_string('pictureof', '', fullname($user));
2465 }
d9c8f425 2466 } else {
97c10099 2467 $alt = '';
5d0c95a5
PS
2468 }
2469
2470 if (empty($userpicture->size)) {
5d0c95a5
PS
2471 $size = 35;
2472 } else if ($userpicture->size === true or $userpicture->size == 1) {
5d0c95a5 2473 $size = 100;
5d0c95a5 2474 } else {
5d0c95a5 2475 $size = $userpicture->size;
d9c8f425 2476 }
2477
5d0c95a5 2478 $class = $userpicture->class;
d9c8f425 2479
4d254790 2480 if ($user->picture == 0) {
5d0c95a5 2481 $class .= ' defaultuserpic';
5d0c95a5 2482 }
d9c8f425 2483
871a3ec5
SH
2484 $src = $userpicture->get_url($this->page, $this);
2485
29cf6631 2486 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
e4a1efcb
JC
2487 if (!$userpicture->visibletoscreenreaders) {
2488 $attributes['role'] = 'presentation';
2489 }
2490
5d0c95a5 2491 // get the image html output fisrt
0e35ba6f 2492 $output = html_writer::empty_tag('img', $attributes);
5d0c95a5
PS
2493
2494 // then wrap it in link if needed
2495 if (!$userpicture->link) {
2496 return $output;
d9c8f425 2497 }
2498
5d0c95a5
PS
2499 if (empty($userpicture->courseid)) {
2500 $courseid = $this->page->course->id;
2501 } else {
2502 $courseid = $userpicture->courseid;
2503 }
2504
03d9401e
MD
2505 if ($courseid == SITEID) {
2506 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2507 } else {
2508 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2509 }
5d0c95a5
PS
2510
2511 $attributes = array('href'=>$url);
e4a1efcb 2512 if (!$userpicture->visibletoscreenreaders) {
e4a1efcb
JC
2513 $attributes['tabindex'] = '-1';
2514 $attributes['aria-hidden'] = 'true';
2515 }
5d0c95a5
PS
2516
2517 if ($userpicture->popup) {
2518 $id = html_writer::random_id('userpicture');
2519 $attributes['id'] = $id;
c80877aa 2520 $this->add_action_handler(new popup_action('click', $url), $id);
5d0c95a5
PS
2521 }
2522
26acc814 2523 return html_writer::tag('a', $output, $attributes);
d9c8f425 2524 }
b80ef420 2525
b80ef420
DC
2526 /**
2527 * Internal implementation of file tree viewer items rendering.
7a3c215b 2528 *
b80ef420
DC
2529 * @param array $dir
2530 * @return string
2531 */
2532 public function htmllize_file_tree($dir) {
2533 if (empty($dir['subdirs']) and empty($dir['files'])) {
2534 return '';
2535 }
2536 $result = '<ul>';
2537 foreach ($dir['subdirs'] as $subdir) {
2538 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2539 }
2540 foreach ($dir['files'] as $file) {
2541 $filename = $file->get_filename();
2542 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2543 }
2544 $result .= '</ul>';
2545
2546 return $result;
2547 }
7a3c215b 2548
bb496de7 2549 /**
7a3c215b 2550 * Returns HTML to display the file picker
bb496de7
DC
2551 *
2552 * <pre>
2553 * $OUTPUT->file_picker($options);
2554 * </pre>
2555 *
2fada290
MG
2556 * Theme developers: DO NOT OVERRIDE! Please override function
2557 * {@link core_renderer::render_file_picker()} instead.
2558 *
bb496de7
DC
2559 * @param array $options associative array with file manager options
2560 * options are:
2561 * maxbytes=>-1,
2562 * itemid=>0,
2563 * client_id=>uniqid(),
2564 * acepted_types=>'*',
2565 * return_types=>FILE_INTERNAL,
2566 * context=>$PAGE->context
2567 * @return string HTML fragment
2568 */
2569 public function file_picker($options) {
2570 $fp = new file_picker($options);
2571 return $this->render($fp);
2572 }
7a3c215b 2573
b80ef420
DC
2574 /**
2575 * Internal implementation of file picker rendering.
7a3c215b 2576 *
b80ef420
DC
2577 * @param file_picker $fp
2578 * @return string
2579 */
bb496de7
DC
2580 public function render_file_picker(file_picker $fp) {
2581 global $CFG, $OUTPUT, $USER;
2582 $options = $fp->options;
2583 $client_id = $options->client_id;
2584 $strsaved = get_string('filesaved', 'repository');
2585 $straddfile = get_string('openpicker', 'repository');
2586 $strloading = get_string('loading', 'repository');
adce0230 2587 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
906e7d89 2588 $strdroptoupload = get_string('droptoupload', 'moodle');
bb496de7
DC
2589 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2590
2591 $currentfile = $options->currentfile;
2592 if (empty($currentfile)) {
322945e9
FM
2593 $currentfile = '';
2594 } else {
2595 $currentfile .= ' - ';
bb496de7 2596 }
b817205b
DC
2597 if ($options->maxbytes) {
2598 $size = $options->maxbytes;
2599 } else {
2600 $size = get_max_upload_file_size();
2601 }
513aed3c 2602 if ($size == -1) {
831399c4 2603 $maxsize = '';
513aed3c
DC
2604 } else {
2605 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2606 }
f50a61fb 2607 if ($options->buttonname) {
4b72f9eb
AW
2608 $buttonname = ' name="' . $options->buttonname . '"';
2609 } else {
2610 $buttonname = '';
2611 }
bb496de7
DC
2612 $html = <<<EOD
2613<div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2614$icon_progress
2615</div>
2616<div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2617 <div>
c81f3328 2618 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
fa7f2a45 2619 <span> $maxsize </span>
bb496de7
DC
2620 </div>
2621EOD;
2622 if ($options->env != 'url') {
2623 $html .= <<<EOD
50597880 2624 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
a9352f1f 2625 <div class="filepicker-filename">
08a6a19d 2626 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
0f94289c 2627 <div class="dndupload-progressbars"></div>
a9352f1f 2628 </div>
08a6a19d 2629 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
f08fac7c 2630 </div>
bb496de7
DC
2631EOD;
2632 }
2633 $html .= '</div>';
2634 return $html;
2635 }
d9c8f425 2636
2637 /**
7a3c215b 2638 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
d9c8f425 2639 *
2640 * @param string $cmid the course_module id.
2641 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2642 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2643 */
2644 public function update_module_button($cmid, $modulename) {
2645 global $CFG;
b0c6dc1c 2646 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
d9c8f425 2647 $modulename = get_string('modulename', $modulename);
2648 $string = get_string('updatethis', '', $modulename);
3ba60ee1
PS
2649 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2650 return $this->single_button($url, $string);
d9c8f425 2651 } else {
2652 return '';
2653 }
2654 }
2655
2656 /**
7a3c215b
SH
2657 * Returns HTML to display a "Turn editing on/off" button in a form.
2658 *
d9c8f425 2659 * @param moodle_url $url The URL + params to send through when clicking the button
2660 * @return string HTML the button
2661 */
2662 public function edit_button(moodle_url $url) {
3362dfdc
EL
2663
2664 $url->param('sesskey', sesskey());
2665 if ($this->page->user_is_editing()) {
2666 $url->param('edit', 'off');
2667 $editstring = get_string('turneditingoff');
d9c8f425 2668 } else {
3362dfdc
EL
2669 $url->param('edit', 'on');
2670 $editstring = get_string('turneditingon');
d9c8f425 2671 }
2672
3362dfdc 2673 return $this->single_button($url, $editstring);
d9c8f425 2674 }
2675
d9c8f425 2676 /**
7a3c215b 2677 * Returns HTML to display a simple button to close a window
d9c8f425 2678 *
d9c8f425 2679 * @param string $text The lang string for the button's label (already output from get_string())
3ba60ee1 2680 * @return string html fragment
d9c8f425 2681 */
7a5c78e0 2682 public function close_window_button($text='') {
d9c8f425 2683 if (empty($text)) {
2684 $text = get_string('closewindow');
2685 }
a6855934
PS
2686 $button = new single_button(new moodle_url('#'), $text, 'get');
2687 $button->add_action(new component_action('click', 'close_window'));
3ba60ee1
PS
2688
2689 return $this->container($this->render($button), 'closewindow');
d9c8f425 2690 }
2691
d9c8f425 2692 /**
2693 * Output an error message. By default wraps the error message in <span class="error">.
2694 * If the error message is blank, nothing is output.
7a3c215b 2695 *
d9c8f425 2696 * @param string $message the error message.
2697 * @return string the HTML to output.
2698 */
2699 public function error_text($message) {
2700 if (empty($message)) {
2701 return '';
2702 }
3246648b 2703 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
26acc814 2704 return html_writer::tag('span', $message, array('class' => 'error'));
d9c8f425 2705 }
2706
2707 /**
2708 * Do not call this function directly.
2709 *
f8129210 2710 * To terminate the current script with a fatal error, call the {@link print_error}
d9c8f425 2711 * function, or throw an exception. Doing either of those things will then call this
2712 * function to display the error, before terminating the execution.
2713 *
2714 * @param string $message The message to output
2715 * @param string $moreinfourl URL where more info can be found about the error
2716 * @param string $link Link for the Continue button
2717 * @param array $backtrace The execution backtrace
2718 * @param string $debuginfo Debugging information
d9c8f425 2719 * @return string the HTML to output.
2720 */
83267ec0 2721 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
6bd8d7e7 2722 global $CFG;
d9c8f425 2723
2724 $output = '';
6f8f4d83 2725 $obbuffer = '';
e57c283d 2726
d9c8f425 2727 if ($this->has_started()) {
50764d37
PS
2728 // we can not always recover properly here, we have problems with output buffering,
2729 // html tables, etc.
d9c8f425 2730 $output .= $this->opencontainers->pop_all_but_last();
50764d37 2731
d9c8f425 2732 } else {
50764d37
PS
2733 // It is really bad if library code throws exception when output buffering is on,
2734 // because the buffered text would be printed before our start of page.
2735 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
6bd8d7e7 2736 error_reporting(0); // disable notices from gzip compression, etc.
50764d37 2737 while (ob_get_level() > 0) {
2cadd443
PS
2738 $buff = ob_get_clean();
2739 if ($buff === false) {
2740 break;
2741 }
2742 $obbuffer .= $buff;
50764d37 2743 }
6bd8d7e7 2744 error_reporting($CFG->debug);
6f8f4d83 2745
f22f1caf
PS
2746 // Output not yet started.
2747 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2748 if (empty($_SERVER['HTTP_RANGE'])) {
2749 @header($protocol . ' 404 Not Found');
2750 } else {
2751 // Must stop byteserving attempts somehow,
2752 // this is weird but Chrome PDF viewer can be stopped only with 407!
2753 @header($protocol . ' 407 Proxy Authentication Required');
85309744 2754 }
f22f1caf 2755
eb5bdb35 2756 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
7fde1e4b 2757 $this->page->set_url('/'); // no url
191b267b 2758 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
dcfb9b78 2759 $this->page->set_title(get_string('error'));
8093188f 2760 $this->page->set_heading($this->page->course->fullname);
d9c8f425 2761 $output .= $this->header();
2762 }
2763
2764 $message = '<p class="errormessage">' . $message . '</p>'.
2765 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2766 get_string('moreinformation') . '</a></p>';
1ad8143a
PS
2767 if (empty($CFG->rolesactive)) {
2768 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2769 //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.
2770 }
4c2892c6 2771 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
d9c8f425 2772
96f81ea3 2773 if ($CFG->debugdeveloper) {
6f8f4d83 2774 if (!empty($debuginfo)) {
c5d18164
PS
2775 $debuginfo = s($debuginfo); // removes all nasty JS
2776 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2777 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
6f8f4d83
PS
2778 }
2779 if (!empty($backtrace)) {
2780 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2781 }
2782 if ($obbuffer !== '' ) {
2783 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2784 }
d9c8f425 2785 }
2786
3efe6bbb
PS
2787 if (empty($CFG->rolesactive)) {
2788 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2789 } else if (!empty($link)) {
d9c8f425 2790 $output .= $this->continue_button($link);
2791 }
2792
2793 $output .= $this->footer();
2794
2795 // Padding to encourage IE to display our error page, rather than its own.
2796 $output .= str_repeat(' ', 512);
2797
2798 return $output;
2799 }
2800
2801 /**
24346803 2802 * Output a notification (that is, a status message about something that has just happened).
d9c8f425 2803 *
0346323c
AN
2804 * Note: \core\notification::add() may be more suitable for your usage.
2805 *
24346803
AN
2806 * @param string $message The message to print out.
2807 * @param string $type The type of notification. See constants on \core\output\notification.
d9c8f425 2808 * @return string the HTML to output.
2809 */
24346803
AN
2810 public function notification($message, $type = null) {
2811 $typemappings = [
2812 // Valid types.
2813 'success' => \core\output\notification::NOTIFY_SUCCESS,
2814 'info' => \core\output\notification::NOTIFY_INFO,
2815 'warning' => \core\output\notification::NOTIFY_WARNING,
2816 'error' => \core\output\notification::NOTIFY_ERROR,
2817
2818 // Legacy types mapped to current types.
2819 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2820 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2821 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2822 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2823 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2824 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2825 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2826 ];
2827
2828 $extraclasses = [];
2829
2830 if ($type) {
2831 if (strpos($type, ' ') === false) {
2832 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2833 if (isset($typemappings[$type])) {
2834 $type = $typemappings[$type];
2835 } else {
2836 // The value provided did not match a known type. It must be an extra class.
2837 $extraclasses = [$type];
2838 }
2839 } else {
2840 // Identify what type of notification this is.
2841 $classarray = explode(' ', self::prepare_classes($type));
2842
2843 // Separate out the type of notification from the extra classes.
2844 foreach ($classarray as $class) {
2845 if (isset($typemappings[$class])) {
2846 $type = $typemappings[$class];
2847 } else {
2848 $extraclasses[] = $class;
2849 }
263fb9d1
JC
2850 }
2851 }
2852 }
2853
24346803
AN
2854 $notification = new \core\output\notification($message, $type);
2855 if (count($extraclasses)) {
2856 $notification->set_extra_classes($extraclasses);
2857 }
263fb9d1 2858
24346803
AN
2859 // Return the rendered template.
2860 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
263fb9d1
JC
2861 }
2862
2863 /**
2864 * Output a notification at a particular level - in this case, NOTIFY_PROBLEM.
2865 *
2866 * @param string $message the message to print out
2867 * @return string HTML fragment.
24346803
AN
2868 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2869 * @todo MDL-53113 This will be removed in Moodle 3.5.
2870 * @see \core\output\notification
263fb9d1
JC
2871 */
2872 public function notify_problem($message) {
24346803 2873 debugging(__FUNCTION__ . ' is deprecated.' .
0346323c 2874 'Please use \core\notification::add, or \core\output\notification as required',
24346803
AN
2875 DEBUG_DEVELOPER);
2876 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_ERROR);
263fb9d1
JC
2877 return $this->render($n);
2878 }
2879
2880 /**
2881 * Output a notification at a particular level - in this case, NOTIFY_SUCCESS.
2882 *
2883 * @param string $message the message to print out
2884 * @return string HTML fragment.
24346803
AN
2885 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2886 * @todo MDL-53113 This will be removed in Moodle 3.5.
2887 * @see \core\output\notification
263fb9d1
JC
2888 */
2889 public function notify_success($message) {
24346803 2890 debugging(__FUNCTION__ . ' is deprecated.' .
0346323c 2891 'Please use \core\notification::add, or \core\output\notification as required',
24346803 2892 DEBUG_DEVELOPER);
263fb9d1
JC
2893 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_SUCCESS);
2894 return $this->render($n);
2895 }
2896
2897 /**
2898 * Output a notification at a particular level - in this case, NOTIFY_MESSAGE.
2899 *
2900 * @param string $message the message to print out
2901 * @return string HTML fragment.
24346803
AN
2902 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2903 * @todo MDL-53113 This will be removed in Moodle 3.5.
2904 * @see \core\output\notification
263fb9d1
JC
2905 */
2906 public function notify_message($message) {
24346803 2907 debugging(__FUNCTION__ . ' is deprecated.' .
0346323c 2908 'Please use \core\notification::add, or \core\output\notification as required',
24346803
AN
2909 DEBUG_DEVELOPER);
2910 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_INFO);
263fb9d1
JC
2911 return $this->render($n);
2912 }
2913
2914 /**
2915 * Output a notification at a particular level - in this case, NOTIFY_REDIRECT.
2916 *
2917 * @param string $message the message to print out
2918 * @return string HTML fragment.
24346803
AN
2919 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2920 * @todo MDL-53113 This will be removed in Moodle 3.5.
2921 * @see \core\output\notification
263fb9d1
JC
2922 */
2923 public function notify_redirect($message) {
24346803 2924 debugging(__FUNCTION__ . ' is deprecated.' .
0346323c 2925 'Please use \core\notification::add, or \core\output\notification as required',
24346803
AN
2926 DEBUG_DEVELOPER);
2927 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_INFO);
263fb9d1
JC
2928 return $this->render($n);
2929 }
2930
2931 /**
2932 * Render a notification (that is, a status message about something that has
2933 * just happened).
2934 *
2935 * @param \core\output\notification $notification the notification to print out
2936 * @return string the HTML to output.
2937 */
2938 protected function render_notification(\core\output\notification $notification) {
24346803 2939 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
d9c8f425 2940 }
2941
2942 /**
7a3c215b 2943 * Returns HTML to display a continue button that goes to a particular URL.
d9c8f425 2944 *
3ba60ee1 2945 * @param string|moodle_url $url The url the button goes to.
d9c8f425 2946 * @return string the HTML to output.
2947 */
3ba60ee1
PS
2948 public function continue_button($url) {
2949 if (!($url instanceof moodle_url)) {
2950 $url = new moodle_url($url);
d9c8f425 2951 }
3ba60ee1
PS
2952 $button = new single_button($url, get_string('continue'), 'get');
2953 $button->class = 'continuebutton';
d9c8f425 2954
3ba60ee1 2955 return $this->render($button);
d9c8f425 2956 }
2957
2958 /**
7a3c215b 2959 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
d9c8f425 2960 *
2fada290
MG
2961 * Theme developers: DO NOT OVERRIDE! Please override function
2962 * {@link core_renderer::render_paging_bar()} instead.
2963 *
71c03ac1 2964 * @param int $totalcount The total number of entries available to be paged through
929d7a83
PS
2965 * @param int $page The page you are currently viewing
2966 * @param int $perpage The number of entries that should be shown per page
2967 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2968 * @param string $pagevar name of page parameter that holds the page number
d9c8f425 2969 * @return string the HTML to output.
2970 */
929d7a83
PS
2971 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2972 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2973 return $this->render($pb);
2974 }
2975
2976 /**
2977 * Internal implementation of paging bar rendering.
7a3c215b 2978 *
929d7a83
PS
2979 * @param paging_bar $pagingbar
2980 * @return string
2981 */
2982 protected function render_paging_bar(paging_bar $pagingbar) {
d9c8f425 2983 $output = '';
2984 $pagingbar = clone($pagingbar);
34059565 2985 $pagingbar->prepare($this, $this->page, $this->target);
d9c8f425 2986
2987 if ($pagingbar->totalcount > $pagingbar->perpage) {
2988 $output .= get_string('page') . ':';
2989
2990 if (!empty($pagingbar->previouslink)) {
b146b6a8 2991 $output .= ' (' . $pagingbar->previouslink . ') ';
d9c8f425 2992 }
2993
2994 if (!empty($pagingbar->firstlink)) {
b146b6a8 2995 $output .= ' ' . $pagingbar->firstlink . ' ...';
d9c8f425 2996 }
2997
2998 foreach ($pagingbar->pagelinks as $link) {
b146b6a8 2999 $output .= " $link";
d9c8f425 3000 }
3001
3002 if (!empty($pagingbar->lastlink)) {
7ca2c19b 3003 $output .= ' ... ' . $pagingbar->lastlink . ' ';
d9c8f425 3004 }
3005
3006 if (!empty($pagingbar->nextlink)) {
b146b6a8 3007 $output .= ' (' . $pagingbar->nextlink . ')';
d9c8f425 3008 }
3009 }
3010
26acc814 3011 return html_writer::tag('div', $output, array('class' => 'paging'));
d9c8f425 3012 }
3013
d9c8f425 3014 /**
3015 * Output the place a skip link goes to.
7a3c215b 3016 *
d9c8f425 3017 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3018 * @return string the HTML to output.
3019 */
fe213365 3020 public function skip_link_target($id = null) {
9e8d0842 3021 return html_writer::span('', '', array('id' => $id));
d9c8f425 3022 }
3023
3024 /**
3025 * Outputs a heading
7a3c215b 3026 *
d9c8f425 3027 * @param string $text The text of the heading
3028 * @param int $level The level of importance of the heading. Defaulting to 2
699e2fd0 3029 * @param string $classes A space-separated list of CSS classes. Defaulting to null
d9c8f425 3030 * @param string $id An optional ID
3031 * @return string the HTML to output.
3032 */
699e2fd0 3033 public function heading($text, $level = 2, $classes = null, $id = null) {
d9c8f425 3034 $level = (integer) $level;
3035 if ($level < 1 or $level > 6) {
3036 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3037 }
26acc814 3038 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
d9c8f425 3039 }
3040
3041 /**
3042 * Outputs a box.
7a3c215b 3043 *
d9c8f425 3044 * @param string $contents The contents of the box
3045 * @param string $classes A space-separated list of CSS classes
3046 * @param string $id An optional ID
3e76c7fa 3047 * @param array $attributes An array of other attributes to give the box.
d9c8f425 3048 * @return string the HTML to output.
3049 */
3e76c7fa
SH
3050 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3051 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
d9c8f425 3052 }
3053
3054 /**
3d3fae72 3055 * Outputs the opening section of a box.
7a3c215b 3056 *
d9c8f425 3057 * @param string $classes A space-separated list of CSS classes
3058 * @param string $id An optional ID
3e76c7fa 3059 * @param array $attributes An array of other attributes to give the box.
d9c8f425 3060 * @return string the HTML to output.
3061 */
3e76c7fa 3062 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
5d0c95a5 3063 $this->opencontainers->push('box', html_writer::end_tag('div'));
3e76c7fa
SH
3064 $attributes['id'] = $id;