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