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