MDL-69395 theme_boost: improve colour contrast for form input fields
[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';
4394f9e3 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
5ebd1fb9
BH
1388 // Give plugins an opportunity to touch the page before JS is finalized.
1389 $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1390 foreach ($pluginswithfunction as $plugins) {
1391 foreach ($plugins as $function) {
1392 $function();
1393 }
1394 }
1395
f6794ace 1396 $output = $this->container_end_all(true);
4d2ee4c2 1397
d9c8f425 1398 $footer = $this->opencontainers->pop('header/footer');
1399
d5a8d9aa 1400 if (debugging() and $DB and $DB->is_transaction_started()) {
03221650 1401 // TODO: MDL-20625 print warning - transaction will be rolled back
d5a8d9aa
PS
1402 }
1403
d9c8f425 1404 // Provide some performance info if required
1405 $performanceinfo = '';
1406 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
1407 $perf = get_performance_info();
d9c8f425 1408 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
1409 $performanceinfo = $perf['html'];
1410 }
1411 }
58a3a34e
DM
1412
1413 // We always want performance data when running a performance test, even if the user is redirected to another page.
1414 if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1415 $footer = $this->unique_performance_info_token . $footer;
1416 }
72009b87 1417 $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
d9c8f425 1418
1dcd0d34
TH
1419 // Only show notifications when the current page has a context id.
1420 if (!empty($this->page->context->id)) {
38870d60 1421 $this->page->requires->js_call_amd('core/notification', 'init', array(
1dcd0d34 1422 $this->page->context->id,
eff7ef2c
MM
1423 \core\notification::fetch_as_array($this),
1424 isloggedin()
38870d60
MN
1425 ));
1426 }
72009b87 1427 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
d9c8f425 1428
1429 $this->page->set_state(moodle_page::STATE_DONE);
d9c8f425 1430
1431 return $output . $footer;
1432 }
1433
f6794ace
PS
1434 /**
1435 * Close all but the last open container. This is useful in places like error
1436 * handling, where you want to close all the open containers (apart from <body>)
1437 * before outputting the error message.
7a3c215b 1438 *
f6794ace
PS
1439 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1440 * developer debug warning if it isn't.
1441 * @return string the HTML required to close any open containers inside <body>.
1442 */
1443 public function container_end_all($shouldbenone = false) {
1444 return $this->opencontainers->pop_all_but_last($shouldbenone);
1445 }
1446
fdd4b9a5
MG
1447 /**
1448 * Returns course-specific information to be output immediately above content on any course page
1449 * (for the current course)
1450 *
1451 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1452 * @return string
1453 */
1454 public function course_content_header($onlyifnotcalledbefore = false) {
1455 global $CFG;
fdd4b9a5
MG
1456 static $functioncalled = false;
1457 if ($functioncalled && $onlyifnotcalledbefore) {
1458 // we have already output the content header
1459 return '';
1460 }
0346323c
AN
1461
1462 // Output any session notification.
1463 $notifications = \core\notification::fetch();
1464
1465 $bodynotifications = '';
1466 foreach ($notifications as $notification) {
1467 $bodynotifications .= $this->render_from_template(
1468 $notification->get_template_name(),
1469 $notification->export_for_template($this)
1470 );
1471 }
1472
1473 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1474
1475 if ($this->page->course->id == SITEID) {
1476 // return immediately and do not include /course/lib.php if not necessary
1477 return $output;
1478 }
1479
fdd4b9a5
MG
1480 require_once($CFG->dirroot.'/course/lib.php');
1481 $functioncalled = true;
1482 $courseformat = course_get_format($this->page->course);
1483 if (($obj = $courseformat->course_content_header()) !== null) {
0346323c 1484 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
fdd4b9a5 1485 }
0346323c 1486 return $output;
fdd4b9a5
MG
1487 }
1488
1489 /**
1490 * Returns course-specific information to be output immediately below content on any course page
1491 * (for the current course)
1492 *
1493 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1494 * @return string
1495 */
1496 public function course_content_footer($onlyifnotcalledbefore = false) {
1497 global $CFG;
1498 if ($this->page->course->id == SITEID) {
1499 // return immediately and do not include /course/lib.php if not necessary
1500 return '';
1501 }
1502 static $functioncalled = false;
1503 if ($functioncalled && $onlyifnotcalledbefore) {
1504 // we have already output the content footer
1505 return '';
1506 }
1507 $functioncalled = true;
1508 require_once($CFG->dirroot.'/course/lib.php');
1509 $courseformat = course_get_format($this->page->course);
1510 if (($obj = $courseformat->course_content_footer()) !== null) {
06a72e01 1511 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
fdd4b9a5
MG
1512 }
1513 return '';
1514 }
1515
1516 /**
1517 * Returns course-specific information to be output on any course page in the header area
1518 * (for the current course)
1519 *
1520 * @return string
1521 */
1522 public function course_header() {
1523 global $CFG;
1524 if ($this->page->course->id == SITEID) {
1525 // return immediately and do not include /course/lib.php if not necessary
1526 return '';
1527 }
1528 require_once($CFG->dirroot.'/course/lib.php');
1529 $courseformat = course_get_format($this->page->course);
1530 if (($obj = $courseformat->course_header()) !== null) {
1531 return $courseformat->get_renderer($this->page)->render($obj);
1532 }
1533 return '';
1534 }
1535
1536 /**
1537 * Returns course-specific information to be output on any course page in the footer area
1538 * (for the current course)
1539 *
1540 * @return string
1541 */
1542 public function course_footer() {
1543 global $CFG;
1544 if ($this->page->course->id == SITEID) {
1545 // return immediately and do not include /course/lib.php if not necessary
1546 return '';
1547 }
1548 require_once($CFG->dirroot.'/course/lib.php');
1549 $courseformat = course_get_format($this->page->course);
1550 if (($obj = $courseformat->course_footer()) !== null) {
1551 return $courseformat->get_renderer($this->page)->render($obj);
1552 }
1553 return '';
1554 }
1555
620896cf
BB
1556 /**
1557 * Get the course pattern datauri to show on a course card.
1558 *
1559 * The datauri is an encoded svg that can be passed as a url.
1560 * @param int $id Id to use when generating the pattern
1561 * @return string datauri
1562 */
1563 public function get_generated_image_for_id($id) {
1564 $color = $this->get_generated_color_for_id($id);
1565 $pattern = new \core_geopattern();
1566 $pattern->setColor($color);
1567 $pattern->patternbyid($id);
1568 return $pattern->datauri();
1569 }
1570
1571 /**
1572 * Get the course color to show on a course card.
1573 *
1574 * @param int $id Id to use when generating the color.
1575 * @return string hex color code.
1576 */
1577 public function get_generated_color_for_id($id) {
c5b2ab47
BB
1578 $colornumbers = range(1, 10);
1579 $basecolors = [];
1580 foreach ($colornumbers as $number) {
1581 $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1582 }
620896cf
BB
1583
1584 $color = $basecolors[$id % 10];
1585 return $color;
1586 }
1587
244a32c6
PS
1588 /**
1589 * Returns lang menu or '', this method also checks forcing of languages in courses.
7a3c215b 1590 *
2fada290
MG
1591 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1592 *
7a3c215b 1593 * @return string The lang menu HTML or empty string
244a32c6
PS
1594 */
1595 public function lang_menu() {
1596 global $CFG;
1597
1598 if (empty($CFG->langmenu)) {
1599 return '';
1600 }
1601
1602 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1603 // do not show lang menu if language forced
1604 return '';
1605 }
1606
1607 $currlang = current_language();
1f96e907 1608 $langs = get_string_manager()->get_list_of_translations();
4bcc5118 1609
244a32c6
PS
1610 if (count($langs) < 2) {
1611 return '';
1612 }
1613
a9967cf5
PS
1614 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1615 $s->label = get_accesshide(get_string('language'));
1616 $s->class = 'langmenu';
1617 return $this->render($s);
244a32c6
PS
1618 }
1619
d9c8f425 1620 /**
1621 * Output the row of editing icons for a block, as defined by the controls array.
7a3c215b 1622 *
f8129210 1623 * @param array $controls an array like {@link block_contents::$controls}.
b59f2e3b 1624 * @param string $blockid The ID given to the block.
7a3c215b 1625 * @return string HTML fragment.
d9c8f425 1626 */
b59f2e3b 1627 public function block_controls($actions, $blockid = null) {
10fc1569 1628 global $CFG;
b59f2e3b
SH
1629 if (empty($actions)) {
1630 return '';
1631 }
cf69a00a 1632 $menu = new action_menu($actions);
b59f2e3b
SH
1633 if ($blockid !== null) {
1634 $menu->set_owner_selector('#'.$blockid);
1635 }
ae3fd8eb 1636 $menu->set_constraint('.block-region');
b59f2e3b
SH
1637 $menu->attributes['class'] .= ' block-control-actions commands';
1638 return $this->render($menu);
1639 }
1640
350d7b06
MN
1641 /**
1642 * Returns the HTML for a basic textarea field.
1643 *
1644 * @param string $name Name to use for the textarea element
1645 * @param string $id The id to use fort he textarea element
1646 * @param string $value Initial content to display in the textarea
1647 * @param int $rows Number of rows to display
1648 * @param int $cols Number of columns to display
1649 * @return string the HTML to display
1650 */
1651 public function print_textarea($name, $id, $value, $rows, $cols) {
350d7b06
MN
1652 editors_head_setup();
1653 $editor = editors_get_preferred_editor(FORMAT_HTML);
1654 $editor->set_text($value);
1655 $editor->use_editor($id, []);
1656
1657 $context = [
1658 'id' => $id,
1659 'name' => $name,
1660 'value' => $value,
1661 'rows' => $rows,
1662 'cols' => $cols
1663 ];
1664
1dcd0d34 1665 return $this->render_from_template('core_form/editor_textarea', $context);
350d7b06
MN
1666 }
1667
b59f2e3b
SH
1668 /**
1669 * Renders an action menu component.
1670 *
1671 * @param action_menu $menu
1672 * @return string HTML
1673 */
1674 public function render_action_menu(action_menu $menu) {
847b0fa9
MM
1675
1676 // We don't want the class icon there!
1677 foreach ($menu->get_secondary_actions() as $action) {
1678 if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1679 $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1680 }
1681 }
1682
1683 if ($menu->is_empty()) {
1684 return '';
1685 }
f15024c1 1686 $context = $menu->export_for_template($this);
847b0fa9 1687
f15024c1 1688 return $this->render_from_template('core/action_menu', $context);
d9c8f425 1689 }
1690
cf69a00a 1691 /**
00c2153b
BH
1692 * Renders a Check API result
1693 *
1694 * @param result $result
1695 * @return string HTML fragment
1696 */
a2827769 1697 protected function render_check_result(core\check\result $result) {
00c2153b
BH
1698 return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1699 }
1700
1701 /**
1702 * Renders a Check API result
1703 *
1704 * @param result $result
1705 * @return string HTML fragment
1706 */
a2827769
BH
1707 public function check_result(core\check\result $result) {
1708 return $this->render_check_result($result);
00c2153b
BH
1709 }
1710
1711 /**
3665af78 1712 * Renders an action_menu_link item.
cf69a00a 1713 *
3665af78 1714 * @param action_menu_link $action
cf69a00a
SH
1715 * @return string HTML fragment
1716 */
3665af78 1717 protected function render_action_menu_link(action_menu_link $action) {
f15024c1 1718 return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
cf69a00a
SH
1719 }
1720
9ac099a1
AN
1721 /**
1722 * Renders a primary action_menu_filler item.
1723 *
1724 * @param action_menu_link_filler $action
1725 * @return string HTML fragment
1726 */
1727 protected function render_action_menu_filler(action_menu_filler $action) {
1728 return html_writer::span('&nbsp;', 'filler');
1729 }
1730
cf69a00a 1731 /**
3665af78 1732 * Renders a primary action_menu_link item.
cf69a00a 1733 *
3665af78 1734 * @param action_menu_link_primary $action
cf69a00a
SH
1735 * @return string HTML fragment
1736 */
3665af78
SH
1737 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1738 return $this->render_action_menu_link($action);
cf69a00a
SH
1739 }
1740
1741 /**
3665af78 1742 * Renders a secondary action_menu_link item.
cf69a00a 1743 *
3665af78 1744 * @param action_menu_link_secondary $action
cf69a00a
SH
1745 * @return string HTML fragment
1746 */
3665af78
SH
1747 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1748 return $this->render_action_menu_link($action);
cf69a00a
SH
1749 }
1750
d9c8f425 1751 /**
1752 * Prints a nice side block with an optional header.
1753 *
d9c8f425 1754 * @param block_contents $bc HTML for the content
1755 * @param string $region the region the block is appearing in.
1756 * @return string the HTML to be output.
1757 */
7a3c215b 1758 public function block(block_contents $bc, $region) {
d9c8f425 1759 $bc = clone($bc); // Avoid messing up the object passed in.
dd72b308
PS
1760 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1761 $bc->collapsible = block_contents::NOT_HIDEABLE;
1762 }
91d941c3 1763
847b0fa9
MM
1764 $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1765 $context = new stdClass();
1766 $context->skipid = $bc->skipid;
768c318a 1767 $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
847b0fa9
MM
1768 $context->dockable = $bc->dockable;
1769 $context->id = $id;
1770 $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1771 $context->skiptitle = strip_tags($bc->title);
1772 $context->showskiplink = !empty($context->skiptitle);
1773 $context->arialabel = $bc->arialabel;
1774 $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
7a02f020 1775 $context->class = $bc->attributes['class'];
847b0fa9
MM
1776 $context->type = $bc->attributes['data-block'];
1777 $context->title = $bc->title;
1778 $context->content = $bc->content;
1779 $context->annotation = $bc->annotation;
1780 $context->footer = $bc->footer;
1781 $context->hascontrols = !empty($bc->controls);
1782 if ($context->hascontrols) {
1783 $context->controls = $this->block_controls($bc->controls, $id);
d9c8f425 1784 }
4d2ee4c2 1785
847b0fa9 1786 return $this->render_from_template('core/block', $context);
d9c8f425 1787 }
1788
1789 /**
1790 * Render the contents of a block_list.
7a3c215b 1791 *
d9c8f425 1792 * @param array $icons the icon for each item.
1793 * @param array $items the content of each item.
1794 * @return string HTML
1795 */
1796 public function list_block_contents($icons, $items) {
1797 $row = 0;
1798 $lis = array();
1799 foreach ($items as $key => $string) {
5d0c95a5 1800 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
2c5ec833 1801 if (!empty($icons[$key])) { //test if the content has an assigned icon
26acc814 1802 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
d9c8f425 1803 }
26acc814 1804 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
5d0c95a5 1805 $item .= html_writer::end_tag('li');
d9c8f425 1806 $lis[] = $item;
1807 $row = 1 - $row; // Flip even/odd.
1808 }
f2a04fc1 1809 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
d9c8f425 1810 }
1811
1812 /**
1813 * Output all the blocks in a particular region.
7a3c215b 1814 *
d9c8f425 1815 * @param string $region the name of a region on this page.
1816 * @return string the HTML to be output.
1817 */
1818 public function blocks_for_region($region) {
1819 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
6671fa73
JF
1820 $lastblock = null;
1821 $zones = array();
da4ded8a
GB
1822 foreach ($blockcontents as $bc) {
1823 if ($bc instanceof block_contents) {
1824 $zones[] = $bc->title;
1825 }
6671fa73 1826 }
d9c8f425 1827 $output = '';
6671fa73 1828
d9c8f425 1829 foreach ($blockcontents as $bc) {
1830 if ($bc instanceof block_contents) {
1831 $output .= $this->block($bc, $region);
6671fa73 1832 $lastblock = $bc->title;
d9c8f425 1833 } else if ($bc instanceof block_move_target) {
686e3b3a 1834 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
d9c8f425 1835 } else {
1836 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1837 }
1838 }
1839 return $output;
1840 }
1841
1842 /**
1843 * Output a place where the block that is currently being moved can be dropped.
7a3c215b 1844 *
d9c8f425 1845 * @param block_move_target $target with the necessary details.
6671fa73
JF
1846 * @param array $zones array of areas where the block can be moved to
1847 * @param string $previous the block located before the area currently being rendered.
686e3b3a 1848 * @param string $region the name of the region
d9c8f425 1849 * @return string the HTML to be output.
1850 */
686e3b3a 1851 public function block_move_target($target, $zones, $previous, $region) {
0e2ca62e 1852 if ($previous == null) {
686e3b3a
FM
1853 if (empty($zones)) {
1854 // There are no zones, probably because there are no blocks.
1855 $regions = $this->page->theme->get_all_block_regions();
1856 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1857 } else {
1858 $position = get_string('moveblockbefore', 'block', $zones[0]);
1859 }
6671fa73
JF
1860 } else {
1861 $position = get_string('moveblockafter', 'block', $previous);
1862 }
1863 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
d9c8f425 1864 }
1865
574fbea4 1866 /**
996b1e0c 1867 * Renders a special html link with attached action
574fbea4 1868 *
2fada290
MG
1869 * Theme developers: DO NOT OVERRIDE! Please override function
1870 * {@link core_renderer::render_action_link()} instead.
1871 *
574fbea4
PS
1872 * @param string|moodle_url $url
1873 * @param string $text HTML fragment
1874 * @param component_action $action
11820bac 1875 * @param array $attributes associative array of html link attributes + disabled
e282c679 1876 * @param pix_icon optional pix icon to render with the link
7a3c215b 1877 * @return string HTML fragment
574fbea4 1878 */
e282c679 1879 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
574fbea4
PS
1880 if (!($url instanceof moodle_url)) {
1881 $url = new moodle_url($url);
1882 }
e282c679 1883 $link = new action_link($url, $text, $action, $attributes, $icon);
574fbea4 1884
f14b641b 1885 return $this->render($link);
574fbea4
PS
1886 }
1887
1888 /**
7a3c215b
SH
1889 * Renders an action_link object.
1890 *
1891 * The provided link is renderer and the HTML returned. At the same time the
f8129210 1892 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
7a3c215b 1893 *
574fbea4
PS
1894 * @param action_link $link
1895 * @return string HTML fragment
1896 */
1897 protected function render_action_link(action_link $link) {
11ba3fd4 1898 return $this->render_from_template('core/action_link', $link->export_for_template($this));
574fbea4
PS
1899 }
1900
c63923bd 1901 /**
7a3c215b
SH
1902 * Renders an action_icon.
1903 *
f8129210 1904 * This function uses the {@link core_renderer::action_link()} method for the
7a3c215b
SH
1905 * most part. What it does different is prepare the icon as HTML and use it
1906 * as the link text.
c63923bd 1907 *
2fada290
MG
1908 * Theme developers: If you want to change how action links and/or icons are rendered,
1909 * consider overriding function {@link core_renderer::render_action_link()} and
1910 * {@link core_renderer::render_pix_icon()}.
1911 *
c63923bd
PS
1912 * @param string|moodle_url $url A string URL or moodel_url
1913 * @param pix_icon $pixicon
1914 * @param component_action $action
1915 * @param array $attributes associative array of html link attributes + disabled
1916 * @param bool $linktext show title next to image in link
1917 * @return string HTML fragment
1918 */
1919 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1920 if (!($url instanceof moodle_url)) {
1921 $url = new moodle_url($url);
1922 }
1923 $attributes = (array)$attributes;
1924
524645e7 1925 if (empty($attributes['class'])) {
c63923bd
PS
1926 // let ppl override the class via $options
1927 $attributes['class'] = 'action-icon';
1928 }
1929
1930 $icon = $this->render($pixicon);
1931
1932 if ($linktext) {
1933 $text = $pixicon->attributes['alt'];
1934 } else {
1935 $text = '';
1936 }
1937
1938 return $this->action_link($url, $text.$icon, $action, $attributes);
1939 }
1940
d9c8f425 1941 /**
0b634d75 1942 * Print a message along with button choices for Continue/Cancel
1943 *
4ed85790 1944 * If a string or moodle_url is given instead of a single_button, method defaults to post.
0b634d75 1945 *
d9c8f425 1946 * @param string $message The question to ask the user
3ba60ee1
PS
1947 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1948 * @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 1949 * @return string HTML fragment
1950 */
1951 public function confirm($message, $continue, $cancel) {
4871a238 1952 if ($continue instanceof single_button) {
11820bac 1953 // ok
f2405a5f 1954 $continue->primary = true;
4871a238 1955 } else if (is_string($continue)) {
f2405a5f 1956 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
4871a238 1957 } else if ($continue instanceof moodle_url) {
f2405a5f 1958 $continue = new single_button($continue, get_string('continue'), 'post', true);
d9c8f425 1959 } else {
4ed85790 1960 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
d9c8f425 1961 }
1962
4871a238 1963 if ($cancel instanceof single_button) {
11820bac 1964 // ok
4871a238
PS
1965 } else if (is_string($cancel)) {
1966 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1967 } else if ($cancel instanceof moodle_url) {
26eab8d4 1968 $cancel = new single_button($cancel, get_string('cancel'), 'get');
d9c8f425 1969 } else {
4ed85790 1970 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
d9c8f425 1971 }
1972
ede1e4a1
DW
1973 $attributes = [
1974 'role'=>'alertdialog',
1975 'aria-labelledby'=>'modal-header',
1976 'aria-describedby'=>'modal-body',
1977 'aria-modal'=>'true'
1978 ];
1979
1980 $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
f2405a5f 1981 $output .= $this->box_start('modal-content', 'modal-content');
4394f9e3 1982 $output .= $this->box_start('modal-header px-3', 'modal-header');
f2405a5f
DW
1983 $output .= html_writer::tag('h4', get_string('confirm'));
1984 $output .= $this->box_end();
ede1e4a1
DW
1985 $attributes = [
1986 'role'=>'alert',
1987 'data-aria-autofocus'=>'true'
1988 ];
1989 $output .= $this->box_start('modal-body', 'modal-body', $attributes);
26acc814 1990 $output .= html_writer::tag('p', $message);
f2405a5f
DW
1991 $output .= $this->box_end();
1992 $output .= $this->box_start('modal-footer', 'modal-footer');
26acc814 1993 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
d9c8f425 1994 $output .= $this->box_end();
f2405a5f
DW
1995 $output .= $this->box_end();
1996 $output .= $this->box_end();
d9c8f425 1997 return $output;
1998 }
1999
3cd5305f 2000 /**
3ba60ee1 2001 * Returns a form with a single button.
3cd5305f 2002 *
2fada290
MG
2003 * Theme developers: DO NOT OVERRIDE! Please override function
2004 * {@link core_renderer::render_single_button()} instead.
2005 *
3ba60ee1 2006 * @param string|moodle_url $url
3cd5305f
PS
2007 * @param string $label button text
2008 * @param string $method get or post submit method
3ba60ee1 2009 * @param array $options associative array {disabled, title, etc.}
3cd5305f
PS
2010 * @return string HTML fragment
2011 */
3ba60ee1 2012 public function single_button($url, $label, $method='post', array $options=null) {
574fbea4
PS
2013 if (!($url instanceof moodle_url)) {
2014 $url = new moodle_url($url);
3ba60ee1 2015 }
574fbea4
PS
2016 $button = new single_button($url, $label, $method);
2017
3ba60ee1 2018 foreach ((array)$options as $key=>$value) {
f4feabb8 2019 if (property_exists($button, $key)) {
3ba60ee1 2020 $button->$key = $value;
ca81e906
DM
2021 } else {
2022 $button->set_attribute($key, $value);
3ba60ee1 2023 }
3cd5305f
PS
2024 }
2025
3ba60ee1 2026 return $this->render($button);
3cd5305f
PS
2027 }
2028
d9c8f425 2029 /**
7a3c215b
SH
2030 * Renders a single button widget.
2031 *
2032 * This will return HTML to display a form containing a single button.
2033 *
3ba60ee1 2034 * @param single_button $button
d9c8f425 2035 * @return string HTML fragment
2036 */
3ba60ee1 2037 protected function render_single_button(single_button $button) {
847b0fa9 2038 return $this->render_from_template('core/single_button', $button->export_for_template($this));
d9c8f425 2039 }
2040
a9967cf5 2041 /**
ab08be98 2042 * Returns a form with a single select widget.
7a3c215b 2043 *
2fada290
MG
2044 * Theme developers: DO NOT OVERRIDE! Please override function
2045 * {@link core_renderer::render_single_select()} instead.
2046 *
a9967cf5
PS
2047 * @param moodle_url $url form action target, includes hidden fields
2048 * @param string $name name of selection field - the changing parameter in url
2049 * @param array $options list of options
2050 * @param string $selected selected element
2051 * @param array $nothing
f8dab966 2052 * @param string $formid
32bd11cb 2053 * @param array $attributes other attributes for the single select
a9967cf5
PS
2054 * @return string HTML fragment
2055 */
32bd11cb
BB
2056 public function single_select($url, $name, array $options, $selected = '',
2057 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
a9967cf5
PS
2058 if (!($url instanceof moodle_url)) {
2059 $url = new moodle_url($url);
2060 }
f8dab966 2061 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
a9967cf5 2062
32bd11cb
BB
2063 if (array_key_exists('label', $attributes)) {
2064 $select->set_label($attributes['label']);
2065 unset($attributes['label']);
2066 }
2067 $select->attributes = $attributes;
2068
a9967cf5
PS
2069 return $this->render($select);
2070 }
2071
bff1edbe
BH
2072 /**
2073 * Returns a dataformat selection and download form
2074 *
2075 * @param string $label A text label
2076 * @param moodle_url|string $base The download page url
2077 * @param string $name The query param which will hold the type of the download
2078 * @param array $params Extra params sent to the download page
2079 * @return string HTML fragment
2080 */
2081 public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2082
2083 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2084 $options = array();
2085 foreach ($formats as $format) {
2086 if ($format->is_enabled()) {
2087 $options[] = array(
2088 'value' => $format->name,
fef11147 2089 'label' => get_string('dataformat', $format->component),
bff1edbe
BH
2090 );
2091 }
2092 }
2093 $hiddenparams = array();
2094 foreach ($params as $key => $value) {
2095 $hiddenparams[] = array(
2096 'name' => $key,
2097 'value' => $value,
2098 );
2099 }
2100 $data = array(
2101 'label' => $label,
2102 'base' => $base,
2103 'name' => $name,
2104 'params' => $hiddenparams,
2105 'options' => $options,
2106 'sesskey' => sesskey(),
2107 'submit' => get_string('download'),
2108 );
2109
2110 return $this->render_from_template('core/dataformat_selector', $data);
2111 }
2112
2113
a9967cf5
PS
2114 /**
2115 * Internal implementation of single_select rendering
7a3c215b 2116 *
a9967cf5
PS
2117 * @param single_select $select
2118 * @return string HTML fragment
2119 */
2120 protected function render_single_select(single_select $select) {
c67e93b2 2121 return $this->render_from_template('core/single_select', $select->export_for_template($this));
4d10e579
PS
2122 }
2123
2124 /**
ab08be98 2125 * Returns a form with a url select widget.
7a3c215b 2126 *
2fada290
MG
2127 * Theme developers: DO NOT OVERRIDE! Please override function
2128 * {@link core_renderer::render_url_select()} instead.
2129 *
4d10e579
PS
2130 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2131 * @param string $selected selected element
2132 * @param array $nothing
2133 * @param string $formid
2134 * @return string HTML fragment
2135 */
7a3c215b 2136 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
4d10e579
PS
2137 $select = new url_select($urls, $selected, $nothing, $formid);
2138 return $this->render($select);
2139 }
2140
2141 /**
ab08be98 2142 * Internal implementation of url_select rendering
7a3c215b
SH
2143 *
2144 * @param url_select $select
4d10e579
PS
2145 * @return string HTML fragment
2146 */
2147 protected function render_url_select(url_select $select) {
c67e93b2 2148 return $this->render_from_template('core/url_select', $select->export_for_template($this));
a9967cf5
PS
2149 }
2150
d9c8f425 2151 /**
2152 * Returns a string containing a link to the user documentation.
2153 * Also contains an icon by default. Shown to teachers and admin only.
7a3c215b 2154 *
d9c8f425 2155 * @param string $path The page link after doc root and language, no leading slash.
2156 * @param string $text The text to be displayed for the link
afe3566c 2157 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
f064e115 2158 * @param array $attributes htm attributes
996b1e0c 2159 * @return string
d9c8f425 2160 */
f064e115 2161 public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
8ae8bf8a
PS
2162 global $CFG;
2163
ae4086bd 2164 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
8ae8bf8a 2165
f064e115 2166 $attributes['href'] = new moodle_url(get_docs_url($path));
afe3566c
ARN
2167 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2168 $attributes['class'] = 'helplinkpopup';
d9c8f425 2169 }
1adaa404 2170
26acc814 2171 return html_writer::tag('a', $icon.$text, $attributes);
d9c8f425 2172 }
2173
c2dde7ee 2174 /**
3e6adcd6 2175 * Return HTML for an image_icon.
c2dde7ee
DW
2176 *
2177 * Theme developers: DO NOT OVERRIDE! Please override function
3e6adcd6 2178 * {@link core_renderer::render_image_icon()} instead.
c2dde7ee
DW
2179 *
2180 * @param string $pix short pix name
2181 * @param string $alt mandatory alt attribute
2182 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
f064e115 2183 * @param array $attributes htm attributes
c2dde7ee
DW
2184 * @return string HTML fragment
2185 */
3e6adcd6
DW
2186 public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2187 $icon = new image_icon($pix, $alt, $component, $attributes);
c2dde7ee
DW
2188 return $this->render($icon);
2189 }
2190
2191 /**
2192 * Renders a pix_icon widget and returns the HTML to display it.
2193 *
b9b409cf 2194 * @param image_icon $icon
c2dde7ee
DW
2195 * @return string HTML fragment
2196 */
3e6adcd6 2197 protected function render_image_icon(image_icon $icon) {
e330b1c2 2198 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
c2dde7ee
DW
2199 return $system->render_pix_icon($this, $icon);
2200 }
2201
000c278c 2202 /**
7a3c215b
SH
2203 * Return HTML for a pix_icon.
2204 *
2fada290
MG
2205 * Theme developers: DO NOT OVERRIDE! Please override function
2206 * {@link core_renderer::render_pix_icon()} instead.
2207 *
000c278c
PS
2208 * @param string $pix short pix name
2209 * @param string $alt mandatory alt attribute
eb557002 2210 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
000c278c
PS
2211 * @param array $attributes htm lattributes
2212 * @return string HTML fragment
2213 */
2214 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2215 $icon = new pix_icon($pix, $alt, $component, $attributes);
2216 return $this->render($icon);
2217 }
2218
2219 /**
7a3c215b
SH
2220 * Renders a pix_icon widget and returns the HTML to display it.
2221 *
000c278c
PS
2222 * @param pix_icon $icon
2223 * @return string HTML fragment
2224 */
ce0110bf 2225 protected function render_pix_icon(pix_icon $icon) {
95b06c13
DW
2226 $system = \core\output\icon_system::instance();
2227 return $system->render_pix_icon($this, $icon);
000c278c
PS
2228 }
2229
d63c5073 2230 /**
7a3c215b
SH
2231 * Return HTML to display an emoticon icon.
2232 *
d63c5073
DM
2233 * @param pix_emoticon $emoticon
2234 * @return string HTML fragment
2235 */
2236 protected function render_pix_emoticon(pix_emoticon $emoticon) {
b9b409cf
DW
2237 $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2238 return $system->render_pix_icon($this, $emoticon);
d63c5073
DM
2239 }
2240
a09aeee4 2241 /**
7a3c215b
SH
2242 * Produces the html that represents this rating in the UI
2243 *
2244 * @param rating $rating the page object on which this rating will appear
2245 * @return string
2246 */
a09aeee4 2247 function render_rating(rating $rating) {
7ac928a7 2248 global $CFG, $USER;
a09aeee4 2249
2b04c41c 2250 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
63e87951
AD
2251 return null;//ratings are turned off
2252 }
2253
2b04c41c
SH
2254 $ratingmanager = new rating_manager();
2255 // Initialise the JavaScript so ratings can be done by AJAX.
2256 $ratingmanager->initialise_rating_javascript($this->page);
a09aeee4 2257
63e87951
AD
2258 $strrate = get_string("rate", "rating");
2259 $ratinghtml = ''; //the string we'll return
2260
2b04c41c
SH
2261 // permissions check - can they view the aggregate?
2262 if ($rating->user_can_view_aggregate()) {
a09aeee4 2263
2b04c41c 2264 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
4dd2570d 2265 $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2b04c41c 2266 $aggregatestr = $rating->get_aggregate_string();
a09aeee4 2267
6278ce45 2268 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2b04c41c 2269 if ($rating->count > 0) {
6278ce45 2270 $countstr = "({$rating->count})";
d251b259 2271 } else {
6278ce45 2272 $countstr = '-';
d251b259 2273 }
6278ce45 2274 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
63e87951 2275
d251b259 2276 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2b04c41c
SH
2277
2278 $nonpopuplink = $rating->get_view_ratings_url();
2279 $popuplink = $rating->get_view_ratings_url(true);
a09aeee4 2280
d251b259 2281 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
4dd2570d 2282 $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
a09aeee4 2283 }
4dd2570d
RW
2284
2285 $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
d251b259 2286 }
a09aeee4 2287
d251b259 2288 $formstart = null;
2b04c41c
SH
2289 // if the item doesn't belong to the current user, the user has permission to rate
2290 // and we're within the assessable period
2291 if ($rating->user_can_rate()) {
771b3fbe 2292
2b04c41c
SH
2293 $rateurl = $rating->get_rate_url();
2294 $inputs = $rateurl->params();
771b3fbe 2295
2b04c41c
SH
2296 //start the rating form
2297 $formattrs = array(
2298 'id' => "postrating{$rating->itemid}",
2299 'class' => 'postratingform',
2300 'method' => 'post',
2301 'action' => $rateurl->out_omit_querystring()
2302 );
2303 $formstart = html_writer::start_tag('form', $formattrs);
2304 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2305
2306 // add the hidden inputs
2307 foreach ($inputs as $name => $value) {
2308 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2309 $formstart .= html_writer::empty_tag('input', $attributes);
2310 }
3180bc2c 2311
d251b259
AD
2312 if (empty($ratinghtml)) {
2313 $ratinghtml .= $strrate.': ';
2314 }
d251b259 2315 $ratinghtml = $formstart.$ratinghtml;
63e87951 2316
2b04c41c
SH
2317 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2318 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
ecc5cc31 2319 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2b04c41c 2320 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
a09aeee4 2321
d251b259 2322 //output submit button
771b3fbe
AD
2323 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2324
2b04c41c 2325 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
771b3fbe 2326 $ratinghtml .= html_writer::empty_tag('input', $attributes);
a09aeee4 2327
2b04c41c 2328 if (!$rating->settings->scale->isnumeric) {
eaf52ff0
MN
2329 // If a global scale, try to find current course ID from the context
2330 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2331 $courseid = $coursecontext->instanceid;
2332 } else {
2333 $courseid = $rating->settings->scale->courseid;
2334 }
2335 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
a09aeee4 2336 }
771b3fbe
AD
2337 $ratinghtml .= html_writer::end_tag('span');
2338 $ratinghtml .= html_writer::end_tag('div');
2339 $ratinghtml .= html_writer::end_tag('form');
a09aeee4
AD
2340 }
2341
63e87951 2342 return $ratinghtml;
a09aeee4
AD
2343 }
2344
7a3c215b 2345 /**
d9c8f425 2346 * Centered heading with attached help button (same title text)
7a3c215b
SH
2347 * and optional icon attached.
2348 *
4bcc5118 2349 * @param string $text A heading text
53a78cef 2350 * @param string $helpidentifier The keyword that defines a help page
4bcc5118
PS
2351 * @param string $component component name
2352 * @param string|moodle_url $icon
2353 * @param string $iconalt icon alt text
699e2fd0
RW
2354 * @param int $level The level of importance of the heading. Defaulting to 2
2355 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
d9c8f425 2356 * @return string HTML fragment
2357 */
699e2fd0 2358 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
4bcc5118
PS
2359 $image = '';
2360 if ($icon) {
8ef1aa40 2361 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
d9c8f425 2362 }
4bcc5118 2363
259c165d
PS
2364 $help = '';
2365 if ($helpidentifier) {
2366 $help = $this->help_icon($helpidentifier, $component);
2367 }
4bcc5118 2368
699e2fd0 2369 return $this->heading($image.$text.$help, $level, $classnames);
d9c8f425 2370 }
2371
2372 /**
7a3c215b 2373 * Returns HTML to display a help icon.
d9c8f425 2374 *
cb616be8 2375 * @deprecated since Moodle 2.0
bf11293a 2376 */
596509e4 2377 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
a6d81a73 2378 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
d9c8f425 2379 }
2380
259c165d 2381 /**
7a3c215b 2382 * Returns HTML to display a help icon.
259c165d 2383 *
2fada290
MG
2384 * Theme developers: DO NOT OVERRIDE! Please override function
2385 * {@link core_renderer::render_help_icon()} instead.
2386 *
259c165d
PS
2387 * @param string $identifier The keyword that defines a help page
2388 * @param string $component component name
2389 * @param string|bool $linktext true means use $title as link text, string means link text value
2390 * @return string HTML fragment
2391 */
2392 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2cf81209 2393 $icon = new help_icon($identifier, $component);
259c165d
PS
2394 $icon->diag_strings();
2395 if ($linktext === true) {
2396 $icon->linktext = get_string($icon->identifier, $icon->component);
2397 } else if (!empty($linktext)) {
2398 $icon->linktext = $linktext;
2399 }
2400 return $this->render($icon);
2401 }
2402
2403 /**
2404 * Implementation of user image rendering.
7a3c215b 2405 *
3d3fae72 2406 * @param help_icon $helpicon A help icon instance
259c165d
PS
2407 * @return string HTML fragment
2408 */
2409 protected function render_help_icon(help_icon $helpicon) {
847b0fa9
MM
2410 $context = $helpicon->export_for_template($this);
2411 return $this->render_from_template('core/help_icon', $context);
259c165d
PS
2412 }
2413
d9c8f425 2414 /**
7a3c215b 2415 * Returns HTML to display a scale help icon.
d9c8f425 2416 *
4bcc5118 2417 * @param int $courseid
7a3c215b
SH
2418 * @param stdClass $scale instance
2419 * @return string HTML fragment
d9c8f425 2420 */
4bcc5118
PS
2421 public function help_icon_scale($courseid, stdClass $scale) {
2422 global $CFG;
02f64f97 2423
4bcc5118 2424 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
02f64f97 2425
0029a917 2426 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
02f64f97 2427
68bf577b
AD
2428 $scaleid = abs($scale->id);
2429
2430 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
230ec401 2431 $action = new popup_action('click', $link, 'ratingscale');
02f64f97 2432
26acc814 2433 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
d9c8f425 2434 }
2435
2436 /**
2437 * Creates and returns a spacer image with optional line break.
2438 *
3d3fae72
SH
2439 * @param array $attributes Any HTML attributes to add to the spaced.
2440 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2441 * laxy do it with CSS which is a much better solution.
d9c8f425 2442 * @return string HTML fragment
2443 */
0029a917
PS
2444 public function spacer(array $attributes = null, $br = false) {
2445 $attributes = (array)$attributes;
2446 if (empty($attributes['width'])) {
2447 $attributes['width'] = 1;
1ba862ec 2448 }
e1a5a9cc 2449 if (empty($attributes['height'])) {
0029a917 2450 $attributes['height'] = 1;
d9c8f425 2451 }
0029a917 2452 $attributes['class'] = 'spacer';
d9c8f425 2453
0029a917 2454 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
b65bfc3e 2455
0029a917 2456 if (!empty($br)) {
1ba862ec
PS
2457 $output .= '<br />';
2458 }
d9c8f425 2459
2460 return $output;
2461 }
2462
d9c8f425 2463 /**
7a3c215b 2464 * Returns HTML to display the specified user's avatar.
d9c8f425 2465 *
5d0c95a5 2466 * User avatar may be obtained in two ways:
d9c8f425 2467 * <pre>
812dbaf7
PS
2468 * // Option 1: (shortcut for simple cases, preferred way)
2469 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2470 * $OUTPUT->user_picture($user, array('popup'=>true));
2471 *
5d0c95a5
PS
2472 * // Option 2:
2473 * $userpic = new user_picture($user);
d9c8f425 2474 * // Set properties of $userpic
812dbaf7 2475 * $userpic->popup = true;
5d0c95a5 2476 * $OUTPUT->render($userpic);
d9c8f425 2477 * </pre>
2478 *
2fada290
MG
2479 * Theme developers: DO NOT OVERRIDE! Please override function
2480 * {@link core_renderer::render_user_picture()} instead.
2481 *
7a3c215b 2482 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
812dbaf7 2483 * If any of these are missing, the database is queried. Avoid this
d9c8f425 2484 * if at all possible, particularly for reports. It is very bad for performance.
812dbaf7
PS
2485 * @param array $options associative array with user picture options, used only if not a user_picture object,
2486 * options are:
2487 * - courseid=$this->page->course->id (course id of user profile in link)
2488 * - size=35 (size of image)
2489 * - link=true (make image clickable - the link leads to user profile)
2490 * - popup=false (open in popup)
2491 * - alttext=true (add image alt attribute)
5d0c95a5 2492 * - class = image class attribute (default 'userpicture')
e4a1efcb 2493 * - visibletoscreenreaders=true (whether to be visible to screen readers)
3b1eba06 2494 * - includefullname=false (whether to include the user's full name together with the user picture)
26e778d1 2495 * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
d9c8f425 2496 * @return string HTML fragment
2497 */
5d0c95a5
PS
2498 public function user_picture(stdClass $user, array $options = null) {
2499 $userpicture = new user_picture($user);
2500 foreach ((array)$options as $key=>$value) {
f4feabb8 2501 if (property_exists($userpicture, $key)) {
5d0c95a5
PS
2502 $userpicture->$key = $value;
2503 }
2504 }
2505 return $this->render($userpicture);
2506 }
2507
2508 /**
2509 * Internal implementation of user image rendering.
7a3c215b 2510 *
5d0c95a5
PS
2511 * @param user_picture $userpicture
2512 * @return string
2513 */
2514 protected function render_user_picture(user_picture $userpicture) {
9ecc75d4 2515 global $CFG, $DB;
812dbaf7 2516
5d0c95a5 2517 $user = $userpicture->user;
9ecc75d4 2518 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
5d0c95a5
PS
2519
2520 if ($userpicture->alttext) {
2521 if (!empty($user->imagealt)) {
2522 $alt = $user->imagealt;
2523 } else {
c157e137 2524 $alt = get_string('pictureof', '', fullname($user, $canviewfullnames));
5d0c95a5 2525 }
d9c8f425 2526 } else {
97c10099 2527 $alt = '';
5d0c95a5
PS
2528 }
2529
2530 if (empty($userpicture->size)) {
5d0c95a5
PS
2531 $size = 35;
2532 } else if ($userpicture->size === true or $userpicture->size == 1) {
5d0c95a5 2533 $size = 100;
5d0c95a5 2534 } else {
5d0c95a5 2535 $size = $userpicture->size;
d9c8f425 2536 }
2537
5d0c95a5 2538 $class = $userpicture->class;
d9c8f425 2539
4d254790 2540 if ($user->picture == 0) {
5d0c95a5 2541 $class .= ' defaultuserpic';
5d0c95a5 2542 }
d9c8f425 2543
871a3ec5
SH
2544 $src = $userpicture->get_url($this->page, $this);
2545
5689bb93 2546 $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
e4a1efcb 2547 if (!$userpicture->visibletoscreenreaders) {
5689bb93
DW
2548 $alt = '';
2549 $attributes['aria-hidden'] = 'true';
2550 }
2551
2552 if (!empty($alt)) {
2553 $attributes['alt'] = $alt;
2554 $attributes['title'] = $alt;
e4a1efcb
JC
2555 }
2556
5d0c95a5 2557 // get the image html output fisrt
0e35ba6f 2558 $output = html_writer::empty_tag('img', $attributes);
5d0c95a5 2559
3b1eba06
JP
2560 // Show fullname together with the picture when desired.
2561 if ($userpicture->includefullname) {
c157e137 2562 $output .= fullname($userpicture->user, $canviewfullnames);
3b1eba06
JP
2563 }
2564
5d0c95a5
PS
2565 // then wrap it in link if needed
2566 if (!$userpicture->link) {
2567 return $output;
d9c8f425 2568 }
2569
5d0c95a5
PS
2570 if (empty($userpicture->courseid)) {
2571 $courseid = $this->page->course->id;
2572 } else {
2573 $courseid = $userpicture->courseid;
2574 }
2575
03d9401e
MD
2576 if ($courseid == SITEID) {
2577 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2578 } else {
2579 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2580 }
5d0c95a5 2581
91de0ed8 2582 $attributes = array('href' => $url, 'class' => 'd-inline-block aabtn');
e4a1efcb 2583 if (!$userpicture->visibletoscreenreaders) {
e4a1efcb
JC
2584 $attributes['tabindex'] = '-1';
2585 $attributes['aria-hidden'] = 'true';
2586 }
5d0c95a5
PS
2587
2588 if ($userpicture->popup) {
2589 $id = html_writer::random_id('userpicture');
2590 $attributes['id'] = $id;
c80877aa 2591 $this->add_action_handler(new popup_action('click', $url), $id);
5d0c95a5
PS
2592 }
2593
26acc814 2594 return html_writer::tag('a', $output, $attributes);
d9c8f425 2595 }
b80ef420 2596
b80ef420
DC
2597 /**
2598 * Internal implementation of file tree viewer items rendering.
7a3c215b 2599 *
b80ef420
DC
2600 * @param array $dir
2601 * @return string
2602 */
2603 public function htmllize_file_tree($dir) {
2604 if (empty($dir['subdirs']) and empty($dir['files'])) {
2605 return '';
2606 }
2607 $result = '<ul>';
2608 foreach ($dir['subdirs'] as $subdir) {
2609 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2610 }
2611 foreach ($dir['files'] as $file) {
2612 $filename = $file->get_filename();
2613 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2614 }
2615 $result .= '</ul>';
2616
2617 return $result;
2618 }
7a3c215b 2619
bb496de7 2620 /**
7a3c215b 2621 * Returns HTML to display the file picker
bb496de7
DC
2622 *
2623 * <pre>
2624 * $OUTPUT->file_picker($options);
2625 * </pre>
2626 *
2fada290
MG
2627 * Theme developers: DO NOT OVERRIDE! Please override function
2628 * {@link core_renderer::render_file_picker()} instead.
2629 *
bb496de7
DC
2630 * @param array $options associative array with file manager options
2631 * options are:
2632 * maxbytes=>-1,
2633 * itemid=>0,
2634 * client_id=>uniqid(),
2635 * acepted_types=>'*',
2636 * return_types=>FILE_INTERNAL,
1dcd0d34 2637 * context=>current page context
bb496de7
DC
2638 * @return string HTML fragment
2639 */
2640 public function file_picker($options) {
2641 $fp = new file_picker($options);
2642 return $this->render($fp);
2643 }
7a3c215b 2644
b80ef420
DC
2645 /**
2646 * Internal implementation of file picker rendering.
7a3c215b 2647 *
b80ef420
DC
2648 * @param file_picker $fp
2649 * @return string
2650 */
bb496de7 2651 public function render_file_picker(file_picker $fp) {
bb496de7
DC
2652 $options = $fp->options;
2653 $client_id = $options->client_id;
2654 $strsaved = get_string('filesaved', 'repository');
2655 $straddfile = get_string('openpicker', 'repository');
2656 $strloading = get_string('loading', 'repository');
adce0230 2657 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
906e7d89 2658 $strdroptoupload = get_string('droptoupload', 'moodle');
19f22196 2659 $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
bb496de7
DC
2660
2661 $currentfile = $options->currentfile;
2662 if (empty($currentfile)) {
322945e9
FM
2663 $currentfile = '';
2664 } else {
2665 $currentfile .= ' - ';
bb496de7 2666 }
b817205b
DC
2667 if ($options->maxbytes) {
2668 $size = $options->maxbytes;
2669 } else {
2670 $size = get_max_upload_file_size();
2671 }
513aed3c 2672 if ($size == -1) {
831399c4 2673 $maxsize = '';
513aed3c
DC
2674 } else {
2675 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2676 }
f50a61fb 2677 if ($options->buttonname) {
4b72f9eb
AW
2678 $buttonname = ' name="' . $options->buttonname . '"';
2679 } else {
2680 $buttonname = '';
2681 }
bb496de7
DC
2682 $html = <<<EOD
2683<div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
19f22196 2684$iconprogress
bb496de7 2685</div>
3ec69c2e 2686<div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
bb496de7 2687 <div>
f6dabb31 2688 <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
fa7f2a45 2689 <span> $maxsize </span>
bb496de7
DC
2690 </div>
2691EOD;
2692 if ($options->env != 'url') {
2693 $html .= <<<EOD
609d8b38 2694 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
a9352f1f 2695 <div class="filepicker-filename">
08a6a19d 2696 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
0f94289c 2697 <div class="dndupload-progressbars"></div>
a9352f1f 2698 </div>
08a6a19d 2699 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
f08fac7c 2700 </div>
bb496de7
DC
2701EOD;
2702 }
2703 $html .= '</div>';
2704 return $html;
2705 }
d9c8f425 2706
2707 /**
d3932d2b 2708 * @deprecated since Moodle 3.2
d9c8f425 2709 */
d8e87342
MG
2710 public function update_module_button() {
2711 throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2712 'modules should not add the edit module button, the link is already available in the Administration block. ' .
2713 'Themes can choose to display the link in the buttons row consistently for all module types.');
d9c8f425 2714 }
2715
2716 /**
7a3c215b
SH
2717 * Returns HTML to display a "Turn editing on/off" button in a form.
2718 *
d9c8f425 2719 * @param moodle_url $url The URL + params to send through when clicking the button
2720 * @return string HTML the button
2721 */
2722 public function edit_button(moodle_url $url) {
3362dfdc
EL
2723
2724 $url->param('sesskey', sesskey());
2725 if ($this->page->user_is_editing()) {
2726 $url->param('edit', 'off');
2727 $editstring = get_string('turneditingoff');
d9c8f425 2728 } else {
3362dfdc
EL
2729 $url->param('edit', 'on');
2730 $editstring = get_string('turneditingon');
d9c8f425 2731 }
2732
3362dfdc 2733 return $this->single_button($url, $editstring);
d9c8f425 2734 }
2735
d9c8f425 2736 /**
7a3c215b 2737 * Returns HTML to display a simple button to close a window
d9c8f425 2738 *
d9c8f425 2739 * @param string $text The lang string for the button's label (already output from get_string())
3ba60ee1 2740 * @return string html fragment
d9c8f425 2741 */
7a5c78e0 2742 public function close_window_button($text='') {
d9c8f425 2743 if (empty($text)) {
2744 $text = get_string('closewindow');
2745 }
a6855934
PS
2746 $button = new single_button(new moodle_url('#'), $text, 'get');
2747 $button->add_action(new component_action('click', 'close_window'));
3ba60ee1
PS
2748
2749 return $this->container($this->render($button), 'closewindow');
d9c8f425 2750 }
2751
d9c8f425 2752 /**
2753 * Output an error message. By default wraps the error message in <span class="error">.
2754 * If the error message is blank, nothing is output.
7a3c215b 2755 *
d9c8f425 2756 * @param string $message the error message.
2757 * @return string the HTML to output.
2758 */
2759 public function error_text($message) {
2760 if (empty($message)) {
2761 return '';
2762 }
3246648b 2763 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
26acc814 2764 return html_writer::tag('span', $message, array('class' => 'error'));
d9c8f425 2765 }
2766
2767 /**
2768 * Do not call this function directly.
2769 *
f8129210 2770 * To terminate the current script with a fatal error, call the {@link print_error}
d9c8f425 2771 * function, or throw an exception. Doing either of those things will then call this
2772 * function to display the error, before terminating the execution.
2773 *
2774 * @param string $message The message to output
2775 * @param string $moreinfourl URL where more info can be found about the error
2776 * @param string $link Link for the Continue button
2777 * @param array $backtrace The execution backtrace
2778 * @param string $debuginfo Debugging information
d9c8f425 2779 * @return string the HTML to output.
2780 */
9201a00a 2781 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
6bd8d7e7 2782 global $CFG;
d9c8f425 2783
2784 $output = '';
6f8f4d83 2785 $obbuffer = '';
e57c283d 2786
d9c8f425 2787 if ($this->has_started()) {
50764d37
PS
2788 // we can not always recover properly here, we have problems with output buffering,
2789 // html tables, etc.
d9c8f425 2790 $output .= $this->opencontainers->pop_all_but_last();
50764d37 2791
d9c8f425 2792 } else {
50764d37
PS
2793 // It is really bad if library code throws exception when output buffering is on,
2794 // because the buffered text would be printed before our start of page.
2795 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
6bd8d7e7 2796 error_reporting(0); // disable notices from gzip compression, etc.
50764d37 2797 while (ob_get_level() > 0) {
2cadd443
PS
2798 $buff = ob_get_clean();
2799 if ($buff === false) {
2800 break;
2801 }
2802 $obbuffer .= $buff;
50764d37 2803 }
6bd8d7e7 2804 error_reporting($CFG->debug);
6f8f4d83 2805
f22f1caf
PS
2806 // Output not yet started.
2807 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2808 if (empty($_SERVER['HTTP_RANGE'])) {
2809 @header($protocol . ' 404 Not Found');
6b0d1723
JF
2810 } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2811 // Coax iOS 10 into sending the session cookie.
2812 @header($protocol . ' 403 Forbidden');
f22f1caf
PS
2813 } else {
2814 // Must stop byteserving attempts somehow,
2815 // this is weird but Chrome PDF viewer can be stopped only with 407!
2816 @header($protocol . ' 407 Proxy Authentication Required');
85309744 2817 }
f22f1caf 2818
eb5bdb35 2819 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
7fde1e4b 2820 $this->page->set_url('/'); // no url
191b267b 2821 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
dcfb9b78 2822 $this->page->set_title(get_string('error'));
8093188f 2823 $this->page->set_heading($this->page->course->fullname);
d9c8f425 2824 $output .= $this->header();
2825 }
2826
aa86441b
MH
2827 $message = '<p class="errormessage">' . s($message) . '</p>'.
2828 '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
d9c8f425 2829 get_string('moreinformation') . '</a></p>';
1ad8143a
PS
2830 if (empty($CFG->rolesactive)) {
2831 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2832 //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.
2833 }
9d492637 2834 $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
d9c8f425 2835
96f81ea3 2836 if ($CFG->debugdeveloper) {
a875f3f5 2837 $labelsep = get_string('labelsep', 'langconfig');
6f8f4d83 2838 if (!empty($debuginfo)) {
c5d18164
PS
2839 $debuginfo = s($debuginfo); // removes all nasty JS
2840 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
a875f3f5
SR
2841 $label = get_string('debuginfo', 'debug') . $labelsep;
2842 $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
6f8f4d83
PS
2843 }
2844 if (!empty($backtrace)) {
a875f3f5
SR
2845 $label = get_string('stacktrace', 'debug') . $labelsep;
2846 $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
6f8f4d83
PS
2847 }
2848 if ($obbuffer !== '' ) {
a875f3f5
SR
2849 $label = get_string('outputbuffer', 'debug') . $labelsep;
2850 $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
6f8f4d83 2851 }
d9c8f425 2852 }
2853
3efe6bbb
PS
2854 if (empty($CFG->rolesactive)) {
2855 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2856 } else if (!empty($link)) {
d9c8f425 2857 $output .= $this->continue_button($link);
2858 }
2859
2860 $output .= $this->footer();
2861
2862 // Padding to encourage IE to display our error page, rather than its own.
2863 $output .= str_repeat(' ', 512);
2864
2865 return $output;
2866 }
2867
2868 /**
24346803 2869 * Output a notification (that is, a status message about something that has just happened).
d9c8f425 2870 *
0346323c
AN
2871 * Note: \core\notification::add() may be more suitable for your usage.
2872 *
24346803
AN
2873 * @param string $message The message to print out.
2874 * @param string $type The type of notification. See constants on \core\output\notification.
d9c8f425 2875 * @return string the HTML to output.
2876 */
24346803
AN
2877 public function notification($message, $type = null) {
2878 $typemappings = [
2879 // Valid types.
2880 'success' => \core\output\notification::NOTIFY_SUCCESS,
2881 'info' => \core\output\notification::NOTIFY_INFO,
2882 'warning' => \core\output\notification::NOTIFY_WARNING,
2883 'error' => \core\output\notification::NOTIFY_ERROR,
2884
2885 // Legacy types mapped to current types.
2886 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2887 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2888 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2889 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2890 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2891 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2892 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2893 ];
2894
2895 $extraclasses = [];
2896
2897 if ($type) {
2898 if (strpos($type, ' ') === false) {
2899 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2900 if (isset($typemappings[$type])) {
2901 $type = $typemappings[$type];
2902 } else {
2903 // The value provided did not match a known type. It must be an extra class.
2904 $extraclasses = [$type];
2905 }
2906 } else {
2907 // Identify what type of notification this is.
2908 $classarray = explode(' ', self::prepare_classes($type));
2909
2910 // Separate out the type of notification from the extra classes.
2911 foreach ($classarray as $class) {
2912 if (isset($typemappings[$class])) {
2913 $type = $typemappings[$class];
2914 } else {
2915 $extraclasses[] = $class;
2916 }
263fb9d1
JC
2917 }
2918 }
2919 }
2920
24346803
AN
2921 $notification = new \core\output\notification($message, $type);
2922 if (count($extraclasses)) {
2923 $notification->set_extra_classes($extraclasses);
2924 }
263fb9d1 2925
24346803
AN
2926 // Return the rendered template.
2927 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
263fb9d1
JC
2928 }
2929
dd9c2927
JP
2930 /**
2931 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2932 */
76f8b361
EL
2933 public function notify_problem() {
2934 throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
2935 'please use \core\notification::add(), or \core\output\notification as required.');
263fb9d1
JC
2936 }
2937
dd9c2927
JP
2938 /**
2939 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2940 */
76f8b361
EL
2941 public function notify_success() {
2942 throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
2943 'please use \core\notification::add(), or \core\output\notification as required.');
263fb9d1
JC
2944 }
2945
dd9c2927
JP
2946 /**
2947 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2948 */
76f8b361
EL
2949 public function notify_message() {
2950 throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
2951 'please use \core\notification::add(), or \core\output\notification as required.');
263fb9d1
JC
2952 }
2953
dd9c2927
JP
2954 /**
2955 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2956 */
76f8b361
EL
2957 public function notify_redirect() {
2958 throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
2959 'please use \core\notification::add(), or \core\output\notification as required.');
263fb9d1
JC
2960 }
2961
2962 /**
2963 * Render a notification (that is, a status message about something that has
2964 * just happened).
2965 *
2966 * @param \core\output\notification $notification the notification to print out
2967 * @return string the HTML to output.
2968 */
2969 protected function render_notification(\core\output\notification $notification) {
24346803 2970 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
d9c8f425 2971 }
2972
2973 /**
7a3c215b 2974 * Returns HTML to display a continue button that goes to a particular URL.
d9c8f425 2975 *
3ba60ee1 2976 * @param string|moodle_url $url The url the button goes to.
d9c8f425 2977 * @return string the HTML to output.
2978 */
3ba60ee1
PS
2979 public function continue_button($url) {
2980 if (!($url instanceof moodle_url)) {
2981 $url = new moodle_url($url);
d9c8f425 2982 }
5c3e1eed 2983 $button = new single_button($url, get_string('continue'), 'get', true);
3ba60ee1 2984 $button->class = 'continuebutton';
d9c8f425 2985
3ba60ee1 2986 return $this->render($button);
d9c8f425 2987 }
2988
2989 /**
7a3c215b 2990 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
d9c8f425 2991 *
2fada290
MG
2992 * Theme developers: DO NOT OVERRIDE! Please override function
2993 * {@link core_renderer::render_paging_bar()} instead.
2994 *
71c03ac1 2995 * @param int $totalcount The total number of entries available to be paged through
929d7a83
PS
2996 * @param int $page The page you are currently viewing
2997 * @param int $perpage The number of entries that should be shown per page
2998 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2999 * @param string $pagevar name of page parameter that holds the page number
d9c8f425 3000 * @return string the HTML to output.
3001 */
929d7a83
PS
3002 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3003 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3004 return $this->render($pb);
3005 }
3006
3007 /**
f3df9f9f 3008 * Returns HTML to display the paging bar.
7a3c215b 3009 *
3db611ec 3010 * @param paging_bar $pagingbar
f3df9f9f 3011 * @return string the HTML to output.
929d7a83
PS
3012 */
3013 protected function render_paging_bar(paging_bar $pagingbar) {
f3df9f9f
BB
3014 // Any more than 10 is not usable and causes weird wrapping of the pagination.
3015 $pagingbar->maxdisplay = 10;
3016 return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
d9c8f425 3017 }
3018
8b844f70
IT
3019 /**
3020 * Returns HTML to display initials bar to provide access to other pages (usually in a search)
3021 *
3022 * @param string $current the currently selected letter.
3023 * @param string $class class name to add to this initial bar.
3024 * @param string $title the name to put in front of this initial bar.
3025 * @param string $urlvar URL parameter name for this initial.
3026 * @param string $url URL object.
3027 * @param array $alpha of letters in the alphabet.
3028 * @return string the HTML to output.
3029 */
3030 public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3031 $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3032 return $this->render($ib);
3033 }
3034
3035 /**
3036 * Internal implementation of initials bar rendering.
3037 *
3038 * @param initials_bar $initialsbar
3039 * @return string
3040 */
3041 protected function render_initials_bar(initials_bar $initialsbar) {
3042 return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3043 }
3044
d9c8f425 3045 /**
3046 * Output the place a skip link goes to.
7a3c215b 3047 *
d9c8f425 3048 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3049 * @return string the HTML to output.
3050 */
fe213365 3051 public function skip_link_target($id = null) {
9e8d0842 3052 return html_writer::span('', '', array('id' => $id));
d9c8f425 3053 }
3054
3055 /**
3056 * Outputs a heading
7a3c215b 3057 *
d9c8f425 3058 * @param string $text The text of the heading
3059 * @param int $level The level of importance of the heading. Defaulting to 2
699e2fd0 3060 * @param string $classes A space-separated list of CSS classes. Defaulting to null
d9c8f425 3061 * @param string $id An optional ID
3062 * @return string the HTML to output.
3063 */
699e2fd0 3064 public function heading($text, $level = 2, $classes = null, $id = null) {
d9c8f425 3065 $level = (integer) $level;
3066 if ($level < 1 or $level > 6) {
3067 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3068 }
26acc814 3069 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
d9c8f425 3070 }
3071
3072 /**
3073 * Outputs a box.
7a3c215b 3074 *
d9c8f425 3075 * @param string $contents The contents of the box
3076 * @param string $classes A space-separated list of CSS classes
3077 * @param string $id An optional ID
3e76c7fa 3078 * @param array $attributes An array of other attributes to give the box.
d9c8f425 3079 * @return string the HTML to output.
3080 */
3e76c7fa
SH
3081 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3082 return $this->box_start($classes, $id, $attribut