RequestDataCollector.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. /**
  23. * @author Fabien Potencier <fabien@symfony.com>
  24. *
  25. * @final
  26. */
  27. class RequestDataCollector extends DataCollector implements EventSubscriberInterface, LateDataCollectorInterface
  28. {
  29. protected $controllers;
  30. private $sessionUsages = [];
  31. private $requestStack;
  32. public function __construct(?RequestStack $requestStack = null)
  33. {
  34. $this->controllers = new \SplObjectStorage();
  35. $this->requestStack = $requestStack;
  36. }
  37. /**
  38. * {@inheritdoc}
  39. */
  40. public function collect(Request $request, Response $response, \Throwable $exception = null)
  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->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 && $this->requestStack->getMasterRequest()->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(function ($v) { return 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[(int) $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()
  152. {
  153. $this->data = $this->cloneVar($this->data);
  154. }
  155. public function reset()
  156. {
  157. $this->data = [];
  158. $this->controllers = new \SplObjectStorage();
  159. $this->sessionUsages = [];
  160. }
  161. public function getMethod()
  162. {
  163. return $this->data['method'];
  164. }
  165. public function getPathInfo()
  166. {
  167. return $this->data['path_info'];
  168. }
  169. public function getRequestRequest()
  170. {
  171. return new ParameterBag($this->data['request_request']->getValue());
  172. }
  173. public function getRequestQuery()
  174. {
  175. return new ParameterBag($this->data['request_query']->getValue());
  176. }
  177. public function getRequestFiles()
  178. {
  179. return new ParameterBag($this->data['request_files']->getValue());
  180. }
  181. public function getRequestHeaders()
  182. {
  183. return new ParameterBag($this->data['request_headers']->getValue());
  184. }
  185. public function getRequestServer($raw = false)
  186. {
  187. return new ParameterBag($this->data['request_server']->getValue($raw));
  188. }
  189. public function getRequestCookies($raw = false)
  190. {
  191. return new ParameterBag($this->data['request_cookies']->getValue($raw));
  192. }
  193. public function getRequestAttributes()
  194. {
  195. return new ParameterBag($this->data['request_attributes']->getValue());
  196. }
  197. public function getResponseHeaders()
  198. {
  199. return new ParameterBag($this->data['response_headers']->getValue());
  200. }
  201. public function getResponseCookies()
  202. {
  203. return new ParameterBag($this->data['response_cookies']->getValue());
  204. }
  205. public function getSessionMetadata()
  206. {
  207. return $this->data['session_metadata']->getValue();
  208. }
  209. public function getSessionAttributes()
  210. {
  211. return $this->data['session_attributes']->getValue();
  212. }
  213. public function getStatelessCheck()
  214. {
  215. return $this->data['stateless_check'];
  216. }
  217. public function getSessionUsages()
  218. {
  219. return $this->data['session_usages'];
  220. }
  221. public function getFlashes()
  222. {
  223. return $this->data['flashes']->getValue();
  224. }
  225. public function getContent()
  226. {
  227. return $this->data['content'];
  228. }
  229. public function isJsonRequest()
  230. {
  231. return 1 === preg_match('{^application/(?:\w+\++)*json$}i', $this->data['request_headers']['content-type']);
  232. }
  233. public function getPrettyJson()
  234. {
  235. $decoded = json_decode($this->getContent());
  236. return \JSON_ERROR_NONE === json_last_error() ? json_encode($decoded, \JSON_PRETTY_PRINT) : null;
  237. }
  238. public function getContentType()
  239. {
  240. return $this->data['content_type'];
  241. }
  242. public function getStatusText()
  243. {
  244. return $this->data['status_text'];
  245. }
  246. public function getStatusCode()
  247. {
  248. return $this->data['status_code'];
  249. }
  250. public function getFormat()
  251. {
  252. return $this->data['format'];
  253. }
  254. public function getLocale()
  255. {
  256. return $this->data['locale'];
  257. }
  258. public function getDotenvVars()
  259. {
  260. return new ParameterBag($this->data['dotenv_vars']->getValue());
  261. }
  262. /**
  263. * Gets the route name.
  264. *
  265. * The _route request attributes is automatically set by the Router Matcher.
  266. *
  267. * @return string The route
  268. */
  269. public function getRoute()
  270. {
  271. return $this->data['route'];
  272. }
  273. public function getIdentifier()
  274. {
  275. return $this->data['identifier'];
  276. }
  277. /**
  278. * Gets the route parameters.
  279. *
  280. * The _route_params request attributes is automatically set by the RouterListener.
  281. *
  282. * @return array The parameters
  283. */
  284. public function getRouteParams()
  285. {
  286. return isset($this->data['request_attributes']['_route_params']) ? $this->data['request_attributes']['_route_params']->getValue() : [];
  287. }
  288. /**
  289. * Gets the parsed controller.
  290. *
  291. * @return array|string The controller as a string or array of data
  292. * with keys 'class', 'method', 'file' and 'line'
  293. */
  294. public function getController()
  295. {
  296. return $this->data['controller'];
  297. }
  298. /**
  299. * Gets the previous request attributes.
  300. *
  301. * @return array|bool A legacy array of data from the previous redirection response
  302. * or false otherwise
  303. */
  304. public function getRedirect()
  305. {
  306. return $this->data['redirect'] ?? false;
  307. }
  308. public function getForwardToken()
  309. {
  310. return $this->data['forward_token'] ?? null;
  311. }
  312. public function onKernelController(ControllerEvent $event)
  313. {
  314. $this->controllers[$event->getRequest()] = $event->getController();
  315. }
  316. public function onKernelResponse(ResponseEvent $event)
  317. {
  318. if (!$event->isMasterRequest()) {
  319. return;
  320. }
  321. if ($event->getRequest()->cookies->has('sf_redirect')) {
  322. $event->getRequest()->attributes->set('_redirected', true);
  323. }
  324. }
  325. public static function getSubscribedEvents()
  326. {
  327. return [
  328. KernelEvents::CONTROLLER => 'onKernelController',
  329. KernelEvents::RESPONSE => 'onKernelResponse',
  330. ];
  331. }
  332. /**
  333. * {@inheritdoc}
  334. */
  335. public function getName()
  336. {
  337. return 'request';
  338. }
  339. public function collectSessionUsage(): void
  340. {
  341. $trace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS);
  342. $traceEndIndex = \count($trace) - 1;
  343. for ($i = $traceEndIndex; $i > 0; --$i) {
  344. if (null !== ($class = $trace[$i]['class'] ?? null) && (is_subclass_of($class, SessionInterface::class) || is_subclass_of($class, SessionBagInterface::class))) {
  345. $traceEndIndex = $i;
  346. break;
  347. }
  348. }
  349. if ((\count($trace) - 1) === $traceEndIndex) {
  350. return;
  351. }
  352. // Remove part of the backtrace that belongs to session only
  353. array_splice($trace, 0, $traceEndIndex);
  354. // Merge identical backtraces generated by internal call reports
  355. $name = sprintf('%s:%s', $trace[1]['class'] ?? $trace[0]['file'], $trace[0]['line']);
  356. if (!\array_key_exists($name, $this->sessionUsages)) {
  357. $this->sessionUsages[$name] = [
  358. 'name' => $name,
  359. 'file' => $trace[0]['file'],
  360. 'line' => $trace[0]['line'],
  361. 'trace' => $trace,
  362. ];
  363. }
  364. }
  365. /**
  366. * Parse a controller.
  367. *
  368. * @param mixed $controller The controller to parse
  369. *
  370. * @return array|string An array of controller data or a simple string
  371. */
  372. protected function parseController($controller)
  373. {
  374. if (\is_string($controller) && false !== strpos($controller, '::')) {
  375. $controller = explode('::', $controller);
  376. }
  377. if (\is_array($controller)) {
  378. try {
  379. $r = new \ReflectionMethod($controller[0], $controller[1]);
  380. return [
  381. 'class' => \is_object($controller[0]) ? get_debug_type($controller[0]) : $controller[0],
  382. 'method' => $controller[1],
  383. 'file' => $r->getFileName(),
  384. 'line' => $r->getStartLine(),
  385. ];
  386. } catch (\ReflectionException $e) {
  387. if (\is_callable($controller)) {
  388. // using __call or __callStatic
  389. return [
  390. 'class' => \is_object($controller[0]) ? get_debug_type($controller[0]) : $controller[0],
  391. 'method' => $controller[1],
  392. 'file' => 'n/a',
  393. 'line' => 'n/a',
  394. ];
  395. }
  396. }
  397. }
  398. if ($controller instanceof \Closure) {
  399. $r = new \ReflectionFunction($controller);
  400. $controller = [
  401. 'class' => $r->getName(),
  402. 'method' => null,
  403. 'file' => $r->getFileName(),
  404. 'line' => $r->getStartLine(),
  405. ];
  406. if (false !== strpos($r->name, '{closure}')) {
  407. return $controller;
  408. }
  409. $controller['method'] = $r->name;
  410. if ($class = $r->getClosureScopeClass()) {
  411. $controller['class'] = $class->name;
  412. } else {
  413. return $r->name;
  414. }
  415. return $controller;
  416. }
  417. if (\is_object($controller)) {
  418. $r = new \ReflectionClass($controller);
  419. return [
  420. 'class' => $r->getName(),
  421. 'method' => null,
  422. 'file' => $r->getFileName(),
  423. 'line' => $r->getStartLine(),
  424. ];
  425. }
  426. return \is_string($controller) ? $controller : 'n/a';
  427. }
  428. }