NativeSessionStorage.php 14 KB

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