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