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