NativeSessionStorage.php 12 KB

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