vendor/symfony/http-kernel/EventListener/AbstractSessionListener.php line 215

  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\EventListener;
  11. use Psr\Container\ContainerInterface;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\HttpFoundation\Cookie;
  14. use Symfony\Component\HttpFoundation\Session\Session;
  15. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  16. use Symfony\Component\HttpFoundation\Session\SessionUtils;
  17. use Symfony\Component\HttpKernel\Event\RequestEvent;
  18. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  19. use Symfony\Component\HttpKernel\Exception\UnexpectedSessionUsageException;
  20. use Symfony\Component\HttpKernel\KernelEvents;
  21. use Symfony\Contracts\Service\ResetInterface;
  22. /**
  23.  * Sets the session onto the request on the "kernel.request" event and saves
  24.  * it on the "kernel.response" event.
  25.  *
  26.  * In addition, if the session has been started it overrides the Cache-Control
  27.  * header in such a way that all caching is disabled in that case.
  28.  * If you have a scenario where caching responses with session information in
  29.  * them makes sense, you can disable this behaviour by setting the header
  30.  * AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER on the response.
  31.  *
  32.  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  33.  * @author Tobias Schultze <http://tobion.de>
  34.  *
  35.  * @internal
  36.  */
  37. abstract class AbstractSessionListener implements EventSubscriberInterfaceResetInterface
  38. {
  39.     public const NO_AUTO_CACHE_CONTROL_HEADER 'Symfony-Session-NoAutoCacheControl';
  40.     protected $container;
  41.     private bool $debug;
  42.     /**
  43.      * @var array<string, mixed>
  44.      */
  45.     private $sessionOptions;
  46.     public function __construct(ContainerInterface $container nullbool $debug false, array $sessionOptions = [])
  47.     {
  48.         $this->container $container;
  49.         $this->debug $debug;
  50.         $this->sessionOptions $sessionOptions;
  51.     }
  52.     public function onKernelRequest(RequestEvent $event): void
  53.     {
  54.         if (!$event->isMainRequest()) {
  55.             return;
  56.         }
  57.         $request $event->getRequest();
  58.         if (!$request->hasSession()) {
  59.             $request->setSessionFactory(function () use ($request) {
  60.                 // Prevent calling `$this->getSession()` twice in case the Request (and the below factory) is cloned
  61.                 static $sess;
  62.                 if (!$sess) {
  63.                     $sess $this->getSession();
  64.                     $request->setSession($sess);
  65.                     /*
  66.                      * For supporting sessions in php runtime with runners like roadrunner or swoole, the session
  67.                      * cookie needs to be read from the cookie bag and set on the session storage.
  68.                      *
  69.                      * Do not set it when a native php session is active.
  70.                      */
  71.                     if ($sess && !$sess->isStarted() && \PHP_SESSION_ACTIVE !== session_status()) {
  72.                         $sessionId $sess->getId() ?: $request->cookies->get($sess->getName(), '');
  73.                         $sess->setId($sessionId);
  74.                     }
  75.                 }
  76.                 return $sess;
  77.             });
  78.         }
  79.     }
  80.     public function onKernelResponse(ResponseEvent $event): void
  81.     {
  82.         if (!$event->isMainRequest() || (!$this->container->has('initialized_session') && !$event->getRequest()->hasSession())) {
  83.             return;
  84.         }
  85.         $response $event->getResponse();
  86.         $autoCacheControl = !$response->headers->has(self::NO_AUTO_CACHE_CONTROL_HEADER);
  87.         // Always remove the internal header if present
  88.         $response->headers->remove(self::NO_AUTO_CACHE_CONTROL_HEADER);
  89.         if (!$event->getRequest()->hasSession(true)) {
  90.             return;
  91.         }
  92.         $session $event->getRequest()->getSession();
  93.         if ($session->isStarted()) {
  94.             /*
  95.              * Saves the session, in case it is still open, before sending the response/headers.
  96.              *
  97.              * This ensures several things in case the developer did not save the session explicitly:
  98.              *
  99.              *  * If a session save handler without locking is used, it ensures the data is available
  100.              *    on the next request, e.g. after a redirect. PHPs auto-save at script end via
  101.              *    session_register_shutdown is executed after fastcgi_finish_request. So in this case
  102.              *    the data could be missing the next request because it might not be saved the moment
  103.              *    the new request is processed.
  104.              *  * A locking save handler (e.g. the native 'files') circumvents concurrency problems like
  105.              *    the one above. But by saving the session before long-running things in the terminate event,
  106.              *    we ensure the session is not blocked longer than needed.
  107.              *  * When regenerating the session ID no locking is involved in PHPs session design. See
  108.              *    https://bugs.php.net/61470 for a discussion. So in this case, the session must
  109.              *    be saved anyway before sending the headers with the new session ID. Otherwise session
  110.              *    data could get lost again for concurrent requests with the new ID. One result could be
  111.              *    that you get logged out after just logging in.
  112.              *
  113.              * This listener should be executed as one of the last listeners, so that previous listeners
  114.              * can still operate on the open session. This prevents the overhead of restarting it.
  115.              * Listeners after closing the session can still work with the session as usual because
  116.              * Symfonys session implementation starts the session on demand. So writing to it after
  117.              * it is saved will just restart it.
  118.              */
  119.             $session->save();
  120.             /*
  121.              * For supporting sessions in php runtime with runners like roadrunner or swoole the session
  122.              * cookie need to be written on the response object and should not be written by PHP itself.
  123.              */
  124.             $sessionName $session->getName();
  125.             $sessionId $session->getId();
  126.             $sessionOptions $this->getSessionOptions($this->sessionOptions);
  127.             $sessionCookiePath $sessionOptions['cookie_path'] ?? '/';
  128.             $sessionCookieDomain $sessionOptions['cookie_domain'] ?? null;
  129.             $sessionCookieSecure $sessionOptions['cookie_secure'] ?? false;
  130.             $sessionCookieHttpOnly $sessionOptions['cookie_httponly'] ?? true;
  131.             $sessionCookieSameSite $sessionOptions['cookie_samesite'] ?? Cookie::SAMESITE_LAX;
  132.             $sessionUseCookies $sessionOptions['use_cookies'] ?? true;
  133.             SessionUtils::popSessionCookie($sessionName$sessionId);
  134.             if ($sessionUseCookies) {
  135.                 $request $event->getRequest();
  136.                 $requestSessionCookieId $request->cookies->get($sessionName);
  137.                 $isSessionEmpty = ($session instanceof Session $session->isEmpty() : !$session->all()) && empty($_SESSION); // checking $_SESSION to keep compatibility with native sessions
  138.                 if ($requestSessionCookieId && $isSessionEmpty) {
  139.                     // PHP internally sets the session cookie value to "deleted" when setcookie() is called with empty string $value argument
  140.                     // which happens in \Symfony\Component\HttpFoundation\Session\Storage\Handler\AbstractSessionHandler::destroy
  141.                     // when the session gets invalidated (for example on logout) so we must handle this case here too
  142.                     // otherwise we would send two Set-Cookie headers back with the response
  143.                     SessionUtils::popSessionCookie($sessionName'deleted');
  144.                     $response->headers->clearCookie(
  145.                         $sessionName,
  146.                         $sessionCookiePath,
  147.                         $sessionCookieDomain,
  148.                         $sessionCookieSecure,
  149.                         $sessionCookieHttpOnly,
  150.                         $sessionCookieSameSite
  151.                     );
  152.                 } elseif ($sessionId !== $requestSessionCookieId && !$isSessionEmpty) {
  153.                     $expire 0;
  154.                     $lifetime $sessionOptions['cookie_lifetime'] ?? null;
  155.                     if ($lifetime) {
  156.                         $expire time() + $lifetime;
  157.                     }
  158.                     $response->headers->setCookie(
  159.                         Cookie::create(
  160.                             $sessionName,
  161.                             $sessionId,
  162.                             $expire,
  163.                             $sessionCookiePath,
  164.                             $sessionCookieDomain,
  165.                             $sessionCookieSecure,
  166.                             $sessionCookieHttpOnly,
  167.                             false,
  168.                             $sessionCookieSameSite
  169.                         )
  170.                     );
  171.                 }
  172.             }
  173.         }
  174.         if ($session instanceof Session === $session->getUsageIndex() : !$session->isStarted()) {
  175.             return;
  176.         }
  177.         if ($autoCacheControl) {
  178.             $maxAge $response->headers->hasCacheControlDirective('public') ? : (int) $response->getMaxAge();
  179.             $response
  180.                 ->setExpires(new \DateTimeImmutable('+'.$maxAge.' seconds'))
  181.                 ->setPrivate()
  182.                 ->setMaxAge($maxAge)
  183.                 ->headers->addCacheControlDirective('must-revalidate');
  184.         }
  185.         if (!$event->getRequest()->attributes->get('_stateless'false)) {
  186.             return;
  187.         }
  188.         if ($this->debug) {
  189.             throw new UnexpectedSessionUsageException('Session was used while the request was declared stateless.');
  190.         }
  191.         if ($this->container->has('logger')) {
  192.             $this->container->get('logger')->warning('Session was used while the request was declared stateless.');
  193.         }
  194.     }
  195.     public function onSessionUsage(): void
  196.     {
  197.         if (!$this->debug) {
  198.             return;
  199.         }
  200.         if ($this->container?->has('session_collector')) {
  201.             $this->container->get('session_collector')();
  202.         }
  203.         if (!$requestStack $this->container?->has('request_stack') ? $this->container->get('request_stack') : null) {
  204.             return;
  205.         }
  206.         $stateless false;
  207.         $clonedRequestStack = clone $requestStack;
  208.         while (null !== ($request $clonedRequestStack->pop()) && !$stateless) {
  209.             $stateless $request->attributes->get('_stateless');
  210.         }
  211.         if (!$stateless) {
  212.             return;
  213.         }
  214.         if (!$session $requestStack->getCurrentRequest()->getSession()) {
  215.             return;
  216.         }
  217.         if ($session->isStarted()) {
  218.             $session->save();
  219.         }
  220.         throw new UnexpectedSessionUsageException('Session was used while the request was declared stateless.');
  221.     }
  222.     public static function getSubscribedEvents(): array
  223.     {
  224.         return [
  225.             KernelEvents::REQUEST => ['onKernelRequest'128],
  226.             // low priority to come after regular response listeners
  227.             KernelEvents::RESPONSE => ['onKernelResponse', -1000],
  228.         ];
  229.     }
  230.     public function reset(): void
  231.     {
  232.         if (\PHP_SESSION_ACTIVE === session_status()) {
  233.             session_abort();
  234.         }
  235.         session_unset();
  236.         $_SESSION = [];
  237.         if (!headers_sent()) { // session id can only be reset when no headers were so we check for headers_sent first
  238.             session_id('');
  239.         }
  240.     }
  241.     /**
  242.      * Gets the session object.
  243.      */
  244.     abstract protected function getSession(): ?SessionInterface;
  245.     private function getSessionOptions(array $sessionOptions): array
  246.     {
  247.         $mergedSessionOptions = [];
  248.         foreach (session_get_cookie_params() as $key => $value) {
  249.             $mergedSessionOptions['cookie_'.$key] = $value;
  250.         }
  251.         foreach ($sessionOptions as $key => $value) {
  252.             // do the same logic as in the NativeSessionStorage
  253.             if ('cookie_secure' === $key && 'auto' === $value) {
  254.                 continue;
  255.             }
  256.             $mergedSessionOptions[$key] = $value;
  257.         }
  258.         return $mergedSessionOptions;
  259.     }
  260. }