Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
/*
4
 * This file is part of the Symfony package.
5
 *
6
 * (c) Fabien Potencier <fabien@symfony.com>
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;
13
 
14
use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException;
15
use Symfony\Component\HttpFoundation\Exception\JsonException;
16
use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
17
use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException;
18
use Symfony\Component\HttpFoundation\Session\SessionInterface;
19
 
20
// Help opcache.preload discover always-needed symbols
21
class_exists(AcceptHeader::class);
22
class_exists(FileBag::class);
23
class_exists(HeaderBag::class);
24
class_exists(HeaderUtils::class);
25
class_exists(InputBag::class);
26
class_exists(ParameterBag::class);
27
class_exists(ServerBag::class);
28
 
29
/**
30
 * Request represents an HTTP request.
31
 *
32
 * The methods dealing with URL accept / return a raw path (% encoded):
33
 *   * getBasePath
34
 *   * getBaseUrl
35
 *   * getPathInfo
36
 *   * getRequestUri
37
 *   * getUri
38
 *   * getUriForPath
39
 *
40
 * @author Fabien Potencier <fabien@symfony.com>
41
 */
42
class Request
43
{
44
    public const HEADER_FORWARDED = 0b000001; // When using RFC 7239
45
    public const HEADER_X_FORWARDED_FOR = 0b000010;
46
    public const HEADER_X_FORWARDED_HOST = 0b000100;
47
    public const HEADER_X_FORWARDED_PROTO = 0b001000;
48
    public const HEADER_X_FORWARDED_PORT = 0b010000;
49
    public const HEADER_X_FORWARDED_PREFIX = 0b100000;
50
 
51
    public const HEADER_X_FORWARDED_AWS_ELB = 0b0011010; // AWS ELB doesn't send X-Forwarded-Host
52
    public const HEADER_X_FORWARDED_TRAEFIK = 0b0111110; // All "X-Forwarded-*" headers sent by Traefik reverse proxy
53
 
54
    public const METHOD_HEAD = 'HEAD';
55
    public const METHOD_GET = 'GET';
56
    public const METHOD_POST = 'POST';
57
    public const METHOD_PUT = 'PUT';
58
    public const METHOD_PATCH = 'PATCH';
59
    public const METHOD_DELETE = 'DELETE';
60
    public const METHOD_PURGE = 'PURGE';
61
    public const METHOD_OPTIONS = 'OPTIONS';
62
    public const METHOD_TRACE = 'TRACE';
63
    public const METHOD_CONNECT = 'CONNECT';
64
 
65
    /**
66
     * @var string[]
67
     */
68
    protected static $trustedProxies = [];
69
 
70
    /**
71
     * @var string[]
72
     */
73
    protected static $trustedHostPatterns = [];
74
 
75
    /**
76
     * @var string[]
77
     */
78
    protected static $trustedHosts = [];
79
 
80
    protected static $httpMethodParameterOverride = false;
81
 
82
    /**
83
     * Custom parameters.
84
     *
85
     * @var ParameterBag
86
     */
87
    public $attributes;
88
 
89
    /**
90
     * Request body parameters ($_POST).
91
     *
92
     * @var InputBag
93
     */
94
    public $request;
95
 
96
    /**
97
     * Query string parameters ($_GET).
98
     *
99
     * @var InputBag
100
     */
101
    public $query;
102
 
103
    /**
104
     * Server and execution environment parameters ($_SERVER).
105
     *
106
     * @var ServerBag
107
     */
108
    public $server;
109
 
110
    /**
111
     * Uploaded files ($_FILES).
112
     *
113
     * @var FileBag
114
     */
115
    public $files;
116
 
117
    /**
118
     * Cookies ($_COOKIE).
119
     *
120
     * @var InputBag
121
     */
122
    public $cookies;
123
 
124
    /**
125
     * Headers (taken from the $_SERVER).
126
     *
127
     * @var HeaderBag
128
     */
129
    public $headers;
130
 
131
    /**
132
     * @var string|resource|false|null
133
     */
134
    protected $content;
135
 
136
    /**
137
     * @var string[]
138
     */
139
    protected $languages;
140
 
141
    /**
142
     * @var string[]
143
     */
144
    protected $charsets;
145
 
146
    /**
147
     * @var string[]
148
     */
149
    protected $encodings;
150
 
151
    /**
152
     * @var string[]
153
     */
154
    protected $acceptableContentTypes;
155
 
156
    /**
157
     * @var string
158
     */
159
    protected $pathInfo;
160
 
161
    /**
162
     * @var string
163
     */
164
    protected $requestUri;
165
 
166
    /**
167
     * @var string
168
     */
169
    protected $baseUrl;
170
 
171
    /**
172
     * @var string
173
     */
174
    protected $basePath;
175
 
176
    /**
177
     * @var string
178
     */
179
    protected $method;
180
 
181
    /**
182
     * @var string
183
     */
184
    protected $format;
185
 
186
    /**
187
     * @var SessionInterface|callable(): SessionInterface
188
     */
189
    protected $session;
190
 
191
    /**
688 lars 192
     * @var string|null
148 lars 193
     */
194
    protected $locale;
195
 
196
    /**
197
     * @var string
198
     */
199
    protected $defaultLocale = 'en';
200
 
201
    /**
202
     * @var array<string, string[]>
203
     */
204
    protected static $formats;
205
 
206
    protected static $requestFactory;
207
 
208
    private ?string $preferredFormat = null;
209
    private bool $isHostValid = true;
210
    private bool $isForwardedValid = true;
211
    private bool $isSafeContentPreferred;
212
 
213
    private static int $trustedHeaderSet = -1;
214
 
215
    private const FORWARDED_PARAMS = [
216
        self::HEADER_X_FORWARDED_FOR => 'for',
217
        self::HEADER_X_FORWARDED_HOST => 'host',
218
        self::HEADER_X_FORWARDED_PROTO => 'proto',
219
        self::HEADER_X_FORWARDED_PORT => 'host',
220
    ];
221
 
222
    /**
223
     * Names for headers that can be trusted when
224
     * using trusted proxies.
225
     *
226
     * The FORWARDED header is the standard as of rfc7239.
227
     *
228
     * The other headers are non-standard, but widely used
229
     * by popular reverse proxies (like Apache mod_proxy or Amazon EC2).
230
     */
231
    private const TRUSTED_HEADERS = [
232
        self::HEADER_FORWARDED => 'FORWARDED',
233
        self::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR',
234
        self::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST',
235
        self::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO',
236
        self::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT',
237
        self::HEADER_X_FORWARDED_PREFIX => 'X_FORWARDED_PREFIX',
238
    ];
239
 
240
    /**
241
     * @param array                $query      The GET parameters
242
     * @param array                $request    The POST parameters
243
     * @param array                $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
244
     * @param array                $cookies    The COOKIE parameters
245
     * @param array                $files      The FILES parameters
246
     * @param array                $server     The SERVER parameters
247
     * @param string|resource|null $content    The raw body data
248
     */
249
    public function __construct(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null)
250
    {
251
        $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
252
    }
253
 
254
    /**
255
     * Sets the parameters for this request.
256
     *
257
     * This method also re-initializes all properties.
258
     *
259
     * @param array                $query      The GET parameters
260
     * @param array                $request    The POST parameters
261
     * @param array                $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
262
     * @param array                $cookies    The COOKIE parameters
263
     * @param array                $files      The FILES parameters
264
     * @param array                $server     The SERVER parameters
265
     * @param string|resource|null $content    The raw body data
266
     */
267
    public function initialize(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null)
268
    {
269
        $this->request = new InputBag($request);
270
        $this->query = new InputBag($query);
271
        $this->attributes = new ParameterBag($attributes);
272
        $this->cookies = new InputBag($cookies);
273
        $this->files = new FileBag($files);
274
        $this->server = new ServerBag($server);
275
        $this->headers = new HeaderBag($this->server->getHeaders());
276
 
277
        $this->content = $content;
278
        $this->languages = null;
279
        $this->charsets = null;
280
        $this->encodings = null;
281
        $this->acceptableContentTypes = null;
282
        $this->pathInfo = null;
283
        $this->requestUri = null;
284
        $this->baseUrl = null;
285
        $this->basePath = null;
286
        $this->method = null;
287
        $this->format = null;
288
    }
289
 
290
    /**
291
     * Creates a new request with values from PHP's super globals.
292
     */
293
    public static function createFromGlobals(): static
294
    {
295
        $request = self::createRequestFromFactory($_GET, $_POST, [], $_COOKIE, $_FILES, $_SERVER);
296
 
297
        if (str_starts_with($request->headers->get('CONTENT_TYPE', ''), 'application/x-www-form-urlencoded')
298
            && \in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), ['PUT', 'DELETE', 'PATCH'])
299
        ) {
300
            parse_str($request->getContent(), $data);
301
            $request->request = new InputBag($data);
302
        }
303
 
304
        return $request;
305
    }
306
 
307
    /**
308
     * Creates a Request based on a given URI and configuration.
309
     *
310
     * The information contained in the URI always take precedence
311
     * over the other information (server and parameters).
312
     *
313
     * @param string               $uri        The URI
314
     * @param string               $method     The HTTP method
315
     * @param array                $parameters The query (GET) or request (POST) parameters
316
     * @param array                $cookies    The request cookies ($_COOKIE)
317
     * @param array                $files      The request files ($_FILES)
318
     * @param array                $server     The server parameters ($_SERVER)
319
     * @param string|resource|null $content    The raw body data
320
     */
321
    public static function create(string $uri, string $method = 'GET', array $parameters = [], array $cookies = [], array $files = [], array $server = [], $content = null): static
322
    {
323
        $server = array_replace([
324
            'SERVER_NAME' => 'localhost',
325
            'SERVER_PORT' => 80,
326
            'HTTP_HOST' => 'localhost',
327
            'HTTP_USER_AGENT' => 'Symfony',
328
            'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
329
            'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5',
330
            'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
331
            'REMOTE_ADDR' => '127.0.0.1',
332
            'SCRIPT_NAME' => '',
333
            'SCRIPT_FILENAME' => '',
334
            'SERVER_PROTOCOL' => 'HTTP/1.1',
335
            'REQUEST_TIME' => time(),
336
            'REQUEST_TIME_FLOAT' => microtime(true),
337
        ], $server);
338
 
339
        $server['PATH_INFO'] = '';
340
        $server['REQUEST_METHOD'] = strtoupper($method);
341
 
342
        $components = parse_url($uri);
343
        if (isset($components['host'])) {
344
            $server['SERVER_NAME'] = $components['host'];
345
            $server['HTTP_HOST'] = $components['host'];
346
        }
347
 
348
        if (isset($components['scheme'])) {
349
            if ('https' === $components['scheme']) {
350
                $server['HTTPS'] = 'on';
351
                $server['SERVER_PORT'] = 443;
352
            } else {
353
                unset($server['HTTPS']);
354
                $server['SERVER_PORT'] = 80;
355
            }
356
        }
357
 
358
        if (isset($components['port'])) {
359
            $server['SERVER_PORT'] = $components['port'];
360
            $server['HTTP_HOST'] .= ':'.$components['port'];
361
        }
362
 
363
        if (isset($components['user'])) {
364
            $server['PHP_AUTH_USER'] = $components['user'];
365
        }
366
 
367
        if (isset($components['pass'])) {
368
            $server['PHP_AUTH_PW'] = $components['pass'];
369
        }
370
 
371
        if (!isset($components['path'])) {
372
            $components['path'] = '/';
373
        }
374
 
375
        switch (strtoupper($method)) {
376
            case 'POST':
377
            case 'PUT':
378
            case 'DELETE':
379
                if (!isset($server['CONTENT_TYPE'])) {
380
                    $server['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
381
                }
382
                // no break
383
            case 'PATCH':
384
                $request = $parameters;
385
                $query = [];
386
                break;
387
            default:
388
                $request = [];
389
                $query = $parameters;
390
                break;
391
        }
392
 
393
        $queryString = '';
394
        if (isset($components['query'])) {
395
            parse_str(html_entity_decode($components['query']), $qs);
396
 
397
            if ($query) {
398
                $query = array_replace($qs, $query);
399
                $queryString = http_build_query($query, '', '&');
400
            } else {
401
                $query = $qs;
402
                $queryString = $components['query'];
403
            }
404
        } elseif ($query) {
405
            $queryString = http_build_query($query, '', '&');
406
        }
407
 
408
        $server['REQUEST_URI'] = $components['path'].('' !== $queryString ? '?'.$queryString : '');
409
        $server['QUERY_STRING'] = $queryString;
410
 
411
        return self::createRequestFromFactory($query, $request, [], $cookies, $files, $server, $content);
412
    }
413
 
414
    /**
415
     * Sets a callable able to create a Request instance.
416
     *
417
     * This is mainly useful when you need to override the Request class
418
     * to keep BC with an existing system. It should not be used for any
419
     * other purpose.
420
     */
421
    public static function setFactory(?callable $callable)
422
    {
423
        self::$requestFactory = $callable;
424
    }
425
 
426
    /**
427
     * Clones a request and overrides some of its parameters.
428
     *
688 lars 429
     * @param array|null $query      The GET parameters
430
     * @param array|null $request    The POST parameters
431
     * @param array|null $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
432
     * @param array|null $cookies    The COOKIE parameters
433
     * @param array|null $files      The FILES parameters
434
     * @param array|null $server     The SERVER parameters
148 lars 435
     */
436
    public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null): static
437
    {
438
        $dup = clone $this;
439
        if (null !== $query) {
440
            $dup->query = new InputBag($query);
441
        }
442
        if (null !== $request) {
443
            $dup->request = new InputBag($request);
444
        }
445
        if (null !== $attributes) {
446
            $dup->attributes = new ParameterBag($attributes);
447
        }
448
        if (null !== $cookies) {
449
            $dup->cookies = new InputBag($cookies);
450
        }
451
        if (null !== $files) {
452
            $dup->files = new FileBag($files);
453
        }
454
        if (null !== $server) {
455
            $dup->server = new ServerBag($server);
456
            $dup->headers = new HeaderBag($dup->server->getHeaders());
457
        }
458
        $dup->languages = null;
459
        $dup->charsets = null;
460
        $dup->encodings = null;
461
        $dup->acceptableContentTypes = null;
462
        $dup->pathInfo = null;
463
        $dup->requestUri = null;
464
        $dup->baseUrl = null;
465
        $dup->basePath = null;
466
        $dup->method = null;
467
        $dup->format = null;
468
 
469
        if (!$dup->get('_format') && $this->get('_format')) {
470
            $dup->attributes->set('_format', $this->get('_format'));
471
        }
472
 
473
        if (!$dup->getRequestFormat(null)) {
474
            $dup->setRequestFormat($this->getRequestFormat(null));
475
        }
476
 
477
        return $dup;
478
    }
479
 
480
    /**
481
     * Clones the current request.
482
     *
483
     * Note that the session is not cloned as duplicated requests
484
     * are most of the time sub-requests of the main one.
485
     */
486
    public function __clone()
487
    {
488
        $this->query = clone $this->query;
489
        $this->request = clone $this->request;
490
        $this->attributes = clone $this->attributes;
491
        $this->cookies = clone $this->cookies;
492
        $this->files = clone $this->files;
493
        $this->server = clone $this->server;
494
        $this->headers = clone $this->headers;
495
    }
496
 
497
    public function __toString(): string
498
    {
499
        $content = $this->getContent();
500
 
501
        $cookieHeader = '';
502
        $cookies = [];
503
 
504
        foreach ($this->cookies as $k => $v) {
505
            $cookies[] = \is_array($v) ? http_build_query([$k => $v], '', '; ', \PHP_QUERY_RFC3986) : "$k=$v";
506
        }
507
 
508
        if ($cookies) {
509
            $cookieHeader = 'Cookie: '.implode('; ', $cookies)."\r\n";
510
        }
511
 
512
        return
513
            sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n".
514
            $this->headers.
515
            $cookieHeader."\r\n".
516
            $content;
517
    }
518
 
519
    /**
520
     * Overrides the PHP global variables according to this request instance.
521
     *
522
     * It overrides $_GET, $_POST, $_REQUEST, $_SERVER, $_COOKIE.
523
     * $_FILES is never overridden, see rfc1867
524
     */
525
    public function overrideGlobals()
526
    {
527
        $this->server->set('QUERY_STRING', static::normalizeQueryString(http_build_query($this->query->all(), '', '&')));
528
 
529
        $_GET = $this->query->all();
530
        $_POST = $this->request->all();
531
        $_SERVER = $this->server->all();
532
        $_COOKIE = $this->cookies->all();
533
 
534
        foreach ($this->headers->all() as $key => $value) {
535
            $key = strtoupper(str_replace('-', '_', $key));
536
            if (\in_array($key, ['CONTENT_TYPE', 'CONTENT_LENGTH', 'CONTENT_MD5'], true)) {
537
                $_SERVER[$key] = implode(', ', $value);
538
            } else {
539
                $_SERVER['HTTP_'.$key] = implode(', ', $value);
540
            }
541
        }
542
 
543
        $request = ['g' => $_GET, 'p' => $_POST, 'c' => $_COOKIE];
544
 
545
        $requestOrder = \ini_get('request_order') ?: \ini_get('variables_order');
546
        $requestOrder = preg_replace('#[^cgp]#', '', strtolower($requestOrder)) ?: 'gp';
547
 
548
        $_REQUEST = [[]];
549
 
550
        foreach (str_split($requestOrder) as $order) {
551
            $_REQUEST[] = $request[$order];
552
        }
553
 
554
        $_REQUEST = array_merge(...$_REQUEST);
555
    }
556
 
557
    /**
558
     * Sets a list of trusted proxies.
559
     *
560
     * You should only list the reverse proxies that you manage directly.
561
     *
562
     * @param array $proxies          A list of trusted proxies, the string 'REMOTE_ADDR' will be replaced with $_SERVER['REMOTE_ADDR']
563
     * @param int   $trustedHeaderSet A bit field of Request::HEADER_*, to set which headers to trust from your proxies
564
     */
565
    public static function setTrustedProxies(array $proxies, int $trustedHeaderSet)
566
    {
567
        self::$trustedProxies = array_reduce($proxies, function ($proxies, $proxy) {
568
            if ('REMOTE_ADDR' !== $proxy) {
569
                $proxies[] = $proxy;
570
            } elseif (isset($_SERVER['REMOTE_ADDR'])) {
571
                $proxies[] = $_SERVER['REMOTE_ADDR'];
572
            }
573
 
574
            return $proxies;
575
        }, []);
576
        self::$trustedHeaderSet = $trustedHeaderSet;
577
    }
578
 
579
    /**
580
     * Gets the list of trusted proxies.
581
     *
582
     * @return string[]
583
     */
584
    public static function getTrustedProxies(): array
585
    {
586
        return self::$trustedProxies;
587
    }
588
 
589
    /**
590
     * Gets the set of trusted headers from trusted proxies.
591
     *
592
     * @return int A bit field of Request::HEADER_* that defines which headers are trusted from your proxies
593
     */
594
    public static function getTrustedHeaderSet(): int
595
    {
596
        return self::$trustedHeaderSet;
597
    }
598
 
599
    /**
600
     * Sets a list of trusted host patterns.
601
     *
602
     * You should only list the hosts you manage using regexs.
603
     *
604
     * @param array $hostPatterns A list of trusted host patterns
605
     */
606
    public static function setTrustedHosts(array $hostPatterns)
607
    {
608
        self::$trustedHostPatterns = array_map(function ($hostPattern) {
609
            return sprintf('{%s}i', $hostPattern);
610
        }, $hostPatterns);
611
        // we need to reset trusted hosts on trusted host patterns change
612
        self::$trustedHosts = [];
613
    }
614
 
615
    /**
616
     * Gets the list of trusted host patterns.
617
     *
618
     * @return string[]
619
     */
620
    public static function getTrustedHosts(): array
621
    {
622
        return self::$trustedHostPatterns;
623
    }
624
 
625
    /**
626
     * Normalizes a query string.
627
     *
628
     * It builds a normalized query string, where keys/value pairs are alphabetized,
629
     * have consistent escaping and unneeded delimiters are removed.
630
     */
631
    public static function normalizeQueryString(?string $qs): string
632
    {
633
        if ('' === ($qs ?? '')) {
634
            return '';
635
        }
636
 
637
        $qs = HeaderUtils::parseQuery($qs);
638
        ksort($qs);
639
 
640
        return http_build_query($qs, '', '&', \PHP_QUERY_RFC3986);
641
    }
642
 
643
    /**
644
     * Enables support for the _method request parameter to determine the intended HTTP method.
645
     *
646
     * Be warned that enabling this feature might lead to CSRF issues in your code.
647
     * Check that you are using CSRF tokens when required.
648
     * If the HTTP method parameter override is enabled, an html-form with method "POST" can be altered
649
     * and used to send a "PUT" or "DELETE" request via the _method request parameter.
650
     * If these methods are not protected against CSRF, this presents a possible vulnerability.
651
     *
652
     * The HTTP method can only be overridden when the real HTTP method is POST.
653
     */
654
    public static function enableHttpMethodParameterOverride()
655
    {
656
        self::$httpMethodParameterOverride = true;
657
    }
658
 
659
    /**
660
     * Checks whether support for the _method request parameter is enabled.
661
     */
662
    public static function getHttpMethodParameterOverride(): bool
663
    {
664
        return self::$httpMethodParameterOverride;
665
    }
666
 
667
    /**
668
     * Gets a "parameter" value from any bag.
669
     *
670
     * This method is mainly useful for libraries that want to provide some flexibility. If you don't need the
671
     * flexibility in controllers, it is better to explicitly get request parameters from the appropriate
672
     * public property instead (attributes, query, request).
673
     *
674
     * Order of precedence: PATH (routing placeholders or custom attributes), GET, POST
675
     *
676
     * @internal use explicit input sources instead
677
     */
678
    public function get(string $key, mixed $default = null): mixed
679
    {
680
        if ($this !== $result = $this->attributes->get($key, $this)) {
681
            return $result;
682
        }
683
 
684
        if ($this->query->has($key)) {
685
            return $this->query->all()[$key];
686
        }
687
 
688
        if ($this->request->has($key)) {
689
            return $this->request->all()[$key];
690
        }
691
 
692
        return $default;
693
    }
694
 
695
    /**
696
     * Gets the Session.
697
     *
698
     * @throws SessionNotFoundException When session is not set properly
699
     */
700
    public function getSession(): SessionInterface
701
    {
702
        $session = $this->session;
703
        if (!$session instanceof SessionInterface && null !== $session) {
704
            $this->setSession($session = $session());
705
        }
706
 
707
        if (null === $session) {
708
            throw new SessionNotFoundException('Session has not been set.');
709
        }
710
 
711
        return $session;
712
    }
713
 
714
    /**
715
     * Whether the request contains a Session which was started in one of the
716
     * previous requests.
717
     */
718
    public function hasPreviousSession(): bool
719
    {
720
        // the check for $this->session avoids malicious users trying to fake a session cookie with proper name
721
        return $this->hasSession() && $this->cookies->has($this->getSession()->getName());
722
    }
723
 
724
    /**
725
     * Whether the request contains a Session object.
726
     *
727
     * This method does not give any information about the state of the session object,
728
     * like whether the session is started or not. It is just a way to check if this Request
729
     * is associated with a Session instance.
730
     *
731
     * @param bool $skipIfUninitialized When true, ignores factories injected by `setSessionFactory`
732
     */
733
    public function hasSession(bool $skipIfUninitialized = false): bool
734
    {
735
        return null !== $this->session && (!$skipIfUninitialized || $this->session instanceof SessionInterface);
736
    }
737
 
738
    public function setSession(SessionInterface $session)
739
    {
740
        $this->session = $session;
741
    }
742
 
743
    /**
744
     * @internal
745
     *
746
     * @param callable(): SessionInterface $factory
747
     */
748
    public function setSessionFactory(callable $factory)
749
    {
750
        $this->session = $factory;
751
    }
752
 
753
    /**
754
     * Returns the client IP addresses.
755
     *
756
     * In the returned array the most trusted IP address is first, and the
757
     * least trusted one last. The "real" client IP address is the last one,
758
     * but this is also the least trusted one. Trusted proxies are stripped.
759
     *
760
     * Use this method carefully; you should use getClientIp() instead.
761
     *
762
     * @see getClientIp()
763
     */
764
    public function getClientIps(): array
765
    {
766
        $ip = $this->server->get('REMOTE_ADDR');
767
 
768
        if (!$this->isFromTrustedProxy()) {
769
            return [$ip];
770
        }
771
 
772
        return $this->getTrustedValues(self::HEADER_X_FORWARDED_FOR, $ip) ?: [$ip];
773
    }
774
 
775
    /**
776
     * Returns the client IP address.
777
     *
778
     * This method can read the client IP address from the "X-Forwarded-For" header
779
     * when trusted proxies were set via "setTrustedProxies()". The "X-Forwarded-For"
780
     * header value is a comma+space separated list of IP addresses, the left-most
781
     * being the original client, and each successive proxy that passed the request
782
     * adding the IP address where it received the request from.
783
     *
784
     * If your reverse proxy uses a different header name than "X-Forwarded-For",
785
     * ("Client-Ip" for instance), configure it via the $trustedHeaderSet
786
     * argument of the Request::setTrustedProxies() method instead.
787
     *
788
     * @see getClientIps()
789
     * @see https://wikipedia.org/wiki/X-Forwarded-For
790
     */
791
    public function getClientIp(): ?string
792
    {
793
        $ipAddresses = $this->getClientIps();
794
 
795
        return $ipAddresses[0];
796
    }
797
 
798
    /**
799
     * Returns current script name.
800
     */
801
    public function getScriptName(): string
802
    {
803
        return $this->server->get('SCRIPT_NAME', $this->server->get('ORIG_SCRIPT_NAME', ''));
804
    }
805
 
806
    /**
807
     * Returns the path being requested relative to the executed script.
808
     *
809
     * The path info always starts with a /.
810
     *
811
     * Suppose this request is instantiated from /mysite on localhost:
812
     *
813
     *  * http://localhost/mysite              returns an empty string
814
     *  * http://localhost/mysite/about        returns '/about'
815
     *  * http://localhost/mysite/enco%20ded   returns '/enco%20ded'
816
     *  * http://localhost/mysite/about?var=1  returns '/about'
817
     *
818
     * @return string The raw path (i.e. not urldecoded)
819
     */
820
    public function getPathInfo(): string
821
    {
822
        return $this->pathInfo ??= $this->preparePathInfo();
823
    }
824
 
825
    /**
826
     * Returns the root path from which this request is executed.
827
     *
828
     * Suppose that an index.php file instantiates this request object:
829
     *
830
     *  * http://localhost/index.php         returns an empty string
831
     *  * http://localhost/index.php/page    returns an empty string
832
     *  * http://localhost/web/index.php     returns '/web'
833
     *  * http://localhost/we%20b/index.php  returns '/we%20b'
834
     *
835
     * @return string The raw path (i.e. not urldecoded)
836
     */
837
    public function getBasePath(): string
838
    {
839
        return $this->basePath ??= $this->prepareBasePath();
840
    }
841
 
842
    /**
843
     * Returns the root URL from which this request is executed.
844
     *
845
     * The base URL never ends with a /.
846
     *
847
     * This is similar to getBasePath(), except that it also includes the
848
     * script filename (e.g. index.php) if one exists.
849
     *
850
     * @return string The raw URL (i.e. not urldecoded)
851
     */
852
    public function getBaseUrl(): string
853
    {
854
        $trustedPrefix = '';
855
 
856
        // the proxy prefix must be prepended to any prefix being needed at the webserver level
857
        if ($this->isFromTrustedProxy() && $trustedPrefixValues = $this->getTrustedValues(self::HEADER_X_FORWARDED_PREFIX)) {
858
            $trustedPrefix = rtrim($trustedPrefixValues[0], '/');
859
        }
860
 
861
        return $trustedPrefix.$this->getBaseUrlReal();
862
    }
863
 
864
    /**
865
     * Returns the real base URL received by the webserver from which this request is executed.
866
     * The URL does not include trusted reverse proxy prefix.
867
     *
868
     * @return string The raw URL (i.e. not urldecoded)
869
     */
870
    private function getBaseUrlReal(): string
871
    {
872
        return $this->baseUrl ??= $this->prepareBaseUrl();
873
    }
874
 
875
    /**
876
     * Gets the request's scheme.
877
     */
878
    public function getScheme(): string
879
    {
880
        return $this->isSecure() ? 'https' : 'http';
881
    }
882
 
883
    /**
884
     * Returns the port on which the request is made.
885
     *
886
     * This method can read the client port from the "X-Forwarded-Port" header
887
     * when trusted proxies were set via "setTrustedProxies()".
888
     *
889
     * The "X-Forwarded-Port" header must contain the client port.
890
     *
891
     * @return int|string|null Can be a string if fetched from the server bag
892
     */
893
    public function getPort(): int|string|null
894
    {
895
        if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_X_FORWARDED_PORT)) {
896
            $host = $host[0];
897
        } elseif ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_X_FORWARDED_HOST)) {
898
            $host = $host[0];
899
        } elseif (!$host = $this->headers->get('HOST')) {
900
            return $this->server->get('SERVER_PORT');
901
        }
902
 
903
        if ('[' === $host[0]) {
904
            $pos = strpos($host, ':', strrpos($host, ']'));
905
        } else {
906
            $pos = strrpos($host, ':');
907
        }
908
 
909
        if (false !== $pos && $port = substr($host, $pos + 1)) {
910
            return (int) $port;
911
        }
912
 
913
        return 'https' === $this->getScheme() ? 443 : 80;
914
    }
915
 
916
    /**
917
     * Returns the user.
918
     */
919
    public function getUser(): ?string
920
    {
921
        return $this->headers->get('PHP_AUTH_USER');
922
    }
923
 
924
    /**
925
     * Returns the password.
926
     */
927
    public function getPassword(): ?string
928
    {
929
        return $this->headers->get('PHP_AUTH_PW');
930
    }
931
 
932
    /**
933
     * Gets the user info.
934
     *
935
     * @return string|null A user name if any and, optionally, scheme-specific information about how to gain authorization to access the server
936
     */
937
    public function getUserInfo(): ?string
938
    {
939
        $userinfo = $this->getUser();
940
 
941
        $pass = $this->getPassword();
942
        if ('' != $pass) {
943
            $userinfo .= ":$pass";
944
        }
945
 
946
        return $userinfo;
947
    }
948
 
949
    /**
950
     * Returns the HTTP host being requested.
951
     *
952
     * The port name will be appended to the host if it's non-standard.
953
     */
954
    public function getHttpHost(): string
955
    {
956
        $scheme = $this->getScheme();
957
        $port = $this->getPort();
958
 
959
        if (('http' === $scheme && 80 == $port) || ('https' === $scheme && 443 == $port)) {
960
            return $this->getHost();
961
        }
962
 
963
        return $this->getHost().':'.$port;
964
    }
965
 
966
    /**
967
     * Returns the requested URI (path and query string).
968
     *
969
     * @return string The raw URI (i.e. not URI decoded)
970
     */
971
    public function getRequestUri(): string
972
    {
973
        return $this->requestUri ??= $this->prepareRequestUri();
974
    }
975
 
976
    /**
977
     * Gets the scheme and HTTP host.
978
     *
979
     * If the URL was called with basic authentication, the user
980
     * and the password are not added to the generated string.
981
     */
982
    public function getSchemeAndHttpHost(): string
983
    {
984
        return $this->getScheme().'://'.$this->getHttpHost();
985
    }
986
 
987
    /**
988
     * Generates a normalized URI (URL) for the Request.
989
     *
990
     * @see getQueryString()
991
     */
992
    public function getUri(): string
993
    {
994
        if (null !== $qs = $this->getQueryString()) {
995
            $qs = '?'.$qs;
996
        }
997
 
998
        return $this->getSchemeAndHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs;
999
    }
1000
 
1001
    /**
1002
     * Generates a normalized URI for the given path.
1003
     *
1004
     * @param string $path A path to use instead of the current one
1005
     */
1006
    public function getUriForPath(string $path): string
1007
    {
1008
        return $this->getSchemeAndHttpHost().$this->getBaseUrl().$path;
1009
    }
1010
 
1011
    /**
1012
     * Returns the path as relative reference from the current Request path.
1013
     *
1014
     * Only the URIs path component (no schema, host etc.) is relevant and must be given.
1015
     * Both paths must be absolute and not contain relative parts.
1016
     * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
1017
     * Furthermore, they can be used to reduce the link size in documents.
1018
     *
1019
     * Example target paths, given a base path of "/a/b/c/d":
1020
     * - "/a/b/c/d"     -> ""
1021
     * - "/a/b/c/"      -> "./"
1022
     * - "/a/b/"        -> "../"
1023
     * - "/a/b/c/other" -> "other"
1024
     * - "/a/x/y"       -> "../../x/y"
1025
     */
1026
    public function getRelativeUriForPath(string $path): string
1027
    {
1028
        // be sure that we are dealing with an absolute path
1029
        if (!isset($path[0]) || '/' !== $path[0]) {
1030
            return $path;
1031
        }
1032
 
1033
        if ($path === $basePath = $this->getPathInfo()) {
1034
            return '';
1035
        }
1036
 
1037
        $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
1038
        $targetDirs = explode('/', substr($path, 1));
1039
        array_pop($sourceDirs);
1040
        $targetFile = array_pop($targetDirs);
1041
 
1042
        foreach ($sourceDirs as $i => $dir) {
1043
            if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
1044
                unset($sourceDirs[$i], $targetDirs[$i]);
1045
            } else {
1046
                break;
1047
            }
1048
        }
1049
 
1050
        $targetDirs[] = $targetFile;
1051
        $path = str_repeat('../', \count($sourceDirs)).implode('/', $targetDirs);
1052
 
1053
        // A reference to the same base directory or an empty subdirectory must be prefixed with "./".
1054
        // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
1055
        // as the first segment of a relative-path reference, as it would be mistaken for a scheme name
1056
        // (see https://tools.ietf.org/html/rfc3986#section-4.2).
1057
        return !isset($path[0]) || '/' === $path[0]
1058
            || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
1059
            ? "./$path" : $path;
1060
    }
1061
 
1062
    /**
1063
     * Generates the normalized query string for the Request.
1064
     *
1065
     * It builds a normalized query string, where keys/value pairs are alphabetized
1066
     * and have consistent escaping.
1067
     */
1068
    public function getQueryString(): ?string
1069
    {
1070
        $qs = static::normalizeQueryString($this->server->get('QUERY_STRING'));
1071
 
1072
        return '' === $qs ? null : $qs;
1073
    }
1074
 
1075
    /**
1076
     * Checks whether the request is secure or not.
1077
     *
1078
     * This method can read the client protocol from the "X-Forwarded-Proto" header
1079
     * when trusted proxies were set via "setTrustedProxies()".
1080
     *
1081
     * The "X-Forwarded-Proto" header must contain the protocol: "https" or "http".
1082
     */
1083
    public function isSecure(): bool
1084
    {
1085
        if ($this->isFromTrustedProxy() && $proto = $this->getTrustedValues(self::HEADER_X_FORWARDED_PROTO)) {
1086
            return \in_array(strtolower($proto[0]), ['https', 'on', 'ssl', '1'], true);
1087
        }
1088
 
1089
        $https = $this->server->get('HTTPS');
1090
 
1091
        return !empty($https) && 'off' !== strtolower($https);
1092
    }
1093
 
1094
    /**
1095
     * Returns the host name.
1096
     *
1097
     * This method can read the client host name from the "X-Forwarded-Host" header
1098
     * when trusted proxies were set via "setTrustedProxies()".
1099
     *
1100
     * The "X-Forwarded-Host" header must contain the client host name.
1101
     *
1102
     * @throws SuspiciousOperationException when the host name is invalid or not trusted
1103
     */
1104
    public function getHost(): string
1105
    {
1106
        if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_X_FORWARDED_HOST)) {
1107
            $host = $host[0];
1108
        } elseif (!$host = $this->headers->get('HOST')) {
1109
            if (!$host = $this->server->get('SERVER_NAME')) {
1110
                $host = $this->server->get('SERVER_ADDR', '');
1111
            }
1112
        }
1113
 
1114
        // trim and remove port number from host
1115
        // host is lowercase as per RFC 952/2181
1116
        $host = strtolower(preg_replace('/:\d+$/', '', trim($host)));
1117
 
1118
        // as the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user)
1119
        // check that it does not contain forbidden characters (see RFC 952 and RFC 2181)
1120
        // use preg_replace() instead of preg_match() to prevent DoS attacks with long host names
1121
        if ($host && '' !== preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $host)) {
1122
            if (!$this->isHostValid) {
1123
                return '';
1124
            }
1125
            $this->isHostValid = false;
1126
 
1127
            throw new SuspiciousOperationException(sprintf('Invalid Host "%s".', $host));
1128
        }
1129
 
1130
        if (\count(self::$trustedHostPatterns) > 0) {
1131
            // to avoid host header injection attacks, you should provide a list of trusted host patterns
1132
 
1133
            if (\in_array($host, self::$trustedHosts)) {
1134
                return $host;
1135
            }
1136
 
1137
            foreach (self::$trustedHostPatterns as $pattern) {
1138
                if (preg_match($pattern, $host)) {
1139
                    self::$trustedHosts[] = $host;
1140
 
1141
                    return $host;
1142
                }
1143
            }
1144
 
1145
            if (!$this->isHostValid) {
1146
                return '';
1147
            }
1148
            $this->isHostValid = false;
1149
 
1150
            throw new SuspiciousOperationException(sprintf('Untrusted Host "%s".', $host));
1151
        }
1152
 
1153
        return $host;
1154
    }
1155
 
1156
    /**
1157
     * Sets the request method.
1158
     */
1159
    public function setMethod(string $method)
1160
    {
1161
        $this->method = null;
1162
        $this->server->set('REQUEST_METHOD', $method);
1163
    }
1164
 
1165
    /**
1166
     * Gets the request "intended" method.
1167
     *
1168
     * If the X-HTTP-Method-Override header is set, and if the method is a POST,
1169
     * then it is used to determine the "real" intended HTTP method.
1170
     *
1171
     * The _method request parameter can also be used to determine the HTTP method,
1172
     * but only if enableHttpMethodParameterOverride() has been called.
1173
     *
1174
     * The method is always an uppercased string.
1175
     *
1176
     * @see getRealMethod()
1177
     */
1178
    public function getMethod(): string
1179
    {
1180
        if (null !== $this->method) {
1181
            return $this->method;
1182
        }
1183
 
1184
        $this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
1185
 
1186
        if ('POST' !== $this->method) {
1187
            return $this->method;
1188
        }
1189
 
1190
        $method = $this->headers->get('X-HTTP-METHOD-OVERRIDE');
1191
 
1192
        if (!$method && self::$httpMethodParameterOverride) {
1193
            $method = $this->request->get('_method', $this->query->get('_method', 'POST'));
1194
        }
1195
 
1196
        if (!\is_string($method)) {
1197
            return $this->method;
1198
        }
1199
 
1200
        $method = strtoupper($method);
1201
 
1202
        if (\in_array($method, ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'PATCH', 'PURGE', 'TRACE'], true)) {
1203
            return $this->method = $method;
1204
        }
1205
 
1206
        if (!preg_match('/^[A-Z]++$/D', $method)) {
1207
            throw new SuspiciousOperationException(sprintf('Invalid method override "%s".', $method));
1208
        }
1209
 
1210
        return $this->method = $method;
1211
    }
1212
 
1213
    /**
1214
     * Gets the "real" request method.
1215
     *
1216
     * @see getMethod()
1217
     */
1218
    public function getRealMethod(): string
1219
    {
1220
        return strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
1221
    }
1222
 
1223
    /**
1224
     * Gets the mime type associated with the format.
1225
     */
1226
    public function getMimeType(string $format): ?string
1227
    {
1228
        if (null === static::$formats) {
1229
            static::initializeFormats();
1230
        }
1231
 
1232
        return isset(static::$formats[$format]) ? static::$formats[$format][0] : null;
1233
    }
1234
 
1235
    /**
1236
     * Gets the mime types associated with the format.
1237
     *
1238
     * @return string[]
1239
     */
1240
    public static function getMimeTypes(string $format): array
1241
    {
1242
        if (null === static::$formats) {
1243
            static::initializeFormats();
1244
        }
1245
 
1246
        return static::$formats[$format] ?? [];
1247
    }
1248
 
1249
    /**
1250
     * Gets the format associated with the mime type.
1251
     */
1252
    public function getFormat(?string $mimeType): ?string
1253
    {
1254
        $canonicalMimeType = null;
1255
        if ($mimeType && false !== $pos = strpos($mimeType, ';')) {
1256
            $canonicalMimeType = trim(substr($mimeType, 0, $pos));
1257
        }
1258
 
1259
        if (null === static::$formats) {
1260
            static::initializeFormats();
1261
        }
1262
 
1263
        foreach (static::$formats as $format => $mimeTypes) {
1264
            if (\in_array($mimeType, (array) $mimeTypes)) {
1265
                return $format;
1266
            }
1267
            if (null !== $canonicalMimeType && \in_array($canonicalMimeType, (array) $mimeTypes)) {
1268
                return $format;
1269
            }
1270
        }
1271
 
1272
        return null;
1273
    }
1274
 
1275
    /**
1276
     * Associates a format with mime types.
1277
     *
1278
     * @param string|string[] $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type)
1279
     */
1280
    public function setFormat(?string $format, string|array $mimeTypes)
1281
    {
1282
        if (null === static::$formats) {
1283
            static::initializeFormats();
1284
        }
1285
 
1286
        static::$formats[$format] = \is_array($mimeTypes) ? $mimeTypes : [$mimeTypes];
1287
    }
1288
 
1289
    /**
1290
     * Gets the request format.
1291
     *
1292
     * Here is the process to determine the format:
1293
     *
1294
     *  * format defined by the user (with setRequestFormat())
1295
     *  * _format request attribute
1296
     *  * $default
1297
     *
1298
     * @see getPreferredFormat
1299
     */
1300
    public function getRequestFormat(?string $default = 'html'): ?string
1301
    {
1302
        $this->format ??= $this->attributes->get('_format');
1303
 
1304
        return $this->format ?? $default;
1305
    }
1306
 
1307
    /**
1308
     * Sets the request format.
1309
     */
1310
    public function setRequestFormat(?string $format)
1311
    {
1312
        $this->format = $format;
1313
    }
1314
 
1315
    /**
1316
     * Gets the usual name of the format associated with the request's media type (provided in the Content-Type header).
1317
     *
1318
     * @deprecated since Symfony 6.2, use getContentTypeFormat() instead
1319
     */
1320
    public function getContentType(): ?string
1321
    {
1322
        trigger_deprecation('symfony/http-foundation', '6.2', 'The "%s()" method is deprecated, use "getContentTypeFormat()" instead.', __METHOD__);
1323
 
1324
        return $this->getContentTypeFormat();
1325
    }
1326
 
1327
    /**
1328
     * Gets the usual name of the format associated with the request's media type (provided in the Content-Type header).
1329
     *
1330
     * @see Request::$formats
1331
     */
1332
    public function getContentTypeFormat(): ?string
1333
    {
1334
        return $this->getFormat($this->headers->get('CONTENT_TYPE', ''));
1335
    }
1336
 
1337
    /**
1338
     * Sets the default locale.
1339
     */
1340
    public function setDefaultLocale(string $locale)
1341
    {
1342
        $this->defaultLocale = $locale;
1343
 
1344
        if (null === $this->locale) {
1345
            $this->setPhpDefaultLocale($locale);
1346
        }
1347
    }
1348
 
1349
    /**
1350
     * Get the default locale.
1351
     */
1352
    public function getDefaultLocale(): string
1353
    {
1354
        return $this->defaultLocale;
1355
    }
1356
 
1357
    /**
1358
     * Sets the locale.
1359
     */
1360
    public function setLocale(string $locale)
1361
    {
1362
        $this->setPhpDefaultLocale($this->locale = $locale);
1363
    }
1364
 
1365
    /**
1366
     * Get the locale.
1367
     */
1368
    public function getLocale(): string
1369
    {
688 lars 1370
        return $this->locale ?? $this->defaultLocale;
148 lars 1371
    }
1372
 
1373
    /**
1374
     * Checks if the request method is of specified type.
1375
     *
1376
     * @param string $method Uppercase request method (GET, POST etc)
1377
     */
1378
    public function isMethod(string $method): bool
1379
    {
1380
        return $this->getMethod() === strtoupper($method);
1381
    }
1382
 
1383
    /**
1384
     * Checks whether or not the method is safe.
1385
     *
1386
     * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1387
     */
1388
    public function isMethodSafe(): bool
1389
    {
1390
        return \in_array($this->getMethod(), ['GET', 'HEAD', 'OPTIONS', 'TRACE']);
1391
    }
1392
 
1393
    /**
1394
     * Checks whether or not the method is idempotent.
1395
     */
1396
    public function isMethodIdempotent(): bool
1397
    {
1398
        return \in_array($this->getMethod(), ['HEAD', 'GET', 'PUT', 'DELETE', 'TRACE', 'OPTIONS', 'PURGE']);
1399
    }
1400
 
1401
    /**
1402
     * Checks whether the method is cacheable or not.
1403
     *
1404
     * @see https://tools.ietf.org/html/rfc7231#section-4.2.3
1405
     */
1406
    public function isMethodCacheable(): bool
1407
    {
1408
        return \in_array($this->getMethod(), ['GET', 'HEAD']);
1409
    }
1410
 
1411
    /**
1412
     * Returns the protocol version.
1413
     *
1414
     * If the application is behind a proxy, the protocol version used in the
1415
     * requests between the client and the proxy and between the proxy and the
1416
     * server might be different. This returns the former (from the "Via" header)
1417
     * if the proxy is trusted (see "setTrustedProxies()"), otherwise it returns
1418
     * the latter (from the "SERVER_PROTOCOL" server parameter).
1419
     */
1420
    public function getProtocolVersion(): ?string
1421
    {
1422
        if ($this->isFromTrustedProxy()) {
1423
            preg_match('~^(HTTP/)?([1-9]\.[0-9]) ~', $this->headers->get('Via') ?? '', $matches);
1424
 
1425
            if ($matches) {
1426
                return 'HTTP/'.$matches[2];
1427
            }
1428
        }
1429
 
1430
        return $this->server->get('SERVER_PROTOCOL');
1431
    }
1432
 
1433
    /**
1434
     * Returns the request body content.
1435
     *
1436
     * @param bool $asResource If true, a resource will be returned
1437
     *
1438
     * @return string|resource
688 lars 1439
     *
148 lars 1440
     * @psalm-return ($asResource is true ? resource : string)
1441
     */
1442
    public function getContent(bool $asResource = false)
1443
    {
1444
        $currentContentIsResource = \is_resource($this->content);
1445
 
1446
        if (true === $asResource) {
1447
            if ($currentContentIsResource) {
1448
                rewind($this->content);
1449
 
1450
                return $this->content;
1451
            }
1452
 
1453
            // Content passed in parameter (test)
1454
            if (\is_string($this->content)) {
1455
                $resource = fopen('php://temp', 'r+');
1456
                fwrite($resource, $this->content);
1457
                rewind($resource);
1458
 
1459
                return $resource;
1460
            }
1461
 
1462
            $this->content = false;
1463
 
1464
            return fopen('php://input', 'r');
1465
        }
1466
 
1467
        if ($currentContentIsResource) {
1468
            rewind($this->content);
1469
 
1470
            return stream_get_contents($this->content);
1471
        }
1472
 
1473
        if (null === $this->content || false === $this->content) {
1474
            $this->content = file_get_contents('php://input');
1475
        }
1476
 
1477
        return $this->content;
1478
    }
1479
 
1480
    /**
1481
     * Gets the request body decoded as array, typically from a JSON payload.
1482
     *
1483
     * @throws JsonException When the body cannot be decoded to an array
1484
     */
1485
    public function toArray(): array
1486
    {
1487
        if ('' === $content = $this->getContent()) {
1488
            throw new JsonException('Request body is empty.');
1489
        }
1490
 
1491
        try {
1492
            $content = json_decode($content, true, 512, \JSON_BIGINT_AS_STRING | \JSON_THROW_ON_ERROR);
1493
        } catch (\JsonException $e) {
1494
            throw new JsonException('Could not decode request body.', $e->getCode(), $e);
1495
        }
1496
 
1497
        if (!\is_array($content)) {
1498
            throw new JsonException(sprintf('JSON content was expected to decode to an array, "%s" returned.', get_debug_type($content)));
1499
        }
1500
 
1501
        return $content;
1502
    }
1503
 
1504
    /**
1505
     * Gets the Etags.
1506
     */
1507
    public function getETags(): array
1508
    {
1509
        return preg_split('/\s*,\s*/', $this->headers->get('If-None-Match', ''), -1, \PREG_SPLIT_NO_EMPTY);
1510
    }
1511
 
1512
    public function isNoCache(): bool
1513
    {
1514
        return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
1515
    }
1516
 
1517
    /**
1518
     * Gets the preferred format for the response by inspecting, in the following order:
1519
     *   * the request format set using setRequestFormat;
1520
     *   * the values of the Accept HTTP header.
1521
     *
1522
     * Note that if you use this method, you should send the "Vary: Accept" header
1523
     * in the response to prevent any issues with intermediary HTTP caches.
1524
     */
1525
    public function getPreferredFormat(?string $default = 'html'): ?string
1526
    {
1527
        if (null !== $this->preferredFormat || null !== $this->preferredFormat = $this->getRequestFormat(null)) {
1528
            return $this->preferredFormat;
1529
        }
1530
 
1531
        foreach ($this->getAcceptableContentTypes() as $mimeType) {
1532
            if ($this->preferredFormat = $this->getFormat($mimeType)) {
1533
                return $this->preferredFormat;
1534
            }
1535
        }
1536
 
1537
        return $default;
1538
    }
1539
 
1540
    /**
1541
     * Returns the preferred language.
1542
     *
1543
     * @param string[] $locales An array of ordered available locales
1544
     */
1545
    public function getPreferredLanguage(array $locales = null): ?string
1546
    {
1547
        $preferredLanguages = $this->getLanguages();
1548
 
1549
        if (empty($locales)) {
1550
            return $preferredLanguages[0] ?? null;
1551
        }
1552
 
1553
        if (!$preferredLanguages) {
1554
            return $locales[0];
1555
        }
1556
 
1557
        $extendedPreferredLanguages = [];
1558
        foreach ($preferredLanguages as $language) {
1559
            $extendedPreferredLanguages[] = $language;
1560
            if (false !== $position = strpos($language, '_')) {
1561
                $superLanguage = substr($language, 0, $position);
1562
                if (!\in_array($superLanguage, $preferredLanguages)) {
1563
                    $extendedPreferredLanguages[] = $superLanguage;
1564
                }
1565
            }
1566
        }
1567
 
1568
        $preferredLanguages = array_values(array_intersect($extendedPreferredLanguages, $locales));
1569
 
1570
        return $preferredLanguages[0] ?? $locales[0];
1571
    }
1572
 
1573
    /**
1574
     * Gets a list of languages acceptable by the client browser ordered in the user browser preferences.
1575
     *
1576
     * @return string[]
1577
     */
1578
    public function getLanguages(): array
1579
    {
1580
        if (null !== $this->languages) {
1581
            return $this->languages;
1582
        }
1583
 
1584
        $languages = AcceptHeader::fromString($this->headers->get('Accept-Language'))->all();
1585
        $this->languages = [];
1586
        foreach ($languages as $acceptHeaderItem) {
1587
            $lang = $acceptHeaderItem->getValue();
1588
            if (str_contains($lang, '-')) {
1589
                $codes = explode('-', $lang);
1590
                if ('i' === $codes[0]) {
1591
                    // Language not listed in ISO 639 that are not variants
1592
                    // of any listed language, which can be registered with the
1593
                    // i-prefix, such as i-cherokee
1594
                    if (\count($codes) > 1) {
1595
                        $lang = $codes[1];
1596
                    }
1597
                } else {
1598
                    for ($i = 0, $max = \count($codes); $i < $max; ++$i) {
1599
                        if (0 === $i) {
1600
                            $lang = strtolower($codes[0]);
1601
                        } else {
1602
                            $lang .= '_'.strtoupper($codes[$i]);
1603
                        }
1604
                    }
1605
                }
1606
            }
1607
 
1608
            $this->languages[] = $lang;
1609
        }
1610
 
1611
        return $this->languages;
1612
    }
1613
 
1614
    /**
1615
     * Gets a list of charsets acceptable by the client browser in preferable order.
1616
     *
1617
     * @return string[]
1618
     */
1619
    public function getCharsets(): array
1620
    {
1621
        if (null !== $this->charsets) {
1622
            return $this->charsets;
1623
        }
1624
 
1625
        return $this->charsets = array_map('strval', array_keys(AcceptHeader::fromString($this->headers->get('Accept-Charset'))->all()));
1626
    }
1627
 
1628
    /**
1629
     * Gets a list of encodings acceptable by the client browser in preferable order.
1630
     *
1631
     * @return string[]
1632
     */
1633
    public function getEncodings(): array
1634
    {
1635
        if (null !== $this->encodings) {
1636
            return $this->encodings;
1637
        }
1638
 
1639
        return $this->encodings = array_map('strval', array_keys(AcceptHeader::fromString($this->headers->get('Accept-Encoding'))->all()));
1640
    }
1641
 
1642
    /**
1643
     * Gets a list of content types acceptable by the client browser in preferable order.
1644
     *
1645
     * @return string[]
1646
     */
1647
    public function getAcceptableContentTypes(): array
1648
    {
1649
        if (null !== $this->acceptableContentTypes) {
1650
            return $this->acceptableContentTypes;
1651
        }
1652
 
1653
        return $this->acceptableContentTypes = array_map('strval', array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all()));
1654
    }
1655
 
1656
    /**
1657
     * Returns true if the request is an XMLHttpRequest.
1658
     *
1659
     * It works if your JavaScript library sets an X-Requested-With HTTP header.
1660
     * It is known to work with common JavaScript frameworks:
1661
     *
1662
     * @see https://wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
1663
     */
1664
    public function isXmlHttpRequest(): bool
1665
    {
1666
        return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
1667
    }
1668
 
1669
    /**
1670
     * Checks whether the client browser prefers safe content or not according to RFC8674.
1671
     *
1672
     * @see https://tools.ietf.org/html/rfc8674
1673
     */
1674
    public function preferSafeContent(): bool
1675
    {
1676
        if (isset($this->isSafeContentPreferred)) {
1677
            return $this->isSafeContentPreferred;
1678
        }
1679
 
1680
        if (!$this->isSecure()) {
1681
            // see https://tools.ietf.org/html/rfc8674#section-3
1682
            return $this->isSafeContentPreferred = false;
1683
        }
1684
 
1685
        return $this->isSafeContentPreferred = AcceptHeader::fromString($this->headers->get('Prefer'))->has('safe');
1686
    }
1687
 
1688
    /*
1689
     * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24)
1690
     *
1691
     * Code subject to the new BSD license (https://framework.zend.com/license).
1692
     *
1693
     * Copyright (c) 2005-2010 Zend Technologies USA Inc. (https://www.zend.com/)
1694
     */
1695
 
1696
    protected function prepareRequestUri()
1697
    {
1698
        $requestUri = '';
1699
 
1700
        if ('1' == $this->server->get('IIS_WasUrlRewritten') && '' != $this->server->get('UNENCODED_URL')) {
1701
            // IIS7 with URL Rewrite: make sure we get the unencoded URL (double slash problem)
1702
            $requestUri = $this->server->get('UNENCODED_URL');
1703
            $this->server->remove('UNENCODED_URL');
1704
            $this->server->remove('IIS_WasUrlRewritten');
1705
        } elseif ($this->server->has('REQUEST_URI')) {
1706
            $requestUri = $this->server->get('REQUEST_URI');
1707
 
1708
            if ('' !== $requestUri && '/' === $requestUri[0]) {
1709
                // To only use path and query remove the fragment.
1710
                if (false !== $pos = strpos($requestUri, '#')) {
1711
                    $requestUri = substr($requestUri, 0, $pos);
1712
                }
1713
            } else {
1714
                // HTTP proxy reqs setup request URI with scheme and host [and port] + the URL path,
1715
                // only use URL path.
1716
                $uriComponents = parse_url($requestUri);
1717
 
1718
                if (isset($uriComponents['path'])) {
1719
                    $requestUri = $uriComponents['path'];
1720
                }
1721
 
1722
                if (isset($uriComponents['query'])) {
1723
                    $requestUri .= '?'.$uriComponents['query'];
1724
                }
1725
            }
1726
        } elseif ($this->server->has('ORIG_PATH_INFO')) {
1727
            // IIS 5.0, PHP as CGI
1728
            $requestUri = $this->server->get('ORIG_PATH_INFO');
1729
            if ('' != $this->server->get('QUERY_STRING')) {
1730
                $requestUri .= '?'.$this->server->get('QUERY_STRING');
1731
            }
1732
            $this->server->remove('ORIG_PATH_INFO');
1733
        }
1734
 
1735
        // normalize the request URI to ease creating sub-requests from this request
1736
        $this->server->set('REQUEST_URI', $requestUri);
1737
 
1738
        return $requestUri;
1739
    }
1740
 
1741
    /**
1742
     * Prepares the base URL.
1743
     */
1744
    protected function prepareBaseUrl(): string
1745
    {
1746
        $filename = basename($this->server->get('SCRIPT_FILENAME', ''));
1747
 
1748
        if (basename($this->server->get('SCRIPT_NAME', '')) === $filename) {
1749
            $baseUrl = $this->server->get('SCRIPT_NAME');
1750
        } elseif (basename($this->server->get('PHP_SELF', '')) === $filename) {
1751
            $baseUrl = $this->server->get('PHP_SELF');
1752
        } elseif (basename($this->server->get('ORIG_SCRIPT_NAME', '')) === $filename) {
1753
            $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility
1754
        } else {
1755
            // Backtrack up the script_filename to find the portion matching
1756
            // php_self
1757
            $path = $this->server->get('PHP_SELF', '');
1758
            $file = $this->server->get('SCRIPT_FILENAME', '');
1759
            $segs = explode('/', trim($file, '/'));
1760
            $segs = array_reverse($segs);
1761
            $index = 0;
1762
            $last = \count($segs);
1763
            $baseUrl = '';
1764
            do {
1765
                $seg = $segs[$index];
1766
                $baseUrl = '/'.$seg.$baseUrl;
1767
                ++$index;
1768
            } while ($last > $index && (false !== $pos = strpos($path, $baseUrl)) && 0 != $pos);
1769
        }
1770
 
1771
        // Does the baseUrl have anything in common with the request_uri?
1772
        $requestUri = $this->getRequestUri();
1773
        if ('' !== $requestUri && '/' !== $requestUri[0]) {
1774
            $requestUri = '/'.$requestUri;
1775
        }
1776
 
1777
        if ($baseUrl && null !== $prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl)) {
1778
            // full $baseUrl matches
1779
            return $prefix;
1780
        }
1781
 
1782
        if ($baseUrl && null !== $prefix = $this->getUrlencodedPrefix($requestUri, rtrim(\dirname($baseUrl), '/'.\DIRECTORY_SEPARATOR).'/')) {
1783
            // directory portion of $baseUrl matches
1784
            return rtrim($prefix, '/'.\DIRECTORY_SEPARATOR);
1785
        }
1786
 
1787
        $truncatedRequestUri = $requestUri;
1788
        if (false !== $pos = strpos($requestUri, '?')) {
1789
            $truncatedRequestUri = substr($requestUri, 0, $pos);
1790
        }
1791
 
1792
        $basename = basename($baseUrl ?? '');
1793
        if (empty($basename) || !strpos(rawurldecode($truncatedRequestUri), $basename)) {
1794
            // no match whatsoever; set it blank
1795
            return '';
1796
        }
1797
 
1798
        // If using mod_rewrite or ISAPI_Rewrite strip the script filename
1799
        // out of baseUrl. $pos !== 0 makes sure it is not matching a value
1800
        // from PATH_INFO or QUERY_STRING
1801
        if (\strlen($requestUri) >= \strlen($baseUrl) && (false !== $pos = strpos($requestUri, $baseUrl)) && 0 !== $pos) {
1802
            $baseUrl = substr($requestUri, 0, $pos + \strlen($baseUrl));
1803
        }
1804
 
1805
        return rtrim($baseUrl, '/'.\DIRECTORY_SEPARATOR);
1806
    }
1807
 
1808
    /**
1809
     * Prepares the base path.
1810
     */
1811
    protected function prepareBasePath(): string
1812
    {
1813
        $baseUrl = $this->getBaseUrl();
1814
        if (empty($baseUrl)) {
1815
            return '';
1816
        }
1817
 
1818
        $filename = basename($this->server->get('SCRIPT_FILENAME'));
1819
        if (basename($baseUrl) === $filename) {
1820
            $basePath = \dirname($baseUrl);
1821
        } else {
1822
            $basePath = $baseUrl;
1823
        }
1824
 
1825
        if ('\\' === \DIRECTORY_SEPARATOR) {
1826
            $basePath = str_replace('\\', '/', $basePath);
1827
        }
1828
 
1829
        return rtrim($basePath, '/');
1830
    }
1831
 
1832
    /**
1833
     * Prepares the path info.
1834
     */
1835
    protected function preparePathInfo(): string
1836
    {
1837
        if (null === ($requestUri = $this->getRequestUri())) {
1838
            return '/';
1839
        }
1840
 
1841
        // Remove the query string from REQUEST_URI
1842
        if (false !== $pos = strpos($requestUri, '?')) {
1843
            $requestUri = substr($requestUri, 0, $pos);
1844
        }
1845
        if ('' !== $requestUri && '/' !== $requestUri[0]) {
1846
            $requestUri = '/'.$requestUri;
1847
        }
1848
 
1849
        if (null === ($baseUrl = $this->getBaseUrlReal())) {
1850
            return $requestUri;
1851
        }
1852
 
1853
        $pathInfo = substr($requestUri, \strlen($baseUrl));
1854
        if (false === $pathInfo || '' === $pathInfo) {
1855
            // If substr() returns false then PATH_INFO is set to an empty string
1856
            return '/';
1857
        }
1858
 
1859
        return $pathInfo;
1860
    }
1861
 
1862
    /**
1863
     * Initializes HTTP request formats.
1864
     */
1865
    protected static function initializeFormats()
1866
    {
1867
        static::$formats = [
1868
            'html' => ['text/html', 'application/xhtml+xml'],
1869
            'txt' => ['text/plain'],
1870
            'js' => ['application/javascript', 'application/x-javascript', 'text/javascript'],
1871
            'css' => ['text/css'],
1872
            'json' => ['application/json', 'application/x-json'],
1873
            'jsonld' => ['application/ld+json'],
1874
            'xml' => ['text/xml', 'application/xml', 'application/x-xml'],
1875
            'rdf' => ['application/rdf+xml'],
1876
            'atom' => ['application/atom+xml'],
1877
            'rss' => ['application/rss+xml'],
1878
            'form' => ['application/x-www-form-urlencoded', 'multipart/form-data'],
1879
        ];
1880
    }
1881
 
1882
    private function setPhpDefaultLocale(string $locale): void
1883
    {
1884
        // if either the class Locale doesn't exist, or an exception is thrown when
1885
        // setting the default locale, the intl module is not installed, and
1886
        // the call can be ignored:
1887
        try {
1888
            if (class_exists(\Locale::class, false)) {
1889
                \Locale::setDefault($locale);
1890
            }
1891
        } catch (\Exception) {
1892
        }
1893
    }
1894
 
1895
    /**
1896
     * Returns the prefix as encoded in the string when the string starts with
1897
     * the given prefix, null otherwise.
1898
     */
1899
    private function getUrlencodedPrefix(string $string, string $prefix): ?string
1900
    {
1901
        if (!str_starts_with(rawurldecode($string), $prefix)) {
1902
            return null;
1903
        }
1904
 
1905
        $len = \strlen($prefix);
1906
 
1907
        if (preg_match(sprintf('#^(%%[[:xdigit:]]{2}|.){%d}#', $len), $string, $match)) {
1908
            return $match[0];
1909
        }
1910
 
1911
        return null;
1912
    }
1913
 
1914
    private static function createRequestFromFactory(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null): static
1915
    {
1916
        if (self::$requestFactory) {
1917
            $request = (self::$requestFactory)($query, $request, $attributes, $cookies, $files, $server, $content);
1918
 
1919
            if (!$request instanceof self) {
1920
                throw new \LogicException('The Request factory must return an instance of Symfony\Component\HttpFoundation\Request.');
1921
            }
1922
 
1923
            return $request;
1924
        }
1925
 
1926
        return new static($query, $request, $attributes, $cookies, $files, $server, $content);
1927
    }
1928
 
1929
    /**
1930
     * Indicates whether this request originated from a trusted proxy.
1931
     *
1932
     * This can be useful to determine whether or not to trust the
1933
     * contents of a proxy-specific header.
1934
     */
1935
    public function isFromTrustedProxy(): bool
1936
    {
1937
        return self::$trustedProxies && IpUtils::checkIp($this->server->get('REMOTE_ADDR', ''), self::$trustedProxies);
1938
    }
1939
 
1940
    private function getTrustedValues(int $type, string $ip = null): array
1941
    {
1942
        $clientValues = [];
1943
        $forwardedValues = [];
1944
 
1945
        if ((self::$trustedHeaderSet & $type) && $this->headers->has(self::TRUSTED_HEADERS[$type])) {
1946
            foreach (explode(',', $this->headers->get(self::TRUSTED_HEADERS[$type])) as $v) {
1947
                $clientValues[] = (self::HEADER_X_FORWARDED_PORT === $type ? '0.0.0.0:' : '').trim($v);
1948
            }
1949
        }
1950
 
1951
        if ((self::$trustedHeaderSet & self::HEADER_FORWARDED) && (isset(self::FORWARDED_PARAMS[$type])) && $this->headers->has(self::TRUSTED_HEADERS[self::HEADER_FORWARDED])) {
1952
            $forwarded = $this->headers->get(self::TRUSTED_HEADERS[self::HEADER_FORWARDED]);
1953
            $parts = HeaderUtils::split($forwarded, ',;=');
1954
            $forwardedValues = [];
1955
            $param = self::FORWARDED_PARAMS[$type];
1956
            foreach ($parts as $subParts) {
1957
                if (null === $v = HeaderUtils::combine($subParts)[$param] ?? null) {
1958
                    continue;
1959
                }
1960
                if (self::HEADER_X_FORWARDED_PORT === $type) {
1961
                    if (str_ends_with($v, ']') || false === $v = strrchr($v, ':')) {
1962
                        $v = $this->isSecure() ? ':443' : ':80';
1963
                    }
1964
                    $v = '0.0.0.0'.$v;
1965
                }
1966
                $forwardedValues[] = $v;
1967
            }
1968
        }
1969
 
1970
        if (null !== $ip) {
1971
            $clientValues = $this->normalizeAndFilterClientIps($clientValues, $ip);
1972
            $forwardedValues = $this->normalizeAndFilterClientIps($forwardedValues, $ip);
1973
        }
1974
 
1975
        if ($forwardedValues === $clientValues || !$clientValues) {
1976
            return $forwardedValues;
1977
        }
1978
 
1979
        if (!$forwardedValues) {
1980
            return $clientValues;
1981
        }
1982
 
1983
        if (!$this->isForwardedValid) {
1984
            return null !== $ip ? ['0.0.0.0', $ip] : [];
1985
        }
1986
        $this->isForwardedValid = false;
1987
 
1988
        throw new ConflictingHeadersException(sprintf('The request has both a trusted "%s" header and a trusted "%s" header, conflicting with each other. You should either configure your proxy to remove one of them, or configure your project to distrust the offending one.', self::TRUSTED_HEADERS[self::HEADER_FORWARDED], self::TRUSTED_HEADERS[$type]));
1989
    }
1990
 
1991
    private function normalizeAndFilterClientIps(array $clientIps, string $ip): array
1992
    {
1993
        if (!$clientIps) {
1994
            return [];
1995
        }
1996
        $clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from
1997
        $firstTrustedIp = null;
1998
 
1999
        foreach ($clientIps as $key => $clientIp) {
2000
            if (strpos($clientIp, '.')) {
2001
                // Strip :port from IPv4 addresses. This is allowed in Forwarded
2002
                // and may occur in X-Forwarded-For.
2003
                $i = strpos($clientIp, ':');
2004
                if ($i) {
2005
                    $clientIps[$key] = $clientIp = substr($clientIp, 0, $i);
2006
                }
2007
            } elseif (str_starts_with($clientIp, '[')) {
2008
                // Strip brackets and :port from IPv6 addresses.
2009
                $i = strpos($clientIp, ']', 1);
2010
                $clientIps[$key] = $clientIp = substr($clientIp, 1, $i - 1);
2011
            }
2012
 
2013
            if (!filter_var($clientIp, \FILTER_VALIDATE_IP)) {
2014
                unset($clientIps[$key]);
2015
 
2016
                continue;
2017
            }
2018
 
2019
            if (IpUtils::checkIp($clientIp, self::$trustedProxies)) {
2020
                unset($clientIps[$key]);
2021
 
2022
                // Fallback to this when the client IP falls into the range of trusted proxies
2023
                $firstTrustedIp ??= $clientIp;
2024
            }
2025
        }
2026
 
2027
        // Now the IP chain contains only untrusted proxies and the client IP
2028
        return $clientIps ? array_reverse($clientIps) : [$firstTrustedIp];
2029
    }
2030
}