-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathWebDebugToolbarListener.php
157 lines (136 loc) · 5.88 KB
/
WebDebugToolbarListener.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\WebProfilerBundle\EventListener;
use Symfony\Bundle\FullStack;
use Symfony\Bundle\WebProfilerBundle\Csp\ContentSecurityPolicyHandler;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Flash\AutoExpireFlashBag;
use Symfony\Component\HttpKernel\DataCollector\DumpDataCollector;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Environment;
/**
* WebDebugToolbarListener injects the Web Debug Toolbar.
*
* The onKernelResponse method must be connected to the kernel.response event.
*
* The WDT is only injected on well-formed HTML (with a proper </body> tag).
* This means that the WDT is never included in sub-requests or ESI requests.
*
* @author Fabien Potencier <[email protected]>
*
* @final
*/
class WebDebugToolbarListener implements EventSubscriberInterface
{
public const DISABLED = 1;
public const ENABLED = 2;
public function __construct(
private Environment $twig,
private bool $interceptRedirects = false,
private int $mode = self::ENABLED,
private ?UrlGeneratorInterface $urlGenerator = null,
private string $excludedAjaxPaths = '^/bundles|^/_wdt',
private ?ContentSecurityPolicyHandler $cspHandler = null,
private ?DumpDataCollector $dumpDataCollector = null,
) {
}
public function isEnabled(): bool
{
return self::DISABLED !== $this->mode;
}
public function setMode(int $mode): void
{
if (self::DISABLED !== $mode && self::ENABLED !== $mode) {
throw new \InvalidArgumentException(\sprintf('Invalid value provided for mode, use one of "%s::DISABLED" or "%s::ENABLED".', self::class, self::class));
}
$this->mode = $mode;
}
public function onKernelResponse(ResponseEvent $event): void
{
$response = $event->getResponse();
$request = $event->getRequest();
if ($response->headers->has('X-Debug-Token') && null !== $this->urlGenerator) {
try {
$response->headers->set(
'X-Debug-Token-Link',
$this->urlGenerator->generate('_profiler', ['token' => $response->headers->get('X-Debug-Token')], UrlGeneratorInterface::ABSOLUTE_URL)
);
} catch (\Exception $e) {
$response->headers->set('X-Debug-Error', $e::class.': '.preg_replace('/\s+/', ' ', $e->getMessage()));
}
}
if (!$event->isMainRequest()) {
return;
}
$nonces = [];
if ($this->cspHandler) {
if ($this->dumpDataCollector?->getDumpsCount() > 0) {
$this->cspHandler->disableCsp();
}
$nonces = $this->cspHandler->updateResponseHeaders($request, $response);
}
// do not capture redirects or modify XML HTTP Requests
if ($request->isXmlHttpRequest()) {
return;
}
if ($response->headers->has('X-Debug-Token') && $response->isRedirect() && $this->interceptRedirects && 'html' === $request->getRequestFormat() && $response->headers->has('Location')) {
if ($request->hasSession() && ($session = $request->getSession())->isStarted() && $session->getFlashBag() instanceof AutoExpireFlashBag) {
// keep current flashes for one more request if using AutoExpireFlashBag
$session->getFlashBag()->setAll($session->getFlashBag()->peekAll());
}
$response->setContent($this->twig->render('@WebProfiler/Profiler/toolbar_redirect.html.twig', ['location' => $response->headers->get('Location'), 'host' => $request->getSchemeAndHttpHost()]));
$response->setStatusCode(200);
$response->headers->remove('Location');
}
if (self::DISABLED === $this->mode
|| !$response->headers->has('X-Debug-Token')
|| $response->isRedirection()
|| ($response->headers->has('Content-Type') && !str_contains($response->headers->get('Content-Type') ?? '', 'html'))
|| 'html' !== $request->getRequestFormat()
|| false !== stripos($response->headers->get('Content-Disposition', ''), 'attachment;')
) {
return;
}
$this->injectToolbar($response, $request, $nonces);
}
/**
* Injects the web debug toolbar into the given Response.
*/
protected function injectToolbar(Response $response, Request $request, array $nonces): void
{
$content = $response->getContent();
$pos = strripos($content, '</body>');
if (false !== $pos) {
$toolbar = "\n".str_replace("\n", '', $this->twig->render(
'@WebProfiler/Profiler/toolbar_js.html.twig',
[
'full_stack' => class_exists(FullStack::class),
'excluded_ajax_paths' => $this->excludedAjaxPaths,
'token' => $response->headers->get('X-Debug-Token'),
'request' => $request,
'csp_script_nonce' => $nonces['csp_script_nonce'] ?? null,
'csp_style_nonce' => $nonces['csp_style_nonce'] ?? null,
]
))."\n";
$content = substr($content, 0, $pos).$toolbar.substr($content, $pos);
$response->setContent($content);
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => ['onKernelResponse', -128],
];
}
}