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