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

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 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 AbstractProxy|\SessionHandlerInterface|null $handler
  91.      */
  92.     public function __construct(array $options = [], $handler nullMetadataBag $metaBag null)
  93.     {
  94.         if (!\extension_loaded('session')) {
  95.             throw new \LogicException('PHP extension "session" is required.');
  96.         }
  97.         $options += [
  98.             'cache_limiter' => '',
  99.             'cache_expire' => 0,
  100.             'use_cookies' => 1,
  101.             'lazy_write' => 1,
  102.             'use_strict_mode' => 1,
  103.         ];
  104.         session_register_shutdown();
  105.         $this->setMetadataBag($metaBag);
  106.         $this->setOptions($options);
  107.         $this->setSaveHandler($handler);
  108.     }
  109.     /**
  110.      * Gets the save handler instance.
  111.      *
  112.      * @return AbstractProxy|\SessionHandlerInterface
  113.      */
  114.     public function getSaveHandler()
  115.     {
  116.         return $this->saveHandler;
  117.     }
  118.     /**
  119.      * {@inheritdoc}
  120.      */
  121.     public function start()
  122.     {
  123.         if ($this->started) {
  124.             return true;
  125.         }
  126.         if (\PHP_SESSION_ACTIVE === session_status()) {
  127.             throw new \RuntimeException('Failed to start the session: already started by PHP.');
  128.         }
  129.         if (filter_var(ini_get('session.use_cookies'), FILTER_VALIDATE_BOOLEAN) && headers_sent($file$line)) {
  130.             throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.'$file$line));
  131.         }
  132.         // ok to try and start the session
  133.         if (!session_start()) {
  134.             throw new \RuntimeException('Failed to start the session');
  135.         }
  136.         if (null !== $this->emulateSameSite) {
  137.             $originalCookie SessionUtils::popSessionCookie(session_name(), session_id());
  138.             if (null !== $originalCookie) {
  139.                 header(sprintf('%s; SameSite=%s'$originalCookie$this->emulateSameSite), false);
  140.             }
  141.         }
  142.         $this->loadSession();
  143.         return true;
  144.     }
  145.     /**
  146.      * {@inheritdoc}
  147.      */
  148.     public function getId()
  149.     {
  150.         return $this->saveHandler->getId();
  151.     }
  152.     /**
  153.      * {@inheritdoc}
  154.      */
  155.     public function setId($id)
  156.     {
  157.         $this->saveHandler->setId($id);
  158.     }
  159.     /**
  160.      * {@inheritdoc}
  161.      */
  162.     public function getName()
  163.     {
  164.         return $this->saveHandler->getName();
  165.     }
  166.     /**
  167.      * {@inheritdoc}
  168.      */
  169.     public function setName($name)
  170.     {
  171.         $this->saveHandler->setName($name);
  172.     }
  173.     /**
  174.      * {@inheritdoc}
  175.      */
  176.     public function regenerate($destroy false$lifetime null)
  177.     {
  178.         // Cannot regenerate the session ID for non-active sessions.
  179.         if (\PHP_SESSION_ACTIVE !== session_status()) {
  180.             return false;
  181.         }
  182.         if (headers_sent()) {
  183.             return false;
  184.         }
  185.         if (null !== $lifetime) {
  186.             ini_set('session.cookie_lifetime'$lifetime);
  187.         }
  188.         if ($destroy) {
  189.             $this->metadataBag->stampNew();
  190.         }
  191.         $isRegenerated session_regenerate_id($destroy);
  192.         // The reference to $_SESSION in session bags is lost in PHP7 and we need to re-create it.
  193.         // @see https://bugs.php.net/70013
  194.         $this->loadSession();
  195.         if (null !== $this->emulateSameSite) {
  196.             $originalCookie SessionUtils::popSessionCookie(session_name(), session_id());
  197.             if (null !== $originalCookie) {
  198.                 header(sprintf('%s; SameSite=%s'$originalCookie$this->emulateSameSite), false);
  199.             }
  200.         }
  201.         return $isRegenerated;
  202.     }
  203.     /**
  204.      * {@inheritdoc}
  205.      */
  206.     public function save()
  207.     {
  208.         // Store a copy so we can restore the bags in case the session was not left empty
  209.         $session $_SESSION;
  210.         foreach ($this->bags as $bag) {
  211.             if (empty($_SESSION[$key $bag->getStorageKey()])) {
  212.                 unset($_SESSION[$key]);
  213.             }
  214.         }
  215.         if ([$key $this->metadataBag->getStorageKey()] === array_keys($_SESSION)) {
  216.             unset($_SESSION[$key]);
  217.         }
  218.         // Register error handler to add information about the current save handler
  219.         $previousHandler set_error_handler(function ($type$msg$file$line) use (&$previousHandler) {
  220.             if (E_WARNING === $type && === strpos($msg'session_write_close():')) {
  221.                 $handler $this->saveHandler instanceof SessionHandlerProxy $this->saveHandler->getHandler() : $this->saveHandler;
  222.                 $msg sprintf('session_write_close(): Failed to write session data with "%s" handler', \get_class($handler));
  223.             }
  224.             return $previousHandler $previousHandler($type$msg$file$line) : false;
  225.         });
  226.         try {
  227.             session_write_close();
  228.         } finally {
  229.             restore_error_handler();
  230.             // Restore only if not empty
  231.             if ($_SESSION) {
  232.                 $_SESSION $session;
  233.             }
  234.         }
  235.         $this->closed true;
  236.         $this->started false;
  237.     }
  238.     /**
  239.      * {@inheritdoc}
  240.      */
  241.     public function clear()
  242.     {
  243.         // clear out the bags
  244.         foreach ($this->bags as $bag) {
  245.             $bag->clear();
  246.         }
  247.         // clear out the session
  248.         $_SESSION = [];
  249.         // reconnect the bags to the session
  250.         $this->loadSession();
  251.     }
  252.     /**
  253.      * {@inheritdoc}
  254.      */
  255.     public function registerBag(SessionBagInterface $bag)
  256.     {
  257.         if ($this->started) {
  258.             throw new \LogicException('Cannot register a bag when the session is already started.');
  259.         }
  260.         $this->bags[$bag->getName()] = $bag;
  261.     }
  262.     /**
  263.      * {@inheritdoc}
  264.      */
  265.     public function getBag($name)
  266.     {
  267.         if (!isset($this->bags[$name])) {
  268.             throw new \InvalidArgumentException(sprintf('The SessionBagInterface %s is not registered.'$name));
  269.         }
  270.         if (!$this->started && $this->saveHandler->isActive()) {
  271.             $this->loadSession();
  272.         } elseif (!$this->started) {
  273.             $this->start();
  274.         }
  275.         return $this->bags[$name];
  276.     }
  277.     public function setMetadataBag(MetadataBag $metaBag null)
  278.     {
  279.         if (null === $metaBag) {
  280.             $metaBag = new MetadataBag();
  281.         }
  282.         $this->metadataBag $metaBag;
  283.     }
  284.     /**
  285.      * Gets the MetadataBag.
  286.      *
  287.      * @return MetadataBag
  288.      */
  289.     public function getMetadataBag()
  290.     {
  291.         return $this->metadataBag;
  292.     }
  293.     /**
  294.      * {@inheritdoc}
  295.      */
  296.     public function isStarted()
  297.     {
  298.         return $this->started;
  299.     }
  300.     /**
  301.      * Sets session.* ini variables.
  302.      *
  303.      * For convenience we omit 'session.' from the beginning of the keys.
  304.      * Explicitly ignores other ini keys.
  305.      *
  306.      * @param array $options Session ini directives [key => value]
  307.      *
  308.      * @see https://php.net/session.configuration
  309.      */
  310.     public function setOptions(array $options)
  311.     {
  312.         if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
  313.             return;
  314.         }
  315.         $validOptions array_flip([
  316.             'cache_expire''cache_limiter''cookie_domain''cookie_httponly',
  317.             'cookie_lifetime''cookie_path''cookie_secure''cookie_samesite',
  318.             'gc_divisor''gc_maxlifetime''gc_probability',
  319.             'lazy_write''name''referer_check',
  320.             'serialize_handler''use_strict_mode''use_cookies',
  321.             'use_only_cookies''use_trans_sid''upload_progress.enabled',
  322.             'upload_progress.cleanup''upload_progress.prefix''upload_progress.name',
  323.             'upload_progress.freq''upload_progress.min_freq''url_rewriter.tags',
  324.             'sid_length''sid_bits_per_character''trans_sid_hosts''trans_sid_tags',
  325.         ]);
  326.         foreach ($options as $key => $value) {
  327.             if (isset($validOptions[$key])) {
  328.                 if ('cookie_samesite' === $key && \PHP_VERSION_ID 70300) {
  329.                     // PHP < 7.3 does not support same_site cookies. We will emulate it in
  330.                     // the start() method instead.
  331.                     $this->emulateSameSite $value;
  332.                     continue;
  333.                 }
  334.                 ini_set('url_rewriter.tags' !== $key 'session.'.$key $key$value);
  335.             }
  336.         }
  337.     }
  338.     /**
  339.      * Registers session save handler as a PHP session handler.
  340.      *
  341.      * To use internal PHP session save handlers, override this method using ini_set with
  342.      * session.save_handler and session.save_path e.g.
  343.      *
  344.      *     ini_set('session.save_handler', 'files');
  345.      *     ini_set('session.save_path', '/tmp');
  346.      *
  347.      * or pass in a \SessionHandler instance which configures session.save_handler in the
  348.      * constructor, for a template see NativeFileSessionHandler or use handlers in
  349.      * composer package drak/native-session
  350.      *
  351.      * @see https://php.net/session-set-save-handler
  352.      * @see https://php.net/sessionhandlerinterface
  353.      * @see https://php.net/sessionhandler
  354.      * @see https://github.com/zikula/NativeSession
  355.      *
  356.      * @param AbstractProxy|\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. }