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