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

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