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

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.         // ok to try and start the session
  121.         if (!session_start()) {
  122.             throw new \RuntimeException('Failed to start the session.');
  123.         }
  124.         $this->loadSession();
  125.         return true;
  126.     }
  127.     /**
  128.      * {@inheritdoc}
  129.      */
  130.     public function getId(): string
  131.     {
  132.         return $this->saveHandler->getId();
  133.     }
  134.     /**
  135.      * {@inheritdoc}
  136.      */
  137.     public function setId(string $id)
  138.     {
  139.         $this->saveHandler->setId($id);
  140.     }
  141.     /**
  142.      * {@inheritdoc}
  143.      */
  144.     public function getName(): string
  145.     {
  146.         return $this->saveHandler->getName();
  147.     }
  148.     /**
  149.      * {@inheritdoc}
  150.      */
  151.     public function setName(string $name)
  152.     {
  153.         $this->saveHandler->setName($name);
  154.     }
  155.     /**
  156.      * {@inheritdoc}
  157.      */
  158.     public function regenerate(bool $destroy falseint $lifetime null): bool
  159.     {
  160.         // Cannot regenerate the session ID for non-active sessions.
  161.         if (\PHP_SESSION_ACTIVE !== session_status()) {
  162.             return false;
  163.         }
  164.         if (headers_sent()) {
  165.             return false;
  166.         }
  167.         if (null !== $lifetime && $lifetime != ini_get('session.cookie_lifetime')) {
  168.             $this->save();
  169.             ini_set('session.cookie_lifetime'$lifetime);
  170.             $this->start();
  171.         }
  172.         if ($destroy) {
  173.             $this->metadataBag->stampNew();
  174.         }
  175.         return session_regenerate_id($destroy);
  176.     }
  177.     /**
  178.      * {@inheritdoc}
  179.      */
  180.     public function save()
  181.     {
  182.         // Store a copy so we can restore the bags in case the session was not left empty
  183.         $session $_SESSION;
  184.         foreach ($this->bags as $bag) {
  185.             if (empty($_SESSION[$key $bag->getStorageKey()])) {
  186.                 unset($_SESSION[$key]);
  187.             }
  188.         }
  189.         if ([$key $this->metadataBag->getStorageKey()] === array_keys($_SESSION)) {
  190.             unset($_SESSION[$key]);
  191.         }
  192.         // Register error handler to add information about the current save handler
  193.         $previousHandler set_error_handler(function ($type$msg$file$line) use (&$previousHandler) {
  194.             if (\E_WARNING === $type && str_starts_with($msg'session_write_close():')) {
  195.                 $handler $this->saveHandler instanceof SessionHandlerProxy $this->saveHandler->getHandler() : $this->saveHandler;
  196.                 $msg sprintf('session_write_close(): Failed to write session data with "%s" handler'\get_class($handler));
  197.             }
  198.             return $previousHandler $previousHandler($type$msg$file$line) : false;
  199.         });
  200.         try {
  201.             session_write_close();
  202.         } finally {
  203.             restore_error_handler();
  204.             // Restore only if not empty
  205.             if ($_SESSION) {
  206.                 $_SESSION $session;
  207.             }
  208.         }
  209.         $this->closed true;
  210.         $this->started false;
  211.     }
  212.     /**
  213.      * {@inheritdoc}
  214.      */
  215.     public function clear()
  216.     {
  217.         // clear out the bags
  218.         foreach ($this->bags as $bag) {
  219.             $bag->clear();
  220.         }
  221.         // clear out the session
  222.         $_SESSION = [];
  223.         // reconnect the bags to the session
  224.         $this->loadSession();
  225.     }
  226.     /**
  227.      * {@inheritdoc}
  228.      */
  229.     public function registerBag(SessionBagInterface $bag)
  230.     {
  231.         if ($this->started) {
  232.             throw new \LogicException('Cannot register a bag when the session is already started.');
  233.         }
  234.         $this->bags[$bag->getName()] = $bag;
  235.     }
  236.     /**
  237.      * {@inheritdoc}
  238.      */
  239.     public function getBag(string $name): SessionBagInterface
  240.     {
  241.         if (!isset($this->bags[$name])) {
  242.             throw new \InvalidArgumentException(sprintf('The SessionBagInterface "%s" is not registered.'$name));
  243.         }
  244.         if (!$this->started && $this->saveHandler->isActive()) {
  245.             $this->loadSession();
  246.         } elseif (!$this->started) {
  247.             $this->start();
  248.         }
  249.         return $this->bags[$name];
  250.     }
  251.     public function setMetadataBag(MetadataBag $metaBag null)
  252.     {
  253.         if (null === $metaBag) {
  254.             $metaBag = new MetadataBag();
  255.         }
  256.         $this->metadataBag $metaBag;
  257.     }
  258.     /**
  259.      * Gets the MetadataBag.
  260.      */
  261.     public function getMetadataBag(): MetadataBag
  262.     {
  263.         return $this->metadataBag;
  264.     }
  265.     /**
  266.      * {@inheritdoc}
  267.      */
  268.     public function isStarted(): bool
  269.     {
  270.         return $this->started;
  271.     }
  272.     /**
  273.      * Sets session.* ini variables.
  274.      *
  275.      * For convenience we omit 'session.' from the beginning of the keys.
  276.      * Explicitly ignores other ini keys.
  277.      *
  278.      * @param array $options Session ini directives [key => value]
  279.      *
  280.      * @see https://php.net/session.configuration
  281.      */
  282.     public function setOptions(array $options)
  283.     {
  284.         if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
  285.             return;
  286.         }
  287.         $validOptions array_flip([
  288.             'cache_expire''cache_limiter''cookie_domain''cookie_httponly',
  289.             'cookie_lifetime''cookie_path''cookie_secure''cookie_samesite',
  290.             'gc_divisor''gc_maxlifetime''gc_probability',
  291.             'lazy_write''name''referer_check',
  292.             'serialize_handler''use_strict_mode''use_cookies',
  293.             'use_only_cookies''use_trans_sid',
  294.             'sid_length''sid_bits_per_character''trans_sid_hosts''trans_sid_tags',
  295.         ]);
  296.         foreach ($options as $key => $value) {
  297.             if (isset($validOptions[$key])) {
  298.                 if ('cookie_secure' === $key && 'auto' === $value) {
  299.                     continue;
  300.                 }
  301.                 ini_set('session.'.$key$value);
  302.             }
  303.         }
  304.     }
  305.     /**
  306.      * Registers session save handler as a PHP session handler.
  307.      *
  308.      * To use internal PHP session save handlers, override this method using ini_set with
  309.      * session.save_handler and session.save_path e.g.
  310.      *
  311.      *     ini_set('session.save_handler', 'files');
  312.      *     ini_set('session.save_path', '/tmp');
  313.      *
  314.      * or pass in a \SessionHandler instance which configures session.save_handler in the
  315.      * constructor, for a template see NativeFileSessionHandler.
  316.      *
  317.      * @see https://php.net/session-set-save-handler
  318.      * @see https://php.net/sessionhandlerinterface
  319.      * @see https://php.net/sessionhandler
  320.      *
  321.      * @throws \InvalidArgumentException
  322.      */
  323.     public function setSaveHandler(AbstractProxy|\SessionHandlerInterface $saveHandler null)
  324.     {
  325.         if (!$saveHandler instanceof AbstractProxy &&
  326.             !$saveHandler instanceof \SessionHandlerInterface &&
  327.             null !== $saveHandler) {
  328.             throw new \InvalidArgumentException('Must be instance of AbstractProxy; implement \SessionHandlerInterface; or be null.');
  329.         }
  330.         // Wrap $saveHandler in proxy and prevent double wrapping of proxy
  331.         if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) {
  332.             $saveHandler = new SessionHandlerProxy($saveHandler);
  333.         } elseif (!$saveHandler instanceof AbstractProxy) {
  334.             $saveHandler = new SessionHandlerProxy(new StrictSessionHandler(new \SessionHandler()));
  335.         }
  336.         $this->saveHandler $saveHandler;
  337.         if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
  338.             return;
  339.         }
  340.         if ($this->saveHandler instanceof SessionHandlerProxy) {
  341.             session_set_save_handler($this->saveHandlerfalse);
  342.         }
  343.     }
  344.     /**
  345.      * Load the session with attributes.
  346.      *
  347.      * After starting the session, PHP retrieves the session from whatever handlers
  348.      * are set to (either PHP's internal, or a custom save handler set with session_set_save_handler()).
  349.      * PHP takes the return value from the read() handler, unserializes it
  350.      * and populates $_SESSION with the result automatically.
  351.      */
  352.     protected function loadSession(array &$session null)
  353.     {
  354.         if (null === $session) {
  355.             $session = &$_SESSION;
  356.         }
  357.         $bags array_merge($this->bags, [$this->metadataBag]);
  358.         foreach ($bags as $bag) {
  359.             $key $bag->getStorageKey();
  360.             $session[$key] = isset($session[$key]) && \is_array($session[$key]) ? $session[$key] : [];
  361.             $bag->initialize($session[$key]);
  362.         }
  363.         $this->started true;
  364.         $this->closed false;
  365.     }
  366. }