NativeSessionStorage.php 13 KB

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