NativeSessionStorage.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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\Proxy\NativeProxy;
  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 array
  26. */
  27. protected $bags;
  28. /**
  29. * @var boolean
  30. */
  31. protected $started = false;
  32. /**
  33. * @var boolean
  34. */
  35. protected $closed = false;
  36. /**
  37. * @var AbstractProxy
  38. */
  39. protected $saveHandler;
  40. /**
  41. * Constructor.
  42. *
  43. * Depending on how you want the storage driver to behave you probably
  44. * want top override this constructor entirely.
  45. *
  46. * List of options for $options array with their defaults.
  47. * @see http://php.net/session.configuration for options
  48. * but we omit 'session.' from the beginning of the keys for convenience.
  49. *
  50. * auto_start, "0"
  51. * cache_limiter, "nocache" (use "0" to prevent headers from being sent entirely).
  52. * cookie_domain, ""
  53. * cookie_httponly, ""
  54. * cookie_lifetime, "0"
  55. * cookie_path, "/"
  56. * cookie_secure, ""
  57. * entropy_file, ""
  58. * entropy_length, "0"
  59. * gc_divisor, "100"
  60. * gc_maxlifetime, "1440"
  61. * gc_probability, "1"
  62. * hash_bits_per_character, "4"
  63. * hash_function, "0"
  64. * name, "PHPSESSID"
  65. * referer_check, ""
  66. * serialize_handler, "php"
  67. * use_cookies, "1"
  68. * use_only_cookies, "1"
  69. * use_trans_sid, "0"
  70. * upload_progress.enabled, "1"
  71. * upload_progress.cleanup, "1"
  72. * upload_progress.prefix, "upload_progress_"
  73. * upload_progress.name, "PHP_SESSION_UPLOAD_PROGRESS"
  74. * upload_progress.freq, "1%"
  75. * upload_progress.min-freq, "1"
  76. * url_rewriter.tags, "a=href,area=href,frame=src,form=,fieldset="
  77. *
  78. * @param array $options Session configuration options.
  79. * @param object $handler SessionHandlerInterface.
  80. */
  81. public function __construct(array $options = array(), $handler = null)
  82. {
  83. // sensible defaults
  84. ini_set('session.auto_start', 0); // by default we prefer to explicitly start the session using the class.
  85. ini_set('session.cache_limiter', ''); // disable by default because it's managed by HeaderBag (if used)
  86. ini_set('session.use_cookies', 1);
  87. if (version_compare(phpversion(), '5.4.0', '>=')) {
  88. session_register_shutdown();
  89. } else {
  90. register_shutdown_function('session_write_close');
  91. }
  92. $this->setOptions($options);
  93. $this->setSaveHandler($handler);
  94. }
  95. /**
  96. * Gets the save handler instance.
  97. *
  98. * @return AbstractProxy
  99. */
  100. public function getSaveHandler()
  101. {
  102. return $this->saveHandler;
  103. }
  104. /**
  105. * {@inheritdoc}
  106. */
  107. public function start()
  108. {
  109. if ($this->started && !$this->closed) {
  110. return true;
  111. }
  112. // catch condition where session was started automatically by PHP
  113. if (!$this->started && !$this->closed && $this->saveHandler->isActive()
  114. && $this->saveHandler->isSessionHandlerInterface()) {
  115. $this->loadSession();
  116. return true;
  117. }
  118. if (ini_get('session.use_cookies') && headers_sent()) {
  119. throw new \RuntimeException('Failed to start the session because headers have already been sent.');
  120. }
  121. // start the session
  122. if (!session_start()) {
  123. throw new \RuntimeException('Failed to start the session');
  124. }
  125. $this->loadSession();
  126. if (!$this->saveHandler->isWrapper() && !$this->saveHandler->isSessionHandlerInterface()) {
  127. $this->saveHandler->setActive(false);
  128. }
  129. return true;
  130. }
  131. /**
  132. * {@inheritdoc}
  133. */
  134. public function getId()
  135. {
  136. if (!$this->started) {
  137. return ''; // returning empty is consistent with session_id() behaviour
  138. }
  139. return $this->saveHandler->getId();
  140. }
  141. /**
  142. * {@inheritdoc}
  143. */
  144. public function setId($id)
  145. {
  146. return $this->saveHandler->setId($id);
  147. }
  148. /**
  149. * {@inheritdoc}
  150. */
  151. public function getName()
  152. {
  153. return $this->saveHandler->getName();
  154. }
  155. /**
  156. * {@inheritdoc}
  157. */
  158. public function setName($name)
  159. {
  160. $this->saveHandler->setName($name);
  161. }
  162. /**
  163. * {@inheritdoc}
  164. */
  165. public function regenerate($destroy = false)
  166. {
  167. return session_regenerate_id($destroy);
  168. }
  169. /**
  170. * {@inheritdoc}
  171. */
  172. public function save()
  173. {
  174. session_write_close();
  175. if (!$this->saveHandler->isWrapper() && !$this->getSaveHandler()->isSessionHandlerInterface()) {
  176. $this->saveHandler->setActive(false);
  177. }
  178. $this->closed = true;
  179. }
  180. /**
  181. * {@inheritdoc}
  182. */
  183. public function clear()
  184. {
  185. // clear out the bags
  186. foreach ($this->bags as $bag) {
  187. $bag->clear();
  188. }
  189. // clear out the session
  190. $_SESSION = array();
  191. // reconnect the bags to the session
  192. $this->loadSession();
  193. }
  194. /**
  195. * {@inheritdoc}
  196. */
  197. public function registerBag(SessionBagInterface $bag)
  198. {
  199. $this->bags[$bag->getName()] = $bag;
  200. }
  201. /**
  202. * {@inheritdoc}
  203. */
  204. public function getBag($name)
  205. {
  206. if (!isset($this->bags[$name])) {
  207. throw new \InvalidArgumentException(sprintf('The SessionBagInterface %s is not registered.', $name));
  208. }
  209. if (ini_get('session.auto_start') && !$this->started) {
  210. $this->start();
  211. } elseif ($this->saveHandler->isActive() && !$this->started) {
  212. $this->loadSession();
  213. }
  214. return $this->bags[$name];
  215. }
  216. /**
  217. * Sets session.* ini variables.
  218. *
  219. * For convenience we omit 'session.' from the beginning of the keys.
  220. * Explicitly ignores other ini keys.
  221. *
  222. * @param array $options Session ini directives array(key => value).
  223. *
  224. * @see http://php.net/session.configuration
  225. */
  226. public function setOptions(array $options)
  227. {
  228. foreach ($options as $key => $value) {
  229. if (in_array($key, array(
  230. 'auto_start', 'cache_limiter', 'cookie_domain', 'cookie_httponly',
  231. 'cookie_lifetime', 'cookie_path', 'cookie_secure',
  232. 'entropy_file', 'entropy_length', 'gc_divisor',
  233. 'gc_maxlifetime', 'gc_probability', 'hash_bits_per_character',
  234. 'hash_function', 'name', 'referer_check',
  235. 'serialize_handler', 'use_cookies',
  236. 'use_only_cookies', 'use_trans_sid', 'upload_progress.enabled',
  237. 'upload_progress.cleanup', 'upload_progress.prefix', 'upload_progress.name',
  238. 'upload_progress.freq', 'upload_progress.min-freq', 'url_rewriter.tags'))) {
  239. ini_set('session.'.$key, $value);
  240. }
  241. }
  242. }
  243. /**
  244. * Registers save handler as a PHP session handler.
  245. *
  246. * To use internal PHP session save handlers, override this method using ini_set with
  247. * session.save_handlers and session.save_path e.g.
  248. *
  249. * ini_set('session.save_handlers', 'files');
  250. * ini_set('session.save_path', /tmp');
  251. *
  252. * @see http://php.net/session-set-save-handler
  253. * @see http://php.net/sessionhandlerinterface
  254. * @see http://php.net/sessionhandler
  255. *
  256. * @param object $saveHandler Default null means NativeProxy.
  257. */
  258. public function setSaveHandler($saveHandler = null)
  259. {
  260. // Wrap $saveHandler in proxy
  261. if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) {
  262. $saveHandler = new SessionHandlerProxy($saveHandler);
  263. } elseif (!$saveHandler instanceof AbstractProxy) {
  264. $saveHandler = new NativeProxy($saveHandler);
  265. }
  266. $this->saveHandler = $saveHandler;
  267. if ($this->saveHandler instanceof \SessionHandlerInterface) {
  268. if (version_compare(phpversion(), '5.4.0', '>=')) {
  269. session_set_save_handler($this->saveHandler, false);
  270. } else {
  271. session_set_save_handler(
  272. array($this->saveHandler, 'open'),
  273. array($this->saveHandler, 'close'),
  274. array($this->saveHandler, 'read'),
  275. array($this->saveHandler, 'write'),
  276. array($this->saveHandler, 'destroy'),
  277. array($this->saveHandler, 'gc')
  278. );
  279. }
  280. }
  281. }
  282. /**
  283. * Load the session with attributes.
  284. *
  285. * After starting the session, PHP retrieves the session from whatever handlers
  286. * are set to (either PHP's internal, or a custom save handler set with session_set_save_handler()).
  287. * PHP takes the return value from the read() handler, unserializes it
  288. * and populates $_SESSION with the result automatically.
  289. *
  290. * @param array|null $session
  291. */
  292. protected function loadSession(array &$session = null)
  293. {
  294. if (null === $session) {
  295. $session = &$_SESSION;
  296. }
  297. foreach ($this->bags as $bag) {
  298. $key = $bag->getStorageKey();
  299. $session[$key] = isset($session[$key]) ? $session[$key] : array();
  300. $bag->initialize($session[$key]);
  301. }
  302. $this->started = true;
  303. $this->closed = false;
  304. }
  305. }