-
Notifications
You must be signed in to change notification settings - Fork 767
/
class.request.php
2173 lines (1925 loc) · 64.2 KB
/
class.request.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Incoming request parser.
*
* @author Todd Burry <todd@vanillaforums.com>
* @author Tim Gunter <tim@vanillaforums.com>
* @copyright 2009-2019 Vanilla Forums Inc.
* @license GPL-2.0-only
* @package Core
* @since 2.0
*/
use Garden\MetaTrait;
use Garden\Web\RequestInterface;
use League\Uri\Http;
use Psr\Http\Message\UriInterface;
use Vanilla\Contracts\Web\RequestModifierInterface;
use Vanilla\UploadedFile;
/**
* Represents a Request to the application, typically from the browser but potentially generated internally, in a format
* that can be accessed directly by the Dispatcher.
*
* @method string requestURI($uri = null) Get/Set the Request URI (REQUEST_URI).
* @method string requestScript($scriptName = null) Get/Set the Request ScriptName (SCRIPT_NAME).
* @method string requestHost($uri = null) Get/Set the Request Host (HTTP_HOST).
* @method string requestFolder($folder = null) Get/Set the Request script's Folder.
* @method string requestAddress($ip = null) Get/Set the Request IP address (first existing of HTTP_X_ORIGINALLY_FORWARDED_FOR,
* HTTP_X_CLUSTER_CLIENT_IP, HTTP_CLIENT_IP, HTTP_X_FORWARDED_FOR, REMOTE_ADDR).
*/
class Gdn_Request implements RequestInterface
{
use MetaTrait;
/** Superglobal source. */
const INPUT_CUSTOM = "custom";
/** Superglobal source. */
const INPUT_ENV = "env";
/** Superglobal source. */
const INPUT_FILES = "files";
/** Superglobal source. */
const INPUT_GET = "get";
/** Superglobal source. */
const INPUT_POST = "post";
/** Superglobal source. */
const INPUT_SERVER = "server";
/** Superglobal source. */
const INPUT_COOKIES = "cookies";
/** HTTP request method. */
const METHOD_HEAD = "HEAD";
/** HTTP request method. */
const METHOD_GET = "GET";
/** HTTP request method. */
const METHOD_POST = "POST";
/** HTTP request method. */
const METHOD_PUT = "PUT";
/** HTTP request method. */
const METHOD_PATCH = "PATCH";
/** HTTP request method. */
const METHOD_DELETE = "DELETE";
/** HTTP request method. */
const METHOD_OPTIONS = "OPTIONS";
/** Special cases in $_SERVER that are also considered headers. */
const SPECIAL_HEADERS = [
"CONTENT_TYPE",
"CONTENT_LENGTH",
"PHP_AUTH_USER",
"PHP_AUTH_PW",
"PHP_AUTH_DIGEST",
"AUTH_TYPE",
];
/** @var bool Whether or not _ParseRequest has been called yet. */
protected $_HaveParsedRequest = false;
/** @var array Raw environment variables, unparsed. */
protected $_Environment;
/** @var array Resolved/parsed request information. */
protected $_ParsedRequest;
/** @var bool */
protected $_Parsing = false;
/** @var array Request data/parameters, either from superglobals or from a custom array of key/value pairs. */
protected $_RequestArguments;
/** @var array Cache of env elements to avoid repeatedly casening strings in loops. */
private $envElementCache = [];
/**
* Instantiate a new instance of the {@link Gdn_Request} class.
*/
public function __construct()
{
$this->reset();
}
/**
* Modify a request using some predefined modifier.
*
* @param RequestModifierInterface $modifier
*/
public function applyRequestModifier(RequestModifierInterface $modifier): void
{
$modifier->modifyRequest($this);
}
/**
* Gets/Sets the relative path to the asset include path.
*
* The asset root represents the folder that static assets are served from.
*
* @param string? $assetRoot An asset root to set.
* @return string Returns the current asset root.
*
* @deprecated 2.8 Use the explicit asset functions instead.
* @codeCoverageIgnore
*/
public function assetRoot($assetRoot = null)
{
if ($assetRoot !== null) {
deprecated(__FUNCTION__, "setAssetRoot");
$this->setAssetRoot($assetRoot);
return $assetRoot;
} else {
deprecated(__FUNCTION__, "getAssetRoot");
$result = $this->getAssetRoot();
}
return $result;
}
/**
* @inheritdoc
*/
public function getAssetRoot()
{
return $this->_parsedRequestElement("AssetRoot");
}
/**
* @inheritdoc
*/
public function setAssetRoot(string $assetRoot)
{
$this->_parsedRequestElement("AssetRoot", rtrim("/" . trim($assetRoot, "/"), "/"));
return $this;
}
/**
* Generic chainable object creation method.
*
* This creates a new Gdn_Request object, loaded with the current Environment $_SERVER and $_ENV superglobal imports, such
* as REQUEST_URI, SCRIPT_NAME, etc. The intended usage is for additional setter methods to be chained
* onto this call in order to fully set up the object.
*
* @flow chain
* @return Gdn_Request
*/
public static function create()
{
return new Gdn_Request();
}
/**
* Gets/Sets the domain from the current url. e.g. "http://localhost" in
* "http://localhost/this/that/garden/index.php?/controller/action/"
*
* @param string|null $domain Optional value to set
* @return string | null
* @deprecated Use Gdn_Request::getHost() and Gdn_Request::setHost() instead.
*/
public function domain($domain = null)
{
return $this->_parsedRequestElement("Domain", $domain);
}
/**
* Accessor method for unparsed request environment data, such as the REQUEST_URI, SCRIPT_NAME,
* HTTP_HOST and REQUEST_METHOD keys in $_SERVER.
*
* A second argument can be supplied, which causes the value of the specified key to be changed
* to that of the second parameter itself.
*
* Currently recognized keys (and their relation to $_SERVER) are:
* - URI -> REQUEST_URI
* - SCRIPT -> SCRIPT_NAME
* - HOST -> HTTP_HOST
* - METHOD -> REQUEST_METHOD
* - FOLDER -> none. this is extracted from SCRIPT_NAME and only available after _ParseRequest()
* - SCHEME -> none. this is derived from 'HTTPS' and 'X-Forwarded-Proto'
* - ADDRESS -> first existing of HTTP_X_ORIGINALLY_FORWARDED_FOR, HTTP_X_CLUSTER_CLIENT_IP,
* HTTP_CLIENT_IP, HTTP_X_FORWARDED_FOR, REMOTE_ADDR
*
* @param string $key Key to retrieve or set.
* @param string $value Value of $Key key to set.
* @param bool $reparse Whether or not to mark the request for reparsing.
* @return string|null
*/
protected function _environmentElement($key, $value = null, $reparse = true)
{
if ($value === null && array_key_exists($key, $this->envElementCache)) {
return $this->envElementCache[$key];
}
$rawKey = $key;
$key = strtoupper($key);
if ($value !== null) {
if ($reparse) {
$this->_HaveParsedRequest = false;
}
switch ($key) {
case "URI":
// Simulate REQUEST_URI decoding.
$value = !is_null($value) ? rawurldecode($value) : $value;
break;
case "SCRIPT":
$value = !is_null($value) ? trim($value, "/") : $value;
break;
case "HOST":
$hostParts = explode(":", $value);
$value = array_shift($hostParts);
break;
case "METHOD":
$value = strtoupper($value);
break;
case "SCHEME":
case "FOLDER":
case "ADDRESS":
default:
// Do nothing special for these
break;
}
$this->envElementCache[$rawKey] = $value;
$this->_Environment[$key] = $value;
}
$result = $this->_Environment[$key] ?? null;
$this->envElementCache[$rawKey] = $result;
return $result;
}
/**
* Convenience method for accessing unparsed environment data via request(ELEMENT) method calls.
*
* @param string $method
* @param array $args
* @return string
*/
public function __call($method, $args)
{
$matches = [];
if (preg_match('/^(Request)(.*)$/i', $method, $matches)) {
$passedArg = is_array($args) && sizeof($args) ? $args[0] : null;
return $this->_environmentElement(strtoupper($matches[2]), $passedArg);
} else {
trigger_error("Call to unknown method 'Gdn_Request->{$method}'", E_USER_ERROR);
}
}
/**
* This method allows requests to export their internal data.
*
* Mostly used in conjunction with fromImport()
*
* @param string $export Data group to export.
* @return mixed
*/
public function export($export)
{
switch ($export) {
case "Environment":
return $this->_Environment;
case "Arguments":
return $this->_RequestArguments;
case "Parsed":
return $this->_ParsedRequest;
default:
return null;
}
}
/**
* Gets/Sets the optional filename (ContentDisposition) of the output.
*
* As with the case above (OutputFormat), this value depends heavily on there being a filename
* at the end of the URI. In the example above, filename() would return 'cashflow2009.pdf'.
*
* @param string|null $filename Optional Filename to set.
* @return string
*/
public function filename($filename = null)
{
return $this->_parsedRequestElement("Filename", $filename);
}
/**
* Convert a header key from HTTP_HEADER_NAME format to Header-Name.
*
* @param string $key A header key.
* @return string The formatted header key.
*/
private function formatHeaderKey($key)
{
$key = $this->headerKey($key);
if (substr($key, 0, 5) == "HTTP_") {
$key = substr($key, 5);
}
$key = strtolower($key);
$key = str_replace("_", "-", $key);
$key = preg_replace_callback(
"/(?<=^|\-)[a-z]/",
function ($m) {
return strtoupper($m[0]);
},
$key
);
return $key;
}
/**
* Chainable lazy Environment Bootstrap
*
* Convenience method allowing quick setup of the default request state... from the current environment.
*
* @flow chain
* @return Gdn_Request
*/
public function fromEnvironment()
{
$this->setURI()->withArgs(
self::INPUT_GET,
self::INPUT_POST,
self::INPUT_SERVER,
self::INPUT_FILES,
self::INPUT_COOKIES
);
return $this;
}
/**
* Chainable Request Importer
*
* This method allows one method to import the raw information of another request
*
* @param Gdn_Request $newRequest New Request from which to import environment and arguments.
* @flow chain
* @return $this
*/
public function fromImport($newRequest)
{
// Import Environment
$this->_Environment = $newRequest->export("Environment");
$this->envElementCache = [];
// Import Arguments
$this->_RequestArguments = $newRequest->export("Arguments");
$this->_HaveParsedRequest = false;
$this->_Parsing = false;
return $this;
}
/**
* Get a value from the GET array or return the entire GET array.
*
* @param string|null $key The key of the get item or null to return the entire get array.
* @param mixed $default The value to return if the item isn't set.
* @return mixed
*/
public function get($key = null, $default = null)
{
if ($key === null) {
return $this->getRequestArguments(self::INPUT_GET);
} else {
return $this->getValueFrom(self::INPUT_GET, $key, $default);
}
}
/**
* Get the POST body of the request.
*
* @return array
*/
public function getBody()
{
return (array) $this->getRequestArguments(self::INPUT_POST);
}
/**
* Get the raw body of the post.
*/
public function getRawBody(): string
{
return file_get_contents("php://input") ?: "";
}
/**
* Get the file extension of the request.
*
* @return string
*/
public function getExt()
{
return (string) $this->_parsedRequestElement("Extension");
}
/**
* Get the full path of the request.
*
* @return string;
*/
public function getFullPath()
{
return $this->getRoot() . $this->getPathExt();
}
/**
* Get the hostname of the request.
*
* @return string
*/
public function getHost()
{
return (string) $this->_environmentElement("HOST");
}
/**
* {@inheritdoc}
*/
public function getHeader(string $header)
{
return $this->getValueFrom(self::INPUT_SERVER, $this->headerKey($header), "");
}
/**
* {@inheritdoc}
*/
public function setHeader(string $header, $value)
{
$this->setValueOn(self::INPUT_SERVER, $this->headerKey($header), $value);
return $this;
}
/**
* {@inheritdoc}
*/
public function getHeaderLine($name)
{
$value = $this->getHeader($name);
if (empty($value)) {
$value = "";
} elseif (is_array($value)) {
$value = implode(",", $value);
}
return $value;
}
/**
* {@inheritdoc}
*/
public function getHeaders()
{
$server = $this->getRequestArguments(self::INPUT_SERVER);
$headers = [];
foreach ($server as $name => $val) {
if (substr($name, 0, 5) != "HTTP_" && !in_array($name, self::SPECIAL_HEADERS)) {
continue;
}
$name = $this->formatHeaderKey($name);
$headers[$name] = $val;
}
return $headers;
}
/**
* {@inheritdoc}
*/
public function hasHeader(string $header): bool
{
return !empty($this->getHeader($header));
}
/**
* Normalize a header name into a header key.
*
* @param string $name The name of the header.
* @return string Returns a string in the form **HTTP_***.
*/
private function headerKey($name)
{
$key = strtoupper(str_replace("-", "_", $name));
if (substr($key, 0, 5) != "HTTP_" && !in_array($key, self::SPECIAL_HEADERS)) {
$key = "HTTP_" . $key;
}
return $key;
}
/**
* Get the host and port, but only if the port is not the standard port for the request scheme.
*
* @return string
*/
public function getHostAndPort()
{
$host = $this->getHost();
$port = $this->getPort();
// Only append the port if it is non-standard.
if ($port == 80 || $port == 443) {
$port = "";
} else {
$port = ":" . $port;
}
return $host . $port;
}
/**
* Get the IP address of the request.
*
* @return string;
*/
public function getIP()
{
return (string) $this->_environmentElement("ADDRESS", null, false);
}
/**
* Legacy get/set request method.
*
* @param string|null $method
* @return string|null
* @deprecated Use `getMethod()` and `setMethod()`.
*/
public function requestMethod(string $method = null)
{
return $this->_environmentElement("METHOD", $method, false);
}
/**
* Get the HTTP method.
*
* @return string Returns the HTTP method.
*/
public function getMethod()
{
return $this->requestMethod();
}
/**
* Set the HTTP method.
*
* @param string $method The new HTTP method.
* @return $this
*/
public function setMethod(string $method)
{
$this->requestMethod($method);
return $this;
}
/**
* Gets the request path.
*
* @return string
*/
public function getPath()
{
$path = (string) $this->_parsedRequestElement("Path");
if (strpos($path, "/") !== 0) {
$path = "/{$path}";
}
return $path;
}
/**
* Get the path and file extension.
*
* @return string
*/
public function getPathExt()
{
$path = $this->getPath();
$extension = $this->getExt();
return $path . $extension;
}
/**
* Gets the port.
*
* @return int
*/
public function getPort()
{
return (int) $this->_environmentElement("PORT");
}
/**
* Get the request query.
*
* @return array
*/
public function getQuery()
{
return (array) $this->getRequestArguments(self::INPUT_GET);
}
/**
* Get an item from the query string array.
*
* @param string $key
* @param mixed $default
* @return string
*/
public function getQueryItem($key, $default = null)
{
return (string) $this->getValueFrom(self::INPUT_GET, $key, "");
}
/**
* Export an entire dataset (effectively, one of the superglobals) from the request arguments list
*
* @param int $paramType Type of data to export. One of the self::INPUT_* constants
* @return array
*/
public function getRequestArguments($paramType = null)
{
if ($paramType === null) {
return $this->_RequestArguments;
} elseif (!isset($this->_RequestArguments[$paramType])) {
return [];
} else {
return $this->_RequestArguments[$paramType];
}
}
/**
* Get the root directory of the request.
*
* @return string
*/
public function getRoot()
{
$root = (string) $this->_parsedRequestElement("WebRoot");
if (strpos($root, "/") !== 0) {
$root = "/{$root}";
}
$root = rtrim($root, "/");
return $root;
}
/**
* Get the request scheme.
*
* @return string
*/
public function getScheme()
{
return (string) $this->_environmentElement("SCHEME");
}
/**
* Get the full url of the request.
*
* @return string
*/
public function getUrl()
{
$scheme = $this->getScheme();
$hostAndPort = $this->getHostAndPort();
$fullPath = \Vanilla\Utility\UrlUtils::encodePath($this->getFullPath());
$query = $this->getQuery();
$queryString = empty($query) ? "" : "?" . http_build_query($query);
return "{$scheme}://{$hostAndPort}{$fullPath}{$queryString}";
}
/**
* Retrieves the URI instance.
*
* This method MUST return a UriInterface instance.
*
* @link http://tools.ietf.org/html/rfc3986#section-4.3
* @return UriInterface Returns a UriInterface instance representing the URI of the request.
*/
public function getUri()
{
return Http::createFromString($this->getUrl());
}
/**
* Search the currently attached data arrays for the requested argument (in order) and
* return the first match. Return $Default if not found.
*
* @param string $key Name of the request argument to retrieve.
* @param mixed $default Value to return if argument not found.
* @return mixed
* @deprecated
* @codeCoverageIgnore
*/
public function getValue($key, $default = false)
{
return $this->merged($key, $default);
}
/**
* Search one of the currently attached data arrays for the requested argument and return its value.
*
* @param string $paramType Which request argument array to query for this value. One of the **INPUT_*** constants.
* @param string $key Name of the request argument to retrieve.
* @param mixed $default Value to return if argument not found.
* @return mixed
*/
public function getValueFrom($paramType, $key, $default = false)
{
$paramType = strtolower($paramType);
if (
array_key_exists($paramType, $this->_RequestArguments) &&
array_key_exists($key, $this->_RequestArguments[$paramType])
) {
$value = $this->_RequestArguments[$paramType][$key];
if (is_array($value) || is_object($value)) {
return $value;
} else {
return $value;
}
}
return $default;
}
/**
* Gets/Sets the host from the current url. e.g. "foo.com" in
* "http://foo.com/this/that/garden/index.php?/controller/action/"
*
* @param string|null $hostname Optional value to set.
* @return string|null
* @deprecated Use Gdn_Request::getHost() and Gdn_Request::setHost() instead.
*/
public function host($hostname = null)
{
return $this->_environmentElement("HOST", $hostname);
}
/**
* Return the host and port together if the port isn't standard.
*
* @return string
* @deprecated Use Gdn_Request::getHostAndPort() instead.
*/
public function hostAndPort()
{
$host = $this->host();
$port = $this->port();
if (!in_array($port, [80, 443])) {
return $host . ":" . $port;
} else {
return $host;
}
}
/**
* Alias for requestAddress()
*
* @return string
* @deprecated Use Gdn_Request::getIP() instead.
*/
public function ipAddress()
{
return $this->_Environment["ADDRESS"];
}
/**
* Returns a boolean value indicating if the current page has an authenticated postback.
*
* @param bool $throw Whether or not to throw an exception if this is a postback AND the transient key doesn't validate.
* @return bool Returns true if the postback could be authenticated or false otherwise.
* @throws Gdn_UserException Throws an exception when this is a postback AND the transient key doesn't validate.
* @since 2.1
*/
public function isAuthenticatedPostBack($throw = false)
{
if (!$this->isPostBack()) {
return false;
}
if (
// https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Protecting_REST_Services:_Use_of_Custom_Request_Headers
$this->hasHeader("X-Requested-With") &&
// https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Identifying_Source_Origin
$this->getHost() === parse_url($this->getHeader("Referer"), PHP_URL_HOST) &&
(!$this->hasHeader("Origin") || $this->getHost() === parse_url($this->getHeader("Origin"), PHP_URL_HOST))
) {
// Check Origin, Referer, and X-Requested-With.
$result = true;
} else {
// Check a submitted transient key.
$transientKey = $this->post(
"TransientKey",
$this->post("transientKey", $this->getHeader("X-Transient-Key"))
);
$result = Gdn::session()->validateTransientKey($transientKey, false);
}
if (!$result && $throw) {
throw new Gdn_UserException(t("Invalid CSRF token.", "Invalid CSRF token. Please try again."), 403);
}
return $result;
}
/**
* Check if request was a POST
*
* @return bool
*/
public function isPostBack()
{
return $this->_environmentElement("METHOD") === "POST";
}
/**
* Gets/sets the port of the request.
*
* @param int $port
* @return int
* @since 2.1
* @deprecated Use Gdn_Request::getPort() instead.
*/
public function port($port = null)
{
return $this->_environmentElement("PORT", $port);
}
/**
* Gets/Sets the scheme from the current url. e.g. "http" in
* "http://foo.com/this/that/garden/index.php?/controller/action/"
*
* @param string $scheme Optional value to set.
* @return string | null
* @deprecated Use Gdn_Request::getScheme() instead.
*/
public function scheme($scheme = null)
{
return $this->_environmentElement("SCHEME", $scheme);
}
/**
* Load the basics of the current environment
*
* The purpose of this method is to consolidate all the various environment information into one
* array under a set of common names, thereby removing the tedium of figuring out which superglobal
* and key combination contain the requested information each time it is needed.
*/
protected function _loadEnvironment()
{
$this->_environmentElement("ConfigWebRoot", Gdn::config("Garden.WebRoot"));
$this->_environmentElement("ConfigStripUrls", Gdn::config("Garden.StripWebRoot", false));
if (isset($_SERVER["HTTP_HOST"])) {
$host = $_SERVER["HTTP_HOST"];
} else {
$host = $_SERVER["SERVER_NAME"] ?? false;
}
// The host can have the port passed in, remove it here if it exists
$hostParts = explode(":", $host, 2);
$host = $hostParts[0];
$rawPort = null;
if (count($hostParts) > 1) {
$rawPort = $hostParts[1];
}
$this->_environmentElement("HOST", $host);
$this->_environmentElement("METHOD", $_SERVER["REQUEST_METHOD"] ?? "CONSOLE");
// Request IP
// Load balancers
$ip = $_SERVER["HTTP_CLIENT_IP"] ?? ($_SERVER["HTTP_X_FORWARDED_FOR"] ?? ($_SERVER["REMOTE_ADDR"] ?? false));
if (strpos($ip, ",") !== false) {
$matched = preg_match_all("/([\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3})(?:, )?/i", $ip, $matches);
// If we found matching IPs
if ($matched) {
$ips = $matches[1];
$ip = $ips[0];
// Fallback
} else {
$remoteAddr = $_SERVER["REMOTE_ADDR"] ?? false;
if (strpos($remoteAddr, ",") !== false) {
$remoteAddr = substr($remoteAddr, 0, strpos($remoteAddr, ","));
}
$ip = $remoteAddr;
}
}
$this->_environmentElement("ADDRESS", $ip);
// Request Scheme
$scheme = "http";
// Webserver-originated SSL
if (isset($_SERVER["HTTPS"]) && strtolower($_SERVER["HTTPS"]) == "on") {
$scheme = "https";
}
// Loadbalancer-originated (and terminated) SSL
if (strtolower($_SERVER["HTTP_X_FORWARDED_PROTO"] ?? "") == "https") {
$scheme = "https";
}
$this->_environmentElement("SCHEME", $scheme);
if (isset($_SERVER["SERVER_PORT"])) {
$port = $_SERVER["SERVER_PORT"];
} elseif ($rawPort) {
$port = $rawPort;
} else {
if ($scheme === "https") {
$port = 443;
} else {
$port = 80;
}
}
$this->port($port);
$path = "";
if (!empty($_SERVER["X_REWRITE"]) || !empty($_SERVER["REDIRECT_X_REWRITE"])) {
$path = $_SERVER["PATH_INFO"] ?? "";
// Some hosts block PATH_INFO from being passed (or even manually set).
// We set X_PATH_INFO in the .htaccess as a fallback for those situations.
// If you work for one of those hosts, know that many beautiful kittens lost their lives for your sins.
if (!$path) {
if (!empty($_SERVER["X_PATH_INFO"])) {
$path = $_SERVER["X_PATH_INFO"];
} elseif (!empty($_SERVER["REDIRECT_X_PATH_INFO"])) {
$path = $_SERVER["REDIRECT_X_PATH_INFO"];
}
}
} elseif (is_array($_GET)) {
if (isset($_GET["_p"])) {
$path = $_GET["_p"];
unset($_GET["_p"]);
} elseif (isset($_GET["p"])) {
$path = $_GET["p"];
unset($_GET["p"]);
}
}
// Set URI directly to avoid double decoding.
$this->_Environment["URI"] = $path;
$possibleScriptNames = [];
if (isset($_SERVER["SCRIPT_NAME"])) {
$possibleScriptNames[] = $_SERVER["SCRIPT_NAME"];
}
if (isset($_ENV["SCRIPT_NAME"])) {
$possibleScriptNames[] = $_ENV["SCRIPT_NAME"];
}
if (PHP_SAPI === "cgi" && isset($_ENV["SCRIPT_URL"])) {
$possibleScriptNames[] = $_ENV["SCRIPT_URL"];
}
if (isset($_SERVER["SCRIPT_FILENAME"])) {
$possibleScriptNames[] = $_SERVER["SCRIPT_FILENAME"];
}
if (isset($_SERVER["ORIG_SCRIPT_NAME"])) {
$possibleScriptNames[] = $_SERVER["ORIG_SCRIPT_NAME"];