-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRequest.php
972 lines (879 loc) · 25.2 KB
/
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
<?php
/**
* File defining Request
*
* PHP Version 5.3
*
* @category Backend
* @package Core
* @author J Jurgens du Toit <jrgns@backend-php.net>
* @copyright 2011 - 2012 Jade IT (cc)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
* @link http://backend-php.net
*/
namespace Backend\Core;
use Backend\Interfaces\RequestInterface;
use Backend\Core\Exception as CoreException;
/**
* The Request class which helps determine the Path and request format.
*
* @category Backend
* @package Core
* @author J Jurgens du Toit <jrgns@backend-php.net>
* @license http://www.opensource.org/licenses/mit-license.php MIT License
* @link http://backend-php.net
* @todo Refactore MimeType methods into separate class.
*/
class Request implements RequestInterface
{
protected $serverInfo = array();
/**
* The absolute path to the site. Used for links to assets.
*
* @var string
*/
protected $path = null;
/**
* The URL for the Request.
*
* @var string
*/
protected $url = null;
/**
* The headers of the Request.
*
* @var array
*/
protected $headers = null;
/**
* The body of the Request.
*
* @var array
*/
protected $body = null;
/**
* The query of the Request.
*
* @var array
*/
protected $query = null;
/**
* The method of the Request. Can be one of GET, POST, PUT, DELETE, HEAD or OPTIONS.
*
* @var string
*/
protected $method = null;
/**
* The extension of the Request.
*
* @var string
*/
protected $extension = null;
/**
* The requested format of the Request.
*
* @var string
*/
protected $format = null;
/**
* The requested mime type of the Request.
*
* @var string
*/
protected $mimeType = null;
/**
* Stream location to read content from.
*
* @var string
*/
protected $inputStream = 'php://input';
/**
* HTTP Methods allowed in the Request.
*
* @var array
*/
public static $allowedMethods = array(
'DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'
);
/**
* The constructor for the class
*
* If no method is supplied, it's determined by one of the following:
* 1. A _method POST variable
* 2. A X_HTTP_METHOD_OVERRIDE header
* 3. The REQUEST_METHOD
*
* @param mixed $url The URL of the request
* @param string $method The request method. Can be one of GET, POST, PUT,
* DELETE or HEAD
* @param mixed $body The request data. Defaults to the HTTP request data
* if not supplied
*/
public function __construct($url = null, $method = null, $body = null)
{
if ($url === null) {
$this->serverInfo = $_SERVER;
$this->serverInfo['PATH_INFO']
= array_key_exists('PATH_INFO', $_SERVER)
? $_SERVER['PATH_INFO'] : '';
} else {
$this->parseUrl($url);
}
if ($method !== null) {
$this->setMethod($method);
}
$this->setBody($body);
$this->getHeaders();
}
/**
* Parse the given URL, and populate the object
*
* @param string $url The URL to parse
*
* @return Request The current object
*/
protected function parseUrl($url)
{
// Build up the different url parts
$urlParts = parse_url($url);
$this->serverInfo['HTTP_HOST'] = $urlParts['host'];
$this->setHeader('host', $urlParts['host']);
$this->serverInfo['QUERY_STRING'] = empty($urlParts['query']) ? ''
: $urlParts['query'];
$urlParts['path'] = empty($urlParts['path']) ? ''
: $urlParts['path'];
// RFC3875 4.1.5 defines path_info as "derived from the portion of the URI
// path hierarchy following the part that identifies the script itself."
// Scripts will end with .php, so work with that.
$regex = '/^(\/.*\.php)?(\/.*)?$/';
preg_match($regex, $urlParts['path'], $matches);
$script = empty($matches[1]) ? '' : $matches[1];
$path = empty($matches[2]) ? '/' : $matches[2];
if (strlen($path) > 0 && substr($path, -1) === '/') {
$path = substr($path, 0, strlen($path) - 1);
}
$urlParts['path'] = $script . $path;
$this->setPath($urlParts['path']);
$this->serverInfo['SCRIPT_NAME'] = empty($script) ? '/index.php' : $script;
$this->serverInfo['PATH_INFO'] = $path;
$this->serverInfo['REQUEST_URI'] = $this->getPath();
$this->serverInfo['REQUEST_TIME'] = time();
if ($urlParts['scheme'] == 'https') {
$this->serverInfo['HTTPS'] = 'on';
$this->serverInfo['SERVER_PORT'] = 443;
} else {
$this->serverInfo['SERVER_PORT'] = 80;
}
if (array_key_exists('port', $urlParts)) {
$this->serverInfo['SERVER_PORT'] = $urlParts['port'];
}
//Keep all $_SERVER details we haven't set
$this->serverInfo = array_merge($_SERVER, $this->serverInfo);
return $this;
}
/**
* Return the HTTP Method used to make the request.
*
* @return string
*/
public function getMethod()
{
if ($this->method !== null) {
return $this->method;
}
//Default to GET
$method = 'GET';
//Copied the way to determine the method from CakePHP
//http://book.cakephp.org/2.0/en/development/rest.html#the-simple-setup
$body = $this->body === null ? $this->getBody() : $this->body;
switch (true) {
case is_array($body) && array_key_exists('_method', $body):
$method = $body['_method'];
unset($this->body['_method']);
break;
case $this->getHeader('METHOD_OVERRIDE') !== null:
$method = $this->getHeader('METHOD_OVERRIDE');
break;
//First CL parameter is the method
case $this->fromCli()
&& count($this->serverInfo['argv']) >= 2
&& in_array(strtoupper($this->serverInfo['argv'][1]), self::$allowedMethods):
$method = $this->serverInfo['argv'][1];
break;
case $this->getServerInfo('request_method') !== null:
$method = $this->getServerInfo('request_method');
break;
default:
break;
}
$this->setMethod($method);
return $this->method;
}
/**
* Set the request's method
*
* @param string $method The Request Method
*
* @return Request The current object
*/
public function setMethod($method)
{
$method = strtoupper($method);
if (!in_array($method, self::$allowedMethods)) {
throw new CoreException('Unsupported method ' . $method);
}
$this->method = $method;
$this->serverInfo['REQUEST_METHOD'] = $method;
return $this;
}
/**
* Build the headers if necessary.
*
* @return Request The current object.
*/
public function buildHeaders($force = false)
{
if ($force || $this->headers === null) {
if (function_exists('apache_request_headers')) {
$this->headers = apache_request_headers();
$this->headers = array_change_key_case($this->headers);
} else {
$this->headers = array();
foreach ($this->serverInfo as $name => $value) {
if (strtolower(substr($name, 0, 5)) !== 'http_') {
continue;
}
$name = strtolower(substr($name, 5));
$this->headers[$name] = $value;
}
}
}
return $this;
}
/**
* Return the Request headers.
*
* @return array
*/
public function getHeaders()
{
$this->buildHeaders();
// Return the compiled headers
$headers = array();
foreach ($this->headers as $name => $content) {
if (is_numeric($name) === false) {
$content = ucwords($name) . ': ' . $content;
}
$headers[] = $content;
}
return $headers;
}
/**
* Set the Request headers.
*
* @param array $headers An array of headers for the Request.
*
* @return \Backend\Interfaces\RequestInterface
*/
public function setHeaders(array $headers)
{
$this->headers = $headers;
return $this;
}
/**
* Return the specified Request header.
*
* @param string $name The name of the header to return.
*
* @return string
*/
public function getHeader($name)
{
$this->buildHeaders();
$name = strtolower($name);
return array_key_exists($name, $this->headers) ? $this->headers[$name] : null;
}
/**
* Set the specified Request headers.
*
* If the name is null, the header won't have a name, and will contain only
* the value of the header.
*
* @param string $name The name of the header to set.
* @param string $value The value of the header.
*
* @return \Backend\Interfaces\RequestInterface
*/
public function setHeader($name, $value)
{
if ($name === null) {
$this->headers[] = $value;
} else {
$name = strtolower($name);
$this->headers[$name] = $value;
}
return $this;
}
/**
* Return the path of the current Request.
*
* In http://backend-php.net/index.php/something, the path will be
* /something
*
* @return string
*/
public function getPath()
{
if ($this->path === null) {
$path = $this->getServerInfo('path_info');
$path = $path ?: '/';
$this->setPath($path);
}
return $this->path;
}
/**
* Set and cleanup the path.
*
* The path should be URL decoded before calling this method.
*
* @param string $path The path
*
* @return \Backend\Core\Request The current object
*/
public function setPath($path)
{
//Clean up the path
//No trailing slash
if (substr($path, -1) === '/') {
$path = substr($path, 0, -1);
}
if (substr($path, 0, 1) != '/') {
$path = '/' . $path;
}
$this->path = $path;
return $this;
}
/**
* Return the url to this Request.
*
* @return string
*/
public function getUrl()
{
if ($this->url === null) {
$this->prepareUrl();
}
return $this->url;
}
/**
* Set the Request's URL.
*
* @param string $url The url.
*
* @return \Backend\Interfaces\RequestInterface
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Prepare the URL.
*
* Build the URL from the current Server Info.
*
* @return null
*/
protected function prepareUrl()
{
//Construct the current URL
$this->url = 'http';
if ($this->getServerInfo('server_port') == 443
|| $this->getServerInfo('https') == 'on'
) {
$this->url .= 's';
}
$this->url .= '://' . $this->getHeader('host');
$script = $this->getServerInfo('script_name');
$this->url .= $script;
// Check for URL Rewriting
$uri = $this->getServerInfo('request_uri');
$path = $this->getServerInfo('path_info');
$path = $path === '/' ? '' : $path;
if (strlen($path) > 0 && substr($path, -1) === '/') {
$path = substr($path, 0, strlen($path) - 1);
}
if (substr($uri, 0, strlen($script)) !== $script) {
$this->url = preg_replace('|/' . basename($script) . '$|', $path, $this->url);
} else {
$this->url .= $path;
}
}
/**
* Determine the requested MIME Type for the request
*
* @return string The MIME Type for the request
* @todo This doesn't check the q variable -
* https://github.com/backend/Backend-PHP-Core/issues/1
*/
public function getMimeType()
{
if ($this->mimeType !== null) {
return $this->mimeType;
}
switch (true) {
case $this->getHeader('accept') !== null:
$mimeType = $this->getHeader('accept');
if ($mimeType !== null) {
//Try to get the first type
$types = explode(',', $mimeType);
$types = array_map('trim', $types);
usort($types, array($this, 'compareMimeTypes'));
//Remove the preference variable
$mimeType = explode(';', end($types));
$this->mimeType = trim(reset($mimeType));
}
break;
case $this->fromCli():
$this->mimeType = 'cli';
break;
default:
break;
}
return $this->mimeType;
}
/**
* Set the Request MIME Type.
*
* @param mixed $mimeType The Request's MIME Type.
*
* @return \Backend\Interfaces\RequestInterface
*/
public function setMimeType($mimeType)
{
$this->mimeType = $mimeType;
return $this;
}
/**
* Compare two mime types. Used for sorting.
*
* @param string $tOne The first mime type.
* @param string $tTwo The first mime type.
*
* @return int
*/
protected function compareMimeTypes($tOne, $tTwo)
{
$tOne = $this->prepareMimeType($tOne);
$tTwo = $this->prepareMimeType($tTwo);
if ($tOne['primary'] === '*') {
return -1;
} elseif ($tTwo['primary'] === '*') {
return 1;
}
if ($tOne['secondary'] === '*') {
return -1;
} elseif ($tTwo['secondary'] === '*') {
return 1;
}
if ($tOne['priority'] === $tTwo['priority']) {
return 0;
}
return $tOne['priority'] < $tTwo['priority'] ? -1 : 1;
}
/**
* Prepare a mime type for comparison.
*
* @param string $type The string representation of the mime type to prepare.
*
* @return array
*/
protected function prepareMimeType($type)
{
$type = explode(';', $type);
$type[1] = empty($type[1]) ? 'q=1' : $type[1];
parse_str($type[1], $type[1]);
$parts = explode('/', $type[0]);
$parts[1] = empty($parts[1]) ? '*' : $parts[1];
$type = array(
'primary' => $parts[0],
'secondary' => $parts[1],
'priority' => $type[1]['q'],
);
return $type;
}
/**
* Determine the requested format for the request
*
* @return string The format for the request
*/
public function getSpecifiedFormat()
{
if ($this->format !== null) {
return $this->format;
}
//Check the format parameter
if (is_array($this->body) && array_key_exists('format', $this->body)) {
$this->format = $this->body['format'];
} elseif ($this->fromCli() && count($this->serverInfo['argv']) >= 4) {
// Third CL parameter is the required format
$this->format = $this->serverInfo['argv'][3];
}
return $this->format;
}
/**
* Set the Request Specified Format.
*
* @param mixed $format The Request's specified format.
*
* @return \Backend\Interfaces\RequestInterface
*/
public function setSpecifiedFormat($format)
{
$this->format = $format;
return $this;
}
/**
* Get the Request Extension
*
* @return string The extension of the request
*/
public function getExtension()
{
if ($this->extension !== null) {
return $this->extension;
}
$pattern = '/[^\/]+\.(.*)\??.*$/';
preg_match('/\.(\w+)$/', $this->getPath(), $matches);
$this->extension = empty($matches[1]) ? null : $matches[1];
return $this->extension;
}
/**
* Set the Request Extension.
*
* @param mixed $extension The Request's extension.
*
* @return \Backend\Interfaces\RequestInterface
*/
public function setExtension($extension)
{
$this->extension = $extension;
return $this;
}
/**
* Return the serverInfo property
*
* @param string $name A specific piece of Server Info
*
* @return array The serverInfo property
*/
public function getServerInfo($name = null)
{
if ($name === null) {
return $this->serverInfo;
}
if (in_array($name, array('argv')) === false) {
$name = strtoupper($name);
}
if (substr($name, 0, 2) === 'X_') {
$name = substr($name, 2);
}
switch (true) {
case array_key_exists($name, $this->serverInfo):
return $this->serverInfo[$name];
break;
//Check for deprecated X- values http://tools.ietf.org/html/rfc6648
case array_key_exists('X_' . $name, $this->serverInfo):
return $this->serverInfo['X_' . $name ];
break;
default:
break;
}
return null;
}
/**
* Set serverInfo values.
*
* @param string $name The name of the serverInfo value to set.
* @param string $value The value of the serverInfo value.
*
* @return Request The current object
*/
public function setServerInfo($name, $value)
{
if (in_array($name, array('argv', 'argc')) === false) {
$name = strtoupper($name);
}
$this->serverInfo[$name] = $value;
return $this;
}
/**
* Utility function to check if the current method equals the specified method
*
* @param string $method The method to check
*
* @return boolean If the current method equals the specified method
*/
protected function isMethod($method)
{
return strtoupper($method) === $this->getMethod();
}
/**
* Check if the current request is a DELETE request
*
* @return boolean If the current request is a DELETE request
*/
public function isDelete()
{
return $this->isMethod('DELETE');
}
/**
* Check if the current request is a GET request
*
* @return boolean If the current request is a GET request
*/
public function isGet()
{
return $this->isMethod('GET');
}
/**
* Check if the current request is a HEAD request
*
* @return boolean If the current request is a HEAD request
*/
public function isHead()
{
return $this->isMethod('HEAD');
}
/**
* Check if the current request is a OPTIONS request
*
* @return boolean If the current request is a OPTIONS request
*/
public function isOptions()
{
return $this->isMethod('OPTIONS');
}
/**
* Check if the current request is a POST request
*
* @return boolean If the current request is a POST request
*/
public function isPost()
{
return $this->isMethod('POST');
}
/**
* Check if the current request is a PUT request
*
* @return boolean If the current request is a PUT request
*/
public function isPut()
{
return $this->isMethod('PUT');
}
/**
* Parse the content / body of the Request
*
* @param string $type The type of the content
* @param string $content The content to parse
*
* @todo Expand this to include other content types
* @todo Refactor so that we can use thirdparty / external parsers -
* https://github.com/backend/Backend-PHP-Core/issues/2
* @return array
*/
public function parseContent($type, $content = null)
{
if ($type === null) {
return null;
}
if ($content === null) {
$data = '';
$fpointer = fopen($this->getInputStream(), 'r');
while ($fpointer && $chunk = fread($fpointer, 1024)) {
$data .= $chunk;
}
} else {
$data = $content;
}
$body = null;
$type = explode(';', $type);
$type = trim($type[0]);
switch ($type) {
case 'application/json':
case 'text/json':
case 'text/javascript':
$body = json_decode($data);
$body = is_object($body) ? (array) $body : $body;
break;
case 'application/x-www-form-urlencoded':
case 'multipart/form-data':
case 'text/plain':
parse_str($data, $body);
break;
case 'application/xml':
$body = simplexml_load_string($data);
$body = is_object($body) ? (array) $body : $body;
break;
default:
throw new CoreException(
'Unknown Content Type: ' . $type,
400
);
break;
}
return $body;
}
/**
* Return the request's body.
*
* @return array The Request body
*/
public function getBody()
{
if ($this->body !== null) {
return $this->body;
}
if ($this->fromCli()) {
if (count($this->serverInfo['argv']) >= 5) {
//Fourth CL parameter is a query string
parse_str($this->serverInfo['argv'][4], $body);
$this->body = $body;
return $this->body;
}
}
$body = $this->parseContent($this->getServerInfo('content_type'));
if ($body) {
$this->setBody($body);
return $this->body;
}
$body = null;
switch (true) {
case count($_GET) > 0:
$body = isset($_GET) ? $_GET : array();
break;
case count($_POST) > 0:
$body = isset($_POST) ? $_POST : array();
break;
default:
break;
}
if ($body === null) {
$body = isset($_REQUEST) ? $_REQUEST : array();
}
$this->setBody($body);
return $this->body;
}
/**
* Get a specific part of the request body.
*
* @param string $name The name of the variable to get.
*
* @return mixed
*/
public function get($name)
{
$body = $this->getBody();
return array_key_exists($name, $body) ? $body[$name] : null;
}
/**
* Set the request's body.
*
* Strings will be parsed for variables and objects will be casted to arrays.
*
* @param mixed $body The Request's body
*
* @return Request The current object.
*/
public function setBody($body)
{
if (is_string($body)) {
parse_str($body, $body);
} elseif (is_object($body)) {
$body = (array) $body;
}
$this->body = $body;
return $this;
}
/**
* Set a specific part of the request body.
*
* @param string $name The name of the variable to set.
* @param mixed $value The value of the variable.
*
* @return Request The current object.
*/
public function set($name, $value)
{
$body = $this->getBody();
$body[$name] = $value;
$this->setBody($body);
return $this;
}
/**
* Return the request's query data.
*
* @return array The Request query data
*/
public function getQuery()
{
if ($this->query !== null) {
return $this->query;
}
$this->setQuery($this->getServerInfo('query_string'));
return $this->query;
}
/**
* Set the request's query data.
*
* Strings will be parsed for variables and objects will be casted to arrays.
*
* @param mixed $body The Request's body
*
* @return Request The current object.
*/
public function setQuery($query)
{
if (is_string($query)) {
parse_str($query, $query);
} elseif (is_object($query)) {
$query = (array) $query;
}
$this->query = $query;
return $this;
}
/**
* Check if this requests originates from a CLI.
*
* This is hidden from the outside world because for application code a Request
* will be a Request, regardless of where it came from.
*
* @return boolean If this is a CLI request
*/
protected function fromCli()
{
return !empty($this->serverInfo['argc']);
}
/**
* Set the input stream.
*
* @param string $stream The stream.
*
* @return Request The current object.
*/
public function setInputStream($stream)
{
$this->inputStream = $stream;
return $this;
}
/**
* Get the input stream.
*
* @return string
*/
public function getInputStream()
{
return $this->inputStream;
}
}