RequestDataCollector.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\DataCollector;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. use Symfony\Component\HttpFoundation\Cookie;
  13. use Symfony\Component\HttpFoundation\ParameterBag;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\RequestStack;
  16. use Symfony\Component\HttpFoundation\Response;
  17. use Symfony\Component\HttpFoundation\Session\SessionBagInterface;
  18. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  19. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  20. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  21. use Symfony\Component\HttpKernel\KernelEvents;
  22. use Symfony\Component\VarDumper\Cloner\Data;
  23. /**
  24. * @author Fabien Potencier <fabien@symfony.com>
  25. *
  26. * @final
  27. */
  28. class RequestDataCollector extends DataCollector implements EventSubscriberInterface, LateDataCollectorInterface
  29. {
  30. /**
  31. * @var \SplObjectStorage<Request, callable>
  32. */
  33. private \SplObjectStorage $controllers;
  34. private array $sessionUsages = [];
  35. public function __construct(
  36. private ?RequestStack $requestStack = null,
  37. ) {
  38. $this->controllers = new \SplObjectStorage();
  39. }
  40. public function collect(Request $request, Response $response, ?\Throwable $exception = null): void
  41. {
  42. // attributes are serialized and as they can be anything, they need to be converted to strings.
  43. $attributes = [];
  44. $route = '';
  45. foreach ($request->attributes->all() as $key => $value) {
  46. if ('_route' === $key) {
  47. $route = \is_object($value) ? $value->getPath() : $value;
  48. $attributes[$key] = $route;
  49. } else {
  50. $attributes[$key] = $value;
  51. }
  52. }
  53. $content = $request->getContent();
  54. $sessionMetadata = [];
  55. $sessionAttributes = [];
  56. $flashes = [];
  57. if (!$request->attributes->getBoolean('_stateless') && $request->hasSession()) {
  58. $session = $request->getSession();
  59. if ($session->isStarted()) {
  60. $sessionMetadata['Created'] = date(\DATE_RFC822, $session->getMetadataBag()->getCreated());
  61. $sessionMetadata['Last used'] = date(\DATE_RFC822, $session->getMetadataBag()->getLastUsed());
  62. $sessionMetadata['Lifetime'] = $session->getMetadataBag()->getLifetime();
  63. $sessionAttributes = $session->all();
  64. $flashes = $session->getFlashBag()->peekAll();
  65. }
  66. }
  67. $statusCode = $response->getStatusCode();
  68. $responseCookies = [];
  69. foreach ($response->headers->getCookies() as $cookie) {
  70. $responseCookies[$cookie->getName()] = $cookie;
  71. }
  72. $dotenvVars = [];
  73. foreach (explode(',', $_SERVER['SYMFONY_DOTENV_VARS'] ?? $_ENV['SYMFONY_DOTENV_VARS'] ?? '') as $name) {
  74. if ('' !== $name && isset($_ENV[$name])) {
  75. $dotenvVars[$name] = $_ENV[$name];
  76. }
  77. }
  78. $this->data = [
  79. 'method' => $request->getMethod(),
  80. 'format' => $request->getRequestFormat(),
  81. 'content_type' => $response->headers->get('Content-Type', 'text/html'),
  82. 'status_text' => Response::$statusTexts[$statusCode] ?? '',
  83. 'status_code' => $statusCode,
  84. 'request_query' => $request->query->all(),
  85. 'request_request' => $request->request->all(),
  86. 'request_files' => $request->files->all(),
  87. 'request_headers' => $request->headers->all(),
  88. 'request_server' => $request->server->all(),
  89. 'request_cookies' => $request->cookies->all(),
  90. 'request_attributes' => $attributes,
  91. 'route' => $route,
  92. 'response_headers' => $response->headers->all(),
  93. 'response_cookies' => $responseCookies,
  94. 'session_metadata' => $sessionMetadata,
  95. 'session_attributes' => $sessionAttributes,
  96. 'session_usages' => array_values($this->sessionUsages),
  97. 'stateless_check' => $this->requestStack?->getMainRequest()?->attributes->get('_stateless') ?? false,
  98. 'flashes' => $flashes,
  99. 'path_info' => $request->getPathInfo(),
  100. 'controller' => 'n/a',
  101. 'locale' => $request->getLocale(),
  102. 'dotenv_vars' => $dotenvVars,
  103. ];
  104. if (isset($this->data['request_headers']['php-auth-pw'])) {
  105. $this->data['request_headers']['php-auth-pw'] = '******';
  106. }
  107. if (isset($this->data['request_server']['PHP_AUTH_PW'])) {
  108. $this->data['request_server']['PHP_AUTH_PW'] = '******';
  109. }
  110. if (isset($this->data['request_request']['_password'])) {
  111. $encodedPassword = rawurlencode($this->data['request_request']['_password']);
  112. $content = str_replace('_password='.$encodedPassword, '_password=******', $content);
  113. $this->data['request_request']['_password'] = '******';
  114. }
  115. $this->data['content'] = $content;
  116. foreach ($this->data as $key => $value) {
  117. if (!\is_array($value)) {
  118. continue;
  119. }
  120. if ('request_headers' === $key || 'response_headers' === $key) {
  121. $this->data[$key] = array_map(fn ($v) => isset($v[0]) && !isset($v[1]) ? $v[0] : $v, $value);
  122. }
  123. }
  124. if (isset($this->controllers[$request])) {
  125. $this->data['controller'] = $this->parseController($this->controllers[$request]);
  126. unset($this->controllers[$request]);
  127. }
  128. if ($request->attributes->has('_redirected') && $redirectCookie = $request->cookies->get('sf_redirect')) {
  129. $this->data['redirect'] = json_decode($redirectCookie, true);
  130. $response->headers->clearCookie('sf_redirect');
  131. }
  132. if ($response->isRedirect()) {
  133. $response->headers->setCookie(new Cookie(
  134. 'sf_redirect',
  135. json_encode([
  136. 'token' => $response->headers->get('x-debug-token'),
  137. 'route' => $request->attributes->get('_route', 'n/a'),
  138. 'method' => $request->getMethod(),
  139. 'controller' => $this->parseController($request->attributes->get('_controller')),
  140. 'status_code' => $statusCode,
  141. 'status_text' => Response::$statusTexts[$statusCode],
  142. ]),
  143. 0, '/', null, $request->isSecure(), true, false, 'lax'
  144. ));
  145. }
  146. $this->data['identifier'] = $this->data['route'] ?: (\is_array($this->data['controller']) ? $this->data['controller']['class'].'::'.$this->data['controller']['method'].'()' : $this->data['controller']);
  147. if ($response->headers->has('x-previous-debug-token')) {
  148. $this->data['forward_token'] = $response->headers->get('x-previous-debug-token');
  149. }
  150. }
  151. public function lateCollect(): void
  152. {
  153. $this->data = $this->cloneVar($this->data);
  154. }
  155. public function reset(): void
  156. {
  157. parent::reset();
  158. $this->controllers = new \SplObjectStorage();
  159. $this->sessionUsages = [];
  160. }
  161. public function getMethod(): string
  162. {
  163. return $this->data['method'];
  164. }
  165. public function getPathInfo(): string
  166. {
  167. return $this->data['path_info'];
  168. }
  169. public function getRequestRequest(): ParameterBag
  170. {
  171. return new ParameterBag($this->data['request_request']->getValue());
  172. }
  173. public function getRequestQuery(): ParameterBag
  174. {
  175. return new ParameterBag($this->data['request_query']->getValue());
  176. }
  177. public function getRequestFiles(): ParameterBag
  178. {
  179. return new ParameterBag($this->data['request_files']->getValue());
  180. }
  181. public function getRequestHeaders(): ParameterBag
  182. {
  183. return new ParameterBag($this->data['request_headers']->getValue());
  184. }
  185. public function getRequestServer(bool $raw = false): ParameterBag
  186. {
  187. return new ParameterBag($this->data['request_server']->getValue($raw));
  188. }
  189. public function getRequestCookies(bool $raw = false): ParameterBag
  190. {
  191. return new ParameterBag($this->data['request_cookies']->getValue($raw));
  192. }
  193. public function getRequestAttributes(): ParameterBag
  194. {
  195. return new ParameterBag($this->data['request_attributes']->getValue());
  196. }
  197. public function getResponseHeaders(): ParameterBag
  198. {
  199. return new ParameterBag($this->data['response_headers']->getValue());
  200. }
  201. public function getResponseCookies(): ParameterBag
  202. {
  203. return new ParameterBag($this->data['response_cookies']->getValue());
  204. }
  205. public function getSessionMetadata(): array
  206. {
  207. return $this->data['session_metadata']->getValue();
  208. }
  209. public function getSessionAttributes(): array
  210. {
  211. return $this->data['session_attributes']->getValue();
  212. }
  213. public function getStatelessCheck(): bool
  214. {
  215. return $this->data['stateless_check'];
  216. }
  217. public function getSessionUsages(): Data|array
  218. {
  219. return $this->data['session_usages'];
  220. }
  221. public function getFlashes(): array
  222. {
  223. return $this->data['flashes']->getValue();
  224. }
  225. /**
  226. * @return string|resource
  227. */
  228. public function getContent()
  229. {
  230. return $this->data['content'];
  231. }
  232. public function isJsonRequest(): bool
  233. {
  234. return 1 === preg_match('{^application/(?:\w+\++)*json$}i', $this->data['request_headers']['content-type']);
  235. }
  236. public function getPrettyJson(): ?string
  237. {
  238. $decoded = json_decode($this->getContent());
  239. return \JSON_ERROR_NONE === json_last_error() ? json_encode($decoded, \JSON_PRETTY_PRINT) : null;
  240. }
  241. public function getContentType(): string
  242. {
  243. return $this->data['content_type'];
  244. }
  245. public function getStatusText(): string
  246. {
  247. return $this->data['status_text'];
  248. }
  249. public function getStatusCode(): int
  250. {
  251. return $this->data['status_code'];
  252. }
  253. public function getFormat(): string
  254. {
  255. return $this->data['format'];
  256. }
  257. public function getLocale(): string
  258. {
  259. return $this->data['locale'];
  260. }
  261. public function getDotenvVars(): ParameterBag
  262. {
  263. return new ParameterBag($this->data['dotenv_vars']->getValue());
  264. }
  265. /**
  266. * Gets the route name.
  267. *
  268. * The _route request attributes is automatically set by the Router Matcher.
  269. */
  270. public function getRoute(): string
  271. {
  272. return $this->data['route'];
  273. }
  274. public function getIdentifier(): string
  275. {
  276. return $this->data['identifier'];
  277. }
  278. /**
  279. * Gets the route parameters.
  280. *
  281. * The _route_params request attributes is automatically set by the RouterListener.
  282. */
  283. public function getRouteParams(): array
  284. {
  285. return isset($this->data['request_attributes']['_route_params']) ? $this->data['request_attributes']['_route_params']->getValue() : [];
  286. }
  287. /**
  288. * Gets the parsed controller.
  289. *
  290. * @return array|string|Data The controller as a string or array of data
  291. * with keys 'class', 'method', 'file' and 'line'
  292. */
  293. public function getController(): array|string|Data
  294. {
  295. return $this->data['controller'];
  296. }
  297. /**
  298. * Gets the previous request attributes.
  299. *
  300. * @return array|Data|false A legacy array of data from the previous redirection response
  301. * or false otherwise
  302. */
  303. public function getRedirect(): array|Data|false
  304. {
  305. return $this->data['redirect'] ?? false;
  306. }
  307. public function getForwardToken(): ?string
  308. {
  309. return $this->data['forward_token'] ?? null;
  310. }
  311. public function onKernelController(ControllerEvent $event): void
  312. {
  313. $this->controllers[$event->getRequest()] = $event->getController();
  314. }
  315. public function onKernelResponse(ResponseEvent $event): void
  316. {
  317. if (!$event->isMainRequest()) {
  318. return;
  319. }
  320. if ($event->getRequest()->cookies->has('sf_redirect')) {
  321. $event->getRequest()->attributes->set('_redirected', true);
  322. }
  323. }
  324. public static function getSubscribedEvents(): array
  325. {
  326. return [
  327. KernelEvents::CONTROLLER => 'onKernelController',
  328. KernelEvents::RESPONSE => 'onKernelResponse',
  329. ];
  330. }
  331. public function getName(): string
  332. {
  333. return 'request';
  334. }
  335. public function collectSessionUsage(): void
  336. {
  337. $trace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS);
  338. $traceEndIndex = \count($trace) - 1;
  339. for ($i = $traceEndIndex; $i > 0; --$i) {
  340. if (null !== ($class = $trace[$i]['class'] ?? null) && (is_subclass_of($class, SessionInterface::class) || is_subclass_of($class, SessionBagInterface::class))) {
  341. $traceEndIndex = $i;
  342. break;
  343. }
  344. }
  345. if ((\count($trace) - 1) === $traceEndIndex) {
  346. return;
  347. }
  348. // Remove part of the backtrace that belongs to session only
  349. array_splice($trace, 0, $traceEndIndex);
  350. // Merge identical backtraces generated by internal call reports
  351. $name = \sprintf('%s:%s', $trace[1]['class'] ?? $trace[0]['file'], $trace[0]['line']);
  352. if (!\array_key_exists($name, $this->sessionUsages)) {
  353. $this->sessionUsages[$name] = [
  354. 'name' => $name,
  355. 'file' => $trace[0]['file'],
  356. 'line' => $trace[0]['line'],
  357. 'trace' => $trace,
  358. ];
  359. }
  360. }
  361. /**
  362. * @return array|string An array of controller data or a simple string
  363. */
  364. private function parseController(array|object|string|null $controller): array|string
  365. {
  366. if (\is_string($controller) && str_contains($controller, '::')) {
  367. $controller = explode('::', $controller);
  368. }
  369. if (\is_array($controller)) {
  370. try {
  371. $r = new \ReflectionMethod($controller[0], $controller[1]);
  372. return [
  373. 'class' => \is_object($controller[0]) ? get_debug_type($controller[0]) : $controller[0],
  374. 'method' => $controller[1],
  375. 'file' => $r->getFileName(),
  376. 'line' => $r->getStartLine(),
  377. ];
  378. } catch (\ReflectionException) {
  379. if (\is_callable($controller)) {
  380. // using __call or __callStatic
  381. return [
  382. 'class' => \is_object($controller[0]) ? get_debug_type($controller[0]) : $controller[0],
  383. 'method' => $controller[1],
  384. 'file' => 'n/a',
  385. 'line' => 'n/a',
  386. ];
  387. }
  388. }
  389. }
  390. if ($controller instanceof \Closure) {
  391. $r = new \ReflectionFunction($controller);
  392. $controller = [
  393. 'class' => $r->getName(),
  394. 'method' => null,
  395. 'file' => $r->getFileName(),
  396. 'line' => $r->getStartLine(),
  397. ];
  398. if ($r->isAnonymous()) {
  399. return $controller;
  400. }
  401. $controller['method'] = $r->name;
  402. if ($class = $r->getClosureCalledClass()) {
  403. $controller['class'] = $class->name;
  404. } else {
  405. return $r->name;
  406. }
  407. return $controller;
  408. }
  409. if (\is_object($controller)) {
  410. $r = new \ReflectionClass($controller);
  411. return [
  412. 'class' => $r->getName(),
  413. 'method' => null,
  414. 'file' => $r->getFileName(),
  415. 'line' => $r->getStartLine(),
  416. ];
  417. }
  418. return \is_string($controller) ? $controller : 'n/a';
  419. }
  420. }