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