Debian Codegraph @

lib/3rdParty/composer/symfony/http-foundation/Session/Storage/NativeSessionStorage.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\HttpFoundation\Session\Storage;
13
14 use Symfony\Component\HttpFoundation\Session\SessionBagInterface;
15 use Symfony\Component\HttpFoundation\Session\Storage\Handler\StrictSessionHandler;
16 use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy;
17 use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;
18
19 // Help opcache.preload discover always-needed symbols
20 class_exists(MetadataBag::class);
21 class_exists(StrictSessionHandler::class);
22 class_exists(SessionHandlerProxy::class);
23
24 /**
25 * This provides a base class for session attribute storage.
26 *
27 * @author Drak <[email protected]>
28 */
29 class NativeSessionStorage implements SessionStorageInterface
30 {
31 /**
32 * @var SessionBagInterface[]
33 */
34 protected array $bags = [];
35 protected bool $started = false;
36 protected bool $closed = false;
37 protected AbstractProxy|\SessionHandlerInterface $saveHandler;
38 protected MetadataBag $metadataBag;
39
40 /**
41 * Depending on how you want the storage driver to behave you probably
42 * want to override this constructor entirely.
43 *
44 * List of options for $options array with their defaults.
45 *
46 * @see https://php.net/session.configuration for options
47 * but we omit 'session.' from the beginning of the keys for convenience.
48 *
49 * ("auto_start", is not supported as it tells PHP to start a session before
50 * PHP starts to execute user-land code. Setting during runtime has no effect).
51 *
52 * cache_limiter, "" (use "0" to prevent headers from being sent entirely).
53 * cache_expire, "0"
54 * cookie_domain, ""
55 * cookie_httponly, ""
56 * cookie_lifetime, "0"
57 * cookie_path, "/"
58 * cookie_secure, ""
59 * cookie_samesite, null
60 * gc_divisor, "100"
61 * gc_maxlifetime, "1440"
62 * gc_probability, "1"
63 * lazy_write, "1"
64 * name, "PHPSESSID"
65 * referer_check, "" (deprecated since Symfony 7.2, to be removed in Symfony 8.0)
66 * serialize_handler, "php"
67 * use_strict_mode, "1"
68 * use_cookies, "1"
69 * use_only_cookies, "1" (deprecated since Symfony 7.2, to be removed in Symfony 8.0)
70 * use_trans_sid, "0" (deprecated since Symfony 7.2, to be removed in Symfony 8.0)
71 * sid_length, "32" (@deprecated since Symfony 7.2, to be removed in 8.0)
72 * sid_bits_per_character, "5" (@deprecated since Symfony 7.2, to be removed in 8.0)
73 * trans_sid_hosts, $_SERVER['HTTP_HOST'] (deprecated since Symfony 7.2, to be removed in Symfony 8.0)
74 * trans_sid_tags, "a=href,area=href,frame=src,form=" (deprecated since Symfony 7.2, to be removed in Symfony 8.0)
75 */
76 public function __construct(array $options = [], AbstractProxy|\SessionHandlerInterface|null $handler = null, ?MetadataBag $metaBag = null)
77 {
78 if (!\extension_loaded('session')) {
79 throw new \LogicException('PHP extension "session" is required.');
80 }
81
82 $options += [
83 'cache_limiter' => '',
84 'cache_expire' => 0,
85 'use_cookies' => 1,
86 'lazy_write' => 1,
87 'use_strict_mode' => 1,
88 ];
89
90 session_register_shutdown();
91
92 $this->setMetadataBag($metaBag);
93 $this->setOptions($options);
94 $this->setSaveHandler($handler);
95 }
96
97 /**
98 * Gets the save handler instance.
99 */
100 public function getSaveHandler(): AbstractProxy|\SessionHandlerInterface
101 {
102 return $this->saveHandler;
103 }
104
105 public function start(): bool
106 {
107 if ($this->started) {
108 return true;
109 }
110
111 if (\PHP_SESSION_ACTIVE === session_status()) {
112 throw new \RuntimeException('Failed to start the session: already started by PHP.');
113 }
114
115 if (filter_var(\ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOL) && headers_sent($file, $line)) {
116 throw new \RuntimeException(\sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file, $line));
117 }
118
119 $sessionId = $_COOKIE[session_name()] ?? null;
120 /*
121 * Explanation of the session ID regular expression: `/^[a-zA-Z0-9,-]{22,250}$/`.
122 *
123 * ---------- Part 1
124 *
125 * The part `[a-zA-Z0-9,-]` is related to the PHP ini directive `session.sid_bits_per_character` defined as 6.
126 * See https://php.net/session.configuration#ini.session.sid-bits-per-character
127 * Allowed values are integers such as:
128 * - 4 for range `a-f0-9`
129 * - 5 for range `a-v0-9` (@deprecated since Symfony 7.2, it will default to 4 and the option will be ignored in Symfony 8.0)
130 * - 6 for range `a-zA-Z0-9,-` (@deprecated since Symfony 7.2, it will default to 4 and the option will be ignored in Symfony 8.0)
131 *
132 * ---------- Part 2
133 *
134 * The part `{22,250}` is related to the PHP ini directive `session.sid_length`.
135 * See https://php.net/session.configuration#ini.session.sid-length
136 * Allowed values are integers between 22 and 256, but we use 250 for the max.
137 *
138 * Where does the 250 come from?
139 * - The length of Windows and Linux filenames is limited to 255 bytes. Then the max must not exceed 255.
140 * - The session filename prefix is `sess_`, a 5 bytes string. Then the max must not exceed 255 - 5 = 250.
141 *
142 * This is @deprecated since Symfony 7.2, the sid length will default to 32 and the option will be ignored in Symfony 8.0.
143 *
144 * ---------- Conclusion
145 *
146 * The parts 1 and 2 prevent the warning below:
147 * `PHP Warning: SessionHandler::read(): Session ID is too long or contains illegal characters. Only the A-Z, a-z, 0-9, "-", and "," characters are allowed.`
148 *
149 * The part 2 prevents the warning below:
150 * `PHP Warning: SessionHandler::read(): open(filepath, O_RDWR) failed: No such file or directory (2).`
151 */
152 if ($sessionId && $this->saveHandler instanceof AbstractProxy && 'files' === $this->saveHandler->getSaveHandlerName() && !preg_match('/^[a-zA-Z0-9,-]{22,250}$/', $sessionId)) {
153 // the session ID in the header is invalid, create a new one
154 session_id(session_create_id());
155 }
156
157 // ok to try and start the session
158 if (!session_start()) {
159 throw new \RuntimeException('Failed to start the session.');
160 }
161
162 $this->loadSession();
163
164 return true;
165 }
166
167 public function getId(): string
168 {
169 return $this->saveHandler->getId();
170 }
171
172 public function setId(string $id): void
173 {
174 $this->saveHandler->setId($id);
175 }
176
177 public function getName(): string
178 {
179 return $this->saveHandler->getName();
180 }
181
182 public function setName(string $name): void
183 {
184 $this->saveHandler->setName($name);
185 }
186
187 public function regenerate(bool $destroy = false, ?int $lifetime = null): bool
188 {
189 // Cannot regenerate the session ID for non-active sessions.
190 if (\PHP_SESSION_ACTIVE !== session_status()) {
191 return false;
192 }
193
194 if (headers_sent()) {
195 return false;
196 }
197
198 if (null !== $lifetime && $lifetime != \ini_get('session.cookie_lifetime')) {
199 $this->save();
200 ini_set('session.cookie_lifetime', $lifetime);
201 $this->start();
202 }
203
204 if ($destroy) {
205 $this->metadataBag->stampNew();
206 }
207
208 return session_regenerate_id($destroy);
209 }
210
211 public function save(): void
212 {
213 // Store a copy so we can restore the bags in case the session was not left empty
214 $session = $_SESSION;
215
216 foreach ($this->bags as $bag) {
217 if (empty($_SESSION[$key = $bag->getStorageKey()])) {
218 unset($_SESSION[$key]);
219 }
220 }
221 if ($_SESSION && [$key = $this->metadataBag->getStorageKey()] === array_keys($_SESSION)) {
222 unset($_SESSION[$key]);
223 }
224
225 // Register error handler to add information about the current save handler
226 $previousHandler = set_error_handler(function ($type, $msg, $file, $line) use (&$previousHandler) {
227 if (\E_WARNING === $type && str_starts_with($msg, 'session_write_close():')) {
228 $handler = $this->saveHandler instanceof SessionHandlerProxy ? $this->saveHandler->getHandler() : $this->saveHandler;
229 $msg = \sprintf('session_write_close(): Failed to write session data with "%s" handler', $handler::class);
230 }
231
232 return $previousHandler ? $previousHandler($type, $msg, $file, $line) : false;
233 });
234
235 try {
236 session_write_close();
237 } finally {
238 restore_error_handler();
239
240 // Restore only if not empty
241 if ($_SESSION) {
242 $_SESSION = $session;
243 }
244 }
245
246 $this->closed = true;
247 $this->started = false;
248 }
249
250 public function clear(): void
251 {
252 // clear out the bags
253 foreach ($this->bags as $bag) {
254 $bag->clear();
255 }
256
257 // clear out the session
258 $_SESSION = [];
259
260 // reconnect the bags to the session
261 $this->loadSession();
262 }
263
264 public function registerBag(SessionBagInterface $bag): void
265 {
266 if ($this->started) {
267 throw new \LogicException('Cannot register a bag when the session is already started.');
268 }
269
270 $this->bags[$bag->getName()] = $bag;
271 }
272
273 public function getBag(string $name): SessionBagInterface
274 {
275 if (!isset($this->bags[$name])) {
276 throw new \InvalidArgumentException(\sprintf('The SessionBagInterface "%s" is not registered.', $name));
277 }
278
279 if (!$this->started && $this->saveHandler->isActive()) {
280 $this->loadSession();
281 } elseif (!$this->started) {
282 $this->start();
283 }
284
285 return $this->bags[$name];
286 }
287
288 public function setMetadataBag(?MetadataBag $metaBag): void
289 {
290 $this->metadataBag = $metaBag ?? new MetadataBag();
291 }
292
293 /**
294 * Gets the MetadataBag.
295 */
296 public function getMetadataBag(): MetadataBag
297 {
298 return $this->metadataBag;
299 }
300
301 public function isStarted(): bool
302 {
303 return $this->started;
304 }
305
306 /**
307 * Sets session.* ini variables.
308 *
309 * For convenience we omit 'session.' from the beginning of the keys.
310 * Explicitly ignores other ini keys.
311 *
312 * @param array $options Session ini directives [key => value]
313 *
314 * @see https://php.net/session.configuration
315 */
316 public function setOptions(array $options): void
317 {
318 if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
319 return;
320 }
321
322 $validOptions = array_flip([
323 'cache_expire', 'cache_limiter', 'cookie_domain', 'cookie_httponly',
324 'cookie_lifetime', 'cookie_path', 'cookie_secure', 'cookie_samesite',
325 'gc_divisor', 'gc_maxlifetime', 'gc_probability',
326 'lazy_write', 'name', 'referer_check',
327 'serialize_handler', 'use_strict_mode', 'use_cookies',
328 'use_only_cookies', 'use_trans_sid',
329 'sid_length', 'sid_bits_per_character', 'trans_sid_hosts', 'trans_sid_tags',
330 ]);
331
332 foreach ($options as $key => $value) {
333 if (\in_array($key, ['referer_check', 'use_only_cookies', 'use_trans_sid', 'trans_sid_hosts', 'trans_sid_tags', 'sid_length', 'sid_bits_per_character'], true)) {
334 trigger_deprecation('symfony/http-foundation', '7.2', 'NativeSessionStorage\'s "%s" option is deprecated and will be ignored in Symfony 8.0.', $key);
335 }
336
337 if (isset($validOptions[$key])) {
338 if ('cookie_secure' === $key && 'auto' === $value) {
339 continue;
340 }
341 ini_set('session.'.$key, $value);
342 }
343 }
344 }
345
346 /**
347 * Registers session save handler as a PHP session handler.
348 *
349 * To use internal PHP session save handlers, override this method using ini_set with
350 * session.save_handler and session.save_path e.g.
351 *
352 * ini_set('session.save_handler', 'files');
353 * ini_set('session.save_path', '/tmp');
354 *
355 * or pass in a \SessionHandler instance which configures session.save_handler in the
356 * constructor, for a template see NativeFileSessionHandler.
357 *
358 * @see https://php.net/session-set-save-handler
359 * @see https://php.net/sessionhandlerinterface
360 * @see https://php.net/sessionhandler
361 *
362 * @throws \InvalidArgumentException
363 */
364 public function setSaveHandler(AbstractProxy|\SessionHandlerInterface|null $saveHandler): void
365 {
366 // Wrap $saveHandler in proxy and prevent double wrapping of proxy
367 if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) {
368 $saveHandler = new SessionHandlerProxy($saveHandler);
369 } elseif (!$saveHandler instanceof AbstractProxy) {
370 $saveHandler = new SessionHandlerProxy(new StrictSessionHandler(new \SessionHandler()));
371 }
372 $this->saveHandler = $saveHandler;
373
374 if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
375 return;
376 }
377
378 if ($this->saveHandler instanceof SessionHandlerProxy) {
379 session_set_save_handler($this->saveHandler, false);
380 }
381 }
382
383 /**
384 * Load the session with attributes.
385 *
386 * After starting the session, PHP retrieves the session from whatever handlers
387 * are set to (either PHP's internal, or a custom save handler set with session_set_save_handler()).
388 * PHP takes the return value from the read() handler, unserializes it
389 * and populates $_SESSION with the result automatically.
390 */
391 protected function loadSession(?array &$session = null): void
392 {
393 if (null === $session) {
394 $session = &$_SESSION;
395 }
396
397 $bags = array_merge($this->bags, [$this->metadataBag]);
398
399 foreach ($bags as $bag) {
400 $key = $bag->getStorageKey();
401 $session[$key] = isset($session[$key]) && \is_array($session[$key]) ? $session[$key] : [];
402 $bag->initialize($session[$key]);
403 }
404
405 $this->started = true;
406 $this->closed = false;
407 }
408 }