NativeSessionStorage.php 13 KB

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