-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathRequest.php
More file actions
911 lines (790 loc) · 19.6 KB
/
Copy pathRequest.php
File metadata and controls
911 lines (790 loc) · 19.6 KB
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
<?php
declare(strict_types=1);
namespace Bow\Http;
use Bow\Auth\Authentication;
use Bow\Http\Exception\BadRequestException;
use Bow\Session\Session;
use Bow\Support\Collection;
use Bow\Support\Str;
use Bow\Validation\Validate;
use Bow\Validation\Validator;
use Throwable;
class Request
{
/**
* The Request instance
*
* @static Request
*/
private static ?Request $instance = null;
/**
* All request input
*
* @var array
*/
private array $input = [];
/**
* Define the post variables
*
* @var array
*/
private array $post = [];
/**
* Define the query variables
*
* @var array
*/
private array $query = [];
/**
* Define the bags instance
*
* @var array
*/
private array $bags = [];
/**
* Define the request id
*
* @var string
*/
private string $id;
/**
* Define the request captured
*
* @var bool
*/
private bool $capture = false;
/**
* Why the JSON payload could not be decoded, when it could not be.
*
* @var string|null
*/
private ?string $invalid_json_payload = null;
/**
* Check if file exists
*
* @param mixed $file
* @return bool
*/
public static function hasFile(mixed $file): bool
{
return isset($_FILES[$file]);
}
/**
* Request constructor
*
* @return mixed
* @throws BadRequestException
*/
public function capture()
{
if ($this->capture) {
return;
}
$data = [];
$this->id = "req_" . sha1(uniqid() . time());
if ($this->getHeader('content-type') == 'application/json') {
$raw = (string) file_get_contents("php://input");
// A bodyless request is not a malformed one. Clients routinely send
// "Content-Type: application/json" on a POST/DELETE that carries no
// payload, and json_decode('') throws — a throw this early cannot be
// rendered, because capture() runs from Application::__construct
// before the container binds "response", which BadRequestException
// needs. The client would get a raw PHP fatal instead of a 400.
if (trim($raw) === '') {
$data = [];
} else {
try {
$data = json_decode($raw, true, 1024, JSON_THROW_ON_ERROR);
} catch (Throwable $e) {
// Recorded, not thrown. capture() runs from
// Application::__construct, which is too early for ANY
// exception to be rendered: the container has not bound
// "response" yet and the error handler is installed later
// in the boot, so a throw here reaches the client as a raw
// PHP fatal instead of a 400. Application::run() raises it
// once both are in place.
$this->invalid_json_payload = $e->getMessage();
$data = [];
}
}
} else {
$data = $_POST ?? [];
if ($this->isPut()) {
parse_str(file_get_contents("php://input"), $data);
}
}
$this->post = $data;
$this->query = $_GET;
$this->input = array_merge((array) $data, $this->query);
foreach ($this->input as $key => $value) {
$this->input[$key] = is_string($value) && strlen($value) == 0 ? null : $value;
}
$this->capture = true;
}
/**
* The JSON decoding error for this request, or null when the payload was
* absent or well-formed.
*
* @return string|null
*/
public function getInvalidJsonPayload(): ?string
{
return $this->invalid_json_payload;
}
/**
* Retrieve query variables
*
* @param string|null $key
* @param mixed $default
* @return mixed
*/
public function query(?string $key = null, mixed $default = null): mixed
{
if ($key === null) {
return $this->query;
}
return $this->query[$key] ?? $default;
}
/**
* Get posted data
*
* @param string|null $key
* @param mixed $default
* @return mixed
*/
public function post(?string $key = null, mixed $default = null): mixed
{
if ($key === null) {
return $this->post;
}
return $this->post[$key] ?? $default;
}
/**
* Get Request header
*
* @param string $key
* @return ?string
*/
public function getHeader(string $key): ?string
{
$key = str_replace('-', '_', strtoupper($key));
if ($this->hasHeader($key)) {
return $_SERVER[$key];
}
if ($this->hasHeader('HTTP_' . $key)) {
return $_SERVER['HTTP_' . $key];
}
return null;
}
/**
* Check if a header exists.
*
* @param string $key
* @return bool
*/
public function hasHeader(string $key): bool
{
return isset($_SERVER[strtoupper($key)]);
}
/**
* Check if the query is of type PUT
*
* @return bool
*/
public function isPut(): bool
{
return $this->method() == 'PUT' || $this->get('_method') == 'PUT';
}
/**
* Returns the method of the request.
*
* @return string|null
*/
public function method(): ?string
{
$method = $_SERVER['REQUEST_METHOD'] ?? null;
if ($method !== 'POST') {
return $method;
}
if (array_key_exists('HTTP_X_HTTP_METHOD', $_SERVER)) {
if (in_array($_SERVER['HTTP_X_HTTP_METHOD'], ['PUT', 'DELETE'])) {
$method = $_SERVER['HTTP_X_HTTP_METHOD'];
}
}
return $method;
}
/**
* Check that the request method matches the given one.
*
* @param string $method
* @return bool
*/
public function isMethod(string $method): bool
{
return strtoupper($method) === $this->method();
}
/**
* Retrieve a value or a collection of values.
*
* @param string $key
* @param mixed|null $default
* @return mixed
*/
public function get(string $key, mixed $default = null): mixed
{
$value = $this->input[$key] ?? $default;
// Only a callable *default* may be resolved — a closure or an invokable
// object. Never a string or an array: those can come straight from the
// request, and is_callable() is true for the name of any defined
// function, so `?field=phpinfo` would call it and return its result in
// place of the input the caller asked for.
if (is_object($value) && is_callable($value)) {
return $value();
}
return $value;
}
/**
* Alias of get, retrieve an input value.
*
* @param string $key
* @param mixed|null $default
* @return mixed
*/
public function input(string $key, mixed $default = null): mixed
{
return $this->get($key, $default);
}
/**
* Retrieve an input value as a boolean.
*
* Truthy values are 1, "1", true, "true", "on" and "yes".
*
* @param string $key
* @param bool $default
* @return bool
*/
public function boolean(string $key, bool $default = false): bool
{
if (!$this->has($key)) {
return $default;
}
return filter_var($this->get($key), FILTER_VALIDATE_BOOLEAN);
}
/**
* Get the request ID
*
* @return string|int
*/
public function getId(): string|int
{
return $this->id;
}
/**
* Set the request id
*
* @param string|int $id
* @return void
*/
public function setId(string|int $id): void
{
$this->id = $id;
}
/**
* Alias of getId
*
* @return string|int
*/
public function id(): string|int
{
return $this->id;
}
/**
* Check if key is existing
*
* @param string $key
* @return bool
*/
public function has(string $key): bool
{
return isset($this->input[$key]);
}
/**
* Get all input value
*
* @return array
*/
public function all(): array
{
return $this->input;
}
/**
* Get url sent by client.
*
* @return string
*/
public function url(): string
{
return $this->origin() . $this->path();
}
/**
* Origin the name of the server + the scheme
*
* @return string
*/
public function origin(): string
{
return $this->scheme() . '://' . $this->hostname();
}
/**
* Get request scheme
*
* @return string
*/
private function scheme(): string
{
return strtolower($_SERVER['REQUEST_SCHEME'] ?? 'http');
}
/**
* Get the host name of the server.
*
* @return string
*/
public function hostname(): string
{
return $_SERVER['HTTP_HOST'] ?? '';
}
/**
* Get the domain of the server.
*
* @return string
*/
public function domain(): string
{
$part = explode(':', $this->hostname());
return $part[0] ?: 'unknown';
}
/**
* Get uri send by client.
*
* @return string
*/
public function path(): string
{
$request_uri = $_SERVER['REQUEST_URI'] ?? '/';
$position = strpos($request_uri, '?');
if ($position !== false) {
return substr($request_uri, 0, $position);
}
return $request_uri;
}
/**
* Get the request time as a UNIX timestamp.
*
* @return int
*/
public function time(): int
{
return (int) ($_SERVER['REQUEST_TIME'] ?? time());
}
/**
* Check if the query is POST
*
* @return bool
*/
public function isPost(): bool
{
return $this->method() == 'POST';
}
/**
* Check if the query is of type GET
*
* @return bool
*/
public function isGet(): bool
{
return $this->method() == 'GET';
}
/**
* Check if the query is DELETE
*
* @return bool
*/
public function isDelete(): bool
{
return $this->method() == 'DELETE' || $this->get('_method') == 'DELETE';
}
/**
* Load the factory for FILES
*
* @param string $key
* @return UploadedFile|Collection|null
*/
public function file(string $key): UploadedFile|Collection|null
{
if (!isset($_FILES[$key])) {
return null;
}
if (!is_array($_FILES[$key]['tmp_name']) && !is_uploaded_file($_FILES[$key]['tmp_name'])) {
return null;
}
if (!is_array($_FILES[$key]['name'])) {
return new UploadedFile($_FILES[$key]);
}
$files = $_FILES[$key];
$collect = [];
foreach ($files['name'] as $key => $name) {
$collect[] = new UploadedFile([
'name' => $name,
'type' => $files['type'][$key],
'size' => $files['size'][$key],
'error' => $files['error'][$key],
'tmp_name' => $files['tmp_name'][$key],
]);
}
return new Collection($collect);
}
/**
* Get previous request data
*
* @param string $key
* @param mixed $fallback
* @return mixed
*/
public function old(string $key, mixed $fallback = null): mixed
{
$old = Session::getInstance()->get('__bow.old', []);
return $old[$key] ?? $fallback;
}
/**
* Singletons loader
*
* @return Request
*/
public static function getInstance(): Request
{
if (static::$instance === null) {
static::$instance = new Request();
}
return static::$instance;
}
/**
* Check if we are in the case of an AJAX request.
*
* @return bool
*/
public function isAjax(): bool
{
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
return false;
}
$xhr_obj = Str::lower($_SERVER['HTTP_X_REQUESTED_WITH']);
if ($xhr_obj == 'xmlhttprequest' || $xhr_obj == 'activexobject') {
return true;
}
$content_type = $this->getHeader("content-type");
return $content_type && str_contains($content_type, "application/json");
}
/**
* Determine if is accept application/json
*
* @return boolean
*/
public function wantsJson(): bool
{
$accept = $this->getHeader('accept');
if ($accept && str_contains($accept, 'application/json')) {
return true;
}
return $this->isAjax();
}
/**
* Check if a url matches with the pattern
*
* @param string $match
* @return bool
*/
public function is(string $match): bool
{
return (bool) preg_match('@' . addcslashes($match, "/{()}[]$^") . '@', $this->path());
}
/**
* Check if a url matches with the pattern
*
* @param string $match
* @return bool
*/
public function isReferer(string $match): bool
{
return (bool) preg_match('@' . addcslashes($match, "/{()}[]$^") . '@', $this->referer());
}
/**
* Get the source of the current request.
*
* @return string
*/
public function referer(): string
{
return $_SERVER['HTTP_REFERER'] ?? '/';
}
/**
* Get client address
*
* @return ?string
*/
public function ip(): ?string
{
$candidates = [
$_SERVER['HTTP_CF_CONNECTING_IP'] ?? null,
isset($_SERVER['HTTP_X_FORWARDED_FOR'])
? explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]
: null,
$_SERVER['HTTP_X_REAL_IP'] ?? null,
$_SERVER['REMOTE_ADDR'] ?? null,
];
foreach ($candidates as $candidate) {
$ip = trim((string) $candidate);
if ($ip !== '' && filter_var($ip, FILTER_VALIDATE_IP) !== false) {
return $ip;
}
}
return null;
}
/**
* Get client port
*
* @return string|null
*/
public function port(): ?string
{
return $_SERVER['REMOTE_PORT'] ?? null;
}
/**
* Get the request locale.
*
* The local is the original language of the client
* e.g fr => locale = fr_FR
* e.g en => locale [ en_US, en_EN]
*
* @return string|null
*/
public function locale(): ?string
{
$accept_language = $this->getHeader('accept-language');
if (!$accept_language) {
return null;
}
$tmp = explode(';', $accept_language)[0];
if (!preg_match('/([a-z]+)[-_]?/i', $tmp, $match)) {
return null;
}
return end($match);
}
/**
* Get request lang.
*
* @return string|null
*/
public function lang(): ?string
{
$accept_language = $this->getHeader('accept-language');
if (!$accept_language) {
return "en";
}
$language = explode(',', explode(';', $accept_language ?? '')[0])[0];
preg_match('/([a-z]+)/', $language, $match);
return end($match);
}
/**
* Get request protocol
*
* @return mixed
*/
public function protocol(): string
{
return $this->scheme();
}
/**
* Check if the secure protocol
*
* @return mixed
*/
public function isSecure(): bool
{
return $this->isProtocol('https');
}
/**
* Check the protocol of the request
*
* @param string $protocol
* @return mixed
*/
public function isProtocol(string $protocol): bool
{
return $this->scheme() == $protocol;
}
/**
* Get Request header
*
* @return array
*/
public function getHeaders(): array
{
$headers = [];
foreach ($_SERVER as $key => $value) {
if (preg_match('/^http_/i', $key)) {
$key = str_replace("http_", "", strtolower($key));
$headers[$key] = $value;
}
}
return $headers;
}
/**
* Get the client user agent
*
* @return ?string
*/
public function userAgent(): ?string
{
return $this->getHeader('USER_AGENT');
}
/**
* Get the Bearer token from the Authorization header.
*
* @return ?string
*/
public function bearerToken(): ?string
{
$authorization = $this->getHeader('authorization');
if ($authorization && str_starts_with($authorization, 'Bearer ')) {
return substr($authorization, 7);
}
return null;
}
/**
* Get session information
*
* @return Session
*/
public function session(): Session
{
return session();
}
/**
* Get auth user information
*
* @param string|null $guard
* @return Authentication|null
*/
public function user(?string $guard = null): ?Authentication
{
return app_auth($guard)->user();
}
/**
* Get cookie
*
* @param string|null $property
* @return string|array|object|null
*/
public function cookie(?string $property = null): string|array|object|null
{
return cookie($property);
}
/**
* Retrieves the values contained in the exception table
*
* @param array $exceptions
* @return array
*/
public function only(array $exceptions = []): array
{
$data = [];
if (!is_array($exceptions)) {
$exceptions = func_get_args();
}
foreach ($exceptions as $exception) {
if (isset($this->input[$exception])) {
$data[$exception] = $this->input[$exception];
}
}
return $data;
}
/**
* Retrieves the rest of values
*
* @param array $ignores
* @return array
*/
public function ignore(array $ignores = []): array
{
$data = $this->input;
if (!is_array($ignores)) {
$ignores = func_get_args();
}
foreach ($ignores as $ignore) {
if (isset($data[$ignore])) {
unset($data[$ignore]);
}
}
return $data;
}
/**
* Validate incoming data
*
* @param array $rule
* @return Validate
*/
public function validate(array $rule): Validate
{
return Validator::make($this->input, $rule);
}
/**
* Set the shared value in request bags
*
* @param string $name
* @param mixed $value
* @return void
*/
public function setBag(string $name, mixed $value): void
{
$this->bags[$name] = $value;
}
/**
* Get the shared value in request bags
*
* @param string $name
* @return mixed
*/
public function getBag(string $name): mixed
{
return $this->bags[$name] ?? null;
}
/**
* Get the shared value in request bags
*
* @return array
*/
public function getBags(): array
{
return $this->bags;
}
/**
* Set the shared value in request bags
*
* @param array $bags
* @return void
*/
public function setBags(array $bags): void
{
$this->bags = $bags;
}
/**
* __call
*
* @param $property
* @return mixed
*/
public function __get($property)
{
return $this->get($property);
}
}