HttpUtils.php 6.5 KB

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