NativeSessionStorage.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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. // Help opcache.preload discover always-needed symbols
  17. class_exists(MetadataBag::class);
  18. class_exists(StrictSessionHandler::class);
  19. class_exists(SessionHandlerProxy::class);
  20. /**
  21. * This provides a base class for session attribute storage.
  22. *
  23. * @author Drak <drak@zikula.org>
  24. */
  25. class NativeSessionStorage implements SessionStorageInterface
  26. {
  27. /**
  28. * @var SessionBagInterface[]
  29. */
  30. protected $bags = [];
  31. /**
  32. * @var bool
  33. */
  34. protected $started = false;
  35. /**
  36. * @var bool
  37. */
  38. protected $closed = false;
  39. /**
  40. * @var AbstractProxy|\SessionHandlerInterface
  41. */
  42. protected $saveHandler;
  43. /**
  44. * @var MetadataBag
  45. */
  46. protected $metadataBag;
  47. /**
  48. * @var string|null
  49. */
  50. private $emulateSameSite;
  51. /**
  52. * Depending on how you want the storage driver to behave you probably
  53. * want to override this constructor entirely.
  54. *
  55. * List of options for $options array with their defaults.
  56. *
  57. * @see https://php.net/session.configuration for options
  58. * but we omit 'session.' from the beginning of the keys for convenience.
  59. *
  60. * ("auto_start", is not supported as it tells PHP to start a session before
  61. * PHP starts to execute user-land code. Setting during runtime has no effect).
  62. *
  63. * cache_limiter, "" (use "0" to prevent headers from being sent entirely).
  64. * cache_expire, "0"
  65. * cookie_domain, ""
  66. * cookie_httponly, ""
  67. * cookie_lifetime, "0"
  68. * cookie_path, "/"
  69. * cookie_secure, ""
  70. * cookie_samesite, null
  71. * gc_divisor, "100"
  72. * gc_maxlifetime, "1440"
  73. * gc_probability, "1"
  74. * lazy_write, "1"
  75. * name, "PHPSESSID"
  76. * referer_check, ""
  77. * serialize_handler, "php"
  78. * use_strict_mode, "1"
  79. * use_cookies, "1"
  80. * use_only_cookies, "1"
  81. * use_trans_sid, "0"
  82. * sid_length, "32"
  83. * sid_bits_per_character, "5"
  84. * trans_sid_hosts, $_SERVER['HTTP_HOST']
  85. * trans_sid_tags, "a=href,area=href,frame=src,form="
  86. *
  87. * @param AbstractProxy|\SessionHandlerInterface|null $handler
  88. */
  89. public function __construct(array $options = [], $handler = null, MetadataBag $metaBag = null)
  90. {
  91. if (!\extension_loaded('session')) {
  92. throw new \LogicException('PHP extension "session" is required.');
  93. }
  94. $options += [
  95. 'cache_limiter' => '',
  96. 'cache_expire' => 0,
  97. 'use_cookies' => 1,
  98. 'lazy_write' => 1,
  99. 'use_strict_mode' => 1,
  100. ];
  101. session_register_shutdown();
  102. $this->setMetadataBag($metaBag);
  103. $this->setOptions($options);
  104. $this->setSaveHandler($handler);
  105. }
  106. /**
  107. * Gets the save handler instance.
  108. *
  109. * @return AbstractProxy|\SessionHandlerInterface
  110. */
  111. public function getSaveHandler()
  112. {
  113. return $this->saveHandler;
  114. }
  115. /**
  116. * {@inheritdoc}
  117. */
  118. public function start()
  119. {
  120. if ($this->started) {
  121. return true;
  122. }
  123. if (\PHP_SESSION_ACTIVE === session_status()) {
  124. throw new \RuntimeException('Failed to start the session: already started by PHP.');
  125. }
  126. if (filter_var(ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOLEAN) && headers_sent($file, $line)) {
  127. throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file, $line));
  128. }
  129. $sessionId = $_COOKIE[session_name()] ?? null;
  130. if ($sessionId && $this->saveHandler instanceof AbstractProxy && 'files' === $this->saveHandler->getSaveHandlerName() && !preg_match('/^[a-zA-Z0-9,-]{22,}$/', $sessionId)) {
  131. // the session ID in the header is invalid, create a new one
  132. session_id(session_create_id());
  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(string $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(string $name)
  172. {
  173. $this->saveHandler->setName($name);
  174. }
  175. /**
  176. * {@inheritdoc}
  177. */
  178. public function regenerate(bool $destroy = false, int $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 && $lifetime != ini_get('session.cookie_lifetime')) {
  188. $this->save();
  189. ini_set('session.cookie_lifetime', $lifetime);
  190. $this->start();
  191. }
  192. if ($destroy) {
  193. $this->metadataBag->stampNew();
  194. }
  195. $isRegenerated = session_regenerate_id($destroy);
  196. if (null !== $this->emulateSameSite) {
  197. $originalCookie = SessionUtils::popSessionCookie(session_name(), session_id());
  198. if (null !== $originalCookie) {
  199. header(sprintf('%s; SameSite=%s', $originalCookie, $this->emulateSameSite), false);
  200. }
  201. }
  202. return $isRegenerated;
  203. }
  204. /**
  205. * {@inheritdoc}
  206. */
  207. public function save()
  208. {
  209. // Store a copy so we can restore the bags in case the session was not left empty
  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 && str_starts_with($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. // Restore only if not empty
  232. if ($_SESSION) {
  233. $_SESSION = $session;
  234. }
  235. }
  236. $this->closed = true;
  237. $this->started = false;
  238. }
  239. /**
  240. * {@inheritdoc}
  241. */
  242. public function clear()
  243. {
  244. // clear out the bags
  245. foreach ($this->bags as $bag) {
  246. $bag->clear();
  247. }
  248. // clear out the session
  249. $_SESSION = [];
  250. // reconnect the bags to the session
  251. $this->loadSession();
  252. }
  253. /**
  254. * {@inheritdoc}
  255. */
  256. public function registerBag(SessionBagInterface $bag)
  257. {
  258. if ($this->started) {
  259. throw new \LogicException('Cannot register a bag when the session is already started.');
  260. }
  261. $this->bags[$bag->getName()] = $bag;
  262. }
  263. /**
  264. * {@inheritdoc}
  265. */
  266. public function getBag(string $name)
  267. {
  268. if (!isset($this->bags[$name])) {
  269. throw new \InvalidArgumentException(sprintf('The SessionBagInterface "%s" is not registered.', $name));
  270. }
  271. if (!$this->started && $this->saveHandler->isActive()) {
  272. $this->loadSession();
  273. } elseif (!$this->started) {
  274. $this->start();
  275. }
  276. return $this->bags[$name];
  277. }
  278. public function setMetadataBag(MetadataBag $metaBag = null)
  279. {
  280. if (null === $metaBag) {
  281. $metaBag = new MetadataBag();
  282. }
  283. $this->metadataBag = $metaBag;
  284. }
  285. /**
  286. * Gets the MetadataBag.
  287. *
  288. * @return MetadataBag
  289. */
  290. public function getMetadataBag()
  291. {
  292. return $this->metadataBag;
  293. }
  294. /**
  295. * {@inheritdoc}
  296. */
  297. public function isStarted()
  298. {
  299. return $this->started;
  300. }
  301. /**
  302. * Sets session.* ini variables.
  303. *
  304. * For convenience we omit 'session.' from the beginning of the keys.
  305. * Explicitly ignores other ini keys.
  306. *
  307. * @param array $options Session ini directives [key => value]
  308. *
  309. * @see https://php.net/session.configuration
  310. */
  311. public function setOptions(array $options)
  312. {
  313. if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
  314. return;
  315. }
  316. $validOptions = array_flip([
  317. 'cache_expire', 'cache_limiter', 'cookie_domain', 'cookie_httponly',
  318. 'cookie_lifetime', 'cookie_path', 'cookie_secure', 'cookie_samesite',
  319. 'gc_divisor', 'gc_maxlifetime', 'gc_probability',
  320. 'lazy_write', 'name', 'referer_check',
  321. 'serialize_handler', 'use_strict_mode', 'use_cookies',
  322. 'use_only_cookies', 'use_trans_sid', 'upload_progress.enabled',
  323. 'upload_progress.cleanup', 'upload_progress.prefix', 'upload_progress.name',
  324. 'upload_progress.freq', 'upload_progress.min_freq', 'url_rewriter.tags',
  325. 'sid_length', 'sid_bits_per_character', 'trans_sid_hosts', 'trans_sid_tags',
  326. ]);
  327. foreach ($options as $key => $value) {
  328. if (isset($validOptions[$key])) {
  329. if (str_starts_with($key, 'upload_progress.')) {
  330. trigger_deprecation('symfony/http-foundation', '5.4', 'Support for the "%s" session option is deprecated. The settings prefixed with "session.upload_progress." can not be changed at runtime.', $key);
  331. continue;
  332. }
  333. if ('url_rewriter.tags' === $key) {
  334. trigger_deprecation('symfony/http-foundation', '5.4', 'Support for the "%s" session option is deprecated. Use "trans_sid_tags" instead.', $key);
  335. }
  336. if ('cookie_samesite' === $key && \PHP_VERSION_ID < 70300) {
  337. // PHP < 7.3 does not support same_site cookies. We will emulate it in
  338. // the start() method instead.
  339. $this->emulateSameSite = $value;
  340. continue;
  341. }
  342. if ('cookie_secure' === $key && 'auto' === $value) {
  343. continue;
  344. }
  345. ini_set('url_rewriter.tags' !== $key ? 'session.'.$key : $key, $value);
  346. }
  347. }
  348. }
  349. /**
  350. * Registers session save handler as a PHP session handler.
  351. *
  352. * To use internal PHP session save handlers, override this method using ini_set with
  353. * session.save_handler and session.save_path e.g.
  354. *
  355. * ini_set('session.save_handler', 'files');
  356. * ini_set('session.save_path', '/tmp');
  357. *
  358. * or pass in a \SessionHandler instance which configures session.save_handler in the
  359. * constructor, for a template see NativeFileSessionHandler.
  360. *
  361. * @see https://php.net/session-set-save-handler
  362. * @see https://php.net/sessionhandlerinterface
  363. * @see https://php.net/sessionhandler
  364. *
  365. * @param AbstractProxy|\SessionHandlerInterface|null $saveHandler
  366. *
  367. * @throws \InvalidArgumentException
  368. */
  369. public function setSaveHandler($saveHandler = null)
  370. {
  371. if (!$saveHandler instanceof AbstractProxy &&
  372. !$saveHandler instanceof \SessionHandlerInterface &&
  373. null !== $saveHandler) {
  374. throw new \InvalidArgumentException('Must be instance of AbstractProxy; implement \SessionHandlerInterface; or be null.');
  375. }
  376. // Wrap $saveHandler in proxy and prevent double wrapping of proxy
  377. if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) {
  378. $saveHandler = new SessionHandlerProxy($saveHandler);
  379. } elseif (!$saveHandler instanceof AbstractProxy) {
  380. $saveHandler = new SessionHandlerProxy(new StrictSessionHandler(new \SessionHandler()));
  381. }
  382. $this->saveHandler = $saveHandler;
  383. if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
  384. return;
  385. }
  386. if ($this->saveHandler instanceof SessionHandlerProxy) {
  387. session_set_save_handler($this->saveHandler, false);
  388. }
  389. }
  390. /**
  391. * Load the session with attributes.
  392. *
  393. * After starting the session, PHP retrieves the session from whatever handlers
  394. * are set to (either PHP's internal, or a custom save handler set with session_set_save_handler()).
  395. * PHP takes the return value from the read() handler, unserializes it
  396. * and populates $_SESSION with the result automatically.
  397. */
  398. protected function loadSession(array &$session = null)
  399. {
  400. if (null === $session) {
  401. $session = &$_SESSION;
  402. }
  403. $bags = array_merge($this->bags, [$this->metadataBag]);
  404. foreach ($bags as $bag) {
  405. $key = $bag->getStorageKey();
  406. $session[$key] = isset($session[$key]) && \is_array($session[$key]) ? $session[$key] : [];
  407. $bag->initialize($session[$key]);
  408. }
  409. $this->started = true;
  410. $this->closed = false;
  411. }
  412. }