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