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