Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\HttpFoundation\Session\Storage; Chris@0: Chris@0: use Symfony\Component\HttpFoundation\Session\SessionBagInterface; Chris@14: use Symfony\Component\HttpFoundation\Session\Storage\Handler\StrictSessionHandler; Chris@0: use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy; Chris@0: use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy; Chris@0: Chris@0: /** Chris@0: * This provides a base class for session attribute storage. Chris@0: * Chris@0: * @author Drak Chris@0: */ Chris@0: class NativeSessionStorage implements SessionStorageInterface Chris@0: { Chris@0: /** Chris@0: * @var SessionBagInterface[] Chris@0: */ Chris@17: protected $bags = []; Chris@0: Chris@0: /** Chris@0: * @var bool Chris@0: */ Chris@0: protected $started = false; Chris@0: Chris@0: /** Chris@0: * @var bool Chris@0: */ Chris@0: protected $closed = false; Chris@0: Chris@0: /** Chris@14: * @var AbstractProxy|\SessionHandlerInterface Chris@0: */ Chris@0: protected $saveHandler; Chris@0: Chris@0: /** Chris@0: * @var MetadataBag Chris@0: */ Chris@0: protected $metadataBag; Chris@0: Chris@0: /** Chris@0: * Depending on how you want the storage driver to behave you probably Chris@0: * want to override this constructor entirely. Chris@0: * Chris@0: * List of options for $options array with their defaults. Chris@0: * Chris@0: * @see http://php.net/session.configuration for options Chris@0: * but we omit 'session.' from the beginning of the keys for convenience. Chris@0: * Chris@0: * ("auto_start", is not supported as it tells PHP to start a session before Chris@0: * PHP starts to execute user-land code. Setting during runtime has no effect). Chris@0: * Chris@0: * cache_limiter, "" (use "0" to prevent headers from being sent entirely). Chris@14: * cache_expire, "0" Chris@0: * cookie_domain, "" Chris@0: * cookie_httponly, "" Chris@0: * cookie_lifetime, "0" Chris@0: * cookie_path, "/" Chris@0: * cookie_secure, "" Chris@0: * entropy_file, "" Chris@0: * entropy_length, "0" Chris@0: * gc_divisor, "100" Chris@0: * gc_maxlifetime, "1440" Chris@0: * gc_probability, "1" Chris@0: * hash_bits_per_character, "4" Chris@0: * hash_function, "0" Chris@14: * lazy_write, "1" Chris@0: * name, "PHPSESSID" Chris@0: * referer_check, "" Chris@0: * serialize_handler, "php" Chris@0: * use_strict_mode, "0" Chris@0: * use_cookies, "1" Chris@0: * use_only_cookies, "1" Chris@0: * use_trans_sid, "0" Chris@0: * upload_progress.enabled, "1" Chris@0: * upload_progress.cleanup, "1" Chris@0: * upload_progress.prefix, "upload_progress_" Chris@0: * upload_progress.name, "PHP_SESSION_UPLOAD_PROGRESS" Chris@0: * upload_progress.freq, "1%" Chris@0: * upload_progress.min-freq, "1" Chris@0: * url_rewriter.tags, "a=href,area=href,frame=src,form=,fieldset=" Chris@12: * sid_length, "32" Chris@12: * sid_bits_per_character, "5" Chris@12: * trans_sid_hosts, $_SERVER['HTTP_HOST'] Chris@12: * trans_sid_tags, "a=href,area=href,frame=src,form=" Chris@0: * Chris@14: * @param array $options Session configuration options Chris@14: * @param \SessionHandlerInterface|null $handler Chris@14: * @param MetadataBag $metaBag MetadataBag Chris@0: */ Chris@17: public function __construct(array $options = [], $handler = null, MetadataBag $metaBag = null) Chris@0: { Chris@17: $options += [ Chris@14: 'cache_limiter' => '', Chris@14: 'cache_expire' => 0, Chris@14: 'use_cookies' => 1, Chris@14: 'lazy_write' => 1, Chris@17: ]; Chris@0: Chris@0: session_register_shutdown(); Chris@0: Chris@0: $this->setMetadataBag($metaBag); Chris@0: $this->setOptions($options); Chris@0: $this->setSaveHandler($handler); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the save handler instance. Chris@0: * Chris@14: * @return AbstractProxy|\SessionHandlerInterface Chris@0: */ Chris@0: public function getSaveHandler() Chris@0: { Chris@0: return $this->saveHandler; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function start() Chris@0: { Chris@0: if ($this->started) { Chris@0: return true; Chris@0: } Chris@0: Chris@0: if (\PHP_SESSION_ACTIVE === session_status()) { Chris@0: throw new \RuntimeException('Failed to start the session: already started by PHP.'); Chris@0: } Chris@0: Chris@17: if (filter_var(ini_get('session.use_cookies'), FILTER_VALIDATE_BOOLEAN) && headers_sent($file, $line)) { Chris@0: throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file, $line)); Chris@0: } Chris@0: Chris@0: // ok to try and start the session Chris@0: if (!session_start()) { Chris@0: throw new \RuntimeException('Failed to start the session'); Chris@0: } Chris@0: Chris@0: $this->loadSession(); Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function getId() Chris@0: { Chris@0: return $this->saveHandler->getId(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function setId($id) Chris@0: { Chris@0: $this->saveHandler->setId($id); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function getName() Chris@0: { Chris@0: return $this->saveHandler->getName(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function setName($name) Chris@0: { Chris@0: $this->saveHandler->setName($name); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function regenerate($destroy = false, $lifetime = null) Chris@0: { Chris@0: // Cannot regenerate the session ID for non-active sessions. Chris@0: if (\PHP_SESSION_ACTIVE !== session_status()) { Chris@0: return false; Chris@0: } Chris@0: Chris@14: if (headers_sent()) { Chris@14: return false; Chris@14: } Chris@14: Chris@0: if (null !== $lifetime) { Chris@0: ini_set('session.cookie_lifetime', $lifetime); Chris@0: } Chris@0: Chris@0: if ($destroy) { Chris@0: $this->metadataBag->stampNew(); Chris@0: } Chris@0: Chris@0: $isRegenerated = session_regenerate_id($destroy); Chris@0: Chris@0: // The reference to $_SESSION in session bags is lost in PHP7 and we need to re-create it. Chris@0: // @see https://bugs.php.net/bug.php?id=70013 Chris@0: $this->loadSession(); Chris@0: Chris@0: return $isRegenerated; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function save() Chris@0: { Chris@14: $session = $_SESSION; Chris@14: Chris@14: foreach ($this->bags as $bag) { Chris@14: if (empty($_SESSION[$key = $bag->getStorageKey()])) { Chris@14: unset($_SESSION[$key]); Chris@14: } Chris@14: } Chris@17: if ([$key = $this->metadataBag->getStorageKey()] === array_keys($_SESSION)) { Chris@14: unset($_SESSION[$key]); Chris@14: } Chris@14: Chris@17: // Register error handler to add information about the current save handler Chris@17: $previousHandler = set_error_handler(function ($type, $msg, $file, $line) use (&$previousHandler) { Chris@17: if (E_WARNING === $type && 0 === strpos($msg, 'session_write_close():')) { Chris@17: $handler = $this->saveHandler instanceof SessionHandlerProxy ? $this->saveHandler->getHandler() : $this->saveHandler; Chris@17: $msg = sprintf('session_write_close(): Failed to write session data with "%s" handler', \get_class($handler)); Chris@17: } Chris@17: Chris@17: return $previousHandler ? $previousHandler($type, $msg, $file, $line) : false; Chris@17: }); Chris@14: Chris@14: try { Chris@14: session_write_close(); Chris@14: } finally { Chris@14: restore_error_handler(); Chris@14: $_SESSION = $session; Chris@14: } Chris@0: Chris@0: $this->closed = true; Chris@0: $this->started = false; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function clear() Chris@0: { Chris@0: // clear out the bags Chris@0: foreach ($this->bags as $bag) { Chris@0: $bag->clear(); Chris@0: } Chris@0: Chris@0: // clear out the session Chris@17: $_SESSION = []; Chris@0: Chris@0: // reconnect the bags to the session Chris@0: $this->loadSession(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function registerBag(SessionBagInterface $bag) Chris@0: { Chris@0: if ($this->started) { Chris@0: throw new \LogicException('Cannot register a bag when the session is already started.'); Chris@0: } Chris@0: Chris@0: $this->bags[$bag->getName()] = $bag; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function getBag($name) Chris@0: { Chris@0: if (!isset($this->bags[$name])) { Chris@0: throw new \InvalidArgumentException(sprintf('The SessionBagInterface %s is not registered.', $name)); Chris@0: } Chris@0: Chris@14: if (!$this->started && $this->saveHandler->isActive()) { Chris@0: $this->loadSession(); Chris@0: } elseif (!$this->started) { Chris@0: $this->start(); Chris@0: } Chris@0: Chris@0: return $this->bags[$name]; Chris@0: } Chris@0: Chris@0: public function setMetadataBag(MetadataBag $metaBag = null) Chris@0: { Chris@0: if (null === $metaBag) { Chris@0: $metaBag = new MetadataBag(); Chris@0: } Chris@0: Chris@0: $this->metadataBag = $metaBag; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the MetadataBag. Chris@0: * Chris@0: * @return MetadataBag Chris@0: */ Chris@0: public function getMetadataBag() Chris@0: { Chris@0: return $this->metadataBag; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function isStarted() Chris@0: { Chris@0: return $this->started; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets session.* ini variables. Chris@0: * Chris@0: * For convenience we omit 'session.' from the beginning of the keys. Chris@0: * Explicitly ignores other ini keys. Chris@0: * Chris@17: * @param array $options Session ini directives [key => value] Chris@0: * Chris@0: * @see http://php.net/session.configuration Chris@0: */ Chris@0: public function setOptions(array $options) Chris@0: { Chris@14: if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) { Chris@14: return; Chris@14: } Chris@14: Chris@17: $validOptions = array_flip([ Chris@16: 'cache_expire', 'cache_limiter', 'cookie_domain', 'cookie_httponly', Chris@0: 'cookie_lifetime', 'cookie_path', 'cookie_secure', Chris@0: 'entropy_file', 'entropy_length', 'gc_divisor', Chris@0: 'gc_maxlifetime', 'gc_probability', 'hash_bits_per_character', Chris@14: 'hash_function', 'lazy_write', 'name', 'referer_check', Chris@0: 'serialize_handler', 'use_strict_mode', 'use_cookies', Chris@0: 'use_only_cookies', 'use_trans_sid', 'upload_progress.enabled', Chris@0: 'upload_progress.cleanup', 'upload_progress.prefix', 'upload_progress.name', Chris@16: 'upload_progress.freq', 'upload_progress.min_freq', 'url_rewriter.tags', Chris@12: 'sid_length', 'sid_bits_per_character', 'trans_sid_hosts', 'trans_sid_tags', Chris@17: ]); Chris@0: Chris@0: foreach ($options as $key => $value) { Chris@0: if (isset($validOptions[$key])) { Chris@16: ini_set('url_rewriter.tags' !== $key ? 'session.'.$key : $key, $value); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Registers session save handler as a PHP session handler. Chris@0: * Chris@0: * To use internal PHP session save handlers, override this method using ini_set with Chris@0: * session.save_handler and session.save_path e.g. Chris@0: * Chris@0: * ini_set('session.save_handler', 'files'); Chris@0: * ini_set('session.save_path', '/tmp'); Chris@0: * Chris@14: * or pass in a \SessionHandler instance which configures session.save_handler in the Chris@0: * constructor, for a template see NativeFileSessionHandler or use handlers in Chris@0: * composer package drak/native-session Chris@0: * Chris@0: * @see http://php.net/session-set-save-handler Chris@0: * @see http://php.net/sessionhandlerinterface Chris@0: * @see http://php.net/sessionhandler Chris@0: * @see http://github.com/drak/NativeSession Chris@0: * Chris@14: * @param \SessionHandlerInterface|null $saveHandler Chris@0: * Chris@0: * @throws \InvalidArgumentException Chris@0: */ Chris@0: public function setSaveHandler($saveHandler = null) Chris@0: { Chris@0: if (!$saveHandler instanceof AbstractProxy && Chris@0: !$saveHandler instanceof \SessionHandlerInterface && Chris@0: null !== $saveHandler) { Chris@14: throw new \InvalidArgumentException('Must be instance of AbstractProxy; implement \SessionHandlerInterface; or be null.'); Chris@0: } Chris@0: Chris@0: // Wrap $saveHandler in proxy and prevent double wrapping of proxy Chris@0: if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) { Chris@0: $saveHandler = new SessionHandlerProxy($saveHandler); Chris@0: } elseif (!$saveHandler instanceof AbstractProxy) { Chris@14: $saveHandler = new SessionHandlerProxy(new StrictSessionHandler(new \SessionHandler())); Chris@0: } Chris@0: $this->saveHandler = $saveHandler; Chris@0: Chris@14: if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) { Chris@14: return; Chris@14: } Chris@14: Chris@14: if ($this->saveHandler instanceof SessionHandlerProxy) { Chris@0: session_set_save_handler($this->saveHandler, false); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Load the session with attributes. Chris@0: * Chris@0: * After starting the session, PHP retrieves the session from whatever handlers Chris@0: * are set to (either PHP's internal, or a custom save handler set with session_set_save_handler()). Chris@0: * PHP takes the return value from the read() handler, unserializes it Chris@0: * and populates $_SESSION with the result automatically. Chris@0: */ Chris@0: protected function loadSession(array &$session = null) Chris@0: { Chris@0: if (null === $session) { Chris@0: $session = &$_SESSION; Chris@0: } Chris@0: Chris@17: $bags = array_merge($this->bags, [$this->metadataBag]); Chris@0: Chris@0: foreach ($bags as $bag) { Chris@0: $key = $bag->getStorageKey(); Chris@17: $session[$key] = isset($session[$key]) ? $session[$key] : []; Chris@0: $bag->initialize($session[$key]); Chris@0: } Chris@0: Chris@0: $this->started = true; Chris@0: $this->closed = false; Chris@0: } Chris@0: }