菜谱项目

NativeSessionStorage.php 13KB

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