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

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\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 <drak@zikula.org>
  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 http://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/bug.php?id=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.         $session $_SESSION;
  211.         foreach ($this->bags as $bag) {
  212.             if (empty($_SESSION[$key $bag->getStorageKey()])) {
  213.                 unset($_SESSION[$key]);
  214.             }
  215.         }
  216.         if ([$key $this->metadataBag->getStorageKey()] === array_keys($_SESSION)) {
  217.             unset($_SESSION[$key]);
  218.         }
  219.         // Register error handler to add information about the current save handler
  220.         $previousHandler set_error_handler(function ($type$msg$file$line) use (&$previousHandler) {
  221.             if (E_WARNING === $type && === strpos($msg'session_write_close():')) {
  222.                 $handler $this->saveHandler instanceof SessionHandlerProxy $this->saveHandler->getHandler() : $this->saveHandler;
  223.                 $msg sprintf('session_write_close(): Failed to write session data with "%s" handler', \get_class($handler));
  224.             }
  225.             return $previousHandler $previousHandler($type$msg$file$line) : false;
  226.         });
  227.         try {
  228.             session_write_close();
  229.         } finally {
  230.             restore_error_handler();
  231.             $_SESSION $session;
  232.         }
  233.         $this->closed true;
  234.         $this->started false;
  235.     }
  236.     /**
  237.      * {@inheritdoc}
  238.      */
  239.     public function clear()
  240.     {
  241.         // clear out the bags
  242.         foreach ($this->bags as $bag) {
  243.             $bag->clear();
  244.         }
  245.         // clear out the session
  246.         $_SESSION = [];
  247.         // reconnect the bags to the session
  248.         $this->loadSession();
  249.     }
  250.     /**
  251.      * {@inheritdoc}
  252.      */
  253.     public function registerBag(SessionBagInterface $bag)
  254.     {
  255.         if ($this->started) {
  256.             throw new \LogicException('Cannot register a bag when the session is already started.');
  257.         }
  258.         $this->bags[$bag->getName()] = $bag;
  259.     }
  260.     /**
  261.      * {@inheritdoc}
  262.      */
  263.     public function getBag($name)
  264.     {
  265.         if (!isset($this->bags[$name])) {
  266.             throw new \InvalidArgumentException(sprintf('The SessionBagInterface %s is not registered.'$name));
  267.         }
  268.         if (!$this->started && $this->saveHandler->isActive()) {
  269.             $this->loadSession();
  270.         } elseif (!$this->started) {
  271.             $this->start();
  272.         }
  273.         return $this->bags[$name];
  274.     }
  275.     public function setMetadataBag(MetadataBag $metaBag null)
  276.     {
  277.         if (null === $metaBag) {
  278.             $metaBag = new MetadataBag();
  279.         }
  280.         $this->metadataBag $metaBag;
  281.     }
  282.     /**
  283.      * Gets the MetadataBag.
  284.      *
  285.      * @return MetadataBag
  286.      */
  287.     public function getMetadataBag()
  288.     {
  289.         return $this->metadataBag;
  290.     }
  291.     /**
  292.      * {@inheritdoc}
  293.      */
  294.     public function isStarted()
  295.     {
  296.         return $this->started;
  297.     }
  298.     /**
  299.      * Sets session.* ini variables.
  300.      *
  301.      * For convenience we omit 'session.' from the beginning of the keys.
  302.      * Explicitly ignores other ini keys.
  303.      *
  304.      * @param array $options Session ini directives [key => value]
  305.      *
  306.      * @see http://php.net/session.configuration
  307.      */
  308.     public function setOptions(array $options)
  309.     {
  310.         if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
  311.             return;
  312.         }
  313.         $validOptions array_flip([
  314.             'cache_expire''cache_limiter''cookie_domain''cookie_httponly',
  315.             'cookie_lifetime''cookie_path''cookie_secure''cookie_samesite',
  316.             'gc_divisor''gc_maxlifetime''gc_probability',
  317.             'lazy_write''name''referer_check',
  318.             'serialize_handler''use_strict_mode''use_cookies',
  319.             'use_only_cookies''use_trans_sid''upload_progress.enabled',
  320.             'upload_progress.cleanup''upload_progress.prefix''upload_progress.name',
  321.             'upload_progress.freq''upload_progress.min_freq''url_rewriter.tags',
  322.             'sid_length''sid_bits_per_character''trans_sid_hosts''trans_sid_tags',
  323.         ]);
  324.         foreach ($options as $key => $value) {
  325.             if (isset($validOptions[$key])) {
  326.                 if ('cookie_samesite' === $key && \PHP_VERSION_ID 70300) {
  327.                     // PHP < 7.3 does not support same_site cookies. We will emulate it in
  328.                     // the start() method instead.
  329.                     $this->emulateSameSite $value;
  330.                     continue;
  331.                 }
  332.                 ini_set('url_rewriter.tags' !== $key 'session.'.$key $key$value);
  333.             }
  334.         }
  335.     }
  336.     /**
  337.      * Registers session save handler as a PHP session handler.
  338.      *
  339.      * To use internal PHP session save handlers, override this method using ini_set with
  340.      * session.save_handler and session.save_path e.g.
  341.      *
  342.      *     ini_set('session.save_handler', 'files');
  343.      *     ini_set('session.save_path', '/tmp');
  344.      *
  345.      * or pass in a \SessionHandler instance which configures session.save_handler in the
  346.      * constructor, for a template see NativeFileSessionHandler or use handlers in
  347.      * composer package drak/native-session
  348.      *
  349.      * @see http://php.net/session-set-save-handler
  350.      * @see http://php.net/sessionhandlerinterface
  351.      * @see http://php.net/sessionhandler
  352.      * @see http://github.com/drak/NativeSession
  353.      *
  354.      * @param \SessionHandlerInterface|null $saveHandler
  355.      *
  356.      * @throws \InvalidArgumentException
  357.      */
  358.     public function setSaveHandler($saveHandler null)
  359.     {
  360.         if (!$saveHandler instanceof AbstractProxy &&
  361.             !$saveHandler instanceof \SessionHandlerInterface &&
  362.             null !== $saveHandler) {
  363.             throw new \InvalidArgumentException('Must be instance of AbstractProxy; implement \SessionHandlerInterface; or be null.');
  364.         }
  365.         // Wrap $saveHandler in proxy and prevent double wrapping of proxy
  366.         if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) {
  367.             $saveHandler = new SessionHandlerProxy($saveHandler);
  368.         } elseif (!$saveHandler instanceof AbstractProxy) {
  369.             $saveHandler = new SessionHandlerProxy(new StrictSessionHandler(new \SessionHandler()));
  370.         }
  371.         $this->saveHandler $saveHandler;
  372.         if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
  373.             return;
  374.         }
  375.         if ($this->saveHandler instanceof SessionHandlerProxy) {
  376.             session_set_save_handler($this->saveHandlerfalse);
  377.         }
  378.     }
  379.     /**
  380.      * Load the session with attributes.
  381.      *
  382.      * After starting the session, PHP retrieves the session from whatever handlers
  383.      * are set to (either PHP's internal, or a custom save handler set with session_set_save_handler()).
  384.      * PHP takes the return value from the read() handler, unserializes it
  385.      * and populates $_SESSION with the result automatically.
  386.      */
  387.     protected function loadSession(array &$session null)
  388.     {
  389.         if (null === $session) {
  390.             $session = &$_SESSION;
  391.         }
  392.         $bags array_merge($this->bags, [$this->metadataBag]);
  393.         foreach ($bags as $bag) {
  394.             $key $bag->getStorageKey();
  395.             $session[$key] = isset($session[$key]) ? $session[$key] : [];
  396.             $bag->initialize($session[$key]);
  397.         }
  398.         $this->started true;
  399.         $this->closed false;
  400.     }
  401. }