NativeSessionStorage.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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\Storage\Handler\StrictSessionHandler;
  13. use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy;
  14. use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;
  15. /**
  16. * This provides a base class for session attribute storage.
  17. *
  18. * @author Drak <drak@zikula.org>
  19. */
  20. class NativeSessionStorage implements SessionStorageInterface
  21. {
  22. /**
  23. * @var SessionBagInterface[]
  24. */
  25. protected $bags = array();
  26. /**
  27. * @var bool
  28. */
  29. protected $started = false;
  30. /**
  31. * @var bool
  32. */
  33. protected $closed = false;
  34. /**
  35. * @var AbstractProxy|\SessionHandlerInterface
  36. */
  37. protected $saveHandler;
  38. /**
  39. * @var MetadataBag
  40. */
  41. protected $metadataBag;
  42. /**
  43. * Depending on how you want the storage driver to behave you probably
  44. * want to override this constructor entirely.
  45. *
  46. * List of options for $options array with their defaults.
  47. *
  48. * @see http://php.net/session.configuration for options
  49. * but we omit 'session.' from the beginning of the keys for convenience.
  50. *
  51. * ("auto_start", is not supported as it tells PHP to start a session before
  52. * PHP starts to execute user-land code. Setting during runtime has no effect).
  53. *
  54. * cache_limiter, "" (use "0" to prevent headers from being sent entirely).
  55. * cache_expire, "0"
  56. * cookie_domain, ""
  57. * cookie_httponly, ""
  58. * cookie_lifetime, "0"
  59. * cookie_path, "/"
  60. * cookie_secure, ""
  61. * entropy_file, ""
  62. * entropy_length, "0"
  63. * gc_divisor, "100"
  64. * gc_maxlifetime, "1440"
  65. * gc_probability, "1"
  66. * hash_bits_per_character, "4"
  67. * hash_function, "0"
  68. * lazy_write, "1"
  69. * name, "PHPSESSID"
  70. * referer_check, ""
  71. * serialize_handler, "php"
  72. * use_strict_mode, "0"
  73. * use_cookies, "1"
  74. * use_only_cookies, "1"
  75. * use_trans_sid, "0"
  76. * upload_progress.enabled, "1"
  77. * upload_progress.cleanup, "1"
  78. * upload_progress.prefix, "upload_progress_"
  79. * upload_progress.name, "PHP_SESSION_UPLOAD_PROGRESS"
  80. * upload_progress.freq, "1%"
  81. * upload_progress.min-freq, "1"
  82. * url_rewriter.tags, "a=href,area=href,frame=src,form=,fieldset="
  83. * sid_length, "32"
  84. * sid_bits_per_character, "5"
  85. * trans_sid_hosts, $_SERVER['HTTP_HOST']
  86. * trans_sid_tags, "a=href,area=href,frame=src,form="
  87. *
  88. * @param array $options Session configuration options
  89. * @param \SessionHandlerInterface|null $handler
  90. * @param MetadataBag $metaBag MetadataBag
  91. */
  92. public function __construct(array $options = array(), $handler = null, MetadataBag $metaBag = null)
  93. {
  94. $options += array(
  95. 'cache_limiter' => '',
  96. 'cache_expire' => 0,
  97. 'use_cookies' => 1,
  98. 'lazy_write' => 1,
  99. );
  100. session_register_shutdown();
  101. $this->setMetadataBag($metaBag);
  102. $this->setOptions($options);
  103. $this->setSaveHandler($handler);
  104. }
  105. /**
  106. * Gets the save handler instance.
  107. *
  108. * @return AbstractProxy|\SessionHandlerInterface
  109. */
  110. public function getSaveHandler()
  111. {
  112. return $this->saveHandler;
  113. }
  114. /**
  115. * {@inheritdoc}
  116. */
  117. public function start()
  118. {
  119. if ($this->started) {
  120. return true;
  121. }
  122. if (\PHP_SESSION_ACTIVE === session_status()) {
  123. throw new \RuntimeException('Failed to start the session: already started by PHP.');
  124. }
  125. if (ini_get('session.use_cookies') && headers_sent($file, $line)) {
  126. throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file, $line));
  127. }
  128. // ok to try and start the session
  129. if (!session_start()) {
  130. throw new \RuntimeException('Failed to start the session');
  131. }
  132. $this->loadSession();
  133. return true;
  134. }
  135. /**
  136. * {@inheritdoc}
  137. */
  138. public function getId()
  139. {
  140. return $this->saveHandler->getId();
  141. }
  142. /**
  143. * {@inheritdoc}
  144. */
  145. public function setId($id)
  146. {
  147. $this->saveHandler->setId($id);
  148. }
  149. /**
  150. * {@inheritdoc}
  151. */
  152. public function getName()
  153. {
  154. return $this->saveHandler->getName();
  155. }
  156. /**
  157. * {@inheritdoc}
  158. */
  159. public function setName($name)
  160. {
  161. $this->saveHandler->setName($name);
  162. }
  163. /**
  164. * {@inheritdoc}
  165. */
  166. public function regenerate($destroy = false, $lifetime = null)
  167. {
  168. // Cannot regenerate the session ID for non-active sessions.
  169. if (\PHP_SESSION_ACTIVE !== session_status()) {
  170. return false;
  171. }
  172. if (headers_sent()) {
  173. return false;
  174. }
  175. if (null !== $lifetime) {
  176. ini_set('session.cookie_lifetime', $lifetime);
  177. }
  178. if ($destroy) {
  179. $this->metadataBag->stampNew();
  180. }
  181. $isRegenerated = session_regenerate_id($destroy);
  182. // The reference to $_SESSION in session bags is lost in PHP7 and we need to re-create it.
  183. // @see https://bugs.php.net/bug.php?id=70013
  184. $this->loadSession();
  185. return $isRegenerated;
  186. }
  187. /**
  188. * {@inheritdoc}
  189. */
  190. public function save()
  191. {
  192. $session = $_SESSION;
  193. foreach ($this->bags as $bag) {
  194. if (empty($_SESSION[$key = $bag->getStorageKey()])) {
  195. unset($_SESSION[$key]);
  196. }
  197. }
  198. if (array($key = $this->metadataBag->getStorageKey()) === array_keys($_SESSION)) {
  199. unset($_SESSION[$key]);
  200. }
  201. // Register custom error handler to catch a possible failure warning during session write
  202. set_error_handler(function ($errno, $errstr, $errfile, $errline) {
  203. throw new \ErrorException($errstr, $errno, E_WARNING, $errfile, $errline);
  204. }, E_WARNING);
  205. try {
  206. $e = null;
  207. session_write_close();
  208. } catch (\ErrorException $e) {
  209. } finally {
  210. restore_error_handler();
  211. $_SESSION = $session;
  212. }
  213. if (null !== $e) {
  214. // The default PHP error message is not very helpful, as it does not give any information on the current save handler.
  215. // Therefore, we catch this error and trigger a warning with a better error message
  216. $handler = $this->getSaveHandler();
  217. if ($handler instanceof SessionHandlerProxy) {
  218. $handler = $handler->getHandler();
  219. }
  220. trigger_error(sprintf('session_write_close(): Failed to write session data with %s handler', get_class($handler)), E_USER_WARNING);
  221. }
  222. $this->closed = true;
  223. $this->started = false;
  224. }
  225. /**
  226. * {@inheritdoc}
  227. */
  228. public function clear()
  229. {
  230. // clear out the bags
  231. foreach ($this->bags as $bag) {
  232. $bag->clear();
  233. }
  234. // clear out the session
  235. $_SESSION = array();
  236. // reconnect the bags to the session
  237. $this->loadSession();
  238. }
  239. /**
  240. * {@inheritdoc}
  241. */
  242. public function registerBag(SessionBagInterface $bag)
  243. {
  244. if ($this->started) {
  245. throw new \LogicException('Cannot register a bag when the session is already started.');
  246. }
  247. $this->bags[$bag->getName()] = $bag;
  248. }
  249. /**
  250. * {@inheritdoc}
  251. */
  252. public function getBag($name)
  253. {
  254. if (!isset($this->bags[$name])) {
  255. throw new \InvalidArgumentException(sprintf('The SessionBagInterface %s is not registered.', $name));
  256. }
  257. if (!$this->started && $this->saveHandler->isActive()) {
  258. $this->loadSession();
  259. } elseif (!$this->started) {
  260. $this->start();
  261. }
  262. return $this->bags[$name];
  263. }
  264. public function setMetadataBag(MetadataBag $metaBag = null)
  265. {
  266. if (null === $metaBag) {
  267. $metaBag = new MetadataBag();
  268. }
  269. $this->metadataBag = $metaBag;
  270. }
  271. /**
  272. * Gets the MetadataBag.
  273. *
  274. * @return MetadataBag
  275. */
  276. public function getMetadataBag()
  277. {
  278. return $this->metadataBag;
  279. }
  280. /**
  281. * {@inheritdoc}
  282. */
  283. public function isStarted()
  284. {
  285. return $this->started;
  286. }
  287. /**
  288. * Sets session.* ini variables.
  289. *
  290. * For convenience we omit 'session.' from the beginning of the keys.
  291. * Explicitly ignores other ini keys.
  292. *
  293. * @param array $options Session ini directives array(key => value)
  294. *
  295. * @see http://php.net/session.configuration
  296. */
  297. public function setOptions(array $options)
  298. {
  299. if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
  300. return;
  301. }
  302. $validOptions = array_flip(array(
  303. 'cache_expire', 'cache_limiter', 'cookie_domain', 'cookie_httponly',
  304. 'cookie_lifetime', 'cookie_path', 'cookie_secure',
  305. 'entropy_file', 'entropy_length', 'gc_divisor',
  306. 'gc_maxlifetime', 'gc_probability', 'hash_bits_per_character',
  307. 'hash_function', 'lazy_write', 'name', 'referer_check',
  308. 'serialize_handler', 'use_strict_mode', 'use_cookies',
  309. 'use_only_cookies', 'use_trans_sid', 'upload_progress.enabled',
  310. 'upload_progress.cleanup', 'upload_progress.prefix', 'upload_progress.name',
  311. 'upload_progress.freq', 'upload_progress.min_freq', 'url_rewriter.tags',
  312. 'sid_length', 'sid_bits_per_character', 'trans_sid_hosts', 'trans_sid_tags',
  313. ));
  314. foreach ($options as $key => $value) {
  315. if (isset($validOptions[$key])) {
  316. ini_set('url_rewriter.tags' !== $key ? 'session.'.$key : $key, $value);
  317. }
  318. }
  319. }
  320. /**
  321. * Registers session save handler as a PHP session handler.
  322. *
  323. * To use internal PHP session save handlers, override this method using ini_set with
  324. * session.save_handler and session.save_path e.g.
  325. *
  326. * ini_set('session.save_handler', 'files');
  327. * ini_set('session.save_path', '/tmp');
  328. *
  329. * or pass in a \SessionHandler instance which configures session.save_handler in the
  330. * constructor, for a template see NativeFileSessionHandler or use handlers in
  331. * composer package drak/native-session
  332. *
  333. * @see http://php.net/session-set-save-handler
  334. * @see http://php.net/sessionhandlerinterface
  335. * @see http://php.net/sessionhandler
  336. * @see http://github.com/drak/NativeSession
  337. *
  338. * @param \SessionHandlerInterface|null $saveHandler
  339. *
  340. * @throws \InvalidArgumentException
  341. */
  342. public function setSaveHandler($saveHandler = null)
  343. {
  344. if (!$saveHandler instanceof AbstractProxy &&
  345. !$saveHandler instanceof \SessionHandlerInterface &&
  346. null !== $saveHandler) {
  347. throw new \InvalidArgumentException('Must be instance of AbstractProxy; implement \SessionHandlerInterface; or be null.');
  348. }
  349. // Wrap $saveHandler in proxy and prevent double wrapping of proxy
  350. if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) {
  351. $saveHandler = new SessionHandlerProxy($saveHandler);
  352. } elseif (!$saveHandler instanceof AbstractProxy) {
  353. $saveHandler = new SessionHandlerProxy(new StrictSessionHandler(new \SessionHandler()));
  354. }
  355. $this->saveHandler = $saveHandler;
  356. if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
  357. return;
  358. }
  359. if ($this->saveHandler instanceof SessionHandlerProxy) {
  360. session_set_save_handler($this->saveHandler->getHandler(), false);
  361. } elseif ($this->saveHandler instanceof \SessionHandlerInterface) {
  362. session_set_save_handler($this->saveHandler, false);
  363. }
  364. }
  365. /**
  366. * Load the session with attributes.
  367. *
  368. * After starting the session, PHP retrieves the session from whatever handlers
  369. * are set to (either PHP's internal, or a custom save handler set with session_set_save_handler()).
  370. * PHP takes the return value from the read() handler, unserializes it
  371. * and populates $_SESSION with the result automatically.
  372. */
  373. protected function loadSession(array &$session = null)
  374. {
  375. if (null === $session) {
  376. $session = &$_SESSION;
  377. }
  378. $bags = array_merge($this->bags, array($this->metadataBag));
  379. foreach ($bags as $bag) {
  380. $key = $bag->getStorageKey();
  381. $session[$key] = isset($session[$key]) ? $session[$key] : array();
  382. $bag->initialize($session[$key]);
  383. }
  384. $this->started = true;
  385. $this->closed = false;
  386. }
  387. }