PageRenderTime 27ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/myCore/lib/laravel/symfony/http-foundation/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php

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