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