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