MDL-30811 output: Add support for session notifications
[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() {
0346323c 1035 global $CFG, $DB, $PAGE;
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
0346323c 1060 $this->page->requires->js_call_amd('core/notification', 'init', array($PAGE->context->id, \core\notification::fetch_as_array($this)));
72009b87 1061 $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
d9c8f425 1062
1063 $this->page->set_state(moodle_page::STATE_DONE);
d9c8f425 1064
1065 return $output . $footer;
1066 }
1067
f6794ace
PS
1068 /**
1069 * Close all but the last open container. This is useful in places like error
1070 * handling, where you want to close all the open containers (apart from <body>)
1071 * before outputting the error message.
7a3c215b 1072 *
f6794ace
PS
1073 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1074 * developer debug warning if it isn't.
1075 * @return string the HTML required to close any open containers inside <body>.
1076 */
1077 public function container_end_all($shouldbenone = false) {
1078 return $this->opencontainers->pop_all_but_last($shouldbenone);
1079 }
1080
fdd4b9a5
MG
1081 /**
1082 * Returns course-specific information to be output immediately above content on any course page
1083 * (for the current course)
1084 *
1085 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1086 * @return string
1087 */
1088 public function course_content_header($onlyifnotcalledbefore = false) {
1089 global $CFG;
fdd4b9a5
MG
1090 static $functioncalled = false;
1091 if ($functioncalled && $onlyifnotcalledbefore) {
1092 // we have already output the content header
1093 return '';
1094 }
0346323c
AN
1095
1096 // Output any session notification.
1097 $notifications = \core\notification::fetch();
1098
1099 $bodynotifications = '';
1100 foreach ($notifications as $notification) {
1101 $bodynotifications .= $this->render_from_template(
1102 $notification->get_template_name(),
1103 $notification->export_for_template($this)
1104 );
1105 }
1106
1107 $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1108
1109 if ($this->page->course->id == SITEID) {
1110 // return immediately and do not include /course/lib.php if not necessary
1111 return $output;
1112 }
1113
fdd4b9a5
MG
1114 require_once($CFG->dirroot.'/course/lib.php');
1115 $functioncalled = true;
1116 $courseformat = course_get_format($this->page->course);
1117 if (($obj = $courseformat->course_content_header()) !== null) {
0346323c 1118 $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
fdd4b9a5 1119 }
0346323c 1120 return $output;
fdd4b9a5
MG
1121 }
1122
1123 /**
1124 * Returns course-specific information to be output immediately below content on any course page
1125 * (for the current course)
1126 *
1127 * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1128 * @return string
1129 */
1130 public function course_content_footer($onlyifnotcalledbefore = false) {
1131 global $CFG;
1132 if ($this->page->course->id == SITEID) {
1133 // return immediately and do not include /course/lib.php if not necessary
1134 return '';
1135 }
1136 static $functioncalled = false;
1137 if ($functioncalled && $onlyifnotcalledbefore) {
1138 // we have already output the content footer
1139 return '';
1140 }
1141 $functioncalled = true;
1142 require_once($CFG->dirroot.'/course/lib.php');
1143 $courseformat = course_get_format($this->page->course);
1144 if (($obj = $courseformat->course_content_footer()) !== null) {
06a72e01 1145 return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
fdd4b9a5
MG
1146 }
1147 return '';
1148 }
1149
1150 /**
1151 * Returns course-specific information to be output on any course page in the header area
1152 * (for the current course)
1153 *
1154 * @return string
1155 */
1156 public function course_header() {
1157 global $CFG;
1158 if ($this->page->course->id == SITEID) {
1159 // return immediately and do not include /course/lib.php if not necessary
1160 return '';
1161 }
1162 require_once($CFG->dirroot.'/course/lib.php');
1163 $courseformat = course_get_format($this->page->course);
1164 if (($obj = $courseformat->course_header()) !== null) {
1165 return $courseformat->get_renderer($this->page)->render($obj);
1166 }
1167 return '';
1168 }
1169
1170 /**
1171 * Returns course-specific information to be output on any course page in the footer area
1172 * (for the current course)
1173 *
1174 * @return string
1175 */
1176 public function course_footer() {
1177 global $CFG;
1178 if ($this->page->course->id == SITEID) {
1179 // return immediately and do not include /course/lib.php if not necessary
1180 return '';
1181 }
1182 require_once($CFG->dirroot.'/course/lib.php');
1183 $courseformat = course_get_format($this->page->course);
1184 if (($obj = $courseformat->course_footer()) !== null) {
1185 return $courseformat->get_renderer($this->page)->render($obj);
1186 }
1187 return '';
1188 }
1189
244a32c6
PS
1190 /**
1191 * Returns lang menu or '', this method also checks forcing of languages in courses.
7a3c215b 1192 *
2fada290
MG
1193 * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1194 *
7a3c215b 1195 * @return string The lang menu HTML or empty string
244a32c6
PS
1196 */
1197 public function lang_menu() {
1198 global $CFG;
1199
1200 if (empty($CFG->langmenu)) {
1201 return '';
1202 }
1203
1204 if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
1205 // do not show lang menu if language forced
1206 return '';
1207 }
1208
1209 $currlang = current_language();
1f96e907 1210 $langs = get_string_manager()->get_list_of_translations();
4bcc5118 1211
244a32c6
PS
1212 if (count($langs) < 2) {
1213 return '';
1214 }
1215
a9967cf5
PS
1216 $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
1217 $s->label = get_accesshide(get_string('language'));
1218 $s->class = 'langmenu';
1219 return $this->render($s);
244a32c6
PS
1220 }
1221
d9c8f425 1222 /**
1223 * Output the row of editing icons for a block, as defined by the controls array.
7a3c215b 1224 *
f8129210 1225 * @param array $controls an array like {@link block_contents::$controls}.
b59f2e3b 1226 * @param string $blockid The ID given to the block.
7a3c215b 1227 * @return string HTML fragment.
d9c8f425 1228 */
b59f2e3b 1229 public function block_controls($actions, $blockid = null) {
10fc1569 1230 global $CFG;
b59f2e3b
SH
1231 if (empty($actions)) {
1232 return '';
1233 }
cf69a00a 1234 $menu = new action_menu($actions);
b59f2e3b
SH
1235 if ($blockid !== null) {
1236 $menu->set_owner_selector('#'.$blockid);
1237 }
ae3fd8eb 1238 $menu->set_constraint('.block-region');
b59f2e3b 1239 $menu->attributes['class'] .= ' block-control-actions commands';
10fc1569
SH
1240 if (isset($CFG->blockeditingmenu) && !$CFG->blockeditingmenu) {
1241 $menu->do_not_enhance();
1242 }
b59f2e3b
SH
1243 return $this->render($menu);
1244 }
1245
1246 /**
1247 * Renders an action menu component.
1248 *
3665af78
SH
1249 * ARIA references:
1250 * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
1251 * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
1252 *
b59f2e3b
SH
1253 * @param action_menu $menu
1254 * @return string HTML
1255 */
1256 public function render_action_menu(action_menu $menu) {
1257 $menu->initialise_js($this->page);
1258
1259 $output = html_writer::start_tag('div', $menu->attributes);
3665af78 1260 $output .= html_writer::start_tag('ul', $menu->attributesprimary);
b59f2e3b
SH
1261 foreach ($menu->get_primary_actions($this) as $action) {
1262 if ($action instanceof renderable) {
3665af78 1263 $content = $this->render($action);
b59f2e3b 1264 } else {
3665af78 1265 $content = $action;
e282c679 1266 }
11dd4dad 1267 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
d9c8f425 1268 }
3665af78
SH
1269 $output .= html_writer::end_tag('ul');
1270 $output .= html_writer::start_tag('ul', $menu->attributessecondary);
b59f2e3b 1271 foreach ($menu->get_secondary_actions() as $action) {
3665af78
SH
1272 if ($action instanceof renderable) {
1273 $content = $this->render($action);
3665af78
SH
1274 } else {
1275 $content = $action;
3665af78 1276 }
11dd4dad 1277 $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
b59f2e3b 1278 }
3665af78 1279 $output .= html_writer::end_tag('ul');
b59f2e3b 1280 $output .= html_writer::end_tag('div');
e282c679 1281 return $output;
d9c8f425 1282 }
1283
cf69a00a 1284 /**
3665af78 1285 * Renders an action_menu_link item.
cf69a00a 1286 *
3665af78 1287 * @param action_menu_link $action
cf69a00a
SH
1288 * @return string HTML fragment
1289 */
3665af78 1290 protected function render_action_menu_link(action_menu_link $action) {
d0647301
SH
1291 static $actioncount = 0;
1292 $actioncount++;
cf69a00a 1293
ea5a01fb 1294 $comparetoalt = '';
cf69a00a 1295 $text = '';
ea5a01fb 1296 if (!$action->icon || $action->primary === false) {
d0647301 1297 $text .= html_writer::start_tag('span', array('class'=>'menu-action-text', 'id' => 'actionmenuaction-'.$actioncount));
cf69a00a
SH
1298 if ($action->text instanceof renderable) {
1299 $text .= $this->render($action->text);
1300 } else {
1301 $text .= $action->text;
cfd1e08a 1302 $comparetoalt = (string)$action->text;
cf69a00a
SH
1303 }
1304 $text .= html_writer::end_tag('span');
1305 }
1306
ea5a01fb
SH
1307 $icon = '';
1308 if ($action->icon) {
1309 $icon = $action->icon;
f803ce26 1310 if ($action->primary || !$action->actionmenu->will_be_enhanced()) {
ea5a01fb
SH
1311 $action->attributes['title'] = $action->text;
1312 }
cfd1e08a
SH
1313 if (!$action->primary && $action->actionmenu->will_be_enhanced()) {
1314 if ((string)$icon->attributes['alt'] === $comparetoalt) {
d0647301 1315 $icon->attributes['alt'] = '';
cfd1e08a 1316 }
c7a2291f 1317 if (isset($icon->attributes['title']) && (string)$icon->attributes['title'] === $comparetoalt) {
cfd1e08a
SH
1318 unset($icon->attributes['title']);
1319 }
1320 }
ea5a01fb
SH
1321 $icon = $this->render($icon);
1322 }
1323
3665af78 1324 // A disabled link is rendered as formatted text.
cf69a00a 1325 if (!empty($action->attributes['disabled'])) {
3665af78 1326 // Do not use div here due to nesting restriction in xhtml strict.
ea5a01fb 1327 return html_writer::tag('span', $icon.$text, array('class'=>'currentlink', 'role' => 'menuitem'));
cf69a00a
SH
1328 }
1329
1330 $attributes = $action->attributes;
1331 unset($action->attributes['disabled']);
1332 $attributes['href'] = $action->url;
d0647301
SH
1333 if ($text !== '') {
1334 $attributes['aria-labelledby'] = 'actionmenuaction-'.$actioncount;
1335 }
cf69a00a 1336
ea5a01fb 1337 return html_writer::tag('a', $icon.$text, $attributes);
cf69a00a
SH
1338 }
1339
9ac099a1
AN
1340 /**
1341 * Renders a primary action_menu_filler item.
1342 *
1343 * @param action_menu_link_filler $action
1344 * @return string HTML fragment
1345 */
1346 protected function render_action_menu_filler(action_menu_filler $action) {
1347 return html_writer::span('&nbsp;', 'filler');
1348 }
1349
cf69a00a 1350 /**
3665af78 1351 * Renders a primary action_menu_link item.
cf69a00a 1352 *
3665af78 1353 * @param action_menu_link_primary $action
cf69a00a
SH
1354 * @return string HTML fragment
1355 */
3665af78
SH
1356 protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1357 return $this->render_action_menu_link($action);
cf69a00a
SH
1358 }
1359
1360 /**
3665af78 1361 * Renders a secondary action_menu_link item.
cf69a00a 1362 *
3665af78 1363 * @param action_menu_link_secondary $action
cf69a00a
SH
1364 * @return string HTML fragment
1365 */
3665af78
SH
1366 protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1367 return $this->render_action_menu_link($action);
cf69a00a
SH
1368 }
1369
d9c8f425 1370 /**
1371 * Prints a nice side block with an optional header.
1372 *
1373 * The content is described
f8129210 1374 * by a {@link core_renderer::block_contents} object.
d9c8f425 1375 *
cbb54cce
SH
1376 * <div id="inst{$instanceid}" class="block_{$blockname} block">
1377 * <div class="header"></div>
1378 * <div class="content">
1379 * ...CONTENT...
1380 * <div class="footer">
1381 * </div>
1382 * </div>
1383 * <div class="annotation">
1384 * </div>
1385 * </div>
1386 *
d9c8f425 1387 * @param block_contents $bc HTML for the content
1388 * @param string $region the region the block is appearing in.
1389 * @return string the HTML to be output.
1390 */
7a3c215b 1391 public function block(block_contents $bc, $region) {
d9c8f425 1392 $bc = clone($bc); // Avoid messing up the object passed in.
dd72b308
PS
1393 if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1394 $bc->collapsible = block_contents::NOT_HIDEABLE;
1395 }
84192d78
SH
1396 if (!empty($bc->blockinstanceid)) {
1397 $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
1398 }
91d941c3
SH
1399 $skiptitle = strip_tags($bc->title);
1400 if ($bc->blockinstanceid && !empty($skiptitle)) {
1401 $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
1402 } else if (!empty($bc->arialabel)) {
1403 $bc->attributes['aria-label'] = $bc->arialabel;
1404 }
84192d78
SH
1405 if ($bc->dockable) {
1406 $bc->attributes['data-dockable'] = 1;
1407 }
dd72b308
PS
1408 if ($bc->collapsible == block_contents::HIDDEN) {
1409 $bc->add_class('hidden');
1410 }
1411 if (!empty($bc->controls)) {
1412 $bc->add_class('block_with_controls');
1413 }
d9c8f425 1414
91d941c3 1415
d9c8f425 1416 if (empty($skiptitle)) {
1417 $output = '';
1418 $skipdest = '';
1419 } else {
9e8d0842
AG
1420 $output = html_writer::link('#sb-'.$bc->skipid, get_string('skipa', 'access', $skiptitle),
1421 array('class' => 'skip skip-block', 'id' => 'fsb-' . $bc->skipid));
0b7856ef 1422 $skipdest = html_writer::span('', 'skip-block-to',
9e8d0842 1423 array('id' => 'sb-' . $bc->skipid));
d9c8f425 1424 }
4d2ee4c2 1425
5d0c95a5 1426 $output .= html_writer::start_tag('div', $bc->attributes);
d9c8f425 1427
9f5c39b5
SH
1428 $output .= $this->block_header($bc);
1429 $output .= $this->block_content($bc);
1430
1431 $output .= html_writer::end_tag('div');
1432
1433 $output .= $this->block_annotation($bc);
1434
1435 $output .= $skipdest;
1436
1437 $this->init_block_hider_js($bc);
1438 return $output;
1439 }
1440
1441 /**
1442 * Produces a header for a block
fa7f2a45 1443 *
9f5c39b5
SH
1444 * @param block_contents $bc
1445 * @return string
1446 */
1447 protected function block_header(block_contents $bc) {
d9c8f425 1448
1449 $title = '';
1450 if ($bc->title) {
91d941c3
SH
1451 $attributes = array();
1452 if ($bc->blockinstanceid) {
1453 $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
1454 }
1455 $title = html_writer::tag('h2', $bc->title, $attributes);
d9c8f425 1456 }
1457
b59f2e3b
SH
1458 $blockid = null;
1459 if (isset($bc->attributes['id'])) {
1460 $blockid = $bc->attributes['id'];
1461 }
1462 $controlshtml = $this->block_controls($bc->controls, $blockid);
9f5c39b5
SH
1463
1464 $output = '';
d9c8f425 1465 if ($title || $controlshtml) {
46de77b6 1466 $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 1467 }
9f5c39b5
SH
1468 return $output;
1469 }
d9c8f425 1470
9f5c39b5
SH
1471 /**
1472 * Produces the content area for a block
1473 *
1474 * @param block_contents $bc
1475 * @return string
1476 */
1477 protected function block_content(block_contents $bc) {
1478 $output = html_writer::start_tag('div', array('class' => 'content'));
1479 if (!$bc->title && !$this->block_controls($bc->controls)) {
46de77b6
SH
1480 $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
1481 }
d9c8f425 1482 $output .= $bc->content;
9f5c39b5
SH
1483 $output .= $this->block_footer($bc);
1484 $output .= html_writer::end_tag('div');
fa7f2a45 1485
9f5c39b5
SH
1486 return $output;
1487 }
d9c8f425 1488
9f5c39b5
SH
1489 /**
1490 * Produces the footer for a block
1491 *
1492 * @param block_contents $bc
1493 * @return string
1494 */
1495 protected function block_footer(block_contents $bc) {
1496 $output = '';
d9c8f425 1497 if ($bc->footer) {
26acc814 1498 $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
d9c8f425 1499 }
9f5c39b5
SH
1500 return $output;
1501 }
d9c8f425 1502
9f5c39b5
SH
1503 /**
1504 * Produces the annotation for a block
1505 *
1506 * @param block_contents $bc
1507 * @return string
1508 */
1509 protected function block_annotation(block_contents $bc) {
1510 $output = '';
d9c8f425 1511 if ($bc->annotation) {
26acc814 1512 $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
d9c8f425 1513 }
d9c8f425 1514 return $output;
1515 }
1516
1517 /**
1518 * Calls the JS require function to hide a block.
7a3c215b 1519 *
d9c8f425 1520 * @param block_contents $bc A block_contents object
d9c8f425 1521 */
dd72b308
PS
1522 protected function init_block_hider_js(block_contents $bc) {
1523 if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
cbb54cce
SH
1524 $config = new stdClass;
1525 $config->id = $bc->attributes['id'];
1526 $config->title = strip_tags($bc->title);
1527 $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
1528 $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
1529 $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
1530
1531 $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
1532 user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
d9c8f425 1533 }
1534 }
1535
1536 /**
1537 * Render the contents of a block_list.
7a3c215b 1538 *
d9c8f425 1539 * @param array $icons the icon for each item.
1540 * @param array $items the content of each item.
1541 * @return string HTML
1542 */
1543 public function list_block_contents($icons, $items) {
1544 $row = 0;
1545 $lis = array();
1546 foreach ($items as $key => $string) {
5d0c95a5 1547 $item = html_writer::start_tag('li', array('class' => 'r' . $row));
2c5ec833 1548 if (!empty($icons[$key])) { //test if the content has an assigned icon
26acc814 1549 $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
d9c8f425 1550 }
26acc814 1551 $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
5d0c95a5 1552 $item .= html_writer::end_tag('li');
d9c8f425 1553 $lis[] = $item;
1554 $row = 1 - $row; // Flip even/odd.
1555 }
f2a04fc1 1556 return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
d9c8f425 1557 }
1558
1559 /**
1560 * Output all the blocks in a particular region.
7a3c215b 1561 *
d9c8f425 1562 * @param string $region the name of a region on this page.
1563 * @return string the HTML to be output.
1564 */
1565 public function blocks_for_region($region) {
1566 $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
6671fa73
JF
1567 $blocks = $this->page->blocks->get_blocks_for_region($region);
1568 $lastblock = null;
1569 $zones = array();
1570 foreach ($blocks as $block) {
1571 $zones[] = $block->title;
1572 }
d9c8f425 1573 $output = '';
6671fa73 1574
d9c8f425 1575 foreach ($blockcontents as $bc) {
1576 if ($bc instanceof block_contents) {
1577 $output .= $this->block($bc, $region);
6671fa73 1578 $lastblock = $bc->title;
d9c8f425 1579 } else if ($bc instanceof block_move_target) {
686e3b3a 1580 $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
d9c8f425 1581 } else {
1582 throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1583 }
1584 }
1585 return $output;
1586 }
1587
1588 /**
1589 * Output a place where the block that is currently being moved can be dropped.
7a3c215b 1590 *
d9c8f425 1591 * @param block_move_target $target with the necessary details.
6671fa73
JF
1592 * @param array $zones array of areas where the block can be moved to
1593 * @param string $previous the block located before the area currently being rendered.
686e3b3a 1594 * @param string $region the name of the region
d9c8f425 1595 * @return string the HTML to be output.
1596 */
686e3b3a 1597 public function block_move_target($target, $zones, $previous, $region) {
0e2ca62e 1598 if ($previous == null) {
686e3b3a
FM
1599 if (empty($zones)) {
1600 // There are no zones, probably because there are no blocks.
1601 $regions = $this->page->theme->get_all_block_regions();
1602 $position = get_string('moveblockinregion', 'block', $regions[$region]);
1603 } else {
1604 $position = get_string('moveblockbefore', 'block', $zones[0]);
1605 }
6671fa73
JF
1606 } else {
1607 $position = get_string('moveblockafter', 'block', $previous);
1608 }
1609 return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
d9c8f425 1610 }
1611
574fbea4 1612 /**
996b1e0c 1613 * Renders a special html link with attached action
574fbea4 1614 *
2fada290
MG
1615 * Theme developers: DO NOT OVERRIDE! Please override function
1616 * {@link core_renderer::render_action_link()} instead.
1617 *
574fbea4
PS
1618 * @param string|moodle_url $url
1619 * @param string $text HTML fragment
1620 * @param component_action $action
11820bac 1621 * @param array $attributes associative array of html link attributes + disabled
e282c679 1622 * @param pix_icon optional pix icon to render with the link
7a3c215b 1623 * @return string HTML fragment
574fbea4 1624 */
e282c679 1625 public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
574fbea4
PS
1626 if (!($url instanceof moodle_url)) {
1627 $url = new moodle_url($url);
1628 }
e282c679 1629 $link = new action_link($url, $text, $action, $attributes, $icon);
574fbea4 1630
f14b641b 1631 return $this->render($link);
574fbea4
PS
1632 }
1633
1634 /**
7a3c215b
SH
1635 * Renders an action_link object.
1636 *
1637 * The provided link is renderer and the HTML returned. At the same time the
f8129210 1638 * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
7a3c215b 1639 *
574fbea4
PS
1640 * @param action_link $link
1641 * @return string HTML fragment
1642 */
1643 protected function render_action_link(action_link $link) {
1644 global $CFG;
1645
e282c679
SH
1646 $text = '';
1647 if ($link->icon) {
1648 $text .= $this->render($link->icon);
1649 }
1650
7749e187 1651 if ($link->text instanceof renderable) {
e282c679 1652 $text .= $this->render($link->text);
7749e187 1653 } else {
e282c679 1654 $text .= $link->text;
7749e187
SH
1655 }
1656
574fbea4
PS
1657 // A disabled link is rendered as formatted text
1658 if (!empty($link->attributes['disabled'])) {
1659 // do not use div here due to nesting restriction in xhtml strict
7749e187 1660 return html_writer::tag('span', $text, array('class'=>'currentlink'));
574fbea4 1661 }
11820bac 1662
574fbea4
PS
1663 $attributes = $link->attributes;
1664 unset($link->attributes['disabled']);
1665 $attributes['href'] = $link->url;
1666
1667 if ($link->actions) {
f14b641b 1668 if (empty($attributes['id'])) {
574fbea4
PS
1669 $id = html_writer::random_id('action_link');
1670 $attributes['id'] = $id;
1671 } else {
1672 $id = $attributes['id'];
1673 }
1674 foreach ($link->actions as $action) {
c80877aa 1675 $this->add_action_handler($action, $id);
574fbea4
PS
1676 }
1677 }
1678
7749e187 1679 return html_writer::tag('a', $text, $attributes);
574fbea4
PS
1680 }
1681
c63923bd
PS
1682
1683 /**
7a3c215b
SH
1684 * Renders an action_icon.
1685 *
f8129210 1686 * This function uses the {@link core_renderer::action_link()} method for the
7a3c215b
SH
1687 * most part. What it does different is prepare the icon as HTML and use it
1688 * as the link text.
c63923bd 1689 *
2fada290
MG
1690 * Theme developers: If you want to change how action links and/or icons are rendered,
1691 * consider overriding function {@link core_renderer::render_action_link()} and
1692 * {@link core_renderer::render_pix_icon()}.
1693 *
c63923bd
PS
1694 * @param string|moodle_url $url A string URL or moodel_url
1695 * @param pix_icon $pixicon
1696 * @param component_action $action
1697 * @param array $attributes associative array of html link attributes + disabled
1698 * @param bool $linktext show title next to image in link
1699 * @return string HTML fragment
1700 */
1701 public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
1702 if (!($url instanceof moodle_url)) {
1703 $url = new moodle_url($url);
1704 }
1705 $attributes = (array)$attributes;
1706
524645e7 1707 if (empty($attributes['class'])) {
c63923bd
PS
1708 // let ppl override the class via $options
1709 $attributes['class'] = 'action-icon';
1710 }
1711
1712 $icon = $this->render($pixicon);
1713
1714 if ($linktext) {
1715 $text = $pixicon->attributes['alt'];
1716 } else {
1717 $text = '';
1718 }
1719
1720 return $this->action_link($url, $text.$icon, $action, $attributes);
1721 }
1722
d9c8f425 1723 /**
0b634d75 1724 * Print a message along with button choices for Continue/Cancel
1725 *
4ed85790 1726 * If a string or moodle_url is given instead of a single_button, method defaults to post.
0b634d75 1727 *
d9c8f425 1728 * @param string $message The question to ask the user
3ba60ee1
PS
1729 * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
1730 * @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 1731 * @return string HTML fragment
1732 */
1733 public function confirm($message, $continue, $cancel) {
4871a238 1734 if ($continue instanceof single_button) {
11820bac 1735 // ok
4871a238
PS
1736 } else if (is_string($continue)) {
1737 $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
1738 } else if ($continue instanceof moodle_url) {
26eab8d4 1739 $continue = new single_button($continue, get_string('continue'), 'post');
d9c8f425 1740 } else {
4ed85790 1741 throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
d9c8f425 1742 }
1743
4871a238 1744 if ($cancel instanceof single_button) {
11820bac 1745 // ok
4871a238
PS
1746 } else if (is_string($cancel)) {
1747 $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
1748 } else if ($cancel instanceof moodle_url) {
26eab8d4 1749 $cancel = new single_button($cancel, get_string('cancel'), 'get');
d9c8f425 1750 } else {
4ed85790 1751 throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
d9c8f425 1752 }
1753
d9c8f425 1754 $output = $this->box_start('generalbox', 'notice');
26acc814
PS
1755 $output .= html_writer::tag('p', $message);
1756 $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
d9c8f425 1757 $output .= $this->box_end();
1758 return $output;
1759 }
1760
3cd5305f 1761 /**
3ba60ee1 1762 * Returns a form with a single button.
3cd5305f 1763 *
2fada290
MG
1764 * Theme developers: DO NOT OVERRIDE! Please override function
1765 * {@link core_renderer::render_single_button()} instead.
1766 *
3ba60ee1 1767 * @param string|moodle_url $url
3cd5305f
PS
1768 * @param string $label button text
1769 * @param string $method get or post submit method
3ba60ee1 1770 * @param array $options associative array {disabled, title, etc.}
3cd5305f
PS
1771 * @return string HTML fragment
1772 */
3ba60ee1 1773 public function single_button($url, $label, $method='post', array $options=null) {
574fbea4
PS
1774 if (!($url instanceof moodle_url)) {
1775 $url = new moodle_url($url);
3ba60ee1 1776 }
574fbea4
PS
1777 $button = new single_button($url, $label, $method);
1778
3ba60ee1
PS
1779 foreach ((array)$options as $key=>$value) {
1780 if (array_key_exists($key, $button)) {
1781 $button->$key = $value;
1782 }
3cd5305f
PS
1783 }
1784
3ba60ee1 1785 return $this->render($button);
3cd5305f
PS
1786 }
1787
d9c8f425 1788 /**
7a3c215b
SH
1789 * Renders a single button widget.
1790 *
1791 * This will return HTML to display a form containing a single button.
1792 *
3ba60ee1 1793 * @param single_button $button
d9c8f425 1794 * @return string HTML fragment
1795 */
3ba60ee1
PS
1796 protected function render_single_button(single_button $button) {
1797 $attributes = array('type' => 'submit',
1798 'value' => $button->label,
db09524d 1799 'disabled' => $button->disabled ? 'disabled' : null,
3ba60ee1
PS
1800 'title' => $button->tooltip);
1801
1802 if ($button->actions) {
1803 $id = html_writer::random_id('single_button');
1804 $attributes['id'] = $id;
1805 foreach ($button->actions as $action) {
c80877aa 1806 $this->add_action_handler($action, $id);
3ba60ee1 1807 }
d9c8f425 1808 }
d9c8f425 1809
3ba60ee1
PS
1810 // first the input element
1811 $output = html_writer::empty_tag('input', $attributes);
d9c8f425 1812
3ba60ee1
PS
1813 // then hidden fields
1814 $params = $button->url->params();
1815 if ($button->method === 'post') {
1816 $params['sesskey'] = sesskey();
1817 }
1818 foreach ($params as $var => $val) {
1819 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
1820 }
d9c8f425 1821
3ba60ee1 1822 // then div wrapper for xhtml strictness
26acc814 1823 $output = html_writer::tag('div', $output);
d9c8f425 1824
3ba60ee1 1825 // now the form itself around it
a12cd69c
DM
1826 if ($button->method === 'get') {
1827 $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
1828 } else {
1829 $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
1830 }
a6855934
PS
1831 if ($url === '') {
1832 $url = '#'; // there has to be always some action
1833 }
3ba60ee1 1834 $attributes = array('method' => $button->method,
a6855934 1835 'action' => $url,
3ba60ee1 1836 'id' => $button->formid);
26acc814 1837 $output = html_writer::tag('form', $output, $attributes);
d9c8f425 1838
3ba60ee1 1839 // and finally one more wrapper with class
26acc814 1840 return html_writer::tag('div', $output, array('class' => $button->class));
d9c8f425 1841 }
1842
a9967cf5 1843 /**
ab08be98 1844 * Returns a form with a single select widget.
7a3c215b 1845 *
2fada290
MG
1846 * Theme developers: DO NOT OVERRIDE! Please override function
1847 * {@link core_renderer::render_single_select()} instead.
1848 *
a9967cf5
PS
1849 * @param moodle_url $url form action target, includes hidden fields
1850 * @param string $name name of selection field - the changing parameter in url
1851 * @param array $options list of options
1852 * @param string $selected selected element
1853 * @param array $nothing
f8dab966 1854 * @param string $formid
32bd11cb 1855 * @param array $attributes other attributes for the single select
a9967cf5
PS
1856 * @return string HTML fragment
1857 */
32bd11cb
BB
1858 public function single_select($url, $name, array $options, $selected = '',
1859 $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
a9967cf5
PS
1860 if (!($url instanceof moodle_url)) {
1861 $url = new moodle_url($url);
1862 }
f8dab966 1863 $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
a9967cf5 1864
32bd11cb
BB
1865 if (array_key_exists('label', $attributes)) {
1866 $select->set_label($attributes['label']);
1867 unset($attributes['label']);
1868 }
1869 $select->attributes = $attributes;
1870
a9967cf5
PS
1871 return $this->render($select);
1872 }
1873
1874 /**
1875 * Internal implementation of single_select rendering
7a3c215b 1876 *
a9967cf5
PS
1877 * @param single_select $select
1878 * @return string HTML fragment
1879 */
1880 protected function render_single_select(single_select $select) {
1881 $select = clone($select);
1882 if (empty($select->formid)) {
1883 $select->formid = html_writer::random_id('single_select_f');
1884 }
1885
1886 $output = '';
1887 $params = $select->url->params();
1888 if ($select->method === 'post') {
1889 $params['sesskey'] = sesskey();
1890 }
1891 foreach ($params as $name=>$value) {
1892 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
1893 }
1894
1895 if (empty($select->attributes['id'])) {
1896 $select->attributes['id'] = html_writer::random_id('single_select');
1897 }
1898
0b2cb132
PS
1899 if ($select->disabled) {
1900 $select->attributes['disabled'] = 'disabled';
1901 }
4d10e579 1902
a9967cf5
PS
1903 if ($select->tooltip) {
1904 $select->attributes['title'] = $select->tooltip;
1905 }
1906
7266bd3e
ARN
1907 $select->attributes['class'] = 'autosubmit';
1908 if ($select->class) {
1909 $select->attributes['class'] .= ' ' . $select->class;
1910 }
1911
a9967cf5 1912 if ($select->label) {
ecc5cc31 1913 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
a9967cf5
PS
1914 }
1915
1916 if ($select->helpicon instanceof help_icon) {
1917 $output .= $this->render($select->helpicon);
1918 }
a9967cf5
PS
1919 $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
1920
1921 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
ebc583e4 1922 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
a9967cf5
PS
1923
1924 $nothing = empty($select->nothing) ? false : key($select->nothing);
7266bd3e
ARN
1925 $this->page->requires->yui_module('moodle-core-formautosubmit',
1926 'M.core.init_formautosubmit',
1927 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
1928 );
a9967cf5
PS
1929
1930 // then div wrapper for xhtml strictness
26acc814 1931 $output = html_writer::tag('div', $output);
a9967cf5
PS
1932
1933 // now the form itself around it
a12cd69c
DM
1934 if ($select->method === 'get') {
1935 $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
1936 } else {
1937 $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
1938 }
a9967cf5 1939 $formattributes = array('method' => $select->method,
a12cd69c 1940 'action' => $url,
a9967cf5 1941 'id' => $select->formid);
26acc814 1942 $output = html_writer::tag('form', $output, $formattributes);
4d10e579
PS
1943
1944 // and finally one more wrapper with class
26acc814 1945 return html_writer::tag('div', $output, array('class' => $select->class));
4d10e579
PS
1946 }
1947
1948 /**
ab08be98 1949 * Returns a form with a url select widget.
7a3c215b 1950 *
2fada290
MG
1951 * Theme developers: DO NOT OVERRIDE! Please override function
1952 * {@link core_renderer::render_url_select()} instead.
1953 *
4d10e579
PS
1954 * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
1955 * @param string $selected selected element
1956 * @param array $nothing
1957 * @param string $formid
1958 * @return string HTML fragment
1959 */
7a3c215b 1960 public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
4d10e579
PS
1961 $select = new url_select($urls, $selected, $nothing, $formid);
1962 return $this->render($select);
1963 }
1964
1965 /**
ab08be98 1966 * Internal implementation of url_select rendering
7a3c215b
SH
1967 *
1968 * @param url_select $select
4d10e579
PS
1969 * @return string HTML fragment
1970 */
1971 protected function render_url_select(url_select $select) {
c422efcf
PS
1972 global $CFG;
1973
4d10e579
PS
1974 $select = clone($select);
1975 if (empty($select->formid)) {
1976 $select->formid = html_writer::random_id('url_select_f');
1977 }
1978
1979 if (empty($select->attributes['id'])) {
1980 $select->attributes['id'] = html_writer::random_id('url_select');
1981 }
1982
1983 if ($select->disabled) {
1984 $select->attributes['disabled'] = 'disabled';
1985 }
1986
1987 if ($select->tooltip) {
1988 $select->attributes['title'] = $select->tooltip;
1989 }
1990
1991 $output = '';
1992
1993 if ($select->label) {
ecc5cc31 1994 $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
4d10e579
PS
1995 }
1996
50d6ad84
ARN
1997 $classes = array();
1998 if (!$select->showbutton) {
1999 $classes[] = 'autosubmit';
2000 }
7266bd3e 2001 if ($select->class) {
50d6ad84
ARN
2002 $classes[] = $select->class;
2003 }
2004 if (count($classes)) {
2005 $select->attributes['class'] = implode(' ', $classes);
7266bd3e
ARN
2006 }
2007
4d10e579
PS
2008 if ($select->helpicon instanceof help_icon) {
2009 $output .= $this->render($select->helpicon);
2010 }
2011
d4dcfc6b
DM
2012 // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
2013 // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
c422efcf
PS
2014 $urls = array();
2015 foreach ($select->urls as $k=>$v) {
d4dcfc6b
DM
2016 if (is_array($v)) {
2017 // optgroup structure
2018 foreach ($v as $optgrouptitle => $optgroupoptions) {
2019 foreach ($optgroupoptions as $optionurl => $optiontitle) {
2020 if (empty($optionurl)) {
2021 $safeoptionurl = '';
2022 } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
2023 // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
2024 $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
2025 } else if (strpos($optionurl, '/') !== 0) {
2026 debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
2027 continue;
2028 } else {
2029 $safeoptionurl = $optionurl;
2030 }
2031 $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
2032 }
2033 }
2034 } else {
2035 // plain list structure
2036 if (empty($k)) {
2037 // nothing selected option
2038 } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
2039 $k = str_replace($CFG->wwwroot, '', $k);
2040 } else if (strpos($k, '/') !== 0) {
2041 debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
2042 continue;
2043 }
2044 $urls[$k] = $v;
2045 }
2046 }
2047 $selected = $select->selected;
2048 if (!empty($selected)) {
2049 if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
2050 $selected = str_replace($CFG->wwwroot, '', $selected);
2051 } else if (strpos($selected, '/') !== 0) {
2052 debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
c422efcf 2053 }
c422efcf
PS
2054 }
2055
4d10e579 2056 $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
d4dcfc6b 2057 $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
4d10e579 2058
15e48a1a
SM
2059 if (!$select->showbutton) {
2060 $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
ebc583e4 2061 $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
15e48a1a 2062 $nothing = empty($select->nothing) ? false : key($select->nothing);
7266bd3e
ARN
2063 $this->page->requires->yui_module('moodle-core-formautosubmit',
2064 'M.core.init_formautosubmit',
2065 array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
2066 );
15e48a1a
SM
2067 } else {
2068 $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
2069 }
4d10e579
PS
2070
2071 // then div wrapper for xhtml strictness
26acc814 2072 $output = html_writer::tag('div', $output);
4d10e579
PS
2073
2074 // now the form itself around it
2075 $formattributes = array('method' => 'post',
2076 'action' => new moodle_url('/course/jumpto.php'),
2077 'id' => $select->formid);
26acc814 2078 $output = html_writer::tag('form', $output, $formattributes);
a9967cf5
PS
2079
2080 // and finally one more wrapper with class
26acc814 2081 return html_writer::tag('div', $output, array('class' => $select->class));
a9967cf5
PS
2082 }
2083
d9c8f425 2084 /**
2085 * Returns a string containing a link to the user documentation.
2086 * Also contains an icon by default. Shown to teachers and admin only.
7a3c215b 2087 *
d9c8f425 2088 * @param string $path The page link after doc root and language, no leading slash.
2089 * @param string $text The text to be displayed for the link
afe3566c 2090 * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
996b1e0c 2091 * @return string
d9c8f425 2092 */
afe3566c 2093 public function doc_link($path, $text = '', $forcepopup = false) {
8ae8bf8a
PS
2094 global $CFG;
2095
ae4086bd 2096 $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
8ae8bf8a 2097
000c278c 2098 $url = new moodle_url(get_docs_url($path));
8ae8bf8a 2099
c80877aa 2100 $attributes = array('href'=>$url);
afe3566c
ARN
2101 if (!empty($CFG->doctonewwindow) || $forcepopup) {
2102 $attributes['class'] = 'helplinkpopup';
d9c8f425 2103 }
1adaa404 2104
26acc814 2105 return html_writer::tag('a', $icon.$text, $attributes);
d9c8f425 2106 }
2107
000c278c 2108 /**
7a3c215b
SH
2109 * Return HTML for a pix_icon.
2110 *
2fada290
MG
2111 * Theme developers: DO NOT OVERRIDE! Please override function
2112 * {@link core_renderer::render_pix_icon()} instead.
2113 *
000c278c
PS
2114 * @param string $pix short pix name
2115 * @param string $alt mandatory alt attribute
eb557002 2116 * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
000c278c
PS
2117 * @param array $attributes htm lattributes
2118 * @return string HTML fragment
2119 */
2120 public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2121 $icon = new pix_icon($pix, $alt, $component, $attributes);
2122 return $this->render($icon);
2123 }
2124
2125 /**
7a3c215b
SH
2126 * Renders a pix_icon widget and returns the HTML to display it.
2127 *
000c278c
PS
2128 * @param pix_icon $icon
2129 * @return string HTML fragment
2130 */
ce0110bf 2131 protected function render_pix_icon(pix_icon $icon) {
eb42bb7e
DC
2132 $data = $icon->export_for_template($this);
2133 return $this->render_from_template('core/pix_icon', $data);
000c278c
PS
2134 }
2135
d63c5073 2136 /**
7a3c215b
SH
2137 * Return HTML to display an emoticon icon.
2138 *
d63c5073
DM
2139 * @param pix_emoticon $emoticon
2140 * @return string HTML fragment
2141 */
2142 protected function render_pix_emoticon(pix_emoticon $emoticon) {
2143 $attributes = $emoticon->attributes;
2144 $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
2145 return html_writer::empty_tag('img', $attributes);
2146 }
2147
a09aeee4 2148 /**
7a3c215b
SH
2149 * Produces the html that represents this rating in the UI
2150 *
2151 * @param rating $rating the page object on which this rating will appear
2152 * @return string
2153 */
a09aeee4 2154 function render_rating(rating $rating) {
7ac928a7 2155 global $CFG, $USER;
a09aeee4 2156
2b04c41c 2157 if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
63e87951
AD
2158 return null;//ratings are turned off
2159 }
2160
2b04c41c
SH
2161 $ratingmanager = new rating_manager();
2162 // Initialise the JavaScript so ratings can be done by AJAX.
2163 $ratingmanager->initialise_rating_javascript($this->page);
a09aeee4 2164
63e87951
AD
2165 $strrate = get_string("rate", "rating");
2166 $ratinghtml = ''; //the string we'll return
2167
2b04c41c
SH
2168 // permissions check - can they view the aggregate?
2169 if ($rating->user_can_view_aggregate()) {
a09aeee4 2170
2b04c41c
SH
2171 $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2172 $aggregatestr = $rating->get_aggregate_string();
a09aeee4 2173
6278ce45 2174 $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2b04c41c 2175 if ($rating->count > 0) {
6278ce45 2176 $countstr = "({$rating->count})";
d251b259 2177 } else {
6278ce45 2178 $countstr = '-';
d251b259 2179 }
6278ce45 2180 $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
63e87951 2181
c6de9cef 2182 $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
d251b259 2183 if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2b04c41c
SH
2184
2185 $nonpopuplink = $rating->get_view_ratings_url();
2186 $popuplink = $rating->get_view_ratings_url(true);
a09aeee4 2187
d251b259 2188 $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
c6de9cef 2189 $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
d251b259 2190 } else {
c6de9cef 2191 $ratinghtml .= $aggregatehtml;
a09aeee4 2192 }
d251b259 2193 }
a09aeee4 2194
d251b259 2195 $formstart = null;
2b04c41c
SH
2196 // if the item doesn't belong to the current user, the user has permission to rate
2197 // and we're within the assessable period
2198 if ($rating->user_can_rate()) {
771b3fbe 2199
2b04c41c
SH
2200 $rateurl = $rating->get_rate_url();
2201 $inputs = $rateurl->params();
771b3fbe 2202
2b04c41c
SH
2203 //start the rating form
2204 $formattrs = array(
2205 'id' => "postrating{$rating->itemid}",
2206 'class' => 'postratingform',
2207 'method' => 'post',
2208 'action' => $rateurl->out_omit_querystring()
2209 );
2210 $formstart = html_writer::start_tag('form', $formattrs);
2211 $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2212
2213 // add the hidden inputs
2214 foreach ($inputs as $name => $value) {
2215 $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2216 $formstart .= html_writer::empty_tag('input', $attributes);
2217 }
3180bc2c 2218
d251b259
AD
2219 if (empty($ratinghtml)) {
2220 $ratinghtml .= $strrate.': ';
2221 }
d251b259 2222 $ratinghtml = $formstart.$ratinghtml;
63e87951 2223
2b04c41c
SH
2224 $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2225 $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
ecc5cc31 2226 $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2b04c41c 2227 $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
a09aeee4 2228
d251b259 2229 //output submit button
771b3fbe
AD
2230 $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2231
2b04c41c 2232 $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
771b3fbe 2233 $ratinghtml .= html_writer::empty_tag('input', $attributes);
a09aeee4 2234
2b04c41c 2235 if (!$rating->settings->scale->isnumeric) {
eaf52ff0
MN
2236 // If a global scale, try to find current course ID from the context
2237 if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2238 $courseid = $coursecontext->instanceid;
2239 } else {
2240 $courseid = $rating->settings->scale->courseid;
2241 }
2242 $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
a09aeee4 2243 }
771b3fbe
AD
2244 $ratinghtml .= html_writer::end_tag('span');
2245 $ratinghtml .= html_writer::end_tag('div');
2246 $ratinghtml .= html_writer::end_tag('form');
a09aeee4
AD
2247 }
2248
63e87951 2249 return $ratinghtml;
a09aeee4
AD
2250 }
2251
7a3c215b 2252 /**
d9c8f425 2253 * Centered heading with attached help button (same title text)
7a3c215b
SH
2254 * and optional icon attached.
2255 *
4bcc5118 2256 * @param string $text A heading text
53a78cef 2257 * @param string $helpidentifier The keyword that defines a help page
4bcc5118
PS
2258 * @param string $component component name
2259 * @param string|moodle_url $icon
2260 * @param string $iconalt icon alt text
699e2fd0
RW
2261 * @param int $level The level of importance of the heading. Defaulting to 2
2262 * @param string $classnames A space-separated list of CSS classes. Defaulting to null
d9c8f425 2263 * @return string HTML fragment
2264 */
699e2fd0 2265 public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
4bcc5118
PS
2266 $image = '';
2267 if ($icon) {
8ef1aa40 2268 $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
d9c8f425 2269 }
4bcc5118 2270
259c165d
PS
2271 $help = '';
2272 if ($helpidentifier) {
2273 $help = $this->help_icon($helpidentifier, $component);
2274 }
4bcc5118 2275
699e2fd0 2276 return $this->heading($image.$text.$help, $level, $classnames);
d9c8f425 2277 }
2278
2279 /**
7a3c215b 2280 * Returns HTML to display a help icon.
d9c8f425 2281 *
cb616be8 2282 * @deprecated since Moodle 2.0
bf11293a 2283 */
596509e4 2284 public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
a6d81a73 2285 throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
d9c8f425 2286 }
2287
259c165d 2288 /**
7a3c215b 2289 * Returns HTML to display a help icon.
259c165d 2290 *
2fada290
MG
2291 * Theme developers: DO NOT OVERRIDE! Please override function
2292 * {@link core_renderer::render_help_icon()} instead.
2293 *
259c165d
PS
2294 * @param string $identifier The keyword that defines a help page
2295 * @param string $component component name
2296 * @param string|bool $linktext true means use $title as link text, string means link text value
2297 * @return string HTML fragment
2298 */
2299 public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2cf81209 2300 $icon = new help_icon($identifier, $component);
259c165d
PS
2301 $icon->diag_strings();
2302 if ($linktext === true) {
2303 $icon->linktext = get_string($icon->identifier, $icon->component);
2304 } else if (!empty($linktext)) {
2305 $icon->linktext = $linktext;
2306 }
2307 return $this->render($icon);
2308 }
2309
2310 /**
2311 * Implementation of user image rendering.
7a3c215b 2312 *
3d3fae72 2313 * @param help_icon $helpicon A help icon instance
259c165d
PS
2314 * @return string HTML fragment
2315 */
2316 protected function render_help_icon(help_icon $helpicon) {
2317 global $CFG;
2318
2319 // first get the help image icon
2320 $src = $this->pix_url('help');
2321
2322 $title = get_string($helpicon->identifier, $helpicon->component);
2323
2324 if (empty($helpicon->linktext)) {
cab2c7ea 2325 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
259c165d
PS
2326 } else {
2327 $alt = get_string('helpwiththis');
2328 }
2329
2330 $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
2331 $output = html_writer::empty_tag('img', $attributes);
2332
2333 // add the link text if given
2334 if (!empty($helpicon->linktext)) {
2335 // the spacing has to be done through CSS
2336 $output .= $helpicon->linktext;
2337 }
2338
69542fb3
PS
2339 // now create the link around it - we need https on loginhttps pages
2340 $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
259c165d
PS
2341
2342 // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
2343 $title = get_string('helpprefix2', '', trim($title, ". \t"));
2344
e88419a2 2345 $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true', 'target'=>'_blank');
259c165d
PS
2346 $output = html_writer::tag('a', $output, $attributes);
2347
2348 // and finally span
238b8bc9 2349 return html_writer::tag('span', $output, array('class' => 'helptooltip'));
259c165d
PS
2350 }
2351
d9c8f425 2352 /**
7a3c215b 2353 * Returns HTML to display a scale help icon.
d9c8f425 2354 *
4bcc5118 2355 * @param int $courseid
7a3c215b
SH
2356 * @param stdClass $scale instance
2357 * @return string HTML fragment
d9c8f425 2358 */
4bcc5118
PS
2359 public function help_icon_scale($courseid, stdClass $scale) {
2360 global $CFG;
02f64f97 2361
4bcc5118 2362 $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
02f64f97 2363
0029a917 2364 $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
02f64f97 2365
68bf577b
AD
2366 $scaleid = abs($scale->id);
2367
2368 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
230ec401 2369 $action = new popup_action('click', $link, 'ratingscale');
02f64f97 2370
26acc814 2371 return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
d9c8f425 2372 }
2373
2374 /**
2375 * Creates and returns a spacer image with optional line break.
2376 *
3d3fae72
SH
2377 * @param array $attributes Any HTML attributes to add to the spaced.
2378 * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2379 * laxy do it with CSS which is a much better solution.
d9c8f425 2380 * @return string HTML fragment
2381 */
0029a917
PS
2382 public function spacer(array $attributes = null, $br = false) {
2383 $attributes = (array)$attributes;
2384 if (empty($attributes['width'])) {
2385 $attributes['width'] = 1;
1ba862ec 2386 }
e1a5a9cc 2387 if (empty($attributes['height'])) {
0029a917 2388 $attributes['height'] = 1;
d9c8f425 2389 }
0029a917 2390 $attributes['class'] = 'spacer';
d9c8f425 2391
0029a917 2392 $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
b65bfc3e 2393
0029a917 2394 if (!empty($br)) {
1ba862ec
PS
2395 $output .= '<br />';
2396 }
d9c8f425 2397
2398 return $output;
2399 }
2400
d9c8f425 2401 /**
7a3c215b 2402 * Returns HTML to display the specified user's avatar.
d9c8f425 2403 *
5d0c95a5 2404 * User avatar may be obtained in two ways:
d9c8f425 2405 * <pre>
812dbaf7
PS
2406 * // Option 1: (shortcut for simple cases, preferred way)
2407 * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2408 * $OUTPUT->user_picture($user, array('popup'=>true));
2409 *
5d0c95a5
PS
2410 * // Option 2:
2411 * $userpic = new user_picture($user);
d9c8f425 2412 * // Set properties of $userpic
812dbaf7 2413 * $userpic->popup = true;
5d0c95a5 2414 * $OUTPUT->render($userpic);
d9c8f425 2415 * </pre>
2416 *
2fada290
MG
2417 * Theme developers: DO NOT OVERRIDE! Please override function
2418 * {@link core_renderer::render_user_picture()} instead.
2419 *
7a3c215b 2420 * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
812dbaf7 2421 * If any of these are missing, the database is queried. Avoid this
d9c8f425 2422 * if at all possible, particularly for reports. It is very bad for performance.
812dbaf7
PS
2423 * @param array $options associative array with user picture options, used only if not a user_picture object,
2424 * options are:
2425 * - courseid=$this->page->course->id (course id of user profile in link)
2426 * - size=35 (size of image)
2427 * - link=true (make image clickable - the link leads to user profile)
2428 * - popup=false (open in popup)
2429 * - alttext=true (add image alt attribute)
5d0c95a5 2430 * - class = image class attribute (default 'userpicture')
e4a1efcb 2431 * - visibletoscreenreaders=true (whether to be visible to screen readers)
d9c8f425 2432 * @return string HTML fragment
2433 */
5d0c95a5
PS
2434 public function user_picture(stdClass $user, array $options = null) {
2435 $userpicture = new user_picture($user);
2436 foreach ((array)$options as $key=>$value) {
2437 if (array_key_exists($key, $userpicture)) {
2438 $userpicture->$key = $value;
2439 }
2440 }
2441 return $this->render($userpicture);
2442 }
2443
2444 /**
2445 * Internal implementation of user image rendering.
7a3c215b 2446 *
5d0c95a5
PS
2447 * @param user_picture $userpicture
2448 * @return string
2449 */
2450 protected function render_user_picture(user_picture $userpicture) {
2451 global $CFG, $DB;
812dbaf7 2452
5d0c95a5
PS
2453 $user = $userpicture->user;
2454
2455 if ($userpicture->alttext) {
2456 if (!empty($user->imagealt)) {
2457 $alt = $user->imagealt;
2458 } else {
2459 $alt = get_string('pictureof', '', fullname($user));
2460 }
d9c8f425 2461 } else {
97c10099 2462 $alt = '';
5d0c95a5
PS
2463 }
2464
2465 if (empty($userpicture->size)) {
5d0c95a5
PS
2466 $size = 35;
2467 } else if ($userpicture->size === true or $userpicture->size == 1) {
5d0c95a5 2468 $size = 100;
5d0c95a5 2469 } else {
5d0c95a5 2470 $size = $userpicture->size;
d9c8f425 2471 }
2472
5d0c95a5 2473 $class = $userpicture->class;
d9c8f425 2474
4d254790 2475 if ($user->picture == 0) {
5d0c95a5 2476 $class .= ' defaultuserpic';
5d0c95a5 2477 }
d9c8f425 2478
871a3ec5
SH
2479 $src = $userpicture->get_url($this->page, $this);
2480
29cf6631 2481 $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
e4a1efcb
JC
2482 if (!$userpicture->visibletoscreenreaders) {
2483 $attributes['role'] = 'presentation';
2484 }
2485
5d0c95a5 2486 // get the image html output fisrt
0e35ba6f 2487 $output = html_writer::empty_tag('img', $attributes);
5d0c95a5
PS
2488
2489 // then wrap it in link if needed
2490 if (!$userpicture->link) {
2491 return $output;
d9c8f425 2492 }
2493
5d0c95a5
PS
2494 if (empty($userpicture->courseid)) {
2495 $courseid = $this->page->course->id;
2496 } else {
2497 $courseid = $userpicture->courseid;
2498 }
2499
03d9401e
MD
2500 if ($courseid == SITEID) {
2501 $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2502 } else {
2503 $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2504 }
5d0c95a5
PS
2505
2506 $attributes = array('href'=>$url);
e4a1efcb 2507 if (!$userpicture->visibletoscreenreaders) {
e4a1efcb
JC
2508 $attributes['tabindex'] = '-1';
2509 $attributes['aria-hidden'] = 'true';
2510 }
5d0c95a5
PS
2511
2512 if ($userpicture->popup) {
2513 $id = html_writer::random_id('userpicture');
2514 $attributes['id'] = $id;
c80877aa 2515 $this->add_action_handler(new popup_action('click', $url), $id);
5d0c95a5
PS
2516 }
2517
26acc814 2518 return html_writer::tag('a', $output, $attributes);
d9c8f425 2519 }
b80ef420 2520
b80ef420
DC
2521 /**
2522 * Internal implementation of file tree viewer items rendering.
7a3c215b 2523 *
b80ef420
DC
2524 * @param array $dir
2525 * @return string
2526 */
2527 public function htmllize_file_tree($dir) {
2528 if (empty($dir['subdirs']) and empty($dir['files'])) {
2529 return '';
2530 }
2531 $result = '<ul>';
2532 foreach ($dir['subdirs'] as $subdir) {
2533 $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2534 }
2535 foreach ($dir['files'] as $file) {
2536 $filename = $file->get_filename();
2537 $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2538 }
2539 $result .= '</ul>';
2540
2541 return $result;
2542 }
7a3c215b 2543
bb496de7 2544 /**
7a3c215b 2545 * Returns HTML to display the file picker
bb496de7
DC
2546 *
2547 * <pre>
2548 * $OUTPUT->file_picker($options);
2549 * </pre>
2550 *
2fada290
MG
2551 * Theme developers: DO NOT OVERRIDE! Please override function
2552 * {@link core_renderer::render_file_picker()} instead.
2553 *
bb496de7
DC
2554 * @param array $options associative array with file manager options
2555 * options are:
2556 * maxbytes=>-1,
2557 * itemid=>0,
2558 * client_id=>uniqid(),
2559 * acepted_types=>'*',
2560 * return_types=>FILE_INTERNAL,
2561 * context=>$PAGE->context
2562 * @return string HTML fragment
2563 */
2564 public function file_picker($options) {
2565 $fp = new file_picker($options);
2566 return $this->render($fp);
2567 }
7a3c215b 2568
b80ef420
DC
2569 /**
2570 * Internal implementation of file picker rendering.
7a3c215b 2571 *
b80ef420
DC
2572 * @param file_picker $fp
2573 * @return string
2574 */
bb496de7
DC
2575 public function render_file_picker(file_picker $fp) {
2576 global $CFG, $OUTPUT, $USER;
2577 $options = $fp->options;
2578 $client_id = $options->client_id;
2579 $strsaved = get_string('filesaved', 'repository');
2580 $straddfile = get_string('openpicker', 'repository');
2581 $strloading = get_string('loading', 'repository');
adce0230 2582 $strdndenabled = get_string('dndenabled_inbox', 'moodle');
906e7d89 2583 $strdroptoupload = get_string('droptoupload', 'moodle');
bb496de7
DC
2584 $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
2585
2586 $currentfile = $options->currentfile;
2587 if (empty($currentfile)) {
322945e9
FM
2588 $currentfile = '';
2589 } else {
2590 $currentfile .= ' - ';
bb496de7 2591 }
b817205b
DC
2592 if ($options->maxbytes) {
2593 $size = $options->maxbytes;
2594 } else {
2595 $size = get_max_upload_file_size();
2596 }
513aed3c 2597 if ($size == -1) {
831399c4 2598 $maxsize = '';
513aed3c
DC
2599 } else {
2600 $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
2601 }
f50a61fb 2602 if ($options->buttonname) {
4b72f9eb
AW
2603 $buttonname = ' name="' . $options->buttonname . '"';
2604 } else {
2605 $buttonname = '';
2606 }
bb496de7
DC
2607 $html = <<<EOD
2608<div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2609$icon_progress
2610</div>
2611<div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
2612 <div>
c81f3328 2613 <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
fa7f2a45 2614 <span> $maxsize </span>
bb496de7
DC
2615 </div>
2616EOD;
2617 if ($options->env != 'url') {
2618 $html .= <<<EOD
50597880 2619 <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
a9352f1f 2620 <div class="filepicker-filename">
08a6a19d 2621 <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
0f94289c 2622 <div class="dndupload-progressbars"></div>
a9352f1f 2623 </div>
08a6a19d 2624 <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
f08fac7c 2625 </div>
bb496de7
DC
2626EOD;
2627 }
2628 $html .= '</div>';
2629 return $html;
2630 }
d9c8f425 2631
2632 /**
7a3c215b 2633 * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
d9c8f425 2634 *
2635 * @param string $cmid the course_module id.
2636 * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
2637 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2638 */
2639 public function update_module_button($cmid, $modulename) {
2640 global $CFG;
b0c6dc1c 2641 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
d9c8f425 2642 $modulename = get_string('modulename', $modulename);
2643 $string = get_string('updatethis', '', $modulename);
3ba60ee1
PS
2644 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2645 return $this->single_button($url, $string);
d9c8f425 2646 } else {
2647 return '';
2648 }
2649 }
2650
2651 /**
7a3c215b
SH
2652 * Returns HTML to display a "Turn editing on/off" button in a form.
2653 *
d9c8f425 2654 * @param moodle_url $url The URL + params to send through when clicking the button
2655 * @return string HTML the button
2656 */
2657 public function edit_button(moodle_url $url) {
3362dfdc
EL
2658
2659 $url->param('sesskey', sesskey());
2660 if ($this->page->user_is_editing()) {
2661 $url->param('edit', 'off');
2662 $editstring = get_string('turneditingoff');
d9c8f425 2663 } else {
3362dfdc
EL
2664 $url->param('edit', 'on');
2665 $editstring = get_string('turneditingon');
d9c8f425 2666 }
2667
3362dfdc 2668 return $this->single_button($url, $editstring);
d9c8f425 2669 }
2670
d9c8f425 2671 /**
7a3c215b 2672 * Returns HTML to display a simple button to close a window
d9c8f425 2673 *
d9c8f425 2674 * @param string $text The lang string for the button's label (already output from get_string())
3ba60ee1 2675 * @return string html fragment
d9c8f425 2676 */
7a5c78e0 2677 public function close_window_button($text='') {
d9c8f425 2678 if (empty($text)) {
2679 $text = get_string('closewindow');
2680 }
a6855934
PS
2681 $button = new single_button(new moodle_url('#'), $text, 'get');
2682 $button->add_action(new component_action('click', 'close_window'));
3ba60ee1
PS
2683
2684 return $this->container($this->render($button), 'closewindow');
d9c8f425 2685 }
2686
d9c8f425 2687 /**
2688 * Output an error message. By default wraps the error message in <span class="error">.
2689 * If the error message is blank, nothing is output.
7a3c215b 2690 *
d9c8f425 2691 * @param string $message the error message.
2692 * @return string the HTML to output.
2693 */
2694 public function error_text($message) {
2695 if (empty($message)) {
2696 return '';
2697 }
3246648b 2698 $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
26acc814 2699 return html_writer::tag('span', $message, array('class' => 'error'));
d9c8f425 2700 }
2701
2702 /**
2703 * Do not call this function directly.
2704 *
f8129210 2705 * To terminate the current script with a fatal error, call the {@link print_error}
d9c8f425 2706 * function, or throw an exception. Doing either of those things will then call this
2707 * function to display the error, before terminating the execution.
2708 *
2709 * @param string $message The message to output
2710 * @param string $moreinfourl URL where more info can be found about the error
2711 * @param string $link Link for the Continue button
2712 * @param array $backtrace The execution backtrace
2713 * @param string $debuginfo Debugging information
d9c8f425 2714 * @return string the HTML to output.
2715 */
83267ec0 2716 public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
6bd8d7e7 2717 global $CFG;
d9c8f425 2718
2719 $output = '';
6f8f4d83 2720 $obbuffer = '';
e57c283d 2721
d9c8f425 2722 if ($this->has_started()) {
50764d37
PS
2723 // we can not always recover properly here, we have problems with output buffering,
2724 // html tables, etc.
d9c8f425 2725 $output .= $this->opencontainers->pop_all_but_last();
50764d37 2726
d9c8f425 2727 } else {
50764d37
PS
2728 // It is really bad if library code throws exception when output buffering is on,
2729 // because the buffered text would be printed before our start of page.
2730 // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
6bd8d7e7 2731 error_reporting(0); // disable notices from gzip compression, etc.
50764d37 2732 while (ob_get_level() > 0) {
2cadd443
PS
2733 $buff = ob_get_clean();
2734 if ($buff === false) {
2735 break;
2736 }
2737 $obbuffer .= $buff;
50764d37 2738 }
6bd8d7e7 2739 error_reporting($CFG->debug);
6f8f4d83 2740
f22f1caf
PS
2741 // Output not yet started.
2742 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2743 if (empty($_SERVER['HTTP_RANGE'])) {
2744 @header($protocol . ' 404 Not Found');
2745 } else {
2746 // Must stop byteserving attempts somehow,
2747 // this is weird but Chrome PDF viewer can be stopped only with 407!
2748 @header($protocol . ' 407 Proxy Authentication Required');
85309744 2749 }
f22f1caf 2750
eb5bdb35 2751 $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
7fde1e4b 2752 $this->page->set_url('/'); // no url
191b267b 2753 //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
dcfb9b78 2754 $this->page->set_title(get_string('error'));
8093188f 2755 $this->page->set_heading($this->page->course->fullname);
d9c8f425 2756 $output .= $this->header();
2757 }
2758
2759 $message = '<p class="errormessage">' . $message . '</p>'.
2760 '<p class="errorcode"><a href="' . $moreinfourl . '">' .
2761 get_string('moreinformation') . '</a></p>';
1ad8143a
PS
2762 if (empty($CFG->rolesactive)) {
2763 $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2764 //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.
2765 }
4c2892c6 2766 $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
d9c8f425 2767
96f81ea3 2768 if ($CFG->debugdeveloper) {
6f8f4d83 2769 if (!empty($debuginfo)) {
c5d18164
PS
2770 $debuginfo = s($debuginfo); // removes all nasty JS
2771 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2772 $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
6f8f4d83
PS
2773 }
2774 if (!empty($backtrace)) {
2775 $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
2776 }
2777 if ($obbuffer !== '' ) {
2778 $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
2779 }
d9c8f425 2780 }
2781
3efe6bbb
PS
2782 if (empty($CFG->rolesactive)) {
2783 // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
2784 } else if (!empty($link)) {
d9c8f425 2785 $output .= $this->continue_button($link);
2786 }
2787
2788 $output .= $this->footer();
2789
2790 // Padding to encourage IE to display our error page, rather than its own.
2791 $output .= str_repeat(' ', 512);
2792
2793 return $output;
2794 }
2795
2796 /**
24346803 2797 * Output a notification (that is, a status message about something that has just happened).
d9c8f425 2798 *
0346323c
AN
2799 * Note: \core\notification::add() may be more suitable for your usage.
2800 *
24346803
AN
2801 * @param string $message The message to print out.
2802 * @param string $type The type of notification. See constants on \core\output\notification.
d9c8f425 2803 * @return string the HTML to output.
2804 */
24346803
AN
2805 public function notification($message, $type = null) {
2806 $typemappings = [
2807 // Valid types.
2808 'success' => \core\output\notification::NOTIFY_SUCCESS,
2809 'info' => \core\output\notification::NOTIFY_INFO,
2810 'warning' => \core\output\notification::NOTIFY_WARNING,
2811 'error' => \core\output\notification::NOTIFY_ERROR,
2812
2813 // Legacy types mapped to current types.
2814 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
2815 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
2816 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
2817 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
2818 'notifymessage' => \core\output\notification::NOTIFY_INFO,
2819 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
2820 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
2821 ];
2822
2823 $extraclasses = [];
2824
2825 if ($type) {
2826 if (strpos($type, ' ') === false) {
2827 // No spaces in the list of classes, therefore no need to loop over and determine the class.
2828 if (isset($typemappings[$type])) {
2829 $type = $typemappings[$type];
2830 } else {
2831 // The value provided did not match a known type. It must be an extra class.
2832 $extraclasses = [$type];
2833 }
2834 } else {
2835 // Identify what type of notification this is.
2836 $classarray = explode(' ', self::prepare_classes($type));
2837
2838 // Separate out the type of notification from the extra classes.
2839 foreach ($classarray as $class) {
2840 if (isset($typemappings[$class])) {
2841 $type = $typemappings[$class];
2842 } else {
2843 $extraclasses[] = $class;
2844 }
263fb9d1
JC
2845 }
2846 }
2847 }
2848
24346803
AN
2849 $notification = new \core\output\notification($message, $type);
2850 if (count($extraclasses)) {
2851 $notification->set_extra_classes($extraclasses);
2852 }
263fb9d1 2853
24346803
AN
2854 // Return the rendered template.
2855 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
263fb9d1
JC
2856 }
2857
2858 /**
2859 * Output a notification at a particular level - in this case, NOTIFY_PROBLEM.
2860 *
2861 * @param string $message the message to print out
2862 * @return string HTML fragment.
24346803
AN
2863 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2864 * @todo MDL-53113 This will be removed in Moodle 3.5.
2865 * @see \core\output\notification
263fb9d1
JC
2866 */
2867 public function notify_problem($message) {
24346803 2868 debugging(__FUNCTION__ . ' is deprecated.' .
0346323c 2869 'Please use \core\notification::add, or \core\output\notification as required',
24346803
AN
2870 DEBUG_DEVELOPER);
2871 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_ERROR);
263fb9d1
JC
2872 return $this->render($n);
2873 }
2874
2875 /**
2876 * Output a notification at a particular level - in this case, NOTIFY_SUCCESS.
2877 *
2878 * @param string $message the message to print out
2879 * @return string HTML fragment.
24346803
AN
2880 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2881 * @todo MDL-53113 This will be removed in Moodle 3.5.
2882 * @see \core\output\notification
263fb9d1
JC
2883 */
2884 public function notify_success($message) {
24346803 2885 debugging(__FUNCTION__ . ' is deprecated.' .
0346323c 2886 'Please use \core\notification::add, or \core\output\notification as required',
24346803 2887 DEBUG_DEVELOPER);
263fb9d1
JC
2888 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_SUCCESS);
2889 return $this->render($n);
2890 }
2891
2892 /**
2893 * Output a notification at a particular level - in this case, NOTIFY_MESSAGE.
2894 *
2895 * @param string $message the message to print out
2896 * @return string HTML fragment.
24346803
AN
2897 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2898 * @todo MDL-53113 This will be removed in Moodle 3.5.
2899 * @see \core\output\notification
263fb9d1
JC
2900 */
2901 public function notify_message($message) {
24346803 2902 debugging(__FUNCTION__ . ' is deprecated.' .
0346323c 2903 'Please use \core\notification::add, or \core\output\notification as required',
24346803
AN
2904 DEBUG_DEVELOPER);
2905 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_INFO);
263fb9d1
JC
2906 return $this->render($n);
2907 }
2908
2909 /**
2910 * Output a notification at a particular level - in this case, NOTIFY_REDIRECT.
2911 *
2912 * @param string $message the message to print out
2913 * @return string HTML fragment.
24346803
AN
2914 * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
2915 * @todo MDL-53113 This will be removed in Moodle 3.5.
2916 * @see \core\output\notification
263fb9d1
JC
2917 */
2918 public function notify_redirect($message) {
24346803 2919 debugging(__FUNCTION__ . ' is deprecated.' .
0346323c 2920 'Please use \core\notification::add, or \core\output\notification as required',
24346803
AN
2921 DEBUG_DEVELOPER);
2922 $n = new \core\output\notification($message, \core\output\notification::NOTIFY_INFO);
263fb9d1
JC
2923 return $this->render($n);
2924 }
2925
2926 /**
2927 * Render a notification (that is, a status message about something that has
2928 * just happened).
2929 *
2930 * @param \core\output\notification $notification the notification to print out
2931 * @return string the HTML to output.
2932 */
2933 protected function render_notification(\core\output\notification $notification) {
24346803 2934 return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
d9c8f425 2935 }
2936
2937 /**
7a3c215b 2938 * Returns HTML to display a continue button that goes to a particular URL.
d9c8f425 2939 *
3ba60ee1 2940 * @param string|moodle_url $url The url the button goes to.
d9c8f425 2941 * @return string the HTML to output.
2942 */
3ba60ee1
PS
2943 public function continue_button($url) {
2944 if (!($url instanceof moodle_url)) {
2945 $url = new moodle_url($url);
d9c8f425 2946 }
3ba60ee1
PS
2947 $button = new single_button($url, get_string('continue'), 'get');
2948 $button->class = 'continuebutton';
d9c8f425 2949
3ba60ee1 2950 return $this->render($button);
d9c8f425 2951 }
2952
2953 /**
7a3c215b 2954 * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
d9c8f425 2955 *
2fada290
MG
2956 * Theme developers: DO NOT OVERRIDE! Please override function
2957 * {@link core_renderer::render_paging_bar()} instead.
2958 *
71c03ac1 2959 * @param int $totalcount The total number of entries available to be paged through
929d7a83
PS
2960 * @param int $page The page you are currently viewing
2961 * @param int $perpage The number of entries that should be shown per page
2962 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2963 * @param string $pagevar name of page parameter that holds the page number
d9c8f425 2964 * @return string the HTML to output.
2965 */
929d7a83
PS
2966 public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2967 $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
2968 return $this->render($pb);
2969 }
2970
2971 /**
2972 * Internal implementation of paging bar rendering.
7a3c215b 2973 *
929d7a83
PS
2974 * @param paging_bar $pagingbar
2975 * @return string
2976 */
2977 protected function render_paging_bar(paging_bar $pagingbar) {
d9c8f425 2978 $output = '';
2979 $pagingbar = clone($pagingbar);
34059565 2980 $pagingbar->prepare($this, $this->page, $this->target);
d9c8f425 2981
2982 if ($pagingbar->totalcount > $pagingbar->perpage) {
2983 $output .= get_string('page') . ':';
2984
2985 if (!empty($pagingbar->previouslink)) {
b146b6a8 2986 $output .= ' (' . $pagingbar->previouslink . ') ';
d9c8f425 2987 }
2988
2989 if (!empty($pagingbar->firstlink)) {
b146b6a8 2990 $output .= ' ' . $pagingbar->firstlink . ' ...';
d9c8f425 2991 }
2992
2993 foreach ($pagingbar->pagelinks as $link) {
b146b6a8 2994 $output .= " $link";
d9c8f425 2995 }
2996
2997 if (!empty($pagingbar->lastlink)) {
b146b6a8 2998 $output .= ' ...' . $pagingbar->lastlink . ' ';
d9c8f425 2999 }
3000
3001 if (!empty($pagingbar->nextlink)) {
b146b6a8 3002 $output .= ' (' . $pagingbar->nextlink . ')';
d9c8f425 3003 }
3004 }
3005
26acc814 3006 return html_writer::tag('div', $output, array('class' => 'paging'));
d9c8f425 3007 }
3008
d9c8f425 3009 /**
3010 * Output the place a skip link goes to.
7a3c215b 3011 *
d9c8f425 3012 * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3013 * @return string the HTML to output.
3014 */
fe213365 3015 public function skip_link_target($id = null) {
9e8d0842 3016 return html_writer::span('', '', array('id' => $id));
d9c8f425 3017 }
3018
3019 /**
3020 * Outputs a heading
7a3c215b 3021 *
d9c8f425 3022 * @param string $text The text of the heading
3023 * @param int $level The level of importance of the heading. Defaulting to 2
699e2fd0 3024 * @param string $classes A space-separated list of CSS classes. Defaulting to null
d9c8f425 3025 * @param string $id An optional ID
3026 * @return string the HTML to output.
3027 */
699e2fd0 3028 public function heading($text, $level = 2, $classes = null, $id = null) {
d9c8f425 3029 $level = (integer) $level;
3030 if ($level < 1 or $level > 6) {
3031 throw new coding_exception('Heading level must be an integer between 1 and 6.');
3032 }
26acc814 3033 return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
d9c8f425 3034 }
3035
3036 /**
3037 * Outputs a box.
7a3c215b 3038 *
d9c8f425 3039 * @param string $contents The contents of the box
3040 * @param string $classes A space-separated list of CSS classes
3041 * @param string $id An optional ID
3e76c7fa 3042 * @param array $attributes An array of other attributes to give the box.
d9c8f425 3043 * @return string the HTML to output.
3044 */
3e76c7fa
SH
3045 public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3046 return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
d9c8f425 3047 }
3048
3049 /**
3d3fae72 3050 * Outputs the opening section of a box.
7a3c215b 3051 *
d9c8f425 3052 * @param string $classes A space-separated list of CSS classes
3053 * @param string $id An optional ID
3e76c7fa 3054 * @param array $attributes An array of other attributes to give the box.
d9c8f425 3055 * @return string the HTML to output.
3056 */
3e76c7fa 3057 public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
5d0c95a5 3058 $this->opencontainers->push('box', html_writer::end_tag('div'));
3e76c7fa
SH
3059 $attributes['id'] = $id;
3060 $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
3061 return html_writer::start_tag('div', $attributes);
d9c8f425 3062 }
3063
3064 /**
3065 * Outputs the closing section of a box.
7a3c215b 3066 *
d9c8f425 3067 * @return string the HTML to output.
3068 */
3069 public function box_end() {