NativeSessionStorage.php 12 KB

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