vendor/symfony/http-foundation/Session/Storage/NativeSessionStorage.php line 287

Open in your IDE?
  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\HttpFoundation\Session\Storage;
  11. use Symfony\Component\HttpFoundation\Session\SessionBagInterface;
  12. use Symfony\Component\HttpFoundation\Session\Storage\Handler\StrictSessionHandler;
  13. use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy;
  14. use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;
  15. // Help opcache.preload discover always-needed symbols
  16. class_exists(MetadataBag::class);
  17. class_exists(StrictSessionHandler::class);
  18. class_exists(SessionHandlerProxy::class);
  19. /**
  20.  * This provides a base class for session attribute storage.
  21.  *
  22.  * @author Drak <drak@zikula.org>
  23.  */
  24. class NativeSessionStorage implements SessionStorageInterface
  25. {
  26.     /**
  27.      * @var SessionBagInterface[]
  28.      */
  29.     protected $bags = [];
  30.     /**
  31.      * @var bool
  32.      */
  33.     protected $started false;
  34.     /**
  35.      * @var bool
  36.      */
  37.     protected $closed false;
  38.     /**
  39.      * @var AbstractProxy|\SessionHandlerInterface
  40.      */
  41.     protected $saveHandler;
  42.     /**
  43.      * @var MetadataBag
  44.      */
  45.     protected $metadataBag;
  46.     /**
  47.      * Depending on how you want the storage driver to behave you probably
  48.      * want to override this constructor entirely.
  49.      *
  50.      * List of options for $options array with their defaults.
  51.      *
  52.      * @see https://php.net/session.configuration for options
  53.      * but we omit 'session.' from the beginning of the keys for convenience.
  54.      *
  55.      * ("auto_start", is not supported as it tells PHP to start a session before
  56.      * PHP starts to execute user-land code. Setting during runtime has no effect).
  57.      *
  58.      * cache_limiter, "" (use "0" to prevent headers from being sent entirely).
  59.      * cache_expire, "0"
  60.      * cookie_domain, ""
  61.      * cookie_httponly, ""
  62.      * cookie_lifetime, "0"
  63.      * cookie_path, "/"
  64.      * cookie_secure, ""
  65.      * cookie_samesite, null
  66.      * gc_divisor, "100"
  67.      * gc_maxlifetime, "1440"
  68.      * gc_probability, "1"
  69.      * lazy_write, "1"
  70.      * name, "PHPSESSID"
  71.      * referer_check, ""
  72.      * serialize_handler, "php"
  73.      * use_strict_mode, "1"
  74.      * use_cookies, "1"
  75.      * use_only_cookies, "1"
  76.      * use_trans_sid, "0"
  77.      * sid_length, "32"
  78.      * sid_bits_per_character, "5"
  79.      * trans_sid_hosts, $_SERVER['HTTP_HOST']
  80.      * trans_sid_tags, "a=href,area=href,frame=src,form="
  81.      */
  82.     public function __construct(array $options = [], AbstractProxy|\SessionHandlerInterface $handler nullMetadataBag $metaBag null)
  83.     {
  84.         if (!\extension_loaded('session')) {
  85.             throw new \LogicException('PHP extension "session" is required.');
  86.         }
  87.         $options += [
  88.             'cache_limiter' => '',
  89.             'cache_expire' => 0,
  90.             'use_cookies' => 1,
  91.             'lazy_write' => 1,
  92.             'use_strict_mode' => 1,
  93.         ];
  94.         session_register_shutdown();
  95.         $this->setMetadataBag($metaBag);
  96.         $this->setOptions($options);
  97.         $this->setSaveHandler($handler);
  98.     }
  99.     /**
  100.      * Gets the save handler instance.
  101.      */
  102.     public function getSaveHandler(): AbstractProxy|\SessionHandlerInterface
  103.     {
  104.         return $this->saveHandler;
  105.     }
  106.     /**
  107.      * {@inheritdoc}
  108.      */
  109.     public function start(): bool
  110.     {
  111.         if ($this->started) {
  112.             return true;
  113.         }
  114.         if (\PHP_SESSION_ACTIVE === session_status()) {
  115.             throw new \RuntimeException('Failed to start the session: already started by PHP.');
  116.         }
  117.         if (filter_var(ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOLEAN) && headers_sent($file$line)) {
  118.             throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.'$file$line));
  119.         }
  120.         $sessionId $_COOKIE[session_name()] ?? null;
  121.         if ($sessionId && !preg_match('/^[a-zA-Z0-9,-]{22,}$/'$sessionId)) {
  122.             // the session ID in the header is invalid, create a new one
  123.             session_id(session_create_id());
  124.         }
  125.         // ok to try and start the session
  126.         if (!session_start()) {
  127.             throw new \RuntimeException('Failed to start the session.');
  128.         }
  129.         $this->loadSession();
  130.         return true;
  131.     }
  132.     /**
  133.      * {@inheritdoc}
  134.      */
  135.     public function getId(): string
  136.     {
  137.         return $this->saveHandler->getId();
  138.     }
  139.     /**
  140.      * {@inheritdoc}
  141.      */
  142.     public function setId(string $id)
  143.     {
  144.         $this->saveHandler->setId($id);
  145.     }
  146.     /**
  147.      * {@inheritdoc}
  148.      */
  149.     public function getName(): string
  150.     {
  151.         return $this->saveHandler->getName();
  152.     }
  153.     /**
  154.      * {@inheritdoc}
  155.      */
  156.     public function setName(string $name)
  157.     {
  158.         $this->saveHandler->setName($name);
  159.     }
  160.     /**
  161.      * {@inheritdoc}
  162.      */
  163.     public function regenerate(bool $destroy falseint $lifetime null): bool
  164.     {
  165.         // Cannot regenerate the session ID for non-active sessions.
  166.         if (\PHP_SESSION_ACTIVE !== session_status()) {
  167.             return false;
  168.         }
  169.         if (headers_sent()) {
  170.             return false;
  171.         }
  172.         if (null !== $lifetime && $lifetime != ini_get('session.cookie_lifetime')) {
  173.             $this->save();
  174.             ini_set('session.cookie_lifetime'$lifetime);
  175.             $this->start();
  176.         }
  177.         if ($destroy) {
  178.             $this->metadataBag->stampNew();
  179.         }
  180.         return session_regenerate_id($destroy);
  181.     }
  182.     /**
  183.      * {@inheritdoc}
  184.      */
  185.     public function save()
  186.     {
  187.         // Store a copy so we can restore the bags in case the session was not left empty
  188.         $session $_SESSION;
  189.         foreach ($this->bags as $bag) {
  190.             if (empty($_SESSION[$key $bag->getStorageKey()])) {
  191.                 unset($_SESSION[$key]);
  192.             }
  193.         }
  194.         if ([$key $this->metadataBag->getStorageKey()] === array_keys($_SESSION)) {
  195.             unset($_SESSION[$key]);
  196.         }
  197.         // Register error handler to add information about the current save handler
  198.         $previousHandler set_error_handler(function ($type$msg$file$line) use (&$previousHandler) {
  199.             if (\E_WARNING === $type && str_starts_with($msg'session_write_close():')) {
  200.                 $handler $this->saveHandler instanceof SessionHandlerProxy $this->saveHandler->getHandler() : $this->saveHandler;
  201.                 $msg sprintf('session_write_close(): Failed to write session data with "%s" handler'\get_class($handler));
  202.             }
  203.             return $previousHandler $previousHandler($type$msg$file$line) : false;
  204.         });
  205.         try {
  206.             session_write_close();
  207.         } finally {
  208.             restore_error_handler();
  209.             // Restore only if not empty
  210.             if ($_SESSION) {
  211.                 $_SESSION $session;
  212.             }
  213.         }
  214.         $this->closed true;
  215.         $this->started false;
  216.     }
  217.     /**
  218.      * {@inheritdoc}
  219.      */
  220.     public function clear()
  221.     {
  222.         // clear out the bags
  223.         foreach ($this->bags as $bag) {
  224.             $bag->clear();
  225.         }
  226.         // clear out the session
  227.         $_SESSION = [];
  228.         // reconnect the bags to the session
  229.         $this->loadSession();
  230.     }
  231.     /**
  232.      * {@inheritdoc}
  233.      */
  234.     public function registerBag(SessionBagInterface $bag)
  235.     {
  236.         if ($this->started) {
  237.             throw new \LogicException('Cannot register a bag when the session is already started.');
  238.         }
  239.         $this->bags[$bag->getName()] = $bag;
  240.     }
  241.     /**
  242.      * {@inheritdoc}
  243.      */
  244.     public function getBag(string $name): SessionBagInterface
  245.     {
  246.         if (!isset($this->bags[$name])) {
  247.             throw new \InvalidArgumentException(sprintf('The SessionBagInterface "%s" is not registered.'$name));
  248.         }
  249.         if (!$this->started && $this->saveHandler->isActive()) {
  250.             $this->loadSession();
  251.         } elseif (!$this->started) {
  252.             $this->start();
  253.         }
  254.         return $this->bags[$name];
  255.     }
  256.     public function setMetadataBag(MetadataBag $metaBag null)
  257.     {
  258.         if (null === $metaBag) {
  259.             $metaBag = new MetadataBag();
  260.         }
  261.         $this->metadataBag $metaBag;
  262.     }
  263.     /**
  264.      * Gets the MetadataBag.
  265.      */
  266.     public function getMetadataBag(): MetadataBag
  267.     {
  268.         return $this->metadataBag;
  269.     }
  270.     /**
  271.      * {@inheritdoc}
  272.      */
  273.     public function isStarted(): bool
  274.     {
  275.         return $this->started;
  276.     }
  277.     /**
  278.      * Sets session.* ini variables.
  279.      *
  280.      * For convenience we omit 'session.' from the beginning of the keys.
  281.      * Explicitly ignores other ini keys.
  282.      *
  283.      * @param array $options Session ini directives [key => value]
  284.      *
  285.      * @see https://php.net/session.configuration
  286.      */
  287.     public function setOptions(array $options)
  288.     {
  289.         if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
  290.             return;
  291.         }
  292.         $validOptions array_flip([
  293.             'cache_expire''cache_limiter''cookie_domain''cookie_httponly',
  294.             'cookie_lifetime''cookie_path''cookie_secure''cookie_samesite',
  295.             'gc_divisor''gc_maxlifetime''gc_probability',
  296.             'lazy_write''name''referer_check',
  297.             'serialize_handler''use_strict_mode''use_cookies',
  298.             'use_only_cookies''use_trans_sid',
  299.             'sid_length''sid_bits_per_character''trans_sid_hosts''trans_sid_tags',
  300.         ]);
  301.         foreach ($options as $key => $value) {
  302.             if (isset($validOptions[$key])) {
  303.                 if ('cookie_secure' === $key && 'auto' === $value) {
  304.                     continue;
  305.                 }
  306.                 ini_set('session.'.$key$value);
  307.             }
  308.         }
  309.     }
  310.     /**
  311.      * Registers session save handler as a PHP session handler.
  312.      *
  313.      * To use internal PHP session save handlers, override this method using ini_set with
  314.      * session.save_handler and session.save_path e.g.
  315.      *
  316.      *     ini_set('session.save_handler', 'files');
  317.      *     ini_set('session.save_path', '/tmp');
  318.      *
  319.      * or pass in a \SessionHandler instance which configures session.save_handler in the
  320.      * constructor, for a template see NativeFileSessionHandler.
  321.      *
  322.      * @see https://php.net/session-set-save-handler
  323.      * @see https://php.net/sessionhandlerinterface
  324.      * @see https://php.net/sessionhandler
  325.      *
  326.      * @throws \InvalidArgumentException
  327.      */
  328.     public function setSaveHandler(AbstractProxy|\SessionHandlerInterface $saveHandler null)
  329.     {
  330.         if (!$saveHandler instanceof AbstractProxy &&
  331.             !$saveHandler instanceof \SessionHandlerInterface &&
  332.             null !== $saveHandler) {
  333.             throw new \InvalidArgumentException('Must be instance of AbstractProxy; implement \SessionHandlerInterface; or be null.');
  334.         }
  335.         // Wrap $saveHandler in proxy and prevent double wrapping of proxy
  336.         if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) {
  337.             $saveHandler = new SessionHandlerProxy($saveHandler);
  338.         } elseif (!$saveHandler instanceof AbstractProxy) {
  339.             $saveHandler = new SessionHandlerProxy(new StrictSessionHandler(new \SessionHandler()));
  340.         }
  341.         $this->saveHandler $saveHandler;
  342.         if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
  343.             return;
  344.         }
  345.         if ($this->saveHandler instanceof SessionHandlerProxy) {
  346.             session_set_save_handler($this->saveHandlerfalse);
  347.         }
  348.     }
  349.     /**
  350.      * Load the session with attributes.
  351.      *
  352.      * After starting the session, PHP retrieves the session from whatever handlers
  353.      * are set to (either PHP's internal, or a custom save handler set with session_set_save_handler()).
  354.      * PHP takes the return value from the read() handler, unserializes it
  355.      * and populates $_SESSION with the result automatically.
  356.      */
  357.     protected function loadSession(array &$session null)
  358.     {
  359.         if (null === $session) {
  360.             $session = &$_SESSION;
  361.         }
  362.         $bags array_merge($this->bags, [$this->metadataBag]);
  363.         foreach ($bags as $bag) {
  364.             $key $bag->getStorageKey();
  365.             $session[$key] = isset($session[$key]) && \is_array($session[$key]) ? $session[$key] : [];
  366.             $bag->initialize($session[$key]);
  367.         }
  368.         $this->started true;
  369.         $this->closed false;
  370.     }
  371. }