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