Security update for Core, with self-updated composer
[yaffs-website] / web / core / lib / Drupal / Component / HttpFoundation / SecuredRedirectResponse.php
1 <?php
2
3 namespace Drupal\Component\HttpFoundation;
4
5 use Symfony\Component\HttpFoundation\RedirectResponse;
6
7 /**
8  * Provides a common base class for safe redirects.
9  *
10  * In case you want to redirect to external URLs use
11  * TrustedRedirectResponse.
12  *
13  * For local URLs we use LocalRedirectResponse which opts
14  * out of external redirects.
15  */
16 abstract class SecuredRedirectResponse extends RedirectResponse {
17
18   /**
19    * Copies an existing redirect response into a safe one.
20    *
21    * The safe one cannot accidentally redirect to an external URL, unless
22    * actively wanted (see TrustedRedirectResponse).
23    *
24    * @param \Symfony\Component\HttpFoundation\RedirectResponse $response
25    *   The original redirect.
26    *
27    * @return static
28    */
29   public static function createFromRedirectResponse(RedirectResponse $response) {
30     $safe_response = new static($response->getTargetUrl(), $response->getStatusCode(), $response->headers->allPreserveCase());
31     $safe_response->fromResponse($response);
32     return $safe_response;
33   }
34
35   /**
36    * Copies over the values from the given response.
37    *
38    * @param \Symfony\Component\HttpFoundation\RedirectResponse $response
39    *   The redirect reponse object.
40    */
41   protected function fromResponse(RedirectResponse $response) {
42     $this->setProtocolVersion($response->getProtocolVersion());
43     $this->setCharset($response->getCharset());
44     // Cookies are separate from other headers and have to be copied over
45     // directly.
46     foreach ($response->headers->getCookies() as $cookie) {
47       $this->headers->setCookie($cookie);
48     }
49   }
50
51   /**
52    * {@inheritdoc}
53    */
54   public function setTargetUrl($url) {
55     if (!$this->isSafe($url)) {
56       throw new \InvalidArgumentException(sprintf('It is not safe to redirect to %s', $url));
57     }
58     return parent::setTargetUrl($url);
59   }
60
61   /**
62    * Returns whether the URL is considered as safe to redirect to.
63    *
64    * @param string $url
65    *   The URL checked for safety.
66    *
67    * @return bool
68    */
69   abstract protected function isSafe($url);
70
71 }