NativeSessionStorage.php 11 KB

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