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