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