HttpUtils.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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\Security\Http;
  11. use Symfony\Component\HttpFoundation\RedirectResponse;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\Routing\Exception\MethodNotAllowedException;
  14. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  15. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  16. use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
  17. use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
  18. use Symfony\Component\Security\Core\Security;
  19. /**
  20. * Encapsulates the logic needed to create sub-requests, redirect the user, and match URLs.
  21. *
  22. * @author Fabien Potencier <fabien@symfony.com>
  23. */
  24. class HttpUtils
  25. {
  26. private $urlGenerator;
  27. private $urlMatcher;
  28. private $domainRegexp;
  29. private $secureDomainRegexp;
  30. /**
  31. * @param UrlMatcherInterface|RequestMatcherInterface $urlMatcher The URL or Request matcher
  32. * @param string|null $domainRegexp A regexp the target of HTTP redirections must match, scheme included
  33. * @param string|null $secureDomainRegexp A regexp the target of HTTP redirections must match when the scheme is "https"
  34. *
  35. * @throws \InvalidArgumentException
  36. */
  37. public function __construct(UrlGeneratorInterface $urlGenerator = null, $urlMatcher = null, string $domainRegexp = null, string $secureDomainRegexp = null)
  38. {
  39. $this->urlGenerator = $urlGenerator;
  40. if (null !== $urlMatcher && !$urlMatcher instanceof UrlMatcherInterface && !$urlMatcher instanceof RequestMatcherInterface) {
  41. throw new \InvalidArgumentException('Matcher must either implement UrlMatcherInterface or RequestMatcherInterface.');
  42. }
  43. $this->urlMatcher = $urlMatcher;
  44. $this->domainRegexp = $domainRegexp;
  45. $this->secureDomainRegexp = $secureDomainRegexp;
  46. }
  47. /**
  48. * Creates a redirect Response.
  49. *
  50. * @param string $path A path (an absolute path (/foo), an absolute URL (http://...), or a route name (foo))
  51. * @param int $status The status code
  52. *
  53. * @return RedirectResponse A RedirectResponse instance
  54. */
  55. public function createRedirectResponse(Request $request, string $path, int $status = 302)
  56. {
  57. if (null !== $this->secureDomainRegexp && 'https' === $this->urlMatcher->getContext()->getScheme() && preg_match('#^https?:[/\\\\]{2,}+[^/]++#i', $path, $host) && !preg_match(sprintf($this->secureDomainRegexp, preg_quote($request->getHttpHost())), $host[0])) {
  58. $path = '/';
  59. }
  60. if (null !== $this->domainRegexp && preg_match('#^https?:[/\\\\]{2,}+[^/]++#i', $path, $host) && !preg_match(sprintf($this->domainRegexp, preg_quote($request->getHttpHost())), $host[0])) {
  61. $path = '/';
  62. }
  63. return new RedirectResponse($this->generateUri($request, $path), $status);
  64. }
  65. /**
  66. * Creates a Request.
  67. *
  68. * @param string $path A path (an absolute path (/foo), an absolute URL (http://...), or a route name (foo))
  69. *
  70. * @return Request A Request instance
  71. */
  72. public function createRequest(Request $request, string $path)
  73. {
  74. $newRequest = Request::create($this->generateUri($request, $path), 'get', [], $request->cookies->all(), [], $request->server->all());
  75. static $setSession;
  76. if (null === $setSession) {
  77. $setSession = \Closure::bind(static function ($newRequest, $request) { $newRequest->session = $request->session; }, null, Request::class);
  78. }
  79. $setSession($newRequest, $request);
  80. if ($request->attributes->has(Security::AUTHENTICATION_ERROR)) {
  81. $newRequest->attributes->set(Security::AUTHENTICATION_ERROR, $request->attributes->get(Security::AUTHENTICATION_ERROR));
  82. }
  83. if ($request->attributes->has(Security::ACCESS_DENIED_ERROR)) {
  84. $newRequest->attributes->set(Security::ACCESS_DENIED_ERROR, $request->attributes->get(Security::ACCESS_DENIED_ERROR));
  85. }
  86. if ($request->attributes->has(Security::LAST_USERNAME)) {
  87. $newRequest->attributes->set(Security::LAST_USERNAME, $request->attributes->get(Security::LAST_USERNAME));
  88. }
  89. if ($request->get('_format')) {
  90. $newRequest->attributes->set('_format', $request->get('_format'));
  91. }
  92. if ($request->getDefaultLocale() !== $request->getLocale()) {
  93. $newRequest->setLocale($request->getLocale());
  94. }
  95. return $newRequest;
  96. }
  97. /**
  98. * Checks that a given path matches the Request.
  99. *
  100. * @param string $path A path (an absolute path (/foo), an absolute URL (http://...), or a route name (foo))
  101. *
  102. * @return bool true if the path is the same as the one from the Request, false otherwise
  103. */
  104. public function checkRequestPath(Request $request, string $path)
  105. {
  106. if ('/' !== $path[0]) {
  107. try {
  108. // matching a request is more powerful than matching a URL path + context, so try that first
  109. if ($this->urlMatcher instanceof RequestMatcherInterface) {
  110. $parameters = $this->urlMatcher->matchRequest($request);
  111. } else {
  112. $parameters = $this->urlMatcher->match($request->getPathInfo());
  113. }
  114. return isset($parameters['_route']) && $path === $parameters['_route'];
  115. } catch (MethodNotAllowedException $e) {
  116. return false;
  117. } catch (ResourceNotFoundException $e) {
  118. return false;
  119. }
  120. }
  121. return $path === rawurldecode($request->getPathInfo());
  122. }
  123. /**
  124. * Generates a URI, based on the given path or absolute URL.
  125. *
  126. * @param string $path A path (an absolute path (/foo), an absolute URL (http://...), or a route name (foo))
  127. *
  128. * @return string An absolute URL
  129. *
  130. * @throws \LogicException
  131. */
  132. public function generateUri(Request $request, string $path)
  133. {
  134. if (0 === strpos($path, 'http') || !$path) {
  135. return $path;
  136. }
  137. if ('/' === $path[0]) {
  138. return $request->getUriForPath($path);
  139. }
  140. if (null === $this->urlGenerator) {
  141. throw new \LogicException('You must provide a UrlGeneratorInterface instance to be able to use routes.');
  142. }
  143. $url = $this->urlGenerator->generate($path, $request->attributes->all(), UrlGeneratorInterface::ABSOLUTE_URL);
  144. // unnecessary query string parameters must be removed from URL
  145. // (ie. query parameters that are presents in $attributes)
  146. // fortunately, they all are, so we have to remove entire query string
  147. $position = strpos($url, '?');
  148. if (false !== $position) {
  149. $fragment = parse_url($url, \PHP_URL_FRAGMENT);
  150. $url = substr($url, 0, $position);
  151. // fragment must be preserved
  152. if ($fragment) {
  153. $url .= "#$fragment";
  154. }
  155. }
  156. return $url;
  157. }
  158. }