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